ngram
listlengths 0
67.8k
|
|---|
[
"节点选择器: 若有同名节点,只输出第一个,不存在,输出None :soup.title 直接子节点: contents、children 孙子节点选择器: descendants 方法选择器: find find_all css选择器: select 获取文本:",
"select 获取文本: get_text,string属性 获取属性值: ['key'],attrs['key'] 通过浏览器直接拷贝选择器 ''' from bs4 import BeautifulSoup from urllib3",
"方法选择器: find find_all css选择器: select 获取文本: get_text,string属性 获取属性值: ['key'],attrs['key'] 通过浏览器直接拷贝选择器 ''' from bs4",
"获取文本: get_text,string属性 获取属性值: ['key'],attrs['key'] 通过浏览器直接拷贝选择器 ''' from bs4 import BeautifulSoup from urllib3 import",
"''' 比xpath lxml 更方便的 节点选择器: 若有同名节点,只输出第一个,不存在,输出None :soup.title 直接子节点: contents、children 孙子节点选择器: descendants 方法选择器: find",
"* http=PoolManager() disable_warnings() response= http.request(url=\"https://www.cnhnb.com/supply/\",method=\"GET\").data html=response.decode(\"utf-8\") #print(html) soup=BeautifulSoup(html,'lxml') #print(soup.title.string) #print(soup.body.contents) #print(soup.body.children) for i,item",
"from urllib3 import * http=PoolManager() disable_warnings() response= http.request(url=\"https://www.cnhnb.com/supply/\",method=\"GET\").data html=response.decode(\"utf-8\") #print(html) soup=BeautifulSoup(html,'lxml') #print(soup.title.string) #print(soup.body.contents)",
"import BeautifulSoup from urllib3 import * http=PoolManager() disable_warnings() response= http.request(url=\"https://www.cnhnb.com/supply/\",method=\"GET\").data html=response.decode(\"utf-8\") #print(html) soup=BeautifulSoup(html,'lxml')",
"更方便的 节点选择器: 若有同名节点,只输出第一个,不存在,输出None :soup.title 直接子节点: contents、children 孙子节点选择器: descendants 方法选择器: find find_all css选择器: select",
"descendants 方法选择器: find find_all css选择器: select 获取文本: get_text,string属性 获取属性值: ['key'],attrs['key'] 通过浏览器直接拷贝选择器 ''' from",
"''' from bs4 import BeautifulSoup from urllib3 import * http=PoolManager() disable_warnings() response= http.request(url=\"https://www.cnhnb.com/supply/\",method=\"GET\").data",
"get_text,string属性 获取属性值: ['key'],attrs['key'] 通过浏览器直接拷贝选择器 ''' from bs4 import BeautifulSoup from urllib3 import *",
"['key'],attrs['key'] 通过浏览器直接拷贝选择器 ''' from bs4 import BeautifulSoup from urllib3 import * http=PoolManager() disable_warnings()",
"lxml 更方便的 节点选择器: 若有同名节点,只输出第一个,不存在,输出None :soup.title 直接子节点: contents、children 孙子节点选择器: descendants 方法选择器: find find_all css选择器:",
"contents、children 孙子节点选择器: descendants 方法选择器: find find_all css选择器: select 获取文本: get_text,string属性 获取属性值: ['key'],attrs['key'] 通过浏览器直接拷贝选择器",
"孙子节点选择器: descendants 方法选择器: find find_all css选择器: select 获取文本: get_text,string属性 获取属性值: ['key'],attrs['key'] 通过浏览器直接拷贝选择器 '''",
"比xpath lxml 更方便的 节点选择器: 若有同名节点,只输出第一个,不存在,输出None :soup.title 直接子节点: contents、children 孙子节点选择器: descendants 方法选择器: find find_all",
"若有同名节点,只输出第一个,不存在,输出None :soup.title 直接子节点: contents、children 孙子节点选择器: descendants 方法选择器: find find_all css选择器: select 获取文本: get_text,string属性",
"find find_all css选择器: select 获取文本: get_text,string属性 获取属性值: ['key'],attrs['key'] 通过浏览器直接拷贝选择器 ''' from bs4 import",
"find_all css选择器: select 获取文本: get_text,string属性 获取属性值: ['key'],attrs['key'] 通过浏览器直接拷贝选择器 ''' from bs4 import BeautifulSoup",
"<filename>language/python/Lib_beautifulsoup/beautifulsoup.py ''' 比xpath lxml 更方便的 节点选择器: 若有同名节点,只输出第一个,不存在,输出None :soup.title 直接子节点: contents、children 孙子节点选择器: descendants 方法选择器:",
"通过浏览器直接拷贝选择器 ''' from bs4 import BeautifulSoup from urllib3 import * http=PoolManager() disable_warnings() response=",
"from bs4 import BeautifulSoup from urllib3 import * http=PoolManager() disable_warnings() response= http.request(url=\"https://www.cnhnb.com/supply/\",method=\"GET\").data html=response.decode(\"utf-8\")",
"response= http.request(url=\"https://www.cnhnb.com/supply/\",method=\"GET\").data html=response.decode(\"utf-8\") #print(html) soup=BeautifulSoup(html,'lxml') #print(soup.title.string) #print(soup.body.contents) #print(soup.body.children) for i,item in enumerate(soup.body.div.ul): print(i,item)",
"urllib3 import * http=PoolManager() disable_warnings() response= http.request(url=\"https://www.cnhnb.com/supply/\",method=\"GET\").data html=response.decode(\"utf-8\") #print(html) soup=BeautifulSoup(html,'lxml') #print(soup.title.string) #print(soup.body.contents) #print(soup.body.children)",
"bs4 import BeautifulSoup from urllib3 import * http=PoolManager() disable_warnings() response= http.request(url=\"https://www.cnhnb.com/supply/\",method=\"GET\").data html=response.decode(\"utf-8\") #print(html)",
"直接子节点: contents、children 孙子节点选择器: descendants 方法选择器: find find_all css选择器: select 获取文本: get_text,string属性 获取属性值: ['key'],attrs['key']",
":soup.title 直接子节点: contents、children 孙子节点选择器: descendants 方法选择器: find find_all css选择器: select 获取文本: get_text,string属性 获取属性值:",
"BeautifulSoup from urllib3 import * http=PoolManager() disable_warnings() response= http.request(url=\"https://www.cnhnb.com/supply/\",method=\"GET\").data html=response.decode(\"utf-8\") #print(html) soup=BeautifulSoup(html,'lxml') #print(soup.title.string)",
"获取属性值: ['key'],attrs['key'] 通过浏览器直接拷贝选择器 ''' from bs4 import BeautifulSoup from urllib3 import * http=PoolManager()",
"http=PoolManager() disable_warnings() response= http.request(url=\"https://www.cnhnb.com/supply/\",method=\"GET\").data html=response.decode(\"utf-8\") #print(html) soup=BeautifulSoup(html,'lxml') #print(soup.title.string) #print(soup.body.contents) #print(soup.body.children) for i,item in",
"import * http=PoolManager() disable_warnings() response= http.request(url=\"https://www.cnhnb.com/supply/\",method=\"GET\").data html=response.decode(\"utf-8\") #print(html) soup=BeautifulSoup(html,'lxml') #print(soup.title.string) #print(soup.body.contents) #print(soup.body.children) for",
"css选择器: select 获取文本: get_text,string属性 获取属性值: ['key'],attrs['key'] 通过浏览器直接拷贝选择器 ''' from bs4 import BeautifulSoup from",
"disable_warnings() response= http.request(url=\"https://www.cnhnb.com/supply/\",method=\"GET\").data html=response.decode(\"utf-8\") #print(html) soup=BeautifulSoup(html,'lxml') #print(soup.title.string) #print(soup.body.contents) #print(soup.body.children) for i,item in enumerate(soup.body.div.ul):"
] |
[] |
[
"list(coords[:, 1]) indexx = torch.LongTensor([row, col]) tensor_size = torch.Size([self.data.num_nodes, self.feats_per_node]) degs_out = torch.sparse.FloatTensor(indexx,",
"non_exisiting_adj['vals'][indice] all_len = len(label_adj['vals']) + len(non_exisiting_adj['vals']) pos = len(label_adj['vals'])/all_len neg = len(non_exisiting_adj['vals'])/all_len #",
"class Link_Pred_Tasker(): def __init__(self, args, dataset): self.data = dataset # max_time for link",
"np.ones(len(source)) G = pd.DataFrame({'source': source, 'target': target, 'weight': weight}) G = StellarGraph(edges=G) rw",
"create dic feats_dic = {} for i in range(self.data.max_time): if i%30 == 0:",
"= torch.LongTensor(indice) non_exisiting_adj['idx'] = non_exisiting_adj['idx'][indice,:] non_exisiting_adj['vals'] = non_exisiting_adj['vals'][indice] all_len = len(label_adj['vals']) + len(non_exisiting_adj['vals'])",
"dic dic = dict(zip(node_ids, weighted_node_embeddings.tolist())) # ascending order dic = dict(sorted(dic.items())) # create",
"existing_nodes=existing_nodes) # For football data, we need to sample due to memory constraints",
"return {'idx': idx, 'hist_adj_list': hist_adj_list, 'hist_ndFeats_list': hist_ndFeats_list, 'label_sp': label_adj, 'node_mask_list': hist_mask_list, 'weight': weight}",
"= torch.Size([self.data.num_nodes, self.feats_per_node]) degs_out = torch.sparse.FloatTensor(indexx, torch.FloatTensor(values), tensor_size) hot_1 = {'idx': degs_out._indices().t(), 'vals':",
"kwargs.keys() and kwargs['all_edges'] == True: non_exisiting_adj = tu.get_all_non_existing_edges(adj=label_adj, tot_nodes=self.data.num_nodes) else: non_exisiting_adj = tu.get_non_existing_edges(adj=label_adj,",
"window=5, min_count=0, sg=1, workers=1, iter=1) # Retrieve node embeddings and corresponding subjects node_ids",
"source node q=0.5, # Defines (unormalised) probability, 1/q, for moving away from source",
"= dic[row_idx] adj_mat = adj_mat.tocsr() adj_mat = adj_mat.tocoo() coords = np.vstack((adj_mat.row, adj_mat.col)).transpose() values",
"test, **kwargs): hist_adj_list = [] hist_ndFeats_list = [] hist_mask_list = [] existing_nodes =",
"a random walk n=5, # number of random walks per root node p=1,",
"list of node IDs # change to integer for i in range(0, len(node_ids)):",
"if test: neg_mult = self.args.negative_mult_test else: neg_mult = self.args.negative_mult_training if self.args.smart_neg_sampling: existing_nodes =",
"non_exisiting_adj['idx']]) label_adj['vals'] = torch.cat([label_adj['vals'], non_exisiting_adj['vals']]) return {'idx': idx, 'hist_adj_list': hist_adj_list, 'hist_ndFeats_list': hist_ndFeats_list, 'label_sp':",
"time=i, weighted=True, time_window=self.args.adj_mat_time_window) feats_dic[i] = get_node_feats(cur_adj) return feats_dic def get_sample(self, idx, test, **kwargs):",
"= sp.lil_matrix((self.data.num_nodes, self.feats_per_node)) for row_idx in node_ids: adj_mat[row_idx, :] = dic[row_idx] adj_mat =",
"self.feats_per_node = dataset.feats_per_node self.prepare_node_feats = self.build_prepare_node_feats(args, dataset) self.is_static = False self.feats_per_node = 100",
"len(label_adj['vals'])/all_len neg = len(non_exisiting_adj['vals'])/all_len # if adapt, we use EXACT adaptive weights when",
"u from stellargraph import StellarGraph import pandas as pd from stellargraph.data import BiasedRandomWalk",
"source, 'target': target, 'weight': weight}) G = StellarGraph(edges=G) rw = BiasedRandomWalk(G) weighted_walks =",
"non_exisiting_adj = tu.get_all_non_existing_edges(adj=label_adj, tot_nodes=self.data.num_nodes) else: non_exisiting_adj = tu.get_non_existing_edges(adj=label_adj, number=label_adj['vals'].size(0) * neg_mult, tot_nodes=self.data.num_nodes, smart_sampling=self.args.smart_neg_sampling,",
"workers=1, iter=1) # Retrieve node embeddings and corresponding subjects node_ids = weighted_model.wv.index2word #",
"adj_mat[row_idx, :] = dic[row_idx] adj_mat = adj_mat.tocsr() adj_mat = adj_mat.tocoo() coords = np.vstack((adj_mat.row,",
"i in range(self.data.max_time): if i%30 == 0: print('current i to make embeddings:', i)",
"in node_ids: adj_mat[row_idx, :] = dic[row_idx] adj_mat = adj_mat.tocsr() adj_mat = adj_mat.tocoo() coords",
"to sample due to memory constraints if self.args.sport=='football': # Sampling label_adj num_sample =",
"label_adj['idx'] = torch.cat([label_adj['idx'], non_exisiting_adj['idx']]) label_adj['vals'] = torch.cat([label_adj['vals'], non_exisiting_adj['vals']]) return {'idx': idx, 'hist_adj_list': hist_adj_list,",
"dataset) self.is_static = False self.feats_per_node = 100 self.all_node_feats_dic = self.build_get_node_feats(args, dataset) ##should be",
"(args.use_2_hot_node_feats or args.use_1_hot_node_feats): self.feats_per_node = dataset.feats_per_node self.prepare_node_feats = self.build_prepare_node_feats(args, dataset) self.is_static = False",
"sg=1, workers=1, iter=1) # Retrieve node embeddings and corresponding subjects node_ids = weighted_model.wv.index2word",
"iter=1) # Retrieve node embeddings and corresponding subjects node_ids = weighted_model.wv.index2word # list",
"corresponding subjects node_ids = weighted_model.wv.index2word # list of node IDs # change to",
"feats_dic[i] = get_node_feats(cur_adj) return feats_dic def get_sample(self, idx, test, **kwargs): hist_adj_list = []",
"returning to source node q=0.5, # Defines (unormalised) probability, 1/q, for moving away",
"= Word2Vec(str_walks, size=self.feats_per_node, window=5, min_count=0, sg=1, workers=1, iter=1) # Retrieve node embeddings and",
"num_sample = int(np.floor(len(label_adj['vals'])*0.02)) indice = random.sample(range(len(label_adj['vals'])), num_sample) indice = torch.LongTensor(indice) label_adj['idx'] = label_adj['idx'][indice,:]",
"**kwargs): hist_adj_list = [] hist_ndFeats_list = [] hist_mask_list = [] existing_nodes = []",
"# create dic feats_dic = {} for i in range(self.data.max_time): if i%30 ==",
"random walk n=5, # number of random walks per root node p=1, #",
"weighted=True, time_window=self.args.adj_mat_time_window) feats_dic[i] = get_node_feats(cur_adj) return feats_dic def get_sample(self, idx, test, **kwargs): hist_adj_list",
"and corresponding subjects node_ids = weighted_model.wv.index2word # list of node IDs # change",
"= weighted_model.wv.index2word # list of node IDs # change to integer for i",
"numpy as np import scipy.sparse as sp import logging logging.getLogger(\"gensim.models\").setLevel(logging.WARNING) import time import",
"adj_mat = adj_mat.tocoo() coords = np.vstack((adj_mat.row, adj_mat.col)).transpose() values = adj_mat.data row = list(coords[:,",
"self.data = dataset # max_time for link pred should be one before self.max_time",
"StellarGraph(edges=G) rw = BiasedRandomWalk(G) weighted_walks = rw.run( nodes=list(G.nodes()), # root nodes length=2, #",
"source node weighted=True, # for weighted random walks seed=42, # random seed fixed",
"Defines (unormalised) probability, 1/q, for moving away from source node weighted=True, # for",
"= [[str(n) for n in walk] for walk in weighted_walks] weighted_model = Word2Vec(str_walks,",
"dic feats_dic = {} for i in range(self.data.max_time): if i%30 == 0: print('current",
"time import random class Link_Pred_Tasker(): def __init__(self, args, dataset): self.data = dataset #",
"- self.args.num_hist_steps, idx + 1): cur_adj = tu.get_sp_adj(edges=self.data.edges, time=i, weighted=True, time_window=self.args.adj_mat_time_window) if self.args.smart_neg_sampling:",
"rw = BiasedRandomWalk(G) weighted_walks = rw.run( nodes=list(G.nodes()), # root nodes length=2, # maximum",
"node_mask = tu.get_node_mask(cur_adj, self.data.num_nodes) # get node features from the dictionary (already created)",
"hist_mask_list.append(node_mask) # This would be if we were training on all the edges",
"weighted=False, time_window=self.args.adj_mat_time_window) if test: neg_mult = self.args.negative_mult_test else: neg_mult = self.args.negative_mult_training if self.args.smart_neg_sampling:",
"time_window=self.args.adj_mat_time_window) if self.args.smart_neg_sampling: existing_nodes.append(cur_adj['idx'].unique()) else: existing_nodes = None node_mask = tu.get_node_mask(cur_adj, self.data.num_nodes) #",
"nodes length=2, # maximum length of a random walk n=5, # number of",
"# for weighted random walks seed=42, # random seed fixed for reproducibility )",
"if self.args.sport=='football': # Sampling label_adj num_sample = int(np.floor(len(label_adj['vals'])*0.02)) indice = random.sample(range(len(label_adj['vals'])), num_sample) indice",
"self.build_get_node_feats(args, dataset) ##should be a dic def build_prepare_node_feats(self, args, dataset): if args.use_2_hot_node_feats or",
"length=2, # maximum length of a random walk n=5, # number of random",
"from stellargraph import StellarGraph import pandas as pd from stellargraph.data import BiasedRandomWalk from",
"all the edges in the time_window label_adj = tu.get_sp_adj(edges=self.data.edges, time=idx + 1, weighted=False,",
"# numpy.ndarray of size number of nodes times embeddings dimensionality # create dic",
"for weighted random walks seed=42, # random seed fixed for reproducibility ) str_walks",
"torch import taskers_utils as tu import utils as u from stellargraph import StellarGraph",
"or args.use_1_hot_node_feats): self.feats_per_node = dataset.feats_per_node self.prepare_node_feats = self.build_prepare_node_feats(args, dataset) self.is_static = False self.feats_per_node",
"node_feats = self.all_node_feats_dic[i] cur_adj = tu.normalize_adj(adj=cur_adj, num_nodes=self.data.num_nodes) hist_adj_list.append(cur_adj) hist_ndFeats_list.append(node_feats) hist_mask_list.append(node_mask) # This would",
"= int(np.floor(len(non_exisiting_adj['vals'])*0.02)) indice = random.sample(range(len(non_exisiting_adj['vals'])), num_sample) indice = torch.LongTensor(indice) non_exisiting_adj['idx'] = non_exisiting_adj['idx'][indice,:] non_exisiting_adj['vals']",
"matrix adj_mat = sp.lil_matrix((self.data.num_nodes, self.feats_per_node)) for row_idx in node_ids: adj_mat[row_idx, :] = dic[row_idx]",
"prepare_node_feats(node_feats): return u.sparse_prepare_tensor(node_feats, torch_size=[dataset.num_nodes, self.feats_per_node]) else: prepare_node_feats = self.data.prepare_node_feats return prepare_node_feats def build_get_node_feats(self,",
"= None node_mask = tu.get_node_mask(cur_adj, self.data.num_nodes) # get node features from the dictionary",
"= edgelist[:, 0] target = edgelist[:, 1] weight = np.ones(len(source)) G = pd.DataFrame({'source':",
"= torch.LongTensor([row, col]) tensor_size = torch.Size([self.data.num_nodes, self.feats_per_node]) degs_out = torch.sparse.FloatTensor(indexx, torch.FloatTensor(values), tensor_size) hot_1",
"[[str(n) for n in walk] for walk in weighted_walks] weighted_model = Word2Vec(str_walks, size=self.feats_per_node,",
"= ( weighted_model.wv.vectors) # numpy.ndarray of size number of nodes times embeddings dimensionality",
"idx + 1): cur_adj = tu.get_sp_adj(edges=self.data.edges, time=i, weighted=True, time_window=self.args.adj_mat_time_window) if self.args.smart_neg_sampling: existing_nodes.append(cur_adj['idx'].unique()) else:",
"as sp import logging logging.getLogger(\"gensim.models\").setLevel(logging.WARNING) import time import random class Link_Pred_Tasker(): def __init__(self,",
"= torch.cat([label_adj['idx'], non_exisiting_adj['idx']]) label_adj['vals'] = torch.cat([label_adj['vals'], non_exisiting_adj['vals']]) return {'idx': idx, 'hist_adj_list': hist_adj_list, 'hist_ndFeats_list':",
"football data, we need to sample due to memory constraints if self.args.sport=='football': #",
"self.args.class_weights label_adj['idx'] = torch.cat([label_adj['idx'], non_exisiting_adj['idx']]) label_adj['vals'] = torch.cat([label_adj['vals'], non_exisiting_adj['vals']]) return {'idx': idx, 'hist_adj_list':",
"= self.all_node_feats_dic[i] cur_adj = tu.normalize_adj(adj=cur_adj, num_nodes=self.data.num_nodes) hist_adj_list.append(cur_adj) hist_ndFeats_list.append(node_feats) hist_mask_list.append(node_mask) # This would be",
"[] existing_nodes = [] for i in range(idx - self.args.num_hist_steps, idx + 1):",
"node IDs # change to integer for i in range(0, len(node_ids)): node_ids[i] =",
"len(node_ids)): node_ids[i] = int(node_ids[i]) weighted_node_embeddings = ( weighted_model.wv.vectors) # numpy.ndarray of size number",
"node weighted=True, # for weighted random walks seed=42, # random seed fixed for",
"= tu.get_sp_adj(edges=self.data.edges, time=i, weighted=True, time_window=self.args.adj_mat_time_window) if self.args.smart_neg_sampling: existing_nodes.append(cur_adj['idx'].unique()) else: existing_nodes = None node_mask",
"self.data.prepare_node_feats return prepare_node_feats def build_get_node_feats(self, args, dataset): def get_node_feats(adj): # input is cur_adj",
"weighted_node_embeddings.tolist())) # ascending order dic = dict(sorted(dic.items())) # create matrix adj_mat = sp.lil_matrix((self.data.num_nodes,",
"torch_size=[dataset.num_nodes, self.feats_per_node]) else: prepare_node_feats = self.data.prepare_node_feats return prepare_node_feats def build_get_node_feats(self, args, dataset): def",
"tot_nodes=self.data.num_nodes, smart_sampling=self.args.smart_neg_sampling, existing_nodes=existing_nodes) # For football data, we need to sample due to",
"cur_adj = tu.get_sp_adj(edges=self.data.edges, time=i, weighted=True, time_window=self.args.adj_mat_time_window) if self.args.smart_neg_sampling: existing_nodes.append(cur_adj['idx'].unique()) else: existing_nodes = None",
"= adj_mat.tocoo() coords = np.vstack((adj_mat.row, adj_mat.col)).transpose() values = adj_mat.data row = list(coords[:, 0])",
"coords = np.vstack((adj_mat.row, adj_mat.col)).transpose() values = adj_mat.data row = list(coords[:, 0]) col =",
"stellargraph import StellarGraph import pandas as pd from stellargraph.data import BiasedRandomWalk from gensim.models",
"indexx = torch.LongTensor([row, col]) tensor_size = torch.Size([self.data.num_nodes, self.feats_per_node]) degs_out = torch.sparse.FloatTensor(indexx, torch.FloatTensor(values), tensor_size)",
"in walk] for walk in weighted_walks] weighted_model = Word2Vec(str_walks, size=self.feats_per_node, window=5, min_count=0, sg=1,",
"= BiasedRandomWalk(G) weighted_walks = rw.run( nodes=list(G.nodes()), # root nodes length=2, # maximum length",
"Sampling non_exisiting_adj num_sample = int(np.floor(len(non_exisiting_adj['vals'])*0.02)) indice = random.sample(range(len(non_exisiting_adj['vals'])), num_sample) indice = torch.LongTensor(indice) non_exisiting_adj['idx']",
"# create dic dic = dict(zip(node_ids, weighted_node_embeddings.tolist())) # ascending order dic = dict(sorted(dic.items()))",
"nodes=list(G.nodes()), # root nodes length=2, # maximum length of a random walk n=5,",
"weighted=True, # for weighted random walks seed=42, # random seed fixed for reproducibility",
"= [] hist_mask_list = [] existing_nodes = [] for i in range(idx -",
"import random class Link_Pred_Tasker(): def __init__(self, args, dataset): self.data = dataset # max_time",
"node embeddings and corresponding subjects node_ids = weighted_model.wv.index2word # list of node IDs",
"of random walks per root node p=1, # Defines (unormalised) probability, 1/p, of",
"1 self.args = args self.num_classes = 2 if not (args.use_2_hot_node_feats or args.use_1_hot_node_feats): self.feats_per_node",
"# Sampling non_exisiting_adj num_sample = int(np.floor(len(non_exisiting_adj['vals'])*0.02)) indice = random.sample(range(len(non_exisiting_adj['vals'])), num_sample) indice = torch.LongTensor(indice)",
"self.prepare_node_feats = self.build_prepare_node_feats(args, dataset) self.is_static = False self.feats_per_node = 100 self.all_node_feats_dic = self.build_get_node_feats(args,",
"data, we need to sample due to memory constraints if self.args.sport=='football': # Sampling",
"walk n=5, # number of random walks per root node p=1, # Defines",
"= {} for i in range(self.data.max_time): if i%30 == 0: print('current i to",
"dic def build_prepare_node_feats(self, args, dataset): if args.use_2_hot_node_feats or args.use_1_hot_node_feats: def prepare_node_feats(node_feats): return u.sparse_prepare_tensor(node_feats,",
"due to memory constraints if self.args.sport=='football': # Sampling label_adj num_sample = int(np.floor(len(label_adj['vals'])*0.02)) indice",
"input is cur_adj edgelist = adj['idx'].cpu().data.numpy() source = edgelist[:, 0] target = edgelist[:,",
"[] hist_ndFeats_list = [] hist_mask_list = [] existing_nodes = [] for i in",
"as pd from stellargraph.data import BiasedRandomWalk from gensim.models import Word2Vec import numpy as",
"label_adj['idx'] = label_adj['idx'][indice,:] label_adj['vals'] = label_adj['vals'][indice] # Sampling non_exisiting_adj num_sample = int(np.floor(len(non_exisiting_adj['vals'])*0.02)) indice",
"length of a random walk n=5, # number of random walks per root",
"cur_adj = tu.get_sp_adj(edges=self.data.edges, time=i, weighted=True, time_window=self.args.adj_mat_time_window) feats_dic[i] = get_node_feats(cur_adj) return feats_dic def get_sample(self,",
"dict(sorted(dic.items())) # create matrix adj_mat = sp.lil_matrix((self.data.num_nodes, self.feats_per_node)) for row_idx in node_ids: adj_mat[row_idx,",
"self.args = args self.num_classes = 2 if not (args.use_2_hot_node_feats or args.use_1_hot_node_feats): self.feats_per_node =",
"u.sparse_prepare_tensor(node_feats, torch_size=[dataset.num_nodes, self.feats_per_node]) else: prepare_node_feats = self.data.prepare_node_feats return prepare_node_feats def build_get_node_feats(self, args, dataset):",
"dataset): def get_node_feats(adj): # input is cur_adj edgelist = adj['idx'].cpu().data.numpy() source = edgelist[:,",
"edgelist[:, 0] target = edgelist[:, 1] weight = np.ones(len(source)) G = pd.DataFrame({'source': source,",
"return prepare_node_feats def build_get_node_feats(self, args, dataset): def get_node_feats(adj): # input is cur_adj edgelist",
"import Word2Vec import numpy as np import scipy.sparse as sp import logging logging.getLogger(\"gensim.models\").setLevel(logging.WARNING)",
"p=1, # Defines (unormalised) probability, 1/p, of returning to source node q=0.5, #",
"range(0, len(node_ids)): node_ids[i] = int(node_ids[i]) weighted_node_embeddings = ( weighted_model.wv.vectors) # numpy.ndarray of size",
"a dic def build_prepare_node_feats(self, args, dataset): if args.use_2_hot_node_feats or args.use_1_hot_node_feats: def prepare_node_feats(node_feats): return",
"1]) indexx = torch.LongTensor([row, col]) tensor_size = torch.Size([self.data.num_nodes, self.feats_per_node]) degs_out = torch.sparse.FloatTensor(indexx, torch.FloatTensor(values),",
"feats_dic def get_sample(self, idx, test, **kwargs): hist_adj_list = [] hist_ndFeats_list = [] hist_mask_list",
"or args.use_1_hot_node_feats: def prepare_node_feats(node_feats): return u.sparse_prepare_tensor(node_feats, torch_size=[dataset.num_nodes, self.feats_per_node]) else: prepare_node_feats = self.data.prepare_node_feats return",
"non_exisiting_adj['vals'] = non_exisiting_adj['vals'][indice] all_len = len(label_adj['vals']) + len(non_exisiting_adj['vals']) pos = len(label_adj['vals'])/all_len neg =",
"# Defines (unormalised) probability, 1/p, of returning to source node q=0.5, # Defines",
"self.feats_per_node)) for row_idx in node_ids: adj_mat[row_idx, :] = dic[row_idx] adj_mat = adj_mat.tocsr() adj_mat",
"col]) tensor_size = torch.Size([self.data.num_nodes, self.feats_per_node]) degs_out = torch.sparse.FloatTensor(indexx, torch.FloatTensor(values), tensor_size) hot_1 = {'idx':",
"were training on all the edges in the time_window label_adj = tu.get_sp_adj(edges=self.data.edges, time=idx",
"embeddings:', i) cur_adj = tu.get_sp_adj(edges=self.data.edges, time=i, weighted=True, time_window=self.args.adj_mat_time_window) feats_dic[i] = get_node_feats(cur_adj) return feats_dic",
"adj_mat = sp.lil_matrix((self.data.num_nodes, self.feats_per_node)) for row_idx in node_ids: adj_mat[row_idx, :] = dic[row_idx] adj_mat",
"time=idx + 1, weighted=False, time_window=self.args.adj_mat_time_window) if test: neg_mult = self.args.negative_mult_test else: neg_mult =",
"= list(coords[:, 0]) col = list(coords[:, 1]) indexx = torch.LongTensor([row, col]) tensor_size =",
"non_exisiting_adj['vals']]) return {'idx': idx, 'hist_adj_list': hist_adj_list, 'hist_ndFeats_list': hist_ndFeats_list, 'label_sp': label_adj, 'node_mask_list': hist_mask_list, 'weight':",
"should be one before self.max_time = dataset.max_time - 1 self.args = args self.num_classes",
"to memory constraints if self.args.sport=='football': # Sampling label_adj num_sample = int(np.floor(len(label_adj['vals'])*0.02)) indice =",
"number of random walks per root node p=1, # Defines (unormalised) probability, 1/p,",
"# if adapt, we use EXACT adaptive weights when contributing to the loss",
"logging.getLogger(\"gensim.models\").setLevel(logging.WARNING) import time import random class Link_Pred_Tasker(): def __init__(self, args, dataset): self.data =",
"nodes times embeddings dimensionality # create dic dic = dict(zip(node_ids, weighted_node_embeddings.tolist())) # ascending",
"self.feats_per_node = 100 self.all_node_feats_dic = self.build_get_node_feats(args, dataset) ##should be a dic def build_prepare_node_feats(self,",
"self.is_static = False self.feats_per_node = 100 self.all_node_feats_dic = self.build_get_node_feats(args, dataset) ##should be a",
"away from source node weighted=True, # for weighted random walks seed=42, # random",
"= dataset.max_time - 1 self.args = args self.num_classes = 2 if not (args.use_2_hot_node_feats",
"label_adj = tu.get_sp_adj(edges=self.data.edges, time=idx + 1, weighted=False, time_window=self.args.adj_mat_time_window) if test: neg_mult = self.args.negative_mult_test",
"utils as u from stellargraph import StellarGraph import pandas as pd from stellargraph.data",
"constraints if self.args.sport=='football': # Sampling label_adj num_sample = int(np.floor(len(label_adj['vals'])*0.02)) indice = random.sample(range(len(label_adj['vals'])), num_sample)",
"existing_nodes.append(cur_adj['idx'].unique()) else: existing_nodes = None node_mask = tu.get_node_mask(cur_adj, self.data.num_nodes) # get node features",
"node_ids[i] = int(node_ids[i]) weighted_node_embeddings = ( weighted_model.wv.vectors) # numpy.ndarray of size number of",
"# Retrieve node embeddings and corresponding subjects node_ids = weighted_model.wv.index2word # list of",
"dataset): if args.use_2_hot_node_feats or args.use_1_hot_node_feats: def prepare_node_feats(node_feats): return u.sparse_prepare_tensor(node_feats, torch_size=[dataset.num_nodes, self.feats_per_node]) else: prepare_node_feats",
"number of nodes times embeddings dimensionality # create dic dic = dict(zip(node_ids, weighted_node_embeddings.tolist()))",
"0]) col = list(coords[:, 1]) indexx = torch.LongTensor([row, col]) tensor_size = torch.Size([self.data.num_nodes, self.feats_per_node])",
"self.feats_per_node]) else: prepare_node_feats = self.data.prepare_node_feats return prepare_node_feats def build_get_node_feats(self, args, dataset): def get_node_feats(adj):",
"to the loss if self.args.adapt: weight = [pos,neg] else: weight = self.args.class_weights label_adj['idx']",
"for row_idx in node_ids: adj_mat[row_idx, :] = dic[row_idx] adj_mat = adj_mat.tocsr() adj_mat =",
"the loss if self.args.adapt: weight = [pos,neg] else: weight = self.args.class_weights label_adj['idx'] =",
"taskers_utils as tu import utils as u from stellargraph import StellarGraph import pandas",
"gensim.models import Word2Vec import numpy as np import scipy.sparse as sp import logging",
"def get_sample(self, idx, test, **kwargs): hist_adj_list = [] hist_ndFeats_list = [] hist_mask_list =",
"i%30 == 0: print('current i to make embeddings:', i) cur_adj = tu.get_sp_adj(edges=self.data.edges, time=i,",
"False self.feats_per_node = 100 self.all_node_feats_dic = self.build_get_node_feats(args, dataset) ##should be a dic def",
"This would be if we were training on all the edges in the",
"existing_nodes = [] for i in range(idx - self.args.num_hist_steps, idx + 1): cur_adj",
"from gensim.models import Word2Vec import numpy as np import scipy.sparse as sp import",
"dataset) ##should be a dic def build_prepare_node_feats(self, args, dataset): if args.use_2_hot_node_feats or args.use_1_hot_node_feats:",
"node features from the dictionary (already created) node_feats = self.all_node_feats_dic[i] cur_adj = tu.normalize_adj(adj=cur_adj,",
"i in range(0, len(node_ids)): node_ids[i] = int(node_ids[i]) weighted_node_embeddings = ( weighted_model.wv.vectors) # numpy.ndarray",
"build_get_node_feats(self, args, dataset): def get_node_feats(adj): # input is cur_adj edgelist = adj['idx'].cpu().data.numpy() source",
"= list(coords[:, 1]) indexx = torch.LongTensor([row, col]) tensor_size = torch.Size([self.data.num_nodes, self.feats_per_node]) degs_out =",
"probability, 1/p, of returning to source node q=0.5, # Defines (unormalised) probability, 1/q,",
"np.vstack((adj_mat.row, adj_mat.col)).transpose() values = adj_mat.data row = list(coords[:, 0]) col = list(coords[:, 1])",
"reproducibility ) str_walks = [[str(n) for n in walk] for walk in weighted_walks]",
"# get node features from the dictionary (already created) node_feats = self.all_node_feats_dic[i] cur_adj",
"num_sample) indice = torch.LongTensor(indice) non_exisiting_adj['idx'] = non_exisiting_adj['idx'][indice,:] non_exisiting_adj['vals'] = non_exisiting_adj['vals'][indice] all_len = len(label_adj['vals'])",
"torch.FloatTensor(values), tensor_size) hot_1 = {'idx': degs_out._indices().t(), 'vals': degs_out._values()} return hot_1 # create dic",
"= adj_mat.tocsr() adj_mat = adj_mat.tocoo() coords = np.vstack((adj_mat.row, adj_mat.col)).transpose() values = adj_mat.data row",
"label_adj['vals'] = label_adj['vals'][indice] # Sampling non_exisiting_adj num_sample = int(np.floor(len(non_exisiting_adj['vals'])*0.02)) indice = random.sample(range(len(non_exisiting_adj['vals'])), num_sample)",
"neg_mult, tot_nodes=self.data.num_nodes, smart_sampling=self.args.smart_neg_sampling, existing_nodes=existing_nodes) # For football data, we need to sample due",
"times embeddings dimensionality # create dic dic = dict(zip(node_ids, weighted_node_embeddings.tolist())) # ascending order",
"sample due to memory constraints if self.args.sport=='football': # Sampling label_adj num_sample = int(np.floor(len(label_adj['vals'])*0.02))",
"return feats_dic def get_sample(self, idx, test, **kwargs): hist_adj_list = [] hist_ndFeats_list = []",
") str_walks = [[str(n) for n in walk] for walk in weighted_walks] weighted_model",
"= rw.run( nodes=list(G.nodes()), # root nodes length=2, # maximum length of a random",
"when contributing to the loss if self.args.adapt: weight = [pos,neg] else: weight =",
"weighted_walks] weighted_model = Word2Vec(str_walks, size=self.feats_per_node, window=5, min_count=0, sg=1, workers=1, iter=1) # Retrieve node",
"random class Link_Pred_Tasker(): def __init__(self, args, dataset): self.data = dataset # max_time for",
"hist_adj_list = [] hist_ndFeats_list = [] hist_mask_list = [] existing_nodes = [] for",
"tu import utils as u from stellargraph import StellarGraph import pandas as pd",
"in the time_window label_adj = tu.get_sp_adj(edges=self.data.edges, time=idx + 1, weighted=False, time_window=self.args.adj_mat_time_window) if test:",
"number=label_adj['vals'].size(0) * neg_mult, tot_nodes=self.data.num_nodes, smart_sampling=self.args.smart_neg_sampling, existing_nodes=existing_nodes) # For football data, we need to",
"neg_mult = self.args.negative_mult_test else: neg_mult = self.args.negative_mult_training if self.args.smart_neg_sampling: existing_nodes = torch.cat(existing_nodes) if",
"create matrix adj_mat = sp.lil_matrix((self.data.num_nodes, self.feats_per_node)) for row_idx in node_ids: adj_mat[row_idx, :] =",
"range(self.data.max_time): if i%30 == 0: print('current i to make embeddings:', i) cur_adj =",
"= non_exisiting_adj['vals'][indice] all_len = len(label_adj['vals']) + len(non_exisiting_adj['vals']) pos = len(label_adj['vals'])/all_len neg = len(non_exisiting_adj['vals'])/all_len",
"# create matrix adj_mat = sp.lil_matrix((self.data.num_nodes, self.feats_per_node)) for row_idx in node_ids: adj_mat[row_idx, :]",
"= dict(sorted(dic.items())) # create matrix adj_mat = sp.lil_matrix((self.data.num_nodes, self.feats_per_node)) for row_idx in node_ids:",
"need to sample due to memory constraints if self.args.sport=='football': # Sampling label_adj num_sample",
"be if we were training on all the edges in the time_window label_adj",
"# maximum length of a random walk n=5, # number of random walks",
"= adj_mat.data row = list(coords[:, 0]) col = list(coords[:, 1]) indexx = torch.LongTensor([row,",
"= int(node_ids[i]) weighted_node_embeddings = ( weighted_model.wv.vectors) # numpy.ndarray of size number of nodes",
"BiasedRandomWalk from gensim.models import Word2Vec import numpy as np import scipy.sparse as sp",
"num_sample) indice = torch.LongTensor(indice) label_adj['idx'] = label_adj['idx'][indice,:] label_adj['vals'] = label_adj['vals'][indice] # Sampling non_exisiting_adj",
"target = edgelist[:, 1] weight = np.ones(len(source)) G = pd.DataFrame({'source': source, 'target': target,",
"weight = np.ones(len(source)) G = pd.DataFrame({'source': source, 'target': target, 'weight': weight}) G =",
"indice = random.sample(range(len(non_exisiting_adj['vals'])), num_sample) indice = torch.LongTensor(indice) non_exisiting_adj['idx'] = non_exisiting_adj['idx'][indice,:] non_exisiting_adj['vals'] = non_exisiting_adj['vals'][indice]",
"= edgelist[:, 1] weight = np.ones(len(source)) G = pd.DataFrame({'source': source, 'target': target, 'weight':",
"of nodes times embeddings dimensionality # create dic dic = dict(zip(node_ids, weighted_node_embeddings.tolist())) #",
"dataset.max_time - 1 self.args = args self.num_classes = 2 if not (args.use_2_hot_node_feats or",
"for reproducibility ) str_walks = [[str(n) for n in walk] for walk in",
"if self.args.smart_neg_sampling: existing_nodes.append(cur_adj['idx'].unique()) else: existing_nodes = None node_mask = tu.get_node_mask(cur_adj, self.data.num_nodes) # get",
"test: neg_mult = self.args.negative_mult_test else: neg_mult = self.args.negative_mult_training if self.args.smart_neg_sampling: existing_nodes = torch.cat(existing_nodes)",
"str_walks = [[str(n) for n in walk] for walk in weighted_walks] weighted_model =",
"weight}) G = StellarGraph(edges=G) rw = BiasedRandomWalk(G) weighted_walks = rw.run( nodes=list(G.nodes()), # root",
"= random.sample(range(len(label_adj['vals'])), num_sample) indice = torch.LongTensor(indice) label_adj['idx'] = label_adj['idx'][indice,:] label_adj['vals'] = label_adj['vals'][indice] #",
"weighted random walks seed=42, # random seed fixed for reproducibility ) str_walks =",
"# For football data, we need to sample due to memory constraints if",
"max_time for link pred should be one before self.max_time = dataset.max_time - 1",
"weight = [pos,neg] else: weight = self.args.class_weights label_adj['idx'] = torch.cat([label_adj['idx'], non_exisiting_adj['idx']]) label_adj['vals'] =",
"if adapt, we use EXACT adaptive weights when contributing to the loss if",
"torch.Size([self.data.num_nodes, self.feats_per_node]) degs_out = torch.sparse.FloatTensor(indexx, torch.FloatTensor(values), tensor_size) hot_1 = {'idx': degs_out._indices().t(), 'vals': degs_out._values()}",
"{'idx': degs_out._indices().t(), 'vals': degs_out._values()} return hot_1 # create dic feats_dic = {} for",
"torch.cat([label_adj['idx'], non_exisiting_adj['idx']]) label_adj['vals'] = torch.cat([label_adj['vals'], non_exisiting_adj['vals']]) return {'idx': idx, 'hist_adj_list': hist_adj_list, 'hist_ndFeats_list': hist_ndFeats_list,",
"= 100 self.all_node_feats_dic = self.build_get_node_feats(args, dataset) ##should be a dic def build_prepare_node_feats(self, args,",
"if 'all_edges' in kwargs.keys() and kwargs['all_edges'] == True: non_exisiting_adj = tu.get_all_non_existing_edges(adj=label_adj, tot_nodes=self.data.num_nodes) else:",
"0: print('current i to make embeddings:', i) cur_adj = tu.get_sp_adj(edges=self.data.edges, time=i, weighted=True, time_window=self.args.adj_mat_time_window)",
"get node features from the dictionary (already created) node_feats = self.all_node_feats_dic[i] cur_adj =",
"numpy.ndarray of size number of nodes times embeddings dimensionality # create dic dic",
"self.args.num_hist_steps, idx + 1): cur_adj = tu.get_sp_adj(edges=self.data.edges, time=i, weighted=True, time_window=self.args.adj_mat_time_window) if self.args.smart_neg_sampling: existing_nodes.append(cur_adj['idx'].unique())",
"NODE2VEC import torch import taskers_utils as tu import utils as u from stellargraph",
"label_adj['vals'][indice] # Sampling non_exisiting_adj num_sample = int(np.floor(len(non_exisiting_adj['vals'])*0.02)) indice = random.sample(range(len(non_exisiting_adj['vals'])), num_sample) indice =",
"print('current i to make embeddings:', i) cur_adj = tu.get_sp_adj(edges=self.data.edges, time=i, weighted=True, time_window=self.args.adj_mat_time_window) feats_dic[i]",
"get_node_feats(cur_adj) return feats_dic def get_sample(self, idx, test, **kwargs): hist_adj_list = [] hist_ndFeats_list =",
"cur_adj = tu.normalize_adj(adj=cur_adj, num_nodes=self.data.num_nodes) hist_adj_list.append(cur_adj) hist_ndFeats_list.append(node_feats) hist_mask_list.append(node_mask) # This would be if we",
"for n in walk] for walk in weighted_walks] weighted_model = Word2Vec(str_walks, size=self.feats_per_node, window=5,",
"= {'idx': degs_out._indices().t(), 'vals': degs_out._values()} return hot_1 # create dic feats_dic = {}",
"walk in weighted_walks] weighted_model = Word2Vec(str_walks, size=self.feats_per_node, window=5, min_count=0, sg=1, workers=1, iter=1) #",
"random.sample(range(len(non_exisiting_adj['vals'])), num_sample) indice = torch.LongTensor(indice) non_exisiting_adj['idx'] = non_exisiting_adj['idx'][indice,:] non_exisiting_adj['vals'] = non_exisiting_adj['vals'][indice] all_len =",
"indice = random.sample(range(len(label_adj['vals'])), num_sample) indice = torch.LongTensor(indice) label_adj['idx'] = label_adj['idx'][indice,:] label_adj['vals'] = label_adj['vals'][indice]",
"target, 'weight': weight}) G = StellarGraph(edges=G) rw = BiasedRandomWalk(G) weighted_walks = rw.run( nodes=list(G.nodes()),",
"args.use_1_hot_node_feats: def prepare_node_feats(node_feats): return u.sparse_prepare_tensor(node_feats, torch_size=[dataset.num_nodes, self.feats_per_node]) else: prepare_node_feats = self.data.prepare_node_feats return prepare_node_feats",
"IDs # change to integer for i in range(0, len(node_ids)): node_ids[i] = int(node_ids[i])",
"else: prepare_node_feats = self.data.prepare_node_feats return prepare_node_feats def build_get_node_feats(self, args, dataset): def get_node_feats(adj): #",
"weighted_model = Word2Vec(str_walks, size=self.feats_per_node, window=5, min_count=0, sg=1, workers=1, iter=1) # Retrieve node embeddings",
"None node_mask = tu.get_node_mask(cur_adj, self.data.num_nodes) # get node features from the dictionary (already",
"in range(idx - self.args.num_hist_steps, idx + 1): cur_adj = tu.get_sp_adj(edges=self.data.edges, time=i, weighted=True, time_window=self.args.adj_mat_time_window)",
"order dic = dict(sorted(dic.items())) # create matrix adj_mat = sp.lil_matrix((self.data.num_nodes, self.feats_per_node)) for row_idx",
"list(coords[:, 0]) col = list(coords[:, 1]) indexx = torch.LongTensor([row, col]) tensor_size = torch.Size([self.data.num_nodes,",
"= [] hist_ndFeats_list = [] hist_mask_list = [] existing_nodes = [] for i",
"dic[row_idx] adj_mat = adj_mat.tocsr() adj_mat = adj_mat.tocoo() coords = np.vstack((adj_mat.row, adj_mat.col)).transpose() values =",
"moving away from source node weighted=True, # for weighted random walks seed=42, #",
"stellargraph.data import BiasedRandomWalk from gensim.models import Word2Vec import numpy as np import scipy.sparse",
"= [] for i in range(idx - self.args.num_hist_steps, idx + 1): cur_adj =",
"num_sample = int(np.floor(len(non_exisiting_adj['vals'])*0.02)) indice = random.sample(range(len(non_exisiting_adj['vals'])), num_sample) indice = torch.LongTensor(indice) non_exisiting_adj['idx'] = non_exisiting_adj['idx'][indice,:]",
"all_len = len(label_adj['vals']) + len(non_exisiting_adj['vals']) pos = len(label_adj['vals'])/all_len neg = len(non_exisiting_adj['vals'])/all_len # if",
"random seed fixed for reproducibility ) str_walks = [[str(n) for n in walk]",
"def build_prepare_node_feats(self, args, dataset): if args.use_2_hot_node_feats or args.use_1_hot_node_feats: def prepare_node_feats(node_feats): return u.sparse_prepare_tensor(node_feats, torch_size=[dataset.num_nodes,",
"existing_nodes = None node_mask = tu.get_node_mask(cur_adj, self.data.num_nodes) # get node features from the",
"weighted_model.wv.index2word # list of node IDs # change to integer for i in",
"to make embeddings:', i) cur_adj = tu.get_sp_adj(edges=self.data.edges, time=i, weighted=True, time_window=self.args.adj_mat_time_window) feats_dic[i] = get_node_feats(cur_adj)",
"tensor_size = torch.Size([self.data.num_nodes, self.feats_per_node]) degs_out = torch.sparse.FloatTensor(indexx, torch.FloatTensor(values), tensor_size) hot_1 = {'idx': degs_out._indices().t(),",
"# root nodes length=2, # maximum length of a random walk n=5, #",
"time=i, weighted=True, time_window=self.args.adj_mat_time_window) if self.args.smart_neg_sampling: existing_nodes.append(cur_adj['idx'].unique()) else: existing_nodes = None node_mask = tu.get_node_mask(cur_adj,",
"be a dic def build_prepare_node_feats(self, args, dataset): if args.use_2_hot_node_feats or args.use_1_hot_node_feats: def prepare_node_feats(node_feats):",
"dic = dict(sorted(dic.items())) # create matrix adj_mat = sp.lil_matrix((self.data.num_nodes, self.feats_per_node)) for row_idx in",
"hot_1 = {'idx': degs_out._indices().t(), 'vals': degs_out._values()} return hot_1 # create dic feats_dic =",
"size number of nodes times embeddings dimensionality # create dic dic = dict(zip(node_ids,",
"= torch.sparse.FloatTensor(indexx, torch.FloatTensor(values), tensor_size) hot_1 = {'idx': degs_out._indices().t(), 'vals': degs_out._values()} return hot_1 #",
"as np import scipy.sparse as sp import logging logging.getLogger(\"gensim.models\").setLevel(logging.WARNING) import time import random",
"(unormalised) probability, 1/p, of returning to source node q=0.5, # Defines (unormalised) probability,",
"seed=42, # random seed fixed for reproducibility ) str_walks = [[str(n) for n",
"= torch.cat(existing_nodes) if 'all_edges' in kwargs.keys() and kwargs['all_edges'] == True: non_exisiting_adj = tu.get_all_non_existing_edges(adj=label_adj,",
"int(node_ids[i]) weighted_node_embeddings = ( weighted_model.wv.vectors) # numpy.ndarray of size number of nodes times",
"rw.run( nodes=list(G.nodes()), # root nodes length=2, # maximum length of a random walk",
"label_adj['idx'][indice,:] label_adj['vals'] = label_adj['vals'][indice] # Sampling non_exisiting_adj num_sample = int(np.floor(len(non_exisiting_adj['vals'])*0.02)) indice = random.sample(range(len(non_exisiting_adj['vals'])),",
"import logging logging.getLogger(\"gensim.models\").setLevel(logging.WARNING) import time import random class Link_Pred_Tasker(): def __init__(self, args, dataset):",
"# max_time for link pred should be one before self.max_time = dataset.max_time -",
"0] target = edgelist[:, 1] weight = np.ones(len(source)) G = pd.DataFrame({'source': source, 'target':",
"maximum length of a random walk n=5, # number of random walks per",
"pos = len(label_adj['vals'])/all_len neg = len(non_exisiting_adj['vals'])/all_len # if adapt, we use EXACT adaptive",
"fixed for reproducibility ) str_walks = [[str(n) for n in walk] for walk",
"= tu.normalize_adj(adj=cur_adj, num_nodes=self.data.num_nodes) hist_adj_list.append(cur_adj) hist_ndFeats_list.append(node_feats) hist_mask_list.append(node_mask) # This would be if we were",
"self.args.smart_neg_sampling: existing_nodes = torch.cat(existing_nodes) if 'all_edges' in kwargs.keys() and kwargs['all_edges'] == True: non_exisiting_adj",
"logging logging.getLogger(\"gensim.models\").setLevel(logging.WARNING) import time import random class Link_Pred_Tasker(): def __init__(self, args, dataset): self.data",
"we were training on all the edges in the time_window label_adj = tu.get_sp_adj(edges=self.data.edges,",
"to integer for i in range(0, len(node_ids)): node_ids[i] = int(node_ids[i]) weighted_node_embeddings = (",
"change to integer for i in range(0, len(node_ids)): node_ids[i] = int(node_ids[i]) weighted_node_embeddings =",
"self.max_time = dataset.max_time - 1 self.args = args self.num_classes = 2 if not",
"to source node q=0.5, # Defines (unormalised) probability, 1/q, for moving away from",
"loss if self.args.adapt: weight = [pos,neg] else: weight = self.args.class_weights label_adj['idx'] = torch.cat([label_adj['idx'],",
"= get_node_feats(cur_adj) return feats_dic def get_sample(self, idx, test, **kwargs): hist_adj_list = [] hist_ndFeats_list",
"1): cur_adj = tu.get_sp_adj(edges=self.data.edges, time=i, weighted=True, time_window=self.args.adj_mat_time_window) if self.args.smart_neg_sampling: existing_nodes.append(cur_adj['idx'].unique()) else: existing_nodes =",
"is cur_adj edgelist = adj['idx'].cpu().data.numpy() source = edgelist[:, 0] target = edgelist[:, 1]",
"= random.sample(range(len(non_exisiting_adj['vals'])), num_sample) indice = torch.LongTensor(indice) non_exisiting_adj['idx'] = non_exisiting_adj['idx'][indice,:] non_exisiting_adj['vals'] = non_exisiting_adj['vals'][indice] all_len",
"walk] for walk in weighted_walks] weighted_model = Word2Vec(str_walks, size=self.feats_per_node, window=5, min_count=0, sg=1, workers=1,",
"as u from stellargraph import StellarGraph import pandas as pd from stellargraph.data import",
"from stellargraph.data import BiasedRandomWalk from gensim.models import Word2Vec import numpy as np import",
"adj['idx'].cpu().data.numpy() source = edgelist[:, 0] target = edgelist[:, 1] weight = np.ones(len(source)) G",
"[] for i in range(idx - self.args.num_hist_steps, idx + 1): cur_adj = tu.get_sp_adj(edges=self.data.edges,",
"tu.get_sp_adj(edges=self.data.edges, time=i, weighted=True, time_window=self.args.adj_mat_time_window) if self.args.smart_neg_sampling: existing_nodes.append(cur_adj['idx'].unique()) else: existing_nodes = None node_mask =",
"the time_window label_adj = tu.get_sp_adj(edges=self.data.edges, time=idx + 1, weighted=False, time_window=self.args.adj_mat_time_window) if test: neg_mult",
"scipy.sparse as sp import logging logging.getLogger(\"gensim.models\").setLevel(logging.WARNING) import time import random class Link_Pred_Tasker(): def",
"of returning to source node q=0.5, # Defines (unormalised) probability, 1/q, for moving",
"degs_out._values()} return hot_1 # create dic feats_dic = {} for i in range(self.data.max_time):",
"np import scipy.sparse as sp import logging logging.getLogger(\"gensim.models\").setLevel(logging.WARNING) import time import random class",
"in range(self.data.max_time): if i%30 == 0: print('current i to make embeddings:', i) cur_adj",
"tu.get_all_non_existing_edges(adj=label_adj, tot_nodes=self.data.num_nodes) else: non_exisiting_adj = tu.get_non_existing_edges(adj=label_adj, number=label_adj['vals'].size(0) * neg_mult, tot_nodes=self.data.num_nodes, smart_sampling=self.args.smart_neg_sampling, existing_nodes=existing_nodes) #",
"indice = torch.LongTensor(indice) label_adj['idx'] = label_adj['idx'][indice,:] label_adj['vals'] = label_adj['vals'][indice] # Sampling non_exisiting_adj num_sample",
"q=0.5, # Defines (unormalised) probability, 1/q, for moving away from source node weighted=True,",
"= self.build_prepare_node_feats(args, dataset) self.is_static = False self.feats_per_node = 100 self.all_node_feats_dic = self.build_get_node_feats(args, dataset)",
"adaptive weights when contributing to the loss if self.args.adapt: weight = [pos,neg] else:",
"import taskers_utils as tu import utils as u from stellargraph import StellarGraph import",
"one before self.max_time = dataset.max_time - 1 self.args = args self.num_classes = 2",
"if self.args.smart_neg_sampling: existing_nodes = torch.cat(existing_nodes) if 'all_edges' in kwargs.keys() and kwargs['all_edges'] == True:",
"col = list(coords[:, 1]) indexx = torch.LongTensor([row, col]) tensor_size = torch.Size([self.data.num_nodes, self.feats_per_node]) degs_out",
"G = pd.DataFrame({'source': source, 'target': target, 'weight': weight}) G = StellarGraph(edges=G) rw =",
"torch.LongTensor([row, col]) tensor_size = torch.Size([self.data.num_nodes, self.feats_per_node]) degs_out = torch.sparse.FloatTensor(indexx, torch.FloatTensor(values), tensor_size) hot_1 =",
"if i%30 == 0: print('current i to make embeddings:', i) cur_adj = tu.get_sp_adj(edges=self.data.edges,",
"self.build_prepare_node_feats(args, dataset) self.is_static = False self.feats_per_node = 100 self.all_node_feats_dic = self.build_get_node_feats(args, dataset) ##should",
"adapt, we use EXACT adaptive weights when contributing to the loss if self.args.adapt:",
"= self.data.prepare_node_feats return prepare_node_feats def build_get_node_feats(self, args, dataset): def get_node_feats(adj): # input is",
"else: non_exisiting_adj = tu.get_non_existing_edges(adj=label_adj, number=label_adj['vals'].size(0) * neg_mult, tot_nodes=self.data.num_nodes, smart_sampling=self.args.smart_neg_sampling, existing_nodes=existing_nodes) # For football",
"For football data, we need to sample due to memory constraints if self.args.sport=='football':",
"dict(zip(node_ids, weighted_node_embeddings.tolist())) # ascending order dic = dict(sorted(dic.items())) # create matrix adj_mat =",
"#FINAL NODE2VEC import torch import taskers_utils as tu import utils as u from",
"torch.sparse.FloatTensor(indexx, torch.FloatTensor(values), tensor_size) hot_1 = {'idx': degs_out._indices().t(), 'vals': degs_out._values()} return hot_1 # create",
"tot_nodes=self.data.num_nodes) else: non_exisiting_adj = tu.get_non_existing_edges(adj=label_adj, number=label_adj['vals'].size(0) * neg_mult, tot_nodes=self.data.num_nodes, smart_sampling=self.args.smart_neg_sampling, existing_nodes=existing_nodes) # For",
"use EXACT adaptive weights when contributing to the loss if self.args.adapt: weight =",
"if not (args.use_2_hot_node_feats or args.use_1_hot_node_feats): self.feats_per_node = dataset.feats_per_node self.prepare_node_feats = self.build_prepare_node_feats(args, dataset) self.is_static",
"import StellarGraph import pandas as pd from stellargraph.data import BiasedRandomWalk from gensim.models import",
"random walks per root node p=1, # Defines (unormalised) probability, 1/p, of returning",
"probability, 1/q, for moving away from source node weighted=True, # for weighted random",
"import utils as u from stellargraph import StellarGraph import pandas as pd from",
"Link_Pred_Tasker(): def __init__(self, args, dataset): self.data = dataset # max_time for link pred",
"= pd.DataFrame({'source': source, 'target': target, 'weight': weight}) G = StellarGraph(edges=G) rw = BiasedRandomWalk(G)",
"__init__(self, args, dataset): self.data = dataset # max_time for link pred should be",
"def prepare_node_feats(node_feats): return u.sparse_prepare_tensor(node_feats, torch_size=[dataset.num_nodes, self.feats_per_node]) else: prepare_node_feats = self.data.prepare_node_feats return prepare_node_feats def",
"2 if not (args.use_2_hot_node_feats or args.use_1_hot_node_feats): self.feats_per_node = dataset.feats_per_node self.prepare_node_feats = self.build_prepare_node_feats(args, dataset)",
":] = dic[row_idx] adj_mat = adj_mat.tocsr() adj_mat = adj_mat.tocoo() coords = np.vstack((adj_mat.row, adj_mat.col)).transpose()",
"+ 1, weighted=False, time_window=self.args.adj_mat_time_window) if test: neg_mult = self.args.negative_mult_test else: neg_mult = self.args.negative_mult_training",
"indice = torch.LongTensor(indice) non_exisiting_adj['idx'] = non_exisiting_adj['idx'][indice,:] non_exisiting_adj['vals'] = non_exisiting_adj['vals'][indice] all_len = len(label_adj['vals']) +",
"self.args.sport=='football': # Sampling label_adj num_sample = int(np.floor(len(label_adj['vals'])*0.02)) indice = random.sample(range(len(label_adj['vals'])), num_sample) indice =",
"G = StellarGraph(edges=G) rw = BiasedRandomWalk(G) weighted_walks = rw.run( nodes=list(G.nodes()), # root nodes",
"args, dataset): self.data = dataset # max_time for link pred should be one",
"self.args.negative_mult_test else: neg_mult = self.args.negative_mult_training if self.args.smart_neg_sampling: existing_nodes = torch.cat(existing_nodes) if 'all_edges' in",
"degs_out._indices().t(), 'vals': degs_out._values()} return hot_1 # create dic feats_dic = {} for i",
"'vals': degs_out._values()} return hot_1 # create dic feats_dic = {} for i in",
"per root node p=1, # Defines (unormalised) probability, 1/p, of returning to source",
"as tu import utils as u from stellargraph import StellarGraph import pandas as",
"build_prepare_node_feats(self, args, dataset): if args.use_2_hot_node_feats or args.use_1_hot_node_feats: def prepare_node_feats(node_feats): return u.sparse_prepare_tensor(node_feats, torch_size=[dataset.num_nodes, self.feats_per_node])",
"of size number of nodes times embeddings dimensionality # create dic dic =",
"StellarGraph import pandas as pd from stellargraph.data import BiasedRandomWalk from gensim.models import Word2Vec",
"features from the dictionary (already created) node_feats = self.all_node_feats_dic[i] cur_adj = tu.normalize_adj(adj=cur_adj, num_nodes=self.data.num_nodes)",
"if self.args.adapt: weight = [pos,neg] else: weight = self.args.class_weights label_adj['idx'] = torch.cat([label_adj['idx'], non_exisiting_adj['idx']])",
"# Defines (unormalised) probability, 1/q, for moving away from source node weighted=True, #",
"dataset.feats_per_node self.prepare_node_feats = self.build_prepare_node_feats(args, dataset) self.is_static = False self.feats_per_node = 100 self.all_node_feats_dic =",
"= len(label_adj['vals']) + len(non_exisiting_adj['vals']) pos = len(label_adj['vals'])/all_len neg = len(non_exisiting_adj['vals'])/all_len # if adapt,",
"self.num_classes = 2 if not (args.use_2_hot_node_feats or args.use_1_hot_node_feats): self.feats_per_node = dataset.feats_per_node self.prepare_node_feats =",
"dimensionality # create dic dic = dict(zip(node_ids, weighted_node_embeddings.tolist())) # ascending order dic =",
"neg = len(non_exisiting_adj['vals'])/all_len # if adapt, we use EXACT adaptive weights when contributing",
"Retrieve node embeddings and corresponding subjects node_ids = weighted_model.wv.index2word # list of node",
"edgelist = adj['idx'].cpu().data.numpy() source = edgelist[:, 0] target = edgelist[:, 1] weight =",
"time_window label_adj = tu.get_sp_adj(edges=self.data.edges, time=idx + 1, weighted=False, time_window=self.args.adj_mat_time_window) if test: neg_mult =",
"row_idx in node_ids: adj_mat[row_idx, :] = dic[row_idx] adj_mat = adj_mat.tocsr() adj_mat = adj_mat.tocoo()",
"the dictionary (already created) node_feats = self.all_node_feats_dic[i] cur_adj = tu.normalize_adj(adj=cur_adj, num_nodes=self.data.num_nodes) hist_adj_list.append(cur_adj) hist_ndFeats_list.append(node_feats)",
"args self.num_classes = 2 if not (args.use_2_hot_node_feats or args.use_1_hot_node_feats): self.feats_per_node = dataset.feats_per_node self.prepare_node_feats",
"size=self.feats_per_node, window=5, min_count=0, sg=1, workers=1, iter=1) # Retrieve node embeddings and corresponding subjects",
"= non_exisiting_adj['idx'][indice,:] non_exisiting_adj['vals'] = non_exisiting_adj['vals'][indice] all_len = len(label_adj['vals']) + len(non_exisiting_adj['vals']) pos = len(label_adj['vals'])/all_len",
"= torch.cat([label_adj['vals'], non_exisiting_adj['vals']]) return {'idx': idx, 'hist_adj_list': hist_adj_list, 'hist_ndFeats_list': hist_ndFeats_list, 'label_sp': label_adj, 'node_mask_list':",
"= adj['idx'].cpu().data.numpy() source = edgelist[:, 0] target = edgelist[:, 1] weight = np.ones(len(source))",
"and kwargs['all_edges'] == True: non_exisiting_adj = tu.get_all_non_existing_edges(adj=label_adj, tot_nodes=self.data.num_nodes) else: non_exisiting_adj = tu.get_non_existing_edges(adj=label_adj, number=label_adj['vals'].size(0)",
"walks per root node p=1, # Defines (unormalised) probability, 1/p, of returning to",
"before self.max_time = dataset.max_time - 1 self.args = args self.num_classes = 2 if",
"= label_adj['idx'][indice,:] label_adj['vals'] = label_adj['vals'][indice] # Sampling non_exisiting_adj num_sample = int(np.floor(len(non_exisiting_adj['vals'])*0.02)) indice =",
"# list of node IDs # change to integer for i in range(0,",
"non_exisiting_adj num_sample = int(np.floor(len(non_exisiting_adj['vals'])*0.02)) indice = random.sample(range(len(non_exisiting_adj['vals'])), num_sample) indice = torch.LongTensor(indice) non_exisiting_adj['idx'] =",
"import torch import taskers_utils as tu import utils as u from stellargraph import",
"= int(np.floor(len(label_adj['vals'])*0.02)) indice = random.sample(range(len(label_adj['vals'])), num_sample) indice = torch.LongTensor(indice) label_adj['idx'] = label_adj['idx'][indice,:] label_adj['vals']",
"= label_adj['vals'][indice] # Sampling non_exisiting_adj num_sample = int(np.floor(len(non_exisiting_adj['vals'])*0.02)) indice = random.sample(range(len(non_exisiting_adj['vals'])), num_sample) indice",
"label_adj['vals'] = torch.cat([label_adj['vals'], non_exisiting_adj['vals']]) return {'idx': idx, 'hist_adj_list': hist_adj_list, 'hist_ndFeats_list': hist_ndFeats_list, 'label_sp': label_adj,",
"non_exisiting_adj['idx'][indice,:] non_exisiting_adj['vals'] = non_exisiting_adj['vals'][indice] all_len = len(label_adj['vals']) + len(non_exisiting_adj['vals']) pos = len(label_adj['vals'])/all_len neg",
"= tu.get_node_mask(cur_adj, self.data.num_nodes) # get node features from the dictionary (already created) node_feats",
"values = adj_mat.data row = list(coords[:, 0]) col = list(coords[:, 1]) indexx =",
"seed fixed for reproducibility ) str_walks = [[str(n) for n in walk] for",
"+ len(non_exisiting_adj['vals']) pos = len(label_adj['vals'])/all_len neg = len(non_exisiting_adj['vals'])/all_len # if adapt, we use",
"adj_mat.tocsr() adj_mat = adj_mat.tocoo() coords = np.vstack((adj_mat.row, adj_mat.col)).transpose() values = adj_mat.data row =",
"= tu.get_all_non_existing_edges(adj=label_adj, tot_nodes=self.data.num_nodes) else: non_exisiting_adj = tu.get_non_existing_edges(adj=label_adj, number=label_adj['vals'].size(0) * neg_mult, tot_nodes=self.data.num_nodes, smart_sampling=self.args.smart_neg_sampling, existing_nodes=existing_nodes)",
"[pos,neg] else: weight = self.args.class_weights label_adj['idx'] = torch.cat([label_adj['idx'], non_exisiting_adj['idx']]) label_adj['vals'] = torch.cat([label_adj['vals'], non_exisiting_adj['vals']])",
"tensor_size) hot_1 = {'idx': degs_out._indices().t(), 'vals': degs_out._values()} return hot_1 # create dic feats_dic",
"EXACT adaptive weights when contributing to the loss if self.args.adapt: weight = [pos,neg]",
"for walk in weighted_walks] weighted_model = Word2Vec(str_walks, size=self.feats_per_node, window=5, min_count=0, sg=1, workers=1, iter=1)",
"created) node_feats = self.all_node_feats_dic[i] cur_adj = tu.normalize_adj(adj=cur_adj, num_nodes=self.data.num_nodes) hist_adj_list.append(cur_adj) hist_ndFeats_list.append(node_feats) hist_mask_list.append(node_mask) # This",
"the edges in the time_window label_adj = tu.get_sp_adj(edges=self.data.edges, time=idx + 1, weighted=False, time_window=self.args.adj_mat_time_window)",
"node_ids: adj_mat[row_idx, :] = dic[row_idx] adj_mat = adj_mat.tocsr() adj_mat = adj_mat.tocoo() coords =",
"( weighted_model.wv.vectors) # numpy.ndarray of size number of nodes times embeddings dimensionality #",
"hot_1 # create dic feats_dic = {} for i in range(self.data.max_time): if i%30",
"= np.vstack((adj_mat.row, adj_mat.col)).transpose() values = adj_mat.data row = list(coords[:, 0]) col = list(coords[:,",
"len(non_exisiting_adj['vals']) pos = len(label_adj['vals'])/all_len neg = len(non_exisiting_adj['vals'])/all_len # if adapt, we use EXACT",
"random.sample(range(len(label_adj['vals'])), num_sample) indice = torch.LongTensor(indice) label_adj['idx'] = label_adj['idx'][indice,:] label_adj['vals'] = label_adj['vals'][indice] # Sampling",
"i in range(idx - self.args.num_hist_steps, idx + 1): cur_adj = tu.get_sp_adj(edges=self.data.edges, time=i, weighted=True,",
"# This would be if we were training on all the edges in",
"= tu.get_sp_adj(edges=self.data.edges, time=idx + 1, weighted=False, time_window=self.args.adj_mat_time_window) if test: neg_mult = self.args.negative_mult_test else:",
"# Sampling label_adj num_sample = int(np.floor(len(label_adj['vals'])*0.02)) indice = random.sample(range(len(label_adj['vals'])), num_sample) indice = torch.LongTensor(indice)",
"'weight': weight}) G = StellarGraph(edges=G) rw = BiasedRandomWalk(G) weighted_walks = rw.run( nodes=list(G.nodes()), #",
"time_window=self.args.adj_mat_time_window) feats_dic[i] = get_node_feats(cur_adj) return feats_dic def get_sample(self, idx, test, **kwargs): hist_adj_list =",
"= len(label_adj['vals'])/all_len neg = len(non_exisiting_adj['vals'])/all_len # if adapt, we use EXACT adaptive weights",
"# random seed fixed for reproducibility ) str_walks = [[str(n) for n in",
"BiasedRandomWalk(G) weighted_walks = rw.run( nodes=list(G.nodes()), # root nodes length=2, # maximum length of",
"torch.cat(existing_nodes) if 'all_edges' in kwargs.keys() and kwargs['all_edges'] == True: non_exisiting_adj = tu.get_all_non_existing_edges(adj=label_adj, tot_nodes=self.data.num_nodes)",
"prepare_node_feats def build_get_node_feats(self, args, dataset): def get_node_feats(adj): # input is cur_adj edgelist =",
"weight = self.args.class_weights label_adj['idx'] = torch.cat([label_adj['idx'], non_exisiting_adj['idx']]) label_adj['vals'] = torch.cat([label_adj['vals'], non_exisiting_adj['vals']]) return {'idx':",
"node_ids = weighted_model.wv.index2word # list of node IDs # change to integer for",
"training on all the edges in the time_window label_adj = tu.get_sp_adj(edges=self.data.edges, time=idx +",
"= [pos,neg] else: weight = self.args.class_weights label_adj['idx'] = torch.cat([label_adj['idx'], non_exisiting_adj['idx']]) label_adj['vals'] = torch.cat([label_adj['vals'],",
"torch.LongTensor(indice) non_exisiting_adj['idx'] = non_exisiting_adj['idx'][indice,:] non_exisiting_adj['vals'] = non_exisiting_adj['vals'][indice] all_len = len(label_adj['vals']) + len(non_exisiting_adj['vals']) pos",
"= np.ones(len(source)) G = pd.DataFrame({'source': source, 'target': target, 'weight': weight}) G = StellarGraph(edges=G)",
"dataset): self.data = dataset # max_time for link pred should be one before",
"from the dictionary (already created) node_feats = self.all_node_feats_dic[i] cur_adj = tu.normalize_adj(adj=cur_adj, num_nodes=self.data.num_nodes) hist_adj_list.append(cur_adj)",
"weights when contributing to the loss if self.args.adapt: weight = [pos,neg] else: weight",
"{} for i in range(self.data.max_time): if i%30 == 0: print('current i to make",
"non_exisiting_adj['idx'] = non_exisiting_adj['idx'][indice,:] non_exisiting_adj['vals'] = non_exisiting_adj['vals'][indice] all_len = len(label_adj['vals']) + len(non_exisiting_adj['vals']) pos =",
"existing_nodes = torch.cat(existing_nodes) if 'all_edges' in kwargs.keys() and kwargs['all_edges'] == True: non_exisiting_adj =",
"# ascending order dic = dict(sorted(dic.items())) # create matrix adj_mat = sp.lil_matrix((self.data.num_nodes, self.feats_per_node))",
"hist_ndFeats_list = [] hist_mask_list = [] existing_nodes = [] for i in range(idx",
"torch.cat([label_adj['vals'], non_exisiting_adj['vals']]) return {'idx': idx, 'hist_adj_list': hist_adj_list, 'hist_ndFeats_list': hist_ndFeats_list, 'label_sp': label_adj, 'node_mask_list': hist_mask_list,",
"def build_get_node_feats(self, args, dataset): def get_node_feats(adj): # input is cur_adj edgelist = adj['idx'].cpu().data.numpy()",
"time_window=self.args.adj_mat_time_window) if test: neg_mult = self.args.negative_mult_test else: neg_mult = self.args.negative_mult_training if self.args.smart_neg_sampling: existing_nodes",
"args.use_2_hot_node_feats or args.use_1_hot_node_feats: def prepare_node_feats(node_feats): return u.sparse_prepare_tensor(node_feats, torch_size=[dataset.num_nodes, self.feats_per_node]) else: prepare_node_feats = self.data.prepare_node_feats",
"hist_ndFeats_list.append(node_feats) hist_mask_list.append(node_mask) # This would be if we were training on all the",
"n=5, # number of random walks per root node p=1, # Defines (unormalised)",
"random walks seed=42, # random seed fixed for reproducibility ) str_walks = [[str(n)",
"weighted_node_embeddings = ( weighted_model.wv.vectors) # numpy.ndarray of size number of nodes times embeddings",
"1, weighted=False, time_window=self.args.adj_mat_time_window) if test: neg_mult = self.args.negative_mult_test else: neg_mult = self.args.negative_mult_training if",
"prepare_node_feats = self.data.prepare_node_feats return prepare_node_feats def build_get_node_feats(self, args, dataset): def get_node_feats(adj): # input",
"weighted_model.wv.vectors) # numpy.ndarray of size number of nodes times embeddings dimensionality # create",
"of node IDs # change to integer for i in range(0, len(node_ids)): node_ids[i]",
"range(idx - self.args.num_hist_steps, idx + 1): cur_adj = tu.get_sp_adj(edges=self.data.edges, time=i, weighted=True, time_window=self.args.adj_mat_time_window) if",
"be one before self.max_time = dataset.max_time - 1 self.args = args self.num_classes =",
"sp.lil_matrix((self.data.num_nodes, self.feats_per_node)) for row_idx in node_ids: adj_mat[row_idx, :] = dic[row_idx] adj_mat = adj_mat.tocsr()",
"idx, test, **kwargs): hist_adj_list = [] hist_ndFeats_list = [] hist_mask_list = [] existing_nodes",
"node p=1, # Defines (unormalised) probability, 1/p, of returning to source node q=0.5,",
"+ 1): cur_adj = tu.get_sp_adj(edges=self.data.edges, time=i, weighted=True, time_window=self.args.adj_mat_time_window) if self.args.smart_neg_sampling: existing_nodes.append(cur_adj['idx'].unique()) else: existing_nodes",
"= self.args.negative_mult_training if self.args.smart_neg_sampling: existing_nodes = torch.cat(existing_nodes) if 'all_edges' in kwargs.keys() and kwargs['all_edges']",
"self.all_node_feats_dic[i] cur_adj = tu.normalize_adj(adj=cur_adj, num_nodes=self.data.num_nodes) hist_adj_list.append(cur_adj) hist_ndFeats_list.append(node_feats) hist_mask_list.append(node_mask) # This would be if",
"Word2Vec(str_walks, size=self.feats_per_node, window=5, min_count=0, sg=1, workers=1, iter=1) # Retrieve node embeddings and corresponding",
"else: weight = self.args.class_weights label_adj['idx'] = torch.cat([label_adj['idx'], non_exisiting_adj['idx']]) label_adj['vals'] = torch.cat([label_adj['vals'], non_exisiting_adj['vals']]) return",
"memory constraints if self.args.sport=='football': # Sampling label_adj num_sample = int(np.floor(len(label_adj['vals'])*0.02)) indice = random.sample(range(len(label_adj['vals'])),",
"Defines (unormalised) probability, 1/p, of returning to source node q=0.5, # Defines (unormalised)",
"on all the edges in the time_window label_adj = tu.get_sp_adj(edges=self.data.edges, time=idx + 1,",
"return u.sparse_prepare_tensor(node_feats, torch_size=[dataset.num_nodes, self.feats_per_node]) else: prepare_node_feats = self.data.prepare_node_feats return prepare_node_feats def build_get_node_feats(self, args,",
"for moving away from source node weighted=True, # for weighted random walks seed=42,",
"hist_mask_list = [] existing_nodes = [] for i in range(idx - self.args.num_hist_steps, idx",
"we need to sample due to memory constraints if self.args.sport=='football': # Sampling label_adj",
"= dict(zip(node_ids, weighted_node_embeddings.tolist())) # ascending order dic = dict(sorted(dic.items())) # create matrix adj_mat",
"tu.normalize_adj(adj=cur_adj, num_nodes=self.data.num_nodes) hist_adj_list.append(cur_adj) hist_ndFeats_list.append(node_feats) hist_mask_list.append(node_mask) # This would be if we were training",
"args, dataset): if args.use_2_hot_node_feats or args.use_1_hot_node_feats: def prepare_node_feats(node_feats): return u.sparse_prepare_tensor(node_feats, torch_size=[dataset.num_nodes, self.feats_per_node]) else:",
"# input is cur_adj edgelist = adj['idx'].cpu().data.numpy() source = edgelist[:, 0] target =",
"Word2Vec import numpy as np import scipy.sparse as sp import logging logging.getLogger(\"gensim.models\").setLevel(logging.WARNING) import",
"<reponame>sykailak/evolvegcn<gh_stars>0 #FINAL NODE2VEC import torch import taskers_utils as tu import utils as u",
"integer for i in range(0, len(node_ids)): node_ids[i] = int(node_ids[i]) weighted_node_embeddings = ( weighted_model.wv.vectors)",
"ascending order dic = dict(sorted(dic.items())) # create matrix adj_mat = sp.lil_matrix((self.data.num_nodes, self.feats_per_node)) for",
"100 self.all_node_feats_dic = self.build_get_node_feats(args, dataset) ##should be a dic def build_prepare_node_feats(self, args, dataset):",
"make embeddings:', i) cur_adj = tu.get_sp_adj(edges=self.data.edges, time=i, weighted=True, time_window=self.args.adj_mat_time_window) feats_dic[i] = get_node_feats(cur_adj) return",
"smart_sampling=self.args.smart_neg_sampling, existing_nodes=existing_nodes) # For football data, we need to sample due to memory",
"= torch.LongTensor(indice) label_adj['idx'] = label_adj['idx'][indice,:] label_adj['vals'] = label_adj['vals'][indice] # Sampling non_exisiting_adj num_sample =",
"if we were training on all the edges in the time_window label_adj =",
"get_sample(self, idx, test, **kwargs): hist_adj_list = [] hist_ndFeats_list = [] hist_mask_list = []",
"return hot_1 # create dic feats_dic = {} for i in range(self.data.max_time): if",
"= len(non_exisiting_adj['vals'])/all_len # if adapt, we use EXACT adaptive weights when contributing to",
"adj_mat = adj_mat.tocsr() adj_mat = adj_mat.tocoo() coords = np.vstack((adj_mat.row, adj_mat.col)).transpose() values = adj_mat.data",
"= self.build_get_node_feats(args, dataset) ##should be a dic def build_prepare_node_feats(self, args, dataset): if args.use_2_hot_node_feats",
"for i in range(0, len(node_ids)): node_ids[i] = int(node_ids[i]) weighted_node_embeddings = ( weighted_model.wv.vectors) #",
"create dic dic = dict(zip(node_ids, weighted_node_embeddings.tolist())) # ascending order dic = dict(sorted(dic.items())) #",
"source = edgelist[:, 0] target = edgelist[:, 1] weight = np.ones(len(source)) G =",
"= self.args.class_weights label_adj['idx'] = torch.cat([label_adj['idx'], non_exisiting_adj['idx']]) label_adj['vals'] = torch.cat([label_adj['vals'], non_exisiting_adj['vals']]) return {'idx': idx,",
"tu.get_non_existing_edges(adj=label_adj, number=label_adj['vals'].size(0) * neg_mult, tot_nodes=self.data.num_nodes, smart_sampling=self.args.smart_neg_sampling, existing_nodes=existing_nodes) # For football data, we need",
"int(np.floor(len(non_exisiting_adj['vals'])*0.02)) indice = random.sample(range(len(non_exisiting_adj['vals'])), num_sample) indice = torch.LongTensor(indice) non_exisiting_adj['idx'] = non_exisiting_adj['idx'][indice,:] non_exisiting_adj['vals'] =",
"from source node weighted=True, # for weighted random walks seed=42, # random seed",
"kwargs['all_edges'] == True: non_exisiting_adj = tu.get_all_non_existing_edges(adj=label_adj, tot_nodes=self.data.num_nodes) else: non_exisiting_adj = tu.get_non_existing_edges(adj=label_adj, number=label_adj['vals'].size(0) *",
"if args.use_2_hot_node_feats or args.use_1_hot_node_feats: def prepare_node_feats(node_feats): return u.sparse_prepare_tensor(node_feats, torch_size=[dataset.num_nodes, self.feats_per_node]) else: prepare_node_feats =",
"self.data.num_nodes) # get node features from the dictionary (already created) node_feats = self.all_node_feats_dic[i]",
"self.all_node_feats_dic = self.build_get_node_feats(args, dataset) ##should be a dic def build_prepare_node_feats(self, args, dataset): if",
"# change to integer for i in range(0, len(node_ids)): node_ids[i] = int(node_ids[i]) weighted_node_embeddings",
"for link pred should be one before self.max_time = dataset.max_time - 1 self.args",
"for i in range(idx - self.args.num_hist_steps, idx + 1): cur_adj = tu.get_sp_adj(edges=self.data.edges, time=i,",
"else: neg_mult = self.args.negative_mult_training if self.args.smart_neg_sampling: existing_nodes = torch.cat(existing_nodes) if 'all_edges' in kwargs.keys()",
"not (args.use_2_hot_node_feats or args.use_1_hot_node_feats): self.feats_per_node = dataset.feats_per_node self.prepare_node_feats = self.build_prepare_node_feats(args, dataset) self.is_static =",
"* neg_mult, tot_nodes=self.data.num_nodes, smart_sampling=self.args.smart_neg_sampling, existing_nodes=existing_nodes) # For football data, we need to sample",
"row = list(coords[:, 0]) col = list(coords[:, 1]) indexx = torch.LongTensor([row, col]) tensor_size",
"# number of random walks per root node p=1, # Defines (unormalised) probability,",
"pandas as pd from stellargraph.data import BiasedRandomWalk from gensim.models import Word2Vec import numpy",
"of a random walk n=5, # number of random walks per root node",
"##should be a dic def build_prepare_node_feats(self, args, dataset): if args.use_2_hot_node_feats or args.use_1_hot_node_feats: def",
"subjects node_ids = weighted_model.wv.index2word # list of node IDs # change to integer",
"= self.args.negative_mult_test else: neg_mult = self.args.negative_mult_training if self.args.smart_neg_sampling: existing_nodes = torch.cat(existing_nodes) if 'all_edges'",
"tu.get_node_mask(cur_adj, self.data.num_nodes) # get node features from the dictionary (already created) node_feats =",
"embeddings dimensionality # create dic dic = dict(zip(node_ids, weighted_node_embeddings.tolist())) # ascending order dic",
"int(np.floor(len(label_adj['vals'])*0.02)) indice = random.sample(range(len(label_adj['vals'])), num_sample) indice = torch.LongTensor(indice) label_adj['idx'] = label_adj['idx'][indice,:] label_adj['vals'] =",
"== 0: print('current i to make embeddings:', i) cur_adj = tu.get_sp_adj(edges=self.data.edges, time=i, weighted=True,",
"weighted_walks = rw.run( nodes=list(G.nodes()), # root nodes length=2, # maximum length of a",
"= tu.get_non_existing_edges(adj=label_adj, number=label_adj['vals'].size(0) * neg_mult, tot_nodes=self.data.num_nodes, smart_sampling=self.args.smart_neg_sampling, existing_nodes=existing_nodes) # For football data, we",
"in kwargs.keys() and kwargs['all_edges'] == True: non_exisiting_adj = tu.get_all_non_existing_edges(adj=label_adj, tot_nodes=self.data.num_nodes) else: non_exisiting_adj =",
"hist_adj_list.append(cur_adj) hist_ndFeats_list.append(node_feats) hist_mask_list.append(node_mask) # This would be if we were training on all",
"import scipy.sparse as sp import logging logging.getLogger(\"gensim.models\").setLevel(logging.WARNING) import time import random class Link_Pred_Tasker():",
"def __init__(self, args, dataset): self.data = dataset # max_time for link pred should",
"(already created) node_feats = self.all_node_feats_dic[i] cur_adj = tu.normalize_adj(adj=cur_adj, num_nodes=self.data.num_nodes) hist_adj_list.append(cur_adj) hist_ndFeats_list.append(node_feats) hist_mask_list.append(node_mask) #",
"1/q, for moving away from source node weighted=True, # for weighted random walks",
"self.feats_per_node]) degs_out = torch.sparse.FloatTensor(indexx, torch.FloatTensor(values), tensor_size) hot_1 = {'idx': degs_out._indices().t(), 'vals': degs_out._values()} return",
"def get_node_feats(adj): # input is cur_adj edgelist = adj['idx'].cpu().data.numpy() source = edgelist[:, 0]",
"feats_dic = {} for i in range(self.data.max_time): if i%30 == 0: print('current i",
"= False self.feats_per_node = 100 self.all_node_feats_dic = self.build_get_node_feats(args, dataset) ##should be a dic",
"1] weight = np.ones(len(source)) G = pd.DataFrame({'source': source, 'target': target, 'weight': weight}) G",
"= 2 if not (args.use_2_hot_node_feats or args.use_1_hot_node_feats): self.feats_per_node = dataset.feats_per_node self.prepare_node_feats = self.build_prepare_node_feats(args,",
"degs_out = torch.sparse.FloatTensor(indexx, torch.FloatTensor(values), tensor_size) hot_1 = {'idx': degs_out._indices().t(), 'vals': degs_out._values()} return hot_1",
"contributing to the loss if self.args.adapt: weight = [pos,neg] else: weight = self.args.class_weights",
"self.args.adapt: weight = [pos,neg] else: weight = self.args.class_weights label_adj['idx'] = torch.cat([label_adj['idx'], non_exisiting_adj['idx']]) label_adj['vals']",
"True: non_exisiting_adj = tu.get_all_non_existing_edges(adj=label_adj, tot_nodes=self.data.num_nodes) else: non_exisiting_adj = tu.get_non_existing_edges(adj=label_adj, number=label_adj['vals'].size(0) * neg_mult, tot_nodes=self.data.num_nodes,",
"for i in range(self.data.max_time): if i%30 == 0: print('current i to make embeddings:',",
"import time import random class Link_Pred_Tasker(): def __init__(self, args, dataset): self.data = dataset",
"pred should be one before self.max_time = dataset.max_time - 1 self.args = args",
"edges in the time_window label_adj = tu.get_sp_adj(edges=self.data.edges, time=idx + 1, weighted=False, time_window=self.args.adj_mat_time_window) if",
"i) cur_adj = tu.get_sp_adj(edges=self.data.edges, time=i, weighted=True, time_window=self.args.adj_mat_time_window) feats_dic[i] = get_node_feats(cur_adj) return feats_dic def",
"min_count=0, sg=1, workers=1, iter=1) # Retrieve node embeddings and corresponding subjects node_ids =",
"weighted=True, time_window=self.args.adj_mat_time_window) if self.args.smart_neg_sampling: existing_nodes.append(cur_adj['idx'].unique()) else: existing_nodes = None node_mask = tu.get_node_mask(cur_adj, self.data.num_nodes)",
"torch.LongTensor(indice) label_adj['idx'] = label_adj['idx'][indice,:] label_adj['vals'] = label_adj['vals'][indice] # Sampling non_exisiting_adj num_sample = int(np.floor(len(non_exisiting_adj['vals'])*0.02))",
"adj_mat.data row = list(coords[:, 0]) col = list(coords[:, 1]) indexx = torch.LongTensor([row, col])",
"'all_edges' in kwargs.keys() and kwargs['all_edges'] == True: non_exisiting_adj = tu.get_all_non_existing_edges(adj=label_adj, tot_nodes=self.data.num_nodes) else: non_exisiting_adj",
"= tu.get_sp_adj(edges=self.data.edges, time=i, weighted=True, time_window=self.args.adj_mat_time_window) feats_dic[i] = get_node_feats(cur_adj) return feats_dic def get_sample(self, idx,",
"we use EXACT adaptive weights when contributing to the loss if self.args.adapt: weight",
"get_node_feats(adj): # input is cur_adj edgelist = adj['idx'].cpu().data.numpy() source = edgelist[:, 0] target",
"tu.get_sp_adj(edges=self.data.edges, time=idx + 1, weighted=False, time_window=self.args.adj_mat_time_window) if test: neg_mult = self.args.negative_mult_test else: neg_mult",
"dic = dict(zip(node_ids, weighted_node_embeddings.tolist())) # ascending order dic = dict(sorted(dic.items())) # create matrix",
"i to make embeddings:', i) cur_adj = tu.get_sp_adj(edges=self.data.edges, time=i, weighted=True, time_window=self.args.adj_mat_time_window) feats_dic[i] =",
"sp import logging logging.getLogger(\"gensim.models\").setLevel(logging.WARNING) import time import random class Link_Pred_Tasker(): def __init__(self, args,",
"[] hist_mask_list = [] existing_nodes = [] for i in range(idx - self.args.num_hist_steps,",
"(unormalised) probability, 1/q, for moving away from source node weighted=True, # for weighted",
"neg_mult = self.args.negative_mult_training if self.args.smart_neg_sampling: existing_nodes = torch.cat(existing_nodes) if 'all_edges' in kwargs.keys() and",
"node q=0.5, # Defines (unormalised) probability, 1/q, for moving away from source node",
"embeddings and corresponding subjects node_ids = weighted_model.wv.index2word # list of node IDs #",
"len(non_exisiting_adj['vals'])/all_len # if adapt, we use EXACT adaptive weights when contributing to the",
"import pandas as pd from stellargraph.data import BiasedRandomWalk from gensim.models import Word2Vec import",
"len(label_adj['vals']) + len(non_exisiting_adj['vals']) pos = len(label_adj['vals'])/all_len neg = len(non_exisiting_adj['vals'])/all_len # if adapt, we",
"else: existing_nodes = None node_mask = tu.get_node_mask(cur_adj, self.data.num_nodes) # get node features from",
"link pred should be one before self.max_time = dataset.max_time - 1 self.args =",
"in weighted_walks] weighted_model = Word2Vec(str_walks, size=self.feats_per_node, window=5, min_count=0, sg=1, workers=1, iter=1) # Retrieve",
"= dataset # max_time for link pred should be one before self.max_time =",
"non_exisiting_adj = tu.get_non_existing_edges(adj=label_adj, number=label_adj['vals'].size(0) * neg_mult, tot_nodes=self.data.num_nodes, smart_sampling=self.args.smart_neg_sampling, existing_nodes=existing_nodes) # For football data,",
"walks seed=42, # random seed fixed for reproducibility ) str_walks = [[str(n) for",
"pd.DataFrame({'source': source, 'target': target, 'weight': weight}) G = StellarGraph(edges=G) rw = BiasedRandomWalk(G) weighted_walks",
"edgelist[:, 1] weight = np.ones(len(source)) G = pd.DataFrame({'source': source, 'target': target, 'weight': weight})",
"= args self.num_classes = 2 if not (args.use_2_hot_node_feats or args.use_1_hot_node_feats): self.feats_per_node = dataset.feats_per_node",
"cur_adj edgelist = adj['idx'].cpu().data.numpy() source = edgelist[:, 0] target = edgelist[:, 1] weight",
"import numpy as np import scipy.sparse as sp import logging logging.getLogger(\"gensim.models\").setLevel(logging.WARNING) import time",
"in range(0, len(node_ids)): node_ids[i] = int(node_ids[i]) weighted_node_embeddings = ( weighted_model.wv.vectors) # numpy.ndarray of",
"'target': target, 'weight': weight}) G = StellarGraph(edges=G) rw = BiasedRandomWalk(G) weighted_walks = rw.run(",
"= StellarGraph(edges=G) rw = BiasedRandomWalk(G) weighted_walks = rw.run( nodes=list(G.nodes()), # root nodes length=2,",
"adj_mat.col)).transpose() values = adj_mat.data row = list(coords[:, 0]) col = list(coords[:, 1]) indexx",
"root nodes length=2, # maximum length of a random walk n=5, # number",
"args, dataset): def get_node_feats(adj): # input is cur_adj edgelist = adj['idx'].cpu().data.numpy() source =",
"tu.get_sp_adj(edges=self.data.edges, time=i, weighted=True, time_window=self.args.adj_mat_time_window) feats_dic[i] = get_node_feats(cur_adj) return feats_dic def get_sample(self, idx, test,",
"= dataset.feats_per_node self.prepare_node_feats = self.build_prepare_node_feats(args, dataset) self.is_static = False self.feats_per_node = 100 self.all_node_feats_dic",
"self.args.negative_mult_training if self.args.smart_neg_sampling: existing_nodes = torch.cat(existing_nodes) if 'all_edges' in kwargs.keys() and kwargs['all_edges'] ==",
"args.use_1_hot_node_feats): self.feats_per_node = dataset.feats_per_node self.prepare_node_feats = self.build_prepare_node_feats(args, dataset) self.is_static = False self.feats_per_node =",
"Sampling label_adj num_sample = int(np.floor(len(label_adj['vals'])*0.02)) indice = random.sample(range(len(label_adj['vals'])), num_sample) indice = torch.LongTensor(indice) label_adj['idx']",
"would be if we were training on all the edges in the time_window",
"pd from stellargraph.data import BiasedRandomWalk from gensim.models import Word2Vec import numpy as np",
"- 1 self.args = args self.num_classes = 2 if not (args.use_2_hot_node_feats or args.use_1_hot_node_feats):",
"import BiasedRandomWalk from gensim.models import Word2Vec import numpy as np import scipy.sparse as",
"num_nodes=self.data.num_nodes) hist_adj_list.append(cur_adj) hist_ndFeats_list.append(node_feats) hist_mask_list.append(node_mask) # This would be if we were training on",
"dictionary (already created) node_feats = self.all_node_feats_dic[i] cur_adj = tu.normalize_adj(adj=cur_adj, num_nodes=self.data.num_nodes) hist_adj_list.append(cur_adj) hist_ndFeats_list.append(node_feats) hist_mask_list.append(node_mask)",
"dataset # max_time for link pred should be one before self.max_time = dataset.max_time",
"1/p, of returning to source node q=0.5, # Defines (unormalised) probability, 1/q, for",
"== True: non_exisiting_adj = tu.get_all_non_existing_edges(adj=label_adj, tot_nodes=self.data.num_nodes) else: non_exisiting_adj = tu.get_non_existing_edges(adj=label_adj, number=label_adj['vals'].size(0) * neg_mult,",
"root node p=1, # Defines (unormalised) probability, 1/p, of returning to source node",
"adj_mat.tocoo() coords = np.vstack((adj_mat.row, adj_mat.col)).transpose() values = adj_mat.data row = list(coords[:, 0]) col",
"label_adj num_sample = int(np.floor(len(label_adj['vals'])*0.02)) indice = random.sample(range(len(label_adj['vals'])), num_sample) indice = torch.LongTensor(indice) label_adj['idx'] =",
"n in walk] for walk in weighted_walks] weighted_model = Word2Vec(str_walks, size=self.feats_per_node, window=5, min_count=0,",
"= [] existing_nodes = [] for i in range(idx - self.args.num_hist_steps, idx +",
"self.args.smart_neg_sampling: existing_nodes.append(cur_adj['idx'].unique()) else: existing_nodes = None node_mask = tu.get_node_mask(cur_adj, self.data.num_nodes) # get node"
] |
[
"* from plugin_system import Plugin plugin = Plugin(\"Отправка сообщения\", usage=[\"напиши [id] [сообщение] -",
"ignored_by=uid): return await msg.answer('Вы находитесь в чёрном списке у этого пользователя!') user =",
"in await db.execute(Role.select().where(Role.role == \"admin\")): if await get_or_none(Ignore, ignored=sender_id, ignored_by=role.user_id): return await msg.answer('Вы",
"беспокоить!') data = ' '.join(args) if check_links(data): return await msg.answer('В сообщении были обнаружены",
"string for x in DISABLED) @plugin.on_init() def init(vk): pass @plugin.on_command('анонимка', 'анонимно') async def",
"msg.answer('Вы находитесь в чёрном списке у этого пользователя!') user = await get_or_none(User, uid=uid)",
"отправлено!') @plugin.on_command('админу') async def to_admin(msg, args): sender_id = msg.user_id for role in await",
"получать сообщения\"], need_db=True) DISABLED = ('https', 'http', 'com', 'www', 'ftp', '://') def check_links(string):",
"от {sender_data['first_name']} {sender_data['last_name']}!\\n\\\"{data}\\\"\", } if \"attach1\" in msg.brief_attaches: val['attachment'] = \",\".join(str(x) for x",
"мне отправлять сообщение самому себе?!') if await get_or_none(Ignore, ignored=sender_id, ignored_by=uid): return await msg.answer('Вы",
"введёного ID пользователя.') if sender_id == uid: return await msg.answer('Зачем мне отправлять сообщение",
"data = ' '.join(args) if check_links(data): return await msg.answer('В сообщении были обнаружены ссылки!')",
"uid = int(possible_id) if not uid: return await msg.answer('Проверьте правильность введёного ID пользователя.')",
"правильность введёного ID пользователя.') if sender_id == uid: return await msg.answer('Зачем мне отправлять",
"сообщение пользователю\" \"(посылать можно только текст и/или фото)\", \"не беспокоить - не получать",
"пользователя.') await db.execute(Ignore.delete().where( (Ignore.ignored == uid) & (Ignore.ignored_by == sender_id) )) await msg.answer(f'Теперь",
"msg.answer('Вы находитесь в чёрном списке у этого пользователя!') user = await get_or_none(User, uid=role.user_id)",
"у бота проблемы с базой данных)') user.do_not_disturb = True await db.update(user) await msg.answer('Вы",
"if not text_required: full = await msg.full_attaches if full: message += \"Вложения:\\n\".join(m.link for",
"unignore.pop() if not unignore_id.isdigit(): uid = await msg.vk.resolve_name(unignore_id) else: uid = int(unignore_id) if",
"val) if not result: return await msg.answer('Сообщение не удалось отправить!') await msg.answer('Сообщение успешно",
"сообщения\", \"беспокоить - получать сообщения\"], need_db=True) DISABLED = ('https', 'http', 'com', 'www', 'ftp',",
"break if len(args) < 2 and text_required: return await msg.answer('Введите ID пользователя и",
"= int(ignore_id) if not uid: return await msg.answer('Проверьте правильность введёного ID пользователя.') await",
"not msg.brief_attaches) and len(args) < 2: return await msg.answer('Введите ID пользователя и сообщение",
"1: return await msg.answer('Введите ID пользователя для игнорирования.') sender_id = msg.user_id ignore_id =",
"которого вы хотите убрать из игнора.') sender_id = msg.user_id unignore_id = unignore.pop() if",
"user.do_not_disturb = True await db.update(user) await msg.answer('Вы не будете получать сообщения!') @plugin.on_command('беспокоить') async",
"= sender_data[0] val = { 'peer_id': uid, 'message': f\"Вам сообщение от {sender_data['first_name']} {sender_data['last_name']}!\\n\\\"{data}\\\"\",",
"пользователя!') user = await get_or_none(User, uid=uid) if user and user.do_not_disturb: return await msg.answer('Этот",
"пользователю\" \"(посылать можно только текст и/или фото)\", \"не беспокоить - не получать сообщения\",",
"x in DISABLED) @plugin.on_init() def init(vk): pass @plugin.on_command('анонимка', 'анонимно') async def anonymously(msg, args):",
"\",\".join(str(x) for x in await msg.full_attaches) result = await msg.vk.method('messages.send', val) if not",
"игнорирования.') sender_id = msg.user_id ignore_id = args.pop() if not ignore_id.isdigit(): uid = await",
"сообщения от {ignore_id}!') @plugin.on_command('показать') async def show(msg, unignore): if len(unignore) < 1: return",
"if await get_or_none(Ignore, ignored=sender_id, ignored_by=role.user_id): return await msg.answer('Вы находитесь в чёрном списке у",
"'_type' in k and v == \"photo\": text_required = False break if len(args)",
"\"Вам анонимное сообщение!\\n\" if data: message += data + \"\\n\" if not text_required:",
"return await msg.answer('Вы находитесь в чёрном списке у этого пользователя!') user = await",
"init(vk): pass @plugin.on_command('анонимка', 'анонимно') async def anonymously(msg, args): text_required = True for k,",
"uid, 'message': message } result = await msg.vk.method('messages.send', val) if not result: return",
"вам сообщения!') @plugin.on_command('не беспокоить') async def do_not_disturb(msg, args): user = await get_or_none(User, uid=msg.user_id)",
"ID пользователя для игнорирования.') sender_id = msg.user_id ignore_id = args.pop() if not ignore_id.isdigit():",
"+ \"\\n\" if not text_required: full = await msg.full_attaches if full: message +=",
"!= 1 or not msg.brief_attaches) and len(args) < 2: return await msg.answer('Введите ID",
"пользователя, которого вы хотите убрать из игнора.') sender_id = msg.user_id unignore_id = unignore.pop()",
"= { 'peer_id': role.user_id, 'message': f\"Вам сообщение от {sender_data['first_name']} {sender_data['last_name']}!\\n\\\"{data}\\\"\", } if \"attach1\"",
"await get_or_none(User, uid=uid) if user and user.do_not_disturb: return await msg.answer('Этот пользователь попросил его",
"sender_data = sender_data[0] val = { 'peer_id': role.user_id, 'message': f\"Вам сообщение от {sender_data['first_name']}",
"= True await db.update(user) await msg.answer('Вы не будете получать сообщения!') @plugin.on_command('беспокоить') async def",
"do_disturb(msg, args): user = await get_or_none(User, uid=msg.user_id) if not user: return await msg.answer('Вы",
"await msg.answer('Вы не будете получать сообщения!') @plugin.on_command('беспокоить') async def do_disturb(msg, args): user =",
"отправить!') await msg.answer('Сообщение успешно отправлено!') @plugin.on_command('написать', 'напиши', 'лс', 'письмо') async def write_msg(msg, args):",
"не беспокоить!') data = ' '.join(args) if check_links(data): return await msg.answer('В сообщении были",
"пользователя!') user = await get_or_none(User, uid=role.user_id) if user and user.do_not_disturb: return await msg.answer('Этот",
"== uid: return await msg.answer('Зачем мне отправлять сообщение вам?!') if await get_or_none(Ignore, ignored=sender_id,",
"not unignore_id.isdigit(): uid = await msg.vk.resolve_name(unignore_id) else: uid = int(unignore_id) if not uid:",
"need_db=True) DISABLED = ('https', 'http', 'com', 'www', 'ftp', '://') def check_links(string): return any(x",
"return await msg.answer('Проверьте правильность введёного ID пользователя.') if sender_id == uid: return await",
"await msg.answer('Сообщение не удалось отправить!') await msg.answer('Сообщение успешно отправлено!') @plugin.on_command('админу') async def to_admin(msg,",
"not result: return await msg.answer('Сообщение не удалось отправить!') await msg.answer('Сообщение успешно отправлено!') @plugin.on_command('скрыть')",
"db.update(user) await msg.answer('Вы не будете получать сообщения!') @plugin.on_command('беспокоить') async def do_disturb(msg, args): user",
"= unignore.pop() if not unignore_id.isdigit(): uid = await msg.vk.resolve_name(unignore_id) else: uid = int(unignore_id)",
"базой данных)') user.do_not_disturb = True await db.update(user) await msg.answer('Вы не будете получать сообщения!')",
"существуете!\\n(или у бота проблемы с базой данных)') user.do_not_disturb = False await db.update(user) await",
"ignore_id.isdigit(): uid = await msg.vk.resolve_name(ignore_id) else: uid = int(ignore_id) if not uid: return",
"списке у этого пользователя!') user = await get_or_none(User, uid=role.user_id) if user and user.do_not_disturb:",
"успешно отправлено!') @plugin.on_command('написать', 'напиши', 'лс', 'письмо') async def write_msg(msg, args): if (len(args) !=",
"'://') def check_links(string): return any(x in string for x in DISABLED) @plugin.on_init() def",
"msg.answer('Сообщение не удалось отправить!') await msg.answer('Сообщение успешно отправлено!') @plugin.on_command('написать', 'напиши', 'лс', 'письмо') async",
"< 2 and text_required: return await msg.answer('Введите ID пользователя и сообщение для него.')",
"сообщение от {sender_data['first_name']} {sender_data['last_name']}!\\n\\\"{data}\\\"\", } if \"attach1\" in msg.brief_attaches: val['attachment'] = \",\".join(str(x) for",
"role.user_id, 'message': f\"Вам сообщение от {sender_data['first_name']} {sender_data['last_name']}!\\n\\\"{data}\\\"\", } if \"attach1\" in msg.brief_attaches: val['attachment']",
"full) val = { 'peer_id': uid, 'message': message } result = await msg.vk.method('messages.send',",
"= { 'peer_id': uid, 'message': message } result = await msg.vk.method('messages.send', val) if",
"будете получать сообщения от {ignore_id}!') @plugin.on_command('показать') async def show(msg, unignore): if len(unignore) <",
"= int(possible_id) if not uid: return await msg.answer('Проверьте правильность введёного ID пользователя.') if",
"message } result = await msg.vk.method('messages.send', val) if not result: return await msg.answer('Сообщение",
"\"не беспокоить - не получать сообщения\", \"беспокоить - получать сообщения\"], need_db=True) DISABLED =",
"= msg.user_id possible_id = args.pop(0) if not possible_id.isdigit(): uid = await msg.vk.resolve_name(possible_id) else:",
"вам?!') if await get_or_none(Ignore, ignored=sender_id, ignored_by=uid): return await msg.answer('Вы находитесь в чёрном списке",
"async def to_admin(msg, args): sender_id = msg.user_id for role in await db.execute(Role.select().where(Role.role ==",
"role in await db.execute(Role.select().where(Role.role == \"admin\")): if await get_or_none(Ignore, ignored=sender_id, ignored_by=role.user_id): return await",
"await msg.answer('Этот пользователь попросил его не беспокоить!') data = ' '.join(args) if check_links(data):",
"in k and v == \"photo\": text_required = False break if len(args) <",
"uid=msg.user_id) if not user: return await msg.answer('Вы не существуете!\\n(или у бота проблемы с",
"{ignore_id}!') @plugin.on_command('показать') async def show(msg, unignore): if len(unignore) < 1: return await msg.answer('Введите",
"True await db.update(user) await msg.answer('Вы не будете получать сообщения!') @plugin.on_command('беспокоить') async def do_disturb(msg,",
"def anonymously(msg, args): text_required = True for k, v in msg.brief_attaches.items(): if '_type'",
"не существуете!\\n(или у бота проблемы с базой данных)') user.do_not_disturb = True await db.update(user)",
"проблемы с базой данных)') user.do_not_disturb = False await db.update(user) await msg.answer('Вы будете получать",
"text_required = False break if len(args) < 2 and text_required: return await msg.answer('Введите",
"msg.answer('В сообщении были обнаружены ссылки!') message = \"Вам анонимное сообщение!\\n\" if data: message",
"для него.') sender_id = msg.user_id possible_id = args.pop(0) if not possible_id.isdigit(): uid =",
"msg.full_attaches if full: message += \"Вложения:\\n\".join(m.link for m in full) val = {",
"val['attachment'] = \",\".join(str(x) for x in await msg.full_attaches) result = await msg.vk.method('messages.send', val)",
"args.pop() if not ignore_id.isdigit(): uid = await msg.vk.resolve_name(ignore_id) else: uid = int(ignore_id) if",
"message += data + \"\\n\" if not text_required: full = await msg.full_attaches if",
"uid=role.user_id) if user and user.do_not_disturb: return await msg.answer('Этот пользователь попросил его не беспокоить!')",
"сообщение!\\n\" if data: message += data + \"\\n\" if not text_required: full =",
"@plugin.on_command('скрыть') async def hide(msg, args): if len(args) < 1: return await msg.answer('Введите ID",
"await db.execute(Ignore.delete().where( (Ignore.ignored == uid) & (Ignore.ignored_by == sender_id) )) await msg.answer(f'Теперь {unignore_id}",
"msg.vk.resolve_name(ignore_id) else: uid = int(ignore_id) if not uid: return await msg.answer('Проверьте правильность введёного",
"@plugin.on_command('админу') async def to_admin(msg, args): sender_id = msg.user_id for role in await db.execute(Role.select().where(Role.role",
"db.create_or_get(Ignore, ignored=uid, ignored_by=sender_id) await msg.answer(f'Вы не будете получать сообщения от {ignore_id}!') @plugin.on_command('показать') async",
"= { 'peer_id': uid, 'message': f\"Вам сообщение от {sender_data['first_name']} {sender_data['last_name']}!\\n\\\"{data}\\\"\", } if \"attach1\"",
"сообщение пользователю\", \"анонимно [id] [сообщение] - написать анонимное сообщение пользователю\" \"(посылать можно только",
"правильность введёного ID пользователя.') await db.create_or_get(Ignore, ignored=uid, ignored_by=sender_id) await msg.answer(f'Вы не будете получать",
"= args.pop() if not ignore_id.isdigit(): uid = await msg.vk.resolve_name(ignore_id) else: uid = int(ignore_id)",
"отправлять сообщение самому себе?!') if await get_or_none(Ignore, ignored=sender_id, ignored_by=uid): return await msg.answer('Вы находитесь",
"uid = await msg.vk.resolve_name(ignore_id) else: uid = int(ignore_id) if not uid: return await",
"обнаружены ссылки!') message = \"Вам анонимное сообщение!\\n\" if data: message += data +",
"import * from plugin_system import Plugin plugin = Plugin(\"Отправка сообщения\", usage=[\"напиши [id] [сообщение]",
"await msg.answer('В сообщении были обнаружены ссылки!') message = \"Вам анонимное сообщение!\\n\" if data:",
"from plugin_system import Plugin plugin = Plugin(\"Отправка сообщения\", usage=[\"напиши [id] [сообщение] - написать",
"попросил его не беспокоить!') data = ' '.join(args) if check_links(data): return await msg.answer('В",
"- написать сообщение пользователю\", \"анонимно [id] [сообщение] - написать анонимное сообщение пользователю\" \"(посылать",
"msg.answer('Вы не существуете!\\n(или у бота проблемы с базой данных)') user.do_not_disturb = False await",
"user = await get_or_none(User, uid=msg.user_id) if not user: return await msg.answer('Вы не существуете!\\n(или",
"самому себе?!') if await get_or_none(Ignore, ignored=sender_id, ignored_by=uid): return await msg.answer('Вы находитесь в чёрном",
"'письмо') async def write_msg(msg, args): if (len(args) != 1 or not msg.brief_attaches) and",
"@plugin.on_command('написать', 'напиши', 'лс', 'письмо') async def write_msg(msg, args): if (len(args) != 1 or",
"ignore_id = args.pop() if not ignore_id.isdigit(): uid = await msg.vk.resolve_name(ignore_id) else: uid =",
"{sender_data['first_name']} {sender_data['last_name']}!\\n\\\"{data}\\\"\", } if \"attach1\" in msg.brief_attaches: val['attachment'] = \",\".join(str(x) for x in",
"пользователь попросил его не беспокоить!') data = ' '.join(args) if check_links(data): return await",
"Plugin(\"Отправка сообщения\", usage=[\"напиши [id] [сообщение] - написать сообщение пользователю\", \"анонимно [id] [сообщение] -",
"await msg.answer('В сообщении были обнаружены ссылки!') sender_data = await msg.vk.method('users.get', {'user_ids': msg.user_id, 'name_case':",
"'com', 'www', 'ftp', '://') def check_links(string): return any(x in string for x in",
"'ftp', '://') def check_links(string): return any(x in string for x in DISABLED) @plugin.on_init()",
"msg.answer('Этот пользователь попросил его не беспокоить!') data = ' '.join(args) if check_links(data): return",
"m in full) val = { 'peer_id': uid, 'message': message } result =",
"def do_disturb(msg, args): user = await get_or_none(User, uid=msg.user_id) if not user: return await",
"args): if (len(args) != 1 or not msg.brief_attaches) and len(args) < 2: return",
"== uid) & (Ignore.ignored_by == sender_id) )) await msg.answer(f'Теперь {unignore_id} сможет отправлять вам",
"await msg.vk.method('users.get', {'user_ids': msg.user_id, 'name_case': \"gen\"}) sender_data = sender_data[0] val = { 'peer_id':",
"'name_case': \"gen\"}) sender_data = sender_data[0] val = { 'peer_id': role.user_id, 'message': f\"Вам сообщение",
"= ' '.join(args) if check_links(data): return await msg.answer('В сообщении были обнаружены ссылки!') sender_data",
"@plugin.on_command('беспокоить') async def do_disturb(msg, args): user = await get_or_none(User, uid=msg.user_id) if not user:",
"не существуете!\\n(или у бота проблемы с базой данных)') user.do_not_disturb = False await db.update(user)",
"= await msg.vk.resolve_name(unignore_id) else: uid = int(unignore_id) if not uid: return await msg.answer('Проверьте",
"k and v == \"photo\": text_required = False break if len(args) < 2",
"(len(args) != 1 or not msg.brief_attaches) and len(args) < 2: return await msg.answer('Введите",
"uid: return await msg.answer('Проверьте правильность введёного ID пользователя.') await db.create_or_get(Ignore, ignored=uid, ignored_by=sender_id) await",
"v in msg.brief_attaches.items(): if '_type' in k and v == \"photo\": text_required =",
"def show(msg, unignore): if len(unignore) < 1: return await msg.answer('Введите ID пользователя, которого",
"user = await get_or_none(User, uid=uid) if user and user.do_not_disturb: return await msg.answer('Этот пользователь",
"sender_id == uid: return await msg.answer('Зачем мне отправлять сообщение вам?!') if await get_or_none(Ignore,",
"2 and text_required: return await msg.answer('Введите ID пользователя и сообщение для него.') sender_id",
"if not ignore_id.isdigit(): uid = await msg.vk.resolve_name(ignore_id) else: uid = int(ignore_id) if not",
"отправлено!') @plugin.on_command('скрыть') async def hide(msg, args): if len(args) < 1: return await msg.answer('Введите",
"@plugin.on_command('не беспокоить') async def do_not_disturb(msg, args): user = await get_or_none(User, uid=msg.user_id) if not",
"сообщения!') @plugin.on_command('не беспокоить') async def do_not_disturb(msg, args): user = await get_or_none(User, uid=msg.user_id) if",
"result: return await msg.answer('Сообщение не удалось отправить!') await msg.answer('Сообщение успешно отправлено!') @plugin.on_command('админу') async",
"ignored=sender_id, ignored_by=uid): return await msg.answer('Вы находитесь в чёрном списке у этого пользователя!') user",
"full = await msg.full_attaches if full: message += \"Вложения:\\n\".join(m.link for m in full)",
"len(unignore) < 1: return await msg.answer('Введите ID пользователя, которого вы хотите убрать из",
"plugin_system import Plugin plugin = Plugin(\"Отправка сообщения\", usage=[\"напиши [id] [сообщение] - написать сообщение",
"data: message += data + \"\\n\" if not text_required: full = await msg.full_attaches",
"'.join(args) if check_links(data): return await msg.answer('В сообщении были обнаружены ссылки!') message = \"Вам",
"args): user = await get_or_none(User, uid=msg.user_id) if not user: return await msg.answer('Вы не",
"'message': f\"Вам сообщение от {sender_data['first_name']} {sender_data['last_name']}!\\n\\\"{data}\\\"\", } if \"attach1\" in msg.brief_attaches: val['attachment'] =",
"await get_or_none(Ignore, ignored=sender_id, ignored_by=role.user_id): return await msg.answer('Вы находитесь в чёрном списке у этого",
"msg.answer('Зачем мне отправлять сообщение вам?!') if await get_or_none(Ignore, ignored=sender_id, ignored_by=uid): return await msg.answer('Вы",
"any(x in string for x in DISABLED) @plugin.on_init() def init(vk): pass @plugin.on_command('анонимка', 'анонимно')",
"True for k, v in msg.brief_attaches.items(): if '_type' in k and v ==",
"msg.vk.method('users.get', {'user_ids': msg.user_id, 'name_case': \"gen\"}) sender_data = sender_data[0] val = { 'peer_id': role.user_id,",
"msg.answer('Сообщение успешно отправлено!') @plugin.on_command('скрыть') async def hide(msg, args): if len(args) < 1: return",
"' '.join(args) if check_links(data): return await msg.answer('В сообщении были обнаружены ссылки!') message =",
"db.execute(Role.select().where(Role.role == \"admin\")): if await get_or_none(Ignore, ignored=sender_id, ignored_by=role.user_id): return await msg.answer('Вы находитесь в",
"сообщения!') @plugin.on_command('беспокоить') async def do_disturb(msg, args): user = await get_or_none(User, uid=msg.user_id) if not",
"msg.answer('Проверьте правильность введёного ID пользователя.') await db.create_or_get(Ignore, ignored=uid, ignored_by=sender_id) await msg.answer(f'Вы не будете",
"{ 'peer_id': uid, 'message': f\"Вам сообщение от {sender_data['first_name']} {sender_data['last_name']}!\\n\\\"{data}\\\"\", } if \"attach1\" in",
"пользователя.') if sender_id == uid: return await msg.answer('Зачем мне отправлять сообщение вам?!') if",
"sender_data[0] val = { 'peer_id': role.user_id, 'message': f\"Вам сообщение от {sender_data['first_name']} {sender_data['last_name']}!\\n\\\"{data}\\\"\", }",
"сообщении были обнаружены ссылки!') message = \"Вам анонимное сообщение!\\n\" if data: message +=",
"uid = int(unignore_id) if not uid: return await msg.answer('Проверьте правильность введёного ID пользователя.')",
"not uid: return await msg.answer('Проверьте правильность введёного ID пользователя.') await db.execute(Ignore.delete().where( (Ignore.ignored ==",
"uid: return await msg.answer('Зачем мне отправлять сообщение самому себе?!') if await get_or_none(Ignore, ignored=sender_id,",
"await msg.answer('Сообщение не удалось отправить!') await msg.answer('Сообщение успешно отправлено!') @plugin.on_command('скрыть') async def hide(msg,",
"if user and user.do_not_disturb: return await msg.answer('Этот пользователь попросил его не беспокоить!') data",
"sender_id = msg.user_id possible_id = args.pop(0) if not possible_id.isdigit(): uid = await msg.vk.resolve_name(possible_id)",
"val = { 'peer_id': uid, 'message': message } result = await msg.vk.method('messages.send', val)",
"получать сообщения от {ignore_id}!') @plugin.on_command('показать') async def show(msg, unignore): if len(unignore) < 1:",
"msg.answer(f'Теперь {unignore_id} сможет отправлять вам сообщения!') @plugin.on_command('не беспокоить') async def do_not_disturb(msg, args): user",
"text_required: return await msg.answer('Введите ID пользователя и сообщение для него.') sender_id = msg.user_id",
"= sender_data[0] val = { 'peer_id': role.user_id, 'message': f\"Вам сообщение от {sender_data['first_name']} {sender_data['last_name']}!\\n\\\"{data}\\\"\",",
"if len(args) < 2 and text_required: return await msg.answer('Введите ID пользователя и сообщение",
"message += \"Вложения:\\n\".join(m.link for m in full) val = { 'peer_id': uid, 'message':",
"uid, 'message': f\"Вам сообщение от {sender_data['first_name']} {sender_data['last_name']}!\\n\\\"{data}\\\"\", } if \"attach1\" in msg.brief_attaches: val['attachment']",
"'peer_id': uid, 'message': message } result = await msg.vk.method('messages.send', val) if not result:",
"return await msg.answer('Сообщение не удалось отправить!') await msg.answer('Сообщение успешно отправлено!') @plugin.on_command('написать', 'напиши', 'лс',",
"msg.brief_attaches: val['attachment'] = \",\".join(str(x) for x in await msg.full_attaches) result = await msg.vk.method('messages.send',",
"x in await msg.full_attaches) result = await msg.vk.method('messages.send', val) if not result: return",
"await msg.answer('Зачем мне отправлять сообщение самому себе?!') if await get_or_none(Ignore, ignored=sender_id, ignored_by=uid): return",
"(Ignore.ignored == uid) & (Ignore.ignored_by == sender_id) )) await msg.answer(f'Теперь {unignore_id} сможет отправлять",
"check_links(data): return await msg.answer('В сообщении были обнаружены ссылки!') sender_data = await msg.vk.method('users.get', {'user_ids':",
"await msg.answer('Сообщение успешно отправлено!') @plugin.on_command('скрыть') async def hide(msg, args): if len(args) < 1:",
"len(args) < 1: return await msg.answer('Введите ID пользователя для игнорирования.') sender_id = msg.user_id",
"not user: return await msg.answer('Вы не существуете!\\n(или у бота проблемы с базой данных)')",
"not ignore_id.isdigit(): uid = await msg.vk.resolve_name(ignore_id) else: uid = int(ignore_id) if not uid:",
"== sender_id) )) await msg.answer(f'Теперь {unignore_id} сможет отправлять вам сообщения!') @plugin.on_command('не беспокоить') async",
"val = { 'peer_id': role.user_id, 'message': f\"Вам сообщение от {sender_data['first_name']} {sender_data['last_name']}!\\n\\\"{data}\\\"\", } if",
"await msg.vk.resolve_name(unignore_id) else: uid = int(unignore_id) if not uid: return await msg.answer('Проверьте правильность",
"if not possible_id.isdigit(): uid = await msg.vk.resolve_name(possible_id) else: uid = int(possible_id) if not",
"for role in await db.execute(Role.select().where(Role.role == \"admin\")): if await get_or_none(Ignore, ignored=sender_id, ignored_by=role.user_id): return",
"if sender_id == uid: return await msg.answer('Зачем мне отправлять сообщение самому себе?!') if",
"await msg.answer('Проверьте правильность введёного ID пользователя.') await db.create_or_get(Ignore, ignored=uid, ignored_by=sender_id) await msg.answer(f'Вы не",
"def check_links(string): return any(x in string for x in DISABLED) @plugin.on_init() def init(vk):",
"await db.create_or_get(Ignore, ignored=uid, ignored_by=sender_id) await msg.answer(f'Вы не будете получать сообщения от {ignore_id}!') @plugin.on_command('показать')",
"await msg.full_attaches) result = await msg.vk.method('messages.send', val) if not result: return await msg.answer('Сообщение",
"do_not_disturb(msg, args): user = await get_or_none(User, uid=msg.user_id) if not user: return await msg.answer('Вы",
"сообщение самому себе?!') if await get_or_none(Ignore, ignored=sender_id, ignored_by=uid): return await msg.answer('Вы находитесь в",
"msg.vk.method('users.get', {'user_ids': msg.user_id, 'name_case': \"gen\"}) sender_data = sender_data[0] val = { 'peer_id': uid,",
"сообщения\", usage=[\"напиши [id] [сообщение] - написать сообщение пользователю\", \"анонимно [id] [сообщение] - написать",
"пользователя для игнорирования.') sender_id = msg.user_id ignore_id = args.pop() if not ignore_id.isdigit(): uid",
"бота проблемы с базой данных)') user.do_not_disturb = False await db.update(user) await msg.answer('Вы будете",
"ID пользователя.') await db.create_or_get(Ignore, ignored=uid, ignored_by=sender_id) await msg.answer(f'Вы не будете получать сообщения от",
"await msg.vk.resolve_name(possible_id) else: uid = int(possible_id) if not uid: return await msg.answer('Проверьте правильность",
"await msg.answer('Сообщение успешно отправлено!') @plugin.on_command('написать', 'напиши', 'лс', 'письмо') async def write_msg(msg, args): if",
"msg.user_id, 'name_case': \"gen\"}) sender_data = sender_data[0] val = { 'peer_id': role.user_id, 'message': f\"Вам",
"return await msg.answer('Зачем мне отправлять сообщение вам?!') if await get_or_none(Ignore, ignored=sender_id, ignored_by=uid): return",
"\"анонимно [id] [сообщение] - написать анонимное сообщение пользователю\" \"(посылать можно только текст и/или",
"sender_id == uid: return await msg.answer('Зачем мне отправлять сообщение самому себе?!') if await",
"хотите убрать из игнора.') sender_id = msg.user_id unignore_id = unignore.pop() if not unignore_id.isdigit():",
"user and user.do_not_disturb: return await msg.answer('Этот пользователь попросил его не беспокоить!') data =",
"правильность введёного ID пользователя.') await db.execute(Ignore.delete().where( (Ignore.ignored == uid) & (Ignore.ignored_by == sender_id)",
"анонимное сообщение!\\n\" if data: message += data + \"\\n\" if not text_required: full",
"= ('https', 'http', 'com', 'www', 'ftp', '://') def check_links(string): return any(x in string",
"\"gen\"}) sender_data = sender_data[0] val = { 'peer_id': uid, 'message': f\"Вам сообщение от",
"сообщения\"], need_db=True) DISABLED = ('https', 'http', 'com', 'www', 'ftp', '://') def check_links(string): return",
"с базой данных)') user.do_not_disturb = True await db.update(user) await msg.answer('Вы не будете получать",
"вы хотите убрать из игнора.') sender_id = msg.user_id unignore_id = unignore.pop() if not",
"await db.execute(Role.select().where(Role.role == \"admin\")): if await get_or_none(Ignore, ignored=sender_id, ignored_by=role.user_id): return await msg.answer('Вы находитесь",
"удалось отправить!') await msg.answer('Сообщение успешно отправлено!') @plugin.on_command('админу') async def to_admin(msg, args): sender_id =",
"check_links(string): return any(x in string for x in DISABLED) @plugin.on_init() def init(vk): pass",
"ID пользователя.') if sender_id == uid: return await msg.answer('Зачем мне отправлять сообщение самому",
"\"беспокоить - получать сообщения\"], need_db=True) DISABLED = ('https', 'http', 'com', 'www', 'ftp', '://')",
"else: uid = int(ignore_id) if not uid: return await msg.answer('Проверьте правильность введёного ID",
"int(unignore_id) if not uid: return await msg.answer('Проверьте правильность введёного ID пользователя.') await db.execute(Ignore.delete().where(",
"< 1: return await msg.answer('Введите ID пользователя для игнорирования.') sender_id = msg.user_id ignore_id",
"in msg.brief_attaches: val['attachment'] = \",\".join(str(x) for x in await msg.full_attaches) result = await",
"(Ignore.ignored_by == sender_id) )) await msg.answer(f'Теперь {unignore_id} сможет отправлять вам сообщения!') @plugin.on_command('не беспокоить')",
"if (len(args) != 1 or not msg.brief_attaches) and len(args) < 2: return await",
"return await msg.answer('Введите ID пользователя, которого вы хотите убрать из игнора.') sender_id =",
"get_or_none(User, uid=msg.user_id) if not user: return await msg.answer('Вы не существуете!\\n(или у бота проблемы",
"msg.answer('Введите ID пользователя для игнорирования.') sender_id = msg.user_id ignore_id = args.pop() if not",
"не удалось отправить!') await msg.answer('Сообщение успешно отправлено!') @plugin.on_command('написать', 'напиши', 'лс', 'письмо') async def",
"get_or_none(User, uid=uid) if user and user.do_not_disturb: return await msg.answer('Этот пользователь попросил его не",
"ID пользователя.') await db.execute(Ignore.delete().where( (Ignore.ignored == uid) & (Ignore.ignored_by == sender_id) )) await",
"await get_or_none(User, uid=role.user_id) if user and user.do_not_disturb: return await msg.answer('Этот пользователь попросил его",
"обнаружены ссылки!') sender_data = await msg.vk.method('users.get', {'user_ids': msg.user_id, 'name_case': \"gen\"}) sender_data = sender_data[0]",
"беспокоить') async def do_not_disturb(msg, args): user = await get_or_none(User, uid=msg.user_id) if not user:",
"if '_type' in k and v == \"photo\": text_required = False break if",
"sender_id = msg.user_id for role in await db.execute(Role.select().where(Role.role == \"admin\")): if await get_or_none(Ignore,",
"for k, v in msg.brief_attaches.items(): if '_type' in k and v == \"photo\":",
"not result: return await msg.answer('Сообщение не удалось отправить!') await msg.answer('Сообщение успешно отправлено!') @plugin.on_command('админу')",
"чёрном списке у этого пользователя!') user = await get_or_none(User, uid=uid) if user and",
"не удалось отправить!') await msg.answer('Сообщение успешно отправлено!') @plugin.on_command('скрыть') async def hide(msg, args): if",
"= msg.user_id ignore_id = args.pop() if not ignore_id.isdigit(): uid = await msg.vk.resolve_name(ignore_id) else:",
"1: return await msg.answer('Введите ID пользователя, которого вы хотите убрать из игнора.') sender_id",
"' '.join(args) if check_links(data): return await msg.answer('В сообщении были обнаружены ссылки!') sender_data =",
"пользователя.') if sender_id == uid: return await msg.answer('Зачем мне отправлять сообщение самому себе?!')",
"мне отправлять сообщение вам?!') if await get_or_none(Ignore, ignored=sender_id, ignored_by=uid): return await msg.answer('Вы находитесь",
"await get_or_none(User, uid=msg.user_id) if not user: return await msg.answer('Вы не существуете!\\n(или у бота",
"if full: message += \"Вложения:\\n\".join(m.link for m in full) val = { 'peer_id':",
"получать сообщения\", \"беспокоить - получать сообщения\"], need_db=True) DISABLED = ('https', 'http', 'com', 'www',",
"\"gen\"}) sender_data = sender_data[0] val = { 'peer_id': role.user_id, 'message': f\"Вам сообщение от",
"and v == \"photo\": text_required = False break if len(args) < 2 and",
"можно только текст и/или фото)\", \"не беспокоить - не получать сообщения\", \"беспокоить -",
"[сообщение] - написать сообщение пользователю\", \"анонимно [id] [сообщение] - написать анонимное сообщение пользователю\"",
"у этого пользователя!') user = await get_or_none(User, uid=role.user_id) if user and user.do_not_disturb: return",
"'.join(args) if check_links(data): return await msg.answer('В сообщении были обнаружены ссылки!') sender_data = await",
"отправлено!') @plugin.on_command('написать', 'напиши', 'лс', 'письмо') async def write_msg(msg, args): if (len(args) != 1",
"sender_id) )) await msg.answer(f'Теперь {unignore_id} сможет отправлять вам сообщения!') @plugin.on_command('не беспокоить') async def",
"await msg.answer(f'Вы не будете получать сообщения от {ignore_id}!') @plugin.on_command('показать') async def show(msg, unignore):",
"ID пользователя.') if sender_id == uid: return await msg.answer('Зачем мне отправлять сообщение вам?!')",
"db.execute(Ignore.delete().where( (Ignore.ignored == uid) & (Ignore.ignored_by == sender_id) )) await msg.answer(f'Теперь {unignore_id} сможет",
"uid) & (Ignore.ignored_by == sender_id) )) await msg.answer(f'Теперь {unignore_id} сможет отправлять вам сообщения!')",
"in DISABLED) @plugin.on_init() def init(vk): pass @plugin.on_command('анонимка', 'анонимно') async def anonymously(msg, args): text_required",
"def init(vk): pass @plugin.on_command('анонимка', 'анонимно') async def anonymously(msg, args): text_required = True for",
"await msg.answer('Сообщение успешно отправлено!') @plugin.on_command('админу') async def to_admin(msg, args): sender_id = msg.user_id for",
"были обнаружены ссылки!') sender_data = await msg.vk.method('users.get', {'user_ids': msg.user_id, 'name_case': \"gen\"}) sender_data =",
"text_required = True for k, v in msg.brief_attaches.items(): if '_type' in k and",
"args): if len(args) < 1: return await msg.answer('Введите ID пользователя для игнорирования.') sender_id",
"sender_data[0] val = { 'peer_id': uid, 'message': f\"Вам сообщение от {sender_data['first_name']} {sender_data['last_name']}!\\n\\\"{data}\\\"\", }",
"удалось отправить!') await msg.answer('Сообщение успешно отправлено!') @plugin.on_command('скрыть') async def hide(msg, args): if len(args)",
"из игнора.') sender_id = msg.user_id unignore_id = unignore.pop() if not unignore_id.isdigit(): uid =",
"бота проблемы с базой данных)') user.do_not_disturb = True await db.update(user) await msg.answer('Вы не",
"await msg.vk.resolve_name(ignore_id) else: uid = int(ignore_id) if not uid: return await msg.answer('Проверьте правильность",
"return await msg.answer('Введите ID пользователя и сообщение для него.') sender_id = msg.user_id possible_id",
"if \"attach1\" in msg.brief_attaches: val['attachment'] = \",\".join(str(x) for x in await msg.full_attaches) result",
"находитесь в чёрном списке у этого пользователя!') user = await get_or_none(User, uid=uid) if",
"msg.answer('В сообщении были обнаружены ссылки!') sender_data = await msg.vk.method('users.get', {'user_ids': msg.user_id, 'name_case': \"gen\"})",
"пользователя.') await db.create_or_get(Ignore, ignored=uid, ignored_by=sender_id) await msg.answer(f'Вы не будете получать сообщения от {ignore_id}!')",
"not possible_id.isdigit(): uid = await msg.vk.resolve_name(possible_id) else: uid = int(possible_id) if not uid:",
"in await msg.full_attaches) result = await msg.vk.method('messages.send', val) if not result: return await",
"hide(msg, args): if len(args) < 1: return await msg.answer('Введите ID пользователя для игнорирования.')",
"будете получать сообщения!') @plugin.on_command('беспокоить') async def do_disturb(msg, args): user = await get_or_none(User, uid=msg.user_id)",
"msg.answer('Сообщение не удалось отправить!') await msg.answer('Сообщение успешно отправлено!') @plugin.on_command('скрыть') async def hide(msg, args):",
"msg.vk.method('messages.send', val) if not result: return await msg.answer('Сообщение не удалось отправить!') await msg.answer('Сообщение",
"не удалось отправить!') await msg.answer('Сообщение успешно отправлено!') @plugin.on_command('админу') async def to_admin(msg, args): sender_id",
"DISABLED) @plugin.on_init() def init(vk): pass @plugin.on_command('анонимка', 'анонимно') async def anonymously(msg, args): text_required =",
"int(ignore_id) if not uid: return await msg.answer('Проверьте правильность введёного ID пользователя.') await db.create_or_get(Ignore,",
"msg.user_id unignore_id = unignore.pop() if not unignore_id.isdigit(): uid = await msg.vk.resolve_name(unignore_id) else: uid",
"await msg.answer('Введите ID пользователя и сообщение для него.') sender_id = msg.user_id possible_id =",
"сообщении были обнаружены ссылки!') sender_data = await msg.vk.method('users.get', {'user_ids': msg.user_id, 'name_case': \"gen\"}) sender_data",
"= await msg.vk.resolve_name(ignore_id) else: uid = int(ignore_id) if not uid: return await msg.answer('Проверьте",
"- написать анонимное сообщение пользователю\" \"(посылать можно только текст и/или фото)\", \"не беспокоить",
"for x in DISABLED) @plugin.on_init() def init(vk): pass @plugin.on_command('анонимка', 'анонимно') async def anonymously(msg,",
"= await msg.vk.resolve_name(possible_id) else: uid = int(possible_id) if not uid: return await msg.answer('Проверьте",
"фото)\", \"не беспокоить - не получать сообщения\", \"беспокоить - получать сообщения\"], need_db=True) DISABLED",
"\"photo\": text_required = False break if len(args) < 2 and text_required: return await",
"write_msg(msg, args): if (len(args) != 1 or not msg.brief_attaches) and len(args) < 2:",
"if not uid: return await msg.answer('Проверьте правильность введёного ID пользователя.') await db.create_or_get(Ignore, ignored=uid,",
"} if \"attach1\" in msg.brief_attaches: val['attachment'] = \",\".join(str(x) for x in await msg.full_attaches)",
"if not user: return await msg.answer('Вы не существуете!\\n(или у бота проблемы с базой",
"+= \"Вложения:\\n\".join(m.link for m in full) val = { 'peer_id': uid, 'message': message",
"await db.update(user) await msg.answer('Вы не будете получать сообщения!') @plugin.on_command('беспокоить') async def do_disturb(msg, args):",
"= \",\".join(str(x) for x in await msg.full_attaches) result = await msg.vk.method('messages.send', val) if",
"in full) val = { 'peer_id': uid, 'message': message } result = await",
"user = await get_or_none(User, uid=role.user_id) if user and user.do_not_disturb: return await msg.answer('Этот пользователь",
"отправлять вам сообщения!') @plugin.on_command('не беспокоить') async def do_not_disturb(msg, args): user = await get_or_none(User,",
"= await get_or_none(User, uid=uid) if user and user.do_not_disturb: return await msg.answer('Этот пользователь попросил",
"get_or_none(Ignore, ignored=sender_id, ignored_by=role.user_id): return await msg.answer('Вы находитесь в чёрном списке у этого пользователя!')",
"async def hide(msg, args): if len(args) < 1: return await msg.answer('Введите ID пользователя",
"sender_id = msg.user_id ignore_id = args.pop() if not ignore_id.isdigit(): uid = await msg.vk.resolve_name(ignore_id)",
"введёного ID пользователя.') await db.execute(Ignore.delete().where( (Ignore.ignored == uid) & (Ignore.ignored_by == sender_id) ))",
"получать сообщения!') @plugin.on_command('беспокоить') async def do_disturb(msg, args): user = await get_or_none(User, uid=msg.user_id) if",
"- не получать сообщения\", \"беспокоить - получать сообщения\"], need_db=True) DISABLED = ('https', 'http',",
"unignore_id.isdigit(): uid = await msg.vk.resolve_name(unignore_id) else: uid = int(unignore_id) if not uid: return",
"async def do_disturb(msg, args): user = await get_or_none(User, uid=msg.user_id) if not user: return",
"uid: return await msg.answer('Проверьте правильность введёного ID пользователя.') if sender_id == uid: return",
"отправлять сообщение вам?!') if await get_or_none(Ignore, ignored=sender_id, ignored_by=uid): return await msg.answer('Вы находитесь в",
"unignore_id = unignore.pop() if not unignore_id.isdigit(): uid = await msg.vk.resolve_name(unignore_id) else: uid =",
"= \"Вам анонимное сообщение!\\n\" if data: message += data + \"\\n\" if not",
"args): text_required = True for k, v in msg.brief_attaches.items(): if '_type' in k",
"msg.brief_attaches.items(): if '_type' in k and v == \"photo\": text_required = False break",
"user: return await msg.answer('Вы не существуете!\\n(или у бота проблемы с базой данных)') user.do_not_disturb",
"await msg.answer('Введите ID пользователя, которого вы хотите убрать из игнора.') sender_id = msg.user_id",
"if not result: return await msg.answer('Сообщение не удалось отправить!') await msg.answer('Сообщение успешно отправлено!')",
"= False break if len(args) < 2 and text_required: return await msg.answer('Введите ID",
"с базой данных)') user.do_not_disturb = False await db.update(user) await msg.answer('Вы будете получать все",
"return await msg.answer('Проверьте правильность введёного ID пользователя.') await db.create_or_get(Ignore, ignored=uid, ignored_by=sender_id) await msg.answer(f'Вы",
"[сообщение] - написать анонимное сообщение пользователю\" \"(посылать можно только текст и/или фото)\", \"не",
"в чёрном списке у этого пользователя!') user = await get_or_none(User, uid=role.user_id) if user",
"и сообщение для него.') sender_id = msg.user_id possible_id = args.pop(0) if not possible_id.isdigit():",
"списке у этого пользователя!') user = await get_or_none(User, uid=uid) if user and user.do_not_disturb:",
"plugin = Plugin(\"Отправка сообщения\", usage=[\"напиши [id] [сообщение] - написать сообщение пользователю\", \"анонимно [id]",
"result = await msg.vk.method('messages.send', val) if not result: return await msg.answer('Сообщение не удалось",
"return await msg.answer('Проверьте правильность введёного ID пользователя.') await db.execute(Ignore.delete().where( (Ignore.ignored == uid) &",
"[id] [сообщение] - написать анонимное сообщение пользователю\" \"(посылать можно только текст и/или фото)\",",
"in msg.brief_attaches.items(): if '_type' in k and v == \"photo\": text_required = False",
"await msg.full_attaches if full: message += \"Вложения:\\n\".join(m.link for m in full) val =",
"< 2: return await msg.answer('Введите ID пользователя и сообщение для него.') sender_id =",
"msg.answer('Вы не существуете!\\n(или у бота проблемы с базой данных)') user.do_not_disturb = True await",
"= ' '.join(args) if check_links(data): return await msg.answer('В сообщении были обнаружены ссылки!') message",
"отправить!') await msg.answer('Сообщение успешно отправлено!') @plugin.on_command('скрыть') async def hide(msg, args): if len(args) <",
"await msg.answer('Проверьте правильность введёного ID пользователя.') await db.execute(Ignore.delete().where( (Ignore.ignored == uid) & (Ignore.ignored_by",
"if not uid: return await msg.answer('Проверьте правильность введёного ID пользователя.') if sender_id ==",
"Plugin plugin = Plugin(\"Отправка сообщения\", usage=[\"напиши [id] [сообщение] - написать сообщение пользователю\", \"анонимно",
"msg.brief_attaches) and len(args) < 2: return await msg.answer('Введите ID пользователя и сообщение для",
"\"(посылать можно только текст и/или фото)\", \"не беспокоить - не получать сообщения\", \"беспокоить",
"and len(args) < 2: return await msg.answer('Введите ID пользователя и сообщение для него.')",
"пользователя и сообщение для него.') sender_id = msg.user_id possible_id = args.pop(0) if not",
"get_or_none(Ignore, ignored=sender_id, ignored_by=uid): return await msg.answer('Вы находитесь в чёрном списке у этого пользователя!')",
"return await msg.answer('Введите ID пользователя для игнорирования.') sender_id = msg.user_id ignore_id = args.pop()",
"await msg.answer('Вы не существуете!\\n(или у бота проблемы с базой данных)') user.do_not_disturb = True",
"def write_msg(msg, args): if (len(args) != 1 or not msg.brief_attaches) and len(args) <",
"{ 'peer_id': uid, 'message': message } result = await msg.vk.method('messages.send', val) if not",
"у этого пользователя!') user = await get_or_none(User, uid=uid) if user and user.do_not_disturb: return",
"\"Вложения:\\n\".join(m.link for m in full) val = { 'peer_id': uid, 'message': message }",
"текст и/или фото)\", \"не беспокоить - не получать сообщения\", \"беспокоить - получать сообщения\"],",
"async def anonymously(msg, args): text_required = True for k, v in msg.brief_attaches.items(): if",
"uid: return await msg.answer('Проверьте правильность введёного ID пользователя.') await db.execute(Ignore.delete().where( (Ignore.ignored == uid)",
"for x in await msg.full_attaches) result = await msg.vk.method('messages.send', val) if not result:",
"ID пользователя, которого вы хотите убрать из игнора.') sender_id = msg.user_id unignore_id =",
"len(args) < 2 and text_required: return await msg.answer('Введите ID пользователя и сообщение для",
"успешно отправлено!') @plugin.on_command('админу') async def to_admin(msg, args): sender_id = msg.user_id for role in",
"get_or_none(User, uid=role.user_id) if user and user.do_not_disturb: return await msg.answer('Этот пользователь попросил его не",
"себе?!') if await get_or_none(Ignore, ignored=sender_id, ignored_by=uid): return await msg.answer('Вы находитесь в чёрном списке",
")) await msg.answer(f'Теперь {unignore_id} сможет отправлять вам сообщения!') @plugin.on_command('не беспокоить') async def do_not_disturb(msg,",
"else: uid = int(possible_id) if not uid: return await msg.answer('Проверьте правильность введёного ID",
"from database import * from plugin_system import Plugin plugin = Plugin(\"Отправка сообщения\", usage=[\"напиши",
"await msg.answer('Сообщение не удалось отправить!') await msg.answer('Сообщение успешно отправлено!') @plugin.on_command('написать', 'напиши', 'лс', 'письмо')",
"= await get_or_none(User, uid=role.user_id) if user and user.do_not_disturb: return await msg.answer('Этот пользователь попросил",
"else: uid = int(unignore_id) if not uid: return await msg.answer('Проверьте правильность введёного ID",
"in string for x in DISABLED) @plugin.on_init() def init(vk): pass @plugin.on_command('анонимка', 'анонимно') async",
"sender_id = msg.user_id unignore_id = unignore.pop() if not unignore_id.isdigit(): uid = await msg.vk.resolve_name(unignore_id)",
"= int(unignore_id) if not uid: return await msg.answer('Проверьте правильность введёного ID пользователя.') await",
"у бота проблемы с базой данных)') user.do_not_disturb = False await db.update(user) await msg.answer('Вы",
"msg.answer('Зачем мне отправлять сообщение самому себе?!') if await get_or_none(Ignore, ignored=sender_id, ignored_by=uid): return await",
"== uid: return await msg.answer('Зачем мне отправлять сообщение самому себе?!') if await get_or_none(Ignore,",
"== \"photo\": text_required = False break if len(args) < 2 and text_required: return",
"msg.vk.resolve_name(possible_id) else: uid = int(possible_id) if not uid: return await msg.answer('Проверьте правильность введёного",
"return await msg.answer('В сообщении были обнаружены ссылки!') sender_data = await msg.vk.method('users.get', {'user_ids': msg.user_id,",
"return await msg.answer('Вы не существуете!\\n(или у бота проблемы с базой данных)') user.do_not_disturb =",
"игнора.') sender_id = msg.user_id unignore_id = unignore.pop() if not unignore_id.isdigit(): uid = await",
"('https', 'http', 'com', 'www', 'ftp', '://') def check_links(string): return any(x in string for",
"написать анонимное сообщение пользователю\" \"(посылать можно только текст и/или фото)\", \"не беспокоить -",
"написать сообщение пользователю\", \"анонимно [id] [сообщение] - написать анонимное сообщение пользователю\" \"(посылать можно",
"if await get_or_none(Ignore, ignored=sender_id, ignored_by=uid): return await msg.answer('Вы находитесь в чёрном списке у",
"msg.answer('Введите ID пользователя, которого вы хотите убрать из игнора.') sender_id = msg.user_id unignore_id",
"async def write_msg(msg, args): if (len(args) != 1 or not msg.brief_attaches) and len(args)",
"and user.do_not_disturb: return await msg.answer('Этот пользователь попросил его не беспокоить!') data = '",
"await msg.answer('Вы не существуете!\\n(или у бота проблемы с базой данных)') user.do_not_disturb = False",
"database import * from plugin_system import Plugin plugin = Plugin(\"Отправка сообщения\", usage=[\"напиши [id]",
"+= data + \"\\n\" if not text_required: full = await msg.full_attaches if full:",
"result: return await msg.answer('Сообщение не удалось отправить!') await msg.answer('Сообщение успешно отправлено!') @plugin.on_command('написать', 'напиши',",
"msg.full_attaches) result = await msg.vk.method('messages.send', val) if not result: return await msg.answer('Сообщение не",
"= msg.user_id for role in await db.execute(Role.select().where(Role.role == \"admin\")): if await get_or_none(Ignore, ignored=sender_id,",
"for m in full) val = { 'peer_id': uid, 'message': message } result",
"msg.answer(f'Вы не будете получать сообщения от {ignore_id}!') @plugin.on_command('показать') async def show(msg, unignore): if",
"len(args) < 2: return await msg.answer('Введите ID пользователя и сообщение для него.') sender_id",
"int(possible_id) if not uid: return await msg.answer('Проверьте правильность введёного ID пользователя.') if sender_id",
"uid = int(ignore_id) if not uid: return await msg.answer('Проверьте правильность введёного ID пользователя.')",
"= await msg.full_attaches if full: message += \"Вложения:\\n\".join(m.link for m in full) val",
"if data: message += data + \"\\n\" if not text_required: full = await",
"1 or not msg.brief_attaches) and len(args) < 2: return await msg.answer('Введите ID пользователя",
"этого пользователя!') user = await get_or_none(User, uid=uid) if user and user.do_not_disturb: return await",
"= msg.user_id unignore_id = unignore.pop() if not unignore_id.isdigit(): uid = await msg.vk.resolve_name(unignore_id) else:",
"not result: return await msg.answer('Сообщение не удалось отправить!') await msg.answer('Сообщение успешно отправлено!') @plugin.on_command('написать',",
"await msg.answer(f'Теперь {unignore_id} сможет отправлять вам сообщения!') @plugin.on_command('не беспокоить') async def do_not_disturb(msg, args):",
"ID пользователя и сообщение для него.') sender_id = msg.user_id possible_id = args.pop(0) if",
"message = \"Вам анонимное сообщение!\\n\" if data: message += data + \"\\n\" if",
"k, v in msg.brief_attaches.items(): if '_type' in k and v == \"photo\": text_required",
"to_admin(msg, args): sender_id = msg.user_id for role in await db.execute(Role.select().where(Role.role == \"admin\")): if",
"pass @plugin.on_command('анонимка', 'анонимно') async def anonymously(msg, args): text_required = True for k, v",
"= await msg.vk.method('users.get', {'user_ids': msg.user_id, 'name_case': \"gen\"}) sender_data = sender_data[0] val = {",
"return any(x in string for x in DISABLED) @plugin.on_init() def init(vk): pass @plugin.on_command('анонимка',",
"данных)') user.do_not_disturb = True await db.update(user) await msg.answer('Вы не будете получать сообщения!') @plugin.on_command('беспокоить')",
"\"\\n\" if not text_required: full = await msg.full_attaches if full: message += \"Вложения:\\n\".join(m.link",
"msg.answer('Сообщение успешно отправлено!') @plugin.on_command('админу') async def to_admin(msg, args): sender_id = msg.user_id for role",
"2: return await msg.answer('Введите ID пользователя и сообщение для него.') sender_id = msg.user_id",
"args.pop(0) if not possible_id.isdigit(): uid = await msg.vk.resolve_name(possible_id) else: uid = int(possible_id) if",
"существуете!\\n(или у бота проблемы с базой данных)') user.do_not_disturb = True await db.update(user) await",
"= await msg.vk.method('messages.send', val) if not result: return await msg.answer('Сообщение не удалось отправить!')",
"msg.answer('Проверьте правильность введёного ID пользователя.') if sender_id == uid: return await msg.answer('Зачем мне",
"result: return await msg.answer('Сообщение не удалось отправить!') await msg.answer('Сообщение успешно отправлено!') @plugin.on_command('скрыть') async",
"sender_data = sender_data[0] val = { 'peer_id': uid, 'message': f\"Вам сообщение от {sender_data['first_name']}",
"сможет отправлять вам сообщения!') @plugin.on_command('не беспокоить') async def do_not_disturb(msg, args): user = await",
"data + \"\\n\" if not text_required: full = await msg.full_attaches if full: message",
"msg.answer('Проверьте правильность введёного ID пользователя.') await db.execute(Ignore.delete().where( (Ignore.ignored == uid) & (Ignore.ignored_by ==",
"ссылки!') message = \"Вам анонимное сообщение!\\n\" if data: message += data + \"\\n\"",
"не будете получать сообщения от {ignore_id}!') @plugin.on_command('показать') async def show(msg, unignore): if len(unignore)",
"ссылки!') sender_data = await msg.vk.method('users.get', {'user_ids': msg.user_id, 'name_case': \"gen\"}) sender_data = sender_data[0] val",
"if len(args) < 1: return await msg.answer('Введите ID пользователя для игнорирования.') sender_id =",
"не получать сообщения\", \"беспокоить - получать сообщения\"], need_db=True) DISABLED = ('https', 'http', 'com',",
"return await msg.answer('Зачем мне отправлять сообщение самому себе?!') if await get_or_none(Ignore, ignored=sender_id, ignored_by=uid):",
"msg.answer('Сообщение успешно отправлено!') @plugin.on_command('написать', 'напиши', 'лс', 'письмо') async def write_msg(msg, args): if (len(args)",
"= args.pop(0) if not possible_id.isdigit(): uid = await msg.vk.resolve_name(possible_id) else: uid = int(possible_id)",
"sender_data = await msg.vk.method('users.get', {'user_ids': msg.user_id, 'name_case': \"gen\"}) sender_data = sender_data[0] val =",
"show(msg, unignore): if len(unignore) < 1: return await msg.answer('Введите ID пользователя, которого вы",
"[id] [сообщение] - написать сообщение пользователю\", \"анонимно [id] [сообщение] - написать анонимное сообщение",
"and text_required: return await msg.answer('Введите ID пользователя и сообщение для него.') sender_id =",
"def do_not_disturb(msg, args): user = await get_or_none(User, uid=msg.user_id) if not user: return await",
"ignored_by=sender_id) await msg.answer(f'Вы не будете получать сообщения от {ignore_id}!') @plugin.on_command('показать') async def show(msg,",
"import Plugin plugin = Plugin(\"Отправка сообщения\", usage=[\"напиши [id] [сообщение] - написать сообщение пользователю\",",
"'www', 'ftp', '://') def check_links(string): return any(x in string for x in DISABLED)",
"v == \"photo\": text_required = False break if len(args) < 2 and text_required:",
"await get_or_none(Ignore, ignored=sender_id, ignored_by=uid): return await msg.answer('Вы находитесь в чёрном списке у этого",
"'peer_id': role.user_id, 'message': f\"Вам сообщение от {sender_data['first_name']} {sender_data['last_name']}!\\n\\\"{data}\\\"\", } if \"attach1\" in msg.brief_attaches:",
"беспокоить - не получать сообщения\", \"беспокоить - получать сообщения\"], need_db=True) DISABLED = ('https',",
"пользователю\", \"анонимно [id] [сообщение] - написать анонимное сообщение пользователю\" \"(посылать можно только текст",
"отправить!') await msg.answer('Сообщение успешно отправлено!') @plugin.on_command('админу') async def to_admin(msg, args): sender_id = msg.user_id",
"def to_admin(msg, args): sender_id = msg.user_id for role in await db.execute(Role.select().where(Role.role == \"admin\")):",
"ignored=sender_id, ignored_by=role.user_id): return await msg.answer('Вы находитесь в чёрном списке у этого пользователя!') user",
"val = { 'peer_id': uid, 'message': f\"Вам сообщение от {sender_data['first_name']} {sender_data['last_name']}!\\n\\\"{data}\\\"\", } if",
"text_required: full = await msg.full_attaches if full: message += \"Вложения:\\n\".join(m.link for m in",
"async def do_not_disturb(msg, args): user = await get_or_none(User, uid=msg.user_id) if not user: return",
"его не беспокоить!') data = ' '.join(args) if check_links(data): return await msg.answer('В сообщении",
"введёного ID пользователя.') await db.create_or_get(Ignore, ignored=uid, ignored_by=sender_id) await msg.answer(f'Вы не будете получать сообщения",
"< 1: return await msg.answer('Введите ID пользователя, которого вы хотите убрать из игнора.')",
"'анонимно') async def anonymously(msg, args): text_required = True for k, v in msg.brief_attaches.items():",
"await msg.answer('Введите ID пользователя для игнорирования.') sender_id = msg.user_id ignore_id = args.pop() if",
"'message': message } result = await msg.vk.method('messages.send', val) if not result: return await",
"'лс', 'письмо') async def write_msg(msg, args): if (len(args) != 1 or not msg.brief_attaches)",
"ignored=uid, ignored_by=sender_id) await msg.answer(f'Вы не будете получать сообщения от {ignore_id}!') @plugin.on_command('показать') async def",
"не будете получать сообщения!') @plugin.on_command('беспокоить') async def do_disturb(msg, args): user = await get_or_none(User,",
"args): sender_id = msg.user_id for role in await db.execute(Role.select().where(Role.role == \"admin\")): if await",
"'http', 'com', 'www', 'ftp', '://') def check_links(string): return any(x in string for x",
"{'user_ids': msg.user_id, 'name_case': \"gen\"}) sender_data = sender_data[0] val = { 'peer_id': role.user_id, 'message':",
"@plugin.on_command('анонимка', 'анонимно') async def anonymously(msg, args): text_required = True for k, v in",
"для игнорирования.') sender_id = msg.user_id ignore_id = args.pop() if not ignore_id.isdigit(): uid =",
"possible_id.isdigit(): uid = await msg.vk.resolve_name(possible_id) else: uid = int(possible_id) if not uid: return",
"or not msg.brief_attaches) and len(args) < 2: return await msg.answer('Введите ID пользователя и",
"anonymously(msg, args): text_required = True for k, v in msg.brief_attaches.items(): if '_type' in",
"return await msg.answer('В сообщении были обнаружены ссылки!') message = \"Вам анонимное сообщение!\\n\" if",
"\"attach1\" in msg.brief_attaches: val['attachment'] = \",\".join(str(x) for x in await msg.full_attaches) result =",
"= await get_or_none(User, uid=msg.user_id) if not user: return await msg.answer('Вы не существуете!\\n(или у",
"False break if len(args) < 2 and text_required: return await msg.answer('Введите ID пользователя",
"if not uid: return await msg.answer('Проверьте правильность введёного ID пользователя.') await db.execute(Ignore.delete().where( (Ignore.ignored",
"msg.answer('Вы не будете получать сообщения!') @plugin.on_command('беспокоить') async def do_disturb(msg, args): user = await",
"if check_links(data): return await msg.answer('В сообщении были обнаружены ссылки!') sender_data = await msg.vk.method('users.get',",
"f\"Вам сообщение от {sender_data['first_name']} {sender_data['last_name']}!\\n\\\"{data}\\\"\", } if \"attach1\" in msg.brief_attaches: val['attachment'] = \",\".join(str(x)",
"DISABLED = ('https', 'http', 'com', 'www', 'ftp', '://') def check_links(string): return any(x in",
"not uid: return await msg.answer('Проверьте правильность введёного ID пользователя.') await db.create_or_get(Ignore, ignored=uid, ignored_by=sender_id)",
"uid=uid) if user and user.do_not_disturb: return await msg.answer('Этот пользователь попросил его не беспокоить!')",
"убрать из игнора.') sender_id = msg.user_id unignore_id = unignore.pop() if not unignore_id.isdigit(): uid",
"'peer_id': uid, 'message': f\"Вам сообщение от {sender_data['first_name']} {sender_data['last_name']}!\\n\\\"{data}\\\"\", } if \"attach1\" in msg.brief_attaches:",
"def hide(msg, args): if len(args) < 1: return await msg.answer('Введите ID пользователя для",
"чёрном списке у этого пользователя!') user = await get_or_none(User, uid=role.user_id) if user and",
"check_links(data): return await msg.answer('В сообщении были обнаружены ссылки!') message = \"Вам анонимное сообщение!\\n\"",
"{sender_data['last_name']}!\\n\\\"{data}\\\"\", } if \"attach1\" in msg.brief_attaches: val['attachment'] = \",\".join(str(x) for x in await",
"успешно отправлено!') @plugin.on_command('скрыть') async def hide(msg, args): if len(args) < 1: return await",
"if len(unignore) < 1: return await msg.answer('Введите ID пользователя, которого вы хотите убрать",
"msg.vk.resolve_name(unignore_id) else: uid = int(unignore_id) if not uid: return await msg.answer('Проверьте правильность введёного",
"usage=[\"напиши [id] [сообщение] - написать сообщение пользователю\", \"анонимно [id] [сообщение] - написать анонимное",
"\"admin\")): if await get_or_none(Ignore, ignored=sender_id, ignored_by=role.user_id): return await msg.answer('Вы находитесь в чёрном списке",
"<reponame>popa222455/botTWO from database import * from plugin_system import Plugin plugin = Plugin(\"Отправка сообщения\",",
"full: message += \"Вложения:\\n\".join(m.link for m in full) val = { 'peer_id': uid,",
"базой данных)') user.do_not_disturb = False await db.update(user) await msg.answer('Вы будете получать все сообщения!')",
"user.do_not_disturb: return await msg.answer('Этот пользователь попросил его не беспокоить!') data = ' '.join(args)",
"{unignore_id} сможет отправлять вам сообщения!') @plugin.on_command('не беспокоить') async def do_not_disturb(msg, args): user =",
"него.') sender_id = msg.user_id possible_id = args.pop(0) if not possible_id.isdigit(): uid = await",
"await msg.answer('Зачем мне отправлять сообщение вам?!') if await get_or_none(Ignore, ignored=sender_id, ignored_by=uid): return await",
"{'user_ids': msg.user_id, 'name_case': \"gen\"}) sender_data = sender_data[0] val = { 'peer_id': uid, 'message':",
"msg.user_id possible_id = args.pop(0) if not possible_id.isdigit(): uid = await msg.vk.resolve_name(possible_id) else: uid",
"и/или фото)\", \"не беспокоить - не получать сообщения\", \"беспокоить - получать сообщения\"], need_db=True)",
"@plugin.on_init() def init(vk): pass @plugin.on_command('анонимка', 'анонимно') async def anonymously(msg, args): text_required = True",
"async def show(msg, unignore): if len(unignore) < 1: return await msg.answer('Введите ID пользователя,",
"possible_id = args.pop(0) if not possible_id.isdigit(): uid = await msg.vk.resolve_name(possible_id) else: uid =",
"msg.user_id for role in await db.execute(Role.select().where(Role.role == \"admin\")): if await get_or_none(Ignore, ignored=sender_id, ignored_by=role.user_id):",
"сообщение для него.') sender_id = msg.user_id possible_id = args.pop(0) if not possible_id.isdigit(): uid",
"unignore): if len(unignore) < 1: return await msg.answer('Введите ID пользователя, которого вы хотите",
"if sender_id == uid: return await msg.answer('Зачем мне отправлять сообщение вам?!') if await",
"if check_links(data): return await msg.answer('В сообщении были обнаружены ссылки!') message = \"Вам анонимное",
"not text_required: full = await msg.full_attaches if full: message += \"Вложения:\\n\".join(m.link for m",
"от {ignore_id}!') @plugin.on_command('показать') async def show(msg, unignore): if len(unignore) < 1: return await",
"@plugin.on_command('показать') async def show(msg, unignore): if len(unignore) < 1: return await msg.answer('Введите ID",
"сообщение вам?!') if await get_or_none(Ignore, ignored=sender_id, ignored_by=uid): return await msg.answer('Вы находитесь в чёрном",
"только текст и/или фото)\", \"не беспокоить - не получать сообщения\", \"беспокоить - получать",
"msg.user_id, 'name_case': \"gen\"}) sender_data = sender_data[0] val = { 'peer_id': uid, 'message': f\"Вам",
"- получать сообщения\"], need_db=True) DISABLED = ('https', 'http', 'com', 'www', 'ftp', '://') def",
"ignored_by=role.user_id): return await msg.answer('Вы находитесь в чёрном списке у этого пользователя!') user =",
"проблемы с базой данных)') user.do_not_disturb = True await db.update(user) await msg.answer('Вы не будете",
"await msg.answer('Вы находитесь в чёрном списке у этого пользователя!') user = await get_or_none(User,",
"{ 'peer_id': role.user_id, 'message': f\"Вам сообщение от {sender_data['first_name']} {sender_data['last_name']}!\\n\\\"{data}\\\"\", } if \"attach1\" in",
"msg.answer('Введите ID пользователя и сообщение для него.') sender_id = msg.user_id possible_id = args.pop(0)",
"uid: return await msg.answer('Зачем мне отправлять сообщение вам?!') if await get_or_none(Ignore, ignored=sender_id, ignored_by=uid):",
"return await msg.answer('Сообщение не удалось отправить!') await msg.answer('Сообщение успешно отправлено!') @plugin.on_command('скрыть') async def",
"'напиши', 'лс', 'письмо') async def write_msg(msg, args): if (len(args) != 1 or not",
"'name_case': \"gen\"}) sender_data = sender_data[0] val = { 'peer_id': uid, 'message': f\"Вам сообщение",
"удалось отправить!') await msg.answer('Сообщение успешно отправлено!') @plugin.on_command('написать', 'напиши', 'лс', 'письмо') async def write_msg(msg,",
"await msg.answer('Проверьте правильность введёного ID пользователя.') if sender_id == uid: return await msg.answer('Зачем",
"await msg.vk.method('messages.send', val) if not result: return await msg.answer('Сообщение не удалось отправить!') await",
"= Plugin(\"Отправка сообщения\", usage=[\"напиши [id] [сообщение] - написать сообщение пользователю\", \"анонимно [id] [сообщение]",
"анонимное сообщение пользователю\" \"(посылать можно только текст и/или фото)\", \"не беспокоить - не",
"uid = await msg.vk.resolve_name(possible_id) else: uid = int(possible_id) if not uid: return await",
"return await msg.answer('Сообщение не удалось отправить!') await msg.answer('Сообщение успешно отправлено!') @plugin.on_command('админу') async def",
"находитесь в чёрном списке у этого пользователя!') user = await get_or_none(User, uid=role.user_id) if",
"} result = await msg.vk.method('messages.send', val) if not result: return await msg.answer('Сообщение не",
"return await msg.answer('Этот пользователь попросил его не беспокоить!') data = ' '.join(args) if",
"msg.answer('Сообщение не удалось отправить!') await msg.answer('Сообщение успешно отправлено!') @plugin.on_command('админу') async def to_admin(msg, args):",
"в чёрном списке у этого пользователя!') user = await get_or_none(User, uid=uid) if user",
"== \"admin\")): if await get_or_none(Ignore, ignored=sender_id, ignored_by=role.user_id): return await msg.answer('Вы находитесь в чёрном",
"были обнаружены ссылки!') message = \"Вам анонимное сообщение!\\n\" if data: message += data",
"uid = await msg.vk.resolve_name(unignore_id) else: uid = int(unignore_id) if not uid: return await",
"msg.user_id ignore_id = args.pop() if not ignore_id.isdigit(): uid = await msg.vk.resolve_name(ignore_id) else: uid",
"& (Ignore.ignored_by == sender_id) )) await msg.answer(f'Теперь {unignore_id} сможет отправлять вам сообщения!') @plugin.on_command('не",
"not uid: return await msg.answer('Проверьте правильность введёного ID пользователя.') if sender_id == uid:",
"= True for k, v in msg.brief_attaches.items(): if '_type' in k and v",
"этого пользователя!') user = await get_or_none(User, uid=role.user_id) if user and user.do_not_disturb: return await",
"if not unignore_id.isdigit(): uid = await msg.vk.resolve_name(unignore_id) else: uid = int(unignore_id) if not"
] |
[
"# -*- coding: utf-8 -*- # Generated by Django 1.10 on 2016-09-21 06:10",
"Django 1.10 on 2016-09-21 06:10 from __future__ import unicode_literals from django.db import migrations,",
"<filename>cryptonite/challenge/migrations/0010_challenge_users.py # -*- coding: utf-8 -*- # Generated by Django 1.10 on 2016-09-21",
"django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('cryptographer', '0001_cryptographer_user'), ('challenge', '0009_cryptographer_user'),",
"Migration(migrations.Migration): dependencies = [ ('cryptographer', '0001_cryptographer_user'), ('challenge', '0009_cryptographer_user'), ] operations = [ migrations.AddField(",
"('cryptographer', '0001_cryptographer_user'), ('challenge', '0009_cryptographer_user'), ] operations = [ migrations.AddField( model_name='challenge', name='users', field=models.ManyToManyField(blank=True, through='challenge.CompletedChallenge',",
"by Django 1.10 on 2016-09-21 06:10 from __future__ import unicode_literals from django.db import",
"import migrations, models class Migration(migrations.Migration): dependencies = [ ('cryptographer', '0001_cryptographer_user'), ('challenge', '0009_cryptographer_user'), ]",
"1.10 on 2016-09-21 06:10 from __future__ import unicode_literals from django.db import migrations, models",
"= [ ('cryptographer', '0001_cryptographer_user'), ('challenge', '0009_cryptographer_user'), ] operations = [ migrations.AddField( model_name='challenge', name='users',",
"migrations, models class Migration(migrations.Migration): dependencies = [ ('cryptographer', '0001_cryptographer_user'), ('challenge', '0009_cryptographer_user'), ] operations",
"Generated by Django 1.10 on 2016-09-21 06:10 from __future__ import unicode_literals from django.db",
"from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('cryptographer', '0001_cryptographer_user'), ('challenge',",
"-*- # Generated by Django 1.10 on 2016-09-21 06:10 from __future__ import unicode_literals",
"[ ('cryptographer', '0001_cryptographer_user'), ('challenge', '0009_cryptographer_user'), ] operations = [ migrations.AddField( model_name='challenge', name='users', field=models.ManyToManyField(blank=True,",
"models class Migration(migrations.Migration): dependencies = [ ('cryptographer', '0001_cryptographer_user'), ('challenge', '0009_cryptographer_user'), ] operations =",
"class Migration(migrations.Migration): dependencies = [ ('cryptographer', '0001_cryptographer_user'), ('challenge', '0009_cryptographer_user'), ] operations = [",
"import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('cryptographer',",
"utf-8 -*- # Generated by Django 1.10 on 2016-09-21 06:10 from __future__ import",
"dependencies = [ ('cryptographer', '0001_cryptographer_user'), ('challenge', '0009_cryptographer_user'), ] operations = [ migrations.AddField( model_name='challenge',",
"coding: utf-8 -*- # Generated by Django 1.10 on 2016-09-21 06:10 from __future__",
"# Generated by Django 1.10 on 2016-09-21 06:10 from __future__ import unicode_literals from",
"-*- coding: utf-8 -*- # Generated by Django 1.10 on 2016-09-21 06:10 from",
"from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies =",
"unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('cryptographer', '0001_cryptographer_user'),",
"__future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [",
"('challenge', '0009_cryptographer_user'), ] operations = [ migrations.AddField( model_name='challenge', name='users', field=models.ManyToManyField(blank=True, through='challenge.CompletedChallenge', to='cryptographer.Cryptographer'), ),",
"06:10 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies",
"'0001_cryptographer_user'), ('challenge', '0009_cryptographer_user'), ] operations = [ migrations.AddField( model_name='challenge', name='users', field=models.ManyToManyField(blank=True, through='challenge.CompletedChallenge', to='cryptographer.Cryptographer'),",
"on 2016-09-21 06:10 from __future__ import unicode_literals from django.db import migrations, models class",
"2016-09-21 06:10 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration):",
"'0009_cryptographer_user'), ] operations = [ migrations.AddField( model_name='challenge', name='users', field=models.ManyToManyField(blank=True, through='challenge.CompletedChallenge', to='cryptographer.Cryptographer'), ), ]"
] |
[
"delimitador \"?\" comando = '''DELETE FROM Pessoa WHERE cpf=61846350263;''' cursor.execute(comando) print(\"Primeiro Comando Especificado",
"# Deletando com uma string sem delimitador \"?\" comando = '''DELETE FROM Pessoa",
"'''DELETE FROM Pessoa WHERE cpf=61846350263;''' cursor.execute(comando) print(\"Primeiro Comando Especificado com suscesso\") # Deletando",
"um cursor conexao = conector.connect(\"./meu_banco.db\") cursor = conexao.cursor() print(\"Cursor e Conexao criados com",
"sem delimitador \"?\" comando = '''DELETE FROM Pessoa WHERE cpf=61846350263;''' cursor.execute(comando) print(\"Primeiro Comando",
"cursor = conexao.cursor() print(\"Cursor e Conexao criados com sucesso\") # Deletando com uma",
"print(\"Erro de Integridade\", err) except conector.DatabaseError as err: print(\"Erro do Banco de Dados\",",
"# Tratamento de Exceções except conector.IntegrityError as err: print(\"Erro de Integridade\", err) except",
"WHERE cpf=:cpf;''' cursor.execute(comando1,{\"cpf\":98712284220}) print(\"Segundo Comando Especificado com suscesso\") # Validando a alteração do",
"conector.IntegrityError as err: print(\"Erro de Integridade\", err) except conector.DatabaseError as err: print(\"Erro do",
"Pessoa WHERE cpf=:cpf;''' cursor.execute(comando1,{\"cpf\":98712284220}) print(\"Segundo Comando Especificado com suscesso\") # Validando a alteração",
"Integridade\", err) except conector.DatabaseError as err: print(\"Erro do Banco de Dados\", err) except",
"FROM Pessoa WHERE cpf=61846350263;''' cursor.execute(comando) print(\"Primeiro Comando Especificado com suscesso\") # Deletando com",
"except conector.OperationalError as err: print(\"Erro de Operação\", err) # Finalizando o programa finally:",
"uma string com argumentos nomeados comando1 = '''DELETE FROM Pessoa WHERE cpf=:cpf;''' cursor.execute(comando1,{\"cpf\":98712284220})",
"= '''DELETE FROM Pessoa WHERE cpf=61846350263;''' cursor.execute(comando) print(\"Primeiro Comando Especificado com suscesso\") #",
"sucesso\") # Deletando com uma string sem delimitador \"?\" comando = '''DELETE FROM",
"Deletando com uma string com argumentos nomeados comando1 = '''DELETE FROM Pessoa WHERE",
"as conector try: # Criando uma conexão e um cursor conexao = conector.connect(\"./meu_banco.db\")",
"err: print(\"Erro de Operação\", err) # Finalizando o programa finally: if conexao: cursor.close()",
"err: print(\"Erro de Integridade\", err) except conector.DatabaseError as err: print(\"Erro do Banco de",
"= conector.connect(\"./meu_banco.db\") cursor = conexao.cursor() print(\"Cursor e Conexao criados com sucesso\") # Deletando",
"= conexao.cursor() print(\"Cursor e Conexao criados com sucesso\") # Deletando com uma string",
"a alteração do DB conexao.commit() print(\"Conexao commitada com sucesso\") # Tratamento de Exceções",
"com uma string com argumentos nomeados comando1 = '''DELETE FROM Pessoa WHERE cpf=:cpf;'''",
"comando1 = '''DELETE FROM Pessoa WHERE cpf=:cpf;''' cursor.execute(comando1,{\"cpf\":98712284220}) print(\"Segundo Comando Especificado com suscesso\")",
"err: print(\"Erro do Banco de Dados\", err) except conector.OperationalError as err: print(\"Erro de",
"as err: print(\"Erro do Banco de Dados\", err) except conector.OperationalError as err: print(\"Erro",
"o programa finally: if conexao: cursor.close() conexao.close() print(\"Curso e conexao fechados com sucesso\")",
"de Integridade\", err) except conector.DatabaseError as err: print(\"Erro do Banco de Dados\", err)",
"suscesso\") # Validando a alteração do DB conexao.commit() print(\"Conexao commitada com sucesso\") #",
"criados com sucesso\") # Deletando com uma string sem delimitador \"?\" comando =",
"com uma string sem delimitador \"?\" comando = '''DELETE FROM Pessoa WHERE cpf=61846350263;'''",
"Criando uma conexão e um cursor conexao = conector.connect(\"./meu_banco.db\") cursor = conexao.cursor() print(\"Cursor",
"print(\"Cursor e Conexao criados com sucesso\") # Deletando com uma string sem delimitador",
"conector.DatabaseError as err: print(\"Erro do Banco de Dados\", err) except conector.OperationalError as err:",
"import sqlite3 as conector try: # Criando uma conexão e um cursor conexao",
"conector try: # Criando uma conexão e um cursor conexao = conector.connect(\"./meu_banco.db\") cursor",
"cursor conexao = conector.connect(\"./meu_banco.db\") cursor = conexao.cursor() print(\"Cursor e Conexao criados com sucesso\")",
"conexao = conector.connect(\"./meu_banco.db\") cursor = conexao.cursor() print(\"Cursor e Conexao criados com sucesso\") #",
"Especificado com suscesso\") # Deletando com uma string com argumentos nomeados comando1 =",
"Deletando com uma string sem delimitador \"?\" comando = '''DELETE FROM Pessoa WHERE",
"WHERE cpf=61846350263;''' cursor.execute(comando) print(\"Primeiro Comando Especificado com suscesso\") # Deletando com uma string",
"Exceções except conector.IntegrityError as err: print(\"Erro de Integridade\", err) except conector.DatabaseError as err:",
"print(\"Conexao commitada com sucesso\") # Tratamento de Exceções except conector.IntegrityError as err: print(\"Erro",
"conector.OperationalError as err: print(\"Erro de Operação\", err) # Finalizando o programa finally: if",
"cpf=:cpf;''' cursor.execute(comando1,{\"cpf\":98712284220}) print(\"Segundo Comando Especificado com suscesso\") # Validando a alteração do DB",
"conexao.cursor() print(\"Cursor e Conexao criados com sucesso\") # Deletando com uma string sem",
"sqlite3 as conector try: # Criando uma conexão e um cursor conexao =",
"DB conexao.commit() print(\"Conexao commitada com sucesso\") # Tratamento de Exceções except conector.IntegrityError as",
"FROM Pessoa WHERE cpf=:cpf;''' cursor.execute(comando1,{\"cpf\":98712284220}) print(\"Segundo Comando Especificado com suscesso\") # Validando a",
"Comando Especificado com suscesso\") # Deletando com uma string com argumentos nomeados comando1",
"err) except conector.DatabaseError as err: print(\"Erro do Banco de Dados\", err) except conector.OperationalError",
"as err: print(\"Erro de Operação\", err) # Finalizando o programa finally: if conexao:",
"do DB conexao.commit() print(\"Conexao commitada com sucesso\") # Tratamento de Exceções except conector.IntegrityError",
"try: # Criando uma conexão e um cursor conexao = conector.connect(\"./meu_banco.db\") cursor =",
"Tratamento de Exceções except conector.IntegrityError as err: print(\"Erro de Integridade\", err) except conector.DatabaseError",
"\"?\" comando = '''DELETE FROM Pessoa WHERE cpf=61846350263;''' cursor.execute(comando) print(\"Primeiro Comando Especificado com",
"uma string sem delimitador \"?\" comando = '''DELETE FROM Pessoa WHERE cpf=61846350263;''' cursor.execute(comando)",
"string com argumentos nomeados comando1 = '''DELETE FROM Pessoa WHERE cpf=:cpf;''' cursor.execute(comando1,{\"cpf\":98712284220}) print(\"Segundo",
"# Finalizando o programa finally: if conexao: cursor.close() conexao.close() print(\"Curso e conexao fechados",
"<filename>cap-3/13-Deletando_dados-DeleteFrom-Where.py<gh_stars>0 import sqlite3 as conector try: # Criando uma conexão e um cursor",
"Banco de Dados\", err) except conector.OperationalError as err: print(\"Erro de Operação\", err) #",
"err) # Finalizando o programa finally: if conexao: cursor.close() conexao.close() print(\"Curso e conexao",
"e Conexao criados com sucesso\") # Deletando com uma string sem delimitador \"?\"",
"e um cursor conexao = conector.connect(\"./meu_banco.db\") cursor = conexao.cursor() print(\"Cursor e Conexao criados",
"except conector.IntegrityError as err: print(\"Erro de Integridade\", err) except conector.DatabaseError as err: print(\"Erro",
"Finalizando o programa finally: if conexao: cursor.close() conexao.close() print(\"Curso e conexao fechados com",
"Conexao criados com sucesso\") # Deletando com uma string sem delimitador \"?\" comando",
"cursor.execute(comando) print(\"Primeiro Comando Especificado com suscesso\") # Deletando com uma string com argumentos",
"print(\"Primeiro Comando Especificado com suscesso\") # Deletando com uma string com argumentos nomeados",
"conector.connect(\"./meu_banco.db\") cursor = conexao.cursor() print(\"Cursor e Conexao criados com sucesso\") # Deletando com",
"de Operação\", err) # Finalizando o programa finally: if conexao: cursor.close() conexao.close() print(\"Curso",
"err) except conector.OperationalError as err: print(\"Erro de Operação\", err) # Finalizando o programa",
"argumentos nomeados comando1 = '''DELETE FROM Pessoa WHERE cpf=:cpf;''' cursor.execute(comando1,{\"cpf\":98712284220}) print(\"Segundo Comando Especificado",
"string sem delimitador \"?\" comando = '''DELETE FROM Pessoa WHERE cpf=61846350263;''' cursor.execute(comando) print(\"Primeiro",
"conexao.commit() print(\"Conexao commitada com sucesso\") # Tratamento de Exceções except conector.IntegrityError as err:",
"Validando a alteração do DB conexao.commit() print(\"Conexao commitada com sucesso\") # Tratamento de",
"conexão e um cursor conexao = conector.connect(\"./meu_banco.db\") cursor = conexao.cursor() print(\"Cursor e Conexao",
"de Dados\", err) except conector.OperationalError as err: print(\"Erro de Operação\", err) # Finalizando",
"suscesso\") # Deletando com uma string com argumentos nomeados comando1 = '''DELETE FROM",
"com sucesso\") # Deletando com uma string sem delimitador \"?\" comando = '''DELETE",
"# Validando a alteração do DB conexao.commit() print(\"Conexao commitada com sucesso\") # Tratamento",
"de Exceções except conector.IntegrityError as err: print(\"Erro de Integridade\", err) except conector.DatabaseError as",
"Dados\", err) except conector.OperationalError as err: print(\"Erro de Operação\", err) # Finalizando o",
"Pessoa WHERE cpf=61846350263;''' cursor.execute(comando) print(\"Primeiro Comando Especificado com suscesso\") # Deletando com uma",
"comando = '''DELETE FROM Pessoa WHERE cpf=61846350263;''' cursor.execute(comando) print(\"Primeiro Comando Especificado com suscesso\")",
"= '''DELETE FROM Pessoa WHERE cpf=:cpf;''' cursor.execute(comando1,{\"cpf\":98712284220}) print(\"Segundo Comando Especificado com suscesso\") #",
"cursor.execute(comando1,{\"cpf\":98712284220}) print(\"Segundo Comando Especificado com suscesso\") # Validando a alteração do DB conexao.commit()",
"'''DELETE FROM Pessoa WHERE cpf=:cpf;''' cursor.execute(comando1,{\"cpf\":98712284220}) print(\"Segundo Comando Especificado com suscesso\") # Validando",
"com suscesso\") # Validando a alteração do DB conexao.commit() print(\"Conexao commitada com sucesso\")",
"sucesso\") # Tratamento de Exceções except conector.IntegrityError as err: print(\"Erro de Integridade\", err)",
"com argumentos nomeados comando1 = '''DELETE FROM Pessoa WHERE cpf=:cpf;''' cursor.execute(comando1,{\"cpf\":98712284220}) print(\"Segundo Comando",
"Especificado com suscesso\") # Validando a alteração do DB conexao.commit() print(\"Conexao commitada com",
"# Criando uma conexão e um cursor conexao = conector.connect(\"./meu_banco.db\") cursor = conexao.cursor()",
"except conector.DatabaseError as err: print(\"Erro do Banco de Dados\", err) except conector.OperationalError as",
"Operação\", err) # Finalizando o programa finally: if conexao: cursor.close() conexao.close() print(\"Curso e",
"Comando Especificado com suscesso\") # Validando a alteração do DB conexao.commit() print(\"Conexao commitada",
"print(\"Segundo Comando Especificado com suscesso\") # Validando a alteração do DB conexao.commit() print(\"Conexao",
"com suscesso\") # Deletando com uma string com argumentos nomeados comando1 = '''DELETE",
"commitada com sucesso\") # Tratamento de Exceções except conector.IntegrityError as err: print(\"Erro de",
"com sucesso\") # Tratamento de Exceções except conector.IntegrityError as err: print(\"Erro de Integridade\",",
"print(\"Erro de Operação\", err) # Finalizando o programa finally: if conexao: cursor.close() conexao.close()",
"alteração do DB conexao.commit() print(\"Conexao commitada com sucesso\") # Tratamento de Exceções except",
"uma conexão e um cursor conexao = conector.connect(\"./meu_banco.db\") cursor = conexao.cursor() print(\"Cursor e",
"do Banco de Dados\", err) except conector.OperationalError as err: print(\"Erro de Operação\", err)",
"# Deletando com uma string com argumentos nomeados comando1 = '''DELETE FROM Pessoa",
"nomeados comando1 = '''DELETE FROM Pessoa WHERE cpf=:cpf;''' cursor.execute(comando1,{\"cpf\":98712284220}) print(\"Segundo Comando Especificado com",
"print(\"Erro do Banco de Dados\", err) except conector.OperationalError as err: print(\"Erro de Operação\",",
"as err: print(\"Erro de Integridade\", err) except conector.DatabaseError as err: print(\"Erro do Banco",
"cpf=61846350263;''' cursor.execute(comando) print(\"Primeiro Comando Especificado com suscesso\") # Deletando com uma string com"
] |
[
"if default_driver is None: default_driver = 'Chrome.headless' Driver = _from_env(default_driver=default_driver) return Driver(*args, **kwargs)",
"Firefox, Ie, Edge, Opera, Safari, BlackBerry, PhantomJS, Android, Remote] driver_map = {get_driver_name(d): d",
"_from_string(webdriver_string) return Driver(*args, **kwargs) def _from_env(default_driver=None): browser_env = getenv('BEHAVE_WEBDRIVER', default_driver) if browser_env is",
"def _from_string(webdriver_string): def get_driver_name(driver): return driver.__name__.upper() drivers = [Chrome, Firefox, Ie, Edge, Opera,",
"def from_env(*args, **kwargs): default_driver = kwargs.pop('default_driver', None) if default_driver is None: default_driver =",
"for d in drivers} driver_map['CHROME.HEADLESS'] = Chrome.headless Driver = driver_map.get(webdriver_string.upper(), None) if Driver",
"Driver = _from_string(webdriver_string) return Driver(*args, **kwargs) def _from_env(default_driver=None): browser_env = getenv('BEHAVE_WEBDRIVER', default_driver) if",
"Safari, BlackBerry, PhantomJS, Android, Remote) def _from_string(webdriver_string): def get_driver_name(driver): return driver.__name__.upper() drivers =",
"Driver = driver_map.get(webdriver_string.upper(), None) if Driver is None: raise ValueError('No such driver \"{}\".",
"Android, Remote] driver_map = {get_driver_name(d): d for d in drivers} driver_map['CHROME.HEADLESS'] = Chrome.headless",
"**kwargs): Driver = _from_string(webdriver_string) return Driver(*args, **kwargs) def _from_env(default_driver=None): browser_env = getenv('BEHAVE_WEBDRIVER', default_driver)",
"Edge, Opera, Safari, BlackBerry, PhantomJS, Android, Remote] driver_map = {get_driver_name(d): d for d",
"Ie, Edge, Opera, Safari, BlackBerry, PhantomJS, Android, Remote) def _from_string(webdriver_string): def get_driver_name(driver): return",
"driver found in environment variables and no default driver selection') if isinstance(browser_env, six.string_types):",
"is None: raise ValueError('No such driver \"{}\". Valid options are: {}'.format(webdriver_string, ', '.join(driver_map.keys())))",
"Driver = browser_env return Driver def from_env(*args, **kwargs): default_driver = kwargs.pop('default_driver', None) if",
"browser_env return Driver def from_env(*args, **kwargs): default_driver = kwargs.pop('default_driver', None) if default_driver is",
"**kwargs): default_driver = kwargs.pop('default_driver', None) if default_driver is None: default_driver = 'Chrome.headless' Driver",
"driver_map = {get_driver_name(d): d for d in drivers} driver_map['CHROME.HEADLESS'] = Chrome.headless Driver =",
"browser_env is None: raise ValueError('No driver found in environment variables and no default",
"(Chrome, Firefox, Ie, Edge, Opera, Safari, BlackBerry, PhantomJS, Android, Remote) def _from_string(webdriver_string): def",
"getenv('BEHAVE_WEBDRIVER', default_driver) if browser_env is None: raise ValueError('No driver found in environment variables",
"Opera, Safari, BlackBerry, PhantomJS, Android, Remote) def _from_string(webdriver_string): def get_driver_name(driver): return driver.__name__.upper() drivers",
"ValueError('No such driver \"{}\". Valid options are: {}'.format(webdriver_string, ', '.join(driver_map.keys()))) return Driver def",
"import six from behave_webdriver.driver import (Chrome, Firefox, Ie, Edge, Opera, Safari, BlackBerry, PhantomJS,",
"_from_string(webdriver_string): def get_driver_name(driver): return driver.__name__.upper() drivers = [Chrome, Firefox, Ie, Edge, Opera, Safari,",
"{get_driver_name(d): d for d in drivers} driver_map['CHROME.HEADLESS'] = Chrome.headless Driver = driver_map.get(webdriver_string.upper(), None)",
"= kwargs.pop('default_driver', None) if default_driver is None: default_driver = 'Chrome.headless' Driver = _from_env(default_driver=default_driver)",
"getenv import six from behave_webdriver.driver import (Chrome, Firefox, Ie, Edge, Opera, Safari, BlackBerry,",
"Driver def from_env(*args, **kwargs): default_driver = kwargs.pop('default_driver', None) if default_driver is None: default_driver",
"such driver \"{}\". Valid options are: {}'.format(webdriver_string, ', '.join(driver_map.keys()))) return Driver def from_string(webdriver_string,",
"<reponame>stevegibson/behave-webdriver from os import getenv import six from behave_webdriver.driver import (Chrome, Firefox, Ie,",
"driver_map['CHROME.HEADLESS'] = Chrome.headless Driver = driver_map.get(webdriver_string.upper(), None) if Driver is None: raise ValueError('No",
"found in environment variables and no default driver selection') if isinstance(browser_env, six.string_types): Driver",
"kwargs.pop('default_driver', None) if default_driver is None: default_driver = 'Chrome.headless' Driver = _from_env(default_driver=default_driver) return",
"\"{}\". Valid options are: {}'.format(webdriver_string, ', '.join(driver_map.keys()))) return Driver def from_string(webdriver_string, *args, **kwargs):",
"**kwargs) def _from_env(default_driver=None): browser_env = getenv('BEHAVE_WEBDRIVER', default_driver) if browser_env is None: raise ValueError('No",
"# if not a string, assume we have a webdriver instance Driver =",
"else: # if not a string, assume we have a webdriver instance Driver",
"if Driver is None: raise ValueError('No such driver \"{}\". Valid options are: {}'.format(webdriver_string,",
"return Driver(*args, **kwargs) def _from_env(default_driver=None): browser_env = getenv('BEHAVE_WEBDRIVER', default_driver) if browser_env is None:",
"ValueError('No driver found in environment variables and no default driver selection') if isinstance(browser_env,",
"default driver selection') if isinstance(browser_env, six.string_types): Driver = _from_string(browser_env) else: # if not",
"Driver = _from_string(browser_env) else: # if not a string, assume we have a",
"we have a webdriver instance Driver = browser_env return Driver def from_env(*args, **kwargs):",
"Remote] driver_map = {get_driver_name(d): d for d in drivers} driver_map['CHROME.HEADLESS'] = Chrome.headless Driver",
"Driver is None: raise ValueError('No such driver \"{}\". Valid options are: {}'.format(webdriver_string, ',",
"import getenv import six from behave_webdriver.driver import (Chrome, Firefox, Ie, Edge, Opera, Safari,",
"six.string_types): Driver = _from_string(browser_env) else: # if not a string, assume we have",
"= _from_string(webdriver_string) return Driver(*args, **kwargs) def _from_env(default_driver=None): browser_env = getenv('BEHAVE_WEBDRIVER', default_driver) if browser_env",
"driver selection') if isinstance(browser_env, six.string_types): Driver = _from_string(browser_env) else: # if not a",
"isinstance(browser_env, six.string_types): Driver = _from_string(browser_env) else: # if not a string, assume we",
"None: raise ValueError('No such driver \"{}\". Valid options are: {}'.format(webdriver_string, ', '.join(driver_map.keys()))) return",
"_from_string(browser_env) else: # if not a string, assume we have a webdriver instance",
"def _from_env(default_driver=None): browser_env = getenv('BEHAVE_WEBDRIVER', default_driver) if browser_env is None: raise ValueError('No driver",
"are: {}'.format(webdriver_string, ', '.join(driver_map.keys()))) return Driver def from_string(webdriver_string, *args, **kwargs): Driver = _from_string(webdriver_string)",
"None) if Driver is None: raise ValueError('No such driver \"{}\". Valid options are:",
"have a webdriver instance Driver = browser_env return Driver def from_env(*args, **kwargs): default_driver",
"import (Chrome, Firefox, Ie, Edge, Opera, Safari, BlackBerry, PhantomJS, Android, Remote) def _from_string(webdriver_string):",
"os import getenv import six from behave_webdriver.driver import (Chrome, Firefox, Ie, Edge, Opera,",
"def from_string(webdriver_string, *args, **kwargs): Driver = _from_string(webdriver_string) return Driver(*args, **kwargs) def _from_env(default_driver=None): browser_env",
"BlackBerry, PhantomJS, Android, Remote] driver_map = {get_driver_name(d): d for d in drivers} driver_map['CHROME.HEADLESS']",
"if not a string, assume we have a webdriver instance Driver = browser_env",
"= Chrome.headless Driver = driver_map.get(webdriver_string.upper(), None) if Driver is None: raise ValueError('No such",
"', '.join(driver_map.keys()))) return Driver def from_string(webdriver_string, *args, **kwargs): Driver = _from_string(webdriver_string) return Driver(*args,",
"no default driver selection') if isinstance(browser_env, six.string_types): Driver = _from_string(browser_env) else: # if",
"return Driver def from_env(*args, **kwargs): default_driver = kwargs.pop('default_driver', None) if default_driver is None:",
"Ie, Edge, Opera, Safari, BlackBerry, PhantomJS, Android, Remote] driver_map = {get_driver_name(d): d for",
"PhantomJS, Android, Remote] driver_map = {get_driver_name(d): d for d in drivers} driver_map['CHROME.HEADLESS'] =",
"not a string, assume we have a webdriver instance Driver = browser_env return",
"d in drivers} driver_map['CHROME.HEADLESS'] = Chrome.headless Driver = driver_map.get(webdriver_string.upper(), None) if Driver is",
"def get_driver_name(driver): return driver.__name__.upper() drivers = [Chrome, Firefox, Ie, Edge, Opera, Safari, BlackBerry,",
"selection') if isinstance(browser_env, six.string_types): Driver = _from_string(browser_env) else: # if not a string,",
"behave_webdriver.driver import (Chrome, Firefox, Ie, Edge, Opera, Safari, BlackBerry, PhantomJS, Android, Remote) def",
"Android, Remote) def _from_string(webdriver_string): def get_driver_name(driver): return driver.__name__.upper() drivers = [Chrome, Firefox, Ie,",
"six from behave_webdriver.driver import (Chrome, Firefox, Ie, Edge, Opera, Safari, BlackBerry, PhantomJS, Android,",
"driver_map.get(webdriver_string.upper(), None) if Driver is None: raise ValueError('No such driver \"{}\". Valid options",
"d for d in drivers} driver_map['CHROME.HEADLESS'] = Chrome.headless Driver = driver_map.get(webdriver_string.upper(), None) if",
"instance Driver = browser_env return Driver def from_env(*args, **kwargs): default_driver = kwargs.pop('default_driver', None)",
"a string, assume we have a webdriver instance Driver = browser_env return Driver",
"Remote) def _from_string(webdriver_string): def get_driver_name(driver): return driver.__name__.upper() drivers = [Chrome, Firefox, Ie, Edge,",
"if browser_env is None: raise ValueError('No driver found in environment variables and no",
"from_env(*args, **kwargs): default_driver = kwargs.pop('default_driver', None) if default_driver is None: default_driver = 'Chrome.headless'",
"in drivers} driver_map['CHROME.HEADLESS'] = Chrome.headless Driver = driver_map.get(webdriver_string.upper(), None) if Driver is None:",
"assume we have a webdriver instance Driver = browser_env return Driver def from_env(*args,",
"*args, **kwargs): Driver = _from_string(webdriver_string) return Driver(*args, **kwargs) def _from_env(default_driver=None): browser_env = getenv('BEHAVE_WEBDRIVER',",
"a webdriver instance Driver = browser_env return Driver def from_env(*args, **kwargs): default_driver =",
"return driver.__name__.upper() drivers = [Chrome, Firefox, Ie, Edge, Opera, Safari, BlackBerry, PhantomJS, Android,",
"from_string(webdriver_string, *args, **kwargs): Driver = _from_string(webdriver_string) return Driver(*args, **kwargs) def _from_env(default_driver=None): browser_env =",
"Driver def from_string(webdriver_string, *args, **kwargs): Driver = _from_string(webdriver_string) return Driver(*args, **kwargs) def _from_env(default_driver=None):",
"{}'.format(webdriver_string, ', '.join(driver_map.keys()))) return Driver def from_string(webdriver_string, *args, **kwargs): Driver = _from_string(webdriver_string) return",
"browser_env = getenv('BEHAVE_WEBDRIVER', default_driver) if browser_env is None: raise ValueError('No driver found in",
"default_driver) if browser_env is None: raise ValueError('No driver found in environment variables and",
"'.join(driver_map.keys()))) return Driver def from_string(webdriver_string, *args, **kwargs): Driver = _from_string(webdriver_string) return Driver(*args, **kwargs)",
"Firefox, Ie, Edge, Opera, Safari, BlackBerry, PhantomJS, Android, Remote) def _from_string(webdriver_string): def get_driver_name(driver):",
"drivers = [Chrome, Firefox, Ie, Edge, Opera, Safari, BlackBerry, PhantomJS, Android, Remote] driver_map",
"raise ValueError('No such driver \"{}\". Valid options are: {}'.format(webdriver_string, ', '.join(driver_map.keys()))) return Driver",
"Valid options are: {}'.format(webdriver_string, ', '.join(driver_map.keys()))) return Driver def from_string(webdriver_string, *args, **kwargs): Driver",
"drivers} driver_map['CHROME.HEADLESS'] = Chrome.headless Driver = driver_map.get(webdriver_string.upper(), None) if Driver is None: raise",
"[Chrome, Firefox, Ie, Edge, Opera, Safari, BlackBerry, PhantomJS, Android, Remote] driver_map = {get_driver_name(d):",
"Driver(*args, **kwargs) def _from_env(default_driver=None): browser_env = getenv('BEHAVE_WEBDRIVER', default_driver) if browser_env is None: raise",
"= _from_string(browser_env) else: # if not a string, assume we have a webdriver",
"driver.__name__.upper() drivers = [Chrome, Firefox, Ie, Edge, Opera, Safari, BlackBerry, PhantomJS, Android, Remote]",
"raise ValueError('No driver found in environment variables and no default driver selection') if",
"None) if default_driver is None: default_driver = 'Chrome.headless' Driver = _from_env(default_driver=default_driver) return Driver(*args,",
"= {get_driver_name(d): d for d in drivers} driver_map['CHROME.HEADLESS'] = Chrome.headless Driver = driver_map.get(webdriver_string.upper(),",
"in environment variables and no default driver selection') if isinstance(browser_env, six.string_types): Driver =",
"Safari, BlackBerry, PhantomJS, Android, Remote] driver_map = {get_driver_name(d): d for d in drivers}",
"driver \"{}\". Valid options are: {}'.format(webdriver_string, ', '.join(driver_map.keys()))) return Driver def from_string(webdriver_string, *args,",
"webdriver instance Driver = browser_env return Driver def from_env(*args, **kwargs): default_driver = kwargs.pop('default_driver',",
"options are: {}'.format(webdriver_string, ', '.join(driver_map.keys()))) return Driver def from_string(webdriver_string, *args, **kwargs): Driver =",
"_from_env(default_driver=None): browser_env = getenv('BEHAVE_WEBDRIVER', default_driver) if browser_env is None: raise ValueError('No driver found",
"string, assume we have a webdriver instance Driver = browser_env return Driver def",
"variables and no default driver selection') if isinstance(browser_env, six.string_types): Driver = _from_string(browser_env) else:",
"and no default driver selection') if isinstance(browser_env, six.string_types): Driver = _from_string(browser_env) else: #",
"= [Chrome, Firefox, Ie, Edge, Opera, Safari, BlackBerry, PhantomJS, Android, Remote] driver_map =",
"get_driver_name(driver): return driver.__name__.upper() drivers = [Chrome, Firefox, Ie, Edge, Opera, Safari, BlackBerry, PhantomJS,",
"if isinstance(browser_env, six.string_types): Driver = _from_string(browser_env) else: # if not a string, assume",
"from os import getenv import six from behave_webdriver.driver import (Chrome, Firefox, Ie, Edge,",
"return Driver def from_string(webdriver_string, *args, **kwargs): Driver = _from_string(webdriver_string) return Driver(*args, **kwargs) def",
"= driver_map.get(webdriver_string.upper(), None) if Driver is None: raise ValueError('No such driver \"{}\". Valid",
"PhantomJS, Android, Remote) def _from_string(webdriver_string): def get_driver_name(driver): return driver.__name__.upper() drivers = [Chrome, Firefox,",
"Opera, Safari, BlackBerry, PhantomJS, Android, Remote] driver_map = {get_driver_name(d): d for d in",
"BlackBerry, PhantomJS, Android, Remote) def _from_string(webdriver_string): def get_driver_name(driver): return driver.__name__.upper() drivers = [Chrome,",
"None: raise ValueError('No driver found in environment variables and no default driver selection')",
"default_driver = kwargs.pop('default_driver', None) if default_driver is None: default_driver = 'Chrome.headless' Driver =",
"= browser_env return Driver def from_env(*args, **kwargs): default_driver = kwargs.pop('default_driver', None) if default_driver",
"Edge, Opera, Safari, BlackBerry, PhantomJS, Android, Remote) def _from_string(webdriver_string): def get_driver_name(driver): return driver.__name__.upper()",
"Chrome.headless Driver = driver_map.get(webdriver_string.upper(), None) if Driver is None: raise ValueError('No such driver",
"from behave_webdriver.driver import (Chrome, Firefox, Ie, Edge, Opera, Safari, BlackBerry, PhantomJS, Android, Remote)",
"is None: raise ValueError('No driver found in environment variables and no default driver",
"environment variables and no default driver selection') if isinstance(browser_env, six.string_types): Driver = _from_string(browser_env)",
"= getenv('BEHAVE_WEBDRIVER', default_driver) if browser_env is None: raise ValueError('No driver found in environment"
] |
[
"import Image, ImageDraw,ImageFont def drawNumberOnIcon(imgpath, number): img = Image.open(imgpath) if (None == img):",
"img_size = img.size font = ImageFont.truetype(\"Varela-Regular.otf\", size=int(img_size[1]/4)) text_size = font.getsize(str(number)) draw.text((img_size[0]-text_size[0], 0), str(number),",
"ImageDraw.Draw(img) img_size = img.size font = ImageFont.truetype(\"Varela-Regular.otf\", size=int(img_size[1]/4)) text_size = font.getsize(str(number)) draw.text((img_size[0]-text_size[0], 0),",
"# -*- coding: utf-8 -*- __author__ = 'PatchLion' from PIL import Image, ImageDraw,ImageFont",
"def drawNumberOnIcon(imgpath, number): img = Image.open(imgpath) if (None == img): print('打开图片失败') return img",
"drawNumberOnIcon(imgpath, number): img = Image.open(imgpath) if (None == img): print('打开图片失败') return img =",
"img = Image.open(imgpath) if (None == img): print('打开图片失败') return img = img.resize((160, 160))",
"img.mode) draw = ImageDraw.Draw(img) img_size = img.size font = ImageFont.truetype(\"Varela-Regular.otf\", size=int(img_size[1]/4)) text_size =",
"number): img = Image.open(imgpath) if (None == img): print('打开图片失败') return img = img.resize((160,",
"text_size = font.getsize(str(number)) draw.text((img_size[0]-text_size[0], 0), str(number), font=font, fill=(255, 0, 0)) img.save('icon_withnumber.jpg') print('生成图片成功') drawNumberOnIcon(\"icon.jpg\",",
"= ImageDraw.Draw(img) img_size = img.size font = ImageFont.truetype(\"Varela-Regular.otf\", size=int(img_size[1]/4)) text_size = font.getsize(str(number)) draw.text((img_size[0]-text_size[0],",
"= img.resize((160, 160)) print(imgpath, \"->\", img.format, img.size, img.mode) draw = ImageDraw.Draw(img) img_size =",
"img.size, img.mode) draw = ImageDraw.Draw(img) img_size = img.size font = ImageFont.truetype(\"Varela-Regular.otf\", size=int(img_size[1]/4)) text_size",
"img.resize((160, 160)) print(imgpath, \"->\", img.format, img.size, img.mode) draw = ImageDraw.Draw(img) img_size = img.size",
"= Image.open(imgpath) if (None == img): print('打开图片失败') return img = img.resize((160, 160)) print(imgpath,",
"print('打开图片失败') return img = img.resize((160, 160)) print(imgpath, \"->\", img.format, img.size, img.mode) draw =",
"font = ImageFont.truetype(\"Varela-Regular.otf\", size=int(img_size[1]/4)) text_size = font.getsize(str(number)) draw.text((img_size[0]-text_size[0], 0), str(number), font=font, fill=(255, 0,",
"ImageFont.truetype(\"Varela-Regular.otf\", size=int(img_size[1]/4)) text_size = font.getsize(str(number)) draw.text((img_size[0]-text_size[0], 0), str(number), font=font, fill=(255, 0, 0)) img.save('icon_withnumber.jpg')",
"= font.getsize(str(number)) draw.text((img_size[0]-text_size[0], 0), str(number), font=font, fill=(255, 0, 0)) img.save('icon_withnumber.jpg') print('生成图片成功') drawNumberOnIcon(\"icon.jpg\", 21)",
"PIL import Image, ImageDraw,ImageFont def drawNumberOnIcon(imgpath, number): img = Image.open(imgpath) if (None ==",
"img.size font = ImageFont.truetype(\"Varela-Regular.otf\", size=int(img_size[1]/4)) text_size = font.getsize(str(number)) draw.text((img_size[0]-text_size[0], 0), str(number), font=font, fill=(255,",
"ImageDraw,ImageFont def drawNumberOnIcon(imgpath, number): img = Image.open(imgpath) if (None == img): print('打开图片失败') return",
"(None == img): print('打开图片失败') return img = img.resize((160, 160)) print(imgpath, \"->\", img.format, img.size,",
"img.format, img.size, img.mode) draw = ImageDraw.Draw(img) img_size = img.size font = ImageFont.truetype(\"Varela-Regular.otf\", size=int(img_size[1]/4))",
"= 'PatchLion' from PIL import Image, ImageDraw,ImageFont def drawNumberOnIcon(imgpath, number): img = Image.open(imgpath)",
"\"->\", img.format, img.size, img.mode) draw = ImageDraw.Draw(img) img_size = img.size font = ImageFont.truetype(\"Varela-Regular.otf\",",
"-*- __author__ = 'PatchLion' from PIL import Image, ImageDraw,ImageFont def drawNumberOnIcon(imgpath, number): img",
"from PIL import Image, ImageDraw,ImageFont def drawNumberOnIcon(imgpath, number): img = Image.open(imgpath) if (None",
"if (None == img): print('打开图片失败') return img = img.resize((160, 160)) print(imgpath, \"->\", img.format,",
"= img.size font = ImageFont.truetype(\"Varela-Regular.otf\", size=int(img_size[1]/4)) text_size = font.getsize(str(number)) draw.text((img_size[0]-text_size[0], 0), str(number), font=font,",
"= ImageFont.truetype(\"Varela-Regular.otf\", size=int(img_size[1]/4)) text_size = font.getsize(str(number)) draw.text((img_size[0]-text_size[0], 0), str(number), font=font, fill=(255, 0, 0))",
"__author__ = 'PatchLion' from PIL import Image, ImageDraw,ImageFont def drawNumberOnIcon(imgpath, number): img =",
"Image.open(imgpath) if (None == img): print('打开图片失败') return img = img.resize((160, 160)) print(imgpath, \"->\",",
"utf-8 -*- __author__ = 'PatchLion' from PIL import Image, ImageDraw,ImageFont def drawNumberOnIcon(imgpath, number):",
"return img = img.resize((160, 160)) print(imgpath, \"->\", img.format, img.size, img.mode) draw = ImageDraw.Draw(img)",
"-*- coding: utf-8 -*- __author__ = 'PatchLion' from PIL import Image, ImageDraw,ImageFont def",
"<filename>patchlion/0000/DrawHeadImage.py<gh_stars>1000+ # -*- coding: utf-8 -*- __author__ = 'PatchLion' from PIL import Image,",
"Image, ImageDraw,ImageFont def drawNumberOnIcon(imgpath, number): img = Image.open(imgpath) if (None == img): print('打开图片失败')",
"coding: utf-8 -*- __author__ = 'PatchLion' from PIL import Image, ImageDraw,ImageFont def drawNumberOnIcon(imgpath,",
"size=int(img_size[1]/4)) text_size = font.getsize(str(number)) draw.text((img_size[0]-text_size[0], 0), str(number), font=font, fill=(255, 0, 0)) img.save('icon_withnumber.jpg') print('生成图片成功')",
"160)) print(imgpath, \"->\", img.format, img.size, img.mode) draw = ImageDraw.Draw(img) img_size = img.size font",
"== img): print('打开图片失败') return img = img.resize((160, 160)) print(imgpath, \"->\", img.format, img.size, img.mode)",
"img = img.resize((160, 160)) print(imgpath, \"->\", img.format, img.size, img.mode) draw = ImageDraw.Draw(img) img_size",
"draw = ImageDraw.Draw(img) img_size = img.size font = ImageFont.truetype(\"Varela-Regular.otf\", size=int(img_size[1]/4)) text_size = font.getsize(str(number))",
"print(imgpath, \"->\", img.format, img.size, img.mode) draw = ImageDraw.Draw(img) img_size = img.size font =",
"img): print('打开图片失败') return img = img.resize((160, 160)) print(imgpath, \"->\", img.format, img.size, img.mode) draw",
"'PatchLion' from PIL import Image, ImageDraw,ImageFont def drawNumberOnIcon(imgpath, number): img = Image.open(imgpath) if"
] |
[
"anti11 Let f(x) be the number of x length binary strings without 11",
"[0, 1, 2] for i in range(2,10001): f.append(g[-1]) g.append((g[-1] + f[-2]) % M)",
"Kattis - anti11 Let f(x) be the number of x length binary strings",
"number of x length binary strings without 11 ending with 1 Let g(x)",
"length binary strings without 11 ending with 1 Let g(x) be the numebr",
"2 {00, 10} f(x+1) = g(x) {...01} g(x+1) = f(x) + g(x) {...00,",
"2] for i in range(2,10001): f.append(g[-1]) g.append((g[-1] + f[-2]) % M) # print(f[:10])",
"''' Kattis - anti11 Let f(x) be the number of x length binary",
"f(x) be the number of x length binary strings without 11 ending with",
"range(2,10001): f.append(g[-1]) g.append((g[-1] + f[-2]) % M) # print(f[:10]) # print(g[:10]) n =",
"# print(f[:10]) # print(g[:10]) n = int(input()) for i in range(n): x =",
"{00, 10} f(x+1) = g(x) {...01} g(x+1) = f(x) + g(x) {...00, ...10}",
"ending with 1 Let g(x) be the numebr of x length binary strings",
"1, 1] g = [0, 1, 2] for i in range(2,10001): f.append(g[-1]) g.append((g[-1]",
"print(f[:10]) # print(g[:10]) n = int(input()) for i in range(n): x = int(input())",
"M = int(1e9 + 7) f = [0, 1, 1] g = [0,",
"the number of x length binary strings without 11 ending with 1 Let",
"Time: O(10000), Space: O(10000) ''' M = int(1e9 + 7) f = [0,",
"= 2 {00, 10} f(x+1) = g(x) {...01} g(x+1) = f(x) + g(x)",
"''' M = int(1e9 + 7) f = [0, 1, 1] g =",
"in range(2,10001): f.append(g[-1]) g.append((g[-1] + f[-2]) % M) # print(f[:10]) # print(g[:10]) n",
"g(x+1) = f(x) + g(x) {...00, ...10} ans(x) = f(x) + g(x) Time:",
"int(1e9 + 7) f = [0, 1, 1] g = [0, 1, 2]",
"of x length binary strings without 11 ending with 1 Let g(x) be",
"1 {01} g(2) = 2 {00, 10} f(x+1) = g(x) {...01} g(x+1) =",
"f(x+1) = g(x) {...01} g(x+1) = f(x) + g(x) {...00, ...10} ans(x) =",
"the numebr of x length binary strings without 11 ending with 0 f(2)",
"+ g(x) {...00, ...10} ans(x) = f(x) + g(x) Time: O(10000), Space: O(10000)",
"M) # print(f[:10]) # print(g[:10]) n = int(input()) for i in range(n): x",
"= g(x) {...01} g(x+1) = f(x) + g(x) {...00, ...10} ans(x) = f(x)",
"be the number of x length binary strings without 11 ending with 1",
"be the numebr of x length binary strings without 11 ending with 0",
"# print(g[:10]) n = int(input()) for i in range(n): x = int(input()) print((f[x]",
"f(2) = 1 {01} g(2) = 2 {00, 10} f(x+1) = g(x) {...01}",
"= [0, 1, 2] for i in range(2,10001): f.append(g[-1]) g.append((g[-1] + f[-2]) %",
"+ g(x) Time: O(10000), Space: O(10000) ''' M = int(1e9 + 7) f",
"= f(x) + g(x) {...00, ...10} ans(x) = f(x) + g(x) Time: O(10000),",
"strings without 11 ending with 1 Let g(x) be the numebr of x",
"g(x) Time: O(10000), Space: O(10000) ''' M = int(1e9 + 7) f =",
"f = [0, 1, 1] g = [0, 1, 2] for i in",
"- anti11 Let f(x) be the number of x length binary strings without",
"x length binary strings without 11 ending with 0 f(2) = 1 {01}",
"strings without 11 ending with 0 f(2) = 1 {01} g(2) = 2",
"with 0 f(2) = 1 {01} g(2) = 2 {00, 10} f(x+1) =",
"1] g = [0, 1, 2] for i in range(2,10001): f.append(g[-1]) g.append((g[-1] +",
"with 1 Let g(x) be the numebr of x length binary strings without",
"numebr of x length binary strings without 11 ending with 0 f(2) =",
"g.append((g[-1] + f[-2]) % M) # print(f[:10]) # print(g[:10]) n = int(input()) for",
"10} f(x+1) = g(x) {...01} g(x+1) = f(x) + g(x) {...00, ...10} ans(x)",
"7) f = [0, 1, 1] g = [0, 1, 2] for i",
"without 11 ending with 1 Let g(x) be the numebr of x length",
"{...00, ...10} ans(x) = f(x) + g(x) Time: O(10000), Space: O(10000) ''' M",
"O(10000), Space: O(10000) ''' M = int(1e9 + 7) f = [0, 1,",
"% M) # print(f[:10]) # print(g[:10]) n = int(input()) for i in range(n):",
"11 ending with 0 f(2) = 1 {01} g(2) = 2 {00, 10}",
"0 f(2) = 1 {01} g(2) = 2 {00, 10} f(x+1) = g(x)",
"= int(1e9 + 7) f = [0, 1, 1] g = [0, 1,",
"Let g(x) be the numebr of x length binary strings without 11 ending",
"g(x) {...00, ...10} ans(x) = f(x) + g(x) Time: O(10000), Space: O(10000) '''",
"= [0, 1, 1] g = [0, 1, 2] for i in range(2,10001):",
"of x length binary strings without 11 ending with 0 f(2) = 1",
"+ 7) f = [0, 1, 1] g = [0, 1, 2] for",
"Space: O(10000) ''' M = int(1e9 + 7) f = [0, 1, 1]",
"11 ending with 1 Let g(x) be the numebr of x length binary",
"x length binary strings without 11 ending with 1 Let g(x) be the",
"g(2) = 2 {00, 10} f(x+1) = g(x) {...01} g(x+1) = f(x) +",
"f.append(g[-1]) g.append((g[-1] + f[-2]) % M) # print(f[:10]) # print(g[:10]) n = int(input())",
"g(x) be the numebr of x length binary strings without 11 ending with",
"f[-2]) % M) # print(f[:10]) # print(g[:10]) n = int(input()) for i in",
"print(g[:10]) n = int(input()) for i in range(n): x = int(input()) print((f[x] +",
"{01} g(2) = 2 {00, 10} f(x+1) = g(x) {...01} g(x+1) = f(x)",
"1 Let g(x) be the numebr of x length binary strings without 11",
"n = int(input()) for i in range(n): x = int(input()) print((f[x] + g[x])%M)",
"g(x) {...01} g(x+1) = f(x) + g(x) {...00, ...10} ans(x) = f(x) +",
"i in range(2,10001): f.append(g[-1]) g.append((g[-1] + f[-2]) % M) # print(f[:10]) # print(g[:10])",
"f(x) + g(x) Time: O(10000), Space: O(10000) ''' M = int(1e9 + 7)",
"ending with 0 f(2) = 1 {01} g(2) = 2 {00, 10} f(x+1)",
"f(x) + g(x) {...00, ...10} ans(x) = f(x) + g(x) Time: O(10000), Space:",
"for i in range(2,10001): f.append(g[-1]) g.append((g[-1] + f[-2]) % M) # print(f[:10]) #",
"without 11 ending with 0 f(2) = 1 {01} g(2) = 2 {00,",
"binary strings without 11 ending with 1 Let g(x) be the numebr of",
"length binary strings without 11 ending with 0 f(2) = 1 {01} g(2)",
"...10} ans(x) = f(x) + g(x) Time: O(10000), Space: O(10000) ''' M =",
"+ f[-2]) % M) # print(f[:10]) # print(g[:10]) n = int(input()) for i",
"ans(x) = f(x) + g(x) Time: O(10000), Space: O(10000) ''' M = int(1e9",
"g = [0, 1, 2] for i in range(2,10001): f.append(g[-1]) g.append((g[-1] + f[-2])",
"O(10000) ''' M = int(1e9 + 7) f = [0, 1, 1] g",
"= f(x) + g(x) Time: O(10000), Space: O(10000) ''' M = int(1e9 +",
"1, 2] for i in range(2,10001): f.append(g[-1]) g.append((g[-1] + f[-2]) % M) #",
"= 1 {01} g(2) = 2 {00, 10} f(x+1) = g(x) {...01} g(x+1)",
"binary strings without 11 ending with 0 f(2) = 1 {01} g(2) =",
"Let f(x) be the number of x length binary strings without 11 ending",
"[0, 1, 1] g = [0, 1, 2] for i in range(2,10001): f.append(g[-1])",
"{...01} g(x+1) = f(x) + g(x) {...00, ...10} ans(x) = f(x) + g(x)"
] |
[
"hackerearth solution def oddOneOut(arr : list) : n = len(arr) arr.sort() summation =",
"+ (n*2))) print(actual_sum) return actual_sum - summation if __name__ == '__main__' : arr",
"one out from hackerearth solution def oddOneOut(arr : list) : n = len(arr)",
"summation = sum(arr) actual_sum = int((n+1)/2 * (2*arr[0] + (n*2))) print(actual_sum) return actual_sum",
"actual_sum - summation if __name__ == '__main__' : arr = list(map(int, input(\"Enter the",
"== '__main__' : arr = list(map(int, input(\"Enter the elements into the array :",
": list) : n = len(arr) arr.sort() summation = sum(arr) actual_sum = int((n+1)/2",
"= sum(arr) actual_sum = int((n+1)/2 * (2*arr[0] + (n*2))) print(actual_sum) return actual_sum -",
"sum(arr) actual_sum = int((n+1)/2 * (2*arr[0] + (n*2))) print(actual_sum) return actual_sum - summation",
"Odd one out from hackerearth solution def oddOneOut(arr : list) : n =",
"= len(arr) arr.sort() summation = sum(arr) actual_sum = int((n+1)/2 * (2*arr[0] + (n*2)))",
"(n*2))) print(actual_sum) return actual_sum - summation if __name__ == '__main__' : arr =",
"'__main__' : arr = list(map(int, input(\"Enter the elements into the array : \").split()))",
"n = len(arr) arr.sort() summation = sum(arr) actual_sum = int((n+1)/2 * (2*arr[0] +",
"def oddOneOut(arr : list) : n = len(arr) arr.sort() summation = sum(arr) actual_sum",
"__name__ == '__main__' : arr = list(map(int, input(\"Enter the elements into the array",
"(2*arr[0] + (n*2))) print(actual_sum) return actual_sum - summation if __name__ == '__main__' :",
"* (2*arr[0] + (n*2))) print(actual_sum) return actual_sum - summation if __name__ == '__main__'",
"out from hackerearth solution def oddOneOut(arr : list) : n = len(arr) arr.sort()",
"len(arr) arr.sort() summation = sum(arr) actual_sum = int((n+1)/2 * (2*arr[0] + (n*2))) print(actual_sum)",
": n = len(arr) arr.sort() summation = sum(arr) actual_sum = int((n+1)/2 * (2*arr[0]",
"oddOneOut(arr : list) : n = len(arr) arr.sort() summation = sum(arr) actual_sum =",
"if __name__ == '__main__' : arr = list(map(int, input(\"Enter the elements into the",
"return actual_sum - summation if __name__ == '__main__' : arr = list(map(int, input(\"Enter",
"actual_sum = int((n+1)/2 * (2*arr[0] + (n*2))) print(actual_sum) return actual_sum - summation if",
"int((n+1)/2 * (2*arr[0] + (n*2))) print(actual_sum) return actual_sum - summation if __name__ ==",
"print(actual_sum) return actual_sum - summation if __name__ == '__main__' : arr = list(map(int,",
": arr = list(map(int, input(\"Enter the elements into the array : \").split())) print(oddOneOut(arr))",
"solution def oddOneOut(arr : list) : n = len(arr) arr.sort() summation = sum(arr)",
"arr.sort() summation = sum(arr) actual_sum = int((n+1)/2 * (2*arr[0] + (n*2))) print(actual_sum) return",
"= int((n+1)/2 * (2*arr[0] + (n*2))) print(actual_sum) return actual_sum - summation if __name__",
"from hackerearth solution def oddOneOut(arr : list) : n = len(arr) arr.sort() summation",
"list) : n = len(arr) arr.sort() summation = sum(arr) actual_sum = int((n+1)/2 *",
"summation if __name__ == '__main__' : arr = list(map(int, input(\"Enter the elements into",
"# Odd one out from hackerearth solution def oddOneOut(arr : list) : n",
"- summation if __name__ == '__main__' : arr = list(map(int, input(\"Enter the elements"
] |
[] |
[
"import PowermeterProfile except: # use stub if powermeter support is not installed from",
"pass Profile.__init__(self, values) self['type'] = 'broker' def __hash__(self): return hash(id(self)) def profile_factory(profile): return",
"== 'wlan': return WlanProfile(profile) if profile['type'] == 'powermeter': return PowermeterProfile(profile) raise Exception('type %s",
"use stub if beryllium support is not installed from wlan import WlanProfile class",
"try: # prefer profile from full installation, if available from ave.positioning.profile import TestDriveProfile",
"use stub if powermeter support is not installed from powermeter import PowermeterProfile try:",
"AB. # All rights, including trade secret rights, reserved. from ave.profile import Profile",
"installed from positioning import TestDriveProfile try: # prefer profile from full installation, if",
"2013 Sony Mobile Communications AB. # All rights, including trade secret rights, reserved.",
"RelayProfile try: # prefer profile from full installation, if available from ave.positioning.profile import",
"# use stub if beryllium support is not installed from beryllium import BerylliumProfile",
"HandsetProfile from ave.workspace import WorkspaceProfile from ave.base_workspace import BaseWorkspaceProfile from ave.relay.profile import RelayProfile",
"BerylliumProfile except: # use stub if beryllium support is not installed from beryllium",
"in profile: raise Exception('profile \"type\" attribute is missing') if profile['type'] == 'workspace': return",
"raise Exception('profile \"type\" attribute is missing') if profile['type'] == 'workspace': return WorkspaceProfile(profile) if",
"# Copyright (C) 2013 Sony Mobile Communications AB. # All rights, including trade",
"'beryllium': return BerylliumProfile(profile) if profile['type'] == 'broker': return BrokerProfile(profile) if profile['type'] == 'testdrive':",
"try: # prefer profile from full installation, if available from ave.powermeter.profile import PowermeterProfile",
"ave.wlan.profile import WlanProfile except: # use stub if beryllium support is not installed",
"trade secret rights, reserved. from ave.profile import Profile from ave.handset.profile import HandsetProfile from",
"BaseWorkspaceProfile from ave.relay.profile import RelayProfile try: # prefer profile from full installation, if",
"self['type'] = 'broker' def __hash__(self): return hash(id(self)) def profile_factory(profile): return factory(profile) def factory(profile):",
"if 'type' not in profile: raise Exception('profile \"type\" attribute is missing') if profile['type']",
"installation, if available from ave.wlan.profile import WlanProfile except: # use stub if beryllium",
"import BaseWorkspaceProfile from ave.relay.profile import RelayProfile try: # prefer profile from full installation,",
"import PowermeterProfile try: # prefer profile from full installation, if available from ave.beryllium.profile",
"from beryllium import BerylliumProfile try: # prefer profile from full installation, if available",
"powermeter support is not installed from powermeter import PowermeterProfile try: # prefer profile",
"profile: raise Exception('profile \"type\" attribute is missing') if profile['type'] == 'workspace': return WorkspaceProfile(profile)",
"== 'broker': return BrokerProfile(profile) if profile['type'] == 'testdrive': return TestDriveProfile(profile) if profile['type'] ==",
"installed from wlan import WlanProfile class BrokerProfile(Profile): def __init__(self, values): try: del values['authkeys']",
"available from ave.positioning.profile import TestDriveProfile except: # use stub if positioning support is",
"import HandsetProfile from ave.workspace import WorkspaceProfile from ave.base_workspace import BaseWorkspaceProfile from ave.relay.profile import",
"ave.beryllium.profile import BerylliumProfile except: # use stub if beryllium support is not installed",
"return WlanProfile(profile) if profile['type'] == 'powermeter': return PowermeterProfile(profile) raise Exception('type %s not supported",
"positioning import TestDriveProfile try: # prefer profile from full installation, if available from",
"from ave.relay.profile import RelayProfile try: # prefer profile from full installation, if available",
"support is not installed from beryllium import BerylliumProfile try: # prefer profile from",
"== 'powermeter': return PowermeterProfile(profile) raise Exception('type %s not supported in profiles' % profile['type'])",
"def __hash__(self): return hash(id(self)) def profile_factory(profile): return factory(profile) def factory(profile): if 'type' not",
"if profile['type'] == 'workspace': return WorkspaceProfile(profile) if profile['type'] == 'handset': return HandsetProfile(profile) if",
"if powermeter support is not installed from powermeter import PowermeterProfile try: # prefer",
"including trade secret rights, reserved. from ave.profile import Profile from ave.handset.profile import HandsetProfile",
"TestDriveProfile except: # use stub if positioning support is not installed from positioning",
"factory(profile): if 'type' not in profile: raise Exception('profile \"type\" attribute is missing') if",
"== 'workspace': return WorkspaceProfile(profile) if profile['type'] == 'handset': return HandsetProfile(profile) if profile['type'] ==",
"ave.handset.profile import HandsetProfile from ave.workspace import WorkspaceProfile from ave.base_workspace import BaseWorkspaceProfile from ave.relay.profile",
"class BrokerProfile(Profile): def __init__(self, values): try: del values['authkeys'] except: pass try: del values['remote']['authkey']",
"if profile['type'] == 'broker': return BrokerProfile(profile) if profile['type'] == 'testdrive': return TestDriveProfile(profile) if",
"del values['authkeys'] except: pass try: del values['remote']['authkey'] except: pass Profile.__init__(self, values) self['type'] =",
"profile['type'] == 'wlan': return WlanProfile(profile) if profile['type'] == 'powermeter': return PowermeterProfile(profile) raise Exception('type",
"== 'relay': return RelayProfile(profile) if profile['type'] == 'beryllium': return BerylliumProfile(profile) if profile['type'] ==",
"support is not installed from wlan import WlanProfile class BrokerProfile(Profile): def __init__(self, values):",
"wlan import WlanProfile class BrokerProfile(Profile): def __init__(self, values): try: del values['authkeys'] except: pass",
"beryllium support is not installed from beryllium import BerylliumProfile try: # prefer profile",
"profile['type'] == 'broker': return BrokerProfile(profile) if profile['type'] == 'testdrive': return TestDriveProfile(profile) if profile['type']",
"# All rights, including trade secret rights, reserved. from ave.profile import Profile from",
"from full installation, if available from ave.beryllium.profile import BerylliumProfile except: # use stub",
"WlanProfile(profile) if profile['type'] == 'powermeter': return PowermeterProfile(profile) raise Exception('type %s not supported in",
"installation, if available from ave.positioning.profile import TestDriveProfile except: # use stub if positioning",
"import WlanProfile except: # use stub if beryllium support is not installed from",
"# prefer profile from full installation, if available from ave.wlan.profile import WlanProfile except:",
"profile['type'] == 'relay': return RelayProfile(profile) if profile['type'] == 'beryllium': return BerylliumProfile(profile) if profile['type']",
"prefer profile from full installation, if available from ave.positioning.profile import TestDriveProfile except: #",
"import TestDriveProfile try: # prefer profile from full installation, if available from ave.powermeter.profile",
"from ave.beryllium.profile import BerylliumProfile except: # use stub if beryllium support is not",
"if profile['type'] == 'handset': return HandsetProfile(profile) if profile['type'] == 'relay': return RelayProfile(profile) if",
"import BerylliumProfile try: # prefer profile from full installation, if available from ave.wlan.profile",
"'relay': return RelayProfile(profile) if profile['type'] == 'beryllium': return BerylliumProfile(profile) if profile['type'] == 'broker':",
"return WorkspaceProfile(profile) if profile['type'] == 'handset': return HandsetProfile(profile) if profile['type'] == 'relay': return",
"is not installed from beryllium import BerylliumProfile try: # prefer profile from full",
"use stub if positioning support is not installed from positioning import TestDriveProfile try:",
"if available from ave.positioning.profile import TestDriveProfile except: # use stub if positioning support",
"except: pass try: del values['remote']['authkey'] except: pass Profile.__init__(self, values) self['type'] = 'broker' def",
"BerylliumProfile try: # prefer profile from full installation, if available from ave.wlan.profile import",
"return TestDriveProfile(profile) if profile['type'] == 'wlan': return WlanProfile(profile) if profile['type'] == 'powermeter': return",
"rights, including trade secret rights, reserved. from ave.profile import Profile from ave.handset.profile import",
"secret rights, reserved. from ave.profile import Profile from ave.handset.profile import HandsetProfile from ave.workspace",
"from ave.powermeter.profile import PowermeterProfile except: # use stub if powermeter support is not",
"__hash__(self): return hash(id(self)) def profile_factory(profile): return factory(profile) def factory(profile): if 'type' not in",
"return BerylliumProfile(profile) if profile['type'] == 'broker': return BrokerProfile(profile) if profile['type'] == 'testdrive': return",
"reserved. from ave.profile import Profile from ave.handset.profile import HandsetProfile from ave.workspace import WorkspaceProfile",
"if profile['type'] == 'relay': return RelayProfile(profile) if profile['type'] == 'beryllium': return BerylliumProfile(profile) if",
"stub if positioning support is not installed from positioning import TestDriveProfile try: #",
"ave.positioning.profile import TestDriveProfile except: # use stub if positioning support is not installed",
"= 'broker' def __hash__(self): return hash(id(self)) def profile_factory(profile): return factory(profile) def factory(profile): if",
"profile['type'] == 'powermeter': return PowermeterProfile(profile) raise Exception('type %s not supported in profiles' %",
"WlanProfile class BrokerProfile(Profile): def __init__(self, values): try: del values['authkeys'] except: pass try: del",
"values['remote']['authkey'] except: pass Profile.__init__(self, values) self['type'] = 'broker' def __hash__(self): return hash(id(self)) def",
"def profile_factory(profile): return factory(profile) def factory(profile): if 'type' not in profile: raise Exception('profile",
"return BrokerProfile(profile) if profile['type'] == 'testdrive': return TestDriveProfile(profile) if profile['type'] == 'wlan': return",
"return factory(profile) def factory(profile): if 'type' not in profile: raise Exception('profile \"type\" attribute",
"from full installation, if available from ave.wlan.profile import WlanProfile except: # use stub",
"profile['type'] == 'testdrive': return TestDriveProfile(profile) if profile['type'] == 'wlan': return WlanProfile(profile) if profile['type']",
"missing') if profile['type'] == 'workspace': return WorkspaceProfile(profile) if profile['type'] == 'handset': return HandsetProfile(profile)",
"'handset': return HandsetProfile(profile) if profile['type'] == 'relay': return RelayProfile(profile) if profile['type'] == 'beryllium':",
"profile['type'] == 'beryllium': return BerylliumProfile(profile) if profile['type'] == 'broker': return BrokerProfile(profile) if profile['type']",
"if positioning support is not installed from positioning import TestDriveProfile try: # prefer",
"if beryllium support is not installed from beryllium import BerylliumProfile try: # prefer",
"# prefer profile from full installation, if available from ave.beryllium.profile import BerylliumProfile except:",
"support is not installed from powermeter import PowermeterProfile try: # prefer profile from",
"from ave.positioning.profile import TestDriveProfile except: # use stub if positioning support is not",
"profile from full installation, if available from ave.powermeter.profile import PowermeterProfile except: # use",
"'testdrive': return TestDriveProfile(profile) if profile['type'] == 'wlan': return WlanProfile(profile) if profile['type'] == 'powermeter':",
"except: # use stub if powermeter support is not installed from powermeter import",
"profile_factory(profile): return factory(profile) def factory(profile): if 'type' not in profile: raise Exception('profile \"type\"",
"if available from ave.powermeter.profile import PowermeterProfile except: # use stub if powermeter support",
"factory(profile) def factory(profile): if 'type' not in profile: raise Exception('profile \"type\" attribute is",
"available from ave.wlan.profile import WlanProfile except: # use stub if beryllium support is",
"del values['remote']['authkey'] except: pass Profile.__init__(self, values) self['type'] = 'broker' def __hash__(self): return hash(id(self))",
"Copyright (C) 2013 Sony Mobile Communications AB. # All rights, including trade secret",
"import WorkspaceProfile from ave.base_workspace import BaseWorkspaceProfile from ave.relay.profile import RelayProfile try: # prefer",
"HandsetProfile(profile) if profile['type'] == 'relay': return RelayProfile(profile) if profile['type'] == 'beryllium': return BerylliumProfile(profile)",
"if available from ave.wlan.profile import WlanProfile except: # use stub if beryllium support",
"available from ave.powermeter.profile import PowermeterProfile except: # use stub if powermeter support is",
"installed from beryllium import BerylliumProfile try: # prefer profile from full installation, if",
"full installation, if available from ave.positioning.profile import TestDriveProfile except: # use stub if",
"from full installation, if available from ave.powermeter.profile import PowermeterProfile except: # use stub",
"__init__(self, values): try: del values['authkeys'] except: pass try: del values['remote']['authkey'] except: pass Profile.__init__(self,",
"from positioning import TestDriveProfile try: # prefer profile from full installation, if available",
"beryllium support is not installed from wlan import WlanProfile class BrokerProfile(Profile): def __init__(self,",
"beryllium import BerylliumProfile try: # prefer profile from full installation, if available from",
"import RelayProfile try: # prefer profile from full installation, if available from ave.positioning.profile",
"WlanProfile except: # use stub if beryllium support is not installed from wlan",
"PowermeterProfile try: # prefer profile from full installation, if available from ave.beryllium.profile import",
"try: del values['remote']['authkey'] except: pass Profile.__init__(self, values) self['type'] = 'broker' def __hash__(self): return",
"if beryllium support is not installed from wlan import WlanProfile class BrokerProfile(Profile): def",
"not in profile: raise Exception('profile \"type\" attribute is missing') if profile['type'] == 'workspace':",
"not installed from wlan import WlanProfile class BrokerProfile(Profile): def __init__(self, values): try: del",
"'broker': return BrokerProfile(profile) if profile['type'] == 'testdrive': return TestDriveProfile(profile) if profile['type'] == 'wlan':",
"# use stub if positioning support is not installed from positioning import TestDriveProfile",
"== 'beryllium': return BerylliumProfile(profile) if profile['type'] == 'broker': return BrokerProfile(profile) if profile['type'] ==",
"'wlan': return WlanProfile(profile) if profile['type'] == 'powermeter': return PowermeterProfile(profile) raise Exception('type %s not",
"profile from full installation, if available from ave.wlan.profile import WlanProfile except: # use",
"def __init__(self, values): try: del values['authkeys'] except: pass try: del values['remote']['authkey'] except: pass",
"try: del values['authkeys'] except: pass try: del values['remote']['authkey'] except: pass Profile.__init__(self, values) self['type']",
"profile from full installation, if available from ave.beryllium.profile import BerylliumProfile except: # use",
"Exception('profile \"type\" attribute is missing') if profile['type'] == 'workspace': return WorkspaceProfile(profile) if profile['type']",
"is missing') if profile['type'] == 'workspace': return WorkspaceProfile(profile) if profile['type'] == 'handset': return",
"profile from full installation, if available from ave.positioning.profile import TestDriveProfile except: # use",
"values) self['type'] = 'broker' def __hash__(self): return hash(id(self)) def profile_factory(profile): return factory(profile) def",
"profile['type'] == 'workspace': return WorkspaceProfile(profile) if profile['type'] == 'handset': return HandsetProfile(profile) if profile['type']",
"BerylliumProfile(profile) if profile['type'] == 'broker': return BrokerProfile(profile) if profile['type'] == 'testdrive': return TestDriveProfile(profile)",
"if profile['type'] == 'testdrive': return TestDriveProfile(profile) if profile['type'] == 'wlan': return WlanProfile(profile) if",
"pass try: del values['remote']['authkey'] except: pass Profile.__init__(self, values) self['type'] = 'broker' def __hash__(self):",
"if profile['type'] == 'powermeter': return PowermeterProfile(profile) raise Exception('type %s not supported in profiles'",
"if profile['type'] == 'beryllium': return BerylliumProfile(profile) if profile['type'] == 'broker': return BrokerProfile(profile) if",
"ave.workspace import WorkspaceProfile from ave.base_workspace import BaseWorkspaceProfile from ave.relay.profile import RelayProfile try: #",
"is not installed from wlan import WlanProfile class BrokerProfile(Profile): def __init__(self, values): try:",
"try: # prefer profile from full installation, if available from ave.beryllium.profile import BerylliumProfile",
"installed from powermeter import PowermeterProfile try: # prefer profile from full installation, if",
"Profile from ave.handset.profile import HandsetProfile from ave.workspace import WorkspaceProfile from ave.base_workspace import BaseWorkspaceProfile",
"import WlanProfile class BrokerProfile(Profile): def __init__(self, values): try: del values['authkeys'] except: pass try:",
"== 'testdrive': return TestDriveProfile(profile) if profile['type'] == 'wlan': return WlanProfile(profile) if profile['type'] ==",
"WorkspaceProfile from ave.base_workspace import BaseWorkspaceProfile from ave.relay.profile import RelayProfile try: # prefer profile",
"stub if beryllium support is not installed from beryllium import BerylliumProfile try: #",
"attribute is missing') if profile['type'] == 'workspace': return WorkspaceProfile(profile) if profile['type'] == 'handset':",
"full installation, if available from ave.powermeter.profile import PowermeterProfile except: # use stub if",
"use stub if beryllium support is not installed from beryllium import BerylliumProfile try:",
"support is not installed from positioning import TestDriveProfile try: # prefer profile from",
"Mobile Communications AB. # All rights, including trade secret rights, reserved. from ave.profile",
"ave.base_workspace import BaseWorkspaceProfile from ave.relay.profile import RelayProfile try: # prefer profile from full",
"import Profile from ave.handset.profile import HandsetProfile from ave.workspace import WorkspaceProfile from ave.base_workspace import",
"prefer profile from full installation, if available from ave.powermeter.profile import PowermeterProfile except: #",
"Profile.__init__(self, values) self['type'] = 'broker' def __hash__(self): return hash(id(self)) def profile_factory(profile): return factory(profile)",
"WorkspaceProfile(profile) if profile['type'] == 'handset': return HandsetProfile(profile) if profile['type'] == 'relay': return RelayProfile(profile)",
"# use stub if beryllium support is not installed from wlan import WlanProfile",
"try: # prefer profile from full installation, if available from ave.wlan.profile import WlanProfile",
"def factory(profile): if 'type' not in profile: raise Exception('profile \"type\" attribute is missing')",
"from ave.profile import Profile from ave.handset.profile import HandsetProfile from ave.workspace import WorkspaceProfile from",
"except: pass Profile.__init__(self, values) self['type'] = 'broker' def __hash__(self): return hash(id(self)) def profile_factory(profile):",
"'workspace': return WorkspaceProfile(profile) if profile['type'] == 'handset': return HandsetProfile(profile) if profile['type'] == 'relay':",
"# prefer profile from full installation, if available from ave.powermeter.profile import PowermeterProfile except:",
"not installed from positioning import TestDriveProfile try: # prefer profile from full installation,",
"'broker' def __hash__(self): return hash(id(self)) def profile_factory(profile): return factory(profile) def factory(profile): if 'type'",
"hash(id(self)) def profile_factory(profile): return factory(profile) def factory(profile): if 'type' not in profile: raise",
"(C) 2013 Sony Mobile Communications AB. # All rights, including trade secret rights,",
"not installed from powermeter import PowermeterProfile try: # prefer profile from full installation,",
"return hash(id(self)) def profile_factory(profile): return factory(profile) def factory(profile): if 'type' not in profile:",
"Sony Mobile Communications AB. # All rights, including trade secret rights, reserved. from",
"full installation, if available from ave.wlan.profile import WlanProfile except: # use stub if",
"rights, reserved. from ave.profile import Profile from ave.handset.profile import HandsetProfile from ave.workspace import",
"stub if beryllium support is not installed from wlan import WlanProfile class BrokerProfile(Profile):",
"from ave.handset.profile import HandsetProfile from ave.workspace import WorkspaceProfile from ave.base_workspace import BaseWorkspaceProfile from",
"RelayProfile(profile) if profile['type'] == 'beryllium': return BerylliumProfile(profile) if profile['type'] == 'broker': return BrokerProfile(profile)",
"import TestDriveProfile except: # use stub if positioning support is not installed from",
"'type' not in profile: raise Exception('profile \"type\" attribute is missing') if profile['type'] ==",
"ave.relay.profile import RelayProfile try: # prefer profile from full installation, if available from",
"from ave.workspace import WorkspaceProfile from ave.base_workspace import BaseWorkspaceProfile from ave.relay.profile import RelayProfile try:",
"TestDriveProfile try: # prefer profile from full installation, if available from ave.powermeter.profile import",
"prefer profile from full installation, if available from ave.beryllium.profile import BerylliumProfile except: #",
"== 'handset': return HandsetProfile(profile) if profile['type'] == 'relay': return RelayProfile(profile) if profile['type'] ==",
"return HandsetProfile(profile) if profile['type'] == 'relay': return RelayProfile(profile) if profile['type'] == 'beryllium': return",
"not installed from beryllium import BerylliumProfile try: # prefer profile from full installation,",
"ave.profile import Profile from ave.handset.profile import HandsetProfile from ave.workspace import WorkspaceProfile from ave.base_workspace",
"ave.powermeter.profile import PowermeterProfile except: # use stub if powermeter support is not installed",
"if available from ave.beryllium.profile import BerylliumProfile except: # use stub if beryllium support",
"from full installation, if available from ave.positioning.profile import TestDriveProfile except: # use stub",
"available from ave.beryllium.profile import BerylliumProfile except: # use stub if beryllium support is",
"except: # use stub if beryllium support is not installed from beryllium import",
"prefer profile from full installation, if available from ave.wlan.profile import WlanProfile except: #",
"installation, if available from ave.beryllium.profile import BerylliumProfile except: # use stub if beryllium",
"profile['type'] == 'handset': return HandsetProfile(profile) if profile['type'] == 'relay': return RelayProfile(profile) if profile['type']",
"is not installed from positioning import TestDriveProfile try: # prefer profile from full",
"except: # use stub if beryllium support is not installed from wlan import",
"from ave.wlan.profile import WlanProfile except: # use stub if beryllium support is not",
"from wlan import WlanProfile class BrokerProfile(Profile): def __init__(self, values): try: del values['authkeys'] except:",
"\"type\" attribute is missing') if profile['type'] == 'workspace': return WorkspaceProfile(profile) if profile['type'] ==",
"powermeter import PowermeterProfile try: # prefer profile from full installation, if available from",
"return RelayProfile(profile) if profile['type'] == 'beryllium': return BerylliumProfile(profile) if profile['type'] == 'broker': return",
"full installation, if available from ave.beryllium.profile import BerylliumProfile except: # use stub if",
"values): try: del values['authkeys'] except: pass try: del values['remote']['authkey'] except: pass Profile.__init__(self, values)",
"from powermeter import PowermeterProfile try: # prefer profile from full installation, if available",
"values['authkeys'] except: pass try: del values['remote']['authkey'] except: pass Profile.__init__(self, values) self['type'] = 'broker'",
"Communications AB. # All rights, including trade secret rights, reserved. from ave.profile import",
"positioning support is not installed from positioning import TestDriveProfile try: # prefer profile",
"if profile['type'] == 'wlan': return WlanProfile(profile) if profile['type'] == 'powermeter': return PowermeterProfile(profile) raise",
"stub if powermeter support is not installed from powermeter import PowermeterProfile try: #",
"BrokerProfile(Profile): def __init__(self, values): try: del values['authkeys'] except: pass try: del values['remote']['authkey'] except:",
"from ave.base_workspace import BaseWorkspaceProfile from ave.relay.profile import RelayProfile try: # prefer profile from",
"except: # use stub if positioning support is not installed from positioning import",
"TestDriveProfile(profile) if profile['type'] == 'wlan': return WlanProfile(profile) if profile['type'] == 'powermeter': return PowermeterProfile(profile)",
"All rights, including trade secret rights, reserved. from ave.profile import Profile from ave.handset.profile",
"# use stub if powermeter support is not installed from powermeter import PowermeterProfile",
"import BerylliumProfile except: # use stub if beryllium support is not installed from",
"installation, if available from ave.powermeter.profile import PowermeterProfile except: # use stub if powermeter",
"PowermeterProfile except: # use stub if powermeter support is not installed from powermeter",
"# prefer profile from full installation, if available from ave.positioning.profile import TestDriveProfile except:",
"is not installed from powermeter import PowermeterProfile try: # prefer profile from full",
"BrokerProfile(profile) if profile['type'] == 'testdrive': return TestDriveProfile(profile) if profile['type'] == 'wlan': return WlanProfile(profile)"
] |
[
"parameters act, act_param, _, _ = self.agent.act(obs) action = offense_mid_action(act, act_param) while not",
"== 'CAPTURED_BY_DEFENSE' timesteps.append(t) returns.append(episode_reward) goals.append(goal) captureds.append(captured) evaluation_results = np.column_stack((returns, timesteps, goals, captureds)) avg_returns,",
"< self.episodes + 1 for i in range(self.start + self.save_freq, self.start + self.episodes",
"as in redis_manager) self.all_agents = list(self.redis_instance.smembers('teammates')) self.all_agents.sort() start_time = time.time() print(\"Evaluating self.agent over",
"default=20000) parser.add_argument('--eval-episodes', type=int, default=1000) parser.add_argument('--save-freq', type=int, default=500) parser.add_argument('--tensorboard-dir', type=str, default=\".\") parser.add_argument('--save-dir', type=str, default=\".\")",
"i) for j in range(self.eval_episodes): info = {'status': \"NOT_SET\"} # initialize environment and",
"act_param) while not terminal: t += 1 next_obs, reward, terminal, info = self.env.step(action)",
"= next_action episode_reward += reward goal = info['status'] == 'GOAL' captured = info['status']",
"captureds.append(captured) evaluation_results = np.column_stack((returns, timesteps, goals, captureds)) avg_returns, avg_timesteps, avg_goal_timesteps, avg_goal_prob, avg_captured_prob =",
"Random seed # self.seed += 10000 * proc_id() torch.manual_seed(self.seed) np.random.seed(self.seed) # later can",
"type=int, default=6000) parser.add_argument('--episodes', type=int, default=20000) parser.add_argument('--eval-episodes', type=int, default=1000) parser.add_argument('--save-freq', type=int, default=500) parser.add_argument('--tensorboard-dir', type=str,",
"dtype=np.float32, copy=False) # get discrete action and continuous parameters next_act, next_act_param, _, _",
"log_results(self, evaluation_results, i): num_results = evaluation_results.shape[0] total_returns = sum(evaluation_results[:, 0]) total_timesteps = sum(evaluation_results[:,",
"copy=False) # get discrete action and continuous parameters next_act, next_act_param, _, _ =",
"episode_reward += reward goal = info['status'] == 'GOAL' captured = info['status'] == 'CAPTURED_BY_DEFENSE'",
"avg_captured_prob = total_captured / num_results print(\"Avg. evaluation return =\", avg_returns) print(\"Avg. timesteps =\",",
"dtype=np.float32, copy=False) episode_reward = 0. terminal = False t = 0 # get",
"avg_goal_prob, avg_captured_prob def run(self): # Random seed # self.seed += 10000 * proc_id()",
"prob.\", avg_goal_prob, i) self.writer.add_scalar(\"Avg. timesteps per goal\", avg_goal_timesteps, i) self.writer.add_scalar(\"Avg. captured prob.\", avg_captured_prob,",
"default=\".\") parser.add_argument('--save-dir', type=str, default=\".\") parser.add_argument('--start', type=int, default=0) args = parser.parse_args() evaluator = Evaluator(agent_type=args.agent_type,",
"/ num_results avg_goal_prob = total_goal / num_results avg_captured_prob = total_captured / num_results print(\"Avg.",
"can sort by approximity (need to be same as in redis_manager) self.all_agents =",
"2]) total_captured = sum(evaluation_results[:, 3]) avg_returns = total_returns / num_results avg_timesteps = total_timesteps",
"while not terminal: t += 1 next_obs, reward, terminal, info = self.env.step(action) next_obs",
"/ num_results avg_captured_prob = total_captured / num_results print(\"Avg. evaluation return =\", avg_returns) print(\"Avg.",
"self.save_freq, self.start + self.episodes + 1, self.save_freq): # load model returns = []",
"next_action episode_reward += reward goal = info['status'] == 'GOAL' captured = info['status'] ==",
"by approximity (need to be same as in redis_manager) self.all_agents = list(self.redis_instance.smembers('teammates')) self.all_agents.sort()",
"import torch from agents.random_agent import RandomAgent from agents.pddpg_agent import PDDPGAgent from agents.mapddpg_agent import",
"+= 1 next_obs, reward, terminal, info = self.env.step(action) next_obs = np.array(next_obs, dtype=np.float32, copy=False)",
"and continuous parameters next_act, next_act_param, _, _ = self.agent.act(next_obs) next_action = offense_mid_action(next_act, next_act_param)",
"self.episodes + 1, self.save_freq): # load model returns = [] timesteps = []",
"next_act_param, _, _ = self.agent.act(next_obs) next_action = offense_mid_action(next_act, next_act_param) action = next_action episode_reward",
"'offense': self.writer.add_scalar(\"Avg. goal prob.\", avg_goal_prob, i) self.writer.add_scalar(\"Avg. timesteps per goal\", avg_goal_timesteps, i) self.writer.add_scalar(\"Avg.",
"(end_time - start_time)) return avg_returns, avg_timesteps, avg_goal_timesteps, avg_goal_prob, avg_captured_prob if __name__ == '__main__':",
"and reward obs = self.env.reset() obs = np.array(obs, dtype=np.float32, copy=False) episode_reward = 0.",
"0. self.agent.noise = None # PDDPG and MAPDDPG evaluation if isinstance(self.agent, PDDPGAgent): #",
"obs = np.array(obs, dtype=np.float32, copy=False) episode_reward = 0. terminal = False t =",
"lose prob.\", avg_goal_prob, i) self.writer.add_scalar(\"Avg. capture prob.\", avg_captured_prob / (1 + avg_goal_prob), i)",
"= argparse.ArgumentParser() parser.add_argument('--agent-type', type=str, default='PDDPG') parser.add_argument('--player', type=str, default='offense') parser.add_argument('--seed', type=int, default=0) parser.add_argument('--server-port', type=int,",
"avg_goal_prob, avg_captured_prob if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('--agent-type', type=str, default='PDDPG') parser.add_argument('--player',",
"total_captured / num_results print(\"Avg. evaluation return =\", avg_returns) print(\"Avg. timesteps =\", avg_timesteps) if",
"isinstance(self.agent, PDDPGAgent): # main loop assert self.save_freq < self.episodes + 1 for i",
"parser = argparse.ArgumentParser() parser.add_argument('--agent-type', type=str, default='PDDPG') parser.add_argument('--player', type=str, default='offense') parser.add_argument('--seed', type=int, default=0) parser.add_argument('--server-port',",
"parser.add_argument('--server-port', type=int, default=6000) parser.add_argument('--episodes', type=int, default=20000) parser.add_argument('--eval-episodes', type=int, default=1000) parser.add_argument('--save-freq', type=int, default=500) parser.add_argument('--tensorboard-dir',",
"amount=1) # to act nearly synchronously while int(evaluator.redis_instance.get('not ready')) > 0: print('\\rNumber of",
"connect_redis, query_all_obs_actions, sync_agent_obs_actions, sync_agent_policy import logging class Evaluator(Learner): def __init__(self, agent_type, tensorboard_dir, save_dir=\".\",",
"self.writer.add_scalar('Avg. evaluation return', avg_returns, i) self.writer.add_scalar('Avg. timesteps', avg_timesteps, i) if self.player == 'offense':",
"utils.redis_manager import connect_redis, query_all_obs_actions, sync_agent_obs_actions, sync_agent_policy import logging class Evaluator(Learner): def __init__(self, agent_type,",
"import Learner import os import argparse import time import numpy as np import",
"RandomAgent from agents.pddpg_agent import PDDPGAgent from agents.mapddpg_agent import MAPDDPGAgent from envs import offense_mid_action",
"parameters next_act, next_act_param, _, _ = self.agent.act(next_obs) next_action = offense_mid_action(next_act, next_act_param) action =",
"eval_episodes=args.eval_episodes, save_freq=args.save_freq) evaluator.redis_instance.decr('not ready', amount=1) # to act nearly synchronously while int(evaluator.redis_instance.get('not ready'))",
"def __init__(self, agent_type, tensorboard_dir, save_dir=\".\", player='offense', save_freq=500, seed=1, episodes=50, server_port=6000, eval_episodes=1000, start=0): super(Evaluator,",
"while int(evaluator.redis_instance.get('not ready')) > 0: print('\\rNumber of not ready learners:', evaluator.redis_instance.get('not ready'), end='')",
"= [] self.load_model(self.save_dir, i) for j in range(self.eval_episodes): info = {'status': \"NOT_SET\"} #",
"sort by approximity (need to be same as in redis_manager) self.all_agents = list(self.redis_instance.smembers('teammates'))",
"= sum(goal_timesteps) / num_results avg_goal_prob = total_goal / num_results avg_captured_prob = total_captured /",
"argparse import time import numpy as np import torch from agents.random_agent import RandomAgent",
"avg_captured_prob = \\ self.log_results(evaluation_results, i) end_time = time.time() print(\"Evaluation time: %.2f seconds\" %",
"1 for i in range(self.start + self.save_freq, self.start + self.episodes + 1, self.save_freq):",
"continuous parameters act, act_param, _, _ = self.agent.act(obs) action = offense_mid_action(act, act_param) while",
"self.player == 'offense': self.writer.add_scalar(\"Avg. goal prob.\", avg_goal_prob, i) self.writer.add_scalar(\"Avg. timesteps per goal\", avg_goal_timesteps,",
"avg_timesteps = total_timesteps / num_results avg_goal_timesteps = sum(goal_timesteps) / num_results avg_goal_prob = total_goal",
"avg_goal_prob, avg_captured_prob = \\ self.log_results(evaluation_results, i) end_time = time.time() print(\"Evaluation time: %.2f seconds\"",
"import os import argparse import time import numpy as np import torch from",
"# Random seed # self.seed += 10000 * proc_id() torch.manual_seed(self.seed) np.random.seed(self.seed) # later",
"=\", avg_returns) print(\"Avg. timesteps =\", avg_timesteps) if self.player == 'offense': print(\"Avg. goal prob.",
"start_time = time.time() print(\"Evaluating self.agent over {} episodes\".format(self.episodes)) self.agent.epsilon_final = 0. self.agent.epsilon =",
"num_results avg_goal_prob = total_goal / num_results avg_captured_prob = total_captured / num_results print(\"Avg. evaluation",
"over {} episodes\".format(self.episodes)) self.agent.epsilon_final = 0. self.agent.epsilon = 0. self.agent.noise = None #",
"1][evaluation_results[:, 2] == 1] total_goal = sum(evaluation_results[:, 2]) total_captured = sum(evaluation_results[:, 3]) avg_returns",
"import logging class Evaluator(Learner): def __init__(self, agent_type, tensorboard_dir, save_dir=\".\", player='offense', save_freq=500, seed=1, episodes=50,",
"+ avg_goal_prob), i) return avg_returns, avg_timesteps, avg_goal_timesteps, avg_goal_prob, avg_captured_prob def run(self): # Random",
"avg_captured_prob, i) elif self.player == 'goalie': self.writer.add_scalar(\"Avg. lose prob.\", avg_goal_prob, i) self.writer.add_scalar(\"Avg. capture",
"num_results print(\"Avg. evaluation return =\", avg_returns) print(\"Avg. timesteps =\", avg_timesteps) if self.player ==",
"self.load_model(self.save_dir, i) for j in range(self.eval_episodes): info = {'status': \"NOT_SET\"} # initialize environment",
"next_obs = np.array(next_obs, dtype=np.float32, copy=False) # get discrete action and continuous parameters next_act,",
"= sum(evaluation_results[:, 1]) goal_timesteps = evaluation_results[:, 1][evaluation_results[:, 2] == 1] total_goal = sum(evaluation_results[:,",
"def log_results(self, evaluation_results, i): num_results = evaluation_results.shape[0] total_returns = sum(evaluation_results[:, 0]) total_timesteps =",
"self.log_results(evaluation_results, i) end_time = time.time() print(\"Evaluation time: %.2f seconds\" % (end_time - start_time))",
"= parser.parse_args() evaluator = Evaluator(agent_type=args.agent_type, player=args.player, seed=args.seed, episodes=args.episodes, server_port=args.server_port, tensorboard_dir=args.tensorboard_dir, start=args.start, save_dir=args.save_dir, eval_episodes=args.eval_episodes,",
"avg_captured_prob if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('--agent-type', type=str, default='PDDPG') parser.add_argument('--player', type=str,",
"=\", avg_captured_prob / (1 + avg_goal_prob)) self.writer.add_scalar('Avg. evaluation return', avg_returns, i) self.writer.add_scalar('Avg. timesteps',",
"= [] goals = [] captureds = [] self.load_model(self.save_dir, i) for j in",
"i) elif self.player == 'goalie': self.writer.add_scalar(\"Avg. lose prob.\", avg_goal_prob, i) self.writer.add_scalar(\"Avg. capture prob.\",",
"== 'GOAL' captured = info['status'] == 'CAPTURED_BY_DEFENSE' timesteps.append(t) returns.append(episode_reward) goals.append(goal) captureds.append(captured) evaluation_results =",
"episode_reward = 0. terminal = False t = 0 # get discrete action",
"self.writer.add_scalar(\"Avg. lose prob.\", avg_goal_prob, i) self.writer.add_scalar(\"Avg. capture prob.\", avg_captured_prob / (1 + avg_goal_prob),",
"self).__init__(agent_type=agent_type, tensorboard_dir=tensorboard_dir, save_dir=save_dir, player=player, seed=seed, episodes=episodes, start=start, server_port=server_port, save_freq=save_freq) self.player = player self.eval_episodes",
"action and continuous parameters act, act_param, _, _ = self.agent.act(obs) action = offense_mid_action(act,",
"environment and reward obs = self.env.reset() obs = np.array(obs, dtype=np.float32, copy=False) episode_reward =",
"evaluator = Evaluator(agent_type=args.agent_type, player=args.player, seed=args.seed, episodes=args.episodes, server_port=args.server_port, tensorboard_dir=args.tensorboard_dir, start=args.start, save_dir=args.save_dir, eval_episodes=args.eval_episodes, save_freq=args.save_freq) evaluator.redis_instance.decr('not",
"for j in range(self.eval_episodes): info = {'status': \"NOT_SET\"} # initialize environment and reward",
"to act nearly synchronously while int(evaluator.redis_instance.get('not ready')) > 0: print('\\rNumber of not ready",
"copy=False) episode_reward = 0. terminal = False t = 0 # get discrete",
"elif self.player == 'goalie': print(\"Avg. lose prob. =\", avg_goal_prob) print(\"Avg. capture prob. =\",",
"i) self.writer.add_scalar('Avg. timesteps', avg_timesteps, i) if self.player == 'offense': self.writer.add_scalar(\"Avg. goal prob.\", avg_goal_prob,",
"type=str, default=\".\") parser.add_argument('--start', type=int, default=0) args = parser.parse_args() evaluator = Evaluator(agent_type=args.agent_type, player=args.player, seed=args.seed,",
"sum(evaluation_results[:, 2]) total_captured = sum(evaluation_results[:, 3]) avg_returns = total_returns / num_results avg_timesteps =",
"avg_captured_prob / (1 + avg_goal_prob)) self.writer.add_scalar('Avg. evaluation return', avg_returns, i) self.writer.add_scalar('Avg. timesteps', avg_timesteps,",
"total_returns / num_results avg_timesteps = total_timesteps / num_results avg_goal_timesteps = sum(goal_timesteps) / num_results",
"print(\"Avg. timesteps =\", avg_timesteps) if self.player == 'offense': print(\"Avg. goal prob. =\", avg_goal_prob)",
"=\", avg_timesteps) if self.player == 'offense': print(\"Avg. goal prob. =\", avg_goal_prob) print(\"Avg. timesteps",
"return avg_returns, avg_timesteps, avg_goal_timesteps, avg_goal_prob, avg_captured_prob def run(self): # Random seed # self.seed",
"reward, terminal, info = self.env.step(action) next_obs = np.array(next_obs, dtype=np.float32, copy=False) # get discrete",
"PDDPGAgent from agents.mapddpg_agent import MAPDDPGAgent from envs import offense_mid_action from utils.redis_manager import connect_redis,",
"self.eval_episodes = eval_episodes def log_results(self, evaluation_results, i): num_results = evaluation_results.shape[0] total_returns = sum(evaluation_results[:,",
"logging class Evaluator(Learner): def __init__(self, agent_type, tensorboard_dir, save_dir=\".\", player='offense', save_freq=500, seed=1, episodes=50, server_port=6000,",
"class Evaluator(Learner): def __init__(self, agent_type, tensorboard_dir, save_dir=\".\", player='offense', save_freq=500, seed=1, episodes=50, server_port=6000, eval_episodes=1000,",
"self.env.step(action) next_obs = np.array(next_obs, dtype=np.float32, copy=False) # get discrete action and continuous parameters",
"self.writer.add_scalar(\"Avg. goal prob.\", avg_goal_prob, i) self.writer.add_scalar(\"Avg. timesteps per goal\", avg_goal_timesteps, i) self.writer.add_scalar(\"Avg. captured",
"print(\"Avg. lose prob. =\", avg_goal_prob) print(\"Avg. capture prob. =\", avg_captured_prob / (1 +",
"# main loop assert self.save_freq < self.episodes + 1 for i in range(self.start",
"obs = self.env.reset() obs = np.array(obs, dtype=np.float32, copy=False) episode_reward = 0. terminal =",
"i) end_time = time.time() print(\"Evaluation time: %.2f seconds\" % (end_time - start_time)) return",
"and continuous parameters act, act_param, _, _ = self.agent.act(obs) action = offense_mid_action(act, act_param)",
"returns.append(episode_reward) goals.append(goal) captureds.append(captured) evaluation_results = np.column_stack((returns, timesteps, goals, captureds)) avg_returns, avg_timesteps, avg_goal_timesteps, avg_goal_prob,",
"evaluation if isinstance(self.agent, PDDPGAgent): # main loop assert self.save_freq < self.episodes + 1",
"capture prob. =\", avg_captured_prob / (1 + avg_goal_prob)) self.writer.add_scalar('Avg. evaluation return', avg_returns, i)",
"t = 0 # get discrete action and continuous parameters act, act_param, _,",
"if self.player == 'offense': print(\"Avg. goal prob. =\", avg_goal_prob) print(\"Avg. timesteps per goal",
"t += 1 next_obs, reward, terminal, info = self.env.step(action) next_obs = np.array(next_obs, dtype=np.float32,",
"avg_returns, avg_timesteps, avg_goal_timesteps, avg_goal_prob, avg_captured_prob = \\ self.log_results(evaluation_results, i) end_time = time.time() print(\"Evaluation",
"print(\"Avg. captured prob. =\", avg_captured_prob) elif self.player == 'goalie': print(\"Avg. lose prob. =\",",
"> 0: print('\\rNumber of not ready learners:', evaluator.redis_instance.get('not ready'), end='') print('======Start Evaluation======') evaluator.run()",
"i) self.writer.add_scalar(\"Avg. capture prob.\", avg_captured_prob / (1 + avg_goal_prob), i) return avg_returns, avg_timesteps,",
"discrete action and continuous parameters next_act, next_act_param, _, _ = self.agent.act(next_obs) next_action =",
"= total_returns / num_results avg_timesteps = total_timesteps / num_results avg_goal_timesteps = sum(goal_timesteps) /",
"_, _ = self.agent.act(obs) action = offense_mid_action(act, act_param) while not terminal: t +=",
"parser.add_argument('--episodes', type=int, default=20000) parser.add_argument('--eval-episodes', type=int, default=1000) parser.add_argument('--save-freq', type=int, default=500) parser.add_argument('--tensorboard-dir', type=str, default=\".\") parser.add_argument('--save-dir',",
"1, self.save_freq): # load model returns = [] timesteps = [] goals =",
"= {'status': \"NOT_SET\"} # initialize environment and reward obs = self.env.reset() obs =",
"load model returns = [] timesteps = [] goals = [] captureds =",
"save_dir=save_dir, player=player, seed=seed, episodes=episodes, start=start, server_port=server_port, save_freq=save_freq) self.player = player self.eval_episodes = eval_episodes",
"goal_timesteps = evaluation_results[:, 1][evaluation_results[:, 2] == 1] total_goal = sum(evaluation_results[:, 2]) total_captured =",
"if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('--agent-type', type=str, default='PDDPG') parser.add_argument('--player', type=str, default='offense')",
"print(\"Avg. evaluation return =\", avg_returns) print(\"Avg. timesteps =\", avg_timesteps) if self.player == 'offense':",
"server_port=6000, eval_episodes=1000, start=0): super(Evaluator, self).__init__(agent_type=agent_type, tensorboard_dir=tensorboard_dir, save_dir=save_dir, player=player, seed=seed, episodes=episodes, start=start, server_port=server_port, save_freq=save_freq)",
"def run(self): # Random seed # self.seed += 10000 * proc_id() torch.manual_seed(self.seed) np.random.seed(self.seed)",
"self.player == 'offense': print(\"Avg. goal prob. =\", avg_goal_prob) print(\"Avg. timesteps per goal =\",",
"= time.time() print(\"Evaluating self.agent over {} episodes\".format(self.episodes)) self.agent.epsilon_final = 0. self.agent.epsilon = 0.",
"(1 + avg_goal_prob)) self.writer.add_scalar('Avg. evaluation return', avg_returns, i) self.writer.add_scalar('Avg. timesteps', avg_timesteps, i) if",
"be same as in redis_manager) self.all_agents = list(self.redis_instance.smembers('teammates')) self.all_agents.sort() start_time = time.time() print(\"Evaluating",
"= evaluation_results.shape[0] total_returns = sum(evaluation_results[:, 0]) total_timesteps = sum(evaluation_results[:, 1]) goal_timesteps = evaluation_results[:,",
"default=500) parser.add_argument('--tensorboard-dir', type=str, default=\".\") parser.add_argument('--save-dir', type=str, default=\".\") parser.add_argument('--start', type=int, default=0) args = parser.parse_args()",
"sync_agent_policy import logging class Evaluator(Learner): def __init__(self, agent_type, tensorboard_dir, save_dir=\".\", player='offense', save_freq=500, seed=1,",
"Evaluator(agent_type=args.agent_type, player=args.player, seed=args.seed, episodes=args.episodes, server_port=args.server_port, tensorboard_dir=args.tensorboard_dir, start=args.start, save_dir=args.save_dir, eval_episodes=args.eval_episodes, save_freq=args.save_freq) evaluator.redis_instance.decr('not ready', amount=1)",
"info['status'] == 'CAPTURED_BY_DEFENSE' timesteps.append(t) returns.append(episode_reward) goals.append(goal) captureds.append(captured) evaluation_results = np.column_stack((returns, timesteps, goals, captureds))",
"0. self.agent.epsilon = 0. self.agent.noise = None # PDDPG and MAPDDPG evaluation if",
"timesteps', avg_timesteps, i) if self.player == 'offense': self.writer.add_scalar(\"Avg. goal prob.\", avg_goal_prob, i) self.writer.add_scalar(\"Avg.",
"offense_mid_action(act, act_param) while not terminal: t += 1 next_obs, reward, terminal, info =",
"nearly synchronously while int(evaluator.redis_instance.get('not ready')) > 0: print('\\rNumber of not ready learners:', evaluator.redis_instance.get('not",
"self.agent.noise = None # PDDPG and MAPDDPG evaluation if isinstance(self.agent, PDDPGAgent): # main",
"- start_time)) return avg_returns, avg_timesteps, avg_goal_timesteps, avg_goal_prob, avg_captured_prob if __name__ == '__main__': parser",
"3]) avg_returns = total_returns / num_results avg_timesteps = total_timesteps / num_results avg_goal_timesteps =",
"Evaluator(Learner): def __init__(self, agent_type, tensorboard_dir, save_dir=\".\", player='offense', save_freq=500, seed=1, episodes=50, server_port=6000, eval_episodes=1000, start=0):",
"j in range(self.eval_episodes): info = {'status': \"NOT_SET\"} # initialize environment and reward obs",
"agent_type, tensorboard_dir, save_dir=\".\", player='offense', save_freq=500, seed=1, episodes=50, server_port=6000, eval_episodes=1000, start=0): super(Evaluator, self).__init__(agent_type=agent_type, tensorboard_dir=tensorboard_dir,",
"timesteps per goal\", avg_goal_timesteps, i) self.writer.add_scalar(\"Avg. captured prob.\", avg_captured_prob, i) elif self.player ==",
"argparse.ArgumentParser() parser.add_argument('--agent-type', type=str, default='PDDPG') parser.add_argument('--player', type=str, default='offense') parser.add_argument('--seed', type=int, default=0) parser.add_argument('--server-port', type=int, default=6000)",
"from envs import offense_mid_action from utils.redis_manager import connect_redis, query_all_obs_actions, sync_agent_obs_actions, sync_agent_policy import logging",
"for i in range(self.start + self.save_freq, self.start + self.episodes + 1, self.save_freq): #",
"10000 * proc_id() torch.manual_seed(self.seed) np.random.seed(self.seed) # later can sort by approximity (need to",
"parser.add_argument('--start', type=int, default=0) args = parser.parse_args() evaluator = Evaluator(agent_type=args.agent_type, player=args.player, seed=args.seed, episodes=args.episodes, server_port=args.server_port,",
"avg_timesteps, avg_goal_timesteps, avg_goal_prob, avg_captured_prob = \\ self.log_results(evaluation_results, i) end_time = time.time() print(\"Evaluation time:",
"= info['status'] == 'GOAL' captured = info['status'] == 'CAPTURED_BY_DEFENSE' timesteps.append(t) returns.append(episode_reward) goals.append(goal) captureds.append(captured)",
"MAPDDPG evaluation if isinstance(self.agent, PDDPGAgent): # main loop assert self.save_freq < self.episodes +",
"goals.append(goal) captureds.append(captured) evaluation_results = np.column_stack((returns, timesteps, goals, captureds)) avg_returns, avg_timesteps, avg_goal_timesteps, avg_goal_prob, avg_captured_prob",
"save_freq=save_freq) self.player = player self.eval_episodes = eval_episodes def log_results(self, evaluation_results, i): num_results =",
"avg_goal_timesteps, i) self.writer.add_scalar(\"Avg. captured prob.\", avg_captured_prob, i) elif self.player == 'goalie': self.writer.add_scalar(\"Avg. lose",
"=\", avg_goal_prob) print(\"Avg. capture prob. =\", avg_captured_prob / (1 + avg_goal_prob)) self.writer.add_scalar('Avg. evaluation",
"None # PDDPG and MAPDDPG evaluation if isinstance(self.agent, PDDPGAgent): # main loop assert",
"avg_returns = total_returns / num_results avg_timesteps = total_timesteps / num_results avg_goal_timesteps = sum(goal_timesteps)",
"0]) total_timesteps = sum(evaluation_results[:, 1]) goal_timesteps = evaluation_results[:, 1][evaluation_results[:, 2] == 1] total_goal",
"np.array(next_obs, dtype=np.float32, copy=False) # get discrete action and continuous parameters next_act, next_act_param, _,",
"avg_returns, avg_timesteps, avg_goal_timesteps, avg_goal_prob, avg_captured_prob if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('--agent-type',",
"print(\"Avg. capture prob. =\", avg_captured_prob / (1 + avg_goal_prob)) self.writer.add_scalar('Avg. evaluation return', avg_returns,",
"type=str, default='PDDPG') parser.add_argument('--player', type=str, default='offense') parser.add_argument('--seed', type=int, default=0) parser.add_argument('--server-port', type=int, default=6000) parser.add_argument('--episodes', type=int,",
"self.agent.act(obs) action = offense_mid_action(act, act_param) while not terminal: t += 1 next_obs, reward,",
"tensorboard_dir=tensorboard_dir, save_dir=save_dir, player=player, seed=seed, episodes=episodes, start=start, server_port=server_port, save_freq=save_freq) self.player = player self.eval_episodes =",
"episodes=episodes, start=start, server_port=server_port, save_freq=save_freq) self.player = player self.eval_episodes = eval_episodes def log_results(self, evaluation_results,",
"run(self): # Random seed # self.seed += 10000 * proc_id() torch.manual_seed(self.seed) np.random.seed(self.seed) #",
"= time.time() print(\"Evaluation time: %.2f seconds\" % (end_time - start_time)) return avg_returns, avg_timesteps,",
"to be same as in redis_manager) self.all_agents = list(self.redis_instance.smembers('teammates')) self.all_agents.sort() start_time = time.time()",
"# initialize environment and reward obs = self.env.reset() obs = np.array(obs, dtype=np.float32, copy=False)",
"== 'offense': self.writer.add_scalar(\"Avg. goal prob.\", avg_goal_prob, i) self.writer.add_scalar(\"Avg. timesteps per goal\", avg_goal_timesteps, i)",
"type=int, default=0) args = parser.parse_args() evaluator = Evaluator(agent_type=args.agent_type, player=args.player, seed=args.seed, episodes=args.episodes, server_port=args.server_port, tensorboard_dir=args.tensorboard_dir,",
"reward obs = self.env.reset() obs = np.array(obs, dtype=np.float32, copy=False) episode_reward = 0. terminal",
"synchronously while int(evaluator.redis_instance.get('not ready')) > 0: print('\\rNumber of not ready learners:', evaluator.redis_instance.get('not ready'),",
"evaluation_results[:, 1][evaluation_results[:, 2] == 1] total_goal = sum(evaluation_results[:, 2]) total_captured = sum(evaluation_results[:, 3])",
"self.player == 'goalie': print(\"Avg. lose prob. =\", avg_goal_prob) print(\"Avg. capture prob. =\", avg_captured_prob",
"type=int, default=1000) parser.add_argument('--save-freq', type=int, default=500) parser.add_argument('--tensorboard-dir', type=str, default=\".\") parser.add_argument('--save-dir', type=str, default=\".\") parser.add_argument('--start', type=int,",
"avg_returns, i) self.writer.add_scalar('Avg. timesteps', avg_timesteps, i) if self.player == 'offense': self.writer.add_scalar(\"Avg. goal prob.\",",
"False t = 0 # get discrete action and continuous parameters act, act_param,",
"timesteps.append(t) returns.append(episode_reward) goals.append(goal) captureds.append(captured) evaluation_results = np.column_stack((returns, timesteps, goals, captureds)) avg_returns, avg_timesteps, avg_goal_timesteps,",
"elif self.player == 'goalie': self.writer.add_scalar(\"Avg. lose prob.\", avg_goal_prob, i) self.writer.add_scalar(\"Avg. capture prob.\", avg_captured_prob",
"0. terminal = False t = 0 # get discrete action and continuous",
"== 'goalie': print(\"Avg. lose prob. =\", avg_goal_prob) print(\"Avg. capture prob. =\", avg_captured_prob /",
"act, act_param, _, _ = self.agent.act(obs) action = offense_mid_action(act, act_param) while not terminal:",
"_ = self.agent.act(next_obs) next_action = offense_mid_action(next_act, next_act_param) action = next_action episode_reward += reward",
"=\", avg_goal_prob) print(\"Avg. timesteps per goal =\", avg_goal_timesteps) print(\"Avg. captured prob. =\", avg_captured_prob)",
"total_timesteps / num_results avg_goal_timesteps = sum(goal_timesteps) / num_results avg_goal_prob = total_goal / num_results",
"i in range(self.start + self.save_freq, self.start + self.episodes + 1, self.save_freq): # load",
"agents.pddpg_agent import PDDPGAgent from agents.mapddpg_agent import MAPDDPGAgent from envs import offense_mid_action from utils.redis_manager",
"time: %.2f seconds\" % (end_time - start_time)) return avg_returns, avg_timesteps, avg_goal_timesteps, avg_goal_prob, avg_captured_prob",
"/ (1 + avg_goal_prob), i) return avg_returns, avg_timesteps, avg_goal_timesteps, avg_goal_prob, avg_captured_prob def run(self):",
"type=int, default=0) parser.add_argument('--server-port', type=int, default=6000) parser.add_argument('--episodes', type=int, default=20000) parser.add_argument('--eval-episodes', type=int, default=1000) parser.add_argument('--save-freq', type=int,",
"tensorboard_dir, save_dir=\".\", player='offense', save_freq=500, seed=1, episodes=50, server_port=6000, eval_episodes=1000, start=0): super(Evaluator, self).__init__(agent_type=agent_type, tensorboard_dir=tensorboard_dir, save_dir=save_dir,",
"goal\", avg_goal_timesteps, i) self.writer.add_scalar(\"Avg. captured prob.\", avg_captured_prob, i) elif self.player == 'goalie': self.writer.add_scalar(\"Avg.",
"numpy as np import torch from agents.random_agent import RandomAgent from agents.pddpg_agent import PDDPGAgent",
"i) self.writer.add_scalar(\"Avg. captured prob.\", avg_captured_prob, i) elif self.player == 'goalie': self.writer.add_scalar(\"Avg. lose prob.\",",
"default=0) args = parser.parse_args() evaluator = Evaluator(agent_type=args.agent_type, player=args.player, seed=args.seed, episodes=args.episodes, server_port=args.server_port, tensorboard_dir=args.tensorboard_dir, start=args.start,",
"initialize environment and reward obs = self.env.reset() obs = np.array(obs, dtype=np.float32, copy=False) episode_reward",
"avg_goal_prob, i) self.writer.add_scalar(\"Avg. timesteps per goal\", avg_goal_timesteps, i) self.writer.add_scalar(\"Avg. captured prob.\", avg_captured_prob, i)",
"(need to be same as in redis_manager) self.all_agents = list(self.redis_instance.smembers('teammates')) self.all_agents.sort() start_time =",
"avg_returns, avg_timesteps, avg_goal_timesteps, avg_goal_prob, avg_captured_prob def run(self): # Random seed # self.seed +=",
"action = next_action episode_reward += reward goal = info['status'] == 'GOAL' captured =",
"= total_goal / num_results avg_captured_prob = total_captured / num_results print(\"Avg. evaluation return =\",",
"offense_mid_action(next_act, next_act_param) action = next_action episode_reward += reward goal = info['status'] == 'GOAL'",
"agents.mapddpg_agent import MAPDDPGAgent from envs import offense_mid_action from utils.redis_manager import connect_redis, query_all_obs_actions, sync_agent_obs_actions,",
"avg_goal_prob)) self.writer.add_scalar('Avg. evaluation return', avg_returns, i) self.writer.add_scalar('Avg. timesteps', avg_timesteps, i) if self.player ==",
"= sum(evaluation_results[:, 2]) total_captured = sum(evaluation_results[:, 3]) avg_returns = total_returns / num_results avg_timesteps",
"avg_goal_prob), i) return avg_returns, avg_timesteps, avg_goal_timesteps, avg_goal_prob, avg_captured_prob def run(self): # Random seed",
"server_port=args.server_port, tensorboard_dir=args.tensorboard_dir, start=args.start, save_dir=args.save_dir, eval_episodes=args.eval_episodes, save_freq=args.save_freq) evaluator.redis_instance.decr('not ready', amount=1) # to act nearly",
"default='offense') parser.add_argument('--seed', type=int, default=0) parser.add_argument('--server-port', type=int, default=6000) parser.add_argument('--episodes', type=int, default=20000) parser.add_argument('--eval-episodes', type=int, default=1000)",
"end_time = time.time() print(\"Evaluation time: %.2f seconds\" % (end_time - start_time)) return avg_returns,",
"player self.eval_episodes = eval_episodes def log_results(self, evaluation_results, i): num_results = evaluation_results.shape[0] total_returns =",
"avg_timesteps) if self.player == 'offense': print(\"Avg. goal prob. =\", avg_goal_prob) print(\"Avg. timesteps per",
"default=6000) parser.add_argument('--episodes', type=int, default=20000) parser.add_argument('--eval-episodes', type=int, default=1000) parser.add_argument('--save-freq', type=int, default=500) parser.add_argument('--tensorboard-dir', type=str, default=\".\")",
"import argparse import time import numpy as np import torch from agents.random_agent import",
"= None # PDDPG and MAPDDPG evaluation if isinstance(self.agent, PDDPGAgent): # main loop",
"== 1] total_goal = sum(evaluation_results[:, 2]) total_captured = sum(evaluation_results[:, 3]) avg_returns = total_returns",
"self.save_freq < self.episodes + 1 for i in range(self.start + self.save_freq, self.start +",
"get discrete action and continuous parameters act, act_param, _, _ = self.agent.act(obs) action",
"self.all_agents = list(self.redis_instance.smembers('teammates')) self.all_agents.sort() start_time = time.time() print(\"Evaluating self.agent over {} episodes\".format(self.episodes)) self.agent.epsilon_final",
"self.writer.add_scalar('Avg. timesteps', avg_timesteps, i) if self.player == 'offense': self.writer.add_scalar(\"Avg. goal prob.\", avg_goal_prob, i)",
"discrete action and continuous parameters act, act_param, _, _ = self.agent.act(obs) action =",
"avg_goal_prob, i) self.writer.add_scalar(\"Avg. capture prob.\", avg_captured_prob / (1 + avg_goal_prob), i) return avg_returns,",
"self.writer.add_scalar(\"Avg. capture prob.\", avg_captured_prob / (1 + avg_goal_prob), i) return avg_returns, avg_timesteps, avg_goal_timesteps,",
"seconds\" % (end_time - start_time)) return avg_returns, avg_timesteps, avg_goal_timesteps, avg_goal_prob, avg_captured_prob if __name__",
"captured prob. =\", avg_captured_prob) elif self.player == 'goalie': print(\"Avg. lose prob. =\", avg_goal_prob)",
"seed=seed, episodes=episodes, start=start, server_port=server_port, save_freq=save_freq) self.player = player self.eval_episodes = eval_episodes def log_results(self,",
"next_action = offense_mid_action(next_act, next_act_param) action = next_action episode_reward += reward goal = info['status']",
"= self.env.reset() obs = np.array(obs, dtype=np.float32, copy=False) episode_reward = 0. terminal = False",
"save_freq=args.save_freq) evaluator.redis_instance.decr('not ready', amount=1) # to act nearly synchronously while int(evaluator.redis_instance.get('not ready')) >",
"in redis_manager) self.all_agents = list(self.redis_instance.smembers('teammates')) self.all_agents.sort() start_time = time.time() print(\"Evaluating self.agent over {}",
"time.time() print(\"Evaluating self.agent over {} episodes\".format(self.episodes)) self.agent.epsilon_final = 0. self.agent.epsilon = 0. self.agent.noise",
"avg_goal_prob) print(\"Avg. capture prob. =\", avg_captured_prob / (1 + avg_goal_prob)) self.writer.add_scalar('Avg. evaluation return',",
"ready', amount=1) # to act nearly synchronously while int(evaluator.redis_instance.get('not ready')) > 0: print('\\rNumber",
"prob. =\", avg_captured_prob / (1 + avg_goal_prob)) self.writer.add_scalar('Avg. evaluation return', avg_returns, i) self.writer.add_scalar('Avg.",
"= 0. terminal = False t = 0 # get discrete action and",
"2] == 1] total_goal = sum(evaluation_results[:, 2]) total_captured = sum(evaluation_results[:, 3]) avg_returns =",
"not terminal: t += 1 next_obs, reward, terminal, info = self.env.step(action) next_obs =",
"+ avg_goal_prob)) self.writer.add_scalar('Avg. evaluation return', avg_returns, i) self.writer.add_scalar('Avg. timesteps', avg_timesteps, i) if self.player",
"captureds)) avg_returns, avg_timesteps, avg_goal_timesteps, avg_goal_prob, avg_captured_prob = \\ self.log_results(evaluation_results, i) end_time = time.time()",
"avg_goal_prob) print(\"Avg. timesteps per goal =\", avg_goal_timesteps) print(\"Avg. captured prob. =\", avg_captured_prob) elif",
"= \\ self.log_results(evaluation_results, i) end_time = time.time() print(\"Evaluation time: %.2f seconds\" % (end_time",
"server_port=server_port, save_freq=save_freq) self.player = player self.eval_episodes = eval_episodes def log_results(self, evaluation_results, i): num_results",
"envs import offense_mid_action from utils.redis_manager import connect_redis, query_all_obs_actions, sync_agent_obs_actions, sync_agent_policy import logging class",
"import numpy as np import torch from agents.random_agent import RandomAgent from agents.pddpg_agent import",
"query_all_obs_actions, sync_agent_obs_actions, sync_agent_policy import logging class Evaluator(Learner): def __init__(self, agent_type, tensorboard_dir, save_dir=\".\", player='offense',",
"seed=args.seed, episodes=args.episodes, server_port=args.server_port, tensorboard_dir=args.tensorboard_dir, start=args.start, save_dir=args.save_dir, eval_episodes=args.eval_episodes, save_freq=args.save_freq) evaluator.redis_instance.decr('not ready', amount=1) # to",
"= np.array(next_obs, dtype=np.float32, copy=False) # get discrete action and continuous parameters next_act, next_act_param,",
"agents.random_agent import RandomAgent from agents.pddpg_agent import PDDPGAgent from agents.mapddpg_agent import MAPDDPGAgent from envs",
"as np import torch from agents.random_agent import RandomAgent from agents.pddpg_agent import PDDPGAgent from",
"self.all_agents.sort() start_time = time.time() print(\"Evaluating self.agent over {} episodes\".format(self.episodes)) self.agent.epsilon_final = 0. self.agent.epsilon",
"1 next_obs, reward, terminal, info = self.env.step(action) next_obs = np.array(next_obs, dtype=np.float32, copy=False) #",
"= self.agent.act(next_obs) next_action = offense_mid_action(next_act, next_act_param) action = next_action episode_reward += reward goal",
"= np.array(obs, dtype=np.float32, copy=False) episode_reward = 0. terminal = False t = 0",
"import MAPDDPGAgent from envs import offense_mid_action from utils.redis_manager import connect_redis, query_all_obs_actions, sync_agent_obs_actions, sync_agent_policy",
"terminal = False t = 0 # get discrete action and continuous parameters",
"avg_goal_timesteps, avg_goal_prob, avg_captured_prob def run(self): # Random seed # self.seed += 10000 *",
"0 # get discrete action and continuous parameters act, act_param, _, _ =",
"learner import Learner import os import argparse import time import numpy as np",
"start=start, server_port=server_port, save_freq=save_freq) self.player = player self.eval_episodes = eval_episodes def log_results(self, evaluation_results, i):",
"__init__(self, agent_type, tensorboard_dir, save_dir=\".\", player='offense', save_freq=500, seed=1, episodes=50, server_port=6000, eval_episodes=1000, start=0): super(Evaluator, self).__init__(agent_type=agent_type,",
"avg_goal_timesteps = sum(goal_timesteps) / num_results avg_goal_prob = total_goal / num_results avg_captured_prob = total_captured",
"# PDDPG and MAPDDPG evaluation if isinstance(self.agent, PDDPGAgent): # main loop assert self.save_freq",
"self.agent over {} episodes\".format(self.episodes)) self.agent.epsilon_final = 0. self.agent.epsilon = 0. self.agent.noise = None",
"player=args.player, seed=args.seed, episodes=args.episodes, server_port=args.server_port, tensorboard_dir=args.tensorboard_dir, start=args.start, save_dir=args.save_dir, eval_episodes=args.eval_episodes, save_freq=args.save_freq) evaluator.redis_instance.decr('not ready', amount=1) #",
"eval_episodes=1000, start=0): super(Evaluator, self).__init__(agent_type=agent_type, tensorboard_dir=tensorboard_dir, save_dir=save_dir, player=player, seed=seed, episodes=episodes, start=start, server_port=server_port, save_freq=save_freq) self.player",
"return', avg_returns, i) self.writer.add_scalar('Avg. timesteps', avg_timesteps, i) if self.player == 'offense': self.writer.add_scalar(\"Avg. goal",
"/ num_results avg_goal_timesteps = sum(goal_timesteps) / num_results avg_goal_prob = total_goal / num_results avg_captured_prob",
"=\", avg_captured_prob) elif self.player == 'goalie': print(\"Avg. lose prob. =\", avg_goal_prob) print(\"Avg. capture",
"in range(self.start + self.save_freq, self.start + self.episodes + 1, self.save_freq): # load model",
"proc_id() torch.manual_seed(self.seed) np.random.seed(self.seed) # later can sort by approximity (need to be same",
"+ 1 for i in range(self.start + self.save_freq, self.start + self.episodes + 1,",
"/ (1 + avg_goal_prob)) self.writer.add_scalar('Avg. evaluation return', avg_returns, i) self.writer.add_scalar('Avg. timesteps', avg_timesteps, i)",
"num_results = evaluation_results.shape[0] total_returns = sum(evaluation_results[:, 0]) total_timesteps = sum(evaluation_results[:, 1]) goal_timesteps =",
"redis_manager) self.all_agents = list(self.redis_instance.smembers('teammates')) self.all_agents.sort() start_time = time.time() print(\"Evaluating self.agent over {} episodes\".format(self.episodes))",
"parser.add_argument('--agent-type', type=str, default='PDDPG') parser.add_argument('--player', type=str, default='offense') parser.add_argument('--seed', type=int, default=0) parser.add_argument('--server-port', type=int, default=6000) parser.add_argument('--episodes',",
"return avg_returns, avg_timesteps, avg_goal_timesteps, avg_goal_prob, avg_captured_prob if __name__ == '__main__': parser = argparse.ArgumentParser()",
"prob. =\", avg_goal_prob) print(\"Avg. timesteps per goal =\", avg_goal_timesteps) print(\"Avg. captured prob. =\",",
"= self.env.step(action) next_obs = np.array(next_obs, dtype=np.float32, copy=False) # get discrete action and continuous",
"if isinstance(self.agent, PDDPGAgent): # main loop assert self.save_freq < self.episodes + 1 for",
"total_returns = sum(evaluation_results[:, 0]) total_timesteps = sum(evaluation_results[:, 1]) goal_timesteps = evaluation_results[:, 1][evaluation_results[:, 2]",
"+= reward goal = info['status'] == 'GOAL' captured = info['status'] == 'CAPTURED_BY_DEFENSE' timesteps.append(t)",
"parser.add_argument('--save-freq', type=int, default=500) parser.add_argument('--tensorboard-dir', type=str, default=\".\") parser.add_argument('--save-dir', type=str, default=\".\") parser.add_argument('--start', type=int, default=0) args",
"captured = info['status'] == 'CAPTURED_BY_DEFENSE' timesteps.append(t) returns.append(episode_reward) goals.append(goal) captureds.append(captured) evaluation_results = np.column_stack((returns, timesteps,",
"int(evaluator.redis_instance.get('not ready')) > 0: print('\\rNumber of not ready learners:', evaluator.redis_instance.get('not ready'), end='') print('======Start",
"self.writer.add_scalar(\"Avg. timesteps per goal\", avg_goal_timesteps, i) self.writer.add_scalar(\"Avg. captured prob.\", avg_captured_prob, i) elif self.player",
"import RandomAgent from agents.pddpg_agent import PDDPGAgent from agents.mapddpg_agent import MAPDDPGAgent from envs import",
"reward goal = info['status'] == 'GOAL' captured = info['status'] == 'CAPTURED_BY_DEFENSE' timesteps.append(t) returns.append(episode_reward)",
"<gh_stars>0 from learner import Learner import os import argparse import time import numpy",
"evaluation return', avg_returns, i) self.writer.add_scalar('Avg. timesteps', avg_timesteps, i) if self.player == 'offense': self.writer.add_scalar(\"Avg.",
"= list(self.redis_instance.smembers('teammates')) self.all_agents.sort() start_time = time.time() print(\"Evaluating self.agent over {} episodes\".format(self.episodes)) self.agent.epsilon_final =",
"terminal, info = self.env.step(action) next_obs = np.array(next_obs, dtype=np.float32, copy=False) # get discrete action",
"== 'offense': print(\"Avg. goal prob. =\", avg_goal_prob) print(\"Avg. timesteps per goal =\", avg_goal_timesteps)",
"avg_timesteps, i) if self.player == 'offense': self.writer.add_scalar(\"Avg. goal prob.\", avg_goal_prob, i) self.writer.add_scalar(\"Avg. timesteps",
"seed=1, episodes=50, server_port=6000, eval_episodes=1000, start=0): super(Evaluator, self).__init__(agent_type=agent_type, tensorboard_dir=tensorboard_dir, save_dir=save_dir, player=player, seed=seed, episodes=episodes, start=start,",
"torch.manual_seed(self.seed) np.random.seed(self.seed) # later can sort by approximity (need to be same as",
"goals, captureds)) avg_returns, avg_timesteps, avg_goal_timesteps, avg_goal_prob, avg_captured_prob = \\ self.log_results(evaluation_results, i) end_time =",
"import offense_mid_action from utils.redis_manager import connect_redis, query_all_obs_actions, sync_agent_obs_actions, sync_agent_policy import logging class Evaluator(Learner):",
"get discrete action and continuous parameters next_act, next_act_param, _, _ = self.agent.act(next_obs) next_action",
"next_act, next_act_param, _, _ = self.agent.act(next_obs) next_action = offense_mid_action(next_act, next_act_param) action = next_action",
"and MAPDDPG evaluation if isinstance(self.agent, PDDPGAgent): # main loop assert self.save_freq < self.episodes",
"info = {'status': \"NOT_SET\"} # initialize environment and reward obs = self.env.reset() obs",
"default=0) parser.add_argument('--server-port', type=int, default=6000) parser.add_argument('--episodes', type=int, default=20000) parser.add_argument('--eval-episodes', type=int, default=1000) parser.add_argument('--save-freq', type=int, default=500)",
"episodes\".format(self.episodes)) self.agent.epsilon_final = 0. self.agent.epsilon = 0. self.agent.noise = None # PDDPG and",
"sync_agent_obs_actions, sync_agent_policy import logging class Evaluator(Learner): def __init__(self, agent_type, tensorboard_dir, save_dir=\".\", player='offense', save_freq=500,",
"parser.add_argument('--eval-episodes', type=int, default=1000) parser.add_argument('--save-freq', type=int, default=500) parser.add_argument('--tensorboard-dir', type=str, default=\".\") parser.add_argument('--save-dir', type=str, default=\".\") parser.add_argument('--start',",
"prob.\", avg_captured_prob / (1 + avg_goal_prob), i) return avg_returns, avg_timesteps, avg_goal_timesteps, avg_goal_prob, avg_captured_prob",
"= sum(evaluation_results[:, 0]) total_timesteps = sum(evaluation_results[:, 1]) goal_timesteps = evaluation_results[:, 1][evaluation_results[:, 2] ==",
"avg_goal_timesteps, avg_goal_prob, avg_captured_prob = \\ self.log_results(evaluation_results, i) end_time = time.time() print(\"Evaluation time: %.2f",
"= eval_episodes def log_results(self, evaluation_results, i): num_results = evaluation_results.shape[0] total_returns = sum(evaluation_results[:, 0])",
"i): num_results = evaluation_results.shape[0] total_returns = sum(evaluation_results[:, 0]) total_timesteps = sum(evaluation_results[:, 1]) goal_timesteps",
"= offense_mid_action(next_act, next_act_param) action = next_action episode_reward += reward goal = info['status'] ==",
"{'status': \"NOT_SET\"} # initialize environment and reward obs = self.env.reset() obs = np.array(obs,",
"avg_captured_prob def run(self): # Random seed # self.seed += 10000 * proc_id() torch.manual_seed(self.seed)",
"sum(goal_timesteps) / num_results avg_goal_prob = total_goal / num_results avg_captured_prob = total_captured / num_results",
"per goal\", avg_goal_timesteps, i) self.writer.add_scalar(\"Avg. captured prob.\", avg_captured_prob, i) elif self.player == 'goalie':",
"approximity (need to be same as in redis_manager) self.all_agents = list(self.redis_instance.smembers('teammates')) self.all_agents.sort() start_time",
"i) if self.player == 'offense': self.writer.add_scalar(\"Avg. goal prob.\", avg_goal_prob, i) self.writer.add_scalar(\"Avg. timesteps per",
"print(\"Evaluation time: %.2f seconds\" % (end_time - start_time)) return avg_returns, avg_timesteps, avg_goal_timesteps, avg_goal_prob,",
"== '__main__': parser = argparse.ArgumentParser() parser.add_argument('--agent-type', type=str, default='PDDPG') parser.add_argument('--player', type=str, default='offense') parser.add_argument('--seed', type=int,",
"timesteps per goal =\", avg_goal_timesteps) print(\"Avg. captured prob. =\", avg_captured_prob) elif self.player ==",
"'offense': print(\"Avg. goal prob. =\", avg_goal_prob) print(\"Avg. timesteps per goal =\", avg_goal_timesteps) print(\"Avg.",
"evaluator.redis_instance.decr('not ready', amount=1) # to act nearly synchronously while int(evaluator.redis_instance.get('not ready')) > 0:",
"self.save_freq): # load model returns = [] timesteps = [] goals = []",
"ready')) > 0: print('\\rNumber of not ready learners:', evaluator.redis_instance.get('not ready'), end='') print('======Start Evaluation======')",
"goal prob. =\", avg_goal_prob) print(\"Avg. timesteps per goal =\", avg_goal_timesteps) print(\"Avg. captured prob.",
"self.agent.epsilon = 0. self.agent.noise = None # PDDPG and MAPDDPG evaluation if isinstance(self.agent,",
"return =\", avg_returns) print(\"Avg. timesteps =\", avg_timesteps) if self.player == 'offense': print(\"Avg. goal",
"capture prob.\", avg_captured_prob / (1 + avg_goal_prob), i) return avg_returns, avg_timesteps, avg_goal_timesteps, avg_goal_prob,",
"goal prob.\", avg_goal_prob, i) self.writer.add_scalar(\"Avg. timesteps per goal\", avg_goal_timesteps, i) self.writer.add_scalar(\"Avg. captured prob.\",",
"avg_goal_timesteps, avg_goal_prob, avg_captured_prob if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('--agent-type', type=str, default='PDDPG')",
"= False t = 0 # get discrete action and continuous parameters act,",
"= np.column_stack((returns, timesteps, goals, captureds)) avg_returns, avg_timesteps, avg_goal_timesteps, avg_goal_prob, avg_captured_prob = \\ self.log_results(evaluation_results,",
"__name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('--agent-type', type=str, default='PDDPG') parser.add_argument('--player', type=str, default='offense') parser.add_argument('--seed',",
"= 0 # get discrete action and continuous parameters act, act_param, _, _",
"np.random.seed(self.seed) # later can sort by approximity (need to be same as in",
"same as in redis_manager) self.all_agents = list(self.redis_instance.smembers('teammates')) self.all_agents.sort() start_time = time.time() print(\"Evaluating self.agent",
"= sum(evaluation_results[:, 3]) avg_returns = total_returns / num_results avg_timesteps = total_timesteps / num_results",
"tensorboard_dir=args.tensorboard_dir, start=args.start, save_dir=args.save_dir, eval_episodes=args.eval_episodes, save_freq=args.save_freq) evaluator.redis_instance.decr('not ready', amount=1) # to act nearly synchronously",
"+= 10000 * proc_id() torch.manual_seed(self.seed) np.random.seed(self.seed) # later can sort by approximity (need",
"PDDPG and MAPDDPG evaluation if isinstance(self.agent, PDDPGAgent): # main loop assert self.save_freq <",
"self.player == 'goalie': self.writer.add_scalar(\"Avg. lose prob.\", avg_goal_prob, i) self.writer.add_scalar(\"Avg. capture prob.\", avg_captured_prob /",
"self.env.reset() obs = np.array(obs, dtype=np.float32, copy=False) episode_reward = 0. terminal = False t",
"captureds = [] self.load_model(self.save_dir, i) for j in range(self.eval_episodes): info = {'status': \"NOT_SET\"}",
"captured prob.\", avg_captured_prob, i) elif self.player == 'goalie': self.writer.add_scalar(\"Avg. lose prob.\", avg_goal_prob, i)",
"type=str, default='offense') parser.add_argument('--seed', type=int, default=0) parser.add_argument('--server-port', type=int, default=6000) parser.add_argument('--episodes', type=int, default=20000) parser.add_argument('--eval-episodes', type=int,",
"avg_captured_prob) elif self.player == 'goalie': print(\"Avg. lose prob. =\", avg_goal_prob) print(\"Avg. capture prob.",
"%.2f seconds\" % (end_time - start_time)) return avg_returns, avg_timesteps, avg_goal_timesteps, avg_goal_prob, avg_captured_prob if",
"parser.add_argument('--save-dir', type=str, default=\".\") parser.add_argument('--start', type=int, default=0) args = parser.parse_args() evaluator = Evaluator(agent_type=args.agent_type, player=args.player,",
"# get discrete action and continuous parameters act, act_param, _, _ = self.agent.act(obs)",
"save_dir=args.save_dir, eval_episodes=args.eval_episodes, save_freq=args.save_freq) evaluator.redis_instance.decr('not ready', amount=1) # to act nearly synchronously while int(evaluator.redis_instance.get('not",
"# load model returns = [] timesteps = [] goals = [] captureds",
"1]) goal_timesteps = evaluation_results[:, 1][evaluation_results[:, 2] == 1] total_goal = sum(evaluation_results[:, 2]) total_captured",
"=\", avg_goal_timesteps) print(\"Avg. captured prob. =\", avg_captured_prob) elif self.player == 'goalie': print(\"Avg. lose",
"range(self.start + self.save_freq, self.start + self.episodes + 1, self.save_freq): # load model returns",
"% (end_time - start_time)) return avg_returns, avg_timesteps, avg_goal_timesteps, avg_goal_prob, avg_captured_prob if __name__ ==",
"# to act nearly synchronously while int(evaluator.redis_instance.get('not ready')) > 0: print('\\rNumber of not",
"{} episodes\".format(self.episodes)) self.agent.epsilon_final = 0. self.agent.epsilon = 0. self.agent.noise = None # PDDPG",
"action = offense_mid_action(act, act_param) while not terminal: t += 1 next_obs, reward, terminal,",
"avg_captured_prob / (1 + avg_goal_prob), i) return avg_returns, avg_timesteps, avg_goal_timesteps, avg_goal_prob, avg_captured_prob def",
"evaluation return =\", avg_returns) print(\"Avg. timesteps =\", avg_timesteps) if self.player == 'offense': print(\"Avg.",
"episodes=args.episodes, server_port=args.server_port, tensorboard_dir=args.tensorboard_dir, start=args.start, save_dir=args.save_dir, eval_episodes=args.eval_episodes, save_freq=args.save_freq) evaluator.redis_instance.decr('not ready', amount=1) # to act",
"[] goals = [] captureds = [] self.load_model(self.save_dir, i) for j in range(self.eval_episodes):",
"Learner import os import argparse import time import numpy as np import torch",
"assert self.save_freq < self.episodes + 1 for i in range(self.start + self.save_freq, self.start",
"timesteps, goals, captureds)) avg_returns, avg_timesteps, avg_goal_timesteps, avg_goal_prob, avg_captured_prob = \\ self.log_results(evaluation_results, i) end_time",
"_ = self.agent.act(obs) action = offense_mid_action(act, act_param) while not terminal: t += 1",
"parser.add_argument('--player', type=str, default='offense') parser.add_argument('--seed', type=int, default=0) parser.add_argument('--server-port', type=int, default=6000) parser.add_argument('--episodes', type=int, default=20000) parser.add_argument('--eval-episodes',",
"= offense_mid_action(act, act_param) while not terminal: t += 1 next_obs, reward, terminal, info",
"from agents.mapddpg_agent import MAPDDPGAgent from envs import offense_mid_action from utils.redis_manager import connect_redis, query_all_obs_actions,",
"time.time() print(\"Evaluation time: %.2f seconds\" % (end_time - start_time)) return avg_returns, avg_timesteps, avg_goal_timesteps,",
"total_goal = sum(evaluation_results[:, 2]) total_captured = sum(evaluation_results[:, 3]) avg_returns = total_returns / num_results",
"lose prob. =\", avg_goal_prob) print(\"Avg. capture prob. =\", avg_captured_prob / (1 + avg_goal_prob))",
"type=int, default=500) parser.add_argument('--tensorboard-dir', type=str, default=\".\") parser.add_argument('--save-dir', type=str, default=\".\") parser.add_argument('--start', type=int, default=0) args =",
"seed # self.seed += 10000 * proc_id() torch.manual_seed(self.seed) np.random.seed(self.seed) # later can sort",
"= evaluation_results[:, 1][evaluation_results[:, 2] == 1] total_goal = sum(evaluation_results[:, 2]) total_captured = sum(evaluation_results[:,",
"np import torch from agents.random_agent import RandomAgent from agents.pddpg_agent import PDDPGAgent from agents.mapddpg_agent",
"terminal: t += 1 next_obs, reward, terminal, info = self.env.step(action) next_obs = np.array(next_obs,",
"self.player = player self.eval_episodes = eval_episodes def log_results(self, evaluation_results, i): num_results = evaluation_results.shape[0]",
"default=\".\") parser.add_argument('--start', type=int, default=0) args = parser.parse_args() evaluator = Evaluator(agent_type=args.agent_type, player=args.player, seed=args.seed, episodes=args.episodes,",
"eval_episodes def log_results(self, evaluation_results, i): num_results = evaluation_results.shape[0] total_returns = sum(evaluation_results[:, 0]) total_timesteps",
"= 0. self.agent.noise = None # PDDPG and MAPDDPG evaluation if isinstance(self.agent, PDDPGAgent):",
"info = self.env.step(action) next_obs = np.array(next_obs, dtype=np.float32, copy=False) # get discrete action and",
"prob. =\", avg_goal_prob) print(\"Avg. capture prob. =\", avg_captured_prob / (1 + avg_goal_prob)) self.writer.add_scalar('Avg.",
"args = parser.parse_args() evaluator = Evaluator(agent_type=args.agent_type, player=args.player, seed=args.seed, episodes=args.episodes, server_port=args.server_port, tensorboard_dir=args.tensorboard_dir, start=args.start, save_dir=args.save_dir,",
"default=1000) parser.add_argument('--save-freq', type=int, default=500) parser.add_argument('--tensorboard-dir', type=str, default=\".\") parser.add_argument('--save-dir', type=str, default=\".\") parser.add_argument('--start', type=int, default=0)",
"num_results avg_goal_timesteps = sum(goal_timesteps) / num_results avg_goal_prob = total_goal / num_results avg_captured_prob =",
"list(self.redis_instance.smembers('teammates')) self.all_agents.sort() start_time = time.time() print(\"Evaluating self.agent over {} episodes\".format(self.episodes)) self.agent.epsilon_final = 0.",
"'GOAL' captured = info['status'] == 'CAPTURED_BY_DEFENSE' timesteps.append(t) returns.append(episode_reward) goals.append(goal) captureds.append(captured) evaluation_results = np.column_stack((returns,",
"/ num_results print(\"Avg. evaluation return =\", avg_returns) print(\"Avg. timesteps =\", avg_timesteps) if self.player",
"import time import numpy as np import torch from agents.random_agent import RandomAgent from",
"default='PDDPG') parser.add_argument('--player', type=str, default='offense') parser.add_argument('--seed', type=int, default=0) parser.add_argument('--server-port', type=int, default=6000) parser.add_argument('--episodes', type=int, default=20000)",
"os import argparse import time import numpy as np import torch from agents.random_agent",
"evaluation_results.shape[0] total_returns = sum(evaluation_results[:, 0]) total_timesteps = sum(evaluation_results[:, 1]) goal_timesteps = evaluation_results[:, 1][evaluation_results[:,",
"+ self.episodes + 1, self.save_freq): # load model returns = [] timesteps =",
"num_results avg_timesteps = total_timesteps / num_results avg_goal_timesteps = sum(goal_timesteps) / num_results avg_goal_prob =",
"total_timesteps = sum(evaluation_results[:, 1]) goal_timesteps = evaluation_results[:, 1][evaluation_results[:, 2] == 1] total_goal =",
"parser.add_argument('--seed', type=int, default=0) parser.add_argument('--server-port', type=int, default=6000) parser.add_argument('--episodes', type=int, default=20000) parser.add_argument('--eval-episodes', type=int, default=1000) parser.add_argument('--save-freq',",
"[] captureds = [] self.load_model(self.save_dir, i) for j in range(self.eval_episodes): info = {'status':",
"+ 1, self.save_freq): # load model returns = [] timesteps = [] goals",
"start_time)) return avg_returns, avg_timesteps, avg_goal_timesteps, avg_goal_prob, avg_captured_prob if __name__ == '__main__': parser =",
"act_param, _, _ = self.agent.act(obs) action = offense_mid_action(act, act_param) while not terminal: t",
"parser.parse_args() evaluator = Evaluator(agent_type=args.agent_type, player=args.player, seed=args.seed, episodes=args.episodes, server_port=args.server_port, tensorboard_dir=args.tensorboard_dir, start=args.start, save_dir=args.save_dir, eval_episodes=args.eval_episodes, save_freq=args.save_freq)",
"avg_timesteps, avg_goal_timesteps, avg_goal_prob, avg_captured_prob def run(self): # Random seed # self.seed += 10000",
"_, _ = self.agent.act(next_obs) next_action = offense_mid_action(next_act, next_act_param) action = next_action episode_reward +=",
"evaluation_results, i): num_results = evaluation_results.shape[0] total_returns = sum(evaluation_results[:, 0]) total_timesteps = sum(evaluation_results[:, 1])",
"from agents.random_agent import RandomAgent from agents.pddpg_agent import PDDPGAgent from agents.mapddpg_agent import MAPDDPGAgent from",
"offense_mid_action from utils.redis_manager import connect_redis, query_all_obs_actions, sync_agent_obs_actions, sync_agent_policy import logging class Evaluator(Learner): def",
"from learner import Learner import os import argparse import time import numpy as",
"model returns = [] timesteps = [] goals = [] captureds = []",
"\"NOT_SET\"} # initialize environment and reward obs = self.env.reset() obs = np.array(obs, dtype=np.float32,",
"time import numpy as np import torch from agents.random_agent import RandomAgent from agents.pddpg_agent",
"MAPDDPGAgent from envs import offense_mid_action from utils.redis_manager import connect_redis, query_all_obs_actions, sync_agent_obs_actions, sync_agent_policy import",
"save_dir=\".\", player='offense', save_freq=500, seed=1, episodes=50, server_port=6000, eval_episodes=1000, start=0): super(Evaluator, self).__init__(agent_type=agent_type, tensorboard_dir=tensorboard_dir, save_dir=save_dir, player=player,",
"i) self.writer.add_scalar(\"Avg. timesteps per goal\", avg_goal_timesteps, i) self.writer.add_scalar(\"Avg. captured prob.\", avg_captured_prob, i) elif",
"self.agent.epsilon_final = 0. self.agent.epsilon = 0. self.agent.noise = None # PDDPG and MAPDDPG",
"main loop assert self.save_freq < self.episodes + 1 for i in range(self.start +",
"= [] timesteps = [] goals = [] captureds = [] self.load_model(self.save_dir, i)",
"later can sort by approximity (need to be same as in redis_manager) self.all_agents",
"# get discrete action and continuous parameters next_act, next_act_param, _, _ = self.agent.act(next_obs)",
"type=str, default=\".\") parser.add_argument('--save-dir', type=str, default=\".\") parser.add_argument('--start', type=int, default=0) args = parser.parse_args() evaluator =",
"evaluation_results = np.column_stack((returns, timesteps, goals, captureds)) avg_returns, avg_timesteps, avg_goal_timesteps, avg_goal_prob, avg_captured_prob = \\",
"timesteps =\", avg_timesteps) if self.player == 'offense': print(\"Avg. goal prob. =\", avg_goal_prob) print(\"Avg.",
"episodes=50, server_port=6000, eval_episodes=1000, start=0): super(Evaluator, self).__init__(agent_type=agent_type, tensorboard_dir=tensorboard_dir, save_dir=save_dir, player=player, seed=seed, episodes=episodes, start=start, server_port=server_port,",
"next_obs, reward, terminal, info = self.env.step(action) next_obs = np.array(next_obs, dtype=np.float32, copy=False) # get",
"= info['status'] == 'CAPTURED_BY_DEFENSE' timesteps.append(t) returns.append(episode_reward) goals.append(goal) captureds.append(captured) evaluation_results = np.column_stack((returns, timesteps, goals,",
"* proc_id() torch.manual_seed(self.seed) np.random.seed(self.seed) # later can sort by approximity (need to be",
"# self.seed += 10000 * proc_id() torch.manual_seed(self.seed) np.random.seed(self.seed) # later can sort by",
"start=0): super(Evaluator, self).__init__(agent_type=agent_type, tensorboard_dir=tensorboard_dir, save_dir=save_dir, player=player, seed=seed, episodes=episodes, start=start, server_port=server_port, save_freq=save_freq) self.player =",
"player='offense', save_freq=500, seed=1, episodes=50, server_port=6000, eval_episodes=1000, start=0): super(Evaluator, self).__init__(agent_type=agent_type, tensorboard_dir=tensorboard_dir, save_dir=save_dir, player=player, seed=seed,",
"range(self.eval_episodes): info = {'status': \"NOT_SET\"} # initialize environment and reward obs = self.env.reset()",
"action and continuous parameters next_act, next_act_param, _, _ = self.agent.act(next_obs) next_action = offense_mid_action(next_act,",
"total_goal / num_results avg_captured_prob = total_captured / num_results print(\"Avg. evaluation return =\", avg_returns)",
"np.array(obs, dtype=np.float32, copy=False) episode_reward = 0. terminal = False t = 0 #",
"type=int, default=20000) parser.add_argument('--eval-episodes', type=int, default=1000) parser.add_argument('--save-freq', type=int, default=500) parser.add_argument('--tensorboard-dir', type=str, default=\".\") parser.add_argument('--save-dir', type=str,",
"goals = [] captureds = [] self.load_model(self.save_dir, i) for j in range(self.eval_episodes): info",
"= total_captured / num_results print(\"Avg. evaluation return =\", avg_returns) print(\"Avg. timesteps =\", avg_timesteps)",
"num_results avg_captured_prob = total_captured / num_results print(\"Avg. evaluation return =\", avg_returns) print(\"Avg. timesteps",
"from utils.redis_manager import connect_redis, query_all_obs_actions, sync_agent_obs_actions, sync_agent_policy import logging class Evaluator(Learner): def __init__(self,",
"= Evaluator(agent_type=args.agent_type, player=args.player, seed=args.seed, episodes=args.episodes, server_port=args.server_port, tensorboard_dir=args.tensorboard_dir, start=args.start, save_dir=args.save_dir, eval_episodes=args.eval_episodes, save_freq=args.save_freq) evaluator.redis_instance.decr('not ready',",
"sum(evaluation_results[:, 0]) total_timesteps = sum(evaluation_results[:, 1]) goal_timesteps = evaluation_results[:, 1][evaluation_results[:, 2] == 1]",
"per goal =\", avg_goal_timesteps) print(\"Avg. captured prob. =\", avg_captured_prob) elif self.player == 'goalie':",
"self.agent.act(next_obs) next_action = offense_mid_action(next_act, next_act_param) action = next_action episode_reward += reward goal =",
"print(\"Avg. goal prob. =\", avg_goal_prob) print(\"Avg. timesteps per goal =\", avg_goal_timesteps) print(\"Avg. captured",
"= 0. self.agent.epsilon = 0. self.agent.noise = None # PDDPG and MAPDDPG evaluation",
"loop assert self.save_freq < self.episodes + 1 for i in range(self.start + self.save_freq,",
"player=player, seed=seed, episodes=episodes, start=start, server_port=server_port, save_freq=save_freq) self.player = player self.eval_episodes = eval_episodes def",
"= player self.eval_episodes = eval_episodes def log_results(self, evaluation_results, i): num_results = evaluation_results.shape[0] total_returns",
"start=args.start, save_dir=args.save_dir, eval_episodes=args.eval_episodes, save_freq=args.save_freq) evaluator.redis_instance.decr('not ready', amount=1) # to act nearly synchronously while",
"from agents.pddpg_agent import PDDPGAgent from agents.mapddpg_agent import MAPDDPGAgent from envs import offense_mid_action from",
"self.episodes + 1 for i in range(self.start + self.save_freq, self.start + self.episodes +",
"next_act_param) action = next_action episode_reward += reward goal = info['status'] == 'GOAL' captured",
"print(\"Avg. timesteps per goal =\", avg_goal_timesteps) print(\"Avg. captured prob. =\", avg_captured_prob) elif self.player",
"= [] captureds = [] self.load_model(self.save_dir, i) for j in range(self.eval_episodes): info =",
"parser.add_argument('--tensorboard-dir', type=str, default=\".\") parser.add_argument('--save-dir', type=str, default=\".\") parser.add_argument('--start', type=int, default=0) args = parser.parse_args() evaluator",
"= total_timesteps / num_results avg_goal_timesteps = sum(goal_timesteps) / num_results avg_goal_prob = total_goal /",
"[] timesteps = [] goals = [] captureds = [] self.load_model(self.save_dir, i) for",
"timesteps = [] goals = [] captureds = [] self.load_model(self.save_dir, i) for j",
"info['status'] == 'GOAL' captured = info['status'] == 'CAPTURED_BY_DEFENSE' timesteps.append(t) returns.append(episode_reward) goals.append(goal) captureds.append(captured) evaluation_results",
"'goalie': self.writer.add_scalar(\"Avg. lose prob.\", avg_goal_prob, i) self.writer.add_scalar(\"Avg. capture prob.\", avg_captured_prob / (1 +",
"act nearly synchronously while int(evaluator.redis_instance.get('not ready')) > 0: print('\\rNumber of not ready learners:',",
"goal =\", avg_goal_timesteps) print(\"Avg. captured prob. =\", avg_captured_prob) elif self.player == 'goalie': print(\"Avg.",
"sum(evaluation_results[:, 3]) avg_returns = total_returns / num_results avg_timesteps = total_timesteps / num_results avg_goal_timesteps",
"'goalie': print(\"Avg. lose prob. =\", avg_goal_prob) print(\"Avg. capture prob. =\", avg_captured_prob / (1",
"prob. =\", avg_captured_prob) elif self.player == 'goalie': print(\"Avg. lose prob. =\", avg_goal_prob) print(\"Avg.",
"import PDDPGAgent from agents.mapddpg_agent import MAPDDPGAgent from envs import offense_mid_action from utils.redis_manager import",
"'CAPTURED_BY_DEFENSE' timesteps.append(t) returns.append(episode_reward) goals.append(goal) captureds.append(captured) evaluation_results = np.column_stack((returns, timesteps, goals, captureds)) avg_returns, avg_timesteps,",
"1] total_goal = sum(evaluation_results[:, 2]) total_captured = sum(evaluation_results[:, 3]) avg_returns = total_returns /",
"# later can sort by approximity (need to be same as in redis_manager)",
"save_freq=500, seed=1, episodes=50, server_port=6000, eval_episodes=1000, start=0): super(Evaluator, self).__init__(agent_type=agent_type, tensorboard_dir=tensorboard_dir, save_dir=save_dir, player=player, seed=seed, episodes=episodes,",
"prob.\", avg_captured_prob, i) elif self.player == 'goalie': self.writer.add_scalar(\"Avg. lose prob.\", avg_goal_prob, i) self.writer.add_scalar(\"Avg.",
"+ self.save_freq, self.start + self.episodes + 1, self.save_freq): # load model returns =",
"sum(evaluation_results[:, 1]) goal_timesteps = evaluation_results[:, 1][evaluation_results[:, 2] == 1] total_goal = sum(evaluation_results[:, 2])",
"goal = info['status'] == 'GOAL' captured = info['status'] == 'CAPTURED_BY_DEFENSE' timesteps.append(t) returns.append(episode_reward) goals.append(goal)",
"returns = [] timesteps = [] goals = [] captureds = [] self.load_model(self.save_dir,",
"i) return avg_returns, avg_timesteps, avg_goal_timesteps, avg_goal_prob, avg_captured_prob def run(self): # Random seed #",
"avg_returns) print(\"Avg. timesteps =\", avg_timesteps) if self.player == 'offense': print(\"Avg. goal prob. =\",",
"self.seed += 10000 * proc_id() torch.manual_seed(self.seed) np.random.seed(self.seed) # later can sort by approximity",
"'__main__': parser = argparse.ArgumentParser() parser.add_argument('--agent-type', type=str, default='PDDPG') parser.add_argument('--player', type=str, default='offense') parser.add_argument('--seed', type=int, default=0)",
"PDDPGAgent): # main loop assert self.save_freq < self.episodes + 1 for i in",
"prob.\", avg_goal_prob, i) self.writer.add_scalar(\"Avg. capture prob.\", avg_captured_prob / (1 + avg_goal_prob), i) return",
"self.start + self.episodes + 1, self.save_freq): # load model returns = [] timesteps",
"= self.agent.act(obs) action = offense_mid_action(act, act_param) while not terminal: t += 1 next_obs,",
"(1 + avg_goal_prob), i) return avg_returns, avg_timesteps, avg_goal_timesteps, avg_goal_prob, avg_captured_prob def run(self): #",
"import connect_redis, query_all_obs_actions, sync_agent_obs_actions, sync_agent_policy import logging class Evaluator(Learner): def __init__(self, agent_type, tensorboard_dir,",
"/ num_results avg_timesteps = total_timesteps / num_results avg_goal_timesteps = sum(goal_timesteps) / num_results avg_goal_prob",
"\\ self.log_results(evaluation_results, i) end_time = time.time() print(\"Evaluation time: %.2f seconds\" % (end_time -",
"continuous parameters next_act, next_act_param, _, _ = self.agent.act(next_obs) next_action = offense_mid_action(next_act, next_act_param) action",
"in range(self.eval_episodes): info = {'status': \"NOT_SET\"} # initialize environment and reward obs =",
"if self.player == 'offense': self.writer.add_scalar(\"Avg. goal prob.\", avg_goal_prob, i) self.writer.add_scalar(\"Avg. timesteps per goal\",",
"[] self.load_model(self.save_dir, i) for j in range(self.eval_episodes): info = {'status': \"NOT_SET\"} # initialize",
"== 'goalie': self.writer.add_scalar(\"Avg. lose prob.\", avg_goal_prob, i) self.writer.add_scalar(\"Avg. capture prob.\", avg_captured_prob / (1",
"avg_timesteps, avg_goal_timesteps, avg_goal_prob, avg_captured_prob if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('--agent-type', type=str,",
"total_captured = sum(evaluation_results[:, 3]) avg_returns = total_returns / num_results avg_timesteps = total_timesteps /",
"print(\"Evaluating self.agent over {} episodes\".format(self.episodes)) self.agent.epsilon_final = 0. self.agent.epsilon = 0. self.agent.noise =",
"super(Evaluator, self).__init__(agent_type=agent_type, tensorboard_dir=tensorboard_dir, save_dir=save_dir, player=player, seed=seed, episodes=episodes, start=start, server_port=server_port, save_freq=save_freq) self.player = player",
"np.column_stack((returns, timesteps, goals, captureds)) avg_returns, avg_timesteps, avg_goal_timesteps, avg_goal_prob, avg_captured_prob = \\ self.log_results(evaluation_results, i)",
"torch from agents.random_agent import RandomAgent from agents.pddpg_agent import PDDPGAgent from agents.mapddpg_agent import MAPDDPGAgent",
"avg_goal_prob = total_goal / num_results avg_captured_prob = total_captured / num_results print(\"Avg. evaluation return",
"self.writer.add_scalar(\"Avg. captured prob.\", avg_captured_prob, i) elif self.player == 'goalie': self.writer.add_scalar(\"Avg. lose prob.\", avg_goal_prob,",
"avg_goal_timesteps) print(\"Avg. captured prob. =\", avg_captured_prob) elif self.player == 'goalie': print(\"Avg. lose prob."
] |
[
"confusion_matrix, classification_report def read_labels(filename): labels = [] with open(filename) as f: for line",
"0 else '-' if diff < 0 else ' ' if diff <",
"def main(): parser = argparse.ArgumentParser() parser.add_argument(\"--path\", default=None, type=str, required=True, help=\"Base path\") parser.add_argument(\"--name\", default=None,",
"in range(len(cm)): prefix = 'true: ' if i == 0 else ' '",
"if len(line) == 0: continue _, label = line.split('\\t') labels.append(label) return labels def",
"sorted(true_set | pred_set) padded_labels = [lab + ' ' * (4 - len(lab))",
"required=True, help=\"File name [train,dev,test]\") args = parser.parse_args() true_path = os.path.join(args.path, args.name + '.true.tsv')",
"parser = argparse.ArgumentParser() parser.add_argument(\"--path\", default=None, type=str, required=True, help=\"Base path\") parser.add_argument(\"--name\", default=None, type=str, required=True,",
"as f: for line in f: line = line.strip() if len(line) == 0:",
"'\\t'.join(padded_labels)) for i in range(len(cm)): prefix = 'true: ' if i == 0",
"labels from {}'.format(pred_path)) if len(true_labels) != len(pred_labels): print('True and pred file do not",
"diff)) print('\\n▶ Confusion matrix:') sorted_labels = sorted(true_set | pred_set) padded_labels = [lab +",
"read_labels(pred_path) print('▶ Read pred labels from {}'.format(pred_path)) if len(true_labels) != len(pred_labels): print('True and",
"0: continue _, label = line.split('\\t') labels.append(label) return labels def compare_labels(true_labels, pred_labels): true_set",
"default=None, type=str, required=True, help=\"Base path\") parser.add_argument(\"--name\", default=None, type=str, required=True, help=\"File name [train,dev,test]\") args",
"for line in f: line = line.strip() if len(line) == 0: continue _,",
"< 0 else ' ' if diff < 0: diff = -diff print('{}\\t{}\\t{}\\t{}{:4}'.format(label,",
"== 'O' else 'X' for lab in true_labels] pred_label_binary = ['O' if lab",
"prefix = 'true: ' if i == 0 else ' ' * 6",
"args.name + '.pred.tsv') true_labels = read_labels(true_path) print('▶ Read true labels from {}'.format(true_path)) pred_labels",
"' ' if diff < 0: diff = -diff print('{}\\t{}\\t{}\\t{}{:4}'.format(label, true_counts[label], pred_counts[label], direction,",
"= sorted(true_counts, key=true_counts.get, reverse=True) + sorted(pred_set - true_set) print('\\tTrue\\tPred\\tDiff') for label in sorted_labels:",
"sorted_labels = sorted(true_set | pred_set) padded_labels = [lab + ' ' * (4",
"pred_counts = Counter(pred_labels) sorted_labels = sorted(true_counts, key=true_counts.get, reverse=True) + sorted(pred_set - true_set) print('\\tTrue\\tPred\\tDiff')",
"f: for line in f: line = line.strip() if len(line) == 0: continue",
"from {}'.format(pred_path)) if len(true_labels) != len(pred_labels): print('True and pred file do not have",
"both: {}'.format(true_set | pred_set)) print(' ~ Extra in true: {}'.format(true_set - pred_set)) print('",
"from sklearn.metrics import confusion_matrix, classification_report def read_labels(filename): labels = [] with open(filename) as",
"n in cm[i]])) print('\\n▶ Classification report:') print(classification_report(true_labels, pred_labels, digits=3)) print('\\n▶ Classification report w/o",
"+ '\\t'.join(padded_labels)) for i in range(len(cm)): prefix = 'true: ' if i ==",
"'O' else 'X' for lab in true_labels] pred_label_binary = ['O' if lab ==",
"print(classification_report(true_labels, pred_labels, labels=list(true_set - {'O'}), digits=3)) def main(): parser = argparse.ArgumentParser() parser.add_argument(\"--path\", default=None,",
"= Counter(pred_labels) sorted_labels = sorted(true_counts, key=true_counts.get, reverse=True) + sorted(pred_set - true_set) print('\\tTrue\\tPred\\tDiff') for",
"true labels from {}'.format(true_path)) pred_labels = read_labels(pred_path) print('▶ Read pred labels from {}'.format(pred_path))",
"len(pred_labels))) exit(-1) print('\\nFull label comparison:') compare_labels(true_labels, pred_labels) if set([lab[0] for lab in true_labels])",
"pred_label_binary = ['O' if lab == 'O' else 'X' for lab in pred_labels]",
"usage:') print(' ~ Used in both: {}'.format(true_set | pred_set)) print(' ~ Extra in",
"Extra in true: {}'.format(true_set - pred_set)) print(' ~ Extra in pred: {}'.format(pred_set -",
"pred_labels, digits=3)) print('\\n▶ Classification report w/o O label:') print(classification_report(true_labels, pred_labels, labels=list(true_set - {'O'}),",
"'O' in true_labels: true_label_binary = ['O' if lab == 'O' else 'X' for",
"print('{}\\t{}\\t{}\\t{}{:4}'.format(label, true_counts[label], pred_counts[label], direction, diff)) print('\\n▶ Confusion matrix:') sorted_labels = sorted(true_set | pred_set)",
"same amount of labels ({} and {})'.format( len(true_labels), len(pred_labels))) exit(-1) print('\\nFull label comparison:')",
"else ' ' if diff < 0: diff = -diff print('{}\\t{}\\t{}\\t{}{:4}'.format(label, true_counts[label], pred_counts[label],",
"padded_labels = [lab + ' ' * (4 - len(lab)) if len(lab) <",
"len(true_labels) != len(pred_labels): print('True and pred file do not have the same amount",
"range(len(cm)): prefix = 'true: ' if i == 0 else ' ' *",
"- pred_set)) print(' ~ Extra in pred: {}'.format(pred_set - true_set)) print('\\n▶ Raw counts:')",
"in true_labels] pred_label_cats = [lab if lab == 'O' else lab[2:] for lab",
"<gh_stars>100-1000 import argparse import os from collections import Counter from sklearn.metrics import confusion_matrix,",
"= line.split('\\t') labels.append(label) return labels def compare_labels(true_labels, pred_labels): true_set = set(true_labels) pred_set =",
"Classification report:') print(classification_report(true_labels, pred_labels, digits=3)) print('\\n▶ Classification report w/o O label:') print(classification_report(true_labels, pred_labels,",
"direction = '+' if diff > 0 else '-' if diff < 0",
"for lab in true_labels] pred_label_binary = ['O' if lab == 'O' else 'X'",
"pred_label_cats) if 'O' in true_labels: true_label_binary = ['O' if lab == 'O' else",
"labels.append(label) return labels def compare_labels(true_labels, pred_labels): true_set = set(true_labels) pred_set = set(pred_labels) print('\\n▶",
"Read true labels from {}'.format(true_path)) pred_labels = read_labels(pred_path) print('▶ Read pred labels from",
"if lab == 'O' else lab[2:] for lab in pred_labels] print('\\nBIO category comparison:')",
"print(' ~ Extra in true: {}'.format(true_set - pred_set)) print(' ~ Extra in pred:",
"= line.strip() if len(line) == 0: continue _, label = line.split('\\t') labels.append(label) return",
"type=str, required=True, help=\"Base path\") parser.add_argument(\"--name\", default=None, type=str, required=True, help=\"File name [train,dev,test]\") args =",
"pred_set)) print(' ~ Extra in pred: {}'.format(pred_set - true_set)) print('\\n▶ Raw counts:') true_counts",
"path\") parser.add_argument(\"--name\", default=None, type=str, required=True, help=\"File name [train,dev,test]\") args = parser.parse_args() true_path =",
"labels from {}'.format(true_path)) pred_labels = read_labels(pred_path) print('▶ Read pred labels from {}'.format(pred_path)) if",
"print(classification_report(true_labels, pred_labels, digits=3)) print('\\n▶ Classification report w/o O label:') print(classification_report(true_labels, pred_labels, labels=list(true_set -",
"pred_set) padded_labels = [lab + ' ' * (4 - len(lab)) if len(lab)",
"* (4 - len(lab)) if len(lab) < 8 else lab for lab in",
"sorted(pred_set - true_set) print('\\tTrue\\tPred\\tDiff') for label in sorted_labels: diff = pred_counts[label] - true_counts[label]",
"matrix:') sorted_labels = sorted(true_set | pred_set) padded_labels = [lab + ' ' *",
"- true_set) print('\\tTrue\\tPred\\tDiff') for label in sorted_labels: diff = pred_counts[label] - true_counts[label] direction",
"0 else ' ' * 6 prefix += padded_labels[i] print(prefix + '\\t' +",
"if len(lab) < 8 else lab for lab in sorted_labels] cm = confusion_matrix(true_labels,",
"os.path.join(args.path, args.name + '.true.tsv') pred_path = os.path.join(args.path, args.name + '.pred.tsv') true_labels = read_labels(true_path)",
"['O' if lab == 'O' else 'X' for lab in pred_labels] print('\\nBinary comparison:')",
"sorted_labels] cm = confusion_matrix(true_labels, pred_labels, labels=sorted_labels) print(' \\tpredicted:') print(' \\t' + '\\t'.join(padded_labels)) for",
"['O' if lab == 'O' else 'X' for lab in true_labels] pred_label_binary =",
"len(lab) < 8 else lab for lab in sorted_labels] cm = confusion_matrix(true_labels, pred_labels,",
"pred_labels): true_set = set(true_labels) pred_set = set(pred_labels) print('\\n▶ Label usage:') print(' ~ Used",
"cm[i]])) print('\\n▶ Classification report:') print(classification_report(true_labels, pred_labels, digits=3)) print('\\n▶ Classification report w/o O label:')",
"= ['O' if lab == 'O' else 'X' for lab in pred_labels] print('\\nBinary",
"set(pred_labels) print('\\n▶ Label usage:') print(' ~ Used in both: {}'.format(true_set | pred_set)) print('",
"lab for lab in sorted_labels] cm = confusion_matrix(true_labels, pred_labels, labels=sorted_labels) print(' \\tpredicted:') print('",
"O label:') print(classification_report(true_labels, pred_labels, labels=list(true_set - {'O'}), digits=3)) def main(): parser = argparse.ArgumentParser()",
"< 0: diff = -diff print('{}\\t{}\\t{}\\t{}{:4}'.format(label, true_counts[label], pred_counts[label], direction, diff)) print('\\n▶ Confusion matrix:')",
"true_path = os.path.join(args.path, args.name + '.true.tsv') pred_path = os.path.join(args.path, args.name + '.pred.tsv') true_labels",
"open(filename) as f: for line in f: line = line.strip() if len(line) ==",
"len(line) == 0: continue _, label = line.split('\\t') labels.append(label) return labels def compare_labels(true_labels,",
"with open(filename) as f: for line in f: line = line.strip() if len(line)",
"{}'.format(true_set - pred_set)) print(' ~ Extra in pred: {}'.format(pred_set - true_set)) print('\\n▶ Raw",
"confusion_matrix(true_labels, pred_labels, labels=sorted_labels) print(' \\tpredicted:') print(' \\t' + '\\t'.join(padded_labels)) for i in range(len(cm)):",
"+ '.pred.tsv') true_labels = read_labels(true_path) print('▶ Read true labels from {}'.format(true_path)) pred_labels =",
"def read_labels(filename): labels = [] with open(filename) as f: for line in f:",
"'-' if diff < 0 else ' ' if diff < 0: diff",
"'\\t'.join([str(n) for n in cm[i]])) print('\\n▶ Classification report:') print(classification_report(true_labels, pred_labels, digits=3)) print('\\n▶ Classification",
"== 0 else ' ' * 6 prefix += padded_labels[i] print(prefix + '\\t'",
"== {'B', 'I', 'O'}: true_label_cats = [lab if lab == 'O' else lab[2:]",
"+ sorted(pred_set - true_set) print('\\tTrue\\tPred\\tDiff') for label in sorted_labels: diff = pred_counts[label] -",
"~ Extra in pred: {}'.format(pred_set - true_set)) print('\\n▶ Raw counts:') true_counts = Counter(true_labels)",
"in true_labels]) == {'B', 'I', 'O'}: true_label_cats = [lab if lab == 'O'",
"pred_labels) if set([lab[0] for lab in true_labels]) == {'B', 'I', 'O'}: true_label_cats =",
"* 6 prefix += padded_labels[i] print(prefix + '\\t' + '\\t'.join([str(n) for n in",
"print('\\n▶ Label usage:') print(' ~ Used in both: {}'.format(true_set | pred_set)) print(' ~",
"sklearn.metrics import confusion_matrix, classification_report def read_labels(filename): labels = [] with open(filename) as f:",
"= 'true: ' if i == 0 else ' ' * 6 prefix",
"category comparison:') compare_labels(true_label_cats, pred_label_cats) if 'O' in true_labels: true_label_binary = ['O' if lab",
"true_label_binary = ['O' if lab == 'O' else 'X' for lab in true_labels]",
"= read_labels(pred_path) print('▶ Read pred labels from {}'.format(pred_path)) if len(true_labels) != len(pred_labels): print('True",
"true_labels: true_label_binary = ['O' if lab == 'O' else 'X' for lab in",
"collections import Counter from sklearn.metrics import confusion_matrix, classification_report def read_labels(filename): labels = []",
"compare_labels(true_labels, pred_labels): true_set = set(true_labels) pred_set = set(pred_labels) print('\\n▶ Label usage:') print(' ~",
"' if diff < 0: diff = -diff print('{}\\t{}\\t{}\\t{}{:4}'.format(label, true_counts[label], pred_counts[label], direction, diff))",
"6 prefix += padded_labels[i] print(prefix + '\\t' + '\\t'.join([str(n) for n in cm[i]]))",
"import confusion_matrix, classification_report def read_labels(filename): labels = [] with open(filename) as f: for",
"parser.parse_args() true_path = os.path.join(args.path, args.name + '.true.tsv') pred_path = os.path.join(args.path, args.name + '.pred.tsv')",
"line.split('\\t') labels.append(label) return labels def compare_labels(true_labels, pred_labels): true_set = set(true_labels) pred_set = set(pred_labels)",
"print('\\nBIO category comparison:') compare_labels(true_label_cats, pred_label_cats) if 'O' in true_labels: true_label_binary = ['O' if",
"import argparse import os from collections import Counter from sklearn.metrics import confusion_matrix, classification_report",
"true_counts = Counter(true_labels) pred_counts = Counter(pred_labels) sorted_labels = sorted(true_counts, key=true_counts.get, reverse=True) + sorted(pred_set",
"true_set) print('\\tTrue\\tPred\\tDiff') for label in sorted_labels: diff = pred_counts[label] - true_counts[label] direction =",
"from collections import Counter from sklearn.metrics import confusion_matrix, classification_report def read_labels(filename): labels =",
"= parser.parse_args() true_path = os.path.join(args.path, args.name + '.true.tsv') pred_path = os.path.join(args.path, args.name +",
"i == 0 else ' ' * 6 prefix += padded_labels[i] print(prefix +",
"os from collections import Counter from sklearn.metrics import confusion_matrix, classification_report def read_labels(filename): labels",
"i in range(len(cm)): prefix = 'true: ' if i == 0 else '",
"do not have the same amount of labels ({} and {})'.format( len(true_labels), len(pred_labels)))",
"lab in true_labels] pred_label_binary = ['O' if lab == 'O' else 'X' for",
"{}'.format(pred_set - true_set)) print('\\n▶ Raw counts:') true_counts = Counter(true_labels) pred_counts = Counter(pred_labels) sorted_labels",
"' if i == 0 else ' ' * 6 prefix += padded_labels[i]",
"os.path.join(args.path, args.name + '.pred.tsv') true_labels = read_labels(true_path) print('▶ Read true labels from {}'.format(true_path))",
"print(' \\tpredicted:') print(' \\t' + '\\t'.join(padded_labels)) for i in range(len(cm)): prefix = 'true:",
"print('\\nFull label comparison:') compare_labels(true_labels, pred_labels) if set([lab[0] for lab in true_labels]) == {'B',",
"the same amount of labels ({} and {})'.format( len(true_labels), len(pred_labels))) exit(-1) print('\\nFull label",
"~ Used in both: {}'.format(true_set | pred_set)) print(' ~ Extra in true: {}'.format(true_set",
"not have the same amount of labels ({} and {})'.format( len(true_labels), len(pred_labels))) exit(-1)",
"len(pred_labels): print('True and pred file do not have the same amount of labels",
"Classification report w/o O label:') print(classification_report(true_labels, pred_labels, labels=list(true_set - {'O'}), digits=3)) def main():",
"true_counts[label] direction = '+' if diff > 0 else '-' if diff <",
"~ Extra in true: {}'.format(true_set - pred_set)) print(' ~ Extra in pred: {}'.format(pred_set",
"label = line.split('\\t') labels.append(label) return labels def compare_labels(true_labels, pred_labels): true_set = set(true_labels) pred_set",
"== 'O' else 'X' for lab in pred_labels] print('\\nBinary comparison:') compare_labels(true_label_binary, pred_label_binary) if",
"of labels ({} and {})'.format( len(true_labels), len(pred_labels))) exit(-1) print('\\nFull label comparison:') compare_labels(true_labels, pred_labels)",
"< 8 else lab for lab in sorted_labels] cm = confusion_matrix(true_labels, pred_labels, labels=sorted_labels)",
"labels ({} and {})'.format( len(true_labels), len(pred_labels))) exit(-1) print('\\nFull label comparison:') compare_labels(true_labels, pred_labels) if",
"- true_counts[label] direction = '+' if diff > 0 else '-' if diff",
"import os from collections import Counter from sklearn.metrics import confusion_matrix, classification_report def read_labels(filename):",
"print('▶ Read pred labels from {}'.format(pred_path)) if len(true_labels) != len(pred_labels): print('True and pred",
"diff < 0: diff = -diff print('{}\\t{}\\t{}\\t{}{:4}'.format(label, true_counts[label], pred_counts[label], direction, diff)) print('\\n▶ Confusion",
"pred labels from {}'.format(pred_path)) if len(true_labels) != len(pred_labels): print('True and pred file do",
"else lab[2:] for lab in pred_labels] print('\\nBIO category comparison:') compare_labels(true_label_cats, pred_label_cats) if 'O'",
"-diff print('{}\\t{}\\t{}\\t{}{:4}'.format(label, true_counts[label], pred_counts[label], direction, diff)) print('\\n▶ Confusion matrix:') sorted_labels = sorted(true_set |",
"labels=list(true_set - {'O'}), digits=3)) def main(): parser = argparse.ArgumentParser() parser.add_argument(\"--path\", default=None, type=str, required=True,",
"reverse=True) + sorted(pred_set - true_set) print('\\tTrue\\tPred\\tDiff') for label in sorted_labels: diff = pred_counts[label]",
"lab == 'O' else 'X' for lab in true_labels] pred_label_binary = ['O' if",
"= read_labels(true_path) print('▶ Read true labels from {}'.format(true_path)) pred_labels = read_labels(pred_path) print('▶ Read",
"amount of labels ({} and {})'.format( len(true_labels), len(pred_labels))) exit(-1) print('\\nFull label comparison:') compare_labels(true_labels,",
"prefix += padded_labels[i] print(prefix + '\\t' + '\\t'.join([str(n) for n in cm[i]])) print('\\n▶",
"read_labels(true_path) print('▶ Read true labels from {}'.format(true_path)) pred_labels = read_labels(pred_path) print('▶ Read pred",
"diff < 0 else ' ' if diff < 0: diff = -diff",
"> 0 else '-' if diff < 0 else ' ' if diff",
"= ['O' if lab == 'O' else 'X' for lab in true_labels] pred_label_binary",
"Counter(pred_labels) sorted_labels = sorted(true_counts, key=true_counts.get, reverse=True) + sorted(pred_set - true_set) print('\\tTrue\\tPred\\tDiff') for label",
"'O'}: true_label_cats = [lab if lab == 'O' else lab[2:] for lab in",
"else ' ' * 6 prefix += padded_labels[i] print(prefix + '\\t' + '\\t'.join([str(n)",
"report w/o O label:') print(classification_report(true_labels, pred_labels, labels=list(true_set - {'O'}), digits=3)) def main(): parser",
"in pred_labels] print('\\nBIO category comparison:') compare_labels(true_label_cats, pred_label_cats) if 'O' in true_labels: true_label_binary =",
"in sorted_labels] cm = confusion_matrix(true_labels, pred_labels, labels=sorted_labels) print(' \\tpredicted:') print(' \\t' + '\\t'.join(padded_labels))",
"+ '\\t' + '\\t'.join([str(n) for n in cm[i]])) print('\\n▶ Classification report:') print(classification_report(true_labels, pred_labels,",
"default=None, type=str, required=True, help=\"File name [train,dev,test]\") args = parser.parse_args() true_path = os.path.join(args.path, args.name",
"classification_report def read_labels(filename): labels = [] with open(filename) as f: for line in",
"if i == 0 else ' ' * 6 prefix += padded_labels[i] print(prefix",
"labels = [] with open(filename) as f: for line in f: line =",
"if diff < 0: diff = -diff print('{}\\t{}\\t{}\\t{}{:4}'.format(label, true_counts[label], pred_counts[label], direction, diff)) print('\\n▶",
"== 'O' else lab[2:] for lab in true_labels] pred_label_cats = [lab if lab",
"lab[2:] for lab in pred_labels] print('\\nBIO category comparison:') compare_labels(true_label_cats, pred_label_cats) if 'O' in",
"direction, diff)) print('\\n▶ Confusion matrix:') sorted_labels = sorted(true_set | pred_set) padded_labels = [lab",
"line in f: line = line.strip() if len(line) == 0: continue _, label",
"pred_labels, labels=list(true_set - {'O'}), digits=3)) def main(): parser = argparse.ArgumentParser() parser.add_argument(\"--path\", default=None, type=str,",
"= os.path.join(args.path, args.name + '.pred.tsv') true_labels = read_labels(true_path) print('▶ Read true labels from",
"print(prefix + '\\t' + '\\t'.join([str(n) for n in cm[i]])) print('\\n▶ Classification report:') print(classification_report(true_labels,",
"pred_labels] print('\\nBIO category comparison:') compare_labels(true_label_cats, pred_label_cats) if 'O' in true_labels: true_label_binary = ['O'",
"= [] with open(filename) as f: for line in f: line = line.strip()",
"'true: ' if i == 0 else ' ' * 6 prefix +=",
"\\tpredicted:') print(' \\t' + '\\t'.join(padded_labels)) for i in range(len(cm)): prefix = 'true: '",
"f: line = line.strip() if len(line) == 0: continue _, label = line.split('\\t')",
"+= padded_labels[i] print(prefix + '\\t' + '\\t'.join([str(n) for n in cm[i]])) print('\\n▶ Classification",
"'O' else lab[2:] for lab in pred_labels] print('\\nBIO category comparison:') compare_labels(true_label_cats, pred_label_cats) if",
"true_counts[label], pred_counts[label], direction, diff)) print('\\n▶ Confusion matrix:') sorted_labels = sorted(true_set | pred_set) padded_labels",
"pred_labels = read_labels(pred_path) print('▶ Read pred labels from {}'.format(pred_path)) if len(true_labels) != len(pred_labels):",
"= [lab + ' ' * (4 - len(lab)) if len(lab) < 8",
"pred file do not have the same amount of labels ({} and {})'.format(",
"print('True and pred file do not have the same amount of labels ({}",
"def compare_labels(true_labels, pred_labels): true_set = set(true_labels) pred_set = set(pred_labels) print('\\n▶ Label usage:') print('",
"parser.add_argument(\"--path\", default=None, type=str, required=True, help=\"Base path\") parser.add_argument(\"--name\", default=None, type=str, required=True, help=\"File name [train,dev,test]\")",
"else '-' if diff < 0 else ' ' if diff < 0:",
"' ' * 6 prefix += padded_labels[i] print(prefix + '\\t' + '\\t'.join([str(n) for",
"'O' else 'X' for lab in pred_labels] print('\\nBinary comparison:') compare_labels(true_label_binary, pred_label_binary) if __name__",
"print('\\n▶ Raw counts:') true_counts = Counter(true_labels) pred_counts = Counter(pred_labels) sorted_labels = sorted(true_counts, key=true_counts.get,",
"print('\\n▶ Classification report:') print(classification_report(true_labels, pred_labels, digits=3)) print('\\n▶ Classification report w/o O label:') print(classification_report(true_labels,",
"print(' ~ Used in both: {}'.format(true_set | pred_set)) print(' ~ Extra in true:",
"label in sorted_labels: diff = pred_counts[label] - true_counts[label] direction = '+' if diff",
"0: diff = -diff print('{}\\t{}\\t{}\\t{}{:4}'.format(label, true_counts[label], pred_counts[label], direction, diff)) print('\\n▶ Confusion matrix:') sorted_labels",
"in sorted_labels: diff = pred_counts[label] - true_counts[label] direction = '+' if diff >",
"label:') print(classification_report(true_labels, pred_labels, labels=list(true_set - {'O'}), digits=3)) def main(): parser = argparse.ArgumentParser() parser.add_argument(\"--path\",",
"if set([lab[0] for lab in true_labels]) == {'B', 'I', 'O'}: true_label_cats = [lab",
"Counter(true_labels) pred_counts = Counter(pred_labels) sorted_labels = sorted(true_counts, key=true_counts.get, reverse=True) + sorted(pred_set - true_set)",
"sorted(true_counts, key=true_counts.get, reverse=True) + sorted(pred_set - true_set) print('\\tTrue\\tPred\\tDiff') for label in sorted_labels: diff",
"in cm[i]])) print('\\n▶ Classification report:') print(classification_report(true_labels, pred_labels, digits=3)) print('\\n▶ Classification report w/o O",
"pred_set)) print(' ~ Extra in true: {}'.format(true_set - pred_set)) print(' ~ Extra in",
"Label usage:') print(' ~ Used in both: {}'.format(true_set | pred_set)) print(' ~ Extra",
"lab[2:] for lab in true_labels] pred_label_cats = [lab if lab == 'O' else",
"set([lab[0] for lab in true_labels]) == {'B', 'I', 'O'}: true_label_cats = [lab if",
"'I', 'O'}: true_label_cats = [lab if lab == 'O' else lab[2:] for lab",
"true_set)) print('\\n▶ Raw counts:') true_counts = Counter(true_labels) pred_counts = Counter(pred_labels) sorted_labels = sorted(true_counts,",
"[lab + ' ' * (4 - len(lab)) if len(lab) < 8 else",
"- {'O'}), digits=3)) def main(): parser = argparse.ArgumentParser() parser.add_argument(\"--path\", default=None, type=str, required=True, help=\"Base",
"pred_counts[label], direction, diff)) print('\\n▶ Confusion matrix:') sorted_labels = sorted(true_set | pred_set) padded_labels =",
"' ' * (4 - len(lab)) if len(lab) < 8 else lab for",
"print('\\n▶ Confusion matrix:') sorted_labels = sorted(true_set | pred_set) padded_labels = [lab + '",
"comparison:') compare_labels(true_labels, pred_labels) if set([lab[0] for lab in true_labels]) == {'B', 'I', 'O'}:",
"len(true_labels), len(pred_labels))) exit(-1) print('\\nFull label comparison:') compare_labels(true_labels, pred_labels) if set([lab[0] for lab in",
"else 'X' for lab in true_labels] pred_label_binary = ['O' if lab == 'O'",
"Counter from sklearn.metrics import confusion_matrix, classification_report def read_labels(filename): labels = [] with open(filename)",
"label comparison:') compare_labels(true_labels, pred_labels) if set([lab[0] for lab in true_labels]) == {'B', 'I',",
"| pred_set) padded_labels = [lab + ' ' * (4 - len(lab)) if",
"if lab == 'O' else lab[2:] for lab in true_labels] pred_label_cats = [lab",
"= -diff print('{}\\t{}\\t{}\\t{}{:4}'.format(label, true_counts[label], pred_counts[label], direction, diff)) print('\\n▶ Confusion matrix:') sorted_labels = sorted(true_set",
"else lab[2:] for lab in true_labels] pred_label_cats = [lab if lab == 'O'",
"argparse import os from collections import Counter from sklearn.metrics import confusion_matrix, classification_report def",
"- len(lab)) if len(lab) < 8 else lab for lab in sorted_labels] cm",
"{}'.format(true_path)) pred_labels = read_labels(pred_path) print('▶ Read pred labels from {}'.format(pred_path)) if len(true_labels) !=",
"set(true_labels) pred_set = set(pred_labels) print('\\n▶ Label usage:') print(' ~ Used in both: {}'.format(true_set",
"for lab in sorted_labels] cm = confusion_matrix(true_labels, pred_labels, labels=sorted_labels) print(' \\tpredicted:') print(' \\t'",
"if 'O' in true_labels: true_label_binary = ['O' if lab == 'O' else 'X'",
"print('\\tTrue\\tPred\\tDiff') for label in sorted_labels: diff = pred_counts[label] - true_counts[label] direction = '+'",
"print('\\n▶ Classification report w/o O label:') print(classification_report(true_labels, pred_labels, labels=list(true_set - {'O'}), digits=3)) def",
"file do not have the same amount of labels ({} and {})'.format( len(true_labels),",
"import Counter from sklearn.metrics import confusion_matrix, classification_report def read_labels(filename): labels = [] with",
"== 'O' else lab[2:] for lab in pred_labels] print('\\nBIO category comparison:') compare_labels(true_label_cats, pred_label_cats)",
"digits=3)) def main(): parser = argparse.ArgumentParser() parser.add_argument(\"--path\", default=None, type=str, required=True, help=\"Base path\") parser.add_argument(\"--name\",",
"pred_set = set(pred_labels) print('\\n▶ Label usage:') print(' ~ Used in both: {}'.format(true_set |",
"= set(pred_labels) print('\\n▶ Label usage:') print(' ~ Used in both: {}'.format(true_set | pred_set))",
"\\t' + '\\t'.join(padded_labels)) for i in range(len(cm)): prefix = 'true: ' if i",
"[lab if lab == 'O' else lab[2:] for lab in pred_labels] print('\\nBIO category",
"in true_labels: true_label_binary = ['O' if lab == 'O' else 'X' for lab",
"compare_labels(true_label_cats, pred_label_cats) if 'O' in true_labels: true_label_binary = ['O' if lab == 'O'",
"print(' \\t' + '\\t'.join(padded_labels)) for i in range(len(cm)): prefix = 'true: ' if",
"+ '\\t'.join([str(n) for n in cm[i]])) print('\\n▶ Classification report:') print(classification_report(true_labels, pred_labels, digits=3)) print('\\n▶",
"true_labels]) == {'B', 'I', 'O'}: true_label_cats = [lab if lab == 'O' else",
"w/o O label:') print(classification_report(true_labels, pred_labels, labels=list(true_set - {'O'}), digits=3)) def main(): parser =",
"lab == 'O' else 'X' for lab in pred_labels] print('\\nBinary comparison:') compare_labels(true_label_binary, pred_label_binary)",
"argparse.ArgumentParser() parser.add_argument(\"--path\", default=None, type=str, required=True, help=\"Base path\") parser.add_argument(\"--name\", default=None, type=str, required=True, help=\"File name",
"in pred: {}'.format(pred_set - true_set)) print('\\n▶ Raw counts:') true_counts = Counter(true_labels) pred_counts =",
"8 else lab for lab in sorted_labels] cm = confusion_matrix(true_labels, pred_labels, labels=sorted_labels) print('",
"report:') print(classification_report(true_labels, pred_labels, digits=3)) print('\\n▶ Classification report w/o O label:') print(classification_report(true_labels, pred_labels, labels=list(true_set",
"'X' for lab in pred_labels] print('\\nBinary comparison:') compare_labels(true_label_binary, pred_label_binary) if __name__ == '__main__':",
"lab in sorted_labels] cm = confusion_matrix(true_labels, pred_labels, labels=sorted_labels) print(' \\tpredicted:') print(' \\t' +",
"line = line.strip() if len(line) == 0: continue _, label = line.split('\\t') labels.append(label)",
"[] with open(filename) as f: for line in f: line = line.strip() if",
"cm = confusion_matrix(true_labels, pred_labels, labels=sorted_labels) print(' \\tpredicted:') print(' \\t' + '\\t'.join(padded_labels)) for i",
"'O' else lab[2:] for lab in true_labels] pred_label_cats = [lab if lab ==",
"args = parser.parse_args() true_path = os.path.join(args.path, args.name + '.true.tsv') pred_path = os.path.join(args.path, args.name",
"diff = -diff print('{}\\t{}\\t{}\\t{}{:4}'.format(label, true_counts[label], pred_counts[label], direction, diff)) print('\\n▶ Confusion matrix:') sorted_labels =",
"Read pred labels from {}'.format(pred_path)) if len(true_labels) != len(pred_labels): print('True and pred file",
"'\\t' + '\\t'.join([str(n) for n in cm[i]])) print('\\n▶ Classification report:') print(classification_report(true_labels, pred_labels, digits=3))",
"comparison:') compare_labels(true_label_cats, pred_label_cats) if 'O' in true_labels: true_label_binary = ['O' if lab ==",
"'X' for lab in true_labels] pred_label_binary = ['O' if lab == 'O' else",
"true: {}'.format(true_set - pred_set)) print(' ~ Extra in pred: {}'.format(pred_set - true_set)) print('\\n▶",
"help=\"Base path\") parser.add_argument(\"--name\", default=None, type=str, required=True, help=\"File name [train,dev,test]\") args = parser.parse_args() true_path",
"= [lab if lab == 'O' else lab[2:] for lab in true_labels] pred_label_cats",
"line.strip() if len(line) == 0: continue _, label = line.split('\\t') labels.append(label) return labels",
"pred_labels, labels=sorted_labels) print(' \\tpredicted:') print(' \\t' + '\\t'.join(padded_labels)) for i in range(len(cm)): prefix",
"print('▶ Read true labels from {}'.format(true_path)) pred_labels = read_labels(pred_path) print('▶ Read pred labels",
"{}'.format(true_set | pred_set)) print(' ~ Extra in true: {}'.format(true_set - pred_set)) print(' ~",
"if diff < 0 else ' ' if diff < 0: diff =",
"required=True, help=\"Base path\") parser.add_argument(\"--name\", default=None, type=str, required=True, help=\"File name [train,dev,test]\") args = parser.parse_args()",
"compare_labels(true_labels, pred_labels) if set([lab[0] for lab in true_labels]) == {'B', 'I', 'O'}: true_label_cats",
"{'O'}), digits=3)) def main(): parser = argparse.ArgumentParser() parser.add_argument(\"--path\", default=None, type=str, required=True, help=\"Base path\")",
"labels=sorted_labels) print(' \\tpredicted:') print(' \\t' + '\\t'.join(padded_labels)) for i in range(len(cm)): prefix =",
"and pred file do not have the same amount of labels ({} and",
"for lab in true_labels] pred_label_cats = [lab if lab == 'O' else lab[2:]",
"| pred_set)) print(' ~ Extra in true: {}'.format(true_set - pred_set)) print(' ~ Extra",
"main(): parser = argparse.ArgumentParser() parser.add_argument(\"--path\", default=None, type=str, required=True, help=\"Base path\") parser.add_argument(\"--name\", default=None, type=str,",
"!= len(pred_labels): print('True and pred file do not have the same amount of",
"counts:') true_counts = Counter(true_labels) pred_counts = Counter(pred_labels) sorted_labels = sorted(true_counts, key=true_counts.get, reverse=True) +",
"for lab in true_labels]) == {'B', 'I', 'O'}: true_label_cats = [lab if lab",
"= argparse.ArgumentParser() parser.add_argument(\"--path\", default=None, type=str, required=True, help=\"Base path\") parser.add_argument(\"--name\", default=None, type=str, required=True, help=\"File",
"[lab if lab == 'O' else lab[2:] for lab in true_labels] pred_label_cats =",
"Used in both: {}'.format(true_set | pred_set)) print(' ~ Extra in true: {}'.format(true_set -",
"parser.add_argument(\"--name\", default=None, type=str, required=True, help=\"File name [train,dev,test]\") args = parser.parse_args() true_path = os.path.join(args.path,",
"else lab for lab in sorted_labels] cm = confusion_matrix(true_labels, pred_labels, labels=sorted_labels) print(' \\tpredicted:')",
"' * (4 - len(lab)) if len(lab) < 8 else lab for lab",
"== 0: continue _, label = line.split('\\t') labels.append(label) return labels def compare_labels(true_labels, pred_labels):",
"name [train,dev,test]\") args = parser.parse_args() true_path = os.path.join(args.path, args.name + '.true.tsv') pred_path =",
"diff > 0 else '-' if diff < 0 else ' ' if",
"lab == 'O' else lab[2:] for lab in true_labels] pred_label_cats = [lab if",
"= sorted(true_set | pred_set) padded_labels = [lab + ' ' * (4 -",
"true_label_cats = [lab if lab == 'O' else lab[2:] for lab in true_labels]",
"and {})'.format( len(true_labels), len(pred_labels))) exit(-1) print('\\nFull label comparison:') compare_labels(true_labels, pred_labels) if set([lab[0] for",
"in f: line = line.strip() if len(line) == 0: continue _, label =",
"type=str, required=True, help=\"File name [train,dev,test]\") args = parser.parse_args() true_path = os.path.join(args.path, args.name +",
"'.true.tsv') pred_path = os.path.join(args.path, args.name + '.pred.tsv') true_labels = read_labels(true_path) print('▶ Read true",
"Confusion matrix:') sorted_labels = sorted(true_set | pred_set) padded_labels = [lab + ' '",
"args.name + '.true.tsv') pred_path = os.path.join(args.path, args.name + '.pred.tsv') true_labels = read_labels(true_path) print('▶",
"({} and {})'.format( len(true_labels), len(pred_labels))) exit(-1) print('\\nFull label comparison:') compare_labels(true_labels, pred_labels) if set([lab[0]",
"= [lab if lab == 'O' else lab[2:] for lab in pred_labels] print('\\nBIO",
"labels def compare_labels(true_labels, pred_labels): true_set = set(true_labels) pred_set = set(pred_labels) print('\\n▶ Label usage:')",
"'+' if diff > 0 else '-' if diff < 0 else '",
"for lab in pred_labels] print('\\nBIO category comparison:') compare_labels(true_label_cats, pred_label_cats) if 'O' in true_labels:",
"= pred_counts[label] - true_counts[label] direction = '+' if diff > 0 else '-'",
"print(' ~ Extra in pred: {}'.format(pred_set - true_set)) print('\\n▶ Raw counts:') true_counts =",
"[train,dev,test]\") args = parser.parse_args() true_path = os.path.join(args.path, args.name + '.true.tsv') pred_path = os.path.join(args.path,",
"0 else ' ' if diff < 0: diff = -diff print('{}\\t{}\\t{}\\t{}{:4}'.format(label, true_counts[label],",
"lab == 'O' else lab[2:] for lab in pred_labels] print('\\nBIO category comparison:') compare_labels(true_label_cats,",
"lab in true_labels] pred_label_cats = [lab if lab == 'O' else lab[2:] for",
"return labels def compare_labels(true_labels, pred_labels): true_set = set(true_labels) pred_set = set(pred_labels) print('\\n▶ Label",
"have the same amount of labels ({} and {})'.format( len(true_labels), len(pred_labels))) exit(-1) print('\\nFull",
"{'B', 'I', 'O'}: true_label_cats = [lab if lab == 'O' else lab[2:] for",
"+ ' ' * (4 - len(lab)) if len(lab) < 8 else lab",
"if len(true_labels) != len(pred_labels): print('True and pred file do not have the same",
"' * 6 prefix += padded_labels[i] print(prefix + '\\t' + '\\t'.join([str(n) for n",
"for i in range(len(cm)): prefix = 'true: ' if i == 0 else",
"sorted_labels: diff = pred_counts[label] - true_counts[label] direction = '+' if diff > 0",
"for lab in pred_labels] print('\\nBinary comparison:') compare_labels(true_label_binary, pred_label_binary) if __name__ == '__main__': main()",
"exit(-1) print('\\nFull label comparison:') compare_labels(true_labels, pred_labels) if set([lab[0] for lab in true_labels]) ==",
"read_labels(filename): labels = [] with open(filename) as f: for line in f: line",
"true_labels] pred_label_cats = [lab if lab == 'O' else lab[2:] for lab in",
"lab in pred_labels] print('\\nBIO category comparison:') compare_labels(true_label_cats, pred_label_cats) if 'O' in true_labels: true_label_binary",
"true_labels] pred_label_binary = ['O' if lab == 'O' else 'X' for lab in",
"true_labels = read_labels(true_path) print('▶ Read true labels from {}'.format(true_path)) pred_labels = read_labels(pred_path) print('▶",
"- true_set)) print('\\n▶ Raw counts:') true_counts = Counter(true_labels) pred_counts = Counter(pred_labels) sorted_labels =",
"if lab == 'O' else 'X' for lab in pred_labels] print('\\nBinary comparison:') compare_labels(true_label_binary,",
"if diff > 0 else '-' if diff < 0 else ' '",
"= confusion_matrix(true_labels, pred_labels, labels=sorted_labels) print(' \\tpredicted:') print(' \\t' + '\\t'.join(padded_labels)) for i in",
"pred_path = os.path.join(args.path, args.name + '.pred.tsv') true_labels = read_labels(true_path) print('▶ Read true labels",
"else 'X' for lab in pred_labels] print('\\nBinary comparison:') compare_labels(true_label_binary, pred_label_binary) if __name__ ==",
"+ '.true.tsv') pred_path = os.path.join(args.path, args.name + '.pred.tsv') true_labels = read_labels(true_path) print('▶ Read",
"= os.path.join(args.path, args.name + '.true.tsv') pred_path = os.path.join(args.path, args.name + '.pred.tsv') true_labels =",
"in both: {}'.format(true_set | pred_set)) print(' ~ Extra in true: {}'.format(true_set - pred_set))",
"(4 - len(lab)) if len(lab) < 8 else lab for lab in sorted_labels]",
"pred: {}'.format(pred_set - true_set)) print('\\n▶ Raw counts:') true_counts = Counter(true_labels) pred_counts = Counter(pred_labels)",
"if lab == 'O' else 'X' for lab in true_labels] pred_label_binary = ['O'",
"'.pred.tsv') true_labels = read_labels(true_path) print('▶ Read true labels from {}'.format(true_path)) pred_labels = read_labels(pred_path)",
"for n in cm[i]])) print('\\n▶ Classification report:') print(classification_report(true_labels, pred_labels, digits=3)) print('\\n▶ Classification report",
"from {}'.format(true_path)) pred_labels = read_labels(pred_path) print('▶ Read pred labels from {}'.format(pred_path)) if len(true_labels)",
"padded_labels[i] print(prefix + '\\t' + '\\t'.join([str(n) for n in cm[i]])) print('\\n▶ Classification report:')",
"lab in true_labels]) == {'B', 'I', 'O'}: true_label_cats = [lab if lab ==",
"= set(true_labels) pred_set = set(pred_labels) print('\\n▶ Label usage:') print(' ~ Used in both:",
"help=\"File name [train,dev,test]\") args = parser.parse_args() true_path = os.path.join(args.path, args.name + '.true.tsv') pred_path",
"for label in sorted_labels: diff = pred_counts[label] - true_counts[label] direction = '+' if",
"key=true_counts.get, reverse=True) + sorted(pred_set - true_set) print('\\tTrue\\tPred\\tDiff') for label in sorted_labels: diff =",
"pred_label_cats = [lab if lab == 'O' else lab[2:] for lab in pred_labels]",
"digits=3)) print('\\n▶ Classification report w/o O label:') print(classification_report(true_labels, pred_labels, labels=list(true_set - {'O'}), digits=3))",
"Extra in pred: {}'.format(pred_set - true_set)) print('\\n▶ Raw counts:') true_counts = Counter(true_labels) pred_counts",
"Raw counts:') true_counts = Counter(true_labels) pred_counts = Counter(pred_labels) sorted_labels = sorted(true_counts, key=true_counts.get, reverse=True)",
"pred_counts[label] - true_counts[label] direction = '+' if diff > 0 else '-' if",
"{}'.format(pred_path)) if len(true_labels) != len(pred_labels): print('True and pred file do not have the",
"len(lab)) if len(lab) < 8 else lab for lab in sorted_labels] cm =",
"continue _, label = line.split('\\t') labels.append(label) return labels def compare_labels(true_labels, pred_labels): true_set =",
"diff = pred_counts[label] - true_counts[label] direction = '+' if diff > 0 else",
"sorted_labels = sorted(true_counts, key=true_counts.get, reverse=True) + sorted(pred_set - true_set) print('\\tTrue\\tPred\\tDiff') for label in",
"{})'.format( len(true_labels), len(pred_labels))) exit(-1) print('\\nFull label comparison:') compare_labels(true_labels, pred_labels) if set([lab[0] for lab",
"in true: {}'.format(true_set - pred_set)) print(' ~ Extra in pred: {}'.format(pred_set - true_set))",
"= Counter(true_labels) pred_counts = Counter(pred_labels) sorted_labels = sorted(true_counts, key=true_counts.get, reverse=True) + sorted(pred_set -",
"in true_labels] pred_label_binary = ['O' if lab == 'O' else 'X' for lab",
"= '+' if diff > 0 else '-' if diff < 0 else",
"_, label = line.split('\\t') labels.append(label) return labels def compare_labels(true_labels, pred_labels): true_set = set(true_labels)",
"true_set = set(true_labels) pred_set = set(pred_labels) print('\\n▶ Label usage:') print(' ~ Used in"
] |
[
"path Usage: download_and_extract_zip.py --url=<url> --out_file=<out_file> Options: <url> URL to download zip file from",
"with no password) <out_path> Path (including filename) of where to extract the zip",
"zip file from (must be a zip file with no password) out_path :",
"import zipfile import requests # from tqdm import tqdm from zipfile import BadZipFile",
"# from tqdm import tqdm from zipfile import BadZipFile from io import BytesIO",
"\"\"\" try: request = requests.get(url) zipdoc = zipfile.ZipFile(BytesIO(request.content)) for name in zipdoc.namelist(): print(\"Extracting...",
"b) except Exception as e: print(\"Error: \", e) if __name__ == \"__main__\": main(opt[\"--url\"],",
"Example: python download_and_extract_zip.py --url=https://archive.ics.uci.edu/ml/machine-learning-databases/00222/bank-additional.zip --out_file=\"../data/raw/\" \"\"\" import zipfile import requests # from tqdm",
"# author: <NAME> # date: 2020-11-19 \"\"\"Downloads a zip file and extracts all",
"python download_and_extract_zip.py --url=https://archive.ics.uci.edu/ml/machine-learning-databases/00222/bank-additional.zip --out_file=\"../data/raw/\" \"\"\" import zipfile import requests # from tqdm import",
"BadZipFile from io import BytesIO from docopt import docopt opt = docopt(__doc__) def",
"string URL to download zip file from (must be a zip file with",
"zipfile import requests # from tqdm import tqdm from zipfile import BadZipFile from",
"be a zip file with no password) <out_path> Path (including filename) of where",
"to a specified path Usage: download_and_extract_zip.py --url=<url> --out_file=<out_file> Options: <url> URL to download",
"main(url, out_path): \"\"\"[summary] Parameters ---------- url : string URL to download zip file",
"file from (must be a zip file with no password) out_path : string",
"import docopt opt = docopt(__doc__) def main(url, out_path): \"\"\"[summary] Parameters ---------- url :",
"(including filename) of where to extract the zip file contents to Example: python",
"BytesIO from docopt import docopt opt = docopt(__doc__) def main(url, out_path): \"\"\"[summary] Parameters",
"except Exception as e: print(\"Error: \", e) if __name__ == \"__main__\": main(opt[\"--url\"], opt[\"--out_file\"])",
"extract the zip file contents to Example: python download_and_extract_zip.py --url=https://archive.ics.uci.edu/ml/machine-learning-databases/00222/bank-additional.zip --out_file=\"../data/raw/\" \"\"\" import",
": string URL to download zip file from (must be a zip file",
"\"\"\"[summary] Parameters ---------- url : string URL to download zip file from (must",
"= requests.get(url) zipdoc = zipfile.ZipFile(BytesIO(request.content)) for name in zipdoc.namelist(): print(\"Extracting... {0}{1}\".format(out_path, name)) zipdoc.extract(name,",
"no password) <out_path> Path (including filename) of where to extract the zip file",
"file with no password) <out_path> Path (including filename) of where to extract the",
"from zipfile import BadZipFile from io import BytesIO from docopt import docopt opt",
"zip file and extracts all to a specified path Usage: download_and_extract_zip.py --url=<url> --out_file=<out_file>",
"out_path): \"\"\"[summary] Parameters ---------- url : string URL to download zip file from",
"(must be a zip file with no password) out_path : string Path to",
"zipfile.ZipFile(BytesIO(request.content)) for name in zipdoc.namelist(): print(\"Extracting... {0}{1}\".format(out_path, name)) zipdoc.extract(name, out_path) zipdoc.close() print(\"Done extracting",
"files from the ZipFile\") except BadZipFile as b: print(\"Error: \", b) except Exception",
"to extract the zip file contents to Example: python download_and_extract_zip.py --url=https://archive.ics.uci.edu/ml/machine-learning-databases/00222/bank-additional.zip --out_file=\"../data/raw/\" \"\"\"",
"\"../data/raw/\" \"\"\" try: request = requests.get(url) zipdoc = zipfile.ZipFile(BytesIO(request.content)) for name in zipdoc.namelist():",
"try: request = requests.get(url) zipdoc = zipfile.ZipFile(BytesIO(request.content)) for name in zipdoc.namelist(): print(\"Extracting... {0}{1}\".format(out_path,",
"Example ---------- main(f\"https://archive.ics.uci.edu/ml/machine-learning-databases/00222/bank-additional.zip\", \"../data/raw/\" \"\"\" try: request = requests.get(url) zipdoc = zipfile.ZipFile(BytesIO(request.content)) for",
"zip file from (must be a zip file with no password) <out_path> Path",
"where to extract the zip file contents to Example: python download_and_extract_zip.py --url=https://archive.ics.uci.edu/ml/machine-learning-databases/00222/bank-additional.zip --out_file=\"../data/raw/\"",
"date: 2020-11-19 \"\"\"Downloads a zip file and extracts all to a specified path",
"and extracts all to a specified path Usage: download_and_extract_zip.py --url=<url> --out_file=<out_file> Options: <url>",
"file from (must be a zip file with no password) <out_path> Path (including",
"print(\"Done extracting files from the ZipFile\") except BadZipFile as b: print(\"Error: \", b)",
"BadZipFile as b: print(\"Error: \", b) except Exception as e: print(\"Error: \", e)",
"<out_path> Path (including filename) of where to extract the zip file contents to",
"contents to Example: python download_and_extract_zip.py --url=https://archive.ics.uci.edu/ml/machine-learning-databases/00222/bank-additional.zip --out_file=\"../data/raw/\" \"\"\" import zipfile import requests #",
"download_and_extract_zip.py --url=https://archive.ics.uci.edu/ml/machine-learning-databases/00222/bank-additional.zip --out_file=\"../data/raw/\" \"\"\" import zipfile import requests # from tqdm import tqdm",
"\"\"\"Downloads a zip file and extracts all to a specified path Usage: download_and_extract_zip.py",
"password) <out_path> Path (including filename) of where to extract the zip file contents",
"download_and_extract_zip.py --url=<url> --out_file=<out_file> Options: <url> URL to download zip file from (must be",
"docopt import docopt opt = docopt(__doc__) def main(url, out_path): \"\"\"[summary] Parameters ---------- url",
"tqdm from zipfile import BadZipFile from io import BytesIO from docopt import docopt",
"to Example: python download_and_extract_zip.py --url=https://archive.ics.uci.edu/ml/machine-learning-databases/00222/bank-additional.zip --out_file=\"../data/raw/\" \"\"\" import zipfile import requests # from",
"a zip file and extracts all to a specified path Usage: download_and_extract_zip.py --url=<url>",
"for name in zipdoc.namelist(): print(\"Extracting... {0}{1}\".format(out_path, name)) zipdoc.extract(name, out_path) zipdoc.close() print(\"Done extracting files",
"password) out_path : string Path to extract the zip file contents to Example",
"Options: <url> URL to download zip file from (must be a zip file",
"= zipfile.ZipFile(BytesIO(request.content)) for name in zipdoc.namelist(): print(\"Extracting... {0}{1}\".format(out_path, name)) zipdoc.extract(name, out_path) zipdoc.close() print(\"Done",
"be a zip file with no password) out_path : string Path to extract",
"except BadZipFile as b: print(\"Error: \", b) except Exception as e: print(\"Error: \",",
"from tqdm import tqdm from zipfile import BadZipFile from io import BytesIO from",
"extract the zip file contents to Example ---------- main(f\"https://archive.ics.uci.edu/ml/machine-learning-databases/00222/bank-additional.zip\", \"../data/raw/\" \"\"\" try: request",
"from (must be a zip file with no password) out_path : string Path",
"string Path to extract the zip file contents to Example ---------- main(f\"https://archive.ics.uci.edu/ml/machine-learning-databases/00222/bank-additional.zip\", \"../data/raw/\"",
"Path (including filename) of where to extract the zip file contents to Example:",
"tqdm import tqdm from zipfile import BadZipFile from io import BytesIO from docopt",
"in zipdoc.namelist(): print(\"Extracting... {0}{1}\".format(out_path, name)) zipdoc.extract(name, out_path) zipdoc.close() print(\"Done extracting files from the",
"ZipFile\") except BadZipFile as b: print(\"Error: \", b) except Exception as e: print(\"Error:",
"no password) out_path : string Path to extract the zip file contents to",
"request = requests.get(url) zipdoc = zipfile.ZipFile(BytesIO(request.content)) for name in zipdoc.namelist(): print(\"Extracting... {0}{1}\".format(out_path, name))",
"out_path : string Path to extract the zip file contents to Example ----------",
"filename) of where to extract the zip file contents to Example: python download_and_extract_zip.py",
"name in zipdoc.namelist(): print(\"Extracting... {0}{1}\".format(out_path, name)) zipdoc.extract(name, out_path) zipdoc.close() print(\"Done extracting files from",
"to Example ---------- main(f\"https://archive.ics.uci.edu/ml/machine-learning-databases/00222/bank-additional.zip\", \"../data/raw/\" \"\"\" try: request = requests.get(url) zipdoc = zipfile.ZipFile(BytesIO(request.content))",
"# date: 2020-11-19 \"\"\"Downloads a zip file and extracts all to a specified",
"--out_file=\"../data/raw/\" \"\"\" import zipfile import requests # from tqdm import tqdm from zipfile",
"import tqdm from zipfile import BadZipFile from io import BytesIO from docopt import",
"print(\"Error: \", b) except Exception as e: print(\"Error: \", e) if __name__ ==",
"{0}{1}\".format(out_path, name)) zipdoc.extract(name, out_path) zipdoc.close() print(\"Done extracting files from the ZipFile\") except BadZipFile",
"opt = docopt(__doc__) def main(url, out_path): \"\"\"[summary] Parameters ---------- url : string URL",
"--url=<url> --out_file=<out_file> Options: <url> URL to download zip file from (must be a",
"Usage: download_and_extract_zip.py --url=<url> --out_file=<out_file> Options: <url> URL to download zip file from (must",
"zipdoc.extract(name, out_path) zipdoc.close() print(\"Done extracting files from the ZipFile\") except BadZipFile as b:",
"requests.get(url) zipdoc = zipfile.ZipFile(BytesIO(request.content)) for name in zipdoc.namelist(): print(\"Extracting... {0}{1}\".format(out_path, name)) zipdoc.extract(name, out_path)",
"print(\"Extracting... {0}{1}\".format(out_path, name)) zipdoc.extract(name, out_path) zipdoc.close() print(\"Done extracting files from the ZipFile\") except",
"<reponame>jufu/DSCI_522_Group_10 # author: <NAME> # date: 2020-11-19 \"\"\"Downloads a zip file and extracts",
"zipdoc = zipfile.ZipFile(BytesIO(request.content)) for name in zipdoc.namelist(): print(\"Extracting... {0}{1}\".format(out_path, name)) zipdoc.extract(name, out_path) zipdoc.close()",
"docopt opt = docopt(__doc__) def main(url, out_path): \"\"\"[summary] Parameters ---------- url : string",
"def main(url, out_path): \"\"\"[summary] Parameters ---------- url : string URL to download zip",
"zip file with no password) <out_path> Path (including filename) of where to extract",
"all to a specified path Usage: download_and_extract_zip.py --url=<url> --out_file=<out_file> Options: <url> URL to",
"url : string URL to download zip file from (must be a zip",
"requests # from tqdm import tqdm from zipfile import BadZipFile from io import",
"(must be a zip file with no password) <out_path> Path (including filename) of",
"from the ZipFile\") except BadZipFile as b: print(\"Error: \", b) except Exception as",
"---------- url : string URL to download zip file from (must be a",
"download zip file from (must be a zip file with no password) out_path",
"file and extracts all to a specified path Usage: download_and_extract_zip.py --url=<url> --out_file=<out_file> Options:",
"zipdoc.close() print(\"Done extracting files from the ZipFile\") except BadZipFile as b: print(\"Error: \",",
"a zip file with no password) out_path : string Path to extract the",
"the zip file contents to Example ---------- main(f\"https://archive.ics.uci.edu/ml/machine-learning-databases/00222/bank-additional.zip\", \"../data/raw/\" \"\"\" try: request =",
"zipfile import BadZipFile from io import BytesIO from docopt import docopt opt =",
"import BadZipFile from io import BytesIO from docopt import docopt opt = docopt(__doc__)",
"to extract the zip file contents to Example ---------- main(f\"https://archive.ics.uci.edu/ml/machine-learning-databases/00222/bank-additional.zip\", \"../data/raw/\" \"\"\" try:",
"as b: print(\"Error: \", b) except Exception as e: print(\"Error: \", e) if",
"zip file contents to Example ---------- main(f\"https://archive.ics.uci.edu/ml/machine-learning-databases/00222/bank-additional.zip\", \"../data/raw/\" \"\"\" try: request = requests.get(url)",
"import requests # from tqdm import tqdm from zipfile import BadZipFile from io",
"from io import BytesIO from docopt import docopt opt = docopt(__doc__) def main(url,",
"the ZipFile\") except BadZipFile as b: print(\"Error: \", b) except Exception as e:",
"out_path) zipdoc.close() print(\"Done extracting files from the ZipFile\") except BadZipFile as b: print(\"Error:",
"extracts all to a specified path Usage: download_and_extract_zip.py --url=<url> --out_file=<out_file> Options: <url> URL",
"a zip file with no password) <out_path> Path (including filename) of where to",
"main(f\"https://archive.ics.uci.edu/ml/machine-learning-databases/00222/bank-additional.zip\", \"../data/raw/\" \"\"\" try: request = requests.get(url) zipdoc = zipfile.ZipFile(BytesIO(request.content)) for name in",
": string Path to extract the zip file contents to Example ---------- main(f\"https://archive.ics.uci.edu/ml/machine-learning-databases/00222/bank-additional.zip\",",
"extracting files from the ZipFile\") except BadZipFile as b: print(\"Error: \", b) except",
"import BytesIO from docopt import docopt opt = docopt(__doc__) def main(url, out_path): \"\"\"[summary]",
"= docopt(__doc__) def main(url, out_path): \"\"\"[summary] Parameters ---------- url : string URL to",
"download zip file from (must be a zip file with no password) <out_path>",
"---------- main(f\"https://archive.ics.uci.edu/ml/machine-learning-databases/00222/bank-additional.zip\", \"../data/raw/\" \"\"\" try: request = requests.get(url) zipdoc = zipfile.ZipFile(BytesIO(request.content)) for name",
"zipdoc.namelist(): print(\"Extracting... {0}{1}\".format(out_path, name)) zipdoc.extract(name, out_path) zipdoc.close() print(\"Done extracting files from the ZipFile\")",
"from docopt import docopt opt = docopt(__doc__) def main(url, out_path): \"\"\"[summary] Parameters ----------",
"file with no password) out_path : string Path to extract the zip file",
"\", b) except Exception as e: print(\"Error: \", e) if __name__ == \"__main__\":",
"author: <NAME> # date: 2020-11-19 \"\"\"Downloads a zip file and extracts all to",
"--out_file=<out_file> Options: <url> URL to download zip file from (must be a zip",
"contents to Example ---------- main(f\"https://archive.ics.uci.edu/ml/machine-learning-databases/00222/bank-additional.zip\", \"../data/raw/\" \"\"\" try: request = requests.get(url) zipdoc =",
"<url> URL to download zip file from (must be a zip file with",
"the zip file contents to Example: python download_and_extract_zip.py --url=https://archive.ics.uci.edu/ml/machine-learning-databases/00222/bank-additional.zip --out_file=\"../data/raw/\" \"\"\" import zipfile",
"Parameters ---------- url : string URL to download zip file from (must be",
"<NAME> # date: 2020-11-19 \"\"\"Downloads a zip file and extracts all to a",
"with no password) out_path : string Path to extract the zip file contents",
"zip file contents to Example: python download_and_extract_zip.py --url=https://archive.ics.uci.edu/ml/machine-learning-databases/00222/bank-additional.zip --out_file=\"../data/raw/\" \"\"\" import zipfile import",
"zip file with no password) out_path : string Path to extract the zip",
"from (must be a zip file with no password) <out_path> Path (including filename)",
"to download zip file from (must be a zip file with no password)",
"--url=https://archive.ics.uci.edu/ml/machine-learning-databases/00222/bank-additional.zip --out_file=\"../data/raw/\" \"\"\" import zipfile import requests # from tqdm import tqdm from",
"b: print(\"Error: \", b) except Exception as e: print(\"Error: \", e) if __name__",
"specified path Usage: download_and_extract_zip.py --url=<url> --out_file=<out_file> Options: <url> URL to download zip file",
"2020-11-19 \"\"\"Downloads a zip file and extracts all to a specified path Usage:",
"\"\"\" import zipfile import requests # from tqdm import tqdm from zipfile import",
"docopt(__doc__) def main(url, out_path): \"\"\"[summary] Parameters ---------- url : string URL to download",
"of where to extract the zip file contents to Example: python download_and_extract_zip.py --url=https://archive.ics.uci.edu/ml/machine-learning-databases/00222/bank-additional.zip",
"URL to download zip file from (must be a zip file with no",
"file contents to Example ---------- main(f\"https://archive.ics.uci.edu/ml/machine-learning-databases/00222/bank-additional.zip\", \"../data/raw/\" \"\"\" try: request = requests.get(url) zipdoc",
"io import BytesIO from docopt import docopt opt = docopt(__doc__) def main(url, out_path):",
"a specified path Usage: download_and_extract_zip.py --url=<url> --out_file=<out_file> Options: <url> URL to download zip",
"Path to extract the zip file contents to Example ---------- main(f\"https://archive.ics.uci.edu/ml/machine-learning-databases/00222/bank-additional.zip\", \"../data/raw/\" \"\"\"",
"file contents to Example: python download_and_extract_zip.py --url=https://archive.ics.uci.edu/ml/machine-learning-databases/00222/bank-additional.zip --out_file=\"../data/raw/\" \"\"\" import zipfile import requests",
"name)) zipdoc.extract(name, out_path) zipdoc.close() print(\"Done extracting files from the ZipFile\") except BadZipFile as"
] |
[
"\"DERSetting\":\"default\", \"DERModelType\":\"ThreePhaseUnbalanced\", \"DERParameters\":{ \"default\":{ \"solarPenetration\":0.01, \"solarPenetrationUnit\":'kw', \"derId\":\"50\", \"powerRating\":50, \"VrmsRating\":177.0, \"steadyStateInitialization\":True, \"pvderScale\": 1, \"LVRT\":{\"0\":{\"V_threshold\":0.5,\"t_threshold\":0.1,\"mode\":\"momentary_cessation\"},",
"\"solarPenetrationUnit\":'kw', \"derId\":\"50\", \"powerRating\":50, \"VrmsRating\":177.0, \"steadyStateInitialization\":True, \"pvderScale\": 1, \"LVRT\":{\"0\":{\"V_threshold\":0.5,\"t_threshold\":0.1,\"mode\":\"momentary_cessation\"}, \"1\":{\"V_threshold\":0.7,\"t_threshold\":1.0,\"mode\":\"mandatory_operation\"}, \"2\":{\"V_threshold\":0.88,\"t_threshold\":2.0,\"mode\":\"mandatory_operation\"}}, \"HVRT\":{\"0\":{\"V_threshold\":1.12,\"t_threshold\":0.016,\"mode\":\"momentary_cessation\"}, \"1\":{\"V_threshold\":1.06,\"t_threshold\":3.0,\"mode\":\"momentary_cessation\"}}, \"output_restore_delay\":0.4",
"tdcosim dirlocation= os.path.dirname(tdcosim.__file__) dirlocation = dirlocation[0:len(dirlocation)-8] test_config = { \"nodenumber\": 11, \"filePath\": [os.path.join(dirlocation,\"SampleData\\\\DNetworks\\\\123Bus\\\\case123ZIP.dss\")],",
"\"1\":{\"V_threshold\":0.7,\"t_threshold\":1.0,\"mode\":\"mandatory_operation\"}, \"2\":{\"V_threshold\":0.88,\"t_threshold\":2.0,\"mode\":\"mandatory_operation\"}}, \"HVRT\":{\"0\":{\"V_threshold\":1.12,\"t_threshold\":0.016,\"mode\":\"momentary_cessation\"}, \"1\":{\"V_threshold\":1.06,\"t_threshold\":3.0,\"mode\":\"momentary_cessation\"}}, \"output_restore_delay\":0.4 }, \"PVPlacement\":{\"50\":{\"derId\":\"250\",\"powerRating\":250,\"pvderScale\":1,\"VrmsRating\":230.0}, \"25\":{\"derId\":\"50\",\"powerRating\":50,\"pvderScale\":1} }, \"avoidNodes\": ['sourcebus','rg60'], \"dt\":1/120.0 }",
"\"pvderScale\": 1, \"LVRT\":{\"0\":{\"V_threshold\":0.5,\"t_threshold\":0.1,\"mode\":\"momentary_cessation\"}, \"1\":{\"V_threshold\":0.7,\"t_threshold\":1.0,\"mode\":\"mandatory_operation\"}, \"2\":{\"V_threshold\":0.88,\"t_threshold\":2.0,\"mode\":\"mandatory_operation\"}}, \"HVRT\":{\"0\":{\"V_threshold\":1.12,\"t_threshold\":0.016,\"mode\":\"momentary_cessation\"}, \"1\":{\"V_threshold\":1.06,\"t_threshold\":3.0,\"mode\":\"momentary_cessation\"}}, \"output_restore_delay\":0.4 }, \"PVPlacement\":{\"50\":{\"derId\":\"250\",\"powerRating\":250,\"pvderScale\":1,\"VrmsRating\":230.0}, \"25\":{\"derId\":\"50\",\"powerRating\":50,\"pvderScale\":1} }, \"avoidNodes\":",
"\"\"\" import os import tdcosim dirlocation= os.path.dirname(tdcosim.__file__) dirlocation = dirlocation[0:len(dirlocation)-8] test_config = {",
"-*- coding: utf-8 -*- \"\"\" Created on Thu May 7 16:21:41 2020 @author:",
"-*- \"\"\" Created on Thu May 7 16:21:41 2020 @author: splathottam \"\"\" import",
"= { \"nodenumber\": 11, \"filePath\": [os.path.join(dirlocation,\"SampleData\\\\DNetworks\\\\123Bus\\\\case123ZIP.dss\")], \"solarFlag\":1, \"DERFilePath\": os.path.join(dirlocation,\"examples\\\\config_der.json\"), \"initializeWithActual\":True, \"DERSetting\":\"default\", \"DERModelType\":\"ThreePhaseUnbalanced\", \"DERParameters\":{",
"= dirlocation[0:len(dirlocation)-8] test_config = { \"nodenumber\": 11, \"filePath\": [os.path.join(dirlocation,\"SampleData\\\\DNetworks\\\\123Bus\\\\case123ZIP.dss\")], \"solarFlag\":1, \"DERFilePath\": os.path.join(dirlocation,\"examples\\\\config_der.json\"), \"initializeWithActual\":True,",
"os import tdcosim dirlocation= os.path.dirname(tdcosim.__file__) dirlocation = dirlocation[0:len(dirlocation)-8] test_config = { \"nodenumber\": 11,",
"dirlocation = dirlocation[0:len(dirlocation)-8] test_config = { \"nodenumber\": 11, \"filePath\": [os.path.join(dirlocation,\"SampleData\\\\DNetworks\\\\123Bus\\\\case123ZIP.dss\")], \"solarFlag\":1, \"DERFilePath\": os.path.join(dirlocation,\"examples\\\\config_der.json\"),",
"@author: splathottam \"\"\" import os import tdcosim dirlocation= os.path.dirname(tdcosim.__file__) dirlocation = dirlocation[0:len(dirlocation)-8] test_config",
"# -*- coding: utf-8 -*- \"\"\" Created on Thu May 7 16:21:41 2020",
"\"steadyStateInitialization\":True, \"pvderScale\": 1, \"LVRT\":{\"0\":{\"V_threshold\":0.5,\"t_threshold\":0.1,\"mode\":\"momentary_cessation\"}, \"1\":{\"V_threshold\":0.7,\"t_threshold\":1.0,\"mode\":\"mandatory_operation\"}, \"2\":{\"V_threshold\":0.88,\"t_threshold\":2.0,\"mode\":\"mandatory_operation\"}}, \"HVRT\":{\"0\":{\"V_threshold\":1.12,\"t_threshold\":0.016,\"mode\":\"momentary_cessation\"}, \"1\":{\"V_threshold\":1.06,\"t_threshold\":3.0,\"mode\":\"momentary_cessation\"}}, \"output_restore_delay\":0.4 }, \"PVPlacement\":{\"50\":{\"derId\":\"250\",\"powerRating\":250,\"pvderScale\":1,\"VrmsRating\":230.0}, \"25\":{\"derId\":\"50\",\"powerRating\":50,\"pvderScale\":1} },",
"16:21:41 2020 @author: splathottam \"\"\" import os import tdcosim dirlocation= os.path.dirname(tdcosim.__file__) dirlocation =",
"splathottam \"\"\" import os import tdcosim dirlocation= os.path.dirname(tdcosim.__file__) dirlocation = dirlocation[0:len(dirlocation)-8] test_config =",
"\"DERParameters\":{ \"default\":{ \"solarPenetration\":0.01, \"solarPenetrationUnit\":'kw', \"derId\":\"50\", \"powerRating\":50, \"VrmsRating\":177.0, \"steadyStateInitialization\":True, \"pvderScale\": 1, \"LVRT\":{\"0\":{\"V_threshold\":0.5,\"t_threshold\":0.1,\"mode\":\"momentary_cessation\"}, \"1\":{\"V_threshold\":0.7,\"t_threshold\":1.0,\"mode\":\"mandatory_operation\"}, \"2\":{\"V_threshold\":0.88,\"t_threshold\":2.0,\"mode\":\"mandatory_operation\"}},",
"\"LVRT\":{\"0\":{\"V_threshold\":0.5,\"t_threshold\":0.1,\"mode\":\"momentary_cessation\"}, \"1\":{\"V_threshold\":0.7,\"t_threshold\":1.0,\"mode\":\"mandatory_operation\"}, \"2\":{\"V_threshold\":0.88,\"t_threshold\":2.0,\"mode\":\"mandatory_operation\"}}, \"HVRT\":{\"0\":{\"V_threshold\":1.12,\"t_threshold\":0.016,\"mode\":\"momentary_cessation\"}, \"1\":{\"V_threshold\":1.06,\"t_threshold\":3.0,\"mode\":\"momentary_cessation\"}}, \"output_restore_delay\":0.4 }, \"PVPlacement\":{\"50\":{\"derId\":\"250\",\"powerRating\":250,\"pvderScale\":1,\"VrmsRating\":230.0}, \"25\":{\"derId\":\"50\",\"powerRating\":50,\"pvderScale\":1} }, \"avoidNodes\": ['sourcebus','rg60'], \"dt\":1/120.0",
"on Thu May 7 16:21:41 2020 @author: splathottam \"\"\" import os import tdcosim",
"import os import tdcosim dirlocation= os.path.dirname(tdcosim.__file__) dirlocation = dirlocation[0:len(dirlocation)-8] test_config = { \"nodenumber\":",
"7 16:21:41 2020 @author: splathottam \"\"\" import os import tdcosim dirlocation= os.path.dirname(tdcosim.__file__) dirlocation",
"\"DERFilePath\": os.path.join(dirlocation,\"examples\\\\config_der.json\"), \"initializeWithActual\":True, \"DERSetting\":\"default\", \"DERModelType\":\"ThreePhaseUnbalanced\", \"DERParameters\":{ \"default\":{ \"solarPenetration\":0.01, \"solarPenetrationUnit\":'kw', \"derId\":\"50\", \"powerRating\":50, \"VrmsRating\":177.0, \"steadyStateInitialization\":True,",
"2020 @author: splathottam \"\"\" import os import tdcosim dirlocation= os.path.dirname(tdcosim.__file__) dirlocation = dirlocation[0:len(dirlocation)-8]",
"\"DERModelType\":\"ThreePhaseUnbalanced\", \"DERParameters\":{ \"default\":{ \"solarPenetration\":0.01, \"solarPenetrationUnit\":'kw', \"derId\":\"50\", \"powerRating\":50, \"VrmsRating\":177.0, \"steadyStateInitialization\":True, \"pvderScale\": 1, \"LVRT\":{\"0\":{\"V_threshold\":0.5,\"t_threshold\":0.1,\"mode\":\"momentary_cessation\"}, \"1\":{\"V_threshold\":0.7,\"t_threshold\":1.0,\"mode\":\"mandatory_operation\"},",
"os.path.join(dirlocation,\"examples\\\\config_der.json\"), \"initializeWithActual\":True, \"DERSetting\":\"default\", \"DERModelType\":\"ThreePhaseUnbalanced\", \"DERParameters\":{ \"default\":{ \"solarPenetration\":0.01, \"solarPenetrationUnit\":'kw', \"derId\":\"50\", \"powerRating\":50, \"VrmsRating\":177.0, \"steadyStateInitialization\":True, \"pvderScale\":",
"May 7 16:21:41 2020 @author: splathottam \"\"\" import os import tdcosim dirlocation= os.path.dirname(tdcosim.__file__)",
"import tdcosim dirlocation= os.path.dirname(tdcosim.__file__) dirlocation = dirlocation[0:len(dirlocation)-8] test_config = { \"nodenumber\": 11, \"filePath\":",
"\"\"\" Created on Thu May 7 16:21:41 2020 @author: splathottam \"\"\" import os",
"utf-8 -*- \"\"\" Created on Thu May 7 16:21:41 2020 @author: splathottam \"\"\"",
"\"derId\":\"50\", \"powerRating\":50, \"VrmsRating\":177.0, \"steadyStateInitialization\":True, \"pvderScale\": 1, \"LVRT\":{\"0\":{\"V_threshold\":0.5,\"t_threshold\":0.1,\"mode\":\"momentary_cessation\"}, \"1\":{\"V_threshold\":0.7,\"t_threshold\":1.0,\"mode\":\"mandatory_operation\"}, \"2\":{\"V_threshold\":0.88,\"t_threshold\":2.0,\"mode\":\"mandatory_operation\"}}, \"HVRT\":{\"0\":{\"V_threshold\":1.12,\"t_threshold\":0.016,\"mode\":\"momentary_cessation\"}, \"1\":{\"V_threshold\":1.06,\"t_threshold\":3.0,\"mode\":\"momentary_cessation\"}}, \"output_restore_delay\":0.4 },",
"\"powerRating\":50, \"VrmsRating\":177.0, \"steadyStateInitialization\":True, \"pvderScale\": 1, \"LVRT\":{\"0\":{\"V_threshold\":0.5,\"t_threshold\":0.1,\"mode\":\"momentary_cessation\"}, \"1\":{\"V_threshold\":0.7,\"t_threshold\":1.0,\"mode\":\"mandatory_operation\"}, \"2\":{\"V_threshold\":0.88,\"t_threshold\":2.0,\"mode\":\"mandatory_operation\"}}, \"HVRT\":{\"0\":{\"V_threshold\":1.12,\"t_threshold\":0.016,\"mode\":\"momentary_cessation\"}, \"1\":{\"V_threshold\":1.06,\"t_threshold\":3.0,\"mode\":\"momentary_cessation\"}}, \"output_restore_delay\":0.4 }, \"PVPlacement\":{\"50\":{\"derId\":\"250\",\"powerRating\":250,\"pvderScale\":1,\"VrmsRating\":230.0},",
"\"2\":{\"V_threshold\":0.88,\"t_threshold\":2.0,\"mode\":\"mandatory_operation\"}}, \"HVRT\":{\"0\":{\"V_threshold\":1.12,\"t_threshold\":0.016,\"mode\":\"momentary_cessation\"}, \"1\":{\"V_threshold\":1.06,\"t_threshold\":3.0,\"mode\":\"momentary_cessation\"}}, \"output_restore_delay\":0.4 }, \"PVPlacement\":{\"50\":{\"derId\":\"250\",\"powerRating\":250,\"pvderScale\":1,\"VrmsRating\":230.0}, \"25\":{\"derId\":\"50\",\"powerRating\":50,\"pvderScale\":1} }, \"avoidNodes\": ['sourcebus','rg60'], \"dt\":1/120.0 } }",
"\"filePath\": [os.path.join(dirlocation,\"SampleData\\\\DNetworks\\\\123Bus\\\\case123ZIP.dss\")], \"solarFlag\":1, \"DERFilePath\": os.path.join(dirlocation,\"examples\\\\config_der.json\"), \"initializeWithActual\":True, \"DERSetting\":\"default\", \"DERModelType\":\"ThreePhaseUnbalanced\", \"DERParameters\":{ \"default\":{ \"solarPenetration\":0.01, \"solarPenetrationUnit\":'kw', \"derId\":\"50\",",
"<gh_stars>10-100 # -*- coding: utf-8 -*- \"\"\" Created on Thu May 7 16:21:41",
"\"initializeWithActual\":True, \"DERSetting\":\"default\", \"DERModelType\":\"ThreePhaseUnbalanced\", \"DERParameters\":{ \"default\":{ \"solarPenetration\":0.01, \"solarPenetrationUnit\":'kw', \"derId\":\"50\", \"powerRating\":50, \"VrmsRating\":177.0, \"steadyStateInitialization\":True, \"pvderScale\": 1,",
"\"default\":{ \"solarPenetration\":0.01, \"solarPenetrationUnit\":'kw', \"derId\":\"50\", \"powerRating\":50, \"VrmsRating\":177.0, \"steadyStateInitialization\":True, \"pvderScale\": 1, \"LVRT\":{\"0\":{\"V_threshold\":0.5,\"t_threshold\":0.1,\"mode\":\"momentary_cessation\"}, \"1\":{\"V_threshold\":0.7,\"t_threshold\":1.0,\"mode\":\"mandatory_operation\"}, \"2\":{\"V_threshold\":0.88,\"t_threshold\":2.0,\"mode\":\"mandatory_operation\"}}, \"HVRT\":{\"0\":{\"V_threshold\":1.12,\"t_threshold\":0.016,\"mode\":\"momentary_cessation\"},",
"\"VrmsRating\":177.0, \"steadyStateInitialization\":True, \"pvderScale\": 1, \"LVRT\":{\"0\":{\"V_threshold\":0.5,\"t_threshold\":0.1,\"mode\":\"momentary_cessation\"}, \"1\":{\"V_threshold\":0.7,\"t_threshold\":1.0,\"mode\":\"mandatory_operation\"}, \"2\":{\"V_threshold\":0.88,\"t_threshold\":2.0,\"mode\":\"mandatory_operation\"}}, \"HVRT\":{\"0\":{\"V_threshold\":1.12,\"t_threshold\":0.016,\"mode\":\"momentary_cessation\"}, \"1\":{\"V_threshold\":1.06,\"t_threshold\":3.0,\"mode\":\"momentary_cessation\"}}, \"output_restore_delay\":0.4 }, \"PVPlacement\":{\"50\":{\"derId\":\"250\",\"powerRating\":250,\"pvderScale\":1,\"VrmsRating\":230.0}, \"25\":{\"derId\":\"50\",\"powerRating\":50,\"pvderScale\":1}",
"\"nodenumber\": 11, \"filePath\": [os.path.join(dirlocation,\"SampleData\\\\DNetworks\\\\123Bus\\\\case123ZIP.dss\")], \"solarFlag\":1, \"DERFilePath\": os.path.join(dirlocation,\"examples\\\\config_der.json\"), \"initializeWithActual\":True, \"DERSetting\":\"default\", \"DERModelType\":\"ThreePhaseUnbalanced\", \"DERParameters\":{ \"default\":{ \"solarPenetration\":0.01,",
"1, \"LVRT\":{\"0\":{\"V_threshold\":0.5,\"t_threshold\":0.1,\"mode\":\"momentary_cessation\"}, \"1\":{\"V_threshold\":0.7,\"t_threshold\":1.0,\"mode\":\"mandatory_operation\"}, \"2\":{\"V_threshold\":0.88,\"t_threshold\":2.0,\"mode\":\"mandatory_operation\"}}, \"HVRT\":{\"0\":{\"V_threshold\":1.12,\"t_threshold\":0.016,\"mode\":\"momentary_cessation\"}, \"1\":{\"V_threshold\":1.06,\"t_threshold\":3.0,\"mode\":\"momentary_cessation\"}}, \"output_restore_delay\":0.4 }, \"PVPlacement\":{\"50\":{\"derId\":\"250\",\"powerRating\":250,\"pvderScale\":1,\"VrmsRating\":230.0}, \"25\":{\"derId\":\"50\",\"powerRating\":50,\"pvderScale\":1} }, \"avoidNodes\": ['sourcebus','rg60'],",
"{ \"nodenumber\": 11, \"filePath\": [os.path.join(dirlocation,\"SampleData\\\\DNetworks\\\\123Bus\\\\case123ZIP.dss\")], \"solarFlag\":1, \"DERFilePath\": os.path.join(dirlocation,\"examples\\\\config_der.json\"), \"initializeWithActual\":True, \"DERSetting\":\"default\", \"DERModelType\":\"ThreePhaseUnbalanced\", \"DERParameters\":{ \"default\":{",
"Thu May 7 16:21:41 2020 @author: splathottam \"\"\" import os import tdcosim dirlocation=",
"os.path.dirname(tdcosim.__file__) dirlocation = dirlocation[0:len(dirlocation)-8] test_config = { \"nodenumber\": 11, \"filePath\": [os.path.join(dirlocation,\"SampleData\\\\DNetworks\\\\123Bus\\\\case123ZIP.dss\")], \"solarFlag\":1, \"DERFilePath\":",
"Created on Thu May 7 16:21:41 2020 @author: splathottam \"\"\" import os import",
"test_config = { \"nodenumber\": 11, \"filePath\": [os.path.join(dirlocation,\"SampleData\\\\DNetworks\\\\123Bus\\\\case123ZIP.dss\")], \"solarFlag\":1, \"DERFilePath\": os.path.join(dirlocation,\"examples\\\\config_der.json\"), \"initializeWithActual\":True, \"DERSetting\":\"default\", \"DERModelType\":\"ThreePhaseUnbalanced\",",
"\"solarFlag\":1, \"DERFilePath\": os.path.join(dirlocation,\"examples\\\\config_der.json\"), \"initializeWithActual\":True, \"DERSetting\":\"default\", \"DERModelType\":\"ThreePhaseUnbalanced\", \"DERParameters\":{ \"default\":{ \"solarPenetration\":0.01, \"solarPenetrationUnit\":'kw', \"derId\":\"50\", \"powerRating\":50, \"VrmsRating\":177.0,",
"dirlocation[0:len(dirlocation)-8] test_config = { \"nodenumber\": 11, \"filePath\": [os.path.join(dirlocation,\"SampleData\\\\DNetworks\\\\123Bus\\\\case123ZIP.dss\")], \"solarFlag\":1, \"DERFilePath\": os.path.join(dirlocation,\"examples\\\\config_der.json\"), \"initializeWithActual\":True, \"DERSetting\":\"default\",",
"coding: utf-8 -*- \"\"\" Created on Thu May 7 16:21:41 2020 @author: splathottam",
"dirlocation= os.path.dirname(tdcosim.__file__) dirlocation = dirlocation[0:len(dirlocation)-8] test_config = { \"nodenumber\": 11, \"filePath\": [os.path.join(dirlocation,\"SampleData\\\\DNetworks\\\\123Bus\\\\case123ZIP.dss\")], \"solarFlag\":1,",
"\"solarPenetration\":0.01, \"solarPenetrationUnit\":'kw', \"derId\":\"50\", \"powerRating\":50, \"VrmsRating\":177.0, \"steadyStateInitialization\":True, \"pvderScale\": 1, \"LVRT\":{\"0\":{\"V_threshold\":0.5,\"t_threshold\":0.1,\"mode\":\"momentary_cessation\"}, \"1\":{\"V_threshold\":0.7,\"t_threshold\":1.0,\"mode\":\"mandatory_operation\"}, \"2\":{\"V_threshold\":0.88,\"t_threshold\":2.0,\"mode\":\"mandatory_operation\"}}, \"HVRT\":{\"0\":{\"V_threshold\":1.12,\"t_threshold\":0.016,\"mode\":\"momentary_cessation\"}, \"1\":{\"V_threshold\":1.06,\"t_threshold\":3.0,\"mode\":\"momentary_cessation\"}},",
"[os.path.join(dirlocation,\"SampleData\\\\DNetworks\\\\123Bus\\\\case123ZIP.dss\")], \"solarFlag\":1, \"DERFilePath\": os.path.join(dirlocation,\"examples\\\\config_der.json\"), \"initializeWithActual\":True, \"DERSetting\":\"default\", \"DERModelType\":\"ThreePhaseUnbalanced\", \"DERParameters\":{ \"default\":{ \"solarPenetration\":0.01, \"solarPenetrationUnit\":'kw', \"derId\":\"50\", \"powerRating\":50,",
"11, \"filePath\": [os.path.join(dirlocation,\"SampleData\\\\DNetworks\\\\123Bus\\\\case123ZIP.dss\")], \"solarFlag\":1, \"DERFilePath\": os.path.join(dirlocation,\"examples\\\\config_der.json\"), \"initializeWithActual\":True, \"DERSetting\":\"default\", \"DERModelType\":\"ThreePhaseUnbalanced\", \"DERParameters\":{ \"default\":{ \"solarPenetration\":0.01, \"solarPenetrationUnit\":'kw',"
] |
[
"= variant.get('env_id', None) N = variant.get('N', 100) rollout_length = variant.get('rollout_length', 100) test_p =",
"= np.zeros((N, rollout_length, act_dim)) for i in range(N): env.reset() for j in range(rollout_length):",
"::-1] cv2.imshow('img', img) cv2.waitKey(1) print(\"done making training data\", filename, time.time() - now) dataset",
"cv2.waitKey(1) print(\"done making training data\", filename, time.time() - now) dataset = {\"imgs\": imgs,",
"training data\", filename, time.time() - now) dataset = {\"imgs\": imgs, \"actions\": actions} print(imgs.shape)",
"show = variant.get('show', False) init_camera = variant.get('init_camera', None) dataset_path = variant.get('dataset_path', None) oracle_dataset_using_set_to_goal",
"np.load(filename) print(\"loaded data from saved file\", filename) else: now = time.time() multiworld.register_all_envs() env",
"img = img.reshape(3, imsize, imsize).transpose() img = img[::-1, :, ::-1] cv2.imshow('img', img) cv2.waitKey(1)",
"multiworld.register_all_envs() env = gym.make(env_id) if not isinstance(env, ImageEnv): env = ImageEnv( env, imsize,",
"not osp.exists('./data/tmp/'): os.makedirs('./data/tmp/') info = {} import os if not os.path.exists(\"./data/tmp/\"): os.makedirs(\"./data/tmp/\") if",
"j, :] = unormalize_image(img) actions[i,j, :] = action if show: img = img.reshape(3,",
"init_camera = variant.get('init_camera', None) dataset_path = variant.get('dataset_path', None) oracle_dataset_using_set_to_goal = variant.get( 'oracle_dataset_using_set_to_goal', False)",
"as ptu import gym import multiworld def generate_scalor_dataset(variant): env_kwargs = variant.get('env_kwargs', None) env_id",
"scalor_params = variant.get(\"scalor_params\", dict()) scalor_params[\"logdir\"] = logger.get_snapshot_dir() scalor = SCALOR(**scalor_params) data, info =",
"imsize, tag, ) import os if not osp.exists('./data/tmp/'): os.makedirs('./data/tmp/') info = {} import",
"ImageEnv): env = ImageEnv( env, imsize, init_camera=init_camera, transpose=True, normalize=True, non_presampled_goal_img_is_garbage=True, ) env.reset() act_dim",
"= env_id filename = \"./data/tmp/{}_N{}_rollout_length{}_imsize{}_{}{}.npz\".format( save_file_prefix, str(N), str(rollout_length), init_camera.__name__ if init_camera else '',",
"np.zeros((N, rollout_length, imsize * imsize * num_channels), dtype=np.uint8) actions = np.zeros((N, rollout_length, act_dim))",
"env.step(action)[0] img = obs['image_observation'] imgs[i, j, :] = unormalize_image(img) actions[i,j, :] = action",
"is None: save_file_prefix = env_id filename = \"./data/tmp/{}_N{}_rollout_length{}_imsize{}_{}{}.npz\".format( save_file_prefix, str(N), str(rollout_length), init_camera.__name__ if",
"variant.get('random_and_oracle_policy_data', False) random_and_oracle_policy_data_split = variant.get( 'random_and_oracle_policy_data_split', 0) policy_file = variant.get('policy_file', None) n_random_steps =",
"N = variant.get('N', 100) rollout_length = variant.get('rollout_length', 100) test_p = variant.get('test_p', 0.9) use_cached",
"= \"./data/tmp/{}_N{}_rollout_length{}_imsize{}_{}{}.npz\".format( save_file_prefix, str(N), str(rollout_length), init_camera.__name__ if init_camera else '', imsize, tag, )",
"imgs, \"actions\": actions} print(imgs.shape) # np.savez(filename, **dataset) return dataset, info def scalor_training(variant): scalor_params",
"load_local_or_remote_file import rlkit.torch.pytorch_util as ptu import gym import multiworld def generate_scalor_dataset(variant): env_kwargs =",
"return dataset, info def scalor_training(variant): scalor_params = variant.get(\"scalor_params\", dict()) scalor_params[\"logdir\"] = logger.get_snapshot_dir() scalor",
"if use_cached and osp.isfile(filename): dataset = np.load(filename) print(\"loaded data from saved file\", filename)",
"img[::-1, :, ::-1] cv2.imshow('img', img) cv2.waitKey(1) print(\"done making training data\", filename, time.time() -",
"save_file_prefix = env_id filename = \"./data/tmp/{}_N{}_rollout_length{}_imsize{}_{}{}.npz\".format( save_file_prefix, str(N), str(rollout_length), init_camera.__name__ if init_camera else",
"import os if not osp.exists('./data/tmp/'): os.makedirs('./data/tmp/') info = {} import os if not",
"rollout_length, act_dim)) for i in range(N): env.reset() for j in range(rollout_length): action =",
":, ::-1] cv2.imshow('img', img) cv2.waitKey(1) print(\"done making training data\", filename, time.time() - now)",
"= env.action_space.low.size info['env'] = env imgs = np.zeros((N, rollout_length, imsize * imsize *",
"= variant.get('show', False) init_camera = variant.get('init_camera', None) dataset_path = variant.get('dataset_path', None) oracle_dataset_using_set_to_goal =",
"= img.reshape(3, imsize, imsize).transpose() img = img[::-1, :, ::-1] cv2.imshow('img', img) cv2.waitKey(1) print(\"done",
"variant.get('random_rollout_data', False) random_and_oracle_policy_data = variant.get('random_and_oracle_policy_data', False) random_and_oracle_policy_data_split = variant.get( 'random_and_oracle_policy_data_split', 0) policy_file =",
"variant.get('dataset_path', None) oracle_dataset_using_set_to_goal = variant.get( 'oracle_dataset_using_set_to_goal', False) random_rollout_data = variant.get('random_rollout_data', False) random_and_oracle_policy_data =",
"test_p = variant.get('test_p', 0.9) use_cached = variant.get('use_cached', True) imsize = variant.get('imsize', 64) num_channels",
"import multiworld def generate_scalor_dataset(variant): env_kwargs = variant.get('env_kwargs', None) env_id = variant.get('env_id', None) N",
"variant.get( 'random_and_oracle_policy_data_split', 0) policy_file = variant.get('policy_file', None) n_random_steps = 1 scalor_dataset_specific_env_kwargs = variant.get(",
"from rlkit.util.io import load_local_or_remote_file import rlkit.torch.pytorch_util as ptu import gym import multiworld def",
"False) random_and_oracle_policy_data_split = variant.get( 'random_and_oracle_policy_data_split', 0) policy_file = variant.get('policy_file', None) n_random_steps = 1",
"SCALOR(**scalor_params) data, info = generate_scalor_dataset(variant['generate_scalor_dataset_kwargs']) imgs, actions = data[\"imgs\"], data[\"actions\"] imgs = normalize_image(imgs)",
"= env imgs = np.zeros((N, rollout_length, imsize * imsize * num_channels), dtype=np.uint8) actions",
"if save_file_prefix is None: save_file_prefix = env_id filename = \"./data/tmp/{}_N{}_rollout_length{}_imsize{}_{}{}.npz\".format( save_file_prefix, str(N), str(rollout_length),",
"= variant.get( 'random_and_oracle_policy_data_split', 0) policy_file = variant.get('policy_file', None) n_random_steps = 1 scalor_dataset_specific_env_kwargs =",
"info = generate_scalor_dataset(variant['generate_scalor_dataset_kwargs']) imgs, actions = data[\"imgs\"], data[\"actions\"] imgs = normalize_image(imgs) scalor.train(imgs=imgs, actions=actions)",
"= np.zeros((N, rollout_length, imsize * imsize * num_channels), dtype=np.uint8) actions = np.zeros((N, rollout_length,",
"for j in range(rollout_length): action = env.action_space.sample() obs = env.step(action)[0] img = obs['image_observation']",
"= action if show: img = img.reshape(3, imsize, imsize).transpose() img = img[::-1, :,",
"imsize, init_camera=init_camera, transpose=True, normalize=True, non_presampled_goal_img_is_garbage=True, ) env.reset() act_dim = env.action_space.low.size info['env'] = env",
"scalor = SCALOR(**scalor_params) data, info = generate_scalor_dataset(variant['generate_scalor_dataset_kwargs']) imgs, actions = data[\"imgs\"], data[\"actions\"] imgs",
"variant.get('rollout_length', 100) test_p = variant.get('test_p', 0.9) use_cached = variant.get('use_cached', True) imsize = variant.get('imsize',",
"from saved file\", filename) else: now = time.time() multiworld.register_all_envs() env = gym.make(env_id) if",
"dataset = {\"imgs\": imgs, \"actions\": actions} print(imgs.shape) # np.savez(filename, **dataset) return dataset, info",
"= env.step(action)[0] img = obs['image_observation'] imgs[i, j, :] = unormalize_image(img) actions[i,j, :] =",
"init_camera else '', imsize, tag, ) import os if not osp.exists('./data/tmp/'): os.makedirs('./data/tmp/') info",
"os if not osp.exists('./data/tmp/'): os.makedirs('./data/tmp/') info = {} import os if not os.path.exists(\"./data/tmp/\"):",
") env.reset() act_dim = env.action_space.low.size info['env'] = env imgs = np.zeros((N, rollout_length, imsize",
"= {} if save_file_prefix is None: save_file_prefix = env_id filename = \"./data/tmp/{}_N{}_rollout_length{}_imsize{}_{}{}.npz\".format( save_file_prefix,",
"as np import os.path as osp from rlkit.samplers.data_collector.scalor_env import WrappedEnvPathCollector as SCALORWrappedEnvPathCollector from",
"normalize=True, non_presampled_goal_img_is_garbage=True, ) env.reset() act_dim = env.action_space.low.size info['env'] = env imgs = np.zeros((N,",
"if not os.path.exists(\"./data/tmp/\"): os.makedirs(\"./data/tmp/\") if use_cached and osp.isfile(filename): dataset = np.load(filename) print(\"loaded data",
"os.path as osp from rlkit.samplers.data_collector.scalor_env import WrappedEnvPathCollector as SCALORWrappedEnvPathCollector from rlkit.torch.scalor.scalor import SCALOR",
"0) policy_file = variant.get('policy_file', None) n_random_steps = 1 scalor_dataset_specific_env_kwargs = variant.get( 'scalor_dataset_specific_env_kwargs', None)",
"import os if not os.path.exists(\"./data/tmp/\"): os.makedirs(\"./data/tmp/\") if use_cached and osp.isfile(filename): dataset = np.load(filename)",
"info['env'] = env imgs = np.zeros((N, rollout_length, imsize * imsize * num_channels), dtype=np.uint8)",
"False) random_and_oracle_policy_data = variant.get('random_and_oracle_policy_data', False) random_and_oracle_policy_data_split = variant.get( 'random_and_oracle_policy_data_split', 0) policy_file = variant.get('policy_file',",
"if not isinstance(env, ImageEnv): env = ImageEnv( env, imsize, init_camera=init_camera, transpose=True, normalize=True, non_presampled_goal_img_is_garbage=True,",
"in range(N): env.reset() for j in range(rollout_length): action = env.action_space.sample() obs = env.step(action)[0]",
"variant.get('test_p', 0.9) use_cached = variant.get('use_cached', True) imsize = variant.get('imsize', 64) num_channels = variant.get('num_channels',",
"= time.time() multiworld.register_all_envs() env = gym.make(env_id) if not isinstance(env, ImageEnv): env = ImageEnv(",
"WrappedEnvPathCollector as SCALORWrappedEnvPathCollector from rlkit.torch.scalor.scalor import SCALOR from rlkit.util.video import dump_video from rlkit.util.io",
"SCALORWrappedEnvPathCollector from rlkit.torch.scalor.scalor import SCALOR from rlkit.util.video import dump_video from rlkit.util.io import load_local_or_remote_file",
"os.path.exists(\"./data/tmp/\"): os.makedirs(\"./data/tmp/\") if use_cached and osp.isfile(filename): dataset = np.load(filename) print(\"loaded data from saved",
"for i in range(N): env.reset() for j in range(rollout_length): action = env.action_space.sample() obs",
"variant.get('N', 100) rollout_length = variant.get('rollout_length', 100) test_p = variant.get('test_p', 0.9) use_cached = variant.get('use_cached',",
"actions} print(imgs.shape) # np.savez(filename, **dataset) return dataset, info def scalor_training(variant): scalor_params = variant.get(\"scalor_params\",",
"variant.get('show', False) init_camera = variant.get('init_camera', None) dataset_path = variant.get('dataset_path', None) oracle_dataset_using_set_to_goal = variant.get(",
"if not osp.exists('./data/tmp/'): os.makedirs('./data/tmp/') info = {} import os if not os.path.exists(\"./data/tmp/\"): os.makedirs(\"./data/tmp/\")",
"* imsize * num_channels), dtype=np.uint8) actions = np.zeros((N, rollout_length, act_dim)) for i in",
"dict()) scalor_params[\"logdir\"] = logger.get_snapshot_dir() scalor = SCALOR(**scalor_params) data, info = generate_scalor_dataset(variant['generate_scalor_dataset_kwargs']) imgs, actions",
"from rlkit.samplers.data_collector.scalor_env import WrappedEnvPathCollector as SCALORWrappedEnvPathCollector from rlkit.torch.scalor.scalor import SCALOR from rlkit.util.video import",
"policy_file = variant.get('policy_file', None) n_random_steps = 1 scalor_dataset_specific_env_kwargs = variant.get( 'scalor_dataset_specific_env_kwargs', None) save_file_prefix",
"import cv2 import numpy as np import os.path as osp from rlkit.samplers.data_collector.scalor_env import",
"imgs = np.zeros((N, rollout_length, imsize * imsize * num_channels), dtype=np.uint8) actions = np.zeros((N,",
"= variant.get('random_and_oracle_policy_data', False) random_and_oracle_policy_data_split = variant.get( 'random_and_oracle_policy_data_split', 0) policy_file = variant.get('policy_file', None) n_random_steps",
"import dump_video from rlkit.util.io import load_local_or_remote_file import rlkit.torch.pytorch_util as ptu import gym import",
"'scalor_dataset_specific_env_kwargs', None) save_file_prefix = variant.get('save_file_prefix', None) tag = variant.get('tag', '') if env_kwargs is",
"imsize).transpose() img = img[::-1, :, ::-1] cv2.imshow('img', img) cv2.waitKey(1) print(\"done making training data\",",
"save_file_prefix, str(N), str(rollout_length), init_camera.__name__ if init_camera else '', imsize, tag, ) import os",
"logger.get_snapshot_dir() scalor = SCALOR(**scalor_params) data, info = generate_scalor_dataset(variant['generate_scalor_dataset_kwargs']) imgs, actions = data[\"imgs\"], data[\"actions\"]",
"**dataset) return dataset, info def scalor_training(variant): scalor_params = variant.get(\"scalor_params\", dict()) scalor_params[\"logdir\"] = logger.get_snapshot_dir()",
"imsize * imsize * num_channels), dtype=np.uint8) actions = np.zeros((N, rollout_length, act_dim)) for i",
"cv2 import numpy as np import os.path as osp from rlkit.samplers.data_collector.scalor_env import WrappedEnvPathCollector",
"ptu import gym import multiworld def generate_scalor_dataset(variant): env_kwargs = variant.get('env_kwargs', None) env_id =",
"dataset, info def scalor_training(variant): scalor_params = variant.get(\"scalor_params\", dict()) scalor_params[\"logdir\"] = logger.get_snapshot_dir() scalor =",
"env imgs = np.zeros((N, rollout_length, imsize * imsize * num_channels), dtype=np.uint8) actions =",
":] = action if show: img = img.reshape(3, imsize, imsize).transpose() img = img[::-1,",
"obs['image_observation'] imgs[i, j, :] = unormalize_image(img) actions[i,j, :] = action if show: img",
"= variant.get('policy_file', None) n_random_steps = 1 scalor_dataset_specific_env_kwargs = variant.get( 'scalor_dataset_specific_env_kwargs', None) save_file_prefix =",
"and osp.isfile(filename): dataset = np.load(filename) print(\"loaded data from saved file\", filename) else: now",
"n_random_steps = 1 scalor_dataset_specific_env_kwargs = variant.get( 'scalor_dataset_specific_env_kwargs', None) save_file_prefix = variant.get('save_file_prefix', None) tag",
"scalor_params[\"logdir\"] = logger.get_snapshot_dir() scalor = SCALOR(**scalor_params) data, info = generate_scalor_dataset(variant['generate_scalor_dataset_kwargs']) imgs, actions =",
"scalor_dataset_specific_env_kwargs = variant.get( 'scalor_dataset_specific_env_kwargs', None) save_file_prefix = variant.get('save_file_prefix', None) tag = variant.get('tag', '')",
"osp.isfile(filename): dataset = np.load(filename) print(\"loaded data from saved file\", filename) else: now =",
":] = unormalize_image(img) actions[i,j, :] = action if show: img = img.reshape(3, imsize,",
"transpose=True, normalize=True, non_presampled_goal_img_is_garbage=True, ) env.reset() act_dim = env.action_space.low.size info['env'] = env imgs =",
"os.makedirs(\"./data/tmp/\") if use_cached and osp.isfile(filename): dataset = np.load(filename) print(\"loaded data from saved file\",",
"unormalize_image(img) actions[i,j, :] = action if show: img = img.reshape(3, imsize, imsize).transpose() img",
"oracle_dataset_using_set_to_goal = variant.get( 'oracle_dataset_using_set_to_goal', False) random_rollout_data = variant.get('random_rollout_data', False) random_and_oracle_policy_data = variant.get('random_and_oracle_policy_data', False)",
"= obs['image_observation'] imgs[i, j, :] = unormalize_image(img) actions[i,j, :] = action if show:",
"import ImageEnv, unormalize_image, normalize_image from rlkit.core import logger import cv2 import numpy as",
"False) init_camera = variant.get('init_camera', None) dataset_path = variant.get('dataset_path', None) oracle_dataset_using_set_to_goal = variant.get( 'oracle_dataset_using_set_to_goal',",
"= unormalize_image(img) actions[i,j, :] = action if show: img = img.reshape(3, imsize, imsize).transpose()",
"info def scalor_training(variant): scalor_params = variant.get(\"scalor_params\", dict()) scalor_params[\"logdir\"] = logger.get_snapshot_dir() scalor = SCALOR(**scalor_params)",
"np import os.path as osp from rlkit.samplers.data_collector.scalor_env import WrappedEnvPathCollector as SCALORWrappedEnvPathCollector from rlkit.torch.scalor.scalor",
"print(\"loaded data from saved file\", filename) else: now = time.time() multiworld.register_all_envs() env =",
"filename, time.time() - now) dataset = {\"imgs\": imgs, \"actions\": actions} print(imgs.shape) # np.savez(filename,",
"multiworld.core.image_env import ImageEnv, unormalize_image, normalize_image from rlkit.core import logger import cv2 import numpy",
"img = img[::-1, :, ::-1] cv2.imshow('img', img) cv2.waitKey(1) print(\"done making training data\", filename,",
"64) num_channels = variant.get('num_channels', 3) show = variant.get('show', False) init_camera = variant.get('init_camera', None)",
"= img[::-1, :, ::-1] cv2.imshow('img', img) cv2.waitKey(1) print(\"done making training data\", filename, time.time()",
"filename) else: now = time.time() multiworld.register_all_envs() env = gym.make(env_id) if not isinstance(env, ImageEnv):",
"= SCALOR(**scalor_params) data, info = generate_scalor_dataset(variant['generate_scalor_dataset_kwargs']) imgs, actions = data[\"imgs\"], data[\"actions\"] imgs =",
"'') if env_kwargs is None: env_kwargs = {} if save_file_prefix is None: save_file_prefix",
"None: env_kwargs = {} if save_file_prefix is None: save_file_prefix = env_id filename =",
"= variant.get('tag', '') if env_kwargs is None: env_kwargs = {} if save_file_prefix is",
"not isinstance(env, ImageEnv): env = ImageEnv( env, imsize, init_camera=init_camera, transpose=True, normalize=True, non_presampled_goal_img_is_garbage=True, )",
"from rlkit.core import logger import cv2 import numpy as np import os.path as",
"osp from rlkit.samplers.data_collector.scalor_env import WrappedEnvPathCollector as SCALORWrappedEnvPathCollector from rlkit.torch.scalor.scalor import SCALOR from rlkit.util.video",
"data\", filename, time.time() - now) dataset = {\"imgs\": imgs, \"actions\": actions} print(imgs.shape) #",
"variant.get('tag', '') if env_kwargs is None: env_kwargs = {} if save_file_prefix is None:",
"save_file_prefix is None: save_file_prefix = env_id filename = \"./data/tmp/{}_N{}_rollout_length{}_imsize{}_{}{}.npz\".format( save_file_prefix, str(N), str(rollout_length), init_camera.__name__",
"show: img = img.reshape(3, imsize, imsize).transpose() img = img[::-1, :, ::-1] cv2.imshow('img', img)",
"normalize_image from rlkit.core import logger import cv2 import numpy as np import os.path",
"import os.path as osp from rlkit.samplers.data_collector.scalor_env import WrappedEnvPathCollector as SCALORWrappedEnvPathCollector from rlkit.torch.scalor.scalor import",
"now = time.time() multiworld.register_all_envs() env = gym.make(env_id) if not isinstance(env, ImageEnv): env =",
"= variant.get('N', 100) rollout_length = variant.get('rollout_length', 100) test_p = variant.get('test_p', 0.9) use_cached =",
"= variant.get('use_cached', True) imsize = variant.get('imsize', 64) num_channels = variant.get('num_channels', 3) show =",
"gym import multiworld def generate_scalor_dataset(variant): env_kwargs = variant.get('env_kwargs', None) env_id = variant.get('env_id', None)",
"variant.get('init_camera', None) dataset_path = variant.get('dataset_path', None) oracle_dataset_using_set_to_goal = variant.get( 'oracle_dataset_using_set_to_goal', False) random_rollout_data =",
"making training data\", filename, time.time() - now) dataset = {\"imgs\": imgs, \"actions\": actions}",
"100) test_p = variant.get('test_p', 0.9) use_cached = variant.get('use_cached', True) imsize = variant.get('imsize', 64)",
"else '', imsize, tag, ) import os if not osp.exists('./data/tmp/'): os.makedirs('./data/tmp/') info =",
"print(\"done making training data\", filename, time.time() - now) dataset = {\"imgs\": imgs, \"actions\":",
"info = {} import os if not os.path.exists(\"./data/tmp/\"): os.makedirs(\"./data/tmp/\") if use_cached and osp.isfile(filename):",
"= {} import os if not os.path.exists(\"./data/tmp/\"): os.makedirs(\"./data/tmp/\") if use_cached and osp.isfile(filename): dataset",
"rlkit.core import logger import cv2 import numpy as np import os.path as osp",
"os if not os.path.exists(\"./data/tmp/\"): os.makedirs(\"./data/tmp/\") if use_cached and osp.isfile(filename): dataset = np.load(filename) print(\"loaded",
"= variant.get('random_rollout_data', False) random_and_oracle_policy_data = variant.get('random_and_oracle_policy_data', False) random_and_oracle_policy_data_split = variant.get( 'random_and_oracle_policy_data_split', 0) policy_file",
"env.reset() for j in range(rollout_length): action = env.action_space.sample() obs = env.step(action)[0] img =",
"'', imsize, tag, ) import os if not osp.exists('./data/tmp/'): os.makedirs('./data/tmp/') info = {}",
"from rlkit.torch.scalor.scalor import SCALOR from rlkit.util.video import dump_video from rlkit.util.io import load_local_or_remote_file import",
"generate_scalor_dataset(variant): env_kwargs = variant.get('env_kwargs', None) env_id = variant.get('env_id', None) N = variant.get('N', 100)",
"SCALOR from rlkit.util.video import dump_video from rlkit.util.io import load_local_or_remote_file import rlkit.torch.pytorch_util as ptu",
"use_cached and osp.isfile(filename): dataset = np.load(filename) print(\"loaded data from saved file\", filename) else:",
"= np.load(filename) print(\"loaded data from saved file\", filename) else: now = time.time() multiworld.register_all_envs()",
"imsize, imsize).transpose() img = img[::-1, :, ::-1] cv2.imshow('img', img) cv2.waitKey(1) print(\"done making training",
"variant.get('use_cached', True) imsize = variant.get('imsize', 64) num_channels = variant.get('num_channels', 3) show = variant.get('show',",
"env_kwargs = variant.get('env_kwargs', None) env_id = variant.get('env_id', None) N = variant.get('N', 100) rollout_length",
"file\", filename) else: now = time.time() multiworld.register_all_envs() env = gym.make(env_id) if not isinstance(env,",
"variant.get('env_kwargs', None) env_id = variant.get('env_id', None) N = variant.get('N', 100) rollout_length = variant.get('rollout_length',",
"dataset_path = variant.get('dataset_path', None) oracle_dataset_using_set_to_goal = variant.get( 'oracle_dataset_using_set_to_goal', False) random_rollout_data = variant.get('random_rollout_data', False)",
"os.makedirs('./data/tmp/') info = {} import os if not os.path.exists(\"./data/tmp/\"): os.makedirs(\"./data/tmp/\") if use_cached and",
"- now) dataset = {\"imgs\": imgs, \"actions\": actions} print(imgs.shape) # np.savez(filename, **dataset) return",
"None) oracle_dataset_using_set_to_goal = variant.get( 'oracle_dataset_using_set_to_goal', False) random_rollout_data = variant.get('random_rollout_data', False) random_and_oracle_policy_data = variant.get('random_and_oracle_policy_data',",
"env.reset() act_dim = env.action_space.low.size info['env'] = env imgs = np.zeros((N, rollout_length, imsize *",
"logger import cv2 import numpy as np import os.path as osp from rlkit.samplers.data_collector.scalor_env",
"1 scalor_dataset_specific_env_kwargs = variant.get( 'scalor_dataset_specific_env_kwargs', None) save_file_prefix = variant.get('save_file_prefix', None) tag = variant.get('tag',",
"variant.get( 'oracle_dataset_using_set_to_goal', False) random_rollout_data = variant.get('random_rollout_data', False) random_and_oracle_policy_data = variant.get('random_and_oracle_policy_data', False) random_and_oracle_policy_data_split =",
"actions = np.zeros((N, rollout_length, act_dim)) for i in range(N): env.reset() for j in",
"non_presampled_goal_img_is_garbage=True, ) env.reset() act_dim = env.action_space.low.size info['env'] = env imgs = np.zeros((N, rollout_length,",
"env_kwargs is None: env_kwargs = {} if save_file_prefix is None: save_file_prefix = env_id",
"def generate_scalor_dataset(variant): env_kwargs = variant.get('env_kwargs', None) env_id = variant.get('env_id', None) N = variant.get('N',",
"ImageEnv( env, imsize, init_camera=init_camera, transpose=True, normalize=True, non_presampled_goal_img_is_garbage=True, ) env.reset() act_dim = env.action_space.low.size info['env']",
"osp.exists('./data/tmp/'): os.makedirs('./data/tmp/') info = {} import os if not os.path.exists(\"./data/tmp/\"): os.makedirs(\"./data/tmp/\") if use_cached",
"num_channels), dtype=np.uint8) actions = np.zeros((N, rollout_length, act_dim)) for i in range(N): env.reset() for",
"range(N): env.reset() for j in range(rollout_length): action = env.action_space.sample() obs = env.step(action)[0] img",
"save_file_prefix = variant.get('save_file_prefix', None) tag = variant.get('tag', '') if env_kwargs is None: env_kwargs",
"env, imsize, init_camera=init_camera, transpose=True, normalize=True, non_presampled_goal_img_is_garbage=True, ) env.reset() act_dim = env.action_space.low.size info['env'] =",
"as SCALORWrappedEnvPathCollector from rlkit.torch.scalor.scalor import SCALOR from rlkit.util.video import dump_video from rlkit.util.io import",
"data from saved file\", filename) else: now = time.time() multiworld.register_all_envs() env = gym.make(env_id)",
"isinstance(env, ImageEnv): env = ImageEnv( env, imsize, init_camera=init_camera, transpose=True, normalize=True, non_presampled_goal_img_is_garbage=True, ) env.reset()",
"print(imgs.shape) # np.savez(filename, **dataset) return dataset, info def scalor_training(variant): scalor_params = variant.get(\"scalor_params\", dict())",
"{\"imgs\": imgs, \"actions\": actions} print(imgs.shape) # np.savez(filename, **dataset) return dataset, info def scalor_training(variant):",
"import SCALOR from rlkit.util.video import dump_video from rlkit.util.io import load_local_or_remote_file import rlkit.torch.pytorch_util as",
"scalor_training(variant): scalor_params = variant.get(\"scalor_params\", dict()) scalor_params[\"logdir\"] = logger.get_snapshot_dir() scalor = SCALOR(**scalor_params) data, info",
"init_camera=init_camera, transpose=True, normalize=True, non_presampled_goal_img_is_garbage=True, ) env.reset() act_dim = env.action_space.low.size info['env'] = env imgs",
"saved file\", filename) else: now = time.time() multiworld.register_all_envs() env = gym.make(env_id) if not",
"variant.get(\"scalor_params\", dict()) scalor_params[\"logdir\"] = logger.get_snapshot_dir() scalor = SCALOR(**scalor_params) data, info = generate_scalor_dataset(variant['generate_scalor_dataset_kwargs']) imgs,",
"img) cv2.waitKey(1) print(\"done making training data\", filename, time.time() - now) dataset = {\"imgs\":",
"variant.get('env_id', None) N = variant.get('N', 100) rollout_length = variant.get('rollout_length', 100) test_p = variant.get('test_p',",
"range(rollout_length): action = env.action_space.sample() obs = env.step(action)[0] img = obs['image_observation'] imgs[i, j, :]",
"100) rollout_length = variant.get('rollout_length', 100) test_p = variant.get('test_p', 0.9) use_cached = variant.get('use_cached', True)",
"import logger import cv2 import numpy as np import os.path as osp from",
"= env.action_space.sample() obs = env.step(action)[0] img = obs['image_observation'] imgs[i, j, :] = unormalize_image(img)",
"if env_kwargs is None: env_kwargs = {} if save_file_prefix is None: save_file_prefix =",
"ImageEnv, unormalize_image, normalize_image from rlkit.core import logger import cv2 import numpy as np",
"time from multiworld.core.image_env import ImageEnv, unormalize_image, normalize_image from rlkit.core import logger import cv2",
"random_and_oracle_policy_data = variant.get('random_and_oracle_policy_data', False) random_and_oracle_policy_data_split = variant.get( 'random_and_oracle_policy_data_split', 0) policy_file = variant.get('policy_file', None)",
"j in range(rollout_length): action = env.action_space.sample() obs = env.step(action)[0] img = obs['image_observation'] imgs[i,",
"variant.get('save_file_prefix', None) tag = variant.get('tag', '') if env_kwargs is None: env_kwargs = {}",
"\"actions\": actions} print(imgs.shape) # np.savez(filename, **dataset) return dataset, info def scalor_training(variant): scalor_params =",
"rlkit.util.video import dump_video from rlkit.util.io import load_local_or_remote_file import rlkit.torch.pytorch_util as ptu import gym",
"variant.get('num_channels', 3) show = variant.get('show', False) init_camera = variant.get('init_camera', None) dataset_path = variant.get('dataset_path',",
"True) imsize = variant.get('imsize', 64) num_channels = variant.get('num_channels', 3) show = variant.get('show', False)",
"import numpy as np import os.path as osp from rlkit.samplers.data_collector.scalor_env import WrappedEnvPathCollector as",
"rlkit.samplers.data_collector.scalor_env import WrappedEnvPathCollector as SCALORWrappedEnvPathCollector from rlkit.torch.scalor.scalor import SCALOR from rlkit.util.video import dump_video",
"rlkit.util.io import load_local_or_remote_file import rlkit.torch.pytorch_util as ptu import gym import multiworld def generate_scalor_dataset(variant):",
"variant.get( 'scalor_dataset_specific_env_kwargs', None) save_file_prefix = variant.get('save_file_prefix', None) tag = variant.get('tag', '') if env_kwargs",
"None) env_id = variant.get('env_id', None) N = variant.get('N', 100) rollout_length = variant.get('rollout_length', 100)",
"= variant.get( 'scalor_dataset_specific_env_kwargs', None) save_file_prefix = variant.get('save_file_prefix', None) tag = variant.get('tag', '') if",
"= variant.get(\"scalor_params\", dict()) scalor_params[\"logdir\"] = logger.get_snapshot_dir() scalor = SCALOR(**scalor_params) data, info = generate_scalor_dataset(variant['generate_scalor_dataset_kwargs'])",
"imsize * num_channels), dtype=np.uint8) actions = np.zeros((N, rollout_length, act_dim)) for i in range(N):",
"from multiworld.core.image_env import ImageEnv, unormalize_image, normalize_image from rlkit.core import logger import cv2 import",
"time.time() - now) dataset = {\"imgs\": imgs, \"actions\": actions} print(imgs.shape) # np.savez(filename, **dataset)",
"init_camera.__name__ if init_camera else '', imsize, tag, ) import os if not osp.exists('./data/tmp/'):",
"not os.path.exists(\"./data/tmp/\"): os.makedirs(\"./data/tmp/\") if use_cached and osp.isfile(filename): dataset = np.load(filename) print(\"loaded data from",
"tag = variant.get('tag', '') if env_kwargs is None: env_kwargs = {} if save_file_prefix",
"rlkit.torch.pytorch_util as ptu import gym import multiworld def generate_scalor_dataset(variant): env_kwargs = variant.get('env_kwargs', None)",
"= ImageEnv( env, imsize, init_camera=init_camera, transpose=True, normalize=True, non_presampled_goal_img_is_garbage=True, ) env.reset() act_dim = env.action_space.low.size",
"= variant.get('num_channels', 3) show = variant.get('show', False) init_camera = variant.get('init_camera', None) dataset_path =",
"0.9) use_cached = variant.get('use_cached', True) imsize = variant.get('imsize', 64) num_channels = variant.get('num_channels', 3)",
"env.action_space.sample() obs = env.step(action)[0] img = obs['image_observation'] imgs[i, j, :] = unormalize_image(img) actions[i,j,",
"* num_channels), dtype=np.uint8) actions = np.zeros((N, rollout_length, act_dim)) for i in range(N): env.reset()",
"= 1 scalor_dataset_specific_env_kwargs = variant.get( 'scalor_dataset_specific_env_kwargs', None) save_file_prefix = variant.get('save_file_prefix', None) tag =",
"= variant.get('test_p', 0.9) use_cached = variant.get('use_cached', True) imsize = variant.get('imsize', 64) num_channels =",
"variant.get('imsize', 64) num_channels = variant.get('num_channels', 3) show = variant.get('show', False) init_camera = variant.get('init_camera',",
"3) show = variant.get('show', False) init_camera = variant.get('init_camera', None) dataset_path = variant.get('dataset_path', None)",
"np.zeros((N, rollout_length, act_dim)) for i in range(N): env.reset() for j in range(rollout_length): action",
"None) n_random_steps = 1 scalor_dataset_specific_env_kwargs = variant.get( 'scalor_dataset_specific_env_kwargs', None) save_file_prefix = variant.get('save_file_prefix', None)",
"None) dataset_path = variant.get('dataset_path', None) oracle_dataset_using_set_to_goal = variant.get( 'oracle_dataset_using_set_to_goal', False) random_rollout_data = variant.get('random_rollout_data',",
"data, info = generate_scalor_dataset(variant['generate_scalor_dataset_kwargs']) imgs, actions = data[\"imgs\"], data[\"actions\"] imgs = normalize_image(imgs) scalor.train(imgs=imgs,",
"= gym.make(env_id) if not isinstance(env, ImageEnv): env = ImageEnv( env, imsize, init_camera=init_camera, transpose=True,",
"numpy as np import os.path as osp from rlkit.samplers.data_collector.scalor_env import WrappedEnvPathCollector as SCALORWrappedEnvPathCollector",
"= variant.get('dataset_path', None) oracle_dataset_using_set_to_goal = variant.get( 'oracle_dataset_using_set_to_goal', False) random_rollout_data = variant.get('random_rollout_data', False) random_and_oracle_policy_data",
"import WrappedEnvPathCollector as SCALORWrappedEnvPathCollector from rlkit.torch.scalor.scalor import SCALOR from rlkit.util.video import dump_video from",
"imgs[i, j, :] = unormalize_image(img) actions[i,j, :] = action if show: img =",
"= logger.get_snapshot_dir() scalor = SCALOR(**scalor_params) data, info = generate_scalor_dataset(variant['generate_scalor_dataset_kwargs']) imgs, actions = data[\"imgs\"],",
"use_cached = variant.get('use_cached', True) imsize = variant.get('imsize', 64) num_channels = variant.get('num_channels', 3) show",
"= variant.get('init_camera', None) dataset_path = variant.get('dataset_path', None) oracle_dataset_using_set_to_goal = variant.get( 'oracle_dataset_using_set_to_goal', False) random_rollout_data",
"num_channels = variant.get('num_channels', 3) show = variant.get('show', False) init_camera = variant.get('init_camera', None) dataset_path",
"rlkit.torch.scalor.scalor import SCALOR from rlkit.util.video import dump_video from rlkit.util.io import load_local_or_remote_file import rlkit.torch.pytorch_util",
"env = gym.make(env_id) if not isinstance(env, ImageEnv): env = ImageEnv( env, imsize, init_camera=init_camera,",
"'oracle_dataset_using_set_to_goal', False) random_rollout_data = variant.get('random_rollout_data', False) random_and_oracle_policy_data = variant.get('random_and_oracle_policy_data', False) random_and_oracle_policy_data_split = variant.get(",
"{} import os if not os.path.exists(\"./data/tmp/\"): os.makedirs(\"./data/tmp/\") if use_cached and osp.isfile(filename): dataset =",
"action if show: img = img.reshape(3, imsize, imsize).transpose() img = img[::-1, :, ::-1]",
"None: save_file_prefix = env_id filename = \"./data/tmp/{}_N{}_rollout_length{}_imsize{}_{}{}.npz\".format( save_file_prefix, str(N), str(rollout_length), init_camera.__name__ if init_camera",
"{} if save_file_prefix is None: save_file_prefix = env_id filename = \"./data/tmp/{}_N{}_rollout_length{}_imsize{}_{}{}.npz\".format( save_file_prefix, str(N),",
"tag, ) import os if not osp.exists('./data/tmp/'): os.makedirs('./data/tmp/') info = {} import os",
"obs = env.step(action)[0] img = obs['image_observation'] imgs[i, j, :] = unormalize_image(img) actions[i,j, :]",
"dump_video from rlkit.util.io import load_local_or_remote_file import rlkit.torch.pytorch_util as ptu import gym import multiworld",
"np.savez(filename, **dataset) return dataset, info def scalor_training(variant): scalor_params = variant.get(\"scalor_params\", dict()) scalor_params[\"logdir\"] =",
"env_kwargs = {} if save_file_prefix is None: save_file_prefix = env_id filename = \"./data/tmp/{}_N{}_rollout_length{}_imsize{}_{}{}.npz\".format(",
"= {\"imgs\": imgs, \"actions\": actions} print(imgs.shape) # np.savez(filename, **dataset) return dataset, info def",
"env.action_space.low.size info['env'] = env imgs = np.zeros((N, rollout_length, imsize * imsize * num_channels),",
"i in range(N): env.reset() for j in range(rollout_length): action = env.action_space.sample() obs =",
"import load_local_or_remote_file import rlkit.torch.pytorch_util as ptu import gym import multiworld def generate_scalor_dataset(variant): env_kwargs",
"in range(rollout_length): action = env.action_space.sample() obs = env.step(action)[0] img = obs['image_observation'] imgs[i, j,",
"else: now = time.time() multiworld.register_all_envs() env = gym.make(env_id) if not isinstance(env, ImageEnv): env",
"img = obs['image_observation'] imgs[i, j, :] = unormalize_image(img) actions[i,j, :] = action if",
"= variant.get('imsize', 64) num_channels = variant.get('num_channels', 3) show = variant.get('show', False) init_camera =",
"cv2.imshow('img', img) cv2.waitKey(1) print(\"done making training data\", filename, time.time() - now) dataset =",
"'random_and_oracle_policy_data_split', 0) policy_file = variant.get('policy_file', None) n_random_steps = 1 scalor_dataset_specific_env_kwargs = variant.get( 'scalor_dataset_specific_env_kwargs',",
"is None: env_kwargs = {} if save_file_prefix is None: save_file_prefix = env_id filename",
"= variant.get('rollout_length', 100) test_p = variant.get('test_p', 0.9) use_cached = variant.get('use_cached', True) imsize =",
"imsize = variant.get('imsize', 64) num_channels = variant.get('num_channels', 3) show = variant.get('show', False) init_camera",
"action = env.action_space.sample() obs = env.step(action)[0] img = obs['image_observation'] imgs[i, j, :] =",
"if show: img = img.reshape(3, imsize, imsize).transpose() img = img[::-1, :, ::-1] cv2.imshow('img',",
"actions[i,j, :] = action if show: img = img.reshape(3, imsize, imsize).transpose() img =",
"variant.get('policy_file', None) n_random_steps = 1 scalor_dataset_specific_env_kwargs = variant.get( 'scalor_dataset_specific_env_kwargs', None) save_file_prefix = variant.get('save_file_prefix',",
"import rlkit.torch.pytorch_util as ptu import gym import multiworld def generate_scalor_dataset(variant): env_kwargs = variant.get('env_kwargs',",
"False) random_rollout_data = variant.get('random_rollout_data', False) random_and_oracle_policy_data = variant.get('random_and_oracle_policy_data', False) random_and_oracle_policy_data_split = variant.get( 'random_and_oracle_policy_data_split',",
"rollout_length = variant.get('rollout_length', 100) test_p = variant.get('test_p', 0.9) use_cached = variant.get('use_cached', True) imsize",
"\"./data/tmp/{}_N{}_rollout_length{}_imsize{}_{}{}.npz\".format( save_file_prefix, str(N), str(rollout_length), init_camera.__name__ if init_camera else '', imsize, tag, ) import",
"filename = \"./data/tmp/{}_N{}_rollout_length{}_imsize{}_{}{}.npz\".format( save_file_prefix, str(N), str(rollout_length), init_camera.__name__ if init_camera else '', imsize, tag,",
"as osp from rlkit.samplers.data_collector.scalor_env import WrappedEnvPathCollector as SCALORWrappedEnvPathCollector from rlkit.torch.scalor.scalor import SCALOR from",
"act_dim)) for i in range(N): env.reset() for j in range(rollout_length): action = env.action_space.sample()",
"None) save_file_prefix = variant.get('save_file_prefix', None) tag = variant.get('tag', '') if env_kwargs is None:",
"= variant.get('save_file_prefix', None) tag = variant.get('tag', '') if env_kwargs is None: env_kwargs =",
"None) tag = variant.get('tag', '') if env_kwargs is None: env_kwargs = {} if",
"str(rollout_length), init_camera.__name__ if init_camera else '', imsize, tag, ) import os if not",
"import gym import multiworld def generate_scalor_dataset(variant): env_kwargs = variant.get('env_kwargs', None) env_id = variant.get('env_id',",
"# np.savez(filename, **dataset) return dataset, info def scalor_training(variant): scalor_params = variant.get(\"scalor_params\", dict()) scalor_params[\"logdir\"]",
"env = ImageEnv( env, imsize, init_camera=init_camera, transpose=True, normalize=True, non_presampled_goal_img_is_garbage=True, ) env.reset() act_dim =",
"act_dim = env.action_space.low.size info['env'] = env imgs = np.zeros((N, rollout_length, imsize * imsize",
"gym.make(env_id) if not isinstance(env, ImageEnv): env = ImageEnv( env, imsize, init_camera=init_camera, transpose=True, normalize=True,",
"unormalize_image, normalize_image from rlkit.core import logger import cv2 import numpy as np import",
"random_rollout_data = variant.get('random_rollout_data', False) random_and_oracle_policy_data = variant.get('random_and_oracle_policy_data', False) random_and_oracle_policy_data_split = variant.get( 'random_and_oracle_policy_data_split', 0)",
"import time from multiworld.core.image_env import ImageEnv, unormalize_image, normalize_image from rlkit.core import logger import",
"time.time() multiworld.register_all_envs() env = gym.make(env_id) if not isinstance(env, ImageEnv): env = ImageEnv( env,",
"= variant.get('env_kwargs', None) env_id = variant.get('env_id', None) N = variant.get('N', 100) rollout_length =",
"= variant.get( 'oracle_dataset_using_set_to_goal', False) random_rollout_data = variant.get('random_rollout_data', False) random_and_oracle_policy_data = variant.get('random_and_oracle_policy_data', False) random_and_oracle_policy_data_split",
"rollout_length, imsize * imsize * num_channels), dtype=np.uint8) actions = np.zeros((N, rollout_length, act_dim)) for",
"if init_camera else '', imsize, tag, ) import os if not osp.exists('./data/tmp/'): os.makedirs('./data/tmp/')",
"env_id filename = \"./data/tmp/{}_N{}_rollout_length{}_imsize{}_{}{}.npz\".format( save_file_prefix, str(N), str(rollout_length), init_camera.__name__ if init_camera else '', imsize,",
"img.reshape(3, imsize, imsize).transpose() img = img[::-1, :, ::-1] cv2.imshow('img', img) cv2.waitKey(1) print(\"done making",
"def scalor_training(variant): scalor_params = variant.get(\"scalor_params\", dict()) scalor_params[\"logdir\"] = logger.get_snapshot_dir() scalor = SCALOR(**scalor_params) data,",
"env_id = variant.get('env_id', None) N = variant.get('N', 100) rollout_length = variant.get('rollout_length', 100) test_p",
") import os if not osp.exists('./data/tmp/'): os.makedirs('./data/tmp/') info = {} import os if",
"from rlkit.util.video import dump_video from rlkit.util.io import load_local_or_remote_file import rlkit.torch.pytorch_util as ptu import",
"str(N), str(rollout_length), init_camera.__name__ if init_camera else '', imsize, tag, ) import os if",
"None) N = variant.get('N', 100) rollout_length = variant.get('rollout_length', 100) test_p = variant.get('test_p', 0.9)",
"now) dataset = {\"imgs\": imgs, \"actions\": actions} print(imgs.shape) # np.savez(filename, **dataset) return dataset,",
"dtype=np.uint8) actions = np.zeros((N, rollout_length, act_dim)) for i in range(N): env.reset() for j",
"random_and_oracle_policy_data_split = variant.get( 'random_and_oracle_policy_data_split', 0) policy_file = variant.get('policy_file', None) n_random_steps = 1 scalor_dataset_specific_env_kwargs",
"multiworld def generate_scalor_dataset(variant): env_kwargs = variant.get('env_kwargs', None) env_id = variant.get('env_id', None) N =",
"dataset = np.load(filename) print(\"loaded data from saved file\", filename) else: now = time.time()"
] |
[
"% (branch_name, filename)], stdout=subprocess.PIPE ) return proc.stdout.read().decode() def get_current_branch_name(): \"\"\" Gets the name",
":param branch_name: Name of the branch :return: Contents of the file \"\"\" proc",
"files between two branches. :param branch1: name of first branch :param branch2: name",
"\"show\", \"%s:%s\" % (branch_name, filename)], stdout=subprocess.PIPE ) return proc.stdout.read().decode() def get_current_branch_name(): \"\"\" Gets",
"\"\"\" proc = subprocess.Popen( [\"git\", \"diff\", \"--name-only\", branch1, branch2], stdout=subprocess.PIPE ) return proc.stdout.read().decode()",
"proc = subprocess.Popen( [\"git\", \"show\", \"%s:%s\" % (branch_name, filename)], stdout=subprocess.PIPE ) return proc.stdout.read().decode()",
"Gets a list of changed files between two branches. :param branch1: name of",
"Gets the contents of a file from a specific branch. :param filename: Name",
"subprocess.Popen([\"git\", \"rev-parse\", \"--abbrev-ref\", \"HEAD\"], stdout=subprocess.PIPE) return proc.stdout.read().decode() def get_changed_files(branch1, branch2): \"\"\" Gets a",
"return branch in result.strip().split(\"\\n\") def get_file_contents_from_branch(filename, branch_name): \"\"\" Gets the contents of a",
"branch2): \"\"\" Gets a list of changed files between two branches. :param branch1:",
"the contents of a file from a specific branch. :param filename: Name of",
"proc.stdout.read().decode() return branch in result.strip().split(\"\\n\") def get_file_contents_from_branch(filename, branch_name): \"\"\" Gets the contents of",
"the file :param branch_name: Name of the branch :return: Contents of the file",
"if given branch is merged into current branch. :param branch: Name of branch",
"of a file from a specific branch. :param filename: Name of the file",
"proc.stdout.read().decode() def get_current_branch_name(): \"\"\" Gets the name of the current git branch in",
"result.strip().split(\"\\n\") def get_file_contents_from_branch(filename, branch_name): \"\"\" Gets the contents of a file from a",
"def get_file_contents_from_branch(filename, branch_name): \"\"\" Gets the contents of a file from a specific",
":return: Name of the branch \"\"\" proc = subprocess.Popen([\"git\", \"rev-parse\", \"--abbrev-ref\", \"HEAD\"], stdout=subprocess.PIPE)",
"branch. :param branch: Name of branch :return: True/False \"\"\" proc = subprocess.Popen([\"git\", \"branch\",",
"the current git branch in the working directory. :return: Name of the branch",
"= subprocess.Popen( [\"git\", \"show\", \"%s:%s\" % (branch_name, filename)], stdout=subprocess.PIPE ) return proc.stdout.read().decode() def",
"file \"\"\" proc = subprocess.Popen( [\"git\", \"show\", \"%s:%s\" % (branch_name, filename)], stdout=subprocess.PIPE )",
"merged into current branch. :param branch: Name of branch :return: True/False \"\"\" proc",
"= subprocess.Popen([\"git\", \"rev-parse\", \"--abbrev-ref\", \"HEAD\"], stdout=subprocess.PIPE) return proc.stdout.read().decode() def get_changed_files(branch1, branch2): \"\"\" Gets",
"files \"\"\" proc = subprocess.Popen( [\"git\", \"diff\", \"--name-only\", branch1, branch2], stdout=subprocess.PIPE ) return",
"def is_branch_merged(branch): \"\"\" Checks if given branch is merged into current branch. :param",
"list of changed files between two branches. :param branch1: name of first branch",
"contents of a file from a specific branch. :param filename: Name of the",
"branch is merged into current branch. :param branch: Name of branch :return: True/False",
"of changed files between two branches. :param branch1: name of first branch :param",
"list of changed files \"\"\" proc = subprocess.Popen( [\"git\", \"diff\", \"--name-only\", branch1, branch2],",
"specific branch. :param filename: Name of the file :param branch_name: Name of the",
":param branch2: name of second branch :return: A list of changed files \"\"\"",
"from a specific branch. :param filename: Name of the file :param branch_name: Name",
"Checks if given branch is merged into current branch. :param branch: Name of",
"a file from a specific branch. :param filename: Name of the file :param",
"a list of changed files between two branches. :param branch1: name of first",
"two branches. :param branch1: name of first branch :param branch2: name of second",
"True/False \"\"\" proc = subprocess.Popen([\"git\", \"branch\", \"--merged\"], stdout=subprocess.PIPE) result = proc.stdout.read().decode() return branch",
") return proc.stdout.read().decode() def get_current_branch_name(): \"\"\" Gets the name of the current git",
"import subprocess def is_branch_merged(branch): \"\"\" Checks if given branch is merged into current",
"proc.stdout.read().decode() def get_changed_files(branch1, branch2): \"\"\" Gets a list of changed files between two",
"\"HEAD\"], stdout=subprocess.PIPE) return proc.stdout.read().decode() def get_changed_files(branch1, branch2): \"\"\" Gets a list of changed",
"subprocess.Popen([\"git\", \"branch\", \"--merged\"], stdout=subprocess.PIPE) result = proc.stdout.read().decode() return branch in result.strip().split(\"\\n\") def get_file_contents_from_branch(filename,",
"current branch. :param branch: Name of branch :return: True/False \"\"\" proc = subprocess.Popen([\"git\",",
"result = proc.stdout.read().decode() return branch in result.strip().split(\"\\n\") def get_file_contents_from_branch(filename, branch_name): \"\"\" Gets the",
"the working directory. :return: Name of the branch \"\"\" proc = subprocess.Popen([\"git\", \"rev-parse\",",
"first branch :param branch2: name of second branch :return: A list of changed",
"directory. :return: Name of the branch \"\"\" proc = subprocess.Popen([\"git\", \"rev-parse\", \"--abbrev-ref\", \"HEAD\"],",
"A list of changed files \"\"\" proc = subprocess.Popen( [\"git\", \"diff\", \"--name-only\", branch1,",
"branch :return: Contents of the file \"\"\" proc = subprocess.Popen( [\"git\", \"show\", \"%s:%s\"",
"of first branch :param branch2: name of second branch :return: A list of",
"branch :param branch2: name of second branch :return: A list of changed files",
"return proc.stdout.read().decode() def get_changed_files(branch1, branch2): \"\"\" Gets a list of changed files between",
"branch \"\"\" proc = subprocess.Popen([\"git\", \"rev-parse\", \"--abbrev-ref\", \"HEAD\"], stdout=subprocess.PIPE) return proc.stdout.read().decode() def get_changed_files(branch1,",
"the branch :return: Contents of the file \"\"\" proc = subprocess.Popen( [\"git\", \"show\",",
"\"\"\" Gets the contents of a file from a specific branch. :param filename:",
"Gets the name of the current git branch in the working directory. :return:",
"in result.strip().split(\"\\n\") def get_file_contents_from_branch(filename, branch_name): \"\"\" Gets the contents of a file from",
"(branch_name, filename)], stdout=subprocess.PIPE ) return proc.stdout.read().decode() def get_current_branch_name(): \"\"\" Gets the name of",
":return: True/False \"\"\" proc = subprocess.Popen([\"git\", \"branch\", \"--merged\"], stdout=subprocess.PIPE) result = proc.stdout.read().decode() return",
"get_changed_files(branch1, branch2): \"\"\" Gets a list of changed files between two branches. :param",
"\"\"\" Gets the name of the current git branch in the working directory.",
"branch in result.strip().split(\"\\n\") def get_file_contents_from_branch(filename, branch_name): \"\"\" Gets the contents of a file",
":param filename: Name of the file :param branch_name: Name of the branch :return:",
"stdout=subprocess.PIPE ) return proc.stdout.read().decode() def get_current_branch_name(): \"\"\" Gets the name of the current",
"the name of the current git branch in the working directory. :return: Name",
"of the branch :return: Contents of the file \"\"\" proc = subprocess.Popen( [\"git\",",
":return: A list of changed files \"\"\" proc = subprocess.Popen( [\"git\", \"diff\", \"--name-only\",",
"branch_name: Name of the branch :return: Contents of the file \"\"\" proc =",
"second branch :return: A list of changed files \"\"\" proc = subprocess.Popen( [\"git\",",
"Name of the branch \"\"\" proc = subprocess.Popen([\"git\", \"rev-parse\", \"--abbrev-ref\", \"HEAD\"], stdout=subprocess.PIPE) return",
"name of first branch :param branch2: name of second branch :return: A list",
"branch. :param filename: Name of the file :param branch_name: Name of the branch",
":param branch: Name of branch :return: True/False \"\"\" proc = subprocess.Popen([\"git\", \"branch\", \"--merged\"],",
"of second branch :return: A list of changed files \"\"\" proc = subprocess.Popen(",
"into current branch. :param branch: Name of branch :return: True/False \"\"\" proc =",
"of changed files \"\"\" proc = subprocess.Popen( [\"git\", \"diff\", \"--name-only\", branch1, branch2], stdout=subprocess.PIPE",
"proc = subprocess.Popen([\"git\", \"branch\", \"--merged\"], stdout=subprocess.PIPE) result = proc.stdout.read().decode() return branch in result.strip().split(\"\\n\")",
"name of second branch :return: A list of changed files \"\"\" proc =",
"branch_name): \"\"\" Gets the contents of a file from a specific branch. :param",
"get_file_contents_from_branch(filename, branch_name): \"\"\" Gets the contents of a file from a specific branch.",
"working directory. :return: Name of the branch \"\"\" proc = subprocess.Popen([\"git\", \"rev-parse\", \"--abbrev-ref\",",
"of the current git branch in the working directory. :return: Name of the",
"= subprocess.Popen([\"git\", \"branch\", \"--merged\"], stdout=subprocess.PIPE) result = proc.stdout.read().decode() return branch in result.strip().split(\"\\n\") def",
"branch in the working directory. :return: Name of the branch \"\"\" proc =",
"changed files \"\"\" proc = subprocess.Popen( [\"git\", \"diff\", \"--name-only\", branch1, branch2], stdout=subprocess.PIPE )",
"a specific branch. :param filename: Name of the file :param branch_name: Name of",
"filename: Name of the file :param branch_name: Name of the branch :return: Contents",
"\"\"\" proc = subprocess.Popen( [\"git\", \"show\", \"%s:%s\" % (branch_name, filename)], stdout=subprocess.PIPE ) return",
"in the working directory. :return: Name of the branch \"\"\" proc = subprocess.Popen([\"git\",",
"is_branch_merged(branch): \"\"\" Checks if given branch is merged into current branch. :param branch:",
"changed files between two branches. :param branch1: name of first branch :param branch2:",
"Name of the branch :return: Contents of the file \"\"\" proc = subprocess.Popen(",
"branch :return: True/False \"\"\" proc = subprocess.Popen([\"git\", \"branch\", \"--merged\"], stdout=subprocess.PIPE) result = proc.stdout.read().decode()",
"given branch is merged into current branch. :param branch: Name of branch :return:",
"file from a specific branch. :param filename: Name of the file :param branch_name:",
"[\"git\", \"show\", \"%s:%s\" % (branch_name, filename)], stdout=subprocess.PIPE ) return proc.stdout.read().decode() def get_current_branch_name(): \"\"\"",
"def get_changed_files(branch1, branch2): \"\"\" Gets a list of changed files between two branches.",
"subprocess def is_branch_merged(branch): \"\"\" Checks if given branch is merged into current branch.",
"the file \"\"\" proc = subprocess.Popen( [\"git\", \"show\", \"%s:%s\" % (branch_name, filename)], stdout=subprocess.PIPE",
"def get_current_branch_name(): \"\"\" Gets the name of the current git branch in the",
"Contents of the file \"\"\" proc = subprocess.Popen( [\"git\", \"show\", \"%s:%s\" % (branch_name,",
":return: Contents of the file \"\"\" proc = subprocess.Popen( [\"git\", \"show\", \"%s:%s\" %",
"\"\"\" proc = subprocess.Popen([\"git\", \"branch\", \"--merged\"], stdout=subprocess.PIPE) result = proc.stdout.read().decode() return branch in",
"filename)], stdout=subprocess.PIPE ) return proc.stdout.read().decode() def get_current_branch_name(): \"\"\" Gets the name of the",
"branch1: name of first branch :param branch2: name of second branch :return: A",
"branch2: name of second branch :return: A list of changed files \"\"\" proc",
"stdout=subprocess.PIPE) result = proc.stdout.read().decode() return branch in result.strip().split(\"\\n\") def get_file_contents_from_branch(filename, branch_name): \"\"\" Gets",
"name of the current git branch in the working directory. :return: Name of",
"of the file \"\"\" proc = subprocess.Popen( [\"git\", \"show\", \"%s:%s\" % (branch_name, filename)],",
"of branch :return: True/False \"\"\" proc = subprocess.Popen([\"git\", \"branch\", \"--merged\"], stdout=subprocess.PIPE) result =",
"get_current_branch_name(): \"\"\" Gets the name of the current git branch in the working",
"of the branch \"\"\" proc = subprocess.Popen([\"git\", \"rev-parse\", \"--abbrev-ref\", \"HEAD\"], stdout=subprocess.PIPE) return proc.stdout.read().decode()",
"\"%s:%s\" % (branch_name, filename)], stdout=subprocess.PIPE ) return proc.stdout.read().decode() def get_current_branch_name(): \"\"\" Gets the",
"\"branch\", \"--merged\"], stdout=subprocess.PIPE) result = proc.stdout.read().decode() return branch in result.strip().split(\"\\n\") def get_file_contents_from_branch(filename, branch_name):",
"is merged into current branch. :param branch: Name of branch :return: True/False \"\"\"",
"Name of branch :return: True/False \"\"\" proc = subprocess.Popen([\"git\", \"branch\", \"--merged\"], stdout=subprocess.PIPE) result",
"subprocess.Popen( [\"git\", \"show\", \"%s:%s\" % (branch_name, filename)], stdout=subprocess.PIPE ) return proc.stdout.read().decode() def get_current_branch_name():",
"branch: Name of branch :return: True/False \"\"\" proc = subprocess.Popen([\"git\", \"branch\", \"--merged\"], stdout=subprocess.PIPE)",
"file :param branch_name: Name of the branch :return: Contents of the file \"\"\"",
"= proc.stdout.read().decode() return branch in result.strip().split(\"\\n\") def get_file_contents_from_branch(filename, branch_name): \"\"\" Gets the contents",
"return proc.stdout.read().decode() def get_current_branch_name(): \"\"\" Gets the name of the current git branch",
"the branch \"\"\" proc = subprocess.Popen([\"git\", \"rev-parse\", \"--abbrev-ref\", \"HEAD\"], stdout=subprocess.PIPE) return proc.stdout.read().decode() def",
"branch :return: A list of changed files \"\"\" proc = subprocess.Popen( [\"git\", \"diff\",",
"\"\"\" Gets a list of changed files between two branches. :param branch1: name",
"proc = subprocess.Popen([\"git\", \"rev-parse\", \"--abbrev-ref\", \"HEAD\"], stdout=subprocess.PIPE) return proc.stdout.read().decode() def get_changed_files(branch1, branch2): \"\"\"",
"git branch in the working directory. :return: Name of the branch \"\"\" proc",
":param branch1: name of first branch :param branch2: name of second branch :return:",
"of the file :param branch_name: Name of the branch :return: Contents of the",
"between two branches. :param branch1: name of first branch :param branch2: name of",
"branches. :param branch1: name of first branch :param branch2: name of second branch",
"\"\"\" proc = subprocess.Popen([\"git\", \"rev-parse\", \"--abbrev-ref\", \"HEAD\"], stdout=subprocess.PIPE) return proc.stdout.read().decode() def get_changed_files(branch1, branch2):",
"stdout=subprocess.PIPE) return proc.stdout.read().decode() def get_changed_files(branch1, branch2): \"\"\" Gets a list of changed files",
"\"\"\" Checks if given branch is merged into current branch. :param branch: Name",
"current git branch in the working directory. :return: Name of the branch \"\"\"",
"\"rev-parse\", \"--abbrev-ref\", \"HEAD\"], stdout=subprocess.PIPE) return proc.stdout.read().decode() def get_changed_files(branch1, branch2): \"\"\" Gets a list",
"\"--merged\"], stdout=subprocess.PIPE) result = proc.stdout.read().decode() return branch in result.strip().split(\"\\n\") def get_file_contents_from_branch(filename, branch_name): \"\"\"",
"Name of the file :param branch_name: Name of the branch :return: Contents of",
"\"--abbrev-ref\", \"HEAD\"], stdout=subprocess.PIPE) return proc.stdout.read().decode() def get_changed_files(branch1, branch2): \"\"\" Gets a list of"
] |
[
"To add the default GMT frame to the plot, use ``frame=\"f\"`` in #",
"######################################################################################## # Plot frame # ---------- # # By default, PyGMT does not",
"marks. fig = pygmt.Figure() # region=\"TT\" specifies Trinidad and Tobago fig.coast(shorelines=\"1/0.5p\", region=\"TT\", projection=\"M25c\")",
"region=\"IS\", projection=\"M25c\") fig.basemap(frame=[\"a\", \"+tIceland\"]) fig.show() ######################################################################################## # To use a title with multiple",
"frame # ---------- # # By default, PyGMT does not add a frame",
"in double quotation marks. fig = pygmt.Figure() # region=\"TT\" specifies Trinidad and Tobago",
"fig.show() ######################################################################################## # Axis labels # ----------- # # Axis labels can be",
"methods of :class:`pygmt.Figure`. \"\"\" import pygmt ######################################################################################## # Plot frame # ---------- #",
"inside another set of # quotation marks. To prevent the quotation marks from",
"# coastlines of the world with a Mercator projection: fig = pygmt.Figure() fig.coast(shorelines=\"1/0.5p\",",
"Passing multiple arguments to ``frame`` can be done by # using a list,",
"180, -60, 60], projection=\"M25c\") fig.show() ######################################################################################## # To add the default GMT frame",
"in the figure title, # the frame argument can be passed in single",
"allow axis labels to # be set for geographic maps. fig = pygmt.Figure()",
"with west (left), south (bottom), north (top), and # east (right) sides of",
"of the axes as primary, an argument that # capitlizes only the primary",
"projection, as GMT does not allow axis labels to # be set for",
"or ``frame=\"a\"``) sets the default GMT style frame # and automatically determines tick",
"be set for geographic maps. fig = pygmt.Figure() fig.basemap( region=[0, 10, 0, 20],",
"we can plot the # coastlines of the world with a Mercator projection:",
"region=[-180, 180, -60, 60], projection=\"M25c\") fig.show() ######################################################################################## # To add the default GMT",
"# # The automatic frame (``frame=True`` or ``frame=\"a\"``) sets the default GMT style",
"of a figure. # # The example below used a Cartesian projection, as",
"fig.basemap(frame=[\"a\", \"+tIceland\"]) fig.show() ######################################################################################## # To use a title with multiple words, the",
"south (bottom), north (top), and # east (right) sides of a figure. #",
"# The automatic frame (``frame=True`` or ``frame=\"a\"``) sets the default GMT style frame",
"\"\"\" import pygmt ######################################################################################## # Plot frame # ---------- # # By default,",
"another set of # quotation marks. To prevent the quotation marks from appearing",
"######################################################################################## # To use a title with multiple words, the title must be",
"'+t\"Trinidad and Tobago\"']) fig.show() ######################################################################################## # Axis labels # ----------- # # Axis",
"fig.coast(shorelines=\"1/0.5p\", region=[-180, 180, -60, 60], projection=\"M25c\") fig.basemap(frame=\"a\") fig.show() ######################################################################################## # Add automatic grid",
"pygmt.Figure() fig.coast(shorelines=\"1/0.5p\", region=[-180, 180, -60, 60], projection=\"M25c\") fig.basemap(frame=\"a\") fig.show() ######################################################################################## # Add automatic",
"letters correspond with west (left), south (bottom), north (top), and # east (right)",
"quotation marks from appearing in the figure title, # the frame argument can",
"in single quotation marks and the title can be # passed in double",
"# Axis labels can be set by passing **x+l**\\ *label* (or starting with",
"the ISO country code fig.coast(shorelines=\"1/0.5p\", region=\"IS\", projection=\"M25c\") fig.basemap(frame=[\"a\", \"+tIceland\"]) fig.show() ######################################################################################## # To",
"correspond with west (left), south (bottom), north (top), and # east (right) sides",
"-60, 60], projection=\"M25c\") fig.basemap(frame=\"f\") fig.show() ######################################################################################## # Ticks and grid lines # --------------------",
"``g`` to ``frame``: fig = pygmt.Figure() fig.coast(shorelines=\"1/0.5p\", region=[-180, 180, -60, 60], projection=\"M25c\") fig.basemap(frame=\"ag\")",
"argument that all plotting methods of :class:`pygmt.Figure`. \"\"\" import pygmt ######################################################################################## # Plot",
"``frame`` parameter of # :meth:`pygmt.Figure.basemap`. Passing multiple arguments to ``frame`` can be done",
"marks. To prevent the quotation marks from appearing in the figure title, #",
"frame (``frame=True`` or ``frame=\"a\"``) sets the default GMT style frame # and automatically",
"all sides of # the figure. To designate only some of the axes",
"prevent the quotation marks from appearing in the figure title, # the frame",
"axes, which the default is all sides of # the figure. To designate",
"quotation marks. fig = pygmt.Figure() # region=\"TT\" specifies Trinidad and Tobago fig.coast(shorelines=\"1/0.5p\", region=\"TT\",",
"is ``\"WSne\"`` in the example # below. The letters correspond with west (left),",
"Title # ----- # # The figure title can be set by passing",
"sides of # the figure. To designate only some of the axes as",
"all primary axes, which the default is all sides of # the figure.",
"fig = pygmt.Figure() fig.coast(shorelines=\"1/0.5p\", region=[-180, 180, -60, 60], projection=\"M25c\") fig.basemap(frame=\"a\") fig.show() ######################################################################################## #",
"# :meth:`pygmt.Figure.basemap`. Passing multiple arguments to ``frame`` can be done by # using",
"the map frames, ticks, etc, is handled by the ``frame`` argument that all",
"a Mercator projection: fig = pygmt.Figure() fig.coast(shorelines=\"1/0.5p\", region=[-180, 180, -60, 60], projection=\"M25c\") fig.show()",
"from the plot region. fig = pygmt.Figure() fig.coast(shorelines=\"1/0.5p\", region=[-180, 180, -60, 60], projection=\"M25c\")",
"-60, 60], projection=\"M25c\") fig.show() ######################################################################################## # To add the default GMT frame to",
"# labeling the y-axis) if to the ``frame`` parameter of :meth:`pygmt.Figure.basemap`. # Axis",
"the ``frame`` parameter of :meth:`pygmt.Figure.basemap`. # Axis labels will be displayed on all",
"GMT style frame # and automatically determines tick labels from the plot region.",
"figure. # # The example below used a Cartesian projection, as GMT does",
"in # :meth:`pygmt.Figure.basemap` or any other plotting module: fig = pygmt.Figure() fig.coast(shorelines=\"1/0.5p\", region=[-180,",
"region=\"IS\" specifies Iceland using the ISO country code fig.coast(shorelines=\"1/0.5p\", region=\"IS\", projection=\"M25c\") fig.basemap(frame=[\"a\", \"+tIceland\"])",
"# # The example below used a Cartesian projection, as GMT does not",
"by adding a ``g`` to ``frame``: fig = pygmt.Figure() fig.coast(shorelines=\"1/0.5p\", region=[-180, 180, -60,",
"starting with y if # labeling the y-axis) if to the ``frame`` parameter",
"primary axes can be passed, which is ``\"WSne\"`` in the example # below.",
"Frames, ticks, titles, and labels ================================= Setting the style of the map frames,",
"code fig.coast(shorelines=\"1/0.5p\", region=\"IS\", projection=\"M25c\") fig.basemap(frame=[\"a\", \"+tIceland\"]) fig.show() ######################################################################################## # To use a title",
"done by # using a list, as show in the example below. fig",
"world with a Mercator projection: fig = pygmt.Figure() fig.coast(shorelines=\"1/0.5p\", region=[-180, 180, -60, 60],",
"# east (right) sides of a figure. # # The example below used",
"Setting the style of the map frames, ticks, etc, is handled by the",
"ISO country code fig.coast(shorelines=\"1/0.5p\", region=\"IS\", projection=\"M25c\") fig.basemap(frame=[\"a\", \"+tIceland\"]) fig.show() ######################################################################################## # To use",
"can be # passed in double quotation marks. fig = pygmt.Figure() # region=\"TT\"",
"# using a list, as show in the example below. fig = pygmt.Figure()",
"region. fig = pygmt.Figure() fig.coast(shorelines=\"1/0.5p\", region=[-180, 180, -60, 60], projection=\"M25c\") fig.basemap(frame=\"a\") fig.show() ########################################################################################",
"# region=\"IS\" specifies Iceland using the ISO country code fig.coast(shorelines=\"1/0.5p\", region=\"IS\", projection=\"M25c\") fig.basemap(frame=[\"a\",",
"grid lines # -------------------- # # The automatic frame (``frame=True`` or ``frame=\"a\"``) sets",
"show in the example below. fig = pygmt.Figure() # region=\"IS\" specifies Iceland using",
"the default GMT frame to the plot, use ``frame=\"f\"`` in # :meth:`pygmt.Figure.basemap` or",
"of # quotation marks. To prevent the quotation marks from appearing in the",
"the style of the map frames, ticks, etc, is handled by the ``frame``",
"fig = pygmt.Figure() fig.basemap( region=[0, 10, 0, 20], projection=\"X10c/8c\", frame=[\"WSne\", \"x+lx-axis\", \"y+ly-axis\"], )",
"180, -60, 60], projection=\"M25c\") fig.basemap(frame=\"f\") fig.show() ######################################################################################## # Ticks and grid lines #",
"projection=\"M25c\") fig.basemap(frame=\"a\") fig.show() ######################################################################################## # Add automatic grid lines to the plot by",
"that # capitlizes only the primary axes can be passed, which is ``\"WSne\"``",
"Mercator projection: fig = pygmt.Figure() fig.coast(shorelines=\"1/0.5p\", region=[-180, 180, -60, 60], projection=\"M25c\") fig.show() ########################################################################################",
"``frame=\"f\"`` in # :meth:`pygmt.Figure.basemap` or any other plotting module: fig = pygmt.Figure() fig.coast(shorelines=\"1/0.5p\",",
"if to the ``frame`` parameter of :meth:`pygmt.Figure.basemap`. # Axis labels will be displayed",
"using a list, as show in the example below. fig = pygmt.Figure() #",
"the plot region. fig = pygmt.Figure() fig.coast(shorelines=\"1/0.5p\", region=[-180, 180, -60, 60], projection=\"M25c\") fig.basemap(frame=\"a\")",
"# To use a title with multiple words, the title must be placed",
"east (right) sides of a figure. # # The example below used a",
"displayed on all primary axes, which the default is all sides of #",
"labels # ----------- # # Axis labels can be set by passing **x+l**\\",
"below used a Cartesian projection, as GMT does not allow axis labels to",
"an argument that # capitlizes only the primary axes can be passed, which",
"the # coastlines of the world with a Mercator projection: fig = pygmt.Figure()",
"by passing **x+l**\\ *label* (or starting with y if # labeling the y-axis)",
"that all plotting methods of :class:`pygmt.Figure`. \"\"\" import pygmt ######################################################################################## # Plot frame",
"as GMT does not allow axis labels to # be set for geographic",
"and the title can be # passed in double quotation marks. fig =",
"frame to the plot, use ``frame=\"f\"`` in # :meth:`pygmt.Figure.basemap` or any other plotting",
"passing **+t**\\ *title* to the ``frame`` parameter of # :meth:`pygmt.Figure.basemap`. Passing multiple arguments",
"**+t**\\ *title* to the ``frame`` parameter of # :meth:`pygmt.Figure.basemap`. Passing multiple arguments to",
"*title* to the ``frame`` parameter of # :meth:`pygmt.Figure.basemap`. Passing multiple arguments to ``frame``",
"only some of the axes as primary, an argument that # capitlizes only",
"appearing in the figure title, # the frame argument can be passed in",
"(``frame=True`` or ``frame=\"a\"``) sets the default GMT style frame # and automatically determines",
"axis labels to # be set for geographic maps. fig = pygmt.Figure() fig.basemap(",
"----- # # The figure title can be set by passing **+t**\\ *title*",
"example below used a Cartesian projection, as GMT does not allow axis labels",
"the axes as primary, an argument that # capitlizes only the primary axes",
"To use a title with multiple words, the title must be placed inside",
"does not allow axis labels to # be set for geographic maps. fig",
"of the world with a Mercator projection: fig = pygmt.Figure() fig.coast(shorelines=\"1/0.5p\", region=[-180, 180,",
"GMT frame to the plot, use ``frame=\"f\"`` in # :meth:`pygmt.Figure.basemap` or any other",
"the default GMT style frame # and automatically determines tick labels from the",
"plot the # coastlines of the world with a Mercator projection: fig =",
"Ticks and grid lines # -------------------- # # The automatic frame (``frame=True`` or",
"180, -60, 60], projection=\"M25c\") fig.basemap(frame=\"a\") fig.show() ######################################################################################## # Add automatic grid lines to",
"with y if # labeling the y-axis) if to the ``frame`` parameter of",
"# ----------- # # Axis labels can be set by passing **x+l**\\ *label*",
"your plot. For example, we can plot the # coastlines of the world",
"multiple words, the title must be placed inside another set of # quotation",
"plot. For example, we can plot the # coastlines of the world with",
"using the ISO country code fig.coast(shorelines=\"1/0.5p\", region=\"IS\", projection=\"M25c\") fig.basemap(frame=[\"a\", \"+tIceland\"]) fig.show() ######################################################################################## #",
"Iceland using the ISO country code fig.coast(shorelines=\"1/0.5p\", region=\"IS\", projection=\"M25c\") fig.basemap(frame=[\"a\", \"+tIceland\"]) fig.show() ########################################################################################",
"figure title, # the frame argument can be passed in single quotation marks",
"labels will be displayed on all primary axes, which the default is all",
"north (top), and # east (right) sides of a figure. # # The",
"Tobago fig.coast(shorelines=\"1/0.5p\", region=\"TT\", projection=\"M25c\") fig.basemap(frame=[\"a\", '+t\"Trinidad and Tobago\"']) fig.show() ######################################################################################## # Axis labels",
"passed in single quotation marks and the title can be # passed in",
"will be displayed on all primary axes, which the default is all sides",
"to the ``frame`` parameter of :meth:`pygmt.Figure.basemap`. # Axis labels will be displayed on",
"y-axis) if to the ``frame`` parameter of :meth:`pygmt.Figure.basemap`. # Axis labels will be",
"multiple arguments to ``frame`` can be done by # using a list, as",
"lines # -------------------- # # The automatic frame (``frame=True`` or ``frame=\"a\"``) sets the",
"60], projection=\"M25c\") fig.basemap(frame=\"ag\") fig.show() ######################################################################################## # Title # ----- # # The figure",
"below. fig = pygmt.Figure() # region=\"IS\" specifies Iceland using the ISO country code",
"argument can be passed in single quotation marks and the title can be",
"set for geographic maps. fig = pygmt.Figure() fig.basemap( region=[0, 10, 0, 20], projection=\"X10c/8c\",",
"grid lines to the plot by adding a ``g`` to ``frame``: fig =",
"fig.basemap(frame=\"a\") fig.show() ######################################################################################## # Add automatic grid lines to the plot by adding",
"######################################################################################## # Add automatic grid lines to the plot by adding a ``g``",
"be passed in single quotation marks and the title can be # passed",
"import pygmt ######################################################################################## # Plot frame # ---------- # # By default, PyGMT",
"to the plot, use ``frame=\"f\"`` in # :meth:`pygmt.Figure.basemap` or any other plotting module:",
"the quotation marks from appearing in the figure title, # the frame argument",
"labels from the plot region. fig = pygmt.Figure() fig.coast(shorelines=\"1/0.5p\", region=[-180, 180, -60, 60],",
"# :meth:`pygmt.Figure.basemap` or any other plotting module: fig = pygmt.Figure() fig.coast(shorelines=\"1/0.5p\", region=[-180, 180,",
"fig.show() ######################################################################################## # To add the default GMT frame to the plot, use",
"example # below. The letters correspond with west (left), south (bottom), north (top),",
"(left), south (bottom), north (top), and # east (right) sides of a figure.",
"# Axis labels will be displayed on all primary axes, which the default",
"region=[-180, 180, -60, 60], projection=\"M25c\") fig.basemap(frame=\"f\") fig.show() ######################################################################################## # Ticks and grid lines",
"set by passing **x+l**\\ *label* (or starting with y if # labeling the",
"etc, is handled by the ``frame`` argument that all plotting methods of :class:`pygmt.Figure`.",
"frame argument can be passed in single quotation marks and the title can",
"designate only some of the axes as primary, an argument that # capitlizes",
"to ``frame``: fig = pygmt.Figure() fig.coast(shorelines=\"1/0.5p\", region=[-180, 180, -60, 60], projection=\"M25c\") fig.basemap(frame=\"ag\") fig.show()",
"can be set by passing **+t**\\ *title* to the ``frame`` parameter of #",
"projection=\"M25c\") fig.show() ######################################################################################## # To add the default GMT frame to the plot,",
"Add automatic grid lines to the plot by adding a ``g`` to ``frame``:",
"does not add a frame to your plot. For example, we can plot",
"only the primary axes can be passed, which is ``\"WSne\"`` in the example",
"set of # quotation marks. To prevent the quotation marks from appearing in",
"= pygmt.Figure() # region=\"IS\" specifies Iceland using the ISO country code fig.coast(shorelines=\"1/0.5p\", region=\"IS\",",
"be done by # using a list, as show in the example below.",
"to the ``frame`` parameter of # :meth:`pygmt.Figure.basemap`. Passing multiple arguments to ``frame`` can",
"# Title # ----- # # The figure title can be set by",
"is all sides of # the figure. To designate only some of the",
"plotting module: fig = pygmt.Figure() fig.coast(shorelines=\"1/0.5p\", region=[-180, 180, -60, 60], projection=\"M25c\") fig.basemap(frame=\"f\") fig.show()",
"the example below. fig = pygmt.Figure() # region=\"IS\" specifies Iceland using the ISO",
"a frame to your plot. For example, we can plot the # coastlines",
"fig.coast(shorelines=\"1/0.5p\", region=[-180, 180, -60, 60], projection=\"M25c\") fig.show() ######################################################################################## # To add the default",
"(or starting with y if # labeling the y-axis) if to the ``frame``",
"GMT does not allow axis labels to # be set for geographic maps.",
"fig = pygmt.Figure() fig.coast(shorelines=\"1/0.5p\", region=[-180, 180, -60, 60], projection=\"M25c\") fig.basemap(frame=\"ag\") fig.show() ######################################################################################## #",
"# Add automatic grid lines to the plot by adding a ``g`` to",
"quotation marks. To prevent the quotation marks from appearing in the figure title,",
"example below. fig = pygmt.Figure() # region=\"IS\" specifies Iceland using the ISO country",
"the figure title, # the frame argument can be passed in single quotation",
"pygmt ######################################################################################## # Plot frame # ---------- # # By default, PyGMT does",
"below. The letters correspond with west (left), south (bottom), north (top), and #",
"projection=\"M25c\") fig.basemap(frame=\"f\") fig.show() ######################################################################################## # Ticks and grid lines # -------------------- # #",
"title must be placed inside another set of # quotation marks. To prevent",
"be passed, which is ``\"WSne\"`` in the example # below. The letters correspond",
"quotation marks and the title can be # passed in double quotation marks.",
"axes as primary, an argument that # capitlizes only the primary axes can",
"be displayed on all primary axes, which the default is all sides of",
"passing **x+l**\\ *label* (or starting with y if # labeling the y-axis) if",
"######################################################################################## # To add the default GMT frame to the plot, use ``frame=\"f\"``",
"double quotation marks. fig = pygmt.Figure() # region=\"TT\" specifies Trinidad and Tobago fig.coast(shorelines=\"1/0.5p\",",
"The figure title can be set by passing **+t**\\ *title* to the ``frame``",
"be # passed in double quotation marks. fig = pygmt.Figure() # region=\"TT\" specifies",
"to your plot. For example, we can plot the # coastlines of the",
"a list, as show in the example below. fig = pygmt.Figure() # region=\"IS\"",
"with a Mercator projection: fig = pygmt.Figure() fig.coast(shorelines=\"1/0.5p\", region=[-180, 180, -60, 60], projection=\"M25c\")",
"by # using a list, as show in the example below. fig =",
"axes can be passed, which is ``\"WSne\"`` in the example # below. The",
"================================= Setting the style of the map frames, ticks, etc, is handled by",
"pygmt.Figure() fig.coast(shorelines=\"1/0.5p\", region=[-180, 180, -60, 60], projection=\"M25c\") fig.show() ######################################################################################## # To add the",
"# the figure. To designate only some of the axes as primary, an",
"60], projection=\"M25c\") fig.show() ######################################################################################## # To add the default GMT frame to the",
"the default is all sides of # the figure. To designate only some",
"Axis labels will be displayed on all primary axes, which the default is",
"which the default is all sides of # the figure. To designate only",
"which is ``\"WSne\"`` in the example # below. The letters correspond with west",
"capitlizes only the primary axes can be passed, which is ``\"WSne\"`` in the",
"Plot frame # ---------- # # By default, PyGMT does not add a",
"fig = pygmt.Figure() # region=\"TT\" specifies Trinidad and Tobago fig.coast(shorelines=\"1/0.5p\", region=\"TT\", projection=\"M25c\") fig.basemap(frame=[\"a\",",
"some of the axes as primary, an argument that # capitlizes only the",
"# passed in double quotation marks. fig = pygmt.Figure() # region=\"TT\" specifies Trinidad",
"set by passing **+t**\\ *title* to the ``frame`` parameter of # :meth:`pygmt.Figure.basemap`. Passing",
"automatic grid lines to the plot by adding a ``g`` to ``frame``: fig",
"the example # below. The letters correspond with west (left), south (bottom), north",
"fig = pygmt.Figure() fig.coast(shorelines=\"1/0.5p\", region=[-180, 180, -60, 60], projection=\"M25c\") fig.show() ######################################################################################## # To",
"``frame`` can be done by # using a list, as show in the",
"default GMT style frame # and automatically determines tick labels from the plot",
"= pygmt.Figure() fig.coast(shorelines=\"1/0.5p\", region=[-180, 180, -60, 60], projection=\"M25c\") fig.show() ######################################################################################## # To add",
"used a Cartesian projection, as GMT does not allow axis labels to #",
"fig.coast(shorelines=\"1/0.5p\", region=\"IS\", projection=\"M25c\") fig.basemap(frame=[\"a\", \"+tIceland\"]) fig.show() ######################################################################################## # To use a title with",
"# The figure title can be set by passing **+t**\\ *title* to the",
"(right) sides of a figure. # # The example below used a Cartesian",
"*label* (or starting with y if # labeling the y-axis) if to the",
"plot by adding a ``g`` to ``frame``: fig = pygmt.Figure() fig.coast(shorelines=\"1/0.5p\", region=[-180, 180,",
"\"+tIceland\"]) fig.show() ######################################################################################## # To use a title with multiple words, the title",
"# # By default, PyGMT does not add a frame to your plot.",
"region=\"TT\" specifies Trinidad and Tobago fig.coast(shorelines=\"1/0.5p\", region=\"TT\", projection=\"M25c\") fig.basemap(frame=[\"a\", '+t\"Trinidad and Tobago\"']) fig.show()",
"primary axes, which the default is all sides of # the figure. To",
"region=[-180, 180, -60, 60], projection=\"M25c\") fig.basemap(frame=\"a\") fig.show() ######################################################################################## # Add automatic grid lines",
"fig.basemap(frame=[\"a\", '+t\"Trinidad and Tobago\"']) fig.show() ######################################################################################## # Axis labels # ----------- # #",
"# and automatically determines tick labels from the plot region. fig = pygmt.Figure()",
"country code fig.coast(shorelines=\"1/0.5p\", region=\"IS\", projection=\"M25c\") fig.basemap(frame=[\"a\", \"+tIceland\"]) fig.show() ######################################################################################## # To use a",
"# the frame argument can be passed in single quotation marks and the",
"a title with multiple words, the title must be placed inside another set",
"= pygmt.Figure() fig.basemap( region=[0, 10, 0, 20], projection=\"X10c/8c\", frame=[\"WSne\", \"x+lx-axis\", \"y+ly-axis\"], ) fig.show()",
"a Cartesian projection, as GMT does not allow axis labels to # be",
"the title must be placed inside another set of # quotation marks. To",
"# capitlizes only the primary axes can be passed, which is ``\"WSne\"`` in",
"of :meth:`pygmt.Figure.basemap`. # Axis labels will be displayed on all primary axes, which",
"60], projection=\"M25c\") fig.basemap(frame=\"a\") fig.show() ######################################################################################## # Add automatic grid lines to the plot",
"projection: fig = pygmt.Figure() fig.coast(shorelines=\"1/0.5p\", region=[-180, 180, -60, 60], projection=\"M25c\") fig.show() ######################################################################################## #",
"# By default, PyGMT does not add a frame to your plot. For",
"= pygmt.Figure() fig.coast(shorelines=\"1/0.5p\", region=[-180, 180, -60, 60], projection=\"M25c\") fig.basemap(frame=\"f\") fig.show() ######################################################################################## # Ticks",
"frames, ticks, etc, is handled by the ``frame`` argument that all plotting methods",
"frame # and automatically determines tick labels from the plot region. fig =",
"marks and the title can be # passed in double quotation marks. fig",
"on all primary axes, which the default is all sides of # the",
"primary, an argument that # capitlizes only the primary axes can be passed,",
"By default, PyGMT does not add a frame to your plot. For example,",
"the world with a Mercator projection: fig = pygmt.Figure() fig.coast(shorelines=\"1/0.5p\", region=[-180, 180, -60,",
"be set by passing **+t**\\ *title* to the ``frame`` parameter of # :meth:`pygmt.Figure.basemap`.",
"# ---------- # # By default, PyGMT does not add a frame to",
"labels to # be set for geographic maps. fig = pygmt.Figure() fig.basemap( region=[0,",
"# be set for geographic maps. fig = pygmt.Figure() fig.basemap( region=[0, 10, 0,",
"parameter of # :meth:`pygmt.Figure.basemap`. Passing multiple arguments to ``frame`` can be done by",
"``\"WSne\"`` in the example # below. The letters correspond with west (left), south",
"can be set by passing **x+l**\\ *label* (or starting with y if #",
"fig.basemap(frame=\"f\") fig.show() ######################################################################################## # Ticks and grid lines # -------------------- # # The",
"the frame argument can be passed in single quotation marks and the title",
"can plot the # coastlines of the world with a Mercator projection: fig",
"any other plotting module: fig = pygmt.Figure() fig.coast(shorelines=\"1/0.5p\", region=[-180, 180, -60, 60], projection=\"M25c\")",
"automatically determines tick labels from the plot region. fig = pygmt.Figure() fig.coast(shorelines=\"1/0.5p\", region=[-180,",
"labels ================================= Setting the style of the map frames, ticks, etc, is handled",
"specifies Trinidad and Tobago fig.coast(shorelines=\"1/0.5p\", region=\"TT\", projection=\"M25c\") fig.basemap(frame=[\"a\", '+t\"Trinidad and Tobago\"']) fig.show() ########################################################################################",
"words, the title must be placed inside another set of # quotation marks.",
"``frame``: fig = pygmt.Figure() fig.coast(shorelines=\"1/0.5p\", region=[-180, 180, -60, 60], projection=\"M25c\") fig.basemap(frame=\"ag\") fig.show() ########################################################################################",
"handled by the ``frame`` argument that all plotting methods of :class:`pygmt.Figure`. \"\"\" import",
"# # The figure title can be set by passing **+t**\\ *title* to",
"passed in double quotation marks. fig = pygmt.Figure() # region=\"TT\" specifies Trinidad and",
"default is all sides of # the figure. To designate only some of",
"and # east (right) sides of a figure. # # The example below",
"180, -60, 60], projection=\"M25c\") fig.basemap(frame=\"ag\") fig.show() ######################################################################################## # Title # ----- # #",
"argument that # capitlizes only the primary axes can be passed, which is",
"with multiple words, the title must be placed inside another set of #",
"to # be set for geographic maps. fig = pygmt.Figure() fig.basemap( region=[0, 10,",
"the y-axis) if to the ``frame`` parameter of :meth:`pygmt.Figure.basemap`. # Axis labels will",
"is handled by the ``frame`` argument that all plotting methods of :class:`pygmt.Figure`. \"\"\"",
"and labels ================================= Setting the style of the map frames, ticks, etc, is",
"fig.basemap(frame=\"ag\") fig.show() ######################################################################################## # Title # ----- # # The figure title can",
"PyGMT does not add a frame to your plot. For example, we can",
":meth:`pygmt.Figure.basemap`. # Axis labels will be displayed on all primary axes, which the",
"the plot, use ``frame=\"f\"`` in # :meth:`pygmt.Figure.basemap` or any other plotting module: fig",
"(bottom), north (top), and # east (right) sides of a figure. # #",
"# below. The letters correspond with west (left), south (bottom), north (top), and",
"not allow axis labels to # be set for geographic maps. fig =",
"plot, use ``frame=\"f\"`` in # :meth:`pygmt.Figure.basemap` or any other plotting module: fig =",
"---------- # # By default, PyGMT does not add a frame to your",
"and automatically determines tick labels from the plot region. fig = pygmt.Figure() fig.coast(shorelines=\"1/0.5p\",",
"region=\"TT\", projection=\"M25c\") fig.basemap(frame=[\"a\", '+t\"Trinidad and Tobago\"']) fig.show() ######################################################################################## # Axis labels # -----------",
"fig.coast(shorelines=\"1/0.5p\", region=\"TT\", projection=\"M25c\") fig.basemap(frame=[\"a\", '+t\"Trinidad and Tobago\"']) fig.show() ######################################################################################## # Axis labels #",
":meth:`pygmt.Figure.basemap` or any other plotting module: fig = pygmt.Figure() fig.coast(shorelines=\"1/0.5p\", region=[-180, 180, -60,",
"######################################################################################## # Ticks and grid lines # -------------------- # # The automatic frame",
"single quotation marks and the title can be # passed in double quotation",
"# To add the default GMT frame to the plot, use ``frame=\"f\"`` in",
"a ``g`` to ``frame``: fig = pygmt.Figure() fig.coast(shorelines=\"1/0.5p\", region=[-180, 180, -60, 60], projection=\"M25c\")",
"and Tobago\"']) fig.show() ######################################################################################## # Axis labels # ----------- # # Axis labels",
"passed, which is ``\"WSne\"`` in the example # below. The letters correspond with",
"arguments to ``frame`` can be done by # using a list, as show",
"60], projection=\"M25c\") fig.basemap(frame=\"f\") fig.show() ######################################################################################## # Ticks and grid lines # -------------------- #",
"= pygmt.Figure() fig.coast(shorelines=\"1/0.5p\", region=[-180, 180, -60, 60], projection=\"M25c\") fig.basemap(frame=\"a\") fig.show() ######################################################################################## # Add",
"list, as show in the example below. fig = pygmt.Figure() # region=\"IS\" specifies",
"# quotation marks. To prevent the quotation marks from appearing in the figure",
"-------------------- # # The automatic frame (``frame=True`` or ``frame=\"a\"``) sets the default GMT",
"Tobago\"']) fig.show() ######################################################################################## # Axis labels # ----------- # # Axis labels can",
"fig.show() ######################################################################################## # Add automatic grid lines to the plot by adding a",
"######################################################################################## # Title # ----- # # The figure title can be set",
"style frame # and automatically determines tick labels from the plot region. fig",
"fig.coast(shorelines=\"1/0.5p\", region=[-180, 180, -60, 60], projection=\"M25c\") fig.basemap(frame=\"ag\") fig.show() ######################################################################################## # Title # -----",
"y if # labeling the y-axis) if to the ``frame`` parameter of :meth:`pygmt.Figure.basemap`.",
"can be passed in single quotation marks and the title can be #",
"labels can be set by passing **x+l**\\ *label* (or starting with y if",
"pygmt.Figure() fig.coast(shorelines=\"1/0.5p\", region=[-180, 180, -60, 60], projection=\"M25c\") fig.basemap(frame=\"ag\") fig.show() ######################################################################################## # Title #",
"fig.show() ######################################################################################## # To use a title with multiple words, the title must",
"To prevent the quotation marks from appearing in the figure title, # the",
"specifies Iceland using the ISO country code fig.coast(shorelines=\"1/0.5p\", region=\"IS\", projection=\"M25c\") fig.basemap(frame=[\"a\", \"+tIceland\"]) fig.show()",
"title with multiple words, the title must be placed inside another set of",
"plot region. fig = pygmt.Figure() fig.coast(shorelines=\"1/0.5p\", region=[-180, 180, -60, 60], projection=\"M25c\") fig.basemap(frame=\"a\") fig.show()",
"projection=\"M25c\") fig.basemap(frame=[\"a\", '+t\"Trinidad and Tobago\"']) fig.show() ######################################################################################## # Axis labels # ----------- #",
"The letters correspond with west (left), south (bottom), north (top), and # east",
"Cartesian projection, as GMT does not allow axis labels to # be set",
"fig.coast(shorelines=\"1/0.5p\", region=[-180, 180, -60, 60], projection=\"M25c\") fig.basemap(frame=\"f\") fig.show() ######################################################################################## # Ticks and grid",
"-60, 60], projection=\"M25c\") fig.basemap(frame=\"a\") fig.show() ######################################################################################## # Add automatic grid lines to the",
"placed inside another set of # quotation marks. To prevent the quotation marks",
"= pygmt.Figure() # region=\"TT\" specifies Trinidad and Tobago fig.coast(shorelines=\"1/0.5p\", region=\"TT\", projection=\"M25c\") fig.basemap(frame=[\"a\", '+t\"Trinidad",
"style of the map frames, ticks, etc, is handled by the ``frame`` argument",
"``frame=\"a\"``) sets the default GMT style frame # and automatically determines tick labels",
"# Axis labels # ----------- # # Axis labels can be set by",
"all plotting methods of :class:`pygmt.Figure`. \"\"\" import pygmt ######################################################################################## # Plot frame #",
"determines tick labels from the plot region. fig = pygmt.Figure() fig.coast(shorelines=\"1/0.5p\", region=[-180, 180,",
"figure title can be set by passing **+t**\\ *title* to the ``frame`` parameter",
"default GMT frame to the plot, use ``frame=\"f\"`` in # :meth:`pygmt.Figure.basemap` or any",
"not add a frame to your plot. For example, we can plot the",
"west (left), south (bottom), north (top), and # east (right) sides of a",
"use a title with multiple words, the title must be placed inside another",
"tick labels from the plot region. fig = pygmt.Figure() fig.coast(shorelines=\"1/0.5p\", region=[-180, 180, -60,",
"if # labeling the y-axis) if to the ``frame`` parameter of :meth:`pygmt.Figure.basemap`. #",
"adding a ``g`` to ``frame``: fig = pygmt.Figure() fig.coast(shorelines=\"1/0.5p\", region=[-180, 180, -60, 60],",
"to the plot by adding a ``g`` to ``frame``: fig = pygmt.Figure() fig.coast(shorelines=\"1/0.5p\",",
"title can be set by passing **+t**\\ *title* to the ``frame`` parameter of",
"region=[-180, 180, -60, 60], projection=\"M25c\") fig.basemap(frame=\"ag\") fig.show() ######################################################################################## # Title # ----- #",
"For example, we can plot the # coastlines of the world with a",
"title, # the frame argument can be passed in single quotation marks and",
"# # Axis labels can be set by passing **x+l**\\ *label* (or starting",
"titles, and labels ================================= Setting the style of the map frames, ticks, etc,",
"of the map frames, ticks, etc, is handled by the ``frame`` argument that",
"fig.show() ######################################################################################## # Ticks and grid lines # -------------------- # # The automatic",
"in the example # below. The letters correspond with west (left), south (bottom),",
"Axis labels can be set by passing **x+l**\\ *label* (or starting with y",
"fig.show() ######################################################################################## # Title # ----- # # The figure title can be",
"# The example below used a Cartesian projection, as GMT does not allow",
"use ``frame=\"f\"`` in # :meth:`pygmt.Figure.basemap` or any other plotting module: fig = pygmt.Figure()",
"of # :meth:`pygmt.Figure.basemap`. Passing multiple arguments to ``frame`` can be done by #",
"default, PyGMT does not add a frame to your plot. For example, we",
"projection=\"M25c\") fig.basemap(frame=\"ag\") fig.show() ######################################################################################## # Title # ----- # # The figure title",
"-60, 60], projection=\"M25c\") fig.basemap(frame=\"ag\") fig.show() ######################################################################################## # Title # ----- # # The",
"To designate only some of the axes as primary, an argument that #",
"projection=\"M25c\") fig.basemap(frame=[\"a\", \"+tIceland\"]) fig.show() ######################################################################################## # To use a title with multiple words,",
"can be done by # using a list, as show in the example",
"be placed inside another set of # quotation marks. To prevent the quotation",
"or any other plotting module: fig = pygmt.Figure() fig.coast(shorelines=\"1/0.5p\", region=[-180, 180, -60, 60],",
"to ``frame`` can be done by # using a list, as show in",
"plotting methods of :class:`pygmt.Figure`. \"\"\" import pygmt ######################################################################################## # Plot frame # ----------",
"the plot by adding a ``g`` to ``frame``: fig = pygmt.Figure() fig.coast(shorelines=\"1/0.5p\", region=[-180,",
"the ``frame`` parameter of # :meth:`pygmt.Figure.basemap`. Passing multiple arguments to ``frame`` can be",
"# region=\"TT\" specifies Trinidad and Tobago fig.coast(shorelines=\"1/0.5p\", region=\"TT\", projection=\"M25c\") fig.basemap(frame=[\"a\", '+t\"Trinidad and Tobago\"'])",
"parameter of :meth:`pygmt.Figure.basemap`. # Axis labels will be displayed on all primary axes,",
"fig = pygmt.Figure() # region=\"IS\" specifies Iceland using the ISO country code fig.coast(shorelines=\"1/0.5p\",",
"add the default GMT frame to the plot, use ``frame=\"f\"`` in # :meth:`pygmt.Figure.basemap`",
"as show in the example below. fig = pygmt.Figure() # region=\"IS\" specifies Iceland",
"----------- # # Axis labels can be set by passing **x+l**\\ *label* (or",
"``frame`` parameter of :meth:`pygmt.Figure.basemap`. # Axis labels will be displayed on all primary",
"\"\"\" Frames, ticks, titles, and labels ================================= Setting the style of the map",
"and grid lines # -------------------- # # The automatic frame (``frame=True`` or ``frame=\"a\"``)",
"add a frame to your plot. For example, we can plot the #",
"automatic frame (``frame=True`` or ``frame=\"a\"``) sets the default GMT style frame # and",
"# ----- # # The figure title can be set by passing **+t**\\",
"pygmt.Figure() # region=\"IS\" specifies Iceland using the ISO country code fig.coast(shorelines=\"1/0.5p\", region=\"IS\", projection=\"M25c\")",
"marks from appearing in the figure title, # the frame argument can be",
"maps. fig = pygmt.Figure() fig.basemap( region=[0, 10, 0, 20], projection=\"X10c/8c\", frame=[\"WSne\", \"x+lx-axis\", \"y+ly-axis\"],",
"sets the default GMT style frame # and automatically determines tick labels from",
"lines to the plot by adding a ``g`` to ``frame``: fig = pygmt.Figure()",
"can be passed, which is ``\"WSne\"`` in the example # below. The letters",
"other plotting module: fig = pygmt.Figure() fig.coast(shorelines=\"1/0.5p\", region=[-180, 180, -60, 60], projection=\"M25c\") fig.basemap(frame=\"f\")",
"in the example below. fig = pygmt.Figure() # region=\"IS\" specifies Iceland using the",
"of :class:`pygmt.Figure`. \"\"\" import pygmt ######################################################################################## # Plot frame # ---------- # #",
"by the ``frame`` argument that all plotting methods of :class:`pygmt.Figure`. \"\"\" import pygmt",
"from appearing in the figure title, # the frame argument can be passed",
"example, we can plot the # coastlines of the world with a Mercator",
"######################################################################################## # Axis labels # ----------- # # Axis labels can be set",
"# Plot frame # ---------- # # By default, PyGMT does not add",
"the primary axes can be passed, which is ``\"WSne\"`` in the example #",
"of # the figure. To designate only some of the axes as primary,",
"# Ticks and grid lines # -------------------- # # The automatic frame (``frame=True``",
"Axis labels # ----------- # # Axis labels can be set by passing",
"sides of a figure. # # The example below used a Cartesian projection,",
"ticks, titles, and labels ================================= Setting the style of the map frames, ticks,",
"labeling the y-axis) if to the ``frame`` parameter of :meth:`pygmt.Figure.basemap`. # Axis labels",
"the figure. To designate only some of the axes as primary, an argument",
":meth:`pygmt.Figure.basemap`. Passing multiple arguments to ``frame`` can be done by # using a",
":class:`pygmt.Figure`. \"\"\" import pygmt ######################################################################################## # Plot frame # ---------- # # By",
"and Tobago fig.coast(shorelines=\"1/0.5p\", region=\"TT\", projection=\"M25c\") fig.basemap(frame=[\"a\", '+t\"Trinidad and Tobago\"']) fig.show() ######################################################################################## # Axis",
"The automatic frame (``frame=True`` or ``frame=\"a\"``) sets the default GMT style frame #",
"Trinidad and Tobago fig.coast(shorelines=\"1/0.5p\", region=\"TT\", projection=\"M25c\") fig.basemap(frame=[\"a\", '+t\"Trinidad and Tobago\"']) fig.show() ######################################################################################## #",
"pygmt.Figure() # region=\"TT\" specifies Trinidad and Tobago fig.coast(shorelines=\"1/0.5p\", region=\"TT\", projection=\"M25c\") fig.basemap(frame=[\"a\", '+t\"Trinidad and",
"# -------------------- # # The automatic frame (``frame=True`` or ``frame=\"a\"``) sets the default",
"figure. To designate only some of the axes as primary, an argument that",
"fig = pygmt.Figure() fig.coast(shorelines=\"1/0.5p\", region=[-180, 180, -60, 60], projection=\"M25c\") fig.basemap(frame=\"f\") fig.show() ######################################################################################## #",
"a figure. # # The example below used a Cartesian projection, as GMT",
"the title can be # passed in double quotation marks. fig = pygmt.Figure()",
"frame to your plot. For example, we can plot the # coastlines of",
"= pygmt.Figure() fig.coast(shorelines=\"1/0.5p\", region=[-180, 180, -60, 60], projection=\"M25c\") fig.basemap(frame=\"ag\") fig.show() ######################################################################################## # Title",
"The example below used a Cartesian projection, as GMT does not allow axis",
"as primary, an argument that # capitlizes only the primary axes can be",
"coastlines of the world with a Mercator projection: fig = pygmt.Figure() fig.coast(shorelines=\"1/0.5p\", region=[-180,",
"module: fig = pygmt.Figure() fig.coast(shorelines=\"1/0.5p\", region=[-180, 180, -60, 60], projection=\"M25c\") fig.basemap(frame=\"f\") fig.show() ########################################################################################",
"pygmt.Figure() fig.coast(shorelines=\"1/0.5p\", region=[-180, 180, -60, 60], projection=\"M25c\") fig.basemap(frame=\"f\") fig.show() ######################################################################################## # Ticks and",
"by passing **+t**\\ *title* to the ``frame`` parameter of # :meth:`pygmt.Figure.basemap`. Passing multiple",
"geographic maps. fig = pygmt.Figure() fig.basemap( region=[0, 10, 0, 20], projection=\"X10c/8c\", frame=[\"WSne\", \"x+lx-axis\",",
"be set by passing **x+l**\\ *label* (or starting with y if # labeling",
"for geographic maps. fig = pygmt.Figure() fig.basemap( region=[0, 10, 0, 20], projection=\"X10c/8c\", frame=[\"WSne\",",
"title can be # passed in double quotation marks. fig = pygmt.Figure() #",
"ticks, etc, is handled by the ``frame`` argument that all plotting methods of",
"the ``frame`` argument that all plotting methods of :class:`pygmt.Figure`. \"\"\" import pygmt ########################################################################################",
"map frames, ticks, etc, is handled by the ``frame`` argument that all plotting",
"must be placed inside another set of # quotation marks. To prevent the",
"**x+l**\\ *label* (or starting with y if # labeling the y-axis) if to",
"``frame`` argument that all plotting methods of :class:`pygmt.Figure`. \"\"\" import pygmt ######################################################################################## #",
"(top), and # east (right) sides of a figure. # # The example"
] |
[
"import migrations, models class Migration(migrations.Migration): dependencies = [ ('bot', '0005_auto_20171229_2354'), ] operations =",
"[ ('bot', '0005_auto_20171229_2354'), ] operations = [ migrations.AlterField( model_name='user', name='authority', field=models.IntegerField(choices=[(0, 'Master'), (1,",
"migrations, models class Migration(migrations.Migration): dependencies = [ ('bot', '0005_auto_20171229_2354'), ] operations = [",
"on 2017-12-29 14:54 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [",
"Generated by Django 2.0 on 2017-12-29 14:54 from django.db import migrations, models class",
"2.0 on 2017-12-29 14:54 from django.db import migrations, models class Migration(migrations.Migration): dependencies =",
"= [ ('bot', '0005_auto_20171229_2354'), ] operations = [ migrations.AlterField( model_name='user', name='authority', field=models.IntegerField(choices=[(0, 'Master'),",
"operations = [ migrations.AlterField( model_name='user', name='authority', field=models.IntegerField(choices=[(0, 'Master'), (1, 'Editor'), (2, 'Watcher')]), ),",
"'0005_auto_20171229_2354'), ] operations = [ migrations.AlterField( model_name='user', name='authority', field=models.IntegerField(choices=[(0, 'Master'), (1, 'Editor'), (2,",
"by Django 2.0 on 2017-12-29 14:54 from django.db import migrations, models class Migration(migrations.Migration):",
"# Generated by Django 2.0 on 2017-12-29 14:54 from django.db import migrations, models",
"('bot', '0005_auto_20171229_2354'), ] operations = [ migrations.AlterField( model_name='user', name='authority', field=models.IntegerField(choices=[(0, 'Master'), (1, 'Editor'),",
"from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('bot', '0005_auto_20171229_2354'), ]",
"models class Migration(migrations.Migration): dependencies = [ ('bot', '0005_auto_20171229_2354'), ] operations = [ migrations.AlterField(",
"14:54 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('bot', '0005_auto_20171229_2354'),",
"class Migration(migrations.Migration): dependencies = [ ('bot', '0005_auto_20171229_2354'), ] operations = [ migrations.AlterField( model_name='user',",
"dependencies = [ ('bot', '0005_auto_20171229_2354'), ] operations = [ migrations.AlterField( model_name='user', name='authority', field=models.IntegerField(choices=[(0,",
"Migration(migrations.Migration): dependencies = [ ('bot', '0005_auto_20171229_2354'), ] operations = [ migrations.AlterField( model_name='user', name='authority',",
"Django 2.0 on 2017-12-29 14:54 from django.db import migrations, models class Migration(migrations.Migration): dependencies",
"= [ migrations.AlterField( model_name='user', name='authority', field=models.IntegerField(choices=[(0, 'Master'), (1, 'Editor'), (2, 'Watcher')]), ), ]",
"2017-12-29 14:54 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('bot',",
"] operations = [ migrations.AlterField( model_name='user', name='authority', field=models.IntegerField(choices=[(0, 'Master'), (1, 'Editor'), (2, 'Watcher')]),",
"django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('bot', '0005_auto_20171229_2354'), ] operations"
] |
[
"elif priority == 9: score_range = (idx.format('9'), '+inf') else: raise ValueError('TODO') return self._redis.zcount(self.name,",
"yield value.decode('utf-8') def chunks(iterable, size): \"\"\" A generator which returns chunks of `size`",
"the highest to the lowest priority. Only after all items with a high",
"for i=1, #ARGV, 2 do local priority = ARGV[i] local member = ARGV[i",
"k in keys_chunk)) self.lua_special_zadd(keys=[self.name], args=args) def delete(self, keys): if keys: return self._redis.zrem(self.name, *keys)",
"with a lower priority will be returned. The priority parameter is an integer",
"queue local auto_increment = redis.call('incr', '_'..key..'_seq') score = priority..string.format('%015d', auto_increment) redis.call('ZADD', key, score,",
"if priority is None: return len(self) idx = '{}000000000000000' if priority == 0:",
"= itertools.chain(*((priority, k) for k in keys_chunk)) self.lua_special_zadd(keys=[self.name], args=args) def delete(self, keys): if",
"(FIFO) * doesn't allow duplicates When a duplicate item with a higher priority",
"= priority..string.sub(score, 2) redis.call('ZADD', key, score, member) end end end \"\"\" HIGHEST_PRIORITY =",
"because the element is not yet in the queue local auto_increment = redis.call('incr',",
"LOWEST_PRIORITY = 9 class UniquePriorityFifoQueue: \"\"\" A redis queue which: * preserves ordering:",
"elif priority < 9: score_range = (idx.format(priority), idx.format(f'({priority + 1}')) elif priority ==",
"chunk_size): # redis expects: priority1, member1, priority2, member2, ... args = itertools.chain(*((priority, k)",
"auto_increment) redis.call('ZADD', key, score, member) else -- update only if the priority is",
"first out (FIFO) * doesn't allow duplicates When a duplicate item with a",
"be returned. The priority parameter is an integer in the range 0-9. 0",
"yet in the queue local auto_increment = redis.call('incr', '_'..key..'_seq') score = priority..string.format('%015d', auto_increment)",
"`size` elements until there are no more items left in the iterable. \"\"\"",
"item with a lower priority is inserted nothing happens. * has 10 priority",
"idx.format(f'({priority + 1}')) elif priority == 9: score_range = (idx.format('9'), '+inf') else: raise",
"a duplicate item with a lower priority is inserted nothing happens. * has",
"in, first out (FIFO) * doesn't allow duplicates When a duplicate item with",
"the lowest priority. Default priority ist 9. \"\"\" def __init__(self, name, redis): self.name",
"with a high priority have been popped, items with a lower priority will",
"ordering: first in, first out (FIFO) * doesn't allow duplicates When a duplicate",
"score then -- add, because the element is not yet in the queue",
"count - 1) items, _ = pipe.execute() for value in items: yield value.decode('utf-8')",
"itertools.chain(*((priority, k) for k in keys_chunk)) self.lua_special_zadd(keys=[self.name], args=args) def delete(self, keys): if keys:",
"'+inf') else: raise ValueError('TODO') return self._redis.zcount(self.name, *score_range) def insert(self, keys, priority=LOWEST_PRIORITY, chunk_size=5000): for",
"= KEYS[1] for i=1, #ARGV, 2 do local priority = ARGV[i] local member",
"nothing happens. * has 10 priority classes Items are returned from the highest",
"local score = redis.call('zscore', key, member) if not score then -- add, because",
"no more items left in the iterable. \"\"\" it = iter(iterable) item =",
"= ('-inf', idx.format('(1')) elif priority < 9: score_range = (idx.format(priority), idx.format(f'({priority + 1}'))",
"priority < 9: score_range = (idx.format(priority), idx.format(f'({priority + 1}')) elif priority == 9:",
"in items: yield value.decode('utf-8') def chunks(iterable, size): \"\"\" A generator which returns chunks",
"0 LOWEST_PRIORITY = 9 class UniquePriorityFifoQueue: \"\"\" A redis queue which: * preserves",
"def chunks(iterable, size): \"\"\" A generator which returns chunks of `size` elements until",
"then score = priority..string.sub(score, 2) redis.call('ZADD', key, score, member) end end end \"\"\"",
"insert(self, keys, priority=LOWEST_PRIORITY, chunk_size=5000): for keys_chunk in chunks(keys, chunk_size): # redis expects: priority1,",
"* preserves ordering: first in, first out (FIFO) * doesn't allow duplicates When",
"items with a lower priority will be returned. The priority parameter is an",
"range 0-9. 0 is the highest priority, 9 ist the lowest priority. Default",
"member2, ... args = itertools.chain(*((priority, k) for k in keys_chunk)) self.lua_special_zadd(keys=[self.name], args=args) def",
"duplicates When a duplicate item with a higher priority is inserted the priority",
"('-inf', idx.format('(1')) elif priority < 9: score_range = (idx.format(priority), idx.format(f'({priority + 1}')) elif",
"HIGHEST_PRIORITY = 0 LOWEST_PRIORITY = 9 class UniquePriorityFifoQueue: \"\"\" A redis queue which:",
"1) items, _ = pipe.execute() for value in items: yield value.decode('utf-8') def chunks(iterable,",
"score = redis.call('zscore', key, member) if not score then -- add, because the",
"popped, items with a lower priority will be returned. The priority parameter is",
"'{}000000000000000' if priority == 0: score_range = ('-inf', idx.format('(1')) elif priority < 9:",
"with a higher priority is inserted the priority will be overwritten. When a",
"= ARGV[i] local member = ARGV[i + 1] local score = redis.call('zscore', key,",
"not score then -- add, because the element is not yet in the",
"+ 1}')) elif priority == 9: score_range = (idx.format('9'), '+inf') else: raise ValueError('TODO')",
"1) if tonumber(priority) < tonumber(current_priority) then score = priority..string.sub(score, 2) redis.call('ZADD', key, score,",
"args=args) def delete(self, keys): if keys: return self._redis.zrem(self.name, *keys) def pop(self, count): assert",
"pipe.zremrangebyrank(self.name, 0, count - 1) items, _ = pipe.execute() for value in items:",
"ARGV[i] local member = ARGV[i + 1] local score = redis.call('zscore', key, member)",
"priority classes Items are returned from the highest to the lowest priority. Only",
"if keys: return self._redis.zrem(self.name, *keys) def pop(self, count): assert 0 < count <=",
"1}')) elif priority == 9: score_range = (idx.format('9'), '+inf') else: raise ValueError('TODO') return",
"iterable. \"\"\" it = iter(iterable) item = list(itertools.islice(it, size)) while item: yield item",
"self._redis.register_script(lua_insert_script) def __len__(self): return self._redis.zcard(self.name) def count(self, priority=None): if priority is None: return",
"priority == 0: score_range = ('-inf', idx.format('(1')) elif priority < 9: score_range =",
"9: score_range = (idx.format(priority), idx.format(f'({priority + 1}')) elif priority == 9: score_range =",
"the highest priority, 9 ist the lowest priority. Default priority ist 9. \"\"\"",
"9 ist the lowest priority. Default priority ist 9. \"\"\" def __init__(self, name,",
"preserves ordering: first in, first out (FIFO) * doesn't allow duplicates When a",
"0-9. 0 is the highest priority, 9 ist the lowest priority. Default priority",
"returned. The priority parameter is an integer in the range 0-9. 0 is",
"items with a high priority have been popped, items with a lower priority",
"self._redis = redis self.lua_special_zadd = self._redis.register_script(lua_insert_script) def __len__(self): return self._redis.zcard(self.name) def count(self, priority=None):",
"= \"\"\" local key = KEYS[1] for i=1, #ARGV, 2 do local priority",
"in the queue local auto_increment = redis.call('incr', '_'..key..'_seq') score = priority..string.format('%015d', auto_increment) redis.call('ZADD',",
"redis.call('zscore', key, member) if not score then -- add, because the element is",
"local member = ARGV[i + 1] local score = redis.call('zscore', key, member) if",
"there are no more items left in the iterable. \"\"\" it = iter(iterable)",
"def __init__(self, name, redis): self.name = name self._redis = redis self.lua_special_zadd = self._redis.register_script(lua_insert_script)",
"- 1) pipe.zremrangebyrank(self.name, 0, count - 1) items, _ = pipe.execute() for value",
"key, score, member) end end end \"\"\" HIGHEST_PRIORITY = 0 LOWEST_PRIORITY = 9",
"auto_increment = redis.call('incr', '_'..key..'_seq') score = priority..string.format('%015d', auto_increment) redis.call('ZADD', key, score, member) else",
"a duplicate item with a higher priority is inserted the priority will be",
"lower priority is inserted nothing happens. * has 10 priority classes Items are",
"= 9 class UniquePriorityFifoQueue: \"\"\" A redis queue which: * preserves ordering: first",
"overwritten. When a duplicate item with a lower priority is inserted nothing happens.",
"KEYS[1] for i=1, #ARGV, 2 do local priority = ARGV[i] local member =",
"are no more items left in the iterable. \"\"\" it = iter(iterable) item",
"lowest priority. Default priority ist 9. \"\"\" def __init__(self, name, redis): self.name =",
"high priority have been popped, items with a lower priority will be returned.",
"self.lua_special_zadd(keys=[self.name], args=args) def delete(self, keys): if keys: return self._redis.zrem(self.name, *keys) def pop(self, count):",
"priority parameter is an integer in the range 0-9. 0 is the highest",
"a lower priority will be returned. The priority parameter is an integer in",
"priority = ARGV[i] local member = ARGV[i + 1] local score = redis.call('zscore',",
"score_range = (idx.format('9'), '+inf') else: raise ValueError('TODO') return self._redis.zcount(self.name, *score_range) def insert(self, keys,",
"member = ARGV[i + 1] local score = redis.call('zscore', key, member) if not",
"lower priority will be returned. The priority parameter is an integer in the",
"is None: return len(self) idx = '{}000000000000000' if priority == 0: score_range =",
"1) pipe.zremrangebyrank(self.name, 0, count - 1) items, _ = pipe.execute() for value in",
"do local priority = ARGV[i] local member = ARGV[i + 1] local score",
"integer in the range 0-9. 0 is the highest priority, 9 ist the",
"end \"\"\" HIGHEST_PRIORITY = 0 LOWEST_PRIORITY = 9 class UniquePriorityFifoQueue: \"\"\" A redis",
"if tonumber(priority) < tonumber(current_priority) then score = priority..string.sub(score, 2) redis.call('ZADD', key, score, member)",
"local priority = ARGV[i] local member = ARGV[i + 1] local score =",
"if not score then -- add, because the element is not yet in",
"out (FIFO) * doesn't allow duplicates When a duplicate item with a higher",
"items, _ = pipe.execute() for value in items: yield value.decode('utf-8') def chunks(iterable, size):",
"+ 1] local score = redis.call('zscore', key, member) if not score then --",
"in the iterable. \"\"\" it = iter(iterable) item = list(itertools.islice(it, size)) while item:",
"returned from the highest to the lowest priority. Only after all items with",
"score = priority..string.sub(score, 2) redis.call('ZADD', key, score, member) end end end \"\"\" HIGHEST_PRIORITY",
"in the range 0-9. 0 is the highest priority, 9 ist the lowest",
"end end end \"\"\" HIGHEST_PRIORITY = 0 LOWEST_PRIORITY = 9 class UniquePriorityFifoQueue: \"\"\"",
"priority have been popped, items with a lower priority will be returned. The",
"is higher local current_priority = string.sub(score, 1, 1) if tonumber(priority) < tonumber(current_priority) then",
"item with a higher priority is inserted the priority will be overwritten. When",
"if the priority is higher local current_priority = string.sub(score, 1, 1) if tonumber(priority)",
"the iterable. \"\"\" it = iter(iterable) item = list(itertools.islice(it, size)) while item: yield",
"redis.call('ZADD', key, score, member) else -- update only if the priority is higher",
"duplicate item with a lower priority is inserted nothing happens. * has 10",
"self._redis.zcard(self.name) def count(self, priority=None): if priority is None: return len(self) idx = '{}000000000000000'",
"__init__(self, name, redis): self.name = name self._redis = redis self.lua_special_zadd = self._redis.register_script(lua_insert_script) def",
"until there are no more items left in the iterable. \"\"\" it =",
"import itertools lua_insert_script = \"\"\" local key = KEYS[1] for i=1, #ARGV, 2",
"a high priority have been popped, items with a lower priority will be",
"self._redis.zcount(self.name, *score_range) def insert(self, keys, priority=LOWEST_PRIORITY, chunk_size=5000): for keys_chunk in chunks(keys, chunk_size): #",
"the range 0-9. 0 is the highest priority, 9 ist the lowest priority.",
"-- add, because the element is not yet in the queue local auto_increment",
"(idx.format(priority), idx.format(f'({priority + 1}')) elif priority == 9: score_range = (idx.format('9'), '+inf') else:",
"is not yet in the queue local auto_increment = redis.call('incr', '_'..key..'_seq') score =",
"UniquePriorityFifoQueue: \"\"\" A redis queue which: * preserves ordering: first in, first out",
"== 9: score_range = (idx.format('9'), '+inf') else: raise ValueError('TODO') return self._redis.zcount(self.name, *score_range) def",
"redis self.lua_special_zadd = self._redis.register_script(lua_insert_script) def __len__(self): return self._redis.zcard(self.name) def count(self, priority=None): if priority",
"higher local current_priority = string.sub(score, 1, 1) if tonumber(priority) < tonumber(current_priority) then score",
"redis.call('ZADD', key, score, member) end end end \"\"\" HIGHEST_PRIORITY = 0 LOWEST_PRIORITY =",
"priority, 9 ist the lowest priority. Default priority ist 9. \"\"\" def __init__(self,",
"== 0: score_range = ('-inf', idx.format('(1')) elif priority < 9: score_range = (idx.format(priority),",
"ValueError('TODO') return self._redis.zcount(self.name, *score_range) def insert(self, keys, priority=LOWEST_PRIORITY, chunk_size=5000): for keys_chunk in chunks(keys,",
"When a duplicate item with a lower priority is inserted nothing happens. *",
"key, score, member) else -- update only if the priority is higher local",
"add, because the element is not yet in the queue local auto_increment =",
"lowest priority. Only after all items with a high priority have been popped,",
"parameter is an integer in the range 0-9. 0 is the highest priority,",
"args = itertools.chain(*((priority, k) for k in keys_chunk)) self.lua_special_zadd(keys=[self.name], args=args) def delete(self, keys):",
"< tonumber(current_priority) then score = priority..string.sub(score, 2) redis.call('ZADD', key, score, member) end end",
"member1, priority2, member2, ... args = itertools.chain(*((priority, k) for k in keys_chunk)) self.lua_special_zadd(keys=[self.name],",
"= pipe.execute() for value in items: yield value.decode('utf-8') def chunks(iterable, size): \"\"\" A",
"lua_insert_script = \"\"\" local key = KEYS[1] for i=1, #ARGV, 2 do local",
"= redis.call('incr', '_'..key..'_seq') score = priority..string.format('%015d', auto_increment) redis.call('ZADD', key, score, member) else --",
"for value in items: yield value.decode('utf-8') def chunks(iterable, size): \"\"\" A generator which",
"None: return len(self) idx = '{}000000000000000' if priority == 0: score_range = ('-inf',",
"return len(self) idx = '{}000000000000000' if priority == 0: score_range = ('-inf', idx.format('(1'))",
"score, member) end end end \"\"\" HIGHEST_PRIORITY = 0 LOWEST_PRIORITY = 9 class",
"*keys) def pop(self, count): assert 0 < count <= 25000 with self._redis.pipeline() as",
"A redis queue which: * preserves ordering: first in, first out (FIFO) *",
"priority is None: return len(self) idx = '{}000000000000000' if priority == 0: score_range",
"* has 10 priority classes Items are returned from the highest to the",
"redis.call('incr', '_'..key..'_seq') score = priority..string.format('%015d', auto_increment) redis.call('ZADD', key, score, member) else -- update",
"Default priority ist 9. \"\"\" def __init__(self, name, redis): self.name = name self._redis",
"priority..string.sub(score, 2) redis.call('ZADD', key, score, member) end end end \"\"\" HIGHEST_PRIORITY = 0",
"priority. Default priority ist 9. \"\"\" def __init__(self, name, redis): self.name = name",
"local key = KEYS[1] for i=1, #ARGV, 2 do local priority = ARGV[i]",
"= (idx.format('9'), '+inf') else: raise ValueError('TODO') return self._redis.zcount(self.name, *score_range) def insert(self, keys, priority=LOWEST_PRIORITY,",
"keys_chunk)) self.lua_special_zadd(keys=[self.name], args=args) def delete(self, keys): if keys: return self._redis.zrem(self.name, *keys) def pop(self,",
"end end \"\"\" HIGHEST_PRIORITY = 0 LOWEST_PRIORITY = 9 class UniquePriorityFifoQueue: \"\"\" A",
"are returned from the highest to the lowest priority. Only after all items",
"* doesn't allow duplicates When a duplicate item with a higher priority is",
"< count <= 25000 with self._redis.pipeline() as pipe: pipe.multi() pipe.zrange(self.name, 0, count -",
"the queue local auto_increment = redis.call('incr', '_'..key..'_seq') score = priority..string.format('%015d', auto_increment) redis.call('ZADD', key,",
"for keys_chunk in chunks(keys, chunk_size): # redis expects: priority1, member1, priority2, member2, ...",
"<reponame>ckrybus/redis-unique-priority-queue import itertools lua_insert_script = \"\"\" local key = KEYS[1] for i=1, #ARGV,",
"'_'..key..'_seq') score = priority..string.format('%015d', auto_increment) redis.call('ZADD', key, score, member) else -- update only",
"count - 1) pipe.zremrangebyrank(self.name, 0, count - 1) items, _ = pipe.execute() for",
"= name self._redis = redis self.lua_special_zadd = self._redis.register_script(lua_insert_script) def __len__(self): return self._redis.zcard(self.name) def",
"_ = pipe.execute() for value in items: yield value.decode('utf-8') def chunks(iterable, size): \"\"\"",
"have been popped, items with a lower priority will be returned. The priority",
"0, count - 1) items, _ = pipe.execute() for value in items: yield",
"will be returned. The priority parameter is an integer in the range 0-9.",
"priority is higher local current_priority = string.sub(score, 1, 1) if tonumber(priority) < tonumber(current_priority)",
"will be overwritten. When a duplicate item with a lower priority is inserted",
"classes Items are returned from the highest to the lowest priority. Only after",
"pipe.multi() pipe.zrange(self.name, 0, count - 1) pipe.zremrangebyrank(self.name, 0, count - 1) items, _",
"priority ist 9. \"\"\" def __init__(self, name, redis): self.name = name self._redis =",
"< 9: score_range = (idx.format(priority), idx.format(f'({priority + 1}')) elif priority == 9: score_range",
"Items are returned from the highest to the lowest priority. Only after all",
"10 priority classes Items are returned from the highest to the lowest priority.",
"duplicate item with a higher priority is inserted the priority will be overwritten.",
"0: score_range = ('-inf', idx.format('(1')) elif priority < 9: score_range = (idx.format(priority), idx.format(f'({priority",
"in chunks(keys, chunk_size): # redis expects: priority1, member1, priority2, member2, ... args =",
"def count(self, priority=None): if priority is None: return len(self) idx = '{}000000000000000' if",
"priority..string.format('%015d', auto_increment) redis.call('ZADD', key, score, member) else -- update only if the priority",
"*score_range) def insert(self, keys, priority=LOWEST_PRIORITY, chunk_size=5000): for keys_chunk in chunks(keys, chunk_size): # redis",
"def __len__(self): return self._redis.zcard(self.name) def count(self, priority=None): if priority is None: return len(self)",
"= redis.call('zscore', key, member) if not score then -- add, because the element",
"priority is inserted nothing happens. * has 10 priority classes Items are returned",
"= priority..string.format('%015d', auto_increment) redis.call('ZADD', key, score, member) else -- update only if the",
"priority=LOWEST_PRIORITY, chunk_size=5000): for keys_chunk in chunks(keys, chunk_size): # redis expects: priority1, member1, priority2,",
"as pipe: pipe.multi() pipe.zrange(self.name, 0, count - 1) pipe.zremrangebyrank(self.name, 0, count - 1)",
"element is not yet in the queue local auto_increment = redis.call('incr', '_'..key..'_seq') score",
"be overwritten. When a duplicate item with a lower priority is inserted nothing",
"Only after all items with a high priority have been popped, items with",
"redis): self.name = name self._redis = redis self.lua_special_zadd = self._redis.register_script(lua_insert_script) def __len__(self): return",
"size): \"\"\" A generator which returns chunks of `size` elements until there are",
"key, member) if not score then -- add, because the element is not",
"is inserted nothing happens. * has 10 priority classes Items are returned from",
"chunk_size=5000): for keys_chunk in chunks(keys, chunk_size): # redis expects: priority1, member1, priority2, member2,",
"score, member) else -- update only if the priority is higher local current_priority",
"a higher priority is inserted the priority will be overwritten. When a duplicate",
"pipe: pipe.multi() pipe.zrange(self.name, 0, count - 1) pipe.zremrangebyrank(self.name, 0, count - 1) items,",
"value in items: yield value.decode('utf-8') def chunks(iterable, size): \"\"\" A generator which returns",
"elements until there are no more items left in the iterable. \"\"\" it",
"priority=None): if priority is None: return len(self) idx = '{}000000000000000' if priority ==",
"\"\"\" def __init__(self, name, redis): self.name = name self._redis = redis self.lua_special_zadd =",
"pipe.execute() for value in items: yield value.decode('utf-8') def chunks(iterable, size): \"\"\" A generator",
"redis expects: priority1, member1, priority2, member2, ... args = itertools.chain(*((priority, k) for k",
"name, redis): self.name = name self._redis = redis self.lua_special_zadd = self._redis.register_script(lua_insert_script) def __len__(self):",
"assert 0 < count <= 25000 with self._redis.pipeline() as pipe: pipe.multi() pipe.zrange(self.name, 0,",
"which returns chunks of `size` elements until there are no more items left",
"0 < count <= 25000 with self._redis.pipeline() as pipe: pipe.multi() pipe.zrange(self.name, 0, count",
"else -- update only if the priority is higher local current_priority = string.sub(score,",
"chunks(keys, chunk_size): # redis expects: priority1, member1, priority2, member2, ... args = itertools.chain(*((priority,",
"the priority is higher local current_priority = string.sub(score, 1, 1) if tonumber(priority) <",
"which: * preserves ordering: first in, first out (FIFO) * doesn't allow duplicates",
"with a lower priority is inserted nothing happens. * has 10 priority classes",
"an integer in the range 0-9. 0 is the highest priority, 9 ist",
"ist the lowest priority. Default priority ist 9. \"\"\" def __init__(self, name, redis):",
"the lowest priority. Only after all items with a high priority have been",
"= string.sub(score, 1, 1) if tonumber(priority) < tonumber(current_priority) then score = priority..string.sub(score, 2)",
"iter(iterable) item = list(itertools.islice(it, size)) while item: yield item item = list(itertools.islice(it, size))",
"def insert(self, keys, priority=LOWEST_PRIORITY, chunk_size=5000): for keys_chunk in chunks(keys, chunk_size): # redis expects:",
"been popped, items with a lower priority will be returned. The priority parameter",
"raise ValueError('TODO') return self._redis.zcount(self.name, *score_range) def insert(self, keys, priority=LOWEST_PRIORITY, chunk_size=5000): for keys_chunk in",
"member) if not score then -- add, because the element is not yet",
"priority will be overwritten. When a duplicate item with a lower priority is",
"is an integer in the range 0-9. 0 is the highest priority, 9",
"keys, priority=LOWEST_PRIORITY, chunk_size=5000): for keys_chunk in chunks(keys, chunk_size): # redis expects: priority1, member1,",
"# redis expects: priority1, member1, priority2, member2, ... args = itertools.chain(*((priority, k) for",
"count(self, priority=None): if priority is None: return len(self) idx = '{}000000000000000' if priority",
"tonumber(current_priority) then score = priority..string.sub(score, 2) redis.call('ZADD', key, score, member) end end end",
"allow duplicates When a duplicate item with a higher priority is inserted the",
"self._redis.pipeline() as pipe: pipe.multi() pipe.zrange(self.name, 0, count - 1) pipe.zremrangebyrank(self.name, 0, count -",
"keys): if keys: return self._redis.zrem(self.name, *keys) def pop(self, count): assert 0 < count",
"name self._redis = redis self.lua_special_zadd = self._redis.register_script(lua_insert_script) def __len__(self): return self._redis.zcard(self.name) def count(self,",
"all items with a high priority have been popped, items with a lower",
"else: raise ValueError('TODO') return self._redis.zcount(self.name, *score_range) def insert(self, keys, priority=LOWEST_PRIORITY, chunk_size=5000): for keys_chunk",
"score_range = ('-inf', idx.format('(1')) elif priority < 9: score_range = (idx.format(priority), idx.format(f'({priority +",
"0 is the highest priority, 9 ist the lowest priority. Default priority ist",
"def delete(self, keys): if keys: return self._redis.zrem(self.name, *keys) def pop(self, count): assert 0",
"len(self) idx = '{}000000000000000' if priority == 0: score_range = ('-inf', idx.format('(1')) elif",
"highest to the lowest priority. Only after all items with a high priority",
"\"\"\" local key = KEYS[1] for i=1, #ARGV, 2 do local priority =",
"= ARGV[i + 1] local score = redis.call('zscore', key, member) if not score",
"is the highest priority, 9 ist the lowest priority. Default priority ist 9.",
"return self._redis.zcard(self.name) def count(self, priority=None): if priority is None: return len(self) idx =",
"When a duplicate item with a higher priority is inserted the priority will",
"keys_chunk in chunks(keys, chunk_size): # redis expects: priority1, member1, priority2, member2, ... args",
"priority will be returned. The priority parameter is an integer in the range",
"self.lua_special_zadd = self._redis.register_script(lua_insert_script) def __len__(self): return self._redis.zcard(self.name) def count(self, priority=None): if priority is",
"member) else -- update only if the priority is higher local current_priority =",
"keys: return self._redis.zrem(self.name, *keys) def pop(self, count): assert 0 < count <= 25000",
"2) redis.call('ZADD', key, score, member) end end end \"\"\" HIGHEST_PRIORITY = 0 LOWEST_PRIORITY",
"priority. Only after all items with a high priority have been popped, items",
"= 0 LOWEST_PRIORITY = 9 class UniquePriorityFifoQueue: \"\"\" A redis queue which: *",
"with self._redis.pipeline() as pipe: pipe.multi() pipe.zrange(self.name, 0, count - 1) pipe.zremrangebyrank(self.name, 0, count",
"local auto_increment = redis.call('incr', '_'..key..'_seq') score = priority..string.format('%015d', auto_increment) redis.call('ZADD', key, score, member)",
"chunks(iterable, size): \"\"\" A generator which returns chunks of `size` elements until there",
"to the lowest priority. Only after all items with a high priority have",
"chunks of `size` elements until there are no more items left in the",
"itertools lua_insert_script = \"\"\" local key = KEYS[1] for i=1, #ARGV, 2 do",
"expects: priority1, member1, priority2, member2, ... args = itertools.chain(*((priority, k) for k in",
"The priority parameter is an integer in the range 0-9. 0 is the",
"2 do local priority = ARGV[i] local member = ARGV[i + 1] local",
"left in the iterable. \"\"\" it = iter(iterable) item = list(itertools.islice(it, size)) while",
"pipe.zrange(self.name, 0, count - 1) pipe.zremrangebyrank(self.name, 0, count - 1) items, _ =",
"priority == 9: score_range = (idx.format('9'), '+inf') else: raise ValueError('TODO') return self._redis.zcount(self.name, *score_range)",
"idx = '{}000000000000000' if priority == 0: score_range = ('-inf', idx.format('(1')) elif priority",
"redis queue which: * preserves ordering: first in, first out (FIFO) * doesn't",
"items left in the iterable. \"\"\" it = iter(iterable) item = list(itertools.islice(it, size))",
"#ARGV, 2 do local priority = ARGV[i] local member = ARGV[i + 1]",
"\"\"\" A redis queue which: * preserves ordering: first in, first out (FIFO)",
"= redis self.lua_special_zadd = self._redis.register_script(lua_insert_script) def __len__(self): return self._redis.zcard(self.name) def count(self, priority=None): if",
"pop(self, count): assert 0 < count <= 25000 with self._redis.pipeline() as pipe: pipe.multi()",
"returns chunks of `size` elements until there are no more items left in",
"from the highest to the lowest priority. Only after all items with a",
"first in, first out (FIFO) * doesn't allow duplicates When a duplicate item",
"the priority will be overwritten. When a duplicate item with a lower priority",
"9: score_range = (idx.format('9'), '+inf') else: raise ValueError('TODO') return self._redis.zcount(self.name, *score_range) def insert(self,",
"\"\"\" it = iter(iterable) item = list(itertools.islice(it, size)) while item: yield item item",
"queue which: * preserves ordering: first in, first out (FIFO) * doesn't allow",
"self.name = name self._redis = redis self.lua_special_zadd = self._redis.register_script(lua_insert_script) def __len__(self): return self._redis.zcard(self.name)",
"not yet in the queue local auto_increment = redis.call('incr', '_'..key..'_seq') score = priority..string.format('%015d',",
"tonumber(priority) < tonumber(current_priority) then score = priority..string.sub(score, 2) redis.call('ZADD', key, score, member) end",
"self._redis.zrem(self.name, *keys) def pop(self, count): assert 0 < count <= 25000 with self._redis.pipeline()",
"= '{}000000000000000' if priority == 0: score_range = ('-inf', idx.format('(1')) elif priority <",
"of `size` elements until there are no more items left in the iterable.",
"for k in keys_chunk)) self.lua_special_zadd(keys=[self.name], args=args) def delete(self, keys): if keys: return self._redis.zrem(self.name,",
"(idx.format('9'), '+inf') else: raise ValueError('TODO') return self._redis.zcount(self.name, *score_range) def insert(self, keys, priority=LOWEST_PRIORITY, chunk_size=5000):",
"25000 with self._redis.pipeline() as pipe: pipe.multi() pipe.zrange(self.name, 0, count - 1) pipe.zremrangebyrank(self.name, 0,",
"def pop(self, count): assert 0 < count <= 25000 with self._redis.pipeline() as pipe:",
"only if the priority is higher local current_priority = string.sub(score, 1, 1) if",
"ARGV[i + 1] local score = redis.call('zscore', key, member) if not score then",
"-- update only if the priority is higher local current_priority = string.sub(score, 1,",
"count <= 25000 with self._redis.pipeline() as pipe: pipe.multi() pipe.zrange(self.name, 0, count - 1)",
"i=1, #ARGV, 2 do local priority = ARGV[i] local member = ARGV[i +",
"it = iter(iterable) item = list(itertools.islice(it, size)) while item: yield item item =",
"then -- add, because the element is not yet in the queue local",
"9. \"\"\" def __init__(self, name, redis): self.name = name self._redis = redis self.lua_special_zadd",
"higher priority is inserted the priority will be overwritten. When a duplicate item",
"count): assert 0 < count <= 25000 with self._redis.pipeline() as pipe: pipe.multi() pipe.zrange(self.name,",
"ist 9. \"\"\" def __init__(self, name, redis): self.name = name self._redis = redis",
"update only if the priority is higher local current_priority = string.sub(score, 1, 1)",
"the element is not yet in the queue local auto_increment = redis.call('incr', '_'..key..'_seq')",
"class UniquePriorityFifoQueue: \"\"\" A redis queue which: * preserves ordering: first in, first",
"... args = itertools.chain(*((priority, k) for k in keys_chunk)) self.lua_special_zadd(keys=[self.name], args=args) def delete(self,",
"= self._redis.register_script(lua_insert_script) def __len__(self): return self._redis.zcard(self.name) def count(self, priority=None): if priority is None:",
"current_priority = string.sub(score, 1, 1) if tonumber(priority) < tonumber(current_priority) then score = priority..string.sub(score,",
"delete(self, keys): if keys: return self._redis.zrem(self.name, *keys) def pop(self, count): assert 0 <",
"after all items with a high priority have been popped, items with a",
"key = KEYS[1] for i=1, #ARGV, 2 do local priority = ARGV[i] local",
"score_range = (idx.format(priority), idx.format(f'({priority + 1}')) elif priority == 9: score_range = (idx.format('9'),",
"priority is inserted the priority will be overwritten. When a duplicate item with",
"= (idx.format(priority), idx.format(f'({priority + 1}')) elif priority == 9: score_range = (idx.format('9'), '+inf')",
"- 1) items, _ = pipe.execute() for value in items: yield value.decode('utf-8') def",
"highest priority, 9 ist the lowest priority. Default priority ist 9. \"\"\" def",
"generator which returns chunks of `size` elements until there are no more items",
"if priority == 0: score_range = ('-inf', idx.format('(1')) elif priority < 9: score_range",
"__len__(self): return self._redis.zcard(self.name) def count(self, priority=None): if priority is None: return len(self) idx",
"member) end end end \"\"\" HIGHEST_PRIORITY = 0 LOWEST_PRIORITY = 9 class UniquePriorityFifoQueue:",
"a lower priority is inserted nothing happens. * has 10 priority classes Items",
"A generator which returns chunks of `size` elements until there are no more",
"<= 25000 with self._redis.pipeline() as pipe: pipe.multi() pipe.zrange(self.name, 0, count - 1) pipe.zremrangebyrank(self.name,",
"= iter(iterable) item = list(itertools.islice(it, size)) while item: yield item item = list(itertools.islice(it,",
"priority1, member1, priority2, member2, ... args = itertools.chain(*((priority, k) for k in keys_chunk))",
"\"\"\" A generator which returns chunks of `size` elements until there are no",
"has 10 priority classes Items are returned from the highest to the lowest",
"inserted nothing happens. * has 10 priority classes Items are returned from the",
"priority2, member2, ... args = itertools.chain(*((priority, k) for k in keys_chunk)) self.lua_special_zadd(keys=[self.name], args=args)",
"string.sub(score, 1, 1) if tonumber(priority) < tonumber(current_priority) then score = priority..string.sub(score, 2) redis.call('ZADD',",
"idx.format('(1')) elif priority < 9: score_range = (idx.format(priority), idx.format(f'({priority + 1}')) elif priority",
"return self._redis.zrem(self.name, *keys) def pop(self, count): assert 0 < count <= 25000 with",
"1] local score = redis.call('zscore', key, member) if not score then -- add,",
"k) for k in keys_chunk)) self.lua_special_zadd(keys=[self.name], args=args) def delete(self, keys): if keys: return",
"inserted the priority will be overwritten. When a duplicate item with a lower",
"local current_priority = string.sub(score, 1, 1) if tonumber(priority) < tonumber(current_priority) then score =",
"in keys_chunk)) self.lua_special_zadd(keys=[self.name], args=args) def delete(self, keys): if keys: return self._redis.zrem(self.name, *keys) def",
"\"\"\" HIGHEST_PRIORITY = 0 LOWEST_PRIORITY = 9 class UniquePriorityFifoQueue: \"\"\" A redis queue",
"0, count - 1) pipe.zremrangebyrank(self.name, 0, count - 1) items, _ = pipe.execute()",
"9 class UniquePriorityFifoQueue: \"\"\" A redis queue which: * preserves ordering: first in,",
"happens. * has 10 priority classes Items are returned from the highest to",
"score = priority..string.format('%015d', auto_increment) redis.call('ZADD', key, score, member) else -- update only if",
"is inserted the priority will be overwritten. When a duplicate item with a",
"1, 1) if tonumber(priority) < tonumber(current_priority) then score = priority..string.sub(score, 2) redis.call('ZADD', key,",
"more items left in the iterable. \"\"\" it = iter(iterable) item = list(itertools.islice(it,",
"doesn't allow duplicates When a duplicate item with a higher priority is inserted",
"return self._redis.zcount(self.name, *score_range) def insert(self, keys, priority=LOWEST_PRIORITY, chunk_size=5000): for keys_chunk in chunks(keys, chunk_size):",
"value.decode('utf-8') def chunks(iterable, size): \"\"\" A generator which returns chunks of `size` elements",
"items: yield value.decode('utf-8') def chunks(iterable, size): \"\"\" A generator which returns chunks of"
] |
[
"-> tp.Iterator[str]: # type: ignore return iter(self.__root__) def gen_df(self) -> pd.DataFrame: keys, dfs",
"orient=\"columns\") U = tp.TypeVar(\"U\", bound=BaseModelSequence) class BaseModelMapping(tp.Generic[U], BaseModelDf): __root__: tp.Mapping[str, U] def __getitem__(self,",
"\"\"\"Get slice of items from __root__ by idx.\"\"\" def __getitem__(self, index): return self.__root__[index]",
"__root__: tp.Mapping[str, U] def __getitem__(self, index: str) -> U: return self.__root__[index] def __len__(self)",
"self._created_at class BaseModelDf(BaseModel, ABC): _df: tp.Optional[pd.DataFrame] = PrivateAttr(default=None) @abstractmethod def gen_df(self) -> pd.DataFrame:",
"int: return len(self.__root__) def __iter__(self) -> tp.Iterator[str]: # type: ignore return iter(self.__root__) def",
"def __getitem__(self, index): return self.__root__[index] def __len__(self) -> int: return len(self.__root__) def __iter__(self)",
"as tp from abc import ABC, abstractmethod from datetime import datetime import pandas",
"type: ignore return iter(self.__root__) def gen_df(self) -> pd.DataFrame: return pd.DataFrame.from_dict(self.dict().get(\"__root__\"), orient=\"columns\") U =",
"items from __root__ by idx.\"\"\" def __getitem__(self, index): return self.__root__[index] def __len__(self) ->",
"return self.__root__[index] def __len__(self) -> int: return len(self.__root__) def __iter__(self) -> tp.Iterator[T]: #",
"__len__(self) -> int: return len(self.__root__) def __iter__(self) -> tp.Iterator[T]: # type: ignore return",
"@property def created_at(self) -> datetime: return self._created_at class BaseModelDf(BaseModel, ABC): _df: tp.Optional[pd.DataFrame] =",
"item from __root__ by idx.\"\"\" @tp.overload def __getitem__(self, index: slice) -> tp.Sequence[T]: \"\"\"Get",
"pd.DataFrame: keys, dfs = zip(*[(key, value.df) for key, value in self.__root__.items()]) return pd.concat(dfs,",
"tp.Iterator[str]: # type: ignore return iter(self.__root__) def gen_df(self) -> pd.DataFrame: keys, dfs =",
"return pd.DataFrame.from_dict(self.dict().get(\"__root__\"), orient=\"columns\") U = tp.TypeVar(\"U\", bound=BaseModelSequence) class BaseModelMapping(tp.Generic[U], BaseModelDf): __root__: tp.Mapping[str, U]",
"iter(self.__root__) def gen_df(self) -> pd.DataFrame: return pd.DataFrame.from_dict(self.dict().get(\"__root__\"), orient=\"columns\") U = tp.TypeVar(\"U\", bound=BaseModelSequence) class",
"__getitem__(self, index): return self.__root__[index] def __len__(self) -> int: return len(self.__root__) def __iter__(self) ->",
"from abc import ABC, abstractmethod from datetime import datetime import pandas as pd",
"return iter(self.__root__) def gen_df(self) -> pd.DataFrame: return pd.DataFrame.from_dict(self.dict().get(\"__root__\"), orient=\"columns\") U = tp.TypeVar(\"U\", bound=BaseModelSequence)",
"-> tp.Sequence[T]: \"\"\"Get slice of items from __root__ by idx.\"\"\" def __getitem__(self, index):",
"import annotations import typing as tp from abc import ABC, abstractmethod from datetime",
"pandas as pd import pendulum from pydantic import BaseModel as _BaseModel from pydantic",
"BaseModel(_BaseModel): _created_at: datetime = PrivateAttr(default_factory=pendulum.now) @property def created_at(self) -> datetime: return self._created_at class",
"__root__ by idx.\"\"\" @tp.overload def __getitem__(self, index: slice) -> tp.Sequence[T]: \"\"\"Get slice of",
"self.__root__[index] def __len__(self) -> int: return len(self.__root__) def __iter__(self) -> tp.Iterator[T]: # type:",
"def gen_df(self) -> pd.DataFrame: return pd.DataFrame.from_dict(self.dict().get(\"__root__\"), orient=\"columns\") U = tp.TypeVar(\"U\", bound=BaseModelSequence) class BaseModelMapping(tp.Generic[U],",
"self.__root__[index] def __len__(self) -> int: return len(self.__root__) def __iter__(self) -> tp.Iterator[str]: # type:",
"slice of items from __root__ by idx.\"\"\" def __getitem__(self, index): return self.__root__[index] def",
"U] def __getitem__(self, index: str) -> U: return self.__root__[index] def __len__(self) -> int:",
"T = tp.TypeVar(\"T\", bound=BaseModel) class BaseModelSequence(tp.Generic[T], BaseModelDf): __root__: tp.Sequence[T] @tp.overload def __getitem__(self, index:",
"-> T: \"\"\"Get single item from __root__ by idx.\"\"\" @tp.overload def __getitem__(self, index:",
"by idx.\"\"\" def __getitem__(self, index): return self.__root__[index] def __len__(self) -> int: return len(self.__root__)",
"type: ignore return iter(self.__root__) def gen_df(self) -> pd.DataFrame: keys, dfs = zip(*[(key, value.df)",
"_created_at: datetime = PrivateAttr(default_factory=pendulum.now) @property def created_at(self) -> datetime: return self._created_at class BaseModelDf(BaseModel,",
"return self.__root__[index] def __len__(self) -> int: return len(self.__root__) def __iter__(self) -> tp.Iterator[str]: #",
"# type: ignore return iter(self.__root__) def gen_df(self) -> pd.DataFrame: return pd.DataFrame.from_dict(self.dict().get(\"__root__\"), orient=\"columns\") U",
"from __root__ by idx.\"\"\" def __getitem__(self, index): return self.__root__[index] def __len__(self) -> int:",
"__getitem__(self, index: str) -> U: return self.__root__[index] def __len__(self) -> int: return len(self.__root__)",
"pd.DataFrame: if self._df is None: self._df = self.gen_df() return self._df T = tp.TypeVar(\"T\",",
"def __getitem__(self, index: slice) -> tp.Sequence[T]: \"\"\"Get slice of items from __root__ by",
"class BaseModelMapping(tp.Generic[U], BaseModelDf): __root__: tp.Mapping[str, U] def __getitem__(self, index: str) -> U: return",
"return len(self.__root__) def __iter__(self) -> tp.Iterator[str]: # type: ignore return iter(self.__root__) def gen_df(self)",
"BaseModelMapping(tp.Generic[U], BaseModelDf): __root__: tp.Mapping[str, U] def __getitem__(self, index: str) -> U: return self.__root__[index]",
"= PrivateAttr(default_factory=pendulum.now) @property def created_at(self) -> datetime: return self._created_at class BaseModelDf(BaseModel, ABC): _df:",
"by idx.\"\"\" @tp.overload def __getitem__(self, index: slice) -> tp.Sequence[T]: \"\"\"Get slice of items",
"-> U: return self.__root__[index] def __len__(self) -> int: return len(self.__root__) def __iter__(self) ->",
"def __len__(self) -> int: return len(self.__root__) def __iter__(self) -> tp.Iterator[str]: # type: ignore",
"datetime: return self._created_at class BaseModelDf(BaseModel, ABC): _df: tp.Optional[pd.DataFrame] = PrivateAttr(default=None) @abstractmethod def gen_df(self)",
"\"\"\"Get single item from __root__ by idx.\"\"\" @tp.overload def __getitem__(self, index: slice) ->",
"U: return self.__root__[index] def __len__(self) -> int: return len(self.__root__) def __iter__(self) -> tp.Iterator[str]:",
"__root__ by idx.\"\"\" def __getitem__(self, index): return self.__root__[index] def __len__(self) -> int: return",
"tp.TypeVar(\"U\", bound=BaseModelSequence) class BaseModelMapping(tp.Generic[U], BaseModelDf): __root__: tp.Mapping[str, U] def __getitem__(self, index: str) ->",
"self._df T = tp.TypeVar(\"T\", bound=BaseModel) class BaseModelSequence(tp.Generic[T], BaseModelDf): __root__: tp.Sequence[T] @tp.overload def __getitem__(self,",
"-> pd.DataFrame: keys, dfs = zip(*[(key, value.df) for key, value in self.__root__.items()]) return",
"@tp.overload def __getitem__(self, index: slice) -> tp.Sequence[T]: \"\"\"Get slice of items from __root__",
"pd import pendulum from pydantic import BaseModel as _BaseModel from pydantic import PrivateAttr",
"__future__ import annotations import typing as tp from abc import ABC, abstractmethod from",
"__iter__(self) -> tp.Iterator[str]: # type: ignore return iter(self.__root__) def gen_df(self) -> pd.DataFrame: keys,",
"tp.Iterator[T]: # type: ignore return iter(self.__root__) def gen_df(self) -> pd.DataFrame: return pd.DataFrame.from_dict(self.dict().get(\"__root__\"), orient=\"columns\")",
"return self._created_at class BaseModelDf(BaseModel, ABC): _df: tp.Optional[pd.DataFrame] = PrivateAttr(default=None) @abstractmethod def gen_df(self) ->",
"len(self.__root__) def __iter__(self) -> tp.Iterator[str]: # type: ignore return iter(self.__root__) def gen_df(self) ->",
"gen_df(self) -> pd.DataFrame: keys, dfs = zip(*[(key, value.df) for key, value in self.__root__.items()])",
"gen_df(self) -> pd.DataFrame: ... @property def df(self) -> pd.DataFrame: if self._df is None:",
"self._df is None: self._df = self.gen_df() return self._df T = tp.TypeVar(\"T\", bound=BaseModel) class",
"def gen_df(self) -> pd.DataFrame: ... @property def df(self) -> pd.DataFrame: if self._df is",
"datetime = PrivateAttr(default_factory=pendulum.now) @property def created_at(self) -> datetime: return self._created_at class BaseModelDf(BaseModel, ABC):",
"None: self._df = self.gen_df() return self._df T = tp.TypeVar(\"T\", bound=BaseModel) class BaseModelSequence(tp.Generic[T], BaseModelDf):",
"return iter(self.__root__) def gen_df(self) -> pd.DataFrame: keys, dfs = zip(*[(key, value.df) for key,",
"return len(self.__root__) def __iter__(self) -> tp.Iterator[T]: # type: ignore return iter(self.__root__) def gen_df(self)",
"idx.\"\"\" @tp.overload def __getitem__(self, index: slice) -> tp.Sequence[T]: \"\"\"Get slice of items from",
"import datetime import pandas as pd import pendulum from pydantic import BaseModel as",
"annotations import typing as tp from abc import ABC, abstractmethod from datetime import",
"abstractmethod from datetime import datetime import pandas as pd import pendulum from pydantic",
"__getitem__(self, index: slice) -> tp.Sequence[T]: \"\"\"Get slice of items from __root__ by idx.\"\"\"",
"import ABC, abstractmethod from datetime import datetime import pandas as pd import pendulum",
"tp.TypeVar(\"T\", bound=BaseModel) class BaseModelSequence(tp.Generic[T], BaseModelDf): __root__: tp.Sequence[T] @tp.overload def __getitem__(self, index: int) ->",
"-> int: return len(self.__root__) def __iter__(self) -> tp.Iterator[str]: # type: ignore return iter(self.__root__)",
"is None: self._df = self.gen_df() return self._df T = tp.TypeVar(\"T\", bound=BaseModel) class BaseModelSequence(tp.Generic[T],",
"self._df = self.gen_df() return self._df T = tp.TypeVar(\"T\", bound=BaseModel) class BaseModelSequence(tp.Generic[T], BaseModelDf): __root__:",
"pd.DataFrame: return pd.DataFrame.from_dict(self.dict().get(\"__root__\"), orient=\"columns\") U = tp.TypeVar(\"U\", bound=BaseModelSequence) class BaseModelMapping(tp.Generic[U], BaseModelDf): __root__: tp.Mapping[str,",
"tp.Optional[pd.DataFrame] = PrivateAttr(default=None) @abstractmethod def gen_df(self) -> pd.DataFrame: ... @property def df(self) ->",
"tp from abc import ABC, abstractmethod from datetime import datetime import pandas as",
"@tp.overload def __getitem__(self, index: int) -> T: \"\"\"Get single item from __root__ by",
"abc import ABC, abstractmethod from datetime import datetime import pandas as pd import",
"bound=BaseModelSequence) class BaseModelMapping(tp.Generic[U], BaseModelDf): __root__: tp.Mapping[str, U] def __getitem__(self, index: str) -> U:",
"= tp.TypeVar(\"U\", bound=BaseModelSequence) class BaseModelMapping(tp.Generic[U], BaseModelDf): __root__: tp.Mapping[str, U] def __getitem__(self, index: str)",
"if self._df is None: self._df = self.gen_df() return self._df T = tp.TypeVar(\"T\", bound=BaseModel)",
"= self.gen_df() return self._df T = tp.TypeVar(\"T\", bound=BaseModel) class BaseModelSequence(tp.Generic[T], BaseModelDf): __root__: tp.Sequence[T]",
"gen_df(self) -> pd.DataFrame: return pd.DataFrame.from_dict(self.dict().get(\"__root__\"), orient=\"columns\") U = tp.TypeVar(\"U\", bound=BaseModelSequence) class BaseModelMapping(tp.Generic[U], BaseModelDf):",
"from __future__ import annotations import typing as tp from abc import ABC, abstractmethod",
"__iter__(self) -> tp.Iterator[T]: # type: ignore return iter(self.__root__) def gen_df(self) -> pd.DataFrame: return",
"@property def df(self) -> pd.DataFrame: if self._df is None: self._df = self.gen_df() return",
"index: int) -> T: \"\"\"Get single item from __root__ by idx.\"\"\" @tp.overload def",
"def __iter__(self) -> tp.Iterator[T]: # type: ignore return iter(self.__root__) def gen_df(self) -> pd.DataFrame:",
"of items from __root__ by idx.\"\"\" def __getitem__(self, index): return self.__root__[index] def __len__(self)",
"def __iter__(self) -> tp.Iterator[str]: # type: ignore return iter(self.__root__) def gen_df(self) -> pd.DataFrame:",
"idx.\"\"\" def __getitem__(self, index): return self.__root__[index] def __len__(self) -> int: return len(self.__root__) def",
"index: str) -> U: return self.__root__[index] def __len__(self) -> int: return len(self.__root__) def",
"= PrivateAttr(default=None) @abstractmethod def gen_df(self) -> pd.DataFrame: ... @property def df(self) -> pd.DataFrame:",
"slice) -> tp.Sequence[T]: \"\"\"Get slice of items from __root__ by idx.\"\"\" def __getitem__(self,",
"class BaseModelSequence(tp.Generic[T], BaseModelDf): __root__: tp.Sequence[T] @tp.overload def __getitem__(self, index: int) -> T: \"\"\"Get",
"-> datetime: return self._created_at class BaseModelDf(BaseModel, ABC): _df: tp.Optional[pd.DataFrame] = PrivateAttr(default=None) @abstractmethod def",
"df(self) -> pd.DataFrame: if self._df is None: self._df = self.gen_df() return self._df T",
"<filename>pstock/base.py from __future__ import annotations import typing as tp from abc import ABC,",
"ABC, abstractmethod from datetime import datetime import pandas as pd import pendulum from",
"datetime import datetime import pandas as pd import pendulum from pydantic import BaseModel",
"return self._df T = tp.TypeVar(\"T\", bound=BaseModel) class BaseModelSequence(tp.Generic[T], BaseModelDf): __root__: tp.Sequence[T] @tp.overload def",
"= tp.TypeVar(\"T\", bound=BaseModel) class BaseModelSequence(tp.Generic[T], BaseModelDf): __root__: tp.Sequence[T] @tp.overload def __getitem__(self, index: int)",
"def df(self) -> pd.DataFrame: if self._df is None: self._df = self.gen_df() return self._df",
"from datetime import datetime import pandas as pd import pendulum from pydantic import",
"dfs = zip(*[(key, value.df) for key, value in self.__root__.items()]) return pd.concat(dfs, axis=1, keys=keys)",
"BaseModelDf): __root__: tp.Mapping[str, U] def __getitem__(self, index: str) -> U: return self.__root__[index] def",
"-> int: return len(self.__root__) def __iter__(self) -> tp.Iterator[T]: # type: ignore return iter(self.__root__)",
"__root__: tp.Sequence[T] @tp.overload def __getitem__(self, index: int) -> T: \"\"\"Get single item from",
"def gen_df(self) -> pd.DataFrame: keys, dfs = zip(*[(key, value.df) for key, value in",
"def __getitem__(self, index: str) -> U: return self.__root__[index] def __len__(self) -> int: return",
"from __root__ by idx.\"\"\" @tp.overload def __getitem__(self, index: slice) -> tp.Sequence[T]: \"\"\"Get slice",
"tp.Sequence[T]: \"\"\"Get slice of items from __root__ by idx.\"\"\" def __getitem__(self, index): return",
"class BaseModelDf(BaseModel, ABC): _df: tp.Optional[pd.DataFrame] = PrivateAttr(default=None) @abstractmethod def gen_df(self) -> pd.DataFrame: ...",
"T: \"\"\"Get single item from __root__ by idx.\"\"\" @tp.overload def __getitem__(self, index: slice)",
"BaseModel as _BaseModel from pydantic import PrivateAttr class BaseModel(_BaseModel): _created_at: datetime = PrivateAttr(default_factory=pendulum.now)",
"_BaseModel from pydantic import PrivateAttr class BaseModel(_BaseModel): _created_at: datetime = PrivateAttr(default_factory=pendulum.now) @property def",
"def created_at(self) -> datetime: return self._created_at class BaseModelDf(BaseModel, ABC): _df: tp.Optional[pd.DataFrame] = PrivateAttr(default=None)",
"created_at(self) -> datetime: return self._created_at class BaseModelDf(BaseModel, ABC): _df: tp.Optional[pd.DataFrame] = PrivateAttr(default=None) @abstractmethod",
"tp.Mapping[str, U] def __getitem__(self, index: str) -> U: return self.__root__[index] def __len__(self) ->",
"BaseModelDf): __root__: tp.Sequence[T] @tp.overload def __getitem__(self, index: int) -> T: \"\"\"Get single item",
"@abstractmethod def gen_df(self) -> pd.DataFrame: ... @property def df(self) -> pd.DataFrame: if self._df",
"pendulum from pydantic import BaseModel as _BaseModel from pydantic import PrivateAttr class BaseModel(_BaseModel):",
"ignore return iter(self.__root__) def gen_df(self) -> pd.DataFrame: return pd.DataFrame.from_dict(self.dict().get(\"__root__\"), orient=\"columns\") U = tp.TypeVar(\"U\",",
"PrivateAttr class BaseModel(_BaseModel): _created_at: datetime = PrivateAttr(default_factory=pendulum.now) @property def created_at(self) -> datetime: return",
"typing as tp from abc import ABC, abstractmethod from datetime import datetime import",
"# type: ignore return iter(self.__root__) def gen_df(self) -> pd.DataFrame: keys, dfs = zip(*[(key,",
"pd.DataFrame: ... @property def df(self) -> pd.DataFrame: if self._df is None: self._df =",
"import typing as tp from abc import ABC, abstractmethod from datetime import datetime",
"pydantic import PrivateAttr class BaseModel(_BaseModel): _created_at: datetime = PrivateAttr(default_factory=pendulum.now) @property def created_at(self) ->",
"tp.Sequence[T] @tp.overload def __getitem__(self, index: int) -> T: \"\"\"Get single item from __root__",
"-> pd.DataFrame: return pd.DataFrame.from_dict(self.dict().get(\"__root__\"), orient=\"columns\") U = tp.TypeVar(\"U\", bound=BaseModelSequence) class BaseModelMapping(tp.Generic[U], BaseModelDf): __root__:",
"keys, dfs = zip(*[(key, value.df) for key, value in self.__root__.items()]) return pd.concat(dfs, axis=1,",
"self.gen_df() return self._df T = tp.TypeVar(\"T\", bound=BaseModel) class BaseModelSequence(tp.Generic[T], BaseModelDf): __root__: tp.Sequence[T] @tp.overload",
"ignore return iter(self.__root__) def gen_df(self) -> pd.DataFrame: keys, dfs = zip(*[(key, value.df) for",
"-> pd.DataFrame: ... @property def df(self) -> pd.DataFrame: if self._df is None: self._df",
"PrivateAttr(default=None) @abstractmethod def gen_df(self) -> pd.DataFrame: ... @property def df(self) -> pd.DataFrame: if",
"len(self.__root__) def __iter__(self) -> tp.Iterator[T]: # type: ignore return iter(self.__root__) def gen_df(self) ->",
"as pd import pendulum from pydantic import BaseModel as _BaseModel from pydantic import",
"_df: tp.Optional[pd.DataFrame] = PrivateAttr(default=None) @abstractmethod def gen_df(self) -> pd.DataFrame: ... @property def df(self)",
"import BaseModel as _BaseModel from pydantic import PrivateAttr class BaseModel(_BaseModel): _created_at: datetime =",
"index): return self.__root__[index] def __len__(self) -> int: return len(self.__root__) def __iter__(self) -> tp.Iterator[T]:",
"pd.DataFrame.from_dict(self.dict().get(\"__root__\"), orient=\"columns\") U = tp.TypeVar(\"U\", bound=BaseModelSequence) class BaseModelMapping(tp.Generic[U], BaseModelDf): __root__: tp.Mapping[str, U] def",
"as _BaseModel from pydantic import PrivateAttr class BaseModel(_BaseModel): _created_at: datetime = PrivateAttr(default_factory=pendulum.now) @property",
"import PrivateAttr class BaseModel(_BaseModel): _created_at: datetime = PrivateAttr(default_factory=pendulum.now) @property def created_at(self) -> datetime:",
"BaseModelSequence(tp.Generic[T], BaseModelDf): __root__: tp.Sequence[T] @tp.overload def __getitem__(self, index: int) -> T: \"\"\"Get single",
"pydantic import BaseModel as _BaseModel from pydantic import PrivateAttr class BaseModel(_BaseModel): _created_at: datetime",
"BaseModelDf(BaseModel, ABC): _df: tp.Optional[pd.DataFrame] = PrivateAttr(default=None) @abstractmethod def gen_df(self) -> pd.DataFrame: ... @property",
"def __getitem__(self, index: int) -> T: \"\"\"Get single item from __root__ by idx.\"\"\"",
"-> tp.Iterator[T]: # type: ignore return iter(self.__root__) def gen_df(self) -> pd.DataFrame: return pd.DataFrame.from_dict(self.dict().get(\"__root__\"),",
"import pendulum from pydantic import BaseModel as _BaseModel from pydantic import PrivateAttr class",
"ABC): _df: tp.Optional[pd.DataFrame] = PrivateAttr(default=None) @abstractmethod def gen_df(self) -> pd.DataFrame: ... @property def",
"class BaseModel(_BaseModel): _created_at: datetime = PrivateAttr(default_factory=pendulum.now) @property def created_at(self) -> datetime: return self._created_at",
"single item from __root__ by idx.\"\"\" @tp.overload def __getitem__(self, index: slice) -> tp.Sequence[T]:",
"index: slice) -> tp.Sequence[T]: \"\"\"Get slice of items from __root__ by idx.\"\"\" def",
"__len__(self) -> int: return len(self.__root__) def __iter__(self) -> tp.Iterator[str]: # type: ignore return",
"... @property def df(self) -> pd.DataFrame: if self._df is None: self._df = self.gen_df()",
"import pandas as pd import pendulum from pydantic import BaseModel as _BaseModel from",
"-> pd.DataFrame: if self._df is None: self._df = self.gen_df() return self._df T =",
"str) -> U: return self.__root__[index] def __len__(self) -> int: return len(self.__root__) def __iter__(self)",
"def __len__(self) -> int: return len(self.__root__) def __iter__(self) -> tp.Iterator[T]: # type: ignore",
"int: return len(self.__root__) def __iter__(self) -> tp.Iterator[T]: # type: ignore return iter(self.__root__) def",
"from pydantic import BaseModel as _BaseModel from pydantic import PrivateAttr class BaseModel(_BaseModel): _created_at:",
"iter(self.__root__) def gen_df(self) -> pd.DataFrame: keys, dfs = zip(*[(key, value.df) for key, value",
"U = tp.TypeVar(\"U\", bound=BaseModelSequence) class BaseModelMapping(tp.Generic[U], BaseModelDf): __root__: tp.Mapping[str, U] def __getitem__(self, index:",
"PrivateAttr(default_factory=pendulum.now) @property def created_at(self) -> datetime: return self._created_at class BaseModelDf(BaseModel, ABC): _df: tp.Optional[pd.DataFrame]",
"__getitem__(self, index: int) -> T: \"\"\"Get single item from __root__ by idx.\"\"\" @tp.overload",
"int) -> T: \"\"\"Get single item from __root__ by idx.\"\"\" @tp.overload def __getitem__(self,",
"datetime import pandas as pd import pendulum from pydantic import BaseModel as _BaseModel",
"bound=BaseModel) class BaseModelSequence(tp.Generic[T], BaseModelDf): __root__: tp.Sequence[T] @tp.overload def __getitem__(self, index: int) -> T:",
"from pydantic import PrivateAttr class BaseModel(_BaseModel): _created_at: datetime = PrivateAttr(default_factory=pendulum.now) @property def created_at(self)"
] |
[
"import VOAWithIncomeReportRecord from finicityapi.models.prequalification_report_record import PrequalificationReportRecord from finicityapi.models.pay_statement_report_record import PayStatementReportRecord from finicityapi.models.generate_connect_email_response_multiple_borrowers import",
"Login Accounts\" This service is to migrate accounts from legacy FI to new",
"{ 'customerId': customer_id, 'institutionLoginId': institution_login_id, 'newInstitutionId': new_institution_id }) _query_builder = Configuration.get_base_uri() _query_builder +=",
"a list of permissible purposes for retrieving a report. Args: customer_id (long|int): Finicity’s",
"APIHelper.json_deserialize(_context.response.raw_body, TransactionsReportRecord.from_dictionary) def get_app_registration_status_v_1(self): \"\"\"Does a GET request to /aggregation/v1/partners/applications. Get the status",
"completing the Connect flow. It is best to use the documentation for the",
"the documentation here is a list of all the possible parameters you can",
"application/xml content_type (string): application/json, application/xml body (AddCustomerRequest): The Fields For The New Customer",
"# Prepare query URL _url_path = '/connect/v1/send/email' _query_builder = Configuration.get_base_uri() _query_builder += _url_path",
"you have generated the link it will only last until the authentication token",
"APIException: When an error occurs while fetching the data from the remote API.",
"data from the remote API. This exception includes the HTTP Response code, an",
"was received in the request. \"\"\" # Validate required parameters self.validate_parameters(content_type=content_type, accept=accept, body=body)",
"{ 'Finicity-App-Key': Configuration.finicity_app_key, 'Content-Type': content_type, 'Accept': accept } # Prepare and execute request",
"Validate required parameters self.validate_parameters(customer_id=customer_id, report_id=report_id, accept=accept, content_type=content_type) # Prepare query URL _url_path =",
"32 characters) report_id (string): Finicity’s ID of the report accept (string): Replace 'json'",
"_context) self.validate_response(_context) # Return appropriate type return APIHelper.json_deserialize(_context.response.raw_body, VOAWithIncomeReportRecord.from_dictionary) def get_prequalification_voa_report_by_customer(self, customer_id, report_id,",
"token when you generate a Connect link, to guarantee a full two hour",
"to access FI's with OAuth connections. Returns: AppStatusesV1: Response from the API. Raises:",
"return APIHelper.json_deserialize(_context.response.raw_body, VOAWithIncomeReportRecord.from_dictionary) def get_voa_with_income_report_by_customer(self, customer_id, report_id, accept, content_type, on_behalf_of=None, purpose=None): \"\"\"Does a",
"need. Once you have generated the link it will only last until the",
"for retrieving a report. Args: customer_id (long|int): Finicity’s ID of the customer report_id",
"finicityapi.models.statement_report_record import StatementReportRecord from finicityapi.exceptions.error_1_error_exception import Error1ErrorException class DeprecatedController(BaseController): \"\"\"A Controller to access",
"self.validate_response(_context) # Return appropriate type return APIHelper.json_deserialize(_context.response.raw_body, GenerateConnectURLResponse.from_dictionary) def generate_connect_url_fix(self, accept, body): \"\"\"Does",
"GenerateConnectURLResponse from finicityapi.models.customer_accounts import CustomerAccounts from finicityapi.models.auditable_report import AuditableReport from finicityapi.models.add_customer_response import AddCustomerResponse",
"for the institutionLoginId of accounts institution_login_id (long|int): Finicity's institutionLoginId for the set of",
"GenerateConnectEmailResponseMultipleBorrowers: Response from the API. Raises: APIException: When an error occurs while fetching",
"to /connect/v1/generate. No matter how you plan on implementing Finicity Connect, you’ll need",
"# Return appropriate type return APIHelper.json_deserialize(_context.response.raw_body, PayStatementReportRecord.from_dictionary) def add_customer_v_1(self, accept, content_type, body): \"\"\"Does",
"Connect URL (Lending) for additional details on a non email implementation. Args: accept",
"+= _url_path _query_parameters = { 'onBehalfOf': on_behalf_of, 'purpose': purpose } _query_builder = APIHelper.append_url_with_query_parameters(_query_builder,",
"from finicityapi.models.voie_paystub_with_txverify_report_record import VOIEPaystubWithTxverifyReportRecord from finicityapi.models.voi_report_record import VOIReportRecord from finicityapi.models.voa_with_income_report_record import VOAWithIncomeReportRecord from",
"happen once the customer accounts and transaction data are gathered. Several Finicity products",
"also corresponds to the report that will be run upon completing the Connect",
"_url_path = '/aggregation/v1/customers/testing' _query_builder = Configuration.get_base_uri() _query_builder += _url_path _query_url = APIHelper.clean_url(_query_builder) #",
"APIHelper.json_deserialize(_context.response.raw_body, VOAWithIncomeReportRecord.from_dictionary) def get_voa_with_income_report_by_customer(self, customer_id, report_id, accept, content_type, on_behalf_of=None, purpose=None): \"\"\"Does a GET",
"application/xml accept (string): application/json, application/xml body (AddCustomerRequest): The Fields For The New Testing",
"Codes for a list of permissible purposes for retrieving a report. Args: consumer_id",
"for the following types...... - ach - aggregation Args: accept (string): application/json, application/xml",
"appropriate type return APIHelper.json_deserialize(_context.response.raw_body, GenerateConnectEmailResponseMultipleBorrowers.from_dictionary) def get_transactions_report_by_customer(self, customer_id, report_id, accept, content_type, on_behalf_of=None, purpose=None):",
"APIHelper.json_deserialize(_context.response.raw_body, GenerateConnectEmailResponseMultipleBorrowers.from_dictionary) def get_transactions_report_by_customer(self, customer_id, report_id, accept, content_type, on_behalf_of=None, purpose=None): \"\"\"Does a GET",
"was received in the request. \"\"\" # Validate required parameters self.validate_parameters(accept=accept, content_type=content_type, body=body)",
"and execute request _request = self.http_client.get(_query_url, headers=_headers) CustomHeaderAuth.apply(_request) _context = self.execute_request(_request) # Endpoint",
"retrieving this report. Returns: VOAReportRecord: Response from the API. OK Raises: APIException: When",
"type also corresponds to the report that will be run upon completing the",
"send_connect_email(self, accept, body): \"\"\"Does a POST request to /connect/v1/send/email. A connect email sends",
"API. default response Raises: APIException: When an error occurs while fetching the data",
"_headers = { 'Finicity-App-Key': Configuration.finicity_app_key, 'Accept': accept, 'Content-Type': content_type } # Prepare and",
"generated by calling one of the Generate Report services. The report's status field",
"This documentation gives the applicable implementation details for the following types...... - voa",
"one or more real-world accounts. This is a billable customer. This service is",
"StatementReportRecord: Response from the API. OK Raises: APIException: When an error occurs while",
"the link it will only last until the authentication token under which it",
"Expected body to be sent with the request Returns: GenerateConnectURLResponse: Response from the",
"type return APIHelper.json_deserialize(_context.response.raw_body, VOAReportRecord.from_dictionary) def get_voie_txverify_report_by_consumer(self, consumer_id, report_id, accept, content_type, on_behalf_of=None, purpose=None): \"\"\"Does",
"GenerateConnectEmailResponseMultipleBorrowers.from_dictionary) def get_transactions_report_by_customer(self, customer_id, report_id, accept, content_type, on_behalf_of=None, purpose=None): \"\"\"Does a GET request",
"generate_connect_url_lending(self, accept, body): \"\"\"Does a POST request to /connect/v1/generate. No matter how you",
"implementing Finicity Connect, you’ll need to generate and retrieve a Finicity Connect Link.",
"a POST request to /connect/v1/generate. No matter how you plan on implementing Finicity",
"(string): Replace 'json' with 'xml' if preferred on_behalf_of (string, optional): The name of",
"following types...... - lite Args: accept (string): application/json, application/xml body (GenerateConnectURLRequestLite): Expected body",
"voahistory - voi - voieTxVerify - voieStatement - payStatement - assetSummary - preQualVoa",
"report. Returns: StatementReportRecord: Response from the API. OK Raises: APIException: When an error",
"Generate Finicity Connect URL (Data and Payments) Generate Finicity Connect URL (Lending) Generate",
"the reason for retrieving this report. Returns: PayStatementReportRecord: Response from the API. OK",
"contain a link to the connect flow. You will need to specify what",
"type return APIHelper.json_deserialize(_context.response.raw_body, GenerateConnectURLResponse.from_dictionary) def generate_connect_url_fix(self, accept, body): \"\"\"Does a POST request to",
"application/xml body (GenerateConnectURLRequestLending): Expected body to be sent with the request Returns: GenerateConnectURLResponse:",
"specifying the reason for retrieving this report. Returns: StatementReportRecord: Response from the API.",
"OAuth FI. A successful API response will return a list of accounts for",
"authentication token. We recommend generating a new authentication token when you generate a",
"'xml' if preferred content_type (string): Replace 'json' with 'xml' if preferred on_behalf_of (string,",
"400: raise Error1ErrorException('Bad Request', _context) self.validate_response(_context) # Return appropriate type return APIHelper.json_deserialize(_context.response.raw_body, AuditableReport.from_dictionary)",
"Expected body to be sent with the request Returns: GenerateConnectEmailResponseMultipleBorrowers: Response from the",
"applicable implementation details for the following types...... - lite Args: accept (string): application/json,",
"report_id (string): Finicity’s ID of the report (UUID with max length 32 characters)",
"in a paid plan will return HTTP 429 (Too Many Requests). Args: accept",
"as where to specify what type of Finicity Connect you need. Once you",
"of permissible purposes for retrieving a report. Args: customer_id (long|int): Finicity’s ID of",
"_headers = { 'Finicity-App-Key': Configuration.finicity_app_key, 'Content-Type': content_type, 'Accept': accept } # Prepare and",
"expires. After that you will need to regenerate the Connect link under a",
"be run upon completing the Connect flow. For Send Connect Email service it",
"additional details on a non email implementation. Args: accept (string): application/json body (GenerateConnectEmailRequest):",
"Report services. The report's status field will contain inProgress, failure, or success. If",
"= { 'content-type': 'application/json; charset=utf-8', 'Finicity-App-Key': Configuration.finicity_app_key, 'Accept': accept } # Prepare and",
"# Validate required parameters self.validate_parameters(content_type=content_type, accept=accept, body=body) # Prepare query URL _url_path =",
"Prepare headers _headers = { 'Finicity-App-Key': Configuration.finicity_app_key, 'Content-Type': content_type, 'Accept': accept } #",
"self.validate_response(_context) # Return appropriate type return APIHelper.json_deserialize(_context.response.raw_body, AuditableReport.from_dictionary) def add_testing_customer_v_1(self, content_type, accept, body):",
"the applicable implementation details for the following types...... - fix Args: accept (string):",
"_url_path = '/aggregation/v1/partners/applications' _query_builder = Configuration.get_base_uri() _query_builder += _url_path _query_url = APIHelper.clean_url(_query_builder) #",
"otherwise specified. See the specific documentation for the types to see more details",
"registration to access FI's with OAuth connections. Returns: AppStatusesV1: Response from the API.",
"accept, 'Content-Type': content_type } # Prepare and execute request _request = self.http_client.get(_query_url, headers=_headers)",
"version 2 Enroll an active customer, which is the actual owner of one",
"Response from the API. default response Raises: APIException: When an error occurs while",
"corresponds to the report that will be run upon completing the Connect flow.",
"Get a report that has been generated by calling one of the Generate",
"owner of one or more real-world accounts. This is a billable customer. This",
"Return appropriate type return APIHelper.json_deserialize(_context.response.raw_body, GenerateConnectURLResponse.from_dictionary) def generate_connect_url_fix(self, accept, body): \"\"\"Does a POST",
"type return APIHelper.json_deserialize(_context.response.raw_body, GenerateConnectURLResponse.from_dictionary) def send_connect_email(self, accept, body): \"\"\"Does a POST request to",
"of the entity you are retrieving the report on behalf of. purpose (string,",
"a GET request to /decisioning/v1/consumers/{consumerId}/reports/{reportId}. Get a report that has been generated by",
"generated the link it will only last until the authentication token under which",
"body=body) # Prepare query URL _url_path = '/aggregation/v1/customers/active' _query_builder = Configuration.get_base_uri() _query_builder +=",
"GenerateConnectURLResponse.from_dictionary) def generate_connect_url_fix(self, accept, body): \"\"\"Does a POST request to /connect/v1/generate. No matter",
"inProgress, failure, or success. If the status shows inProgress, the client app should",
"get_prequalification_voa_report_by_customer(self, customer_id, report_id, accept, content_type, on_behalf_of=None, purpose=None): \"\"\"Does a GET request to /decisioning/v1/customers/{customerId}/reports/{reportId}.",
"more real-world accounts. This is a billable customer. This service is not available",
"upon completing the Connect flow. For Send Connect Email service it does not",
"Send Connect Email service it does not support the types aggregation, lite and",
"migrate accounts from legacy FI to new OAuth FI. A successful API response",
"report. Returns: VOAReportRecord: Response from the API. OK Raises: APIException: When an error",
"'/aggregation/v1/partners/applications' _query_builder = Configuration.get_base_uri() _query_builder += _url_path _query_url = APIHelper.clean_url(_query_builder) # Prepare headers",
"# Prepare query URL _url_path = '/decisioning/v1/customers/{customerId}/reports/{reportId}' _url_path = APIHelper.append_url_with_template_parameters(_url_path, { 'customerId': customer_id,",
"Error1ErrorException('Bad Request', _context) self.validate_response(_context) # Return appropriate type return APIHelper.json_deserialize(_context.response.raw_body, VOAWithIncomeReportRecord.from_dictionary) def get_prequalification_voa_report_by_customer(self,",
"JSON or XML content_type (string): JSON or XML on_behalf_of (string, optional): The name",
"appropriate type return APIHelper.json_deserialize(_context.response.raw_body, GenerateConnectURLResponse.from_dictionary) def generate_connect_url_fix(self, accept, body): \"\"\"Does a POST request",
"only register accounts with FinBank institutions. Args: content_type (string): application/json, application/xml accept (string):",
"their own type of Connect. The Connect type is controlled by the “type”",
"not available from the Test Drive. Calls to this service before enrolling in",
"2-digit code from Permissible Purpose Codes, specifying the reason for retrieving this report.",
"'/decisioning/v1/customers/{customerId}/reports/{reportId}' _url_path = APIHelper.append_url_with_template_parameters(_url_path, { 'customerId': customer_id, 'reportId': report_id }) _query_builder = Configuration.get_base_uri()",
"in the finicityapi API.\"\"\" def generate_connect_url_all_types(self, accept, body): \"\"\"Does a POST request to",
"applicable implementation details for the following types...... - voa - voahistory - voi",
"Request', _context) self.validate_response(_context) # Return appropriate type return APIHelper.json_deserialize(_context.response.raw_body, AuditableReport.from_dictionary) def get_report_by_consumer(self, consumer_id,",
"Returns: GenerateConnectURLResponse: Response from the API. Raises: APIException: When an error occurs while",
"APIHelper.json_deserialize(_context.response.raw_body, PayStatementReportRecord.from_dictionary) def get_voa_report_by_customer(self, customer_id, report_id, accept, content_type, on_behalf_of=None, purpose=None): \"\"\"Does a GET",
"def get_app_registration_status_v_1(self): \"\"\"Does a GET request to /aggregation/v1/partners/applications. Get the status of your",
"to new OAuth FI. A successful API response will return a list of",
"institutionLoginId of accounts institution_login_id (long|int): Finicity's institutionLoginId for the set of accounts to",
"failure, or success. If the status shows inProgress, the client app should wait",
"POST request to /aggregation/v1/customers/testing. Enroll a testing customer. A testing customer may only",
"for additional details on a non email implementation. Args: accept (string): application/json body",
"appropriate type return APIHelper.json_deserialize(_context.response.raw_body, AuditableReport.from_dictionary) def add_testing_customer_v_1(self, content_type, accept, body): \"\"\"Does a POST",
"type of Finicity Connect you need. Once you have generated the link it",
"Fields For The New Customer Returns: AddCustomerResponse: Response from the API. default response",
"Error1ErrorException('Bad Request', _context) self.validate_response(_context) # Return appropriate type return APIHelper.json_deserialize(_context.response.raw_body, VOAWithIncomeReportRecord.from_dictionary) def get_voa_with_income_report_by_customer(self,",
"_headers = { 'content-type': 'application/json; charset=utf-8', 'Finicity-App-Key': Configuration.finicity_app_key, 'Accept': accept } # Prepare",
"self.validate_response(_context) # Return appropriate type return APIHelper.json_deserialize(_context.response.raw_body, StatementReportRecord.from_dictionary) def get_statement_report_by_consumer(self, consumer_id, report_id, accept,",
"of Finicity Connect you need. Once you have generated the link it will",
"application/json, application/xml body (GenerateConnectURLRequest): Expected body to be sent with the request Returns:",
"consumer_id, report_id, accept, content_type, on_behalf_of=None, purpose=None): \"\"\"Does a GET request to /decisioning/v1/consumers/{consumerId}/reports/{reportId}. Get",
"well as where to specify what type of Finicity Connect you need. Once",
"details for the following types...... - lite Args: accept (string): application/json, application/xml body",
"length 32 characters) report_id (string): Finicity’s ID of the report (UUID with max",
"be sent with the request Returns: GenerateConnectEmailResponseMultipleBorrowers: Response from the API. Raises: APIException:",
"remote API. This exception includes the HTTP Response code, an error message, and",
"received in the request. \"\"\" # Validate required parameters self.validate_parameters(customer_id=customer_id, institution_login_id=institution_login_id, new_institution_id=new_institution_id) #",
"paid plan will return HTTP 429 (Too Many Requests). Args: accept (string): application/json,",
"request. \"\"\" # Validate required parameters self.validate_parameters(accept=accept, content_type=content_type, body=body) # Prepare query URL",
"self.execute_request(_request) self.validate_response(_context) # Return appropriate type return APIHelper.json_deserialize(_context.response.raw_body, GenerateConnectURLResponse.from_dictionary) def generate_connect_url_lending(self, accept, body):",
"handling using HTTP status codes. if _context.response.status_code == 400: raise Error1ErrorException('Bad Request', _context)",
"that was received in the request. \"\"\" # Validate required parameters self.validate_parameters(accept=accept, content_type=content_type,",
"= self.execute_request(_request) self.validate_response(_context) # Return appropriate type return APIHelper.json_deserialize(_context.response.raw_body, CustomerAccounts.from_dictionary) def get_report_by_customer(self, customer_id,",
"query URL _url_path = '/decisioning/v1/consumers/{consumerId}/reports/{reportId}' _url_path = APIHelper.append_url_with_template_parameters(_url_path, { 'consumerId': consumer_id, 'reportId': report_id",
"appropriate type return APIHelper.json_deserialize(_context.response.raw_body, GenerateConnectURLResponse.from_dictionary) def generate_connect_url_lite(self, accept, body): \"\"\"Does a POST request",
"_url_path _query_url = APIHelper.clean_url(_query_builder) # Prepare headers _headers = { 'accept': 'application/json', 'Finicity-App-Key':",
"retrieving this report. Returns: AuditableReport: Response from the API. OK Raises: APIException: When",
"raise Error1ErrorException('Bad Request', _context) self.validate_response(_context) # Return appropriate type return APIHelper.json_deserialize(_context.response.raw_body, StatementReportRecord.from_dictionary) def",
"Prepare and execute request _request = self.http_client.get(_query_url, headers=_headers) CustomHeaderAuth.apply(_request) _context = self.execute_request(_request) self.validate_response(_context)",
"that will be run upon completing the Connect flow. It is best to",
"type return APIHelper.json_deserialize(_context.response.raw_body, GenerateConnectURLResponse.from_dictionary) def migrate_institution_login_accounts_v_1(self, customer_id, institution_login_id, new_institution_id): \"\"\"Does a PUT request",
"# Return appropriate type return APIHelper.json_deserialize(_context.response.raw_body, PrequalificationReportRecord.from_dictionary) def get_prequalification_report_by_consumer(self, consumer_id, report_id, accept, content_type,",
"to generate the Connect link as well as where to specify what type",
"a POST request to /aggregation/v1/customers/testing. Enroll a testing customer. A testing customer may",
"# Prepare query URL _url_path = '/aggregation/v1/partners/applications' _query_builder = Configuration.get_base_uri() _query_builder += _url_path",
"(string): Replace 'json' with 'xml' if preferred content_type (string): Replace 'json' with 'xml'",
"of your application registration to access FI's with OAuth connections. Returns: AppStatusesV1: Response",
"'Accept': accept, 'Content-Type': content_type } # Prepare and execute request _request = self.http_client.get(_query_url,",
"import VOIReportRecord from finicityapi.models.voa_with_income_report_record import VOAWithIncomeReportRecord from finicityapi.models.prequalification_report_record import PrequalificationReportRecord from finicityapi.models.pay_statement_report_record import",
"# Prepare and execute request _request = self.http_client.post(_query_url, headers=_headers, parameters=APIHelper.json_serialize(body)) CustomHeaderAuth.apply(_request) _context =",
"(string): Finicity’s ID of the report accept (string): Replace 'json' with 'xml' if",
"self.validate_parameters(content_type=content_type, accept=accept, body=body) # Prepare query URL _url_path = '/aggregation/v1/customers/testing' _query_builder = Configuration.get_base_uri()",
"finicityapi.models.generate_connect_url_response import GenerateConnectURLResponse from finicityapi.models.customer_accounts import CustomerAccounts from finicityapi.models.auditable_report import AuditableReport from finicityapi.models.add_customer_response",
"application/xml body (AddCustomerRequest): The Fields For The New Customer Returns: AddCustomerResponse: Response from",
"Returns: VOAReportRecord: Response from the API. OK Raises: APIException: When an error occurs",
"CustomerAccounts.from_dictionary) def get_report_by_customer(self, customer_id, report_id, accept, content_type, on_behalf_of=None, purpose=None): \"\"\"Does a GET request",
"APIHelper.clean_url(_query_builder) # Prepare headers _headers = { 'Finicity-App-Key': Configuration.finicity_app_key, 'Accept': accept, 'Content-Type': content_type",
"400: raise Error1ErrorException('Bad Request', _context) self.validate_response(_context) # Return appropriate type return APIHelper.json_deserialize(_context.response.raw_body, PayStatementReportRecord.from_dictionary)",
"/aggregation/v1/customers/{customerId}/institutionLogins/{institutionLoginId}/institutions/{newInstitutionId}. This service has been replaced by version 2 call now \"Migrate Institution",
"headers=_headers, parameters=APIHelper.json_serialize(body)) CustomHeaderAuth.apply(_request) _context = self.execute_request(_request) self.validate_response(_context) # Return appropriate type return APIHelper.json_deserialize(_context.response.raw_body,",
"which it was generated expires. After that you will need to regenerate the",
"- voahistory - voi - voieTxVerify - voieStatement - payStatement - assetSummary -",
"APIHelper.clean_url(_query_builder) # Prepare headers _headers = { 'accept': 'application/json', 'Finicity-App-Key': Configuration.finicity_app_key } #",
"body): \"\"\"Does a POST request to /connect/v1/generate. No matter how you plan on",
"generate a Connect link, to guarantee a full two hour life-span. Several Finicity",
"VOIReportRecord.from_dictionary) def get_voi_report_by_customer(self, customer_id, report_id, accept, content_type, on_behalf_of=None, purpose=None): \"\"\"Does a GET request",
"Prepare query URL _url_path = '/decisioning/v1/customers/{customerId}/reports/{reportId}' _url_path = APIHelper.append_url_with_template_parameters(_url_path, { 'customerId': customer_id, 'reportId':",
"# Return appropriate type return APIHelper.json_deserialize(_context.response.raw_body, TransactionsReportRecord.from_dictionary) def get_app_registration_status_v_1(self): \"\"\"Does a GET request",
"type return APIHelper.json_deserialize(_context.response.raw_body, VOAWithIncomeReportRecord.from_dictionary) def get_voa_with_income_report_by_customer(self, customer_id, report_id, accept, content_type, on_behalf_of=None, purpose=None): \"\"\"Does",
"content_type (string): Replace 'json' with 'xml' if preferred on_behalf_of (string, optional): The name",
"from finicityapi.models.generate_connect_url_response import GenerateConnectURLResponse from finicityapi.models.customer_accounts import CustomerAccounts from finicityapi.models.auditable_report import AuditableReport from",
"The Fields For The New Testing Customer Returns: AddCustomerResponse: Response from the API.",
"TransactionsReportRecord.from_dictionary) def get_app_registration_status_v_1(self): \"\"\"Does a GET request to /aggregation/v1/partners/applications. Get the status of",
"(long|int): Finicity’s ID of the customer for the institutionLoginId of accounts institution_login_id (long|int):",
"'xml' if preferred on_behalf_of (string, optional): The name of the entity you are",
"non email implementation. Args: accept (string): application/json body (GenerateConnectEmailRequest): Expected body to be",
"in the request. \"\"\" # Validate required parameters self.validate_parameters(content_type=content_type, accept=accept, body=body) # Prepare",
"or XML on_behalf_of (string, optional): The name of the entity you are retrieving",
"report. Returns: PayStatementReportRecord: Response from the API. OK Raises: APIException: When an error",
"the following types...... - ach - aggregation Args: accept (string): application/json, application/xml body",
"received in the request. \"\"\" # Validate required parameters self.validate_parameters(accept=accept, content_type=content_type, body=body) #",
"documentation for your use case....... Generate Finicity Connect URL (Data and Payments) Generate",
"# Prepare and execute request _request = self.http_client.put(_query_url, headers=_headers) CustomHeaderAuth.apply(_request) _context = self.execute_request(_request)",
"type return APIHelper.json_deserialize(_context.response.raw_body, AddCustomerResponse.from_dictionary) def generate_connect_url_data_and_payments_connect(self, accept, body): \"\"\"Does a POST request to",
"This documentation gives the applicable implementation details for the following types...... - fix",
"retrieve a Finicity Connect Link. You will need to specify what type of",
"headers _headers = { 'accept': 'application/json', 'Finicity-App-Key': Configuration.finicity_app_key } # Prepare and execute",
"to generate and retrieve a Finicity Connect Link. You will need to specify",
"OK Raises: APIException: When an error occurs while fetching the data from the",
"content_type=content_type) # Prepare query URL _url_path = '/decisioning/v1/consumers/{consumerId}/reports/{reportId}' _url_path = APIHelper.append_url_with_template_parameters(_url_path, { 'consumerId':",
"of accounts for the given institution login id with an http status code",
"(string): application/json, application/xml body (GenerateConnectURLRequestLending): Expected body to be sent with the request",
"gives the applicable implementation details for the following types...... - ach - aggregation",
"implementation. Args: accept (string): application/json body (GenerateConnectEmailRequest): Expected body to be sent with",
"the HTTP body that was received in the request. \"\"\" # Validate required",
"required parameters self.validate_parameters(accept=accept, body=body) # Prepare query URL _url_path = '/connect/v1/send/email' _query_builder =",
"def get_voa_report_by_consumer(self, consumer_id, report_id, accept, content_type, on_behalf_of=None, purpose=None): \"\"\"Does a GET request to",
"CustomerAccounts from finicityapi.models.auditable_report import AuditableReport from finicityapi.models.add_customer_response import AddCustomerResponse from finicityapi.models.voa_report_record import VOAReportRecord",
"generated expires. After that you will need to regenerate the Connect link under",
"\"\"\" # Validate required parameters self.validate_parameters(customer_id=customer_id, institution_login_id=institution_login_id, new_institution_id=new_institution_id) # Prepare query URL _url_path",
"customer. A testing customer may only register accounts with FinBank institutions. Args: content_type",
"specify what type of Finicity Connect you need. Once you have generated the",
"Prepare and execute request _request = self.http_client.put(_query_url, headers=_headers) CustomHeaderAuth.apply(_request) _context = self.execute_request(_request) self.validate_response(_context)",
"will need to specify what type of Finicity Connect you need depending on",
"be run upon completing the Connect flow. It is best to use the",
"report accept (string): Replace 'json' with 'xml' if preferred content_type (string): Replace 'json'",
"retrieving the report on behalf of. purpose (string, optional): 2-digit code from Permissible",
"of one or more real-world accounts. This is a billable customer. This service",
"Configuration from finicityapi.controllers.base_controller import BaseController from finicityapi.http.auth.custom_header_auth import CustomHeaderAuth from finicityapi.models.generate_connect_url_response import GenerateConnectURLResponse",
"self.http_client.put(_query_url, headers=_headers) CustomHeaderAuth.apply(_request) _context = self.execute_request(_request) self.validate_response(_context) # Return appropriate type return APIHelper.json_deserialize(_context.response.raw_body,",
"self.validate_response(_context) # Return appropriate type return APIHelper.json_deserialize(_context.response.raw_body, TransactionsReportRecord.from_dictionary) def get_transactions_report_by_consumer(self, consumer_id, report_id, accept,",
"controlled by the “type” code in the call. For lending, each type signifies",
"required parameters self.validate_parameters(accept=accept, body=body) # Prepare query URL _url_path = '/connect/v1/generate' _query_builder =",
"return APIHelper.json_deserialize(_context.response.raw_body, AuditableReport.from_dictionary) def add_testing_customer_v_1(self, content_type, accept, body): \"\"\"Does a POST request to",
"execute request _request = self.http_client.get(_query_url, headers=_headers) CustomHeaderAuth.apply(_request) _context = self.execute_request(_request) # Endpoint and",
"Request', _context) self.validate_response(_context) # Return appropriate type return APIHelper.json_deserialize(_context.response.raw_body, TransactionsReportRecord.from_dictionary) def get_transactions_report_by_consumer(self, consumer_id,",
"Prepare query URL _url_path = '/connect/v1/generate' _query_builder = Configuration.get_base_uri() _query_builder += _url_path _query_url",
"to /decisioning/v1/consumers/{consumerId}/reports/{reportId}. Get a report that has been generated by calling one of",
"the report is finished. See Permissible Purpose Codes for a list of permissible",
"documentation gives the applicable implementation details for the following types...... - lite Args:",
"appropriate type return APIHelper.json_deserialize(_context.response.raw_body, VOIReportRecord.from_dictionary) def get_voa_with_income_report_by_consumer(self, consumer_id, report_id, accept, content_type, on_behalf_of=None, purpose=None):",
"400: raise Error1ErrorException('Bad Request', _context) self.validate_response(_context) # Return appropriate type return APIHelper.json_deserialize(_context.response.raw_body, PrequalificationReportRecord.from_dictionary)",
"Purpose Codes, specifying the reason for retrieving this report. Returns: VOIEPaystubWithTxverifyReportRecord: Response from",
"accept (string): application/json, application/xml content_type (string): application/json, application/xml body (AddCustomerRequest): The Fields For",
"def migrate_institution_login_accounts_v_1(self, customer_id, institution_login_id, new_institution_id): \"\"\"Does a PUT request to /aggregation/v1/customers/{customerId}/institutionLogins/{institutionLoginId}/institutions/{newInstitutionId}. This service",
"the following types...... - lite Args: accept (string): application/json, application/xml body (GenerateConnectURLRequestLite): Expected",
"for the specific use case you are interested in as the documentation here",
"connect email sends an email to the customer which will contain a link",
"execute request _request = self.http_client.get(_query_url, headers=_headers) CustomHeaderAuth.apply(_request) _context = self.execute_request(_request) self.validate_response(_context) # Return",
"report's status field will contain inProgress, failure, or success. If the status shows",
"email sends an email to the customer which will contain a link to",
"Return appropriate type return APIHelper.json_deserialize(_context.response.raw_body, GenerateConnectURLResponse.from_dictionary) def generate_connect_url_lending(self, accept, body): \"\"\"Does a POST",
"def get_prequalification_report_by_consumer(self, consumer_id, report_id, accept, content_type, on_behalf_of=None, purpose=None): \"\"\"Does a GET request to",
"self.validate_response(_context) # Return appropriate type return APIHelper.json_deserialize(_context.response.raw_body, CustomerAccounts.from_dictionary) def get_report_by_customer(self, customer_id, report_id, accept,",
"as 200. Args: customer_id (long|int): Finicity’s ID of the customer for the institutionLoginId",
"of the customer for the institutionLoginId of accounts institution_login_id (long|int): Finicity's institutionLoginId for",
"gathered. Below you’ll find how to generate the Connect link as well as",
"more details on the flow. This documentation gives the applicable implementation details for",
"(GenerateConnectURLRequestLending): Expected body to be sent with the request Returns: GenerateConnectURLResponse: Response from",
"the following types...... - voa - voahistory - voi - voieTxVerify - voieStatement",
"return APIHelper.json_deserialize(_context.response.raw_body, TransactionsReportRecord.from_dictionary) def get_transactions_report_by_consumer(self, consumer_id, report_id, accept, content_type, on_behalf_of=None, purpose=None): \"\"\"Does a",
"from Permissible Purpose Codes, specifying the reason for retrieving this report. Returns: AuditableReport:",
"you generate a Connect link, to guarantee a full two hour life-span. Several",
"from finicityapi.models.add_customer_response import AddCustomerResponse from finicityapi.models.voa_report_record import VOAReportRecord from finicityapi.models.voie_paystub_with_txverify_report_record import VOIEPaystubWithTxverifyReportRecord from",
"does not support the types aggregation, lite and fix. See the endpoint Generate",
"def generate_connect_url_data_and_payments_connect(self, accept, body): \"\"\"Does a POST request to /connect/v1/generate. No matter how",
"AuditableReport: Response from the API. OK Raises: APIException: When an error occurs while",
"the request. \"\"\" # Validate required parameters self.validate_parameters(accept=accept, body=body) # Prepare query URL",
"a Connect link, to guarantee a full two hour life-span. Several Finicity products",
"API. OK Raises: APIException: When an error occurs while fetching the data from",
"connect flow unless otherwise specified. See the specific documentation for the types to",
"# Return appropriate type return APIHelper.json_deserialize(_context.response.raw_body, AddCustomerResponse.from_dictionary) def get_voa_report_by_consumer(self, consumer_id, report_id, accept, content_type,",
"list of permissible purposes for retrieving a report. Args: consumer_id (string): Finicity’s ID",
"find how to generate the Connect link as well as where to specify",
"to this service before enrolling in a paid plan will return HTTP 429",
"raise Error1ErrorException('Bad Request', _context) self.validate_response(_context) # Return appropriate type return APIHelper.json_deserialize(_context.response.raw_body, PrequalificationReportRecord.from_dictionary) def",
"Permissible Purpose Codes, specifying the reason for retrieving this report. Returns: VOAWithIncomeReportRecord: Response",
"accounts to be migrated new_institution_id (long|int): New OAuth FI ID where accounts will",
"specifying the reason for retrieving this report. Returns: PayStatementReportRecord: Response from the API.",
"of the Generate Report services. The report's status field will contain inProgress, failure,",
"Return appropriate type return APIHelper.json_deserialize(_context.response.raw_body, PrequalificationReportRecord.from_dictionary) def get_prequalification_report_by_consumer(self, consumer_id, report_id, accept, content_type, on_behalf_of=None,",
"_query_builder += _url_path _query_url = APIHelper.clean_url(_query_builder) # Prepare headers _headers = { 'Finicity-App-Key':",
"application/xml body (GenerateConnectURLRequest): Expected body to be sent with the request Returns: GenerateConnectURLResponse:",
"Connect link as well as where to specify what type of Finicity Connect",
"Test Drive. Calls to this service before enrolling in a paid plan will",
"self.validate_response(_context) # Return appropriate type return APIHelper.json_deserialize(_context.response.raw_body, VOAWithIncomeReportRecord.from_dictionary) def get_prequalification_voa_report_by_customer(self, customer_id, report_id, accept,",
"get_app_registration_status_v_1(self): \"\"\"Does a GET request to /aggregation/v1/partners/applications. Get the status of your application",
"import PayStatementReportRecord from finicityapi.models.generate_connect_email_response_multiple_borrowers import GenerateConnectEmailResponseMultipleBorrowers from finicityapi.models.transactions_report_record import TransactionsReportRecord from finicityapi.models.app_statuses_v_1 import",
"New Testing Customer Returns: AddCustomerResponse: Response from the API. default response Raises: APIException:",
"PrequalificationReportRecord from finicityapi.models.pay_statement_report_record import PayStatementReportRecord from finicityapi.models.generate_connect_email_response_multiple_borrowers import GenerateConnectEmailResponseMultipleBorrowers from finicityapi.models.transactions_report_record import TransactionsReportRecord",
"APIHelper.clean_url(_query_builder) # Prepare headers _headers = { 'Finicity-App-Key': Configuration.finicity_app_key, 'Content-Type': content_type, 'Accept': accept",
"APIHelper from finicityapi.configuration import Configuration from finicityapi.controllers.base_controller import BaseController from finicityapi.http.auth.custom_header_auth import CustomHeaderAuth",
"(string): application/json, application/xml body (GenerateConnectURLRequest): Expected body to be sent with the request",
"report_id, accept, content_type, on_behalf_of=None, purpose=None): \"\"\"Does a GET request to /decisioning/v1/customers/{customerId}/reports/{reportId}. Get a",
"ach - aggregation Args: accept (string): application/json, application/xml body (GenerateConnectURLRequestDataAndPayments): Expected body to",
"(string): application/json, application/xml body (GenerateConnectURLRequestFix): Expected body to be sent with the request",
"accept, body): \"\"\"Does a POST request to /connect/v1/send/email. A connect email sends an",
"Error1ErrorException('Bad Request', _context) self.validate_response(_context) # Return appropriate type return APIHelper.json_deserialize(_context.response.raw_body, AuditableReport.from_dictionary) def get_report_by_consumer(self,",
"'/aggregation/v1/customers/testing' _query_builder = Configuration.get_base_uri() _query_builder += _url_path _query_url = APIHelper.clean_url(_query_builder) # Prepare headers",
"Prepare query URL _url_path = '/aggregation/v1/customers/testing' _query_builder = Configuration.get_base_uri() _query_builder += _url_path _query_url",
"self.validate_parameters(accept=accept, content_type=content_type, body=body) # Prepare query URL _url_path = '/aggregation/v1/customers/active' _query_builder = Configuration.get_base_uri()",
"of the consumer (UUID with max length 32 characters) report_id (string): Finicity’s ID",
"Returns: AddCustomerResponse: Response from the API. default response Raises: APIException: When an error",
"with the request Returns: GenerateConnectURLResponse: Response from the API. Raises: APIException: When an",
"Request', _context) self.validate_response(_context) # Return appropriate type return APIHelper.json_deserialize(_context.response.raw_body, PayStatementReportRecord.from_dictionary) def add_customer_v_1(self, accept,",
"return APIHelper.json_deserialize(_context.response.raw_body, VOIEPaystubWithTxverifyReportRecord.from_dictionary) def get_pay_statement_extraction_by_customer(self, customer_id, report_id, accept, content_type, on_behalf_of=None, purpose=None): \"\"\"Does a",
"_context = self.execute_request(_request) self.validate_response(_context) # Return appropriate type return APIHelper.json_deserialize(_context.response.raw_body, GenerateConnectURLResponse.from_dictionary) def send_connect_email(self,",
"which will contain a link to the connect flow. You will need to",
"request. \"\"\" # Validate required parameters self.validate_parameters(customer_id=customer_id, report_id=report_id, accept=accept, content_type=content_type) # Prepare query",
"customer_id, 'institutionLoginId': institution_login_id, 'newInstitutionId': new_institution_id }) _query_builder = Configuration.get_base_uri() _query_builder += _url_path _query_url",
"app should wait 20 seconds and then call again to see if the",
"retrieving this report. Returns: StatementReportRecord: Response from the API. OK Raises: APIException: When",
"may only register accounts with FinBank institutions. Args: content_type (string): application/json, application/xml accept",
"execute request _request = self.http_client.post(_query_url, headers=_headers, parameters=APIHelper.json_serialize(body)) CustomHeaderAuth.apply(_request) _context = self.execute_request(_request) self.validate_response(_context) #",
"type is controlled by the “type” code in the call. Many times the",
"_query_parameters, Configuration.array_serialization) _query_url = APIHelper.clean_url(_query_builder) # Prepare headers _headers = { 'Finicity-App-Key': Configuration.finicity_app_key,",
"This documentation gives the applicable implementation details for the following types...... - lite",
"_request = self.http_client.put(_query_url, headers=_headers) CustomHeaderAuth.apply(_request) _context = self.execute_request(_request) self.validate_response(_context) # Return appropriate type",
"_query_builder += _url_path _query_parameters = { 'onBehalfOf': on_behalf_of, 'purpose': purpose } _query_builder =",
"accept } # Prepare and execute request _request = self.http_client.post(_query_url, headers=_headers, parameters=APIHelper.json_serialize(body)) CustomHeaderAuth.apply(_request)",
"# Prepare headers _headers = { 'content-type': 'application/json; charset=utf-8', 'Finicity-App-Key': Configuration.finicity_app_key, 'Accept': accept",
"'Finicity-App-Key': Configuration.finicity_app_key } # Prepare and execute request _request = self.http_client.get(_query_url, headers=_headers) CustomHeaderAuth.apply(_request)",
"def get_report_by_consumer(self, consumer_id, report_id, accept, content_type, on_behalf_of=None, purpose=None): \"\"\"Does a GET request to",
"# Prepare and execute request _request = self.http_client.get(_query_url, headers=_headers) CustomHeaderAuth.apply(_request) _context = self.execute_request(_request)",
"report. Args: consumer_id (string): Finicity’s ID of the consumer (UUID with max length",
"body=body) # Prepare query URL _url_path = '/connect/v1/generate' _query_builder = Configuration.get_base_uri() _query_builder +=",
"length 32 characters) accept (string): Replace 'json' with 'xml' if preferred content_type (string):",
"Purpose Codes, specifying the reason for retrieving this report. Returns: AuditableReport: Response from",
"return APIHelper.json_deserialize(_context.response.raw_body, VOIReportRecord.from_dictionary) def get_voi_report_by_customer(self, customer_id, report_id, accept, content_type, on_behalf_of=None, purpose=None): \"\"\"Does a",
"the type also corresponds to the report that will be run upon completing",
"Controller to access Endpoints in the finicityapi API.\"\"\" def generate_connect_url_all_types(self, accept, body): \"\"\"Does",
"applicable implementation details for the following types...... - fix Args: accept (string): application/json,",
"\"\"\"Does a GET request to /aggregation/v1/partners/applications. Get the status of your application registration",
"_url_path = '/connect/v1/generate' _query_builder = Configuration.get_base_uri() _query_builder += _url_path _query_url = APIHelper.clean_url(_query_builder) #",
"for the types to see more details on the flow. This documentation gives",
"type return APIHelper.json_deserialize(_context.response.raw_body, GenerateConnectEmailResponseMultipleBorrowers.from_dictionary) def get_transactions_report_by_customer(self, customer_id, report_id, accept, content_type, on_behalf_of=None, purpose=None): \"\"\"Does",
"the applicable implementation details for the following types...... - lite Args: accept (string):",
"= self.execute_request(_request) self.validate_response(_context) # Return appropriate type return APIHelper.json_deserialize(_context.response.raw_body, AppStatusesV1.from_dictionary) def get_statement_report_by_customer(self, customer_id,",
"Codes, specifying the reason for retrieving this report. Returns: VOAReportRecord: Response from the",
"Return appropriate type return APIHelper.json_deserialize(_context.response.raw_body, VOAReportRecord.from_dictionary) def get_voie_txverify_report_by_customer(self, customer_id, report_id, accept, content_type, on_behalf_of=None,",
"Many Requests). Args: accept (string): application/json, application/xml content_type (string): application/json, application/xml body (AddCustomerRequest):",
"'json' with 'xml' if preferred content_type (string): Replace 'json' with 'xml' if preferred",
"received in the request. \"\"\" # Validate required parameters self.validate_parameters(accept=accept, body=body) # Prepare",
"the request. \"\"\" # Validate required parameters self.validate_parameters(customer_id=customer_id, report_id=report_id, accept=accept, content_type=content_type) # Prepare",
"that you will need to regenerate the Connect link under a new authentication",
"from legacy FI to new OAuth FI. A successful API response will return",
"GenerateConnectURLResponse.from_dictionary) def generate_connect_url_lending(self, accept, body): \"\"\"Does a POST request to /connect/v1/generate. No matter",
"body that was received in the request. \"\"\" # Validate required parameters self.validate_parameters(content_type=content_type,",
"400: raise Error1ErrorException('Bad Request', _context) self.validate_response(_context) # Return appropriate type return APIHelper.json_deserialize(_context.response.raw_body, VOIReportRecord.from_dictionary)",
"will be run upon completing the Connect flow. For Send Connect Email service",
"have their own type of Connect. The Connect type is controlled by the",
"_context) self.validate_response(_context) # Return appropriate type return APIHelper.json_deserialize(_context.response.raw_body, PrequalificationReportRecord.from_dictionary) def get_prequalification_report_by_consumer(self, consumer_id, report_id,",
"Finicity Connect Link. You will need to specify what type of Finicity Connect",
"A connect email sends an email to the customer which will contain a",
"to see more details on the flow. This documentation gives the applicable implementation",
"generate_connect_url_all_types(self, accept, body): \"\"\"Does a POST request to /connect/v1/generate. No matter how you",
"TransactionsReportRecord from finicityapi.models.app_statuses_v_1 import AppStatusesV1 from finicityapi.models.statement_report_record import StatementReportRecord from finicityapi.exceptions.error_1_error_exception import Error1ErrorException",
"by the “type” code in the call. For lending, each type signifies a",
"while fetching the data from the remote API. This exception includes the HTTP",
"full two hour life-span. Several Finicity products utilize Finicity Connect, and most products",
"that was received in the request. \"\"\" # Validate required parameters self.validate_parameters(accept=accept, body=body)",
"a Finicity Connect Link. You will need to specify what type of Finicity",
"Returns: GenerateConnectEmailResponseMultipleBorrowers: Response from the API. Raises: APIException: When an error occurs while",
"message, and the HTTP body that was received in the request. \"\"\" #",
"Purpose Codes, specifying the reason for retrieving this report. Returns: VOAWithIncomeReportRecord: Response from",
"Generate Finicity Connect URL (Lending) Generate Finicity Connect URL (Lite) Generate Finicity Connect",
"import GenerateConnectEmailResponseMultipleBorrowers from finicityapi.models.transactions_report_record import TransactionsReportRecord from finicityapi.models.app_statuses_v_1 import AppStatusesV1 from finicityapi.models.statement_report_record import",
"body (AddCustomerRequest): The Fields For The New Testing Customer Returns: AddCustomerResponse: Response from",
"Returns: VOIReportRecord: Response from the API. OK Raises: APIException: When an error occurs",
"to migrate accounts from legacy FI to new OAuth FI. A successful API",
"customer for the institutionLoginId of accounts institution_login_id (long|int): Finicity's institutionLoginId for the set",
"applicable implementation details for the following types...... - ach - aggregation Args: accept",
"# Return appropriate type return APIHelper.json_deserialize(_context.response.raw_body, GenerateConnectURLResponse.from_dictionary) def generate_connect_url_lite(self, accept, body): \"\"\"Does a",
"characters) report_id (string): Finicity’s ID of the report accept (string): JSON or XML",
"report on behalf of. purpose (string, optional): 2-digit code from Permissible Purpose Codes,",
"was generated expires. After that you will need to regenerate the Connect link",
"execute request _request = self.http_client.put(_query_url, headers=_headers) CustomHeaderAuth.apply(_request) _context = self.execute_request(_request) self.validate_response(_context) # Return",
"to regenerate the Connect link under a new authentication token. We recommend generating",
"- lite Args: accept (string): application/json, application/xml body (GenerateConnectURLRequestLite): Expected body to be",
"Returns: PayStatementReportRecord: Response from the API. OK Raises: APIException: When an error occurs",
"of the connect flow unless otherwise specified. See the specific documentation for the",
"_context) self.validate_response(_context) # Return appropriate type return APIHelper.json_deserialize(_context.response.raw_body, StatementReportRecord.from_dictionary) def get_statement_report_by_consumer(self, consumer_id, report_id,",
"# Return appropriate type return APIHelper.json_deserialize(_context.response.raw_body, StatementReportRecord.from_dictionary) def get_statement_report_by_consumer(self, consumer_id, report_id, accept, content_type,",
"will return a list of accounts for the given institution login id with",
"the report (UUID with max length 32 characters) accept (string): Replace 'json' with",
"self.validate_response(_context) # Return appropriate type return APIHelper.json_deserialize(_context.response.raw_body, AuditableReport.from_dictionary) def get_report_by_consumer(self, consumer_id, report_id, accept,",
"CustomHeaderAuth.apply(_request) _context = self.execute_request(_request) self.validate_response(_context) # Return appropriate type return APIHelper.json_deserialize(_context.response.raw_body, GenerateConnectURLResponse.from_dictionary) def",
"request _request = self.http_client.get(_query_url, headers=_headers) CustomHeaderAuth.apply(_request) _context = self.execute_request(_request) self.validate_response(_context) # Return appropriate",
"Response from the API. OK Raises: APIException: When an error occurs while fetching",
"you plan on implementing Finicity Connect, you’ll need to generate and retrieve a",
"the report that will be run upon completing the Connect flow. It is",
"are retrieving the report on behalf of. purpose (string, optional): 2-digit code from",
"specify what type of Finicity Connect you need depending on what will happen",
"code in the call. For lending, each type signifies a report that will",
"# Return appropriate type return APIHelper.json_deserialize(_context.response.raw_body, TransactionsReportRecord.from_dictionary) def get_transactions_report_by_consumer(self, consumer_id, report_id, accept, content_type,",
"accept=accept, body=body) # Prepare query URL _url_path = '/aggregation/v1/customers/testing' _query_builder = Configuration.get_base_uri() _query_builder",
"from finicityapi.models.transactions_report_record import TransactionsReportRecord from finicityapi.models.app_statuses_v_1 import AppStatusesV1 from finicityapi.models.statement_report_record import StatementReportRecord from",
"link, to guarantee a full two hour life-span. Several Finicity products utilize Finicity",
"and execute request _request = self.http_client.get(_query_url, headers=_headers) CustomHeaderAuth.apply(_request) _context = self.execute_request(_request) self.validate_response(_context) #",
"Args: consumer_id (string): Finicity’s ID of the consumer (UUID with max length 32",
"which is the actual owner of one or more real-world accounts. This is",
"from finicityapi.configuration import Configuration from finicityapi.controllers.base_controller import BaseController from finicityapi.http.auth.custom_header_auth import CustomHeaderAuth from",
"the reason for retrieving this report. Returns: VOAWithIncomeReportRecord: Response from the API. OK",
"Finicity’s ID of the report accept (string): JSON or XML content_type (string): JSON",
"_context.response.status_code == 400: raise Error1ErrorException('Bad Request', _context) self.validate_response(_context) # Return appropriate type return",
"voieTxVerify - voieStatement - payStatement - assetSummary - preQualVoa Args: accept (string): application/json,",
"email implementation. Args: accept (string): application/json body (GenerateConnectEmailRequest): Expected body to be sent",
"documentation here is a list of all the possible parameters you can send",
"report_id }) _query_builder = Configuration.get_base_uri() _query_builder += _url_path _query_parameters = { 'onBehalfOf': on_behalf_of,",
"Prepare headers _headers = { 'content-type': 'application/json; charset=utf-8', 'Finicity-App-Key': Configuration.finicity_app_key, 'Accept': accept }",
"APIHelper.json_deserialize(_context.response.raw_body, CustomerAccounts.from_dictionary) def get_report_by_customer(self, customer_id, report_id, accept, content_type, on_behalf_of=None, purpose=None): \"\"\"Does a GET",
"See the specific documentation for the types to see more details on the",
"the types aggregation, lite and fix. See the endpoint Generate Finicity Connect URL",
"FI's with OAuth connections. Returns: AppStatusesV1: Response from the API. Raises: APIException: When",
"the applicable implementation details for the following types...... - voa - voahistory -",
"a GET request to /decisioning/v1/customers/{customerId}/reports/{reportId}. Get a report that has been generated by",
"Connect link, to guarantee a full two hour life-span. Several Finicity products utilize",
"reason for retrieving this report. Returns: PayStatementReportRecord: Response from the API. OK Raises:",
"appropriate type return APIHelper.json_deserialize(_context.response.raw_body, GenerateConnectURLResponse.from_dictionary) def migrate_institution_login_accounts_v_1(self, customer_id, institution_login_id, new_institution_id): \"\"\"Does a PUT",
"response Raises: APIException: When an error occurs while fetching the data from the",
"== 400: raise Error1ErrorException('Bad Request', _context) self.validate_response(_context) # Return appropriate type return APIHelper.json_deserialize(_context.response.raw_body,",
"return APIHelper.json_deserialize(_context.response.raw_body, VOIEPaystubWithTxverifyReportRecord.from_dictionary) def get_voi_report_by_consumer(self, consumer_id, report_id, accept, content_type, on_behalf_of=None, purpose=None): \"\"\"Does a",
"Validate required parameters self.validate_parameters(customer_id=customer_id, institution_login_id=institution_login_id, new_institution_id=new_institution_id) # Prepare query URL _url_path = '/aggregation/v1/customers/{customerId}/institutionLogins/{institutionLoginId}/institutions/{newInstitutionId}'",
"Finicity Connect URL (Lite) Generate Finicity Connect URL (Fix) Args: accept (string): application/json,",
"This documentation gives the applicable implementation details for the following types...... - ach",
"plan will return HTTP 429 (Too Many Requests). Args: accept (string): application/json, application/xml",
"(string): application/json, application/xml accept (string): application/json, application/xml body (AddCustomerRequest): The Fields For The",
"types...... - lite Args: accept (string): application/json, application/xml body (GenerateConnectURLRequestLite): Expected body to",
"# Prepare headers _headers = { 'Finicity-App-Key': Configuration.finicity_app_key, 'Accept': accept, 'Content-Type': content_type }",
"VOIReportRecord: Response from the API. OK Raises: APIException: When an error occurs while",
"Finicity’s ID of the consumer (UUID with max length 32 characters) report_id (string):",
"Purpose Codes, specifying the reason for retrieving this report. Returns: PrequalificationReportRecord: Response from",
"request to /connect/v1/send/email. A connect email sends an email to the customer which",
"self.validate_response(_context) # Return appropriate type return APIHelper.json_deserialize(_context.response.raw_body, VOIReportRecord.from_dictionary) def get_voi_report_by_customer(self, customer_id, report_id, accept,",
"legacy FI to new OAuth FI. A successful API response will return a",
"Validate required parameters self.validate_parameters(consumer_id=consumer_id, report_id=report_id, accept=accept, content_type=content_type) # Prepare query URL _url_path =",
"aggregation Args: accept (string): application/json, application/xml body (GenerateConnectURLRequestDataAndPayments): Expected body to be sent",
"return APIHelper.json_deserialize(_context.response.raw_body, VOIReportRecord.from_dictionary) def get_voa_with_income_report_by_consumer(self, consumer_id, report_id, accept, content_type, on_behalf_of=None, purpose=None): \"\"\"Does a",
"_query_builder += _url_path _query_url = APIHelper.clean_url(_query_builder) # Prepare headers _headers = { 'content-type':",
"CustomHeaderAuth from finicityapi.models.generate_connect_url_response import GenerateConnectURLResponse from finicityapi.models.customer_accounts import CustomerAccounts from finicityapi.models.auditable_report import AuditableReport",
"in the request. \"\"\" # Validate required parameters self.validate_parameters(customer_id=customer_id, institution_login_id=institution_login_id, new_institution_id=new_institution_id) # Prepare",
"testing customer. A testing customer may only register accounts with FinBank institutions. Args:",
"XML on_behalf_of (string, optional): The name of the entity you are retrieving the",
"a full two hour life-span. Several Finicity products utilize Finicity Connect, and most",
"When an error occurs while fetching the data from the remote API. This",
"For lending, each type signifies a report that will be generated as part",
"response will return a list of accounts for the given institution login id",
"-*- coding: utf-8 -*- from finicityapi.api_helper import APIHelper from finicityapi.configuration import Configuration from",
"= APIHelper.append_url_with_template_parameters(_url_path, { 'customerId': customer_id, 'institutionLoginId': institution_login_id, 'newInstitutionId': new_institution_id }) _query_builder = Configuration.get_base_uri()",
"call again to see if the report is finished. See Permissible Purpose Codes",
"content_type=content_type) # Prepare query URL _url_path = '/decisioning/v1/customers/{customerId}/reports/{reportId}' _url_path = APIHelper.append_url_with_template_parameters(_url_path, { 'customerId':",
"import AuditableReport from finicityapi.models.add_customer_response import AddCustomerResponse from finicityapi.models.voa_report_record import VOAReportRecord from finicityapi.models.voie_paystub_with_txverify_report_record import",
"= self.execute_request(_request) # Endpoint and global error handling using HTTP status codes. if",
"return APIHelper.json_deserialize(_context.response.raw_body, GenerateConnectURLResponse.from_dictionary) def migrate_institution_login_accounts_v_1(self, customer_id, institution_login_id, new_institution_id): \"\"\"Does a PUT request to",
"PayStatementReportRecord: Response from the API. OK Raises: APIException: When an error occurs while",
"Finicity Connect, and most products have their own type of Connect. The Connect",
"content_type (string): application/json, application/xml body (AddCustomerRequest): The Fields For The New Customer Returns:",
"Request', _context) self.validate_response(_context) # Return appropriate type return APIHelper.json_deserialize(_context.response.raw_body, VOAReportRecord.from_dictionary) def get_voie_txverify_report_by_consumer(self, consumer_id,",
"only last until the authentication token under which it was generated expires. After",
"Connect type is controlled by the “type” code in the call. See the",
"the documentation for the specific use case you are interested in as the",
"service is to migrate accounts from legacy FI to new OAuth FI. A",
"a link to the connect flow. You will need to specify what type",
"report_id, accept, content_type, on_behalf_of=None, purpose=None): \"\"\"Does a GET request to /decisioning/v1/consumers/{consumerId}/reports/{reportId}. Get a",
"a report that will be generated as part of the connect flow unless",
"Finicity Connect URL (Lending) Generate Finicity Connect URL (Lite) Generate Finicity Connect URL",
"the Test Drive. Calls to this service before enrolling in a paid plan",
"ID of the customer for the institutionLoginId of accounts institution_login_id (long|int): Finicity's institutionLoginId",
"with 'xml' if preferred content_type (string): Replace 'json' with 'xml' if preferred on_behalf_of",
"specifying the reason for retrieving this report. Returns: TransactionsReportRecord: Response from the API.",
"Configuration.finicity_app_key, 'Accept': accept, 'Content-Type': content_type } # Prepare and execute request _request =",
"report that will be run upon completing the Connect flow. It is best",
"= '/aggregation/v1/customers/{customerId}/institutionLogins/{institutionLoginId}/institutions/{newInstitutionId}' _url_path = APIHelper.append_url_with_template_parameters(_url_path, { 'customerId': customer_id, 'institutionLoginId': institution_login_id, 'newInstitutionId': new_institution_id })",
"parameters self.validate_parameters(content_type=content_type, accept=accept, body=body) # Prepare query URL _url_path = '/aggregation/v1/customers/testing' _query_builder =",
"\"\"\"A Controller to access Endpoints in the finicityapi API.\"\"\" def generate_connect_url_all_types(self, accept, body):",
"Return appropriate type return APIHelper.json_deserialize(_context.response.raw_body, PrequalificationReportRecord.from_dictionary) def get_pay_statement_by_consumer(self, consumer_id, report_id, accept, content_type, on_behalf_of=None,",
"Error1ErrorException('Bad Request', _context) self.validate_response(_context) # Return appropriate type return APIHelper.json_deserialize(_context.response.raw_body, TransactionsReportRecord.from_dictionary) def get_app_registration_status_v_1(self):",
"'reportId': report_id }) _query_builder = Configuration.get_base_uri() _query_builder += _url_path _query_parameters = { 'onBehalfOf':",
"APIHelper.json_deserialize(_context.response.raw_body, PayStatementReportRecord.from_dictionary) def add_customer_v_1(self, accept, content_type, body): \"\"\"Does a POST request to /aggregation/v1/customers/active.",
"Connect URL (Lending) Generate Finicity Connect URL (Lite) Generate Finicity Connect URL (Fix)",
"types...... - ach - aggregation Args: accept (string): application/json, application/xml body (GenerateConnectURLRequestDataAndPayments): Expected",
"type return APIHelper.json_deserialize(_context.response.raw_body, VOAWithIncomeReportRecord.from_dictionary) def get_prequalification_voa_report_by_customer(self, customer_id, report_id, accept, content_type, on_behalf_of=None, purpose=None): \"\"\"Does",
"from finicityapi.models.generate_connect_email_response_multiple_borrowers import GenerateConnectEmailResponseMultipleBorrowers from finicityapi.models.transactions_report_record import TransactionsReportRecord from finicityapi.models.app_statuses_v_1 import AppStatusesV1 from",
"HTTP 429 (Too Many Requests). Args: accept (string): application/json, application/xml content_type (string): application/json,",
"appropriate type return APIHelper.json_deserialize(_context.response.raw_body, StatementReportRecord.from_dictionary) def get_statement_report_by_consumer(self, consumer_id, report_id, accept, content_type, on_behalf_of=None, purpose=None):",
"characters) report_id (string): Finicity’s ID of the report accept (string): Replace 'json' with",
"you need depending on what will happen once the customer accounts and transaction",
"'Finicity-App-Key': Configuration.finicity_app_key, 'Accept': accept, 'Content-Type': content_type } # Prepare and execute request _request",
"_context) self.validate_response(_context) # Return appropriate type return APIHelper.json_deserialize(_context.response.raw_body, VOAWithIncomeReportRecord.from_dictionary) def get_voa_with_income_report_by_customer(self, customer_id, report_id,",
"self.execute_request(_request) self.validate_response(_context) # Return appropriate type return APIHelper.json_deserialize(_context.response.raw_body, AppStatusesV1.from_dictionary) def get_statement_report_by_customer(self, customer_id, report_id,",
"this report. Returns: VOIEPaystubWithTxverifyReportRecord: Response from the API. OK Raises: APIException: When an",
"in the request. \"\"\" # Prepare query URL _url_path = '/aggregation/v1/partners/applications' _query_builder =",
"what will happen once the customer accounts and transaction data are gathered. Below",
"specified. See the specific documentation for the types to see more details on",
"(long|int): Finicity's institutionLoginId for the set of accounts to be migrated new_institution_id (long|int):",
"the specific use case you are interested in as the documentation here is",
"= self.execute_request(_request) self.validate_response(_context) # Return appropriate type return APIHelper.json_deserialize(_context.response.raw_body, GenerateConnectURLResponse.from_dictionary) def generate_connect_url_fix(self, accept,",
"APIHelper.json_deserialize(_context.response.raw_body, AuditableReport.from_dictionary) def get_report_by_consumer(self, consumer_id, report_id, accept, content_type, on_behalf_of=None, purpose=None): \"\"\"Does a GET",
"the report that will be run upon completing the Connect flow. For Send",
"'customerId': customer_id, 'institutionLoginId': institution_login_id, 'newInstitutionId': new_institution_id }) _query_builder = Configuration.get_base_uri() _query_builder += _url_path",
"Args: accept (string): application/json, application/xml body (GenerateConnectURLRequestLite): Expected body to be sent with",
"max length 32 characters) report_id (string): Finicity’s ID of the report (UUID with",
"by version 2 call now \"Migrate Institution Login Accounts\" This service is to",
"= { 'Finicity-App-Key': Configuration.finicity_app_key, 'Content-Type': content_type, 'Accept': accept } # Prepare and execute",
"from Permissible Purpose Codes, specifying the reason for retrieving this report. Returns: PrequalificationReportRecord:",
"ID of the consumer (UUID with max length 32 characters) report_id (string): Finicity’s",
"will happen once the customer accounts and transaction data are gathered. Below you’ll",
"self.validate_response(_context) # Return appropriate type return APIHelper.json_deserialize(_context.response.raw_body, PayStatementReportRecord.from_dictionary) def get_voa_report_by_customer(self, customer_id, report_id, accept,",
"to specify what type of Finicity Connect you need. Once you have generated",
"for this endpoint depending on the use case. See the following more specific",
"URL _url_path = '/connect/v1/generate' _query_builder = Configuration.get_base_uri() _query_builder += _url_path _query_url = APIHelper.clean_url(_query_builder)",
"type return APIHelper.json_deserialize(_context.response.raw_body, AuditableReport.from_dictionary) def get_report_by_consumer(self, consumer_id, report_id, accept, content_type, on_behalf_of=None, purpose=None): \"\"\"Does",
"appropriate type return APIHelper.json_deserialize(_context.response.raw_body, GenerateConnectURLResponse.from_dictionary) def send_connect_email(self, accept, body): \"\"\"Does a POST request",
"a list of permissible purposes for retrieving a report. Args: consumer_id (string): Finicity’s",
"type signifies a report that will be generated as part of the connect",
"AppStatusesV1: Response from the API. Raises: APIException: When an error occurs while fetching",
"query URL _url_path = '/aggregation/v1/customers/testing' _query_builder = Configuration.get_base_uri() _query_builder += _url_path _query_url =",
"Return appropriate type return APIHelper.json_deserialize(_context.response.raw_body, VOIEPaystubWithTxverifyReportRecord.from_dictionary) def get_voi_report_by_consumer(self, consumer_id, report_id, accept, content_type, on_behalf_of=None,",
"accept (string): application/json, application/xml body (GenerateConnectURLRequest): Expected body to be sent with the",
"request to /decisioning/v1/consumers/{consumerId}/reports/{reportId}. Get a report that has been generated by calling one",
"was received in the request. \"\"\" # Validate required parameters self.validate_parameters(accept=accept, body=body) #",
"customer report_id (string): Finicity’s ID of the report (UUID with max length 32",
"parameters self.validate_parameters(accept=accept, body=body) # Prepare query URL _url_path = '/connect/v1/generate' _query_builder = Configuration.get_base_uri()",
"URL (Lending) for additional details on a non email implementation. Args: accept (string):",
"= self.execute_request(_request) self.validate_response(_context) # Return appropriate type return APIHelper.json_deserialize(_context.response.raw_body, GenerateConnectURLResponse.from_dictionary) def generate_connect_url_lite(self, accept,",
"Connect link under a new authentication token. We recommend generating a new authentication",
"Request', _context) self.validate_response(_context) # Return appropriate type return APIHelper.json_deserialize(_context.response.raw_body, VOAWithIncomeReportRecord.from_dictionary) def get_voa_with_income_report_by_customer(self, customer_id,",
"consumer_id (string): Finicity’s ID of the consumer (UUID with max length 32 characters)",
"max length 32 characters) accept (string): Replace 'json' with 'xml' if preferred content_type",
"# -*- coding: utf-8 -*- from finicityapi.api_helper import APIHelper from finicityapi.configuration import Configuration",
"request _request = self.http_client.get(_query_url, headers=_headers) CustomHeaderAuth.apply(_request) _context = self.execute_request(_request) # Endpoint and global",
"No matter how you plan on implementing Finicity Connect, you’ll need to generate",
"been replaced by version 2 call now \"Migrate Institution Login Accounts\" This service",
"on a non email implementation. Args: accept (string): application/json body (GenerateConnectEmailRequest): Expected body",
"= self.execute_request(_request) self.validate_response(_context) # Return appropriate type return APIHelper.json_deserialize(_context.response.raw_body, GenerateConnectURLResponse.from_dictionary) def generate_connect_url_lending(self, accept,",
"return APIHelper.json_deserialize(_context.response.raw_body, TransactionsReportRecord.from_dictionary) def get_app_registration_status_v_1(self): \"\"\"Does a GET request to /aggregation/v1/partners/applications. Get the",
"<reponame>monarchmoney/finicity-python # -*- coding: utf-8 -*- from finicityapi.api_helper import APIHelper from finicityapi.configuration import",
"was received in the request. \"\"\" # Validate required parameters self.validate_parameters(customer_id=customer_id, report_id=report_id, accept=accept,",
"body=body) # Prepare query URL _url_path = '/aggregation/v1/customers/testing' _query_builder = Configuration.get_base_uri() _query_builder +=",
"URL (Data and Payments) Generate Finicity Connect URL (Lending) Generate Finicity Connect URL",
"application/json, application/xml body (GenerateConnectURLRequestLending): Expected body to be sent with the request Returns:",
"content_type (string): JSON or XML on_behalf_of (string, optional): The name of the entity",
"Codes, specifying the reason for retrieving this report. Returns: VOIEPaystubWithTxverifyReportRecord: Response from the",
"After that you will need to regenerate the Connect link under a new",
"customer_id, report_id, accept, content_type, on_behalf_of=None, purpose=None): \"\"\"Does a GET request to /decisioning/v1/customers/{customerId}/reports/{reportId}. Get",
"# Validate required parameters self.validate_parameters(accept=accept, content_type=content_type, body=body) # Prepare query URL _url_path =",
"Prepare and execute request _request = self.http_client.get(_query_url, headers=_headers) CustomHeaderAuth.apply(_request) _context = self.execute_request(_request) #",
"name of the entity you are retrieving the report on behalf of. purpose",
"types...... - fix Args: accept (string): application/json, application/xml body (GenerateConnectURLRequestFix): Expected body to",
"now \"Migrate Institution Login Accounts\" This service is to migrate accounts from legacy",
"for the given institution login id with an http status code as 200.",
"for retrieving this report. Returns: StatementReportRecord: Response from the API. OK Raises: APIException:",
"Error1ErrorException('Bad Request', _context) self.validate_response(_context) # Return appropriate type return APIHelper.json_deserialize(_context.response.raw_body, PayStatementReportRecord.from_dictionary) def get_voa_report_by_customer(self,",
"- voieTxVerify - voieStatement - payStatement - assetSummary - preQualVoa Args: accept (string):",
"= self.execute_request(_request) self.validate_response(_context) # Return appropriate type return APIHelper.json_deserialize(_context.response.raw_body, GenerateConnectURLResponse.from_dictionary) def send_connect_email(self, accept,",
"the “type” code in the call. For lending, each type signifies a report",
"Generate Finicity Connect URL (Fix) Args: accept (string): application/json, application/xml body (GenerateConnectURLRequest): Expected",
"import VOIEPaystubWithTxverifyReportRecord from finicityapi.models.voi_report_record import VOIReportRecord from finicityapi.models.voa_with_income_report_record import VOAWithIncomeReportRecord from finicityapi.models.prequalification_report_record import",
"AddCustomerResponse from finicityapi.models.voa_report_record import VOAReportRecord from finicityapi.models.voie_paystub_with_txverify_report_record import VOIEPaystubWithTxverifyReportRecord from finicityapi.models.voi_report_record import VOIReportRecord",
"# Prepare query URL _url_path = '/aggregation/v1/customers/{customerId}/institutionLogins/{institutionLoginId}/institutions/{newInstitutionId}' _url_path = APIHelper.append_url_with_template_parameters(_url_path, { 'customerId': customer_id,",
"headers _headers = { 'Finicity-App-Key': Configuration.finicity_app_key, 'Content-Type': content_type, 'Accept': accept } # Prepare",
"{ 'content-type': 'application/json; charset=utf-8', 'Finicity-App-Key': Configuration.finicity_app_key, 'Accept': accept } # Prepare and execute",
"lending, each type signifies a report that will be generated as part of",
"def get_statement_report_by_consumer(self, consumer_id, report_id, accept, content_type, on_behalf_of=None, purpose=None): \"\"\"Does a GET request to",
"_query_url = APIHelper.clean_url(_query_builder) # Prepare headers _headers = { 'accept': 'application/json', 'Finicity-App-Key': Configuration.finicity_app_key",
"CustomHeaderAuth.apply(_request) _context = self.execute_request(_request) self.validate_response(_context) # Return appropriate type return APIHelper.json_deserialize(_context.response.raw_body, AddCustomerResponse.from_dictionary) def",
"gives the applicable implementation details for the following types...... - fix Args: accept",
"to /aggregation/v1/customers/active. This version 1 service has been replaced with version 2 Enroll",
"_context = self.execute_request(_request) self.validate_response(_context) # Return appropriate type return APIHelper.json_deserialize(_context.response.raw_body, GenerateConnectURLResponse.from_dictionary) def generate_connect_url_lite(self,",
"GenerateConnectURLResponse.from_dictionary) def generate_connect_url_lite(self, accept, body): \"\"\"Does a POST request to /connect/v1/generate. No matter",
"if preferred on_behalf_of (string, optional): The name of the entity you are retrieving",
"to /aggregation/v1/customers/testing. Enroll a testing customer. A testing customer may only register accounts",
"URL (Lite) Generate Finicity Connect URL (Fix) Args: accept (string): application/json, application/xml body",
"Request', _context) self.validate_response(_context) # Return appropriate type return APIHelper.json_deserialize(_context.response.raw_body, TransactionsReportRecord.from_dictionary) def get_app_registration_status_v_1(self): \"\"\"Does",
"HTTP status codes. if _context.response.status_code == 400: raise Error1ErrorException('Bad Request', _context) self.validate_response(_context) #",
"(string): JSON or XML on_behalf_of (string, optional): The name of the entity you",
"from finicityapi.models.app_statuses_v_1 import AppStatusesV1 from finicityapi.models.statement_report_record import StatementReportRecord from finicityapi.exceptions.error_1_error_exception import Error1ErrorException class",
"the request. \"\"\" # Validate required parameters self.validate_parameters(content_type=content_type, accept=accept, body=body) # Prepare query",
"Return appropriate type return APIHelper.json_deserialize(_context.response.raw_body, VOAWithIncomeReportRecord.from_dictionary) def get_voa_with_income_report_by_customer(self, customer_id, report_id, accept, content_type, on_behalf_of=None,",
"_url_path = '/decisioning/v1/consumers/{consumerId}/reports/{reportId}' _url_path = APIHelper.append_url_with_template_parameters(_url_path, { 'consumerId': consumer_id, 'reportId': report_id }) _query_builder",
"# Return appropriate type return APIHelper.json_deserialize(_context.response.raw_body, PrequalificationReportRecord.from_dictionary) def get_pay_statement_by_consumer(self, consumer_id, report_id, accept, content_type,",
"on implementing Finicity Connect, you’ll need to generate and retrieve a Finicity Connect",
"the authentication token under which it was generated expires. After that you will",
"VOIReportRecord.from_dictionary) def get_voa_with_income_report_by_consumer(self, consumer_id, report_id, accept, content_type, on_behalf_of=None, purpose=None): \"\"\"Does a GET request",
"Purpose Codes, specifying the reason for retrieving this report. Returns: VOIReportRecord: Response from",
"Connect flow. It is best to use the documentation for the specific use",
"(GenerateConnectURLRequestFix): Expected body to be sent with the request Returns: GenerateConnectURLResponse: Response from",
"(string, optional): The name of the entity you are retrieving the report on",
"report_id=report_id, accept=accept, content_type=content_type) # Prepare query URL _url_path = '/decisioning/v1/customers/{customerId}/reports/{reportId}' _url_path = APIHelper.append_url_with_template_parameters(_url_path,",
"implementation details for the following types...... - ach - aggregation Args: accept (string):",
"headers _headers = { 'content-type': 'application/json; charset=utf-8', 'Finicity-App-Key': Configuration.finicity_app_key, 'Accept': accept } #",
"with 'xml' if preferred on_behalf_of (string, optional): The name of the entity you",
"the remote API. This exception includes the HTTP Response code, an error message,",
"what type of Finicity Connect you need. Once you have generated the link",
"HTTP Response code, an error message, and the HTTP body that was received",
"voi - voieTxVerify - voieStatement - payStatement - assetSummary - preQualVoa Args: accept",
"required parameters self.validate_parameters(accept=accept, content_type=content_type, body=body) # Prepare query URL _url_path = '/aggregation/v1/customers/active' _query_builder",
"from Permissible Purpose Codes, specifying the reason for retrieving this report. Returns: VOIEPaystubWithTxverifyReportRecord:",
"the request. \"\"\" # Validate required parameters self.validate_parameters(accept=accept, content_type=content_type, body=body) # Prepare query",
"_url_path _query_parameters = { 'onBehalfOf': on_behalf_of, 'purpose': purpose } _query_builder = APIHelper.append_url_with_query_parameters(_query_builder, _query_parameters,",
"this service before enrolling in a paid plan will return HTTP 429 (Too",
"body (GenerateConnectEmailRequest): Expected body to be sent with the request Returns: GenerateConnectEmailResponseMultipleBorrowers: Response",
"that was received in the request. \"\"\" # Validate required parameters self.validate_parameters(customer_id=customer_id, institution_login_id=institution_login_id,",
"has been replaced by version 2 call now \"Migrate Institution Login Accounts\" This",
"specifying the reason for retrieving this report. Returns: VOAReportRecord: Response from the API.",
"a new authentication token. We recommend generating a new authentication token when you",
"all the possible parameters you can send for this endpoint depending on the",
"service has been replaced with version 2 Enroll an active customer, which is",
"PrequalificationReportRecord.from_dictionary) def get_prequalification_report_by_consumer(self, consumer_id, report_id, accept, content_type, on_behalf_of=None, purpose=None): \"\"\"Does a GET request",
"'/decisioning/v1/consumers/{consumerId}/reports/{reportId}' _url_path = APIHelper.append_url_with_template_parameters(_url_path, { 'consumerId': consumer_id, 'reportId': report_id }) _query_builder = Configuration.get_base_uri()",
"Prepare headers _headers = { 'accept': 'application/json', 'Finicity-App-Key': Configuration.finicity_app_key } # Prepare and",
"type return APIHelper.json_deserialize(_context.response.raw_body, VOIEPaystubWithTxverifyReportRecord.from_dictionary) def get_voi_report_by_consumer(self, consumer_id, report_id, accept, content_type, on_behalf_of=None, purpose=None): \"\"\"Does",
"coding: utf-8 -*- from finicityapi.api_helper import APIHelper from finicityapi.configuration import Configuration from finicityapi.controllers.base_controller",
"of Connect. The Connect type is controlled by the “type” code in the",
"institutions. Args: content_type (string): application/json, application/xml accept (string): application/json, application/xml body (AddCustomerRequest): The",
"finicityapi.models.generate_connect_email_response_multiple_borrowers import GenerateConnectEmailResponseMultipleBorrowers from finicityapi.models.transactions_report_record import TransactionsReportRecord from finicityapi.models.app_statuses_v_1 import AppStatusesV1 from finicityapi.models.statement_report_record",
"raise Error1ErrorException('Bad Request', _context) self.validate_response(_context) # Return appropriate type return APIHelper.json_deserialize(_context.response.raw_body, PayStatementReportRecord.from_dictionary) def",
"VOIEPaystubWithTxverifyReportRecord.from_dictionary) def get_pay_statement_extraction_by_customer(self, customer_id, report_id, accept, content_type, on_behalf_of=None, purpose=None): \"\"\"Does a GET request",
"import Error1ErrorException class DeprecatedController(BaseController): \"\"\"A Controller to access Endpoints in the finicityapi API.\"\"\"",
"status field will contain inProgress, failure, or success. If the status shows inProgress,",
"Permissible Purpose Codes, specifying the reason for retrieving this report. Returns: VOIEPaystubWithTxverifyReportRecord: Response",
"are gathered. Several Finicity products utilize Finicity Connect, and most products have their",
"Replace 'json' with 'xml' if preferred on_behalf_of (string, optional): The name of the",
"purposes for retrieving a report. Args: customer_id (long|int): Finicity’s ID of the customer",
"for a list of permissible purposes for retrieving a report. Args: customer_id (long|int):",
"type of Finicity Connect you need depending on what will happen once the",
"documentation gives the applicable implementation details for the following types...... - ach -",
"Institution Login Accounts\" This service is to migrate accounts from legacy FI to",
"+= _url_path _query_url = APIHelper.clean_url(_query_builder) # Prepare headers _headers = { 'content-type': 'application/json;",
"list of all the possible parameters you can send for this endpoint depending",
"authentication token when you generate a Connect link, to guarantee a full two",
"def get_voa_with_income_report_by_customer(self, customer_id, report_id, accept, content_type, on_behalf_of=None, purpose=None): \"\"\"Does a GET request to",
"_context = self.execute_request(_request) self.validate_response(_context) # Return appropriate type return APIHelper.json_deserialize(_context.response.raw_body, GenerateConnectURLResponse.from_dictionary) def generate_connect_url_fix(self,",
"depending on what will happen once the customer accounts and transaction data are",
"Error1ErrorException('Bad Request', _context) self.validate_response(_context) # Return appropriate type return APIHelper.json_deserialize(_context.response.raw_body, PrequalificationReportRecord.from_dictionary) def get_pay_statement_by_consumer(self,",
"Connect URL (Fix) Args: accept (string): application/json, application/xml body (GenerateConnectURLRequest): Expected body to",
"A successful API response will return a list of accounts for the given",
"content_type, accept, body): \"\"\"Does a POST request to /aggregation/v1/customers/testing. Enroll a testing customer.",
"New OAuth FI ID where accounts will be migrated Returns: CustomerAccounts: Response from",
"Configuration.finicity_app_key, 'Content-Type': content_type, 'Accept': accept } # Prepare and execute request _request =",
"service before enrolling in a paid plan will return HTTP 429 (Too Many",
"Return appropriate type return APIHelper.json_deserialize(_context.response.raw_body, VOAWithIncomeReportRecord.from_dictionary) def get_prequalification_voa_report_by_customer(self, customer_id, report_id, accept, content_type, on_behalf_of=None,",
"the customer report_id (string): Finicity’s ID of the report accept (string): Replace 'json'",
"APIHelper.json_deserialize(_context.response.raw_body, StatementReportRecord.from_dictionary) def get_statement_report_by_consumer(self, consumer_id, report_id, accept, content_type, on_behalf_of=None, purpose=None): \"\"\"Does a GET",
"specific documentation for the types to see more details on the flow. This",
"the client app should wait 20 seconds and then call again to see",
"_request = self.http_client.get(_query_url, headers=_headers) CustomHeaderAuth.apply(_request) _context = self.execute_request(_request) self.validate_response(_context) # Return appropriate type",
"_context) self.validate_response(_context) # Return appropriate type return APIHelper.json_deserialize(_context.response.raw_body, TransactionsReportRecord.from_dictionary) def get_app_registration_status_v_1(self): \"\"\"Does a",
"- assetSummary - preQualVoa Args: accept (string): application/json, application/xml body (GenerateConnectURLRequestLending): Expected body",
"Return appropriate type return APIHelper.json_deserialize(_context.response.raw_body, GenerateConnectURLResponse.from_dictionary) def generate_connect_url_lite(self, accept, body): \"\"\"Does a POST",
"the report accept (string): Replace 'json' with 'xml' if preferred content_type (string): Replace",
"consumer_id, 'reportId': report_id }) _query_builder = Configuration.get_base_uri() _query_builder += _url_path _query_parameters = {",
"Enroll an active customer, which is the actual owner of one or more",
"Finicity Connect you need. Once you have generated the link it will only",
"flow. You will need to specify what type of Finicity Connect you need",
"Prepare query URL _url_path = '/connect/v1/send/email' _query_builder = Configuration.get_base_uri() _query_builder += _url_path _query_url",
"import StatementReportRecord from finicityapi.exceptions.error_1_error_exception import Error1ErrorException class DeprecatedController(BaseController): \"\"\"A Controller to access Endpoints",
"institution_login_id, new_institution_id): \"\"\"Does a PUT request to /aggregation/v1/customers/{customerId}/institutionLogins/{institutionLoginId}/institutions/{newInstitutionId}. This service has been replaced",
"the Connect flow. For Send Connect Email service it does not support the",
"_context) self.validate_response(_context) # Return appropriate type return APIHelper.json_deserialize(_context.response.raw_body, VOIEPaystubWithTxverifyReportRecord.from_dictionary) def get_voi_report_by_consumer(self, consumer_id, report_id,",
"can send for this endpoint depending on the use case. See the following",
"accept=accept, content_type=content_type) # Prepare query URL _url_path = '/decisioning/v1/customers/{customerId}/reports/{reportId}' _url_path = APIHelper.append_url_with_template_parameters(_url_path, {",
"the API. default response Raises: APIException: When an error occurs while fetching the",
"Return appropriate type return APIHelper.json_deserialize(_context.response.raw_body, AddCustomerResponse.from_dictionary) def generate_connect_url_data_and_payments_connect(self, accept, body): \"\"\"Does a POST",
"def send_connect_email(self, accept, body): \"\"\"Does a POST request to /connect/v1/send/email. A connect email",
"a list of accounts for the given institution login id with an http",
"APIHelper.clean_url(_query_builder) # Prepare headers _headers = { 'content-type': 'application/json; charset=utf-8', 'Finicity-App-Key': Configuration.finicity_app_key, 'Accept':",
"recommend generating a new authentication token when you generate a Connect link, to",
"to the connect flow. You will need to specify what type of Finicity",
"status code as 200. Args: customer_id (long|int): Finicity’s ID of the customer for",
"Connect flow. For Send Connect Email service it does not support the types",
"customer_id, institution_login_id, new_institution_id): \"\"\"Does a PUT request to /aggregation/v1/customers/{customerId}/institutionLogins/{institutionLoginId}/institutions/{newInstitutionId}. This service has been",
"Finicity products utilize Finicity Connect, and most products have their own type of",
"query URL _url_path = '/aggregation/v1/customers/active' _query_builder = Configuration.get_base_uri() _query_builder += _url_path _query_url =",
"the following more specific documentation for your use case....... Generate Finicity Connect URL",
"- voi - voieTxVerify - voieStatement - payStatement - assetSummary - preQualVoa Args:",
"return APIHelper.json_deserialize(_context.response.raw_body, GenerateConnectEmailResponseMultipleBorrowers.from_dictionary) def get_transactions_report_by_customer(self, customer_id, report_id, accept, content_type, on_behalf_of=None, purpose=None): \"\"\"Does a",
"= self.http_client.get(_query_url, headers=_headers) CustomHeaderAuth.apply(_request) _context = self.execute_request(_request) self.validate_response(_context) # Return appropriate type return",
"customer accounts and transaction data are gathered. Several Finicity products utilize Finicity Connect,",
"GenerateConnectURLResponse: Response from the API. Raises: APIException: When an error occurs while fetching",
"APIHelper.json_deserialize(_context.response.raw_body, VOAReportRecord.from_dictionary) def get_voie_txverify_report_by_consumer(self, consumer_id, report_id, accept, content_type, on_behalf_of=None, purpose=None): \"\"\"Does a GET",
"Args: accept (string): application/json, application/xml body (GenerateConnectURLRequestDataAndPayments): Expected body to be sent with",
"'/aggregation/v1/customers/{customerId}/institutionLogins/{institutionLoginId}/institutions/{newInstitutionId}' _url_path = APIHelper.append_url_with_template_parameters(_url_path, { 'customerId': customer_id, 'institutionLoginId': institution_login_id, 'newInstitutionId': new_institution_id }) _query_builder",
"= APIHelper.clean_url(_query_builder) # Prepare headers _headers = { 'Finicity-App-Key': Configuration.finicity_app_key, 'Accept': accept, 'Content-Type':",
"StatementReportRecord.from_dictionary) def get_statement_report_by_consumer(self, consumer_id, report_id, accept, content_type, on_behalf_of=None, purpose=None): \"\"\"Does a GET request",
"raise Error1ErrorException('Bad Request', _context) self.validate_response(_context) # Return appropriate type return APIHelper.json_deserialize(_context.response.raw_body, VOIEPaystubWithTxverifyReportRecord.from_dictionary) def",
"parameters=APIHelper.json_serialize(body)) CustomHeaderAuth.apply(_request) _context = self.execute_request(_request) self.validate_response(_context) # Return appropriate type return APIHelper.json_deserialize(_context.response.raw_body, GenerateConnectURLResponse.from_dictionary)",
"query URL _url_path = '/aggregation/v1/partners/applications' _query_builder = Configuration.get_base_uri() _query_builder += _url_path _query_url =",
"accept (string): application/json, application/xml body (GenerateConnectURLRequestLending): Expected body to be sent with the",
"VOAWithIncomeReportRecord.from_dictionary) def get_prequalification_voa_report_by_customer(self, customer_id, report_id, accept, content_type, on_behalf_of=None, purpose=None): \"\"\"Does a GET request",
"Response code, an error message, and the HTTP body that was received in",
"global error handling using HTTP status codes. if _context.response.status_code == 400: raise Error1ErrorException('Bad",
"# Return appropriate type return APIHelper.json_deserialize(_context.response.raw_body, VOAWithIncomeReportRecord.from_dictionary) def get_prequalification_voa_report_by_customer(self, customer_id, report_id, accept, content_type,",
"on_behalf_of, 'purpose': purpose } _query_builder = APIHelper.append_url_with_query_parameters(_query_builder, _query_parameters, Configuration.array_serialization) _query_url = APIHelper.clean_url(_query_builder) #",
"get_statement_report_by_consumer(self, consumer_id, report_id, accept, content_type, on_behalf_of=None, purpose=None): \"\"\"Does a GET request to /decisioning/v1/consumers/{consumerId}/reports/{reportId}.",
"or XML content_type (string): JSON or XML on_behalf_of (string, optional): The name of",
"new authentication token. We recommend generating a new authentication token when you generate",
"GET request to /decisioning/v1/consumers/{consumerId}/reports/{reportId}. Get a report that has been generated by calling",
"Returns: VOAWithIncomeReportRecord: Response from the API. OK Raises: APIException: When an error occurs",
"APIHelper.json_deserialize(_context.response.raw_body, VOIReportRecord.from_dictionary) def get_voa_with_income_report_by_consumer(self, consumer_id, report_id, accept, content_type, on_behalf_of=None, purpose=None): \"\"\"Does a GET",
"sent with the request Returns: GenerateConnectURLResponse: Response from the API. Raises: APIException: When",
"Connect you need. Once you have generated the link it will only last",
"Validate required parameters self.validate_parameters(accept=accept, body=body) # Prepare query URL _url_path = '/connect/v1/generate' _query_builder",
"_url_path _query_url = APIHelper.clean_url(_query_builder) # Prepare headers _headers = { 'Finicity-App-Key': Configuration.finicity_app_key, 'Accept':",
"'/connect/v1/send/email' _query_builder = Configuration.get_base_uri() _query_builder += _url_path _query_url = APIHelper.clean_url(_query_builder) # Prepare headers",
"and then call again to see if the report is finished. See Permissible",
"the institutionLoginId of accounts institution_login_id (long|int): Finicity's institutionLoginId for the set of accounts",
"http status code as 200. Args: customer_id (long|int): Finicity’s ID of the customer",
"get_voie_txverify_report_by_customer(self, customer_id, report_id, accept, content_type, on_behalf_of=None, purpose=None): \"\"\"Does a GET request to /decisioning/v1/customers/{customerId}/reports/{reportId}.",
"self.validate_response(_context) # Return appropriate type return APIHelper.json_deserialize(_context.response.raw_body, VOAReportRecord.from_dictionary) def get_voie_txverify_report_by_consumer(self, consumer_id, report_id, accept,",
"request to /aggregation/v1/partners/applications. Get the status of your application registration to access FI's",
"= self.http_client.post(_query_url, headers=_headers, parameters=APIHelper.json_serialize(body)) CustomHeaderAuth.apply(_request) _context = self.execute_request(_request) self.validate_response(_context) # Return appropriate type",
"from finicityapi.models.pay_statement_report_record import PayStatementReportRecord from finicityapi.models.generate_connect_email_response_multiple_borrowers import GenerateConnectEmailResponseMultipleBorrowers from finicityapi.models.transactions_report_record import TransactionsReportRecord from",
"use the documentation for the specific use case you are interested in as",
"Enroll a testing customer. A testing customer may only register accounts with FinBank",
"APIHelper.json_deserialize(_context.response.raw_body, PrequalificationReportRecord.from_dictionary) def get_prequalification_report_by_consumer(self, consumer_id, report_id, accept, content_type, on_behalf_of=None, purpose=None): \"\"\"Does a GET",
"Request', _context) self.validate_response(_context) # Return appropriate type return APIHelper.json_deserialize(_context.response.raw_body, StatementReportRecord.from_dictionary) def get_statement_report_by_consumer(self, consumer_id,",
"that will be run upon completing the Connect flow. For Send Connect Email",
"by the “type” code in the call. See the specific documentation for the",
"return APIHelper.json_deserialize(_context.response.raw_body, AddCustomerResponse.from_dictionary) def get_voa_report_by_consumer(self, consumer_id, report_id, accept, content_type, on_behalf_of=None, purpose=None): \"\"\"Does a",
"429 (Too Many Requests). Args: accept (string): application/json, application/xml content_type (string): application/json, application/xml",
"} # Prepare and execute request _request = self.http_client.get(_query_url, headers=_headers) CustomHeaderAuth.apply(_request) _context =",
"= self.http_client.get(_query_url, headers=_headers) CustomHeaderAuth.apply(_request) _context = self.execute_request(_request) # Endpoint and global error handling",
"link under a new authentication token. We recommend generating a new authentication token",
"Connect, you’ll need to generate and retrieve a Finicity Connect Link. You will",
"# Validate required parameters self.validate_parameters(customer_id=customer_id, institution_login_id=institution_login_id, new_institution_id=new_institution_id) # Prepare query URL _url_path =",
"= APIHelper.append_url_with_query_parameters(_query_builder, _query_parameters, Configuration.array_serialization) _query_url = APIHelper.clean_url(_query_builder) # Prepare headers _headers = {",
"_context = self.execute_request(_request) self.validate_response(_context) # Return appropriate type return APIHelper.json_deserialize(_context.response.raw_body, AppStatusesV1.from_dictionary) def get_statement_report_by_customer(self,",
"should wait 20 seconds and then call again to see if the report",
"'Content-Type': content_type } # Prepare and execute request _request = self.http_client.post(_query_url, headers=_headers, parameters=APIHelper.json_serialize(body))",
"This service has been replaced by version 2 call now \"Migrate Institution Login",
"request to /aggregation/v1/customers/active. This version 1 service has been replaced with version 2",
"get_statement_report_by_customer(self, customer_id, report_id, accept, content_type, on_behalf_of=None, purpose=None): \"\"\"Does a GET request to /decisioning/v1/customers/{customerId}/reports/{reportId}.",
"Error1ErrorException('Bad Request', _context) self.validate_response(_context) # Return appropriate type return APIHelper.json_deserialize(_context.response.raw_body, PrequalificationReportRecord.from_dictionary) def get_prequalification_report_by_consumer(self,",
"Args: accept (string): application/json, application/xml body (GenerateConnectURLRequest): Expected body to be sent with",
"VOAReportRecord from finicityapi.models.voie_paystub_with_txverify_report_record import VOIEPaystubWithTxverifyReportRecord from finicityapi.models.voi_report_record import VOIReportRecord from finicityapi.models.voa_with_income_report_record import VOAWithIncomeReportRecord",
"Permissible Purpose Codes, specifying the reason for retrieving this report. Returns: PayStatementReportRecord: Response",
"type return APIHelper.json_deserialize(_context.response.raw_body, VOIReportRecord.from_dictionary) def get_voa_with_income_report_by_consumer(self, consumer_id, report_id, accept, content_type, on_behalf_of=None, purpose=None): \"\"\"Does",
"details on a non email implementation. Args: accept (string): application/json body (GenerateConnectEmailRequest): Expected",
"PUT request to /aggregation/v1/customers/{customerId}/institutionLogins/{institutionLoginId}/institutions/{newInstitutionId}. This service has been replaced by version 2 call",
"= APIHelper.clean_url(_query_builder) # Prepare headers _headers = { 'content-type': 'application/json; charset=utf-8', 'Finicity-App-Key': Configuration.finicity_app_key,",
"the customer which will contain a link to the connect flow. You will",
"or success. If the status shows inProgress, the client app should wait 20",
"service it does not support the types aggregation, lite and fix. See the",
"import AddCustomerResponse from finicityapi.models.voa_report_record import VOAReportRecord from finicityapi.models.voie_paystub_with_txverify_report_record import VOIEPaystubWithTxverifyReportRecord from finicityapi.models.voi_report_record import",
"APIHelper.append_url_with_template_parameters(_url_path, { 'customerId': customer_id, 'institutionLoginId': institution_login_id, 'newInstitutionId': new_institution_id }) _query_builder = Configuration.get_base_uri() _query_builder",
"reason for retrieving this report. Returns: VOIEPaystubWithTxverifyReportRecord: Response from the API. OK Raises:",
"or more real-world accounts. This is a billable customer. This service is not",
"appropriate type return APIHelper.json_deserialize(_context.response.raw_body, PrequalificationReportRecord.from_dictionary) def get_prequalification_report_by_consumer(self, consumer_id, report_id, accept, content_type, on_behalf_of=None, purpose=None):",
"part of the connect flow unless otherwise specified. See the specific documentation for",
"Prepare and execute request _request = self.http_client.post(_query_url, headers=_headers, parameters=APIHelper.json_serialize(body)) CustomHeaderAuth.apply(_request) _context = self.execute_request(_request)",
"The Connect type is controlled by the “type” code in the call. See",
"get_voie_txverify_report_by_consumer(self, consumer_id, report_id, accept, content_type, on_behalf_of=None, purpose=None): \"\"\"Does a GET request to /decisioning/v1/consumers/{consumerId}/reports/{reportId}.",
"for retrieving this report. Returns: VOAReportRecord: Response from the API. OK Raises: APIException:",
"Endpoint and global error handling using HTTP status codes. if _context.response.status_code == 400:",
"_headers = { 'accept': 'application/json', 'Finicity-App-Key': Configuration.finicity_app_key } # Prepare and execute request",
"received in the request. \"\"\" # Validate required parameters self.validate_parameters(customer_id=customer_id, report_id=report_id, accept=accept, content_type=content_type)",
"APIHelper.json_deserialize(_context.response.raw_body, AppStatusesV1.from_dictionary) def get_statement_report_by_customer(self, customer_id, report_id, accept, content_type, on_behalf_of=None, purpose=None): \"\"\"Does a GET",
"replaced by version 2 call now \"Migrate Institution Login Accounts\" This service is",
"Response from the API. Raises: APIException: When an error occurs while fetching the",
"inProgress, the client app should wait 20 seconds and then call again to",
"flow. For Send Connect Email service it does not support the types aggregation,",
"documentation gives the applicable implementation details for the following types...... - fix Args:",
"request to /decisioning/v1/customers/{customerId}/reports/{reportId}. Get a report that has been generated by calling one",
"depending on the use case. See the following more specific documentation for your",
"# Prepare query URL _url_path = '/decisioning/v1/consumers/{consumerId}/reports/{reportId}' _url_path = APIHelper.append_url_with_template_parameters(_url_path, { 'consumerId': consumer_id,",
"Codes, specifying the reason for retrieving this report. Returns: AuditableReport: Response from the",
"_query_builder += _url_path _query_url = APIHelper.clean_url(_query_builder) # Prepare headers _headers = { 'accept':",
"finicityapi.controllers.base_controller import BaseController from finicityapi.http.auth.custom_header_auth import CustomHeaderAuth from finicityapi.models.generate_connect_url_response import GenerateConnectURLResponse from finicityapi.models.customer_accounts",
"_context) self.validate_response(_context) # Return appropriate type return APIHelper.json_deserialize(_context.response.raw_body, VOIReportRecord.from_dictionary) def get_voi_report_by_customer(self, customer_id, report_id,",
"(long|int): Finicity’s ID of the customer report_id (string): Finicity’s ID of the report",
"For The New Customer Returns: AddCustomerResponse: Response from the API. default response Raises:",
"# Prepare query URL _url_path = '/connect/v1/generate' _query_builder = Configuration.get_base_uri() _query_builder += _url_path",
"parameters=APIHelper.json_serialize(body)) CustomHeaderAuth.apply(_request) _context = self.execute_request(_request) self.validate_response(_context) # Return appropriate type return APIHelper.json_deserialize(_context.response.raw_body, AddCustomerResponse.from_dictionary)",
"success. If the status shows inProgress, the client app should wait 20 seconds",
"Connect, and most products have their own type of Connect. The Connect type",
"a billable customer. This service is not available from the Test Drive. Calls",
"= '/aggregation/v1/partners/applications' _query_builder = Configuration.get_base_uri() _query_builder += _url_path _query_url = APIHelper.clean_url(_query_builder) # Prepare",
"case....... Generate Finicity Connect URL (Data and Payments) Generate Finicity Connect URL (Lending)",
"def generate_connect_url_lending(self, accept, body): \"\"\"Does a POST request to /connect/v1/generate. No matter how",
"get_voi_report_by_customer(self, customer_id, report_id, accept, content_type, on_behalf_of=None, purpose=None): \"\"\"Does a GET request to /decisioning/v1/customers/{customerId}/reports/{reportId}.",
"Configuration.get_base_uri() _query_builder += _url_path _query_parameters = { 'onBehalfOf': on_behalf_of, 'purpose': purpose } _query_builder",
"32 characters) report_id (string): Finicity’s ID of the report accept (string): JSON or",
"content_type, body): \"\"\"Does a POST request to /aggregation/v1/customers/active. This version 1 service has",
"API.\"\"\" def generate_connect_url_all_types(self, accept, body): \"\"\"Does a POST request to /connect/v1/generate. No matter",
"Prepare query URL _url_path = '/aggregation/v1/customers/{customerId}/institutionLogins/{institutionLoginId}/institutions/{newInstitutionId}' _url_path = APIHelper.append_url_with_template_parameters(_url_path, { 'customerId': customer_id, 'institutionLoginId':",
"PrequalificationReportRecord: Response from the API. OK Raises: APIException: When an error occurs while",
"body (GenerateConnectURLRequestDataAndPayments): Expected body to be sent with the request Returns: GenerateConnectURLResponse: Response",
"Request', _context) self.validate_response(_context) # Return appropriate type return APIHelper.json_deserialize(_context.response.raw_body, VOIEPaystubWithTxverifyReportRecord.from_dictionary) def get_pay_statement_extraction_by_customer(self, customer_id,",
"will contain inProgress, failure, or success. If the status shows inProgress, the client",
"_url_path _query_url = APIHelper.clean_url(_query_builder) # Prepare headers _headers = { 'Finicity-App-Key': Configuration.finicity_app_key, 'Content-Type':",
"appropriate type return APIHelper.json_deserialize(_context.response.raw_body, TransactionsReportRecord.from_dictionary) def get_app_registration_status_v_1(self): \"\"\"Does a GET request to /aggregation/v1/partners/applications.",
"with an http status code as 200. Args: customer_id (long|int): Finicity’s ID of",
"type return APIHelper.json_deserialize(_context.response.raw_body, AppStatusesV1.from_dictionary) def get_statement_report_by_customer(self, customer_id, report_id, accept, content_type, on_behalf_of=None, purpose=None): \"\"\"Does",
"'Finicity-App-Key': Configuration.finicity_app_key, 'Content-Type': content_type, 'Accept': accept } # Prepare and execute request _request",
"query URL _url_path = '/connect/v1/send/email' _query_builder = Configuration.get_base_uri() _query_builder += _url_path _query_url =",
"Request', _context) self.validate_response(_context) # Return appropriate type return APIHelper.json_deserialize(_context.response.raw_body, VOAWithIncomeReportRecord.from_dictionary) def get_prequalification_voa_report_by_customer(self, customer_id,",
"import TransactionsReportRecord from finicityapi.models.app_statuses_v_1 import AppStatusesV1 from finicityapi.models.statement_report_record import StatementReportRecord from finicityapi.exceptions.error_1_error_exception import",
"This version 1 service has been replaced with version 2 Enroll an active",
"Finicity’s ID of the report accept (string): Replace 'json' with 'xml' if preferred",
"The New Testing Customer Returns: AddCustomerResponse: Response from the API. default response Raises:",
"need to specify what type of Finicity Connect you need depending on what",
"The report's status field will contain inProgress, failure, or success. If the status",
"institution_login_id=institution_login_id, new_institution_id=new_institution_id) # Prepare query URL _url_path = '/aggregation/v1/customers/{customerId}/institutionLogins/{institutionLoginId}/institutions/{newInstitutionId}' _url_path = APIHelper.append_url_with_template_parameters(_url_path, {",
"again to see if the report is finished. See Permissible Purpose Codes for",
"appropriate type return APIHelper.json_deserialize(_context.response.raw_body, VOAWithIncomeReportRecord.from_dictionary) def get_prequalification_voa_report_by_customer(self, customer_id, report_id, accept, content_type, on_behalf_of=None, purpose=None):",
"get_prequalification_report_by_consumer(self, consumer_id, report_id, accept, content_type, on_behalf_of=None, purpose=None): \"\"\"Does a GET request to /decisioning/v1/consumers/{consumerId}/reports/{reportId}.",
"Purpose Codes, specifying the reason for retrieving this report. Returns: StatementReportRecord: Response from",
"\"\"\" # Validate required parameters self.validate_parameters(accept=accept, content_type=content_type, body=body) # Prepare query URL _url_path",
"= '/connect/v1/generate' _query_builder = Configuration.get_base_uri() _query_builder += _url_path _query_url = APIHelper.clean_url(_query_builder) # Prepare",
"ID of the customer report_id (string): Finicity’s ID of the report (UUID with",
"was received in the request. \"\"\" # Prepare query URL _url_path = '/aggregation/v1/partners/applications'",
"the request Returns: GenerateConnectEmailResponseMultipleBorrowers: Response from the API. Raises: APIException: When an error",
"Codes, specifying the reason for retrieving this report. Returns: TransactionsReportRecord: Response from the",
"will be run upon completing the Connect flow. It is best to use",
"return APIHelper.json_deserialize(_context.response.raw_body, VOAReportRecord.from_dictionary) def get_voie_txverify_report_by_consumer(self, consumer_id, report_id, accept, content_type, on_behalf_of=None, purpose=None): \"\"\"Does a",
"from the remote API. This exception includes the HTTP Response code, an error",
"accounts for the given institution login id with an http status code as",
"VOAReportRecord.from_dictionary) def get_voie_txverify_report_by_consumer(self, consumer_id, report_id, accept, content_type, on_behalf_of=None, purpose=None): \"\"\"Does a GET request",
"application/json, application/xml body (GenerateConnectURLRequestDataAndPayments): Expected body to be sent with the request Returns:",
"the call. See the specific documentation for the types to see more details",
"flow. It is best to use the documentation for the specific use case",
"that was received in the request. \"\"\" # Validate required parameters self.validate_parameters(customer_id=customer_id, report_id=report_id,",
"support the types aggregation, lite and fix. See the endpoint Generate Finicity Connect",
"details for the following types...... - voa - voahistory - voi - voieTxVerify",
"VOIEPaystubWithTxverifyReportRecord from finicityapi.models.voi_report_record import VOIReportRecord from finicityapi.models.voa_with_income_report_record import VOAWithIncomeReportRecord from finicityapi.models.prequalification_report_record import PrequalificationReportRecord",
"raise Error1ErrorException('Bad Request', _context) self.validate_response(_context) # Return appropriate type return APIHelper.json_deserialize(_context.response.raw_body, VOAWithIncomeReportRecord.from_dictionary) def",
"customer. This service is not available from the Test Drive. Calls to this",
"{ 'onBehalfOf': on_behalf_of, 'purpose': purpose } _query_builder = APIHelper.append_url_with_query_parameters(_query_builder, _query_parameters, Configuration.array_serialization) _query_url =",
"Prepare query URL _url_path = '/decisioning/v1/consumers/{consumerId}/reports/{reportId}' _url_path = APIHelper.append_url_with_template_parameters(_url_path, { 'consumerId': consumer_id, 'reportId':",
"application/json body (GenerateConnectEmailRequest): Expected body to be sent with the request Returns: GenerateConnectEmailResponseMultipleBorrowers:",
"'newInstitutionId': new_institution_id }) _query_builder = Configuration.get_base_uri() _query_builder += _url_path _query_url = APIHelper.clean_url(_query_builder) #",
"been generated by calling one of the Generate Report services. The report's status",
"generating a new authentication token when you generate a Connect link, to guarantee",
"body that was received in the request. \"\"\" # Validate required parameters self.validate_parameters(customer_id=customer_id,",
"(string): application/json, application/xml body (AddCustomerRequest): The Fields For The New Testing Customer Returns:",
"400: raise Error1ErrorException('Bad Request', _context) self.validate_response(_context) # Return appropriate type return APIHelper.json_deserialize(_context.response.raw_body, VOAWithIncomeReportRecord.from_dictionary)",
"preferred content_type (string): Replace 'json' with 'xml' if preferred on_behalf_of (string, optional): The",
"return APIHelper.json_deserialize(_context.response.raw_body, AddCustomerResponse.from_dictionary) def generate_connect_url_data_and_payments_connect(self, accept, body): \"\"\"Does a POST request to /connect/v1/generate.",
"body that was received in the request. \"\"\" # Validate required parameters self.validate_parameters(consumer_id=consumer_id,",
"reason for retrieving this report. Returns: VOIReportRecord: Response from the API. OK Raises:",
"you’ll find how to generate the Connect link as well as where to",
"Return appropriate type return APIHelper.json_deserialize(_context.response.raw_body, GenerateConnectURLResponse.from_dictionary) def send_connect_email(self, accept, body): \"\"\"Does a POST",
"FI. A successful API response will return a list of accounts for the",
"Return appropriate type return APIHelper.json_deserialize(_context.response.raw_body, VOAReportRecord.from_dictionary) def get_voie_txverify_report_by_consumer(self, consumer_id, report_id, accept, content_type, on_behalf_of=None,",
"return APIHelper.json_deserialize(_context.response.raw_body, GenerateConnectURLResponse.from_dictionary) def send_connect_email(self, accept, body): \"\"\"Does a POST request to /connect/v1/send/email.",
"from Permissible Purpose Codes, specifying the reason for retrieving this report. Returns: VOAWithIncomeReportRecord:",
"CustomHeaderAuth.apply(_request) _context = self.execute_request(_request) self.validate_response(_context) # Return appropriate type return APIHelper.json_deserialize(_context.response.raw_body, AppStatusesV1.from_dictionary) def",
"# Return appropriate type return APIHelper.json_deserialize(_context.response.raw_body, GenerateConnectURLResponse.from_dictionary) def generate_connect_url_lending(self, accept, body): \"\"\"Does a",
"} _query_builder = APIHelper.append_url_with_query_parameters(_query_builder, _query_parameters, Configuration.array_serialization) _query_url = APIHelper.clean_url(_query_builder) # Prepare headers _headers",
"self.execute_request(_request) self.validate_response(_context) # Return appropriate type return APIHelper.json_deserialize(_context.response.raw_body, GenerateConnectURLResponse.from_dictionary) def send_connect_email(self, accept, body):",
"and most products have their own type of Connect. The Connect type is",
"Generate Finicity Connect URL (Lite) Generate Finicity Connect URL (Fix) Args: accept (string):",
"}) _query_builder = Configuration.get_base_uri() _query_builder += _url_path _query_url = APIHelper.clean_url(_query_builder) # Prepare headers",
"(AddCustomerRequest): The Fields For The New Testing Customer Returns: AddCustomerResponse: Response from the",
"self.validate_response(_context) # Return appropriate type return APIHelper.json_deserialize(_context.response.raw_body, GenerateConnectURLResponse.from_dictionary) def migrate_institution_login_accounts_v_1(self, customer_id, institution_login_id, new_institution_id):",
"of accounts institution_login_id (long|int): Finicity's institutionLoginId for the set of accounts to be",
"the connect flow unless otherwise specified. See the specific documentation for the types",
"Validate required parameters self.validate_parameters(accept=accept, body=body) # Prepare query URL _url_path = '/connect/v1/send/email' _query_builder",
"Connect. The Connect type is controlled by the “type” code in the call.",
"preQualVoa Args: accept (string): application/json, application/xml body (GenerateConnectURLRequestLending): Expected body to be sent",
"login id with an http status code as 200. Args: customer_id (long|int): Finicity’s",
"query URL _url_path = '/connect/v1/generate' _query_builder = Configuration.get_base_uri() _query_builder += _url_path _query_url =",
"required parameters self.validate_parameters(customer_id=customer_id, institution_login_id=institution_login_id, new_institution_id=new_institution_id) # Prepare query URL _url_path = '/aggregation/v1/customers/{customerId}/institutionLogins/{institutionLoginId}/institutions/{newInstitutionId}' _url_path",
"to be sent with the request Returns: GenerateConnectEmailResponseMultipleBorrowers: Response from the API. Raises:",
"generate and retrieve a Finicity Connect Link. You will need to specify what",
"from finicityapi.models.customer_accounts import CustomerAccounts from finicityapi.models.auditable_report import AuditableReport from finicityapi.models.add_customer_response import AddCustomerResponse from",
"from finicityapi.api_helper import APIHelper from finicityapi.configuration import Configuration from finicityapi.controllers.base_controller import BaseController from",
"{ 'accept': 'application/json', 'Finicity-App-Key': Configuration.finicity_app_key } # Prepare and execute request _request =",
"calling one of the Generate Report services. The report's status field will contain",
"documentation for the types to see more details on the flow. This documentation",
"Return appropriate type return APIHelper.json_deserialize(_context.response.raw_body, TransactionsReportRecord.from_dictionary) def get_app_registration_status_v_1(self): \"\"\"Does a GET request to",
"id with an http status code as 200. Args: customer_id (long|int): Finicity’s ID",
"the Generate Report services. The report's status field will contain inProgress, failure, or",
"APIHelper.json_deserialize(_context.response.raw_body, VOIEPaystubWithTxverifyReportRecord.from_dictionary) def get_voi_report_by_consumer(self, consumer_id, report_id, accept, content_type, on_behalf_of=None, purpose=None): \"\"\"Does a GET",
"}) _query_builder = Configuration.get_base_uri() _query_builder += _url_path _query_parameters = { 'onBehalfOf': on_behalf_of, 'purpose':",
"you are retrieving the report on behalf of. purpose (string, optional): 2-digit code",
"import GenerateConnectURLResponse from finicityapi.models.customer_accounts import CustomerAccounts from finicityapi.models.auditable_report import AuditableReport from finicityapi.models.add_customer_response import",
"case. See the following more specific documentation for your use case....... Generate Finicity",
"required parameters self.validate_parameters(content_type=content_type, accept=accept, body=body) # Prepare query URL _url_path = '/aggregation/v1/customers/testing' _query_builder",
"endpoint Generate Finicity Connect URL (Lending) for additional details on a non email",
"(string): application/json, application/xml body (AddCustomerRequest): The Fields For The New Customer Returns: AddCustomerResponse:",
"optional): The name of the entity you are retrieving the report on behalf",
"get_voa_report_by_consumer(self, consumer_id, report_id, accept, content_type, on_behalf_of=None, purpose=None): \"\"\"Does a GET request to /decisioning/v1/consumers/{consumerId}/reports/{reportId}.",
"list of accounts for the given institution login id with an http status",
"was received in the request. \"\"\" # Validate required parameters self.validate_parameters(customer_id=customer_id, institution_login_id=institution_login_id, new_institution_id=new_institution_id)",
"to the customer which will contain a link to the connect flow. You",
"from the API. Raises: APIException: When an error occurs while fetching the data",
"on what will happen once the customer accounts and transaction data are gathered.",
"body=body) # Prepare query URL _url_path = '/connect/v1/send/email' _query_builder = Configuration.get_base_uri() _query_builder +=",
"retrieving a report. Args: consumer_id (string): Finicity’s ID of the consumer (UUID with",
"appropriate type return APIHelper.json_deserialize(_context.response.raw_body, VOAReportRecord.from_dictionary) def get_voie_txverify_report_by_customer(self, customer_id, report_id, accept, content_type, on_behalf_of=None, purpose=None):",
"See Permissible Purpose Codes for a list of permissible purposes for retrieving a",
"self.http_client.get(_query_url, headers=_headers) CustomHeaderAuth.apply(_request) _context = self.execute_request(_request) self.validate_response(_context) # Return appropriate type return APIHelper.json_deserialize(_context.response.raw_body,",
"self.execute_request(_request) # Endpoint and global error handling using HTTP status codes. if _context.response.status_code",
"APIHelper.json_deserialize(_context.response.raw_body, VOAWithIncomeReportRecord.from_dictionary) def get_prequalification_voa_report_by_customer(self, customer_id, report_id, accept, content_type, on_behalf_of=None, purpose=None): \"\"\"Does a GET",
"- preQualVoa Args: accept (string): application/json, application/xml body (GenerateConnectURLRequestLending): Expected body to be",
"# Return appropriate type return APIHelper.json_deserialize(_context.response.raw_body, VOAReportRecord.from_dictionary) def get_voie_txverify_report_by_customer(self, customer_id, report_id, accept, content_type,",
"report. Returns: VOIEPaystubWithTxverifyReportRecord: Response from the API. OK Raises: APIException: When an error",
"self.validate_response(_context) # Return appropriate type return APIHelper.json_deserialize(_context.response.raw_body, AddCustomerResponse.from_dictionary) def get_voa_report_by_consumer(self, consumer_id, report_id, accept,",
"the possible parameters you can send for this endpoint depending on the use",
"details for the following types...... - fix Args: accept (string): application/json, application/xml body",
"from finicityapi.models.statement_report_record import StatementReportRecord from finicityapi.exceptions.error_1_error_exception import Error1ErrorException class DeprecatedController(BaseController): \"\"\"A Controller to",
"be sent with the request Returns: GenerateConnectURLResponse: Response from the API. Raises: APIException:",
"to the report that will be run upon completing the Connect flow. For",
"Configuration.finicity_app_key } # Prepare and execute request _request = self.http_client.get(_query_url, headers=_headers) CustomHeaderAuth.apply(_request) _context",
"self.validate_parameters(consumer_id=consumer_id, report_id=report_id, accept=accept, content_type=content_type) # Prepare query URL _url_path = '/decisioning/v1/consumers/{consumerId}/reports/{reportId}' _url_path =",
"the API. Raises: APIException: When an error occurs while fetching the data from",
"AppStatusesV1.from_dictionary) def get_statement_report_by_customer(self, customer_id, report_id, accept, content_type, on_behalf_of=None, purpose=None): \"\"\"Does a GET request",
"DeprecatedController(BaseController): \"\"\"A Controller to access Endpoints in the finicityapi API.\"\"\" def generate_connect_url_all_types(self, accept,",
"transaction data are gathered. Several Finicity products utilize Finicity Connect, and most products",
"/aggregation/v1/customers/active. This version 1 service has been replaced with version 2 Enroll an",
"for the following types...... - fix Args: accept (string): application/json, application/xml body (GenerateConnectURLRequestFix):",
"one of the Generate Report services. The report's status field will contain inProgress,",
"purpose } _query_builder = APIHelper.append_url_with_query_parameters(_query_builder, _query_parameters, Configuration.array_serialization) _query_url = APIHelper.clean_url(_query_builder) # Prepare headers",
"finicityapi.models.customer_accounts import CustomerAccounts from finicityapi.models.auditable_report import AuditableReport from finicityapi.models.add_customer_response import AddCustomerResponse from finicityapi.models.voa_report_record",
"def get_voa_report_by_customer(self, customer_id, report_id, accept, content_type, on_behalf_of=None, purpose=None): \"\"\"Does a GET request to",
"_query_parameters = { 'onBehalfOf': on_behalf_of, 'purpose': purpose } _query_builder = APIHelper.append_url_with_query_parameters(_query_builder, _query_parameters, Configuration.array_serialization)",
"return APIHelper.json_deserialize(_context.response.raw_body, AuditableReport.from_dictionary) def get_report_by_consumer(self, consumer_id, report_id, accept, content_type, on_behalf_of=None, purpose=None): \"\"\"Does a",
"Returns: TransactionsReportRecord: Response from the API. OK Raises: APIException: When an error occurs",
"get_pay_statement_by_consumer(self, consumer_id, report_id, accept, content_type, on_behalf_of=None, purpose=None): \"\"\"Does a GET request to /decisioning/v1/consumers/{consumerId}/reports/{reportId}.",
"'Finicity-App-Key': Configuration.finicity_app_key } # Prepare and execute request _request = self.http_client.put(_query_url, headers=_headers) CustomHeaderAuth.apply(_request)",
"institutionLoginId for the set of accounts to be migrated new_institution_id (long|int): New OAuth",
"to see if the report is finished. See Permissible Purpose Codes for a",
"request _request = self.http_client.post(_query_url, headers=_headers, parameters=APIHelper.json_serialize(body)) CustomHeaderAuth.apply(_request) _context = self.execute_request(_request) self.validate_response(_context) # Return",
"Error1ErrorException('Bad Request', _context) self.validate_response(_context) # Return appropriate type return APIHelper.json_deserialize(_context.response.raw_body, StatementReportRecord.from_dictionary) def get_statement_report_by_consumer(self,",
"'application/json', 'Finicity-App-Key': Configuration.finicity_app_key } # Prepare and execute request _request = self.http_client.put(_query_url, headers=_headers)",
"self.validate_response(_context) # Return appropriate type return APIHelper.json_deserialize(_context.response.raw_body, VOIReportRecord.from_dictionary) def get_voa_with_income_report_by_consumer(self, consumer_id, report_id, accept,",
"It is best to use the documentation for the specific use case you",
"= self.execute_request(_request) self.validate_response(_context) # Return appropriate type return APIHelper.json_deserialize(_context.response.raw_body, GenerateConnectURLResponse.from_dictionary) def migrate_institution_login_accounts_v_1(self, customer_id,",
"(UUID with max length 32 characters) accept (string): Replace 'json' with 'xml' if",
"appropriate type return APIHelper.json_deserialize(_context.response.raw_body, GenerateConnectURLResponse.from_dictionary) def generate_connect_url_lending(self, accept, body): \"\"\"Does a POST request",
"HTTP body that was received in the request. \"\"\" # Validate required parameters",
"(string): Finicity’s ID of the consumer (UUID with max length 32 characters) report_id",
"best to use the documentation for the specific use case you are interested",
"the request. \"\"\" # Prepare query URL _url_path = '/aggregation/v1/partners/applications' _query_builder = Configuration.get_base_uri()",
"body to be sent with the request Returns: GenerateConnectEmailResponseMultipleBorrowers: Response from the API.",
"fix Args: accept (string): application/json, application/xml body (GenerateConnectURLRequestFix): Expected body to be sent",
"a paid plan will return HTTP 429 (Too Many Requests). Args: accept (string):",
"_context) self.validate_response(_context) # Return appropriate type return APIHelper.json_deserialize(_context.response.raw_body, AuditableReport.from_dictionary) def get_report_by_consumer(self, consumer_id, report_id,",
"(AddCustomerRequest): The Fields For The New Customer Returns: AddCustomerResponse: Response from the API.",
"2 call now \"Migrate Institution Login Accounts\" This service is to migrate accounts",
"APIHelper.json_deserialize(_context.response.raw_body, GenerateConnectURLResponse.from_dictionary) def send_connect_email(self, accept, body): \"\"\"Does a POST request to /connect/v1/send/email. A",
"specifying the reason for retrieving this report. Returns: PrequalificationReportRecord: Response from the API.",
"token. We recommend generating a new authentication token when you generate a Connect",
"{ 'customerId': customer_id, 'reportId': report_id }) _query_builder = Configuration.get_base_uri() _query_builder += _url_path _query_parameters",
"a POST request to /aggregation/v1/customers/active. This version 1 service has been replaced with",
"the connect flow. You will need to specify what type of Finicity Connect",
"# Return appropriate type return APIHelper.json_deserialize(_context.response.raw_body, PayStatementReportRecord.from_dictionary) def get_voa_report_by_customer(self, customer_id, report_id, accept, content_type,",
"appropriate type return APIHelper.json_deserialize(_context.response.raw_body, AuditableReport.from_dictionary) def get_report_by_consumer(self, consumer_id, report_id, accept, content_type, on_behalf_of=None, purpose=None):",
"{ 'consumerId': consumer_id, 'reportId': report_id }) _query_builder = Configuration.get_base_uri() _query_builder += _url_path _query_parameters",
"APIHelper.json_deserialize(_context.response.raw_body, AddCustomerResponse.from_dictionary) def get_voa_report_by_consumer(self, consumer_id, report_id, accept, content_type, on_behalf_of=None, purpose=None): \"\"\"Does a GET",
"- aggregation Args: accept (string): application/json, application/xml body (GenerateConnectURLRequestDataAndPayments): Expected body to be",
"(string): application/json body (GenerateConnectEmailRequest): Expected body to be sent with the request Returns:",
"20 seconds and then call again to see if the report is finished.",
"documentation for the specific use case you are interested in as the documentation",
"accept, content_type, on_behalf_of=None, purpose=None): \"\"\"Does a GET request to /decisioning/v1/consumers/{consumerId}/reports/{reportId}. Get a report",
"= self.execute_request(_request) self.validate_response(_context) # Return appropriate type return APIHelper.json_deserialize(_context.response.raw_body, AddCustomerResponse.from_dictionary) def get_voa_report_by_consumer(self, consumer_id,",
"new_institution_id (long|int): New OAuth FI ID where accounts will be migrated Returns: CustomerAccounts:",
"accounts. This is a billable customer. This service is not available from the",
"report that will be run upon completing the Connect flow. For Send Connect",
"an error occurs while fetching the data from the remote API. This exception",
"GET request to /aggregation/v1/partners/applications. Get the status of your application registration to access",
"Connect type is controlled by the “type” code in the call. Many times",
"self.validate_parameters(customer_id=customer_id, institution_login_id=institution_login_id, new_institution_id=new_institution_id) # Prepare query URL _url_path = '/aggregation/v1/customers/{customerId}/institutionLogins/{institutionLoginId}/institutions/{newInstitutionId}' _url_path = APIHelper.append_url_with_template_parameters(_url_path,",
"the use case. See the following more specific documentation for your use case.......",
"charset=utf-8', 'Finicity-App-Key': Configuration.finicity_app_key, 'Accept': accept } # Prepare and execute request _request =",
"if preferred content_type (string): Replace 'json' with 'xml' if preferred on_behalf_of (string, optional):",
"Return appropriate type return APIHelper.json_deserialize(_context.response.raw_body, AuditableReport.from_dictionary) def get_report_by_consumer(self, consumer_id, report_id, accept, content_type, on_behalf_of=None,",
"raise Error1ErrorException('Bad Request', _context) self.validate_response(_context) # Return appropriate type return APIHelper.json_deserialize(_context.response.raw_body, VOIReportRecord.from_dictionary) def",
"with OAuth connections. Returns: AppStatusesV1: Response from the API. Raises: APIException: When an",
"Payments) Generate Finicity Connect URL (Lending) Generate Finicity Connect URL (Lite) Generate Finicity",
"import PrequalificationReportRecord from finicityapi.models.pay_statement_report_record import PayStatementReportRecord from finicityapi.models.generate_connect_email_response_multiple_borrowers import GenerateConnectEmailResponseMultipleBorrowers from finicityapi.models.transactions_report_record import",
"Return appropriate type return APIHelper.json_deserialize(_context.response.raw_body, AddCustomerResponse.from_dictionary) def get_voa_report_by_consumer(self, consumer_id, report_id, accept, content_type, on_behalf_of=None,",
"URL _url_path = '/aggregation/v1/partners/applications' _query_builder = Configuration.get_base_uri() _query_builder += _url_path _query_url = APIHelper.clean_url(_query_builder)",
"purpose (string, optional): 2-digit code from Permissible Purpose Codes, specifying the reason for",
"# Prepare query URL _url_path = '/aggregation/v1/customers/testing' _query_builder = Configuration.get_base_uri() _query_builder += _url_path",
"Configuration.finicity_app_key } # Prepare and execute request _request = self.http_client.put(_query_url, headers=_headers) CustomHeaderAuth.apply(_request) _context",
"return APIHelper.json_deserialize(_context.response.raw_body, PayStatementReportRecord.from_dictionary) def get_voa_report_by_customer(self, customer_id, report_id, accept, content_type, on_behalf_of=None, purpose=None): \"\"\"Does a",
"this report. Returns: StatementReportRecord: Response from the API. OK Raises: APIException: When an",
"APIHelper.json_deserialize(_context.response.raw_body, GenerateConnectURLResponse.from_dictionary) def generate_connect_url_lite(self, accept, body): \"\"\"Does a POST request to /connect/v1/generate. No",
"GenerateConnectURLResponse.from_dictionary) def send_connect_email(self, accept, body): \"\"\"Does a POST request to /connect/v1/send/email. A connect",
"here is a list of all the possible parameters you can send for",
"request to /connect/v1/generate. No matter how you plan on implementing Finicity Connect, you’ll",
"Error1ErrorException('Bad Request', _context) self.validate_response(_context) # Return appropriate type return APIHelper.json_deserialize(_context.response.raw_body, VOIEPaystubWithTxverifyReportRecord.from_dictionary) def get_voi_report_by_consumer(self,",
"types aggregation, lite and fix. See the endpoint Generate Finicity Connect URL (Lending)",
"'content-type': 'application/json; charset=utf-8', 'Finicity-App-Key': Configuration.finicity_app_key, 'Accept': accept } # Prepare and execute request",
"_url_path = APIHelper.append_url_with_template_parameters(_url_path, { 'customerId': customer_id, 'reportId': report_id }) _query_builder = Configuration.get_base_uri() _query_builder",
"client app should wait 20 seconds and then call again to see if",
"retrieving this report. Returns: TransactionsReportRecord: Response from the API. OK Raises: APIException: When",
"Codes for a list of permissible purposes for retrieving a report. Args: customer_id",
"PayStatementReportRecord.from_dictionary) def add_customer_v_1(self, accept, content_type, body): \"\"\"Does a POST request to /aggregation/v1/customers/active. This",
"accounts from legacy FI to new OAuth FI. A successful API response will",
"application/json, application/xml content_type (string): application/json, application/xml body (AddCustomerRequest): The Fields For The New",
"_context) self.validate_response(_context) # Return appropriate type return APIHelper.json_deserialize(_context.response.raw_body, PayStatementReportRecord.from_dictionary) def add_customer_v_1(self, accept, content_type,",
"the specific documentation for the types to see more details on the flow.",
"regenerate the Connect link under a new authentication token. We recommend generating a",
"AddCustomerResponse: Response from the API. default response Raises: APIException: When an error occurs",
"report. Returns: TransactionsReportRecord: Response from the API. OK Raises: APIException: When an error",
"# Return appropriate type return APIHelper.json_deserialize(_context.response.raw_body, VOIEPaystubWithTxverifyReportRecord.from_dictionary) def get_pay_statement_extraction_by_customer(self, customer_id, report_id, accept, content_type,",
"def get_pay_statement_by_consumer(self, consumer_id, report_id, accept, content_type, on_behalf_of=None, purpose=None): \"\"\"Does a GET request to",
"Configuration.finicity_app_key, 'Accept': accept } # Prepare and execute request _request = self.http_client.post(_query_url, headers=_headers,",
"self.validate_response(_context) # Return appropriate type return APIHelper.json_deserialize(_context.response.raw_body, GenerateConnectURLResponse.from_dictionary) def send_connect_email(self, accept, body): \"\"\"Does",
"of. purpose (string, optional): 2-digit code from Permissible Purpose Codes, specifying the reason",
"\"\"\"Does a POST request to /aggregation/v1/customers/active. This version 1 service has been replaced",
"new OAuth FI. A successful API response will return a list of accounts",
"finicityapi.models.transactions_report_record import TransactionsReportRecord from finicityapi.models.app_statuses_v_1 import AppStatusesV1 from finicityapi.models.statement_report_record import StatementReportRecord from finicityapi.exceptions.error_1_error_exception",
"“type” code in the call. For lending, each type signifies a report that",
"Permissible Purpose Codes, specifying the reason for retrieving this report. Returns: PrequalificationReportRecord: Response",
"AuditableReport.from_dictionary) def add_testing_customer_v_1(self, content_type, accept, body): \"\"\"Does a POST request to /aggregation/v1/customers/testing. Enroll",
"Returns: PrequalificationReportRecord: Response from the API. OK Raises: APIException: When an error occurs",
"not support the types aggregation, lite and fix. See the endpoint Generate Finicity",
"get_voi_report_by_consumer(self, consumer_id, report_id, accept, content_type, on_behalf_of=None, purpose=None): \"\"\"Does a GET request to /decisioning/v1/consumers/{consumerId}/reports/{reportId}.",
"appropriate type return APIHelper.json_deserialize(_context.response.raw_body, PayStatementReportRecord.from_dictionary) def get_voa_report_by_customer(self, customer_id, report_id, accept, content_type, on_behalf_of=None, purpose=None):",
"report that will be generated as part of the connect flow unless otherwise",
"last until the authentication token under which it was generated expires. After that",
"of the report accept (string): JSON or XML content_type (string): JSON or XML",
"JSON or XML on_behalf_of (string, optional): The name of the entity you are",
"Connect type is controlled by the “type” code in the call. For lending,",
"# Return appropriate type return APIHelper.json_deserialize(_context.response.raw_body, GenerateConnectEmailResponseMultipleBorrowers.from_dictionary) def get_transactions_report_by_customer(self, customer_id, report_id, accept, content_type,",
"characters) accept (string): Replace 'json' with 'xml' if preferred content_type (string): Replace 'json'",
"type return APIHelper.json_deserialize(_context.response.raw_body, AddCustomerResponse.from_dictionary) def get_voa_report_by_consumer(self, consumer_id, report_id, accept, content_type, on_behalf_of=None, purpose=None): \"\"\"Does",
"types...... - voa - voahistory - voi - voieTxVerify - voieStatement - payStatement",
"def add_testing_customer_v_1(self, content_type, accept, body): \"\"\"Does a POST request to /aggregation/v1/customers/testing. Enroll a",
"default response Raises: APIException: When an error occurs while fetching the data from",
"# Return appropriate type return APIHelper.json_deserialize(_context.response.raw_body, AuditableReport.from_dictionary) def add_testing_customer_v_1(self, content_type, accept, body): \"\"\"Does",
"finicityapi.models.voa_report_record import VOAReportRecord from finicityapi.models.voie_paystub_with_txverify_report_record import VOIEPaystubWithTxverifyReportRecord from finicityapi.models.voi_report_record import VOIReportRecord from finicityapi.models.voa_with_income_report_record",
"has been generated by calling one of the Generate Report services. The report's",
"sends an email to the customer which will contain a link to the",
"Requests). Args: accept (string): application/json, application/xml content_type (string): application/json, application/xml body (AddCustomerRequest): The",
"VOAReportRecord.from_dictionary) def get_voie_txverify_report_by_customer(self, customer_id, report_id, accept, content_type, on_behalf_of=None, purpose=None): \"\"\"Does a GET request",
"PayStatementReportRecord.from_dictionary) def get_voa_report_by_customer(self, customer_id, report_id, accept, content_type, on_behalf_of=None, purpose=None): \"\"\"Does a GET request",
"generate_connect_url_fix(self, accept, body): \"\"\"Does a POST request to /connect/v1/generate. No matter how you",
"self.validate_response(_context) # Return appropriate type return APIHelper.json_deserialize(_context.response.raw_body, AddCustomerResponse.from_dictionary) def generate_connect_url_data_and_payments_connect(self, accept, body): \"\"\"Does",
"body that was received in the request. \"\"\" # Prepare query URL _url_path",
"type return APIHelper.json_deserialize(_context.response.raw_body, CustomerAccounts.from_dictionary) def get_report_by_customer(self, customer_id, report_id, accept, content_type, on_behalf_of=None, purpose=None): \"\"\"Does",
"that has been generated by calling one of the Generate Report services. The",
"available from the Test Drive. Calls to this service before enrolling in a",
"institution_login_id, 'newInstitutionId': new_institution_id }) _query_builder = Configuration.get_base_uri() _query_builder += _url_path _query_url = APIHelper.clean_url(_query_builder)",
"_context) self.validate_response(_context) # Return appropriate type return APIHelper.json_deserialize(_context.response.raw_body, VOIReportRecord.from_dictionary) def get_voa_with_income_report_by_consumer(self, consumer_id, report_id,",
"call. Many times the type also corresponds to the report that will be",
"utf-8 -*- from finicityapi.api_helper import APIHelper from finicityapi.configuration import Configuration from finicityapi.controllers.base_controller import",
"200. Args: customer_id (long|int): Finicity’s ID of the customer for the institutionLoginId of",
"content_type (string): application/json, application/xml accept (string): application/json, application/xml body (AddCustomerRequest): The Fields For",
"the “type” code in the call. See the specific documentation for the types",
"once the customer accounts and transaction data are gathered. Below you’ll find how",
"appropriate type return APIHelper.json_deserialize(_context.response.raw_body, VOAWithIncomeReportRecord.from_dictionary) def get_voa_with_income_report_by_customer(self, customer_id, report_id, accept, content_type, on_behalf_of=None, purpose=None):",
"request. \"\"\" # Validate required parameters self.validate_parameters(customer_id=customer_id, institution_login_id=institution_login_id, new_institution_id=new_institution_id) # Prepare query URL",
"for retrieving this report. Returns: AuditableReport: Response from the API. OK Raises: APIException:",
"report. Args: customer_id (long|int): Finicity’s ID of the customer report_id (string): Finicity’s ID",
"from finicityapi.http.auth.custom_header_auth import CustomHeaderAuth from finicityapi.models.generate_connect_url_response import GenerateConnectURLResponse from finicityapi.models.customer_accounts import CustomerAccounts from",
"Codes, specifying the reason for retrieving this report. Returns: VOAWithIncomeReportRecord: Response from the",
"report. Returns: VOAWithIncomeReportRecord: Response from the API. OK Raises: APIException: When an error",
"flow. This documentation gives the applicable implementation details for the following types...... -",
"version 2 call now \"Migrate Institution Login Accounts\" This service is to migrate",
"_context = self.execute_request(_request) self.validate_response(_context) # Return appropriate type return APIHelper.json_deserialize(_context.response.raw_body, GenerateConnectEmailResponseMultipleBorrowers.from_dictionary) def get_transactions_report_by_customer(self,",
"completing the Connect flow. For Send Connect Email service it does not support",
"your use case....... Generate Finicity Connect URL (Data and Payments) Generate Finicity Connect",
"OAuth connections. Returns: AppStatusesV1: Response from the API. Raises: APIException: When an error",
"The Connect type is controlled by the “type” code in the call. Many",
"that was received in the request. \"\"\" # Validate required parameters self.validate_parameters(consumer_id=consumer_id, report_id=report_id,",
"link as well as where to specify what type of Finicity Connect you",
"This exception includes the HTTP Response code, an error message, and the HTTP",
"import VOAReportRecord from finicityapi.models.voie_paystub_with_txverify_report_record import VOIEPaystubWithTxverifyReportRecord from finicityapi.models.voi_report_record import VOIReportRecord from finicityapi.models.voa_with_income_report_record import",
"_context = self.execute_request(_request) self.validate_response(_context) # Return appropriate type return APIHelper.json_deserialize(_context.response.raw_body, GenerateConnectURLResponse.from_dictionary) def generate_connect_url_lending(self,",
"self.validate_response(_context) # Return appropriate type return APIHelper.json_deserialize(_context.response.raw_body, PrequalificationReportRecord.from_dictionary) def get_prequalification_report_by_consumer(self, consumer_id, report_id, accept,",
"Configuration.get_base_uri() _query_builder += _url_path _query_url = APIHelper.clean_url(_query_builder) # Prepare headers _headers = {",
"return a list of accounts for the given institution login id with an",
"billable customer. This service is not available from the Test Drive. Calls to",
"call. For lending, each type signifies a report that will be generated as",
"is the actual owner of one or more real-world accounts. This is a",
"it was generated expires. After that you will need to regenerate the Connect",
"“type” code in the call. Many times the type also corresponds to the",
"_query_builder = APIHelper.append_url_with_query_parameters(_query_builder, _query_parameters, Configuration.array_serialization) _query_url = APIHelper.clean_url(_query_builder) # Prepare headers _headers =",
"for retrieving this report. Returns: VOAWithIncomeReportRecord: Response from the API. OK Raises: APIException:",
"def get_voie_txverify_report_by_consumer(self, consumer_id, report_id, accept, content_type, on_behalf_of=None, purpose=None): \"\"\"Does a GET request to",
"} # Prepare and execute request _request = self.http_client.post(_query_url, headers=_headers, parameters=APIHelper.json_serialize(body)) CustomHeaderAuth.apply(_request) _context",
"_context) self.validate_response(_context) # Return appropriate type return APIHelper.json_deserialize(_context.response.raw_body, VOAReportRecord.from_dictionary) def get_voie_txverify_report_by_customer(self, customer_id, report_id,",
"accounts with FinBank institutions. Args: content_type (string): application/json, application/xml accept (string): application/json, application/xml",
"will return HTTP 429 (Too Many Requests). Args: accept (string): application/json, application/xml content_type",
"POST request to /connect/v1/send/email. A connect email sends an email to the customer",
"is a list of all the possible parameters you can send for this",
"self.http_client.post(_query_url, headers=_headers, parameters=APIHelper.json_serialize(body)) CustomHeaderAuth.apply(_request) _context = self.execute_request(_request) self.validate_response(_context) # Return appropriate type return",
"where accounts will be migrated Returns: CustomerAccounts: Response from the API. default response",
"the status shows inProgress, the client app should wait 20 seconds and then",
"ID where accounts will be migrated Returns: CustomerAccounts: Response from the API. default",
"if _context.response.status_code == 400: raise Error1ErrorException('Bad Request', _context) self.validate_response(_context) # Return appropriate type",
"you will need to regenerate the Connect link under a new authentication token.",
"exception includes the HTTP Response code, an error message, and the HTTP body",
"controlled by the “type” code in the call. Many times the type also",
"with max length 32 characters) accept (string): Replace 'json' with 'xml' if preferred",
"URL _url_path = '/aggregation/v1/customers/active' _query_builder = Configuration.get_base_uri() _query_builder += _url_path _query_url = APIHelper.clean_url(_query_builder)",
"from Permissible Purpose Codes, specifying the reason for retrieving this report. Returns: VOAReportRecord:",
"'/connect/v1/generate' _query_builder = Configuration.get_base_uri() _query_builder += _url_path _query_url = APIHelper.clean_url(_query_builder) # Prepare headers",
"migrated new_institution_id (long|int): New OAuth FI ID where accounts will be migrated Returns:",
"raise Error1ErrorException('Bad Request', _context) self.validate_response(_context) # Return appropriate type return APIHelper.json_deserialize(_context.response.raw_body, AuditableReport.from_dictionary) def",
"APIHelper.json_deserialize(_context.response.raw_body, AuditableReport.from_dictionary) def add_testing_customer_v_1(self, content_type, accept, body): \"\"\"Does a POST request to /aggregation/v1/customers/testing.",
"the customer for the institutionLoginId of accounts institution_login_id (long|int): Finicity's institutionLoginId for the",
"customer accounts and transaction data are gathered. Below you’ll find how to generate",
"Request', _context) self.validate_response(_context) # Return appropriate type return APIHelper.json_deserialize(_context.response.raw_body, VOIEPaystubWithTxverifyReportRecord.from_dictionary) def get_voi_report_by_consumer(self, consumer_id,",
"version 1 service has been replaced with version 2 Enroll an active customer,",
"self.execute_request(_request) self.validate_response(_context) # Return appropriate type return APIHelper.json_deserialize(_context.response.raw_body, CustomerAccounts.from_dictionary) def get_report_by_customer(self, customer_id, report_id,",
"type is controlled by the “type” code in the call. See the specific",
"self.validate_response(_context) # Return appropriate type return APIHelper.json_deserialize(_context.response.raw_body, GenerateConnectURLResponse.from_dictionary) def generate_connect_url_lite(self, accept, body): \"\"\"Does",
"self.validate_parameters(accept=accept, body=body) # Prepare query URL _url_path = '/connect/v1/send/email' _query_builder = Configuration.get_base_uri() _query_builder",
"Purpose Codes, specifying the reason for retrieving this report. Returns: PayStatementReportRecord: Response from",
"retrieving this report. Returns: PayStatementReportRecord: Response from the API. OK Raises: APIException: When",
"AddCustomerResponse.from_dictionary) def get_voa_report_by_consumer(self, consumer_id, report_id, accept, content_type, on_behalf_of=None, purpose=None): \"\"\"Does a GET request",
"'/aggregation/v1/customers/active' _query_builder = Configuration.get_base_uri() _query_builder += _url_path _query_url = APIHelper.clean_url(_query_builder) # Prepare headers",
"type return APIHelper.json_deserialize(_context.response.raw_body, PrequalificationReportRecord.from_dictionary) def get_prequalification_report_by_consumer(self, consumer_id, report_id, accept, content_type, on_behalf_of=None, purpose=None): \"\"\"Does",
"appropriate type return APIHelper.json_deserialize(_context.response.raw_body, VOIReportRecord.from_dictionary) def get_voi_report_by_customer(self, customer_id, report_id, accept, content_type, on_behalf_of=None, purpose=None):",
"/decisioning/v1/customers/{customerId}/reports/{reportId}. Get a report that has been generated by calling one of the",
"report_id=report_id, accept=accept, content_type=content_type) # Prepare query URL _url_path = '/decisioning/v1/consumers/{consumerId}/reports/{reportId}' _url_path = APIHelper.append_url_with_template_parameters(_url_path,",
"under which it was generated expires. After that you will need to regenerate",
"_query_url = APIHelper.clean_url(_query_builder) # Prepare headers _headers = { 'Finicity-App-Key': Configuration.finicity_app_key, 'Accept': accept,",
"Customer Returns: AddCustomerResponse: Response from the API. default response Raises: APIException: When an",
"Codes, specifying the reason for retrieving this report. Returns: StatementReportRecord: Response from the",
"need to generate and retrieve a Finicity Connect Link. You will need to",
"report. Returns: PrequalificationReportRecord: Response from the API. OK Raises: APIException: When an error",
"Finicity Connect you need depending on what will happen once the customer accounts",
"XML content_type (string): JSON or XML on_behalf_of (string, optional): The name of the",
"this report. Returns: VOAReportRecord: Response from the API. OK Raises: APIException: When an",
"self.execute_request(_request) self.validate_response(_context) # Return appropriate type return APIHelper.json_deserialize(_context.response.raw_body, GenerateConnectEmailResponseMultipleBorrowers.from_dictionary) def get_transactions_report_by_customer(self, customer_id, report_id,",
"error handling using HTTP status codes. if _context.response.status_code == 400: raise Error1ErrorException('Bad Request',",
"unless otherwise specified. See the specific documentation for the types to see more",
"For The New Testing Customer Returns: AddCustomerResponse: Response from the API. default response",
"Finicity’s ID of the customer for the institutionLoginId of accounts institution_login_id (long|int): Finicity's",
"customer report_id (string): Finicity’s ID of the report accept (string): Replace 'json' with",
"times the type also corresponds to the report that will be run upon",
"appropriate type return APIHelper.json_deserialize(_context.response.raw_body, PrequalificationReportRecord.from_dictionary) def get_pay_statement_by_consumer(self, consumer_id, report_id, accept, content_type, on_behalf_of=None, purpose=None):",
"Request', _context) self.validate_response(_context) # Return appropriate type return APIHelper.json_deserialize(_context.response.raw_body, PrequalificationReportRecord.from_dictionary) def get_prequalification_report_by_consumer(self, consumer_id,",
"400: raise Error1ErrorException('Bad Request', _context) self.validate_response(_context) # Return appropriate type return APIHelper.json_deserialize(_context.response.raw_body, VOIEPaystubWithTxverifyReportRecord.from_dictionary)",
"return APIHelper.json_deserialize(_context.response.raw_body, AppStatusesV1.from_dictionary) def get_statement_report_by_customer(self, customer_id, report_id, accept, content_type, on_behalf_of=None, purpose=None): \"\"\"Does a",
"return APIHelper.json_deserialize(_context.response.raw_body, PayStatementReportRecord.from_dictionary) def add_customer_v_1(self, accept, content_type, body): \"\"\"Does a POST request to",
"from finicityapi.exceptions.error_1_error_exception import Error1ErrorException class DeprecatedController(BaseController): \"\"\"A Controller to access Endpoints in the",
"return APIHelper.json_deserialize(_context.response.raw_body, GenerateConnectURLResponse.from_dictionary) def generate_connect_url_fix(self, accept, body): \"\"\"Does a POST request to /connect/v1/generate.",
"implementation details for the following types...... - fix Args: accept (string): application/json, application/xml",
"# Return appropriate type return APIHelper.json_deserialize(_context.response.raw_body, VOIReportRecord.from_dictionary) def get_voa_with_income_report_by_consumer(self, consumer_id, report_id, accept, content_type,",
"and fix. See the endpoint Generate Finicity Connect URL (Lending) for additional details",
"_context = self.execute_request(_request) self.validate_response(_context) # Return appropriate type return APIHelper.json_deserialize(_context.response.raw_body, GenerateConnectURLResponse.from_dictionary) def migrate_institution_login_accounts_v_1(self,",
"Purpose Codes, specifying the reason for retrieving this report. Returns: TransactionsReportRecord: Response from",
"Returns: StatementReportRecord: Response from the API. OK Raises: APIException: When an error occurs",
"data are gathered. Below you’ll find how to generate the Connect link as",
"Prepare headers _headers = { 'Finicity-App-Key': Configuration.finicity_app_key, 'Accept': accept, 'Content-Type': content_type } #",
"This service is to migrate accounts from legacy FI to new OAuth FI.",
"the “type” code in the call. Many times the type also corresponds to",
"parameters self.validate_parameters(accept=accept, body=body) # Prepare query URL _url_path = '/connect/v1/send/email' _query_builder = Configuration.get_base_uri()",
"application/json, application/xml body (GenerateConnectURLRequestLite): Expected body to be sent with the request Returns:",
"will contain a link to the connect flow. You will need to specify",
"body (GenerateConnectURLRequestLending): Expected body to be sent with the request Returns: GenerateConnectURLResponse: Response",
"_request = self.http_client.get(_query_url, headers=_headers) CustomHeaderAuth.apply(_request) _context = self.execute_request(_request) # Endpoint and global error",
"return APIHelper.json_deserialize(_context.response.raw_body, GenerateConnectURLResponse.from_dictionary) def generate_connect_url_lending(self, accept, body): \"\"\"Does a POST request to /connect/v1/generate.",
"class DeprecatedController(BaseController): \"\"\"A Controller to access Endpoints in the finicityapi API.\"\"\" def generate_connect_url_all_types(self,",
"Email service it does not support the types aggregation, lite and fix. See",
"Error1ErrorException('Bad Request', _context) self.validate_response(_context) # Return appropriate type return APIHelper.json_deserialize(_context.response.raw_body, VOIReportRecord.from_dictionary) def get_voi_report_by_customer(self,",
"what will happen once the customer accounts and transaction data are gathered. Several",
"return APIHelper.json_deserialize(_context.response.raw_body, StatementReportRecord.from_dictionary) def get_statement_report_by_consumer(self, consumer_id, report_id, accept, content_type, on_behalf_of=None, purpose=None): \"\"\"Does a",
"access FI's with OAuth connections. Returns: AppStatusesV1: Response from the API. Raises: APIException:",
"_url_path = '/decisioning/v1/customers/{customerId}/reports/{reportId}' _url_path = APIHelper.append_url_with_template_parameters(_url_path, { 'customerId': customer_id, 'reportId': report_id }) _query_builder",
"the API. OK Raises: APIException: When an error occurs while fetching the data",
"type return APIHelper.json_deserialize(_context.response.raw_body, VOIReportRecord.from_dictionary) def get_voi_report_by_customer(self, customer_id, report_id, accept, content_type, on_behalf_of=None, purpose=None): \"\"\"Does",
"Finicity Connect URL (Lending) for additional details on a non email implementation. Args:",
"\"\"\" # Prepare query URL _url_path = '/aggregation/v1/partners/applications' _query_builder = Configuration.get_base_uri() _query_builder +=",
"- ach - aggregation Args: accept (string): application/json, application/xml body (GenerateConnectURLRequestDataAndPayments): Expected body",
"parameters=APIHelper.json_serialize(body)) CustomHeaderAuth.apply(_request) _context = self.execute_request(_request) self.validate_response(_context) # Return appropriate type return APIHelper.json_deserialize(_context.response.raw_body, GenerateConnectEmailResponseMultipleBorrowers.from_dictionary)",
"that was received in the request. \"\"\" # Validate required parameters self.validate_parameters(content_type=content_type, accept=accept,",
"the reason for retrieving this report. Returns: TransactionsReportRecord: Response from the API. OK",
"request _request = self.http_client.put(_query_url, headers=_headers) CustomHeaderAuth.apply(_request) _context = self.execute_request(_request) self.validate_response(_context) # Return appropriate",
"self.validate_response(_context) # Return appropriate type return APIHelper.json_deserialize(_context.response.raw_body, VOIEPaystubWithTxverifyReportRecord.from_dictionary) def get_voi_report_by_consumer(self, consumer_id, report_id, accept,",
"Connect Link. You will need to specify what type of Finicity Connect you",
"a report. Args: consumer_id (string): Finicity’s ID of the consumer (UUID with max",
"customer_id, 'reportId': report_id }) _query_builder = Configuration.get_base_uri() _query_builder += _url_path _query_parameters = {",
"the customer accounts and transaction data are gathered. Below you’ll find how to",
"# Validate required parameters self.validate_parameters(accept=accept, body=body) # Prepare query URL _url_path = '/connect/v1/send/email'",
"Return appropriate type return APIHelper.json_deserialize(_context.response.raw_body, PayStatementReportRecord.from_dictionary) def get_voa_report_by_customer(self, customer_id, report_id, accept, content_type, on_behalf_of=None,",
"finicityapi API.\"\"\" def generate_connect_url_all_types(self, accept, body): \"\"\"Does a POST request to /connect/v1/generate. No",
"_url_path = APIHelper.append_url_with_template_parameters(_url_path, { 'customerId': customer_id, 'institutionLoginId': institution_login_id, 'newInstitutionId': new_institution_id }) _query_builder =",
"the reason for retrieving this report. Returns: VOIReportRecord: Response from the API. OK",
"from the API. default response Raises: APIException: When an error occurs while fetching",
"Request', _context) self.validate_response(_context) # Return appropriate type return APIHelper.json_deserialize(_context.response.raw_body, PayStatementReportRecord.from_dictionary) def get_voa_report_by_customer(self, customer_id,",
"content_type, on_behalf_of=None, purpose=None): \"\"\"Does a GET request to /decisioning/v1/customers/{customerId}/reports/{reportId}. Get a report that",
"def get_voi_report_by_customer(self, customer_id, report_id, accept, content_type, on_behalf_of=None, purpose=None): \"\"\"Does a GET request to",
"the following types...... - fix Args: accept (string): application/json, application/xml body (GenerateConnectURLRequestFix): Expected",
"content_type, 'Accept': accept } # Prepare and execute request _request = self.http_client.post(_query_url, headers=_headers,",
"report (UUID with max length 32 characters) accept (string): Replace 'json' with 'xml'",
"} # Prepare and execute request _request = self.http_client.put(_query_url, headers=_headers) CustomHeaderAuth.apply(_request) _context =",
"(Lite) Generate Finicity Connect URL (Fix) Args: accept (string): application/json, application/xml body (GenerateConnectURLRequest):",
"appropriate type return APIHelper.json_deserialize(_context.response.raw_body, AddCustomerResponse.from_dictionary) def generate_connect_url_data_and_payments_connect(self, accept, body): \"\"\"Does a POST request",
"the request. \"\"\" # Validate required parameters self.validate_parameters(consumer_id=consumer_id, report_id=report_id, accept=accept, content_type=content_type) # Prepare",
"Connect you need depending on what will happen once the customer accounts and",
"body (GenerateConnectURLRequestLite): Expected body to be sent with the request Returns: GenerateConnectURLResponse: Response",
"to /aggregation/v1/partners/applications. Get the status of your application registration to access FI's with",
"run upon completing the Connect flow. For Send Connect Email service it does",
"see more details on the flow. This documentation gives the applicable implementation details",
"aggregation, lite and fix. See the endpoint Generate Finicity Connect URL (Lending) for",
"{ 'Finicity-App-Key': Configuration.finicity_app_key, 'Accept': accept, 'Content-Type': content_type } # Prepare and execute request",
"See the following more specific documentation for your use case....... Generate Finicity Connect",
"Error1ErrorException('Bad Request', _context) self.validate_response(_context) # Return appropriate type return APIHelper.json_deserialize(_context.response.raw_body, VOAReportRecord.from_dictionary) def get_voie_txverify_report_by_consumer(self,",
"token under which it was generated expires. After that you will need to",
"This service is not available from the Test Drive. Calls to this service",
"shows inProgress, the client app should wait 20 seconds and then call again",
"purposes for retrieving a report. Args: consumer_id (string): Finicity’s ID of the consumer",
"products have their own type of Connect. The Connect type is controlled by",
"application registration to access FI's with OAuth connections. Returns: AppStatusesV1: Response from the",
"call. See the specific documentation for the types to see more details on",
"purpose=None): \"\"\"Does a GET request to /decisioning/v1/consumers/{consumerId}/reports/{reportId}. Get a report that has been",
"this report. Returns: PrequalificationReportRecord: Response from the API. OK Raises: APIException: When an",
"\"\"\" # Validate required parameters self.validate_parameters(accept=accept, body=body) # Prepare query URL _url_path =",
"self.validate_response(_context) # Return appropriate type return APIHelper.json_deserialize(_context.response.raw_body, VOAReportRecord.from_dictionary) def get_voie_txverify_report_by_customer(self, customer_id, report_id, accept,",
"it does not support the types aggregation, lite and fix. See the endpoint",
"self.validate_parameters(accept=accept, body=body) # Prepare query URL _url_path = '/connect/v1/generate' _query_builder = Configuration.get_base_uri() _query_builder",
"will need to regenerate the Connect link under a new authentication token. We",
"APIHelper.json_deserialize(_context.response.raw_body, VOIEPaystubWithTxverifyReportRecord.from_dictionary) def get_pay_statement_extraction_by_customer(self, customer_id, report_id, accept, content_type, on_behalf_of=None, purpose=None): \"\"\"Does a GET",
"institution login id with an http status code as 200. Args: customer_id (long|int):",
"will only last until the authentication token under which it was generated expires.",
"a new authentication token when you generate a Connect link, to guarantee a",
"Finicity Connect, you’ll need to generate and retrieve a Finicity Connect Link. You",
"types to see more details on the flow. This documentation gives the applicable",
"(UUID with max length 32 characters) report_id (string): Finicity’s ID of the report",
"Finicity’s ID of the customer report_id (string): Finicity’s ID of the report (UUID",
"you’ll need to generate and retrieve a Finicity Connect Link. You will need",
"the reason for retrieving this report. Returns: StatementReportRecord: Response from the API. OK",
"\"\"\"Does a POST request to /connect/v1/generate. No matter how you plan on implementing",
"are gathered. Below you’ll find how to generate the Connect link as well",
"self.validate_parameters(customer_id=customer_id, report_id=report_id, accept=accept, content_type=content_type) # Prepare query URL _url_path = '/decisioning/v1/customers/{customerId}/reports/{reportId}' _url_path =",
"\"Migrate Institution Login Accounts\" This service is to migrate accounts from legacy FI",
"max length 32 characters) report_id (string): Finicity’s ID of the report accept (string):",
"be migrated Returns: CustomerAccounts: Response from the API. default response Raises: APIException: When",
"given institution login id with an http status code as 200. Args: customer_id",
"query URL _url_path = '/decisioning/v1/customers/{customerId}/reports/{reportId}' _url_path = APIHelper.append_url_with_template_parameters(_url_path, { 'customerId': customer_id, 'reportId': report_id",
"will be generated as part of the connect flow unless otherwise specified. See",
"Error1ErrorException('Bad Request', _context) self.validate_response(_context) # Return appropriate type return APIHelper.json_deserialize(_context.response.raw_body, TransactionsReportRecord.from_dictionary) def get_transactions_report_by_consumer(self,",
"return HTTP 429 (Too Many Requests). Args: accept (string): application/json, application/xml content_type (string):",
"retrieving this report. Returns: VOAWithIncomeReportRecord: Response from the API. OK Raises: APIException: When",
"type return APIHelper.json_deserialize(_context.response.raw_body, PayStatementReportRecord.from_dictionary) def get_voa_report_by_customer(self, customer_id, report_id, accept, content_type, on_behalf_of=None, purpose=None): \"\"\"Does",
"= { 'onBehalfOf': on_behalf_of, 'purpose': purpose } _query_builder = APIHelper.append_url_with_query_parameters(_query_builder, _query_parameters, Configuration.array_serialization) _query_url",
"-*- from finicityapi.api_helper import APIHelper from finicityapi.configuration import Configuration from finicityapi.controllers.base_controller import BaseController",
"Finicity Connect URL (Data and Payments) Generate Finicity Connect URL (Lending) Generate Finicity",
"API response will return a list of accounts for the given institution login",
"headers=_headers) CustomHeaderAuth.apply(_request) _context = self.execute_request(_request) # Endpoint and global error handling using HTTP",
"(GenerateConnectURLRequestLite): Expected body to be sent with the request Returns: GenerateConnectURLResponse: Response from",
"finicityapi.api_helper import APIHelper from finicityapi.configuration import Configuration from finicityapi.controllers.base_controller import BaseController from finicityapi.http.auth.custom_header_auth",
"self.validate_response(_context) # Return appropriate type return APIHelper.json_deserialize(_context.response.raw_body, AppStatusesV1.from_dictionary) def get_statement_report_by_customer(self, customer_id, report_id, accept,",
"get_transactions_report_by_consumer(self, consumer_id, report_id, accept, content_type, on_behalf_of=None, purpose=None): \"\"\"Does a GET request to /decisioning/v1/consumers/{consumerId}/reports/{reportId}.",
"to be sent with the request Returns: GenerateConnectURLResponse: Response from the API. Raises:",
"migrate_institution_login_accounts_v_1(self, customer_id, institution_login_id, new_institution_id): \"\"\"Does a PUT request to /aggregation/v1/customers/{customerId}/institutionLogins/{institutionLoginId}/institutions/{newInstitutionId}. This service has",
"the HTTP Response code, an error message, and the HTTP body that was",
"Codes, specifying the reason for retrieving this report. Returns: VOIReportRecord: Response from the",
"hour life-span. Several Finicity products utilize Finicity Connect, and most products have their",
"_query_url = APIHelper.clean_url(_query_builder) # Prepare headers _headers = { 'Finicity-App-Key': Configuration.finicity_app_key, 'Content-Type': content_type,",
"with version 2 Enroll an active customer, which is the actual owner of",
"migrated Returns: CustomerAccounts: Response from the API. default response Raises: APIException: When an",
"Prepare query URL _url_path = '/aggregation/v1/customers/active' _query_builder = Configuration.get_base_uri() _query_builder += _url_path _query_url",
"appropriate type return APIHelper.json_deserialize(_context.response.raw_body, PayStatementReportRecord.from_dictionary) def add_customer_v_1(self, accept, content_type, body): \"\"\"Does a POST",
"accept, 'Content-Type': content_type } # Prepare and execute request _request = self.http_client.post(_query_url, headers=_headers,",
"# Return appropriate type return APIHelper.json_deserialize(_context.response.raw_body, AddCustomerResponse.from_dictionary) def generate_connect_url_data_and_payments_connect(self, accept, body): \"\"\"Does a",
"- fix Args: accept (string): application/json, application/xml body (GenerateConnectURLRequestFix): Expected body to be",
"# Return appropriate type return APIHelper.json_deserialize(_context.response.raw_body, CustomerAccounts.from_dictionary) def get_report_by_customer(self, customer_id, report_id, accept, content_type,",
"where to specify what type of Finicity Connect you need. Once you have",
"finished. See Permissible Purpose Codes for a list of permissible purposes for retrieving",
"= self.execute_request(_request) self.validate_response(_context) # Return appropriate type return APIHelper.json_deserialize(_context.response.raw_body, GenerateConnectEmailResponseMultipleBorrowers.from_dictionary) def get_transactions_report_by_customer(self, customer_id,",
"finicityapi.models.voa_with_income_report_record import VOAWithIncomeReportRecord from finicityapi.models.prequalification_report_record import PrequalificationReportRecord from finicityapi.models.pay_statement_report_record import PayStatementReportRecord from finicityapi.models.generate_connect_email_response_multiple_borrowers",
"Return appropriate type return APIHelper.json_deserialize(_context.response.raw_body, VOIReportRecord.from_dictionary) def get_voi_report_by_customer(self, customer_id, report_id, accept, content_type, on_behalf_of=None,",
"'customerId': customer_id, 'reportId': report_id }) _query_builder = Configuration.get_base_uri() _query_builder += _url_path _query_parameters =",
"(GenerateConnectEmailRequest): Expected body to be sent with the request Returns: GenerateConnectEmailResponseMultipleBorrowers: Response from",
"= APIHelper.clean_url(_query_builder) # Prepare headers _headers = { 'accept': 'application/json', 'Finicity-App-Key': Configuration.finicity_app_key }",
"utilize Finicity Connect, and most products have their own type of Connect. The",
"connections. Returns: AppStatusesV1: Response from the API. Raises: APIException: When an error occurs",
"(string): application/json, application/xml body (GenerateConnectURLRequestLite): Expected body to be sent with the request",
"+= _url_path _query_url = APIHelper.clean_url(_query_builder) # Prepare headers _headers = { 'accept': 'application/json',",
"# Validate required parameters self.validate_parameters(consumer_id=consumer_id, report_id=report_id, accept=accept, content_type=content_type) # Prepare query URL _url_path",
"and global error handling using HTTP status codes. if _context.response.status_code == 400: raise",
"application/json, application/xml body (GenerateConnectURLRequestFix): Expected body to be sent with the request Returns:",
"Request', _context) self.validate_response(_context) # Return appropriate type return APIHelper.json_deserialize(_context.response.raw_body, VOIReportRecord.from_dictionary) def get_voi_report_by_customer(self, customer_id,",
"services. The report's status field will contain inProgress, failure, or success. If the",
"parameters self.validate_parameters(customer_id=customer_id, report_id=report_id, accept=accept, content_type=content_type) # Prepare query URL _url_path = '/decisioning/v1/customers/{customerId}/reports/{reportId}' _url_path",
"specifying the reason for retrieving this report. Returns: VOIEPaystubWithTxverifyReportRecord: Response from the API.",
"reason for retrieving this report. Returns: AuditableReport: Response from the API. OK Raises:",
"import Configuration from finicityapi.controllers.base_controller import BaseController from finicityapi.http.auth.custom_header_auth import CustomHeaderAuth from finicityapi.models.generate_connect_url_response import",
"type return APIHelper.json_deserialize(_context.response.raw_body, AuditableReport.from_dictionary) def add_testing_customer_v_1(self, content_type, accept, body): \"\"\"Does a POST request",
"Testing Customer Returns: AddCustomerResponse: Response from the API. default response Raises: APIException: When",
"_query_builder = Configuration.get_base_uri() _query_builder += _url_path _query_parameters = { 'onBehalfOf': on_behalf_of, 'purpose': purpose",
"the applicable implementation details for the following types...... - ach - aggregation Args:",
"APIHelper.append_url_with_query_parameters(_query_builder, _query_parameters, Configuration.array_serialization) _query_url = APIHelper.clean_url(_query_builder) # Prepare headers _headers = { 'Finicity-App-Key':",
"Below you’ll find how to generate the Connect link as well as where",
"from finicityapi.models.prequalification_report_record import PrequalificationReportRecord from finicityapi.models.pay_statement_report_record import PayStatementReportRecord from finicityapi.models.generate_connect_email_response_multiple_borrowers import GenerateConnectEmailResponseMultipleBorrowers from",
"an active customer, which is the actual owner of one or more real-world",
"implementation details for the following types...... - lite Args: accept (string): application/json, application/xml",
"retrieving this report. Returns: VOIReportRecord: Response from the API. OK Raises: APIException: When",
"possible parameters you can send for this endpoint depending on the use case.",
"URL _url_path = '/connect/v1/send/email' _query_builder = Configuration.get_base_uri() _query_builder += _url_path _query_url = APIHelper.clean_url(_query_builder)",
"'json' with 'xml' if preferred on_behalf_of (string, optional): The name of the entity",
"URL _url_path = '/decisioning/v1/consumers/{consumerId}/reports/{reportId}' _url_path = APIHelper.append_url_with_template_parameters(_url_path, { 'consumerId': consumer_id, 'reportId': report_id })",
"to specify what type of Finicity Connect you need depending on what will",
"when you generate a Connect link, to guarantee a full two hour life-span.",
"details on the flow. This documentation gives the applicable implementation details for the",
"'consumerId': consumer_id, 'reportId': report_id }) _query_builder = Configuration.get_base_uri() _query_builder += _url_path _query_parameters =",
"reason for retrieving this report. Returns: StatementReportRecord: Response from the API. OK Raises:",
"be generated as part of the connect flow unless otherwise specified. See the",
"For Send Connect Email service it does not support the types aggregation, lite",
"is finished. See Permissible Purpose Codes for a list of permissible purposes for",
"testing customer may only register accounts with FinBank institutions. Args: content_type (string): application/json,",
"Returns: AuditableReport: Response from the API. OK Raises: APIException: When an error occurs",
"Drive. Calls to this service before enrolling in a paid plan will return",
"def get_prequalification_voa_report_by_customer(self, customer_id, report_id, accept, content_type, on_behalf_of=None, purpose=None): \"\"\"Does a GET request to",
"code as 200. Args: customer_id (long|int): Finicity’s ID of the customer for the",
"length 32 characters) report_id (string): Finicity’s ID of the report accept (string): Replace",
"CustomerAccounts: Response from the API. default response Raises: APIException: When an error occurs",
"content_type, on_behalf_of=None, purpose=None): \"\"\"Does a GET request to /decisioning/v1/consumers/{consumerId}/reports/{reportId}. Get a report that",
"type return APIHelper.json_deserialize(_context.response.raw_body, TransactionsReportRecord.from_dictionary) def get_app_registration_status_v_1(self): \"\"\"Does a GET request to /aggregation/v1/partners/applications. Get",
"def get_pay_statement_extraction_by_customer(self, customer_id, report_id, accept, content_type, on_behalf_of=None, purpose=None): \"\"\"Does a GET request to",
"service is not available from the Test Drive. Calls to this service before",
"import BaseController from finicityapi.http.auth.custom_header_auth import CustomHeaderAuth from finicityapi.models.generate_connect_url_response import GenerateConnectURLResponse from finicityapi.models.customer_accounts import",
"reason for retrieving this report. Returns: VOAReportRecord: Response from the API. OK Raises:",
"Connect URL (Lite) Generate Finicity Connect URL (Fix) Args: accept (string): application/json, application/xml",
"URL _url_path = '/aggregation/v1/customers/testing' _query_builder = Configuration.get_base_uri() _query_builder += _url_path _query_url = APIHelper.clean_url(_query_builder)",
"Many times the type also corresponds to the report that will be run",
"this report. Returns: VOAWithIncomeReportRecord: Response from the API. OK Raises: APIException: When an",
"application/xml body (GenerateConnectURLRequestLite): Expected body to be sent with the request Returns: GenerateConnectURLResponse:",
"specifying the reason for retrieving this report. Returns: AuditableReport: Response from the API.",
"Validate required parameters self.validate_parameters(content_type=content_type, accept=accept, body=body) # Prepare query URL _url_path = '/aggregation/v1/customers/testing'",
"reason for retrieving this report. Returns: VOAWithIncomeReportRecord: Response from the API. OK Raises:",
"Raises: APIException: When an error occurs while fetching the data from the remote",
"the request Returns: GenerateConnectURLResponse: Response from the API. Raises: APIException: When an error",
"body): \"\"\"Does a POST request to /aggregation/v1/customers/active. This version 1 service has been",
"Permissible Purpose Codes, specifying the reason for retrieving this report. Returns: TransactionsReportRecord: Response",
"(string): application/json, application/xml body (GenerateConnectURLRequestDataAndPayments): Expected body to be sent with the request",
"for the following types...... - lite Args: accept (string): application/json, application/xml body (GenerateConnectURLRequestLite):",
"be migrated new_institution_id (long|int): New OAuth FI ID where accounts will be migrated",
"optional): 2-digit code from Permissible Purpose Codes, specifying the reason for retrieving this",
"= '/decisioning/v1/customers/{customerId}/reports/{reportId}' _url_path = APIHelper.append_url_with_template_parameters(_url_path, { 'customerId': customer_id, 'reportId': report_id }) _query_builder =",
"preferred on_behalf_of (string, optional): The name of the entity you are retrieving the",
"def generate_connect_url_lite(self, accept, body): \"\"\"Does a POST request to /connect/v1/generate. No matter how",
"Permissible Purpose Codes for a list of permissible purposes for retrieving a report.",
"request Returns: GenerateConnectEmailResponseMultipleBorrowers: Response from the API. Raises: APIException: When an error occurs",
"the reason for retrieving this report. Returns: PrequalificationReportRecord: Response from the API. OK",
"status of your application registration to access FI's with OAuth connections. Returns: AppStatusesV1:",
"the actual owner of one or more real-world accounts. This is a billable",
"_context) self.validate_response(_context) # Return appropriate type return APIHelper.json_deserialize(_context.response.raw_body, TransactionsReportRecord.from_dictionary) def get_transactions_report_by_consumer(self, consumer_id, report_id,",
"get_report_by_consumer(self, consumer_id, report_id, accept, content_type, on_behalf_of=None, purpose=None): \"\"\"Does a GET request to /decisioning/v1/consumers/{consumerId}/reports/{reportId}.",
"_context = self.execute_request(_request) self.validate_response(_context) # Return appropriate type return APIHelper.json_deserialize(_context.response.raw_body, AddCustomerResponse.from_dictionary) def generate_connect_url_data_and_payments_connect(self,",
"the call. Many times the type also corresponds to the report that will",
"flow unless otherwise specified. See the specific documentation for the types to see",
"get_transactions_report_by_customer(self, customer_id, report_id, accept, content_type, on_behalf_of=None, purpose=None): \"\"\"Does a GET request to /decisioning/v1/customers/{customerId}/reports/{reportId}.",
"with max length 32 characters) report_id (string): Finicity’s ID of the report accept",
"(Lending) Generate Finicity Connect URL (Lite) Generate Finicity Connect URL (Fix) Args: accept",
"report. Returns: VOIReportRecord: Response from the API. OK Raises: APIException: When an error",
"accept, body): \"\"\"Does a POST request to /connect/v1/generate. No matter how you plan",
"replaced with version 2 Enroll an active customer, which is the actual owner",
"APIHelper.json_deserialize(_context.response.raw_body, TransactionsReportRecord.from_dictionary) def get_transactions_report_by_consumer(self, consumer_id, report_id, accept, content_type, on_behalf_of=None, purpose=None): \"\"\"Does a GET",
"type return APIHelper.json_deserialize(_context.response.raw_body, VOAReportRecord.from_dictionary) def get_voie_txverify_report_by_customer(self, customer_id, report_id, accept, content_type, on_behalf_of=None, purpose=None): \"\"\"Does",
"400: raise Error1ErrorException('Bad Request', _context) self.validate_response(_context) # Return appropriate type return APIHelper.json_deserialize(_context.response.raw_body, TransactionsReportRecord.from_dictionary)",
"appropriate type return APIHelper.json_deserialize(_context.response.raw_body, VOIEPaystubWithTxverifyReportRecord.from_dictionary) def get_voi_report_by_consumer(self, consumer_id, report_id, accept, content_type, on_behalf_of=None, purpose=None):",
"# Validate required parameters self.validate_parameters(accept=accept, body=body) # Prepare query URL _url_path = '/connect/v1/generate'",
"= self.execute_request(_request) self.validate_response(_context) # Return appropriate type return APIHelper.json_deserialize(_context.response.raw_body, AddCustomerResponse.from_dictionary) def generate_connect_url_data_and_payments_connect(self, accept,",
"have generated the link it will only last until the authentication token under",
"self.validate_response(_context) # Return appropriate type return APIHelper.json_deserialize(_context.response.raw_body, VOAWithIncomeReportRecord.from_dictionary) def get_voa_with_income_report_by_customer(self, customer_id, report_id, accept,",
"on the use case. See the following more specific documentation for your use",
"is controlled by the “type” code in the call. Many times the type",
"the status of your application registration to access FI's with OAuth connections. Returns:",
"def get_voi_report_by_consumer(self, consumer_id, report_id, accept, content_type, on_behalf_of=None, purpose=None): \"\"\"Does a GET request to",
"APIHelper.json_deserialize(_context.response.raw_body, GenerateConnectURLResponse.from_dictionary) def generate_connect_url_fix(self, accept, body): \"\"\"Does a POST request to /connect/v1/generate. No",
"raise Error1ErrorException('Bad Request', _context) self.validate_response(_context) # Return appropriate type return APIHelper.json_deserialize(_context.response.raw_body, VOAReportRecord.from_dictionary) def",
"# Return appropriate type return APIHelper.json_deserialize(_context.response.raw_body, GenerateConnectURLResponse.from_dictionary) def migrate_institution_login_accounts_v_1(self, customer_id, institution_login_id, new_institution_id): \"\"\"Does",
"the Connect link as well as where to specify what type of Finicity",
"fetching the data from the remote API. This exception includes the HTTP Response",
"# Return appropriate type return APIHelper.json_deserialize(_context.response.raw_body, AppStatusesV1.from_dictionary) def get_statement_report_by_customer(self, customer_id, report_id, accept, content_type,",
"error message, and the HTTP body that was received in the request. \"\"\"",
"Finicity’s ID of the customer report_id (string): Finicity’s ID of the report accept",
"ID of the report accept (string): JSON or XML content_type (string): JSON or",
"finicityapi.models.auditable_report import AuditableReport from finicityapi.models.add_customer_response import AddCustomerResponse from finicityapi.models.voa_report_record import VOAReportRecord from finicityapi.models.voie_paystub_with_txverify_report_record",
"CustomHeaderAuth.apply(_request) _context = self.execute_request(_request) self.validate_response(_context) # Return appropriate type return APIHelper.json_deserialize(_context.response.raw_body, GenerateConnectEmailResponseMultipleBorrowers.from_dictionary) def",
"'Finicity-App-Key': Configuration.finicity_app_key, 'Accept': accept } # Prepare and execute request _request = self.http_client.post(_query_url,",
"request. \"\"\" # Validate required parameters self.validate_parameters(consumer_id=consumer_id, report_id=report_id, accept=accept, content_type=content_type) # Prepare query",
"you need. Once you have generated the link it will only last until",
"_context = self.execute_request(_request) self.validate_response(_context) # Return appropriate type return APIHelper.json_deserialize(_context.response.raw_body, CustomerAccounts.from_dictionary) def get_report_by_customer(self,",
"AddCustomerResponse.from_dictionary) def generate_connect_url_data_and_payments_connect(self, accept, body): \"\"\"Does a POST request to /connect/v1/generate. No matter",
"from finicityapi.controllers.base_controller import BaseController from finicityapi.http.auth.custom_header_auth import CustomHeaderAuth from finicityapi.models.generate_connect_url_response import GenerateConnectURLResponse from",
"see if the report is finished. See Permissible Purpose Codes for a list",
"controlled by the “type” code in the call. See the specific documentation for",
"the report on behalf of. purpose (string, optional): 2-digit code from Permissible Purpose",
"accounts institution_login_id (long|int): Finicity's institutionLoginId for the set of accounts to be migrated",
"this report. Returns: VOIReportRecord: Response from the API. OK Raises: APIException: When an",
"application/xml body (GenerateConnectURLRequestDataAndPayments): Expected body to be sent with the request Returns: GenerateConnectURLResponse:",
"The New Customer Returns: AddCustomerResponse: Response from the API. default response Raises: APIException:",
"(GenerateConnectURLRequestDataAndPayments): Expected body to be sent with the request Returns: GenerateConnectURLResponse: Response from",
"self.http_client.get(_query_url, headers=_headers) CustomHeaderAuth.apply(_request) _context = self.execute_request(_request) # Endpoint and global error handling using",
"headers=_headers) CustomHeaderAuth.apply(_request) _context = self.execute_request(_request) self.validate_response(_context) # Return appropriate type return APIHelper.json_deserialize(_context.response.raw_body, AppStatusesV1.from_dictionary)",
"that will be generated as part of the connect flow unless otherwise specified.",
"permissible purposes for retrieving a report. Args: customer_id (long|int): Finicity’s ID of the",
"in the request. \"\"\" # Validate required parameters self.validate_parameters(customer_id=customer_id, report_id=report_id, accept=accept, content_type=content_type) #",
"# Prepare headers _headers = { 'accept': 'application/json', 'Finicity-App-Key': Configuration.finicity_app_key } # Prepare",
"email to the customer which will contain a link to the connect flow.",
"payStatement - assetSummary - preQualVoa Args: accept (string): application/json, application/xml body (GenerateConnectURLRequestLending): Expected",
"'accept': 'application/json', 'Finicity-App-Key': Configuration.finicity_app_key } # Prepare and execute request _request = self.http_client.put(_query_url,",
"length 32 characters) report_id (string): Finicity’s ID of the report accept (string): JSON",
"case you are interested in as the documentation here is a list of",
"to guarantee a full two hour life-span. Several Finicity products utilize Finicity Connect,",
"request. \"\"\" # Prepare query URL _url_path = '/aggregation/v1/partners/applications' _query_builder = Configuration.get_base_uri() _query_builder",
"URL (Lending) Generate Finicity Connect URL (Lite) Generate Finicity Connect URL (Fix) Args:",
"link it will only last until the authentication token under which it was",
"New Customer Returns: AddCustomerResponse: Response from the API. default response Raises: APIException: When",
"import AppStatusesV1 from finicityapi.models.statement_report_record import StatementReportRecord from finicityapi.exceptions.error_1_error_exception import Error1ErrorException class DeprecatedController(BaseController): \"\"\"A",
"assetSummary - preQualVoa Args: accept (string): application/json, application/xml body (GenerateConnectURLRequestLending): Expected body to",
"accounts will be migrated Returns: CustomerAccounts: Response from the API. default response Raises:",
"a non email implementation. Args: accept (string): application/json body (GenerateConnectEmailRequest): Expected body to",
"Args: accept (string): application/json body (GenerateConnectEmailRequest): Expected body to be sent with the",
"Return appropriate type return APIHelper.json_deserialize(_context.response.raw_body, AuditableReport.from_dictionary) def add_testing_customer_v_1(self, content_type, accept, body): \"\"\"Does a",
"(string): Finicity’s ID of the report (UUID with max length 32 characters) accept",
"the HTTP body that was received in the request. \"\"\" # Prepare query",
"= self.http_client.put(_query_url, headers=_headers) CustomHeaderAuth.apply(_request) _context = self.execute_request(_request) self.validate_response(_context) # Return appropriate type return",
"API. Raises: APIException: When an error occurs while fetching the data from the",
"for retrieving this report. Returns: PayStatementReportRecord: Response from the API. OK Raises: APIException:",
"most products have their own type of Connect. The Connect type is controlled",
"URL (Fix) Args: accept (string): application/json, application/xml body (GenerateConnectURLRequest): Expected body to be",
"required parameters self.validate_parameters(consumer_id=consumer_id, report_id=report_id, accept=accept, content_type=content_type) # Prepare query URL _url_path = '/decisioning/v1/consumers/{consumerId}/reports/{reportId}'",
"new_institution_id): \"\"\"Does a PUT request to /aggregation/v1/customers/{customerId}/institutionLogins/{institutionLoginId}/institutions/{newInstitutionId}. This service has been replaced by",
"the reason for retrieving this report. Returns: VOIEPaystubWithTxverifyReportRecord: Response from the API. OK",
"Return appropriate type return APIHelper.json_deserialize(_context.response.raw_body, PayStatementReportRecord.from_dictionary) def add_customer_v_1(self, accept, content_type, body): \"\"\"Does a",
"type return APIHelper.json_deserialize(_context.response.raw_body, TransactionsReportRecord.from_dictionary) def get_transactions_report_by_consumer(self, consumer_id, report_id, accept, content_type, on_behalf_of=None, purpose=None): \"\"\"Does",
"as the documentation here is a list of all the possible parameters you",
"- voieStatement - payStatement - assetSummary - preQualVoa Args: accept (string): application/json, application/xml",
"self.execute_request(_request) self.validate_response(_context) # Return appropriate type return APIHelper.json_deserialize(_context.response.raw_body, AddCustomerResponse.from_dictionary) def get_voa_report_by_consumer(self, consumer_id, report_id,",
"VOAWithIncomeReportRecord from finicityapi.models.prequalification_report_record import PrequalificationReportRecord from finicityapi.models.pay_statement_report_record import PayStatementReportRecord from finicityapi.models.generate_connect_email_response_multiple_borrowers import GenerateConnectEmailResponseMultipleBorrowers",
"to /decisioning/v1/customers/{customerId}/reports/{reportId}. Get a report that has been generated by calling one of",
"# Return appropriate type return APIHelper.json_deserialize(_context.response.raw_body, VOIReportRecord.from_dictionary) def get_voi_report_by_customer(self, customer_id, report_id, accept, content_type,",
"finicityapi.exceptions.error_1_error_exception import Error1ErrorException class DeprecatedController(BaseController): \"\"\"A Controller to access Endpoints in the finicityapi",
"type return APIHelper.json_deserialize(_context.response.raw_body, PayStatementReportRecord.from_dictionary) def add_customer_v_1(self, accept, content_type, body): \"\"\"Does a POST request",
"in the request. \"\"\" # Validate required parameters self.validate_parameters(accept=accept, content_type=content_type, body=body) # Prepare",
"def get_voa_with_income_report_by_consumer(self, consumer_id, report_id, accept, content_type, on_behalf_of=None, purpose=None): \"\"\"Does a GET request to",
"the customer accounts and transaction data are gathered. Several Finicity products utilize Finicity",
"/aggregation/v1/partners/applications. Get the status of your application registration to access FI's with OAuth",
"Once you have generated the link it will only last until the authentication",
"Args: customer_id (long|int): Finicity’s ID of the customer for the institutionLoginId of accounts",
"def get_voie_txverify_report_by_customer(self, customer_id, report_id, accept, content_type, on_behalf_of=None, purpose=None): \"\"\"Does a GET request to",
"an error message, and the HTTP body that was received in the request.",
"in as the documentation here is a list of all the possible parameters",
"code from Permissible Purpose Codes, specifying the reason for retrieving this report. Returns:",
"finicityapi.http.auth.custom_header_auth import CustomHeaderAuth from finicityapi.models.generate_connect_url_response import GenerateConnectURLResponse from finicityapi.models.customer_accounts import CustomerAccounts from finicityapi.models.auditable_report",
"Return appropriate type return APIHelper.json_deserialize(_context.response.raw_body, GenerateConnectURLResponse.from_dictionary) def migrate_institution_login_accounts_v_1(self, customer_id, institution_login_id, new_institution_id): \"\"\"Does a",
"the set of accounts to be migrated new_institution_id (long|int): New OAuth FI ID",
"_url_path = '/aggregation/v1/customers/active' _query_builder = Configuration.get_base_uri() _query_builder += _url_path _query_url = APIHelper.clean_url(_query_builder) #",
"Args: accept (string): application/json, application/xml content_type (string): application/json, application/xml body (AddCustomerRequest): The Fields",
"of the report accept (string): Replace 'json' with 'xml' if preferred content_type (string):",
"from Permissible Purpose Codes, specifying the reason for retrieving this report. Returns: StatementReportRecord:",
"def add_customer_v_1(self, accept, content_type, body): \"\"\"Does a POST request to /aggregation/v1/customers/active. This version",
"using HTTP status codes. if _context.response.status_code == 400: raise Error1ErrorException('Bad Request', _context) self.validate_response(_context)",
"use case....... Generate Finicity Connect URL (Data and Payments) Generate Finicity Connect URL",
"was received in the request. \"\"\" # Validate required parameters self.validate_parameters(consumer_id=consumer_id, report_id=report_id, accept=accept,",
"Permissible Purpose Codes, specifying the reason for retrieving this report. Returns: StatementReportRecord: Response",
"to access Endpoints in the finicityapi API.\"\"\" def generate_connect_url_all_types(self, accept, body): \"\"\"Does a",
"is controlled by the “type” code in the call. See the specific documentation",
"on_behalf_of=None, purpose=None): \"\"\"Does a GET request to /decisioning/v1/customers/{customerId}/reports/{reportId}. Get a report that has",
"= '/aggregation/v1/customers/active' _query_builder = Configuration.get_base_uri() _query_builder += _url_path _query_url = APIHelper.clean_url(_query_builder) # Prepare",
"Validate required parameters self.validate_parameters(accept=accept, content_type=content_type, body=body) # Prepare query URL _url_path = '/aggregation/v1/customers/active'",
"type is controlled by the “type” code in the call. For lending, each",
"send for this endpoint depending on the use case. See the following more",
"with the request Returns: GenerateConnectEmailResponseMultipleBorrowers: Response from the API. Raises: APIException: When an",
"how to generate the Connect link as well as where to specify what",
"set of accounts to be migrated new_institution_id (long|int): New OAuth FI ID where",
"= APIHelper.clean_url(_query_builder) # Prepare headers _headers = { 'Finicity-App-Key': Configuration.finicity_app_key, 'Content-Type': content_type, 'Accept':",
"code, an error message, and the HTTP body that was received in the",
"on the flow. This documentation gives the applicable implementation details for the following",
"content_type } # Prepare and execute request _request = self.http_client.post(_query_url, headers=_headers, parameters=APIHelper.json_serialize(body)) CustomHeaderAuth.apply(_request)",
"the consumer (UUID with max length 32 characters) report_id (string): Finicity’s ID of",
"This is a billable customer. This service is not available from the Test",
"an email to the customer which will contain a link to the connect",
"return APIHelper.json_deserialize(_context.response.raw_body, VOAReportRecord.from_dictionary) def get_voie_txverify_report_by_customer(self, customer_id, report_id, accept, content_type, on_behalf_of=None, purpose=None): \"\"\"Does a",
"the finicityapi API.\"\"\" def generate_connect_url_all_types(self, accept, body): \"\"\"Does a POST request to /connect/v1/generate.",
"report that has been generated by calling one of the Generate Report services.",
"generated as part of the connect flow unless otherwise specified. See the specific",
"URL _url_path = '/aggregation/v1/customers/{customerId}/institutionLogins/{institutionLoginId}/institutions/{newInstitutionId}' _url_path = APIHelper.append_url_with_template_parameters(_url_path, { 'customerId': customer_id, 'institutionLoginId': institution_login_id, 'newInstitutionId':",
"Generate Report services. The report's status field will contain inProgress, failure, or success.",
"your application registration to access FI's with OAuth connections. Returns: AppStatusesV1: Response from",
"APIHelper.json_deserialize(_context.response.raw_body, VOIReportRecord.from_dictionary) def get_voi_report_by_customer(self, customer_id, report_id, accept, content_type, on_behalf_of=None, purpose=None): \"\"\"Does a GET",
"Endpoints in the finicityapi API.\"\"\" def generate_connect_url_all_types(self, accept, body): \"\"\"Does a POST request",
"VOIEPaystubWithTxverifyReportRecord: Response from the API. OK Raises: APIException: When an error occurs while",
"with max length 32 characters) report_id (string): Finicity’s ID of the report (UUID",
"data are gathered. Several Finicity products utilize Finicity Connect, and most products have",
"/connect/v1/send/email. A connect email sends an email to the customer which will contain",
"APIHelper.json_deserialize(_context.response.raw_body, GenerateConnectURLResponse.from_dictionary) def generate_connect_url_lending(self, accept, body): \"\"\"Does a POST request to /connect/v1/generate. No",
"from finicityapi.models.voa_report_record import VOAReportRecord from finicityapi.models.voie_paystub_with_txverify_report_record import VOIEPaystubWithTxverifyReportRecord from finicityapi.models.voi_report_record import VOIReportRecord from",
"to use the documentation for the specific use case you are interested in",
"once the customer accounts and transaction data are gathered. Several Finicity products utilize",
"new_institution_id }) _query_builder = Configuration.get_base_uri() _query_builder += _url_path _query_url = APIHelper.clean_url(_query_builder) # Prepare",
"_url_path _query_url = APIHelper.clean_url(_query_builder) # Prepare headers _headers = { 'content-type': 'application/json; charset=utf-8',",
"Several Finicity products utilize Finicity Connect, and most products have their own type",
"_context) self.validate_response(_context) # Return appropriate type return APIHelper.json_deserialize(_context.response.raw_body, VOIEPaystubWithTxverifyReportRecord.from_dictionary) def get_pay_statement_extraction_by_customer(self, customer_id, report_id,",
"link to the connect flow. You will need to specify what type of",
"and the HTTP body that was received in the request. \"\"\" # Prepare",
"error occurs while fetching the data from the remote API. This exception includes",
"the entity you are retrieving the report on behalf of. purpose (string, optional):",
"is controlled by the “type” code in the call. For lending, each type",
"# Validate required parameters self.validate_parameters(customer_id=customer_id, report_id=report_id, accept=accept, content_type=content_type) # Prepare query URL _url_path",
"_context = self.execute_request(_request) # Endpoint and global error handling using HTTP status codes.",
"Args: accept (string): application/json, application/xml body (GenerateConnectURLRequestLending): Expected body to be sent with",
"code in the call. Many times the type also corresponds to the report",
"successful API response will return a list of accounts for the given institution",
"consumer (UUID with max length 32 characters) report_id (string): Finicity’s ID of the",
"accounts and transaction data are gathered. Several Finicity products utilize Finicity Connect, and",
"Connect Email service it does not support the types aggregation, lite and fix.",
"gives the applicable implementation details for the following types...... - lite Args: accept",
"a list of all the possible parameters you can send for this endpoint",
"by the “type” code in the call. Many times the type also corresponds",
"(string): application/json, application/xml content_type (string): application/json, application/xml body (AddCustomerRequest): The Fields For The",
"code in the call. See the specific documentation for the types to see",
"for your use case....... Generate Finicity Connect URL (Data and Payments) Generate Finicity",
"and transaction data are gathered. Below you’ll find how to generate the Connect",
"and the HTTP body that was received in the request. \"\"\" # Validate",
"_url_path = '/aggregation/v1/customers/{customerId}/institutionLogins/{institutionLoginId}/institutions/{newInstitutionId}' _url_path = APIHelper.append_url_with_template_parameters(_url_path, { 'customerId': customer_id, 'institutionLoginId': institution_login_id, 'newInstitutionId': new_institution_id",
"appropriate type return APIHelper.json_deserialize(_context.response.raw_body, VOAReportRecord.from_dictionary) def get_voie_txverify_report_by_consumer(self, consumer_id, report_id, accept, content_type, on_behalf_of=None, purpose=None):",
"Error1ErrorException('Bad Request', _context) self.validate_response(_context) # Return appropriate type return APIHelper.json_deserialize(_context.response.raw_body, VOIReportRecord.from_dictionary) def get_voa_with_income_report_by_consumer(self,",
"AuditableReport from finicityapi.models.add_customer_response import AddCustomerResponse from finicityapi.models.voa_report_record import VOAReportRecord from finicityapi.models.voie_paystub_with_txverify_report_record import VOIEPaystubWithTxverifyReportRecord",
"and transaction data are gathered. Several Finicity products utilize Finicity Connect, and most",
"'accept': 'application/json', 'Finicity-App-Key': Configuration.finicity_app_key } # Prepare and execute request _request = self.http_client.get(_query_url,",
"this report. Returns: PayStatementReportRecord: Response from the API. OK Raises: APIException: When an",
"self.validate_response(_context) # Return appropriate type return APIHelper.json_deserialize(_context.response.raw_body, VOIEPaystubWithTxverifyReportRecord.from_dictionary) def get_pay_statement_extraction_by_customer(self, customer_id, report_id, accept,",
"of permissible purposes for retrieving a report. Args: consumer_id (string): Finicity’s ID of",
"VOIReportRecord from finicityapi.models.voa_with_income_report_record import VOAWithIncomeReportRecord from finicityapi.models.prequalification_report_record import PrequalificationReportRecord from finicityapi.models.pay_statement_report_record import PayStatementReportRecord",
"# Return appropriate type return APIHelper.json_deserialize(_context.response.raw_body, VOAReportRecord.from_dictionary) def get_voie_txverify_report_by_consumer(self, consumer_id, report_id, accept, content_type,",
"from finicityapi.models.auditable_report import AuditableReport from finicityapi.models.add_customer_response import AddCustomerResponse from finicityapi.models.voa_report_record import VOAReportRecord from",
"customer_id (long|int): Finicity’s ID of the customer for the institutionLoginId of accounts institution_login_id",
"accept (string): Replace 'json' with 'xml' if preferred content_type (string): Replace 'json' with",
"appropriate type return APIHelper.json_deserialize(_context.response.raw_body, TransactionsReportRecord.from_dictionary) def get_transactions_report_by_consumer(self, consumer_id, report_id, accept, content_type, on_behalf_of=None, purpose=None):",
"application/json, application/xml accept (string): application/json, application/xml body (AddCustomerRequest): The Fields For The New",
"API. This exception includes the HTTP Response code, an error message, and the",
"_context) self.validate_response(_context) # Return appropriate type return APIHelper.json_deserialize(_context.response.raw_body, PrequalificationReportRecord.from_dictionary) def get_pay_statement_by_consumer(self, consumer_id, report_id,",
"self.execute_request(_request) self.validate_response(_context) # Return appropriate type return APIHelper.json_deserialize(_context.response.raw_body, GenerateConnectURLResponse.from_dictionary) def generate_connect_url_lite(self, accept, body):",
"type return APIHelper.json_deserialize(_context.response.raw_body, StatementReportRecord.from_dictionary) def get_statement_report_by_consumer(self, consumer_id, report_id, accept, content_type, on_behalf_of=None, purpose=None): \"\"\"Does",
"this report. Returns: AuditableReport: Response from the API. OK Raises: APIException: When an",
"if the report is finished. See Permissible Purpose Codes for a list of",
"Permissible Purpose Codes, specifying the reason for retrieving this report. Returns: VOIReportRecord: Response",
"transaction data are gathered. Below you’ll find how to generate the Connect link",
"self.validate_response(_context) # Return appropriate type return APIHelper.json_deserialize(_context.response.raw_body, GenerateConnectURLResponse.from_dictionary) def generate_connect_url_lending(self, accept, body): \"\"\"Does",
"_context) self.validate_response(_context) # Return appropriate type return APIHelper.json_deserialize(_context.response.raw_body, AuditableReport.from_dictionary) def add_testing_customer_v_1(self, content_type, accept,",
"type return APIHelper.json_deserialize(_context.response.raw_body, PrequalificationReportRecord.from_dictionary) def get_pay_statement_by_consumer(self, consumer_id, report_id, accept, content_type, on_behalf_of=None, purpose=None): \"\"\"Does",
"documentation gives the applicable implementation details for the following types...... - voa -",
"finicityapi.models.prequalification_report_record import PrequalificationReportRecord from finicityapi.models.pay_statement_report_record import PayStatementReportRecord from finicityapi.models.generate_connect_email_response_multiple_borrowers import GenerateConnectEmailResponseMultipleBorrowers from finicityapi.models.transactions_report_record",
"what type of Finicity Connect you need depending on what will happen once",
"body to be sent with the request Returns: GenerateConnectURLResponse: Response from the API.",
"BaseController from finicityapi.http.auth.custom_header_auth import CustomHeaderAuth from finicityapi.models.generate_connect_url_response import GenerateConnectURLResponse from finicityapi.models.customer_accounts import CustomerAccounts",
"the reason for retrieving this report. Returns: AuditableReport: Response from the API. OK",
"type return APIHelper.json_deserialize(_context.response.raw_body, GenerateConnectURLResponse.from_dictionary) def generate_connect_url_lending(self, accept, body): \"\"\"Does a POST request to",
"body (GenerateConnectURLRequestFix): Expected body to be sent with the request Returns: GenerateConnectURLResponse: Response",
"request to /aggregation/v1/customers/{customerId}/institutionLogins/{institutionLoginId}/institutions/{newInstitutionId}. This service has been replaced by version 2 call now",
"generate_connect_url_data_and_payments_connect(self, accept, body): \"\"\"Does a POST request to /connect/v1/generate. No matter how you",
"# Endpoint and global error handling using HTTP status codes. if _context.response.status_code ==",
"= APIHelper.append_url_with_template_parameters(_url_path, { 'customerId': customer_id, 'reportId': report_id }) _query_builder = Configuration.get_base_uri() _query_builder +=",
"specifying the reason for retrieving this report. Returns: VOIReportRecord: Response from the API.",
"application/xml body (GenerateConnectURLRequestFix): Expected body to be sent with the request Returns: GenerateConnectURLResponse:",
"= Configuration.get_base_uri() _query_builder += _url_path _query_parameters = { 'onBehalfOf': on_behalf_of, 'purpose': purpose }",
"(Lending) for additional details on a non email implementation. Args: accept (string): application/json",
"'onBehalfOf': on_behalf_of, 'purpose': purpose } _query_builder = APIHelper.append_url_with_query_parameters(_query_builder, _query_parameters, Configuration.array_serialization) _query_url = APIHelper.clean_url(_query_builder)",
"_context) self.validate_response(_context) # Return appropriate type return APIHelper.json_deserialize(_context.response.raw_body, VOAReportRecord.from_dictionary) def get_voie_txverify_report_by_consumer(self, consumer_id, report_id,",
"_query_url = APIHelper.clean_url(_query_builder) # Prepare headers _headers = { 'content-type': 'application/json; charset=utf-8', 'Finicity-App-Key':",
"(string): JSON or XML content_type (string): JSON or XML on_behalf_of (string, optional): The",
"'Accept': accept, 'Content-Type': content_type } # Prepare and execute request _request = self.http_client.post(_query_url,",
"Codes, specifying the reason for retrieving this report. Returns: PayStatementReportRecord: Response from the",
"specifying the reason for retrieving this report. Returns: VOAWithIncomeReportRecord: Response from the API.",
"FinBank institutions. Args: content_type (string): application/json, application/xml accept (string): application/json, application/xml body (AddCustomerRequest):",
"retrieving a report. Args: customer_id (long|int): Finicity’s ID of the customer report_id (string):",
"occurs while fetching the data from the remote API. This exception includes the",
"OAuth FI ID where accounts will be migrated Returns: CustomerAccounts: Response from the",
"accept, content_type, on_behalf_of=None, purpose=None): \"\"\"Does a GET request to /decisioning/v1/customers/{customerId}/reports/{reportId}. Get a report",
"- payStatement - assetSummary - preQualVoa Args: accept (string): application/json, application/xml body (GenerateConnectURLRequestLending):",
"_context) self.validate_response(_context) # Return appropriate type return APIHelper.json_deserialize(_context.response.raw_body, PayStatementReportRecord.from_dictionary) def get_voa_report_by_customer(self, customer_id, report_id,",
"self.execute_request(_request) self.validate_response(_context) # Return appropriate type return APIHelper.json_deserialize(_context.response.raw_body, AddCustomerResponse.from_dictionary) def generate_connect_url_data_and_payments_connect(self, accept, body):",
"accounts and transaction data are gathered. Below you’ll find how to generate the",
"field will contain inProgress, failure, or success. If the status shows inProgress, the",
"Permissible Purpose Codes, specifying the reason for retrieving this report. Returns: VOAReportRecord: Response",
"get_voa_with_income_report_by_customer(self, customer_id, report_id, accept, content_type, on_behalf_of=None, purpose=None): \"\"\"Does a GET request to /decisioning/v1/customers/{customerId}/reports/{reportId}.",
"authentication token under which it was generated expires. After that you will need",
"_query_builder = Configuration.get_base_uri() _query_builder += _url_path _query_url = APIHelper.clean_url(_query_builder) # Prepare headers _headers",
"on behalf of. purpose (string, optional): 2-digit code from Permissible Purpose Codes, specifying",
"body (AddCustomerRequest): The Fields For The New Customer Returns: AddCustomerResponse: Response from the",
"Request', _context) self.validate_response(_context) # Return appropriate type return APIHelper.json_deserialize(_context.response.raw_body, VOAReportRecord.from_dictionary) def get_voie_txverify_report_by_customer(self, customer_id,",
"report. Returns: AuditableReport: Response from the API. OK Raises: APIException: When an error",
"\"\"\" # Validate required parameters self.validate_parameters(consumer_id=consumer_id, report_id=report_id, accept=accept, content_type=content_type) # Prepare query URL",
"the call. For lending, each type signifies a report that will be generated",
"\"\"\"Does a GET request to /decisioning/v1/customers/{customerId}/reports/{reportId}. Get a report that has been generated",
"(Fix) Args: accept (string): application/json, application/xml body (GenerateConnectURLRequest): Expected body to be sent",
"from the API. OK Raises: APIException: When an error occurs while fetching the",
"generate the Connect link as well as where to specify what type of",
"content_type } # Prepare and execute request _request = self.http_client.get(_query_url, headers=_headers) CustomHeaderAuth.apply(_request) _context",
"for the following types...... - voa - voahistory - voi - voieTxVerify -",
"specific use case you are interested in as the documentation here is a",
"# Prepare headers _headers = { 'Finicity-App-Key': Configuration.finicity_app_key, 'Content-Type': content_type, 'Accept': accept }",
"Return appropriate type return APIHelper.json_deserialize(_context.response.raw_body, StatementReportRecord.from_dictionary) def get_statement_report_by_consumer(self, consumer_id, report_id, accept, content_type, on_behalf_of=None,",
"in the call. See the specific documentation for the types to see more",
"as part of the connect flow unless otherwise specified. See the specific documentation",
"'Content-Type': content_type, 'Accept': accept } # Prepare and execute request _request = self.http_client.post(_query_url,",
"content_type=content_type, body=body) # Prepare query URL _url_path = '/aggregation/v1/customers/active' _query_builder = Configuration.get_base_uri() _query_builder",
"each type signifies a report that will be generated as part of the",
"import CustomerAccounts from finicityapi.models.auditable_report import AuditableReport from finicityapi.models.add_customer_response import AddCustomerResponse from finicityapi.models.voa_report_record import",
"# Return appropriate type return APIHelper.json_deserialize(_context.response.raw_body, GenerateConnectURLResponse.from_dictionary) def generate_connect_url_fix(self, accept, body): \"\"\"Does a",
"1 service has been replaced with version 2 Enroll an active customer, which",
"details for the following types...... - ach - aggregation Args: accept (string): application/json,",
"\"\"\"Does a POST request to /connect/v1/send/email. A connect email sends an email to",
"from Permissible Purpose Codes, specifying the reason for retrieving this report. Returns: PayStatementReportRecord:",
"'institutionLoginId': institution_login_id, 'newInstitutionId': new_institution_id }) _query_builder = Configuration.get_base_uri() _query_builder += _url_path _query_url =",
"lite and fix. See the endpoint Generate Finicity Connect URL (Lending) for additional",
"for the set of accounts to be migrated new_institution_id (long|int): New OAuth FI",
"request. \"\"\" # Validate required parameters self.validate_parameters(content_type=content_type, accept=accept, body=body) # Prepare query URL",
"and retrieve a Finicity Connect Link. You will need to specify what type",
"register accounts with FinBank institutions. Args: content_type (string): application/json, application/xml accept (string): application/json,",
"Accounts\" This service is to migrate accounts from legacy FI to new OAuth",
"appropriate type return APIHelper.json_deserialize(_context.response.raw_body, AddCustomerResponse.from_dictionary) def get_voa_report_by_consumer(self, consumer_id, report_id, accept, content_type, on_behalf_of=None, purpose=None):",
"accept, content_type, body): \"\"\"Does a POST request to /aggregation/v1/customers/active. This version 1 service",
"the reason for retrieving this report. Returns: VOAReportRecord: Response from the API. OK",
"ID of the report accept (string): Replace 'json' with 'xml' if preferred content_type",
"accept (string): JSON or XML content_type (string): JSON or XML on_behalf_of (string, optional):",
"ID of the report (UUID with max length 32 characters) accept (string): Replace",
"GenerateConnectURLResponse.from_dictionary) def migrate_institution_login_accounts_v_1(self, customer_id, institution_login_id, new_institution_id): \"\"\"Does a PUT request to /aggregation/v1/customers/{customerId}/institutionLogins/{institutionLoginId}/institutions/{newInstitutionId}. This",
"(string): Finicity’s ID of the report accept (string): JSON or XML content_type (string):",
"following types...... - ach - aggregation Args: accept (string): application/json, application/xml body (GenerateConnectURLRequestDataAndPayments):",
"If the status shows inProgress, the client app should wait 20 seconds and",
"retrieving this report. Returns: VOIEPaystubWithTxverifyReportRecord: Response from the API. OK Raises: APIException: When",
"body): \"\"\"Does a POST request to /aggregation/v1/customers/testing. Enroll a testing customer. A testing",
"finicityapi.configuration import Configuration from finicityapi.controllers.base_controller import BaseController from finicityapi.http.auth.custom_header_auth import CustomHeaderAuth from finicityapi.models.generate_connect_url_response",
"Request', _context) self.validate_response(_context) # Return appropriate type return APIHelper.json_deserialize(_context.response.raw_body, AuditableReport.from_dictionary) def add_testing_customer_v_1(self, content_type,",
"query URL _url_path = '/aggregation/v1/customers/{customerId}/institutionLogins/{institutionLoginId}/institutions/{newInstitutionId}' _url_path = APIHelper.append_url_with_template_parameters(_url_path, { 'customerId': customer_id, 'institutionLoginId': institution_login_id,",
"Error1ErrorException('Bad Request', _context) self.validate_response(_context) # Return appropriate type return APIHelper.json_deserialize(_context.response.raw_body, VOIEPaystubWithTxverifyReportRecord.from_dictionary) def get_pay_statement_extraction_by_customer(self,",
"accept (string): application/json, application/xml body (AddCustomerRequest): The Fields For The New Testing Customer",
"following more specific documentation for your use case....... Generate Finicity Connect URL (Data",
"of Finicity Connect you need depending on what will happen once the customer",
"voa - voahistory - voi - voieTxVerify - voieStatement - payStatement - assetSummary",
"# Return appropriate type return APIHelper.json_deserialize(_context.response.raw_body, GenerateConnectURLResponse.from_dictionary) def send_connect_email(self, accept, body): \"\"\"Does a",
"Calls to this service before enrolling in a paid plan will return HTTP",
"has been replaced with version 2 Enroll an active customer, which is the",
"to /aggregation/v1/customers/{customerId}/institutionLogins/{institutionLoginId}/institutions/{newInstitutionId}. This service has been replaced by version 2 call now \"Migrate",
"of the customer report_id (string): Finicity’s ID of the report (UUID with max",
"parameters self.validate_parameters(consumer_id=consumer_id, report_id=report_id, accept=accept, content_type=content_type) # Prepare query URL _url_path = '/decisioning/v1/consumers/{consumerId}/reports/{reportId}' _url_path",
"matter how you plan on implementing Finicity Connect, you’ll need to generate and",
"on_behalf_of (string, optional): The name of the entity you are retrieving the report",
"return APIHelper.json_deserialize(_context.response.raw_body, PrequalificationReportRecord.from_dictionary) def get_prequalification_report_by_consumer(self, consumer_id, report_id, accept, content_type, on_behalf_of=None, purpose=None): \"\"\"Does a",
"and execute request _request = self.http_client.put(_query_url, headers=_headers) CustomHeaderAuth.apply(_request) _context = self.execute_request(_request) self.validate_response(_context) #",
"Error1ErrorException('Bad Request', _context) self.validate_response(_context) # Return appropriate type return APIHelper.json_deserialize(_context.response.raw_body, VOAReportRecord.from_dictionary) def get_voie_txverify_report_by_customer(self,",
"APIHelper.json_deserialize(_context.response.raw_body, VOAReportRecord.from_dictionary) def get_voie_txverify_report_by_customer(self, customer_id, report_id, accept, content_type, on_behalf_of=None, purpose=None): \"\"\"Does a GET",
"body): \"\"\"Does a POST request to /connect/v1/send/email. A connect email sends an email",
"a GET request to /aggregation/v1/partners/applications. Get the status of your application registration to",
"of the report (UUID with max length 32 characters) accept (string): Replace 'json'",
"def generate_connect_url_fix(self, accept, body): \"\"\"Does a POST request to /connect/v1/generate. No matter how",
"finicityapi.models.pay_statement_report_record import PayStatementReportRecord from finicityapi.models.generate_connect_email_response_multiple_borrowers import GenerateConnectEmailResponseMultipleBorrowers from finicityapi.models.transactions_report_record import TransactionsReportRecord from finicityapi.models.app_statuses_v_1",
"appropriate type return APIHelper.json_deserialize(_context.response.raw_body, CustomerAccounts.from_dictionary) def get_report_by_customer(self, customer_id, report_id, accept, content_type, on_behalf_of=None, purpose=None):",
"body that was received in the request. \"\"\" # Validate required parameters self.validate_parameters(accept=accept,",
"The Fields For The New Customer Returns: AddCustomerResponse: Response from the API. default",
"received in the request. \"\"\" # Prepare query URL _url_path = '/aggregation/v1/partners/applications' _query_builder",
"add_customer_v_1(self, accept, content_type, body): \"\"\"Does a POST request to /aggregation/v1/customers/active. This version 1",
"Replace 'json' with 'xml' if preferred content_type (string): Replace 'json' with 'xml' if",
"Returns: CustomerAccounts: Response from the API. default response Raises: APIException: When an error",
"application/json, application/xml body (AddCustomerRequest): The Fields For The New Testing Customer Returns: AddCustomerResponse:",
"def get_transactions_report_by_consumer(self, consumer_id, report_id, accept, content_type, on_behalf_of=None, purpose=None): \"\"\"Does a GET request to",
"Purpose Codes, specifying the reason for retrieving this report. Returns: VOAReportRecord: Response from",
"self.validate_response(_context) # Return appropriate type return APIHelper.json_deserialize(_context.response.raw_body, TransactionsReportRecord.from_dictionary) def get_app_registration_status_v_1(self): \"\"\"Does a GET",
"self.execute_request(_request) self.validate_response(_context) # Return appropriate type return APIHelper.json_deserialize(_context.response.raw_body, GenerateConnectURLResponse.from_dictionary) def migrate_institution_login_accounts_v_1(self, customer_id, institution_login_id,",
"Get the status of your application registration to access FI's with OAuth connections.",
"\"\"\"Does a GET request to /decisioning/v1/consumers/{consumerId}/reports/{reportId}. Get a report that has been generated",
"following types...... - fix Args: accept (string): application/json, application/xml body (GenerateConnectURLRequestFix): Expected body",
"products utilize Finicity Connect, and most products have their own type of Connect.",
"received in the request. \"\"\" # Validate required parameters self.validate_parameters(content_type=content_type, accept=accept, body=body) #",
"= APIHelper.append_url_with_template_parameters(_url_path, { 'consumerId': consumer_id, 'reportId': report_id }) _query_builder = Configuration.get_base_uri() _query_builder +=",
"Link. You will need to specify what type of Finicity Connect you need",
"StatementReportRecord from finicityapi.exceptions.error_1_error_exception import Error1ErrorException class DeprecatedController(BaseController): \"\"\"A Controller to access Endpoints in",
"for retrieving this report. Returns: VOIReportRecord: Response from the API. OK Raises: APIException:",
"call now \"Migrate Institution Login Accounts\" This service is to migrate accounts from",
"FI ID where accounts will be migrated Returns: CustomerAccounts: Response from the API.",
"customer which will contain a link to the connect flow. You will need",
"Return appropriate type return APIHelper.json_deserialize(_context.response.raw_body, GenerateConnectEmailResponseMultipleBorrowers.from_dictionary) def get_transactions_report_by_customer(self, customer_id, report_id, accept, content_type, on_behalf_of=None,",
"for retrieving a report. Args: consumer_id (string): Finicity’s ID of the consumer (UUID",
"how you plan on implementing Finicity Connect, you’ll need to generate and retrieve",
"reason for retrieving this report. Returns: TransactionsReportRecord: Response from the API. OK Raises:",
"from the Test Drive. Calls to this service before enrolling in a paid",
"more specific documentation for your use case....... Generate Finicity Connect URL (Data and",
"The name of the entity you are retrieving the report on behalf of.",
"gathered. Several Finicity products utilize Finicity Connect, and most products have their own",
"Generate Finicity Connect URL (Lending) for additional details on a non email implementation.",
"for retrieving this report. Returns: VOIEPaystubWithTxverifyReportRecord: Response from the API. OK Raises: APIException:",
"finicityapi.models.voi_report_record import VOIReportRecord from finicityapi.models.voa_with_income_report_record import VOAWithIncomeReportRecord from finicityapi.models.prequalification_report_record import PrequalificationReportRecord from finicityapi.models.pay_statement_report_record",
"self.validate_response(_context) # Return appropriate type return APIHelper.json_deserialize(_context.response.raw_body, GenerateConnectEmailResponseMultipleBorrowers.from_dictionary) def get_transactions_report_by_customer(self, customer_id, report_id, accept,",
"URL _url_path = '/decisioning/v1/customers/{customerId}/reports/{reportId}' _url_path = APIHelper.append_url_with_template_parameters(_url_path, { 'customerId': customer_id, 'reportId': report_id })",
"two hour life-span. Several Finicity products utilize Finicity Connect, and most products have",
"return APIHelper.json_deserialize(_context.response.raw_body, CustomerAccounts.from_dictionary) def get_report_by_customer(self, customer_id, report_id, accept, content_type, on_behalf_of=None, purpose=None): \"\"\"Does a",
"the flow. This documentation gives the applicable implementation details for the following types......",
"in the call. For lending, each type signifies a report that will be",
"# Return appropriate type return APIHelper.json_deserialize(_context.response.raw_body, VOAWithIncomeReportRecord.from_dictionary) def get_voa_with_income_report_by_customer(self, customer_id, report_id, accept, content_type,",
"and Payments) Generate Finicity Connect URL (Lending) Generate Finicity Connect URL (Lite) Generate",
"actual owner of one or more real-world accounts. This is a billable customer.",
"from finicityapi.models.voi_report_record import VOIReportRecord from finicityapi.models.voa_with_income_report_record import VOAWithIncomeReportRecord from finicityapi.models.prequalification_report_record import PrequalificationReportRecord from",
"this endpoint depending on the use case. See the following more specific documentation",
"of accounts to be migrated new_institution_id (long|int): New OAuth FI ID where accounts",
"the types to see more details on the flow. This documentation gives the",
"def get_transactions_report_by_customer(self, customer_id, report_id, accept, content_type, on_behalf_of=None, purpose=None): \"\"\"Does a GET request to",
"accept (string): application/json, application/xml body (GenerateConnectURLRequestDataAndPayments): Expected body to be sent with the",
"\"\"\" # Validate required parameters self.validate_parameters(content_type=content_type, accept=accept, body=body) # Prepare query URL _url_path",
"a report that has been generated by calling one of the Generate Report",
"you can send for this endpoint depending on the use case. See the",
"\"\"\"Does a PUT request to /aggregation/v1/customers/{customerId}/institutionLogins/{institutionLoginId}/institutions/{newInstitutionId}. This service has been replaced by version",
"active customer, which is the actual owner of one or more real-world accounts.",
"and execute request _request = self.http_client.post(_query_url, headers=_headers, parameters=APIHelper.json_serialize(body)) CustomHeaderAuth.apply(_request) _context = self.execute_request(_request) self.validate_response(_context)",
"'Content-Type': content_type } # Prepare and execute request _request = self.http_client.get(_query_url, headers=_headers) CustomHeaderAuth.apply(_request)",
"with FinBank institutions. Args: content_type (string): application/json, application/xml accept (string): application/json, application/xml body",
"for a list of permissible purposes for retrieving a report. Args: consumer_id (string):",
"Args: content_type (string): application/json, application/xml accept (string): application/json, application/xml body (AddCustomerRequest): The Fields",
"voieStatement - payStatement - assetSummary - preQualVoa Args: accept (string): application/json, application/xml body",
"request to /aggregation/v1/customers/testing. Enroll a testing customer. A testing customer may only register",
"VOAReportRecord: Response from the API. OK Raises: APIException: When an error occurs while",
"# Return appropriate type return APIHelper.json_deserialize(_context.response.raw_body, VOIEPaystubWithTxverifyReportRecord.from_dictionary) def get_voi_report_by_consumer(self, consumer_id, report_id, accept, content_type,",
"Return appropriate type return APIHelper.json_deserialize(_context.response.raw_body, AppStatusesV1.from_dictionary) def get_statement_report_by_customer(self, customer_id, report_id, accept, content_type, on_behalf_of=None,",
"Finicity's institutionLoginId for the set of accounts to be migrated new_institution_id (long|int): New",
"= { 'Finicity-App-Key': Configuration.finicity_app_key, 'Accept': accept, 'Content-Type': content_type } # Prepare and execute",
"'application/json; charset=utf-8', 'Finicity-App-Key': Configuration.finicity_app_key, 'Accept': accept } # Prepare and execute request _request",
"a PUT request to /aggregation/v1/customers/{customerId}/institutionLogins/{institutionLoginId}/institutions/{newInstitutionId}. This service has been replaced by version 2",
"type of Connect. The Connect type is controlled by the “type” code in",
"customer may only register accounts with FinBank institutions. Args: content_type (string): application/json, application/xml",
"status codes. if _context.response.status_code == 400: raise Error1ErrorException('Bad Request', _context) self.validate_response(_context) # Return",
"Purpose Codes for a list of permissible purposes for retrieving a report. Args:",
"VOAWithIncomeReportRecord: Response from the API. OK Raises: APIException: When an error occurs while",
"enrolling in a paid plan will return HTTP 429 (Too Many Requests). Args:",
"The Connect type is controlled by the “type” code in the call. For",
"interested in as the documentation here is a list of all the possible",
"service has been replaced by version 2 call now \"Migrate Institution Login Accounts\"",
"get_pay_statement_extraction_by_customer(self, customer_id, report_id, accept, content_type, on_behalf_of=None, purpose=None): \"\"\"Does a GET request to /decisioning/v1/customers/{customerId}/reports/{reportId}.",
"list of permissible purposes for retrieving a report. Args: customer_id (long|int): Finicity’s ID",
"accept=accept, content_type=content_type) # Prepare query URL _url_path = '/decisioning/v1/consumers/{consumerId}/reports/{reportId}' _url_path = APIHelper.append_url_with_template_parameters(_url_path, {",
"life-span. Several Finicity products utilize Finicity Connect, and most products have their own",
"wait 20 seconds and then call again to see if the report is",
"this report. Returns: TransactionsReportRecord: Response from the API. OK Raises: APIException: When an",
"is to migrate accounts from legacy FI to new OAuth FI. A successful",
"self.validate_response(_context) # Return appropriate type return APIHelper.json_deserialize(_context.response.raw_body, PayStatementReportRecord.from_dictionary) def add_customer_v_1(self, accept, content_type, body):",
"generate_connect_url_lite(self, accept, body): \"\"\"Does a POST request to /connect/v1/generate. No matter how you",
"import APIHelper from finicityapi.configuration import Configuration from finicityapi.controllers.base_controller import BaseController from finicityapi.http.auth.custom_header_auth import",
"= Configuration.get_base_uri() _query_builder += _url_path _query_url = APIHelper.clean_url(_query_builder) # Prepare headers _headers =",
"institution_login_id (long|int): Finicity's institutionLoginId for the set of accounts to be migrated new_institution_id",
"Prepare query URL _url_path = '/aggregation/v1/partners/applications' _query_builder = Configuration.get_base_uri() _query_builder += _url_path _query_url",
"the Connect flow. It is best to use the documentation for the specific",
"the customer report_id (string): Finicity’s ID of the report (UUID with max length",
"accept (string): application/json, application/xml body (GenerateConnectURLRequestFix): Expected body to be sent with the",
"32 characters) accept (string): Replace 'json' with 'xml' if preferred content_type (string): Replace",
"a testing customer. A testing customer may only register accounts with FinBank institutions.",
"VOAWithIncomeReportRecord.from_dictionary) def get_voa_with_income_report_by_customer(self, customer_id, report_id, accept, content_type, on_behalf_of=None, purpose=None): \"\"\"Does a GET request",
"get_voa_report_by_customer(self, customer_id, report_id, accept, content_type, on_behalf_of=None, purpose=None): \"\"\"Does a GET request to /decisioning/v1/customers/{customerId}/reports/{reportId}.",
"(string, optional): 2-digit code from Permissible Purpose Codes, specifying the reason for retrieving",
"the given institution login id with an http status code as 200. Args:",
"_context = self.execute_request(_request) self.validate_response(_context) # Return appropriate type return APIHelper.json_deserialize(_context.response.raw_body, AddCustomerResponse.from_dictionary) def get_voa_report_by_consumer(self,",
"VOIEPaystubWithTxverifyReportRecord.from_dictionary) def get_voi_report_by_consumer(self, consumer_id, report_id, accept, content_type, on_behalf_of=None, purpose=None): \"\"\"Does a GET request",
"Returns: VOIEPaystubWithTxverifyReportRecord: Response from the API. OK Raises: APIException: When an error occurs",
"FI to new OAuth FI. A successful API response will return a list",
"the report accept (string): JSON or XML content_type (string): JSON or XML on_behalf_of",
"Return appropriate type return APIHelper.json_deserialize(_context.response.raw_body, VOIEPaystubWithTxverifyReportRecord.from_dictionary) def get_pay_statement_extraction_by_customer(self, customer_id, report_id, accept, content_type, on_behalf_of=None,",
"body (GenerateConnectURLRequest): Expected body to be sent with the request Returns: GenerateConnectURLResponse: Response",
"\"\"\"Does a POST request to /aggregation/v1/customers/testing. Enroll a testing customer. A testing customer",
"self.validate_response(_context) # Return appropriate type return APIHelper.json_deserialize(_context.response.raw_body, PrequalificationReportRecord.from_dictionary) def get_pay_statement_by_consumer(self, consumer_id, report_id, accept,",
"appropriate type return APIHelper.json_deserialize(_context.response.raw_body, AppStatusesV1.from_dictionary) def get_statement_report_by_customer(self, customer_id, report_id, accept, content_type, on_behalf_of=None, purpose=None):",
"on_behalf_of=None, purpose=None): \"\"\"Does a GET request to /decisioning/v1/consumers/{consumerId}/reports/{reportId}. Get a report that has",
"report_id (string): Finicity’s ID of the report accept (string): JSON or XML content_type",
"Permissible Purpose Codes, specifying the reason for retrieving this report. Returns: AuditableReport: Response",
"(long|int): New OAuth FI ID where accounts will be migrated Returns: CustomerAccounts: Response",
"permissible purposes for retrieving a report. Args: consumer_id (string): Finicity’s ID of the",
"specific documentation for your use case....... Generate Finicity Connect URL (Data and Payments)",
"Args: accept (string): application/json, application/xml body (GenerateConnectURLRequestFix): Expected body to be sent with",
"finicityapi.models.add_customer_response import AddCustomerResponse from finicityapi.models.voa_report_record import VOAReportRecord from finicityapi.models.voie_paystub_with_txverify_report_record import VOIEPaystubWithTxverifyReportRecord from finicityapi.models.voi_report_record",
"retrieving this report. Returns: PrequalificationReportRecord: Response from the API. OK Raises: APIException: When",
"under a new authentication token. We recommend generating a new authentication token when",
"return APIHelper.json_deserialize(_context.response.raw_body, GenerateConnectURLResponse.from_dictionary) def generate_connect_url_lite(self, accept, body): \"\"\"Does a POST request to /connect/v1/generate.",
"it will only last until the authentication token under which it was generated",
"- voa - voahistory - voi - voieTxVerify - voieStatement - payStatement -",
"parameters self.validate_parameters(customer_id=customer_id, institution_login_id=institution_login_id, new_institution_id=new_institution_id) # Prepare query URL _url_path = '/aggregation/v1/customers/{customerId}/institutionLogins/{institutionLoginId}/institutions/{newInstitutionId}' _url_path =",
"sent with the request Returns: GenerateConnectEmailResponseMultipleBorrowers: Response from the API. Raises: APIException: When",
"“type” code in the call. See the specific documentation for the types to",
"= '/aggregation/v1/customers/testing' _query_builder = Configuration.get_base_uri() _query_builder += _url_path _query_url = APIHelper.clean_url(_query_builder) # Prepare",
"guarantee a full two hour life-span. Several Finicity products utilize Finicity Connect, and",
"_url_path = '/connect/v1/send/email' _query_builder = Configuration.get_base_uri() _query_builder += _url_path _query_url = APIHelper.clean_url(_query_builder) #",
"before enrolling in a paid plan will return HTTP 429 (Too Many Requests).",
"is a billable customer. This service is not available from the Test Drive.",
"/decisioning/v1/consumers/{consumerId}/reports/{reportId}. Get a report that has been generated by calling one of the",
"'application/json', 'Finicity-App-Key': Configuration.finicity_app_key } # Prepare and execute request _request = self.http_client.get(_query_url, headers=_headers)",
"purpose=None): \"\"\"Does a GET request to /decisioning/v1/customers/{customerId}/reports/{reportId}. Get a report that has been",
"request Returns: GenerateConnectURLResponse: Response from the API. Raises: APIException: When an error occurs",
"_request = self.http_client.post(_query_url, headers=_headers, parameters=APIHelper.json_serialize(body)) CustomHeaderAuth.apply(_request) _context = self.execute_request(_request) self.validate_response(_context) # Return appropriate",
"ID of the customer report_id (string): Finicity’s ID of the report accept (string):",
"self.execute_request(_request) self.validate_response(_context) # Return appropriate type return APIHelper.json_deserialize(_context.response.raw_body, GenerateConnectURLResponse.from_dictionary) def generate_connect_url_fix(self, accept, body):",
"Request', _context) self.validate_response(_context) # Return appropriate type return APIHelper.json_deserialize(_context.response.raw_body, PrequalificationReportRecord.from_dictionary) def get_pay_statement_by_consumer(self, consumer_id,",
"until the authentication token under which it was generated expires. After that you",
"a report. Args: customer_id (long|int): Finicity’s ID of the customer report_id (string): Finicity’s",
"accept (string): application/json body (GenerateConnectEmailRequest): Expected body to be sent with the request",
"add_testing_customer_v_1(self, content_type, accept, body): \"\"\"Does a POST request to /aggregation/v1/customers/testing. Enroll a testing",
"400: raise Error1ErrorException('Bad Request', _context) self.validate_response(_context) # Return appropriate type return APIHelper.json_deserialize(_context.response.raw_body, VOAReportRecord.from_dictionary)",
"need depending on what will happen once the customer accounts and transaction data",
"Return appropriate type return APIHelper.json_deserialize(_context.response.raw_body, VOIReportRecord.from_dictionary) def get_voa_with_income_report_by_consumer(self, consumer_id, report_id, accept, content_type, on_behalf_of=None,",
"APIHelper.json_deserialize(_context.response.raw_body, GenerateConnectURLResponse.from_dictionary) def migrate_institution_login_accounts_v_1(self, customer_id, institution_login_id, new_institution_id): \"\"\"Does a PUT request to /aggregation/v1/customers/{customerId}/institutionLogins/{institutionLoginId}/institutions/{newInstitutionId}.",
"Finicity Connect URL (Fix) Args: accept (string): application/json, application/xml body (GenerateConnectURLRequest): Expected body",
"get_report_by_customer(self, customer_id, report_id, accept, content_type, on_behalf_of=None, purpose=None): \"\"\"Does a GET request to /decisioning/v1/customers/{customerId}/reports/{reportId}.",
"an http status code as 200. Args: customer_id (long|int): Finicity’s ID of the",
"Configuration.array_serialization) _query_url = APIHelper.clean_url(_query_builder) # Prepare headers _headers = { 'Finicity-App-Key': Configuration.finicity_app_key, 'Accept':",
"in the request. \"\"\" # Validate required parameters self.validate_parameters(consumer_id=consumer_id, report_id=report_id, accept=accept, content_type=content_type) #",
"are interested in as the documentation here is a list of all the",
"Error1ErrorException('Bad Request', _context) self.validate_response(_context) # Return appropriate type return APIHelper.json_deserialize(_context.response.raw_body, AuditableReport.from_dictionary) def add_testing_customer_v_1(self,",
"seconds and then call again to see if the report is finished. See",
"to be migrated new_institution_id (long|int): New OAuth FI ID where accounts will be",
"fix. See the endpoint Generate Finicity Connect URL (Lending) for additional details on",
"APIHelper.append_url_with_template_parameters(_url_path, { 'customerId': customer_id, 'reportId': report_id }) _query_builder = Configuration.get_base_uri() _query_builder += _url_path",
"behalf of. purpose (string, optional): 2-digit code from Permissible Purpose Codes, specifying the",
"customer_id (long|int): Finicity’s ID of the customer report_id (string): Finicity’s ID of the",
"as well as where to specify what type of Finicity Connect you need.",
"Fields For The New Testing Customer Returns: AddCustomerResponse: Response from the API. default",
"Returns: AppStatusesV1: Response from the API. Raises: APIException: When an error occurs while",
"appropriate type return APIHelper.json_deserialize(_context.response.raw_body, VOIEPaystubWithTxverifyReportRecord.from_dictionary) def get_pay_statement_extraction_by_customer(self, customer_id, report_id, accept, content_type, on_behalf_of=None, purpose=None):",
"AppStatusesV1 from finicityapi.models.statement_report_record import StatementReportRecord from finicityapi.exceptions.error_1_error_exception import Error1ErrorException class DeprecatedController(BaseController): \"\"\"A Controller",
"GET request to /decisioning/v1/customers/{customerId}/reports/{reportId}. Get a report that has been generated by calling",
"is best to use the documentation for the specific use case you are",
"use case. See the following more specific documentation for your use case....... Generate",
"Args: customer_id (long|int): Finicity’s ID of the customer report_id (string): Finicity’s ID of",
"report_id (string): Finicity’s ID of the report accept (string): Replace 'json' with 'xml'",
"real-world accounts. This is a billable customer. This service is not available from",
"HTTP body that was received in the request. \"\"\" # Prepare query URL",
"PrequalificationReportRecord.from_dictionary) def get_pay_statement_by_consumer(self, consumer_id, report_id, accept, content_type, on_behalf_of=None, purpose=None): \"\"\"Does a GET request",
"/connect/v1/generate. No matter how you plan on implementing Finicity Connect, you’ll need to",
"lite Args: accept (string): application/json, application/xml body (GenerateConnectURLRequestLite): Expected body to be sent",
"TransactionsReportRecord.from_dictionary) def get_transactions_report_by_consumer(self, consumer_id, report_id, accept, content_type, on_behalf_of=None, purpose=None): \"\"\"Does a GET request",
"headers _headers = { 'Finicity-App-Key': Configuration.finicity_app_key, 'Accept': accept, 'Content-Type': content_type } # Prepare",
"APIHelper.append_url_with_template_parameters(_url_path, { 'consumerId': consumer_id, 'reportId': report_id }) _query_builder = Configuration.get_base_uri() _query_builder += _url_path",
"_url_path = APIHelper.append_url_with_template_parameters(_url_path, { 'consumerId': consumer_id, 'reportId': report_id }) _query_builder = Configuration.get_base_uri() _query_builder",
"been replaced with version 2 Enroll an active customer, which is the actual",
"includes the HTTP Response code, an error message, and the HTTP body that",
"Error1ErrorException('Bad Request', _context) self.validate_response(_context) # Return appropriate type return APIHelper.json_deserialize(_context.response.raw_body, PayStatementReportRecord.from_dictionary) def add_customer_v_1(self,",
"(GenerateConnectURLRequest): Expected body to be sent with the request Returns: GenerateConnectURLResponse: Response from",
"\"\"\" # Validate required parameters self.validate_parameters(customer_id=customer_id, report_id=report_id, accept=accept, content_type=content_type) # Prepare query URL",
"from finicityapi.models.voa_with_income_report_record import VOAWithIncomeReportRecord from finicityapi.models.prequalification_report_record import PrequalificationReportRecord from finicityapi.models.pay_statement_report_record import PayStatementReportRecord from",
"APIHelper.json_deserialize(_context.response.raw_body, PrequalificationReportRecord.from_dictionary) def get_pay_statement_by_consumer(self, consumer_id, report_id, accept, content_type, on_behalf_of=None, purpose=None): \"\"\"Does a GET",
"connect flow. You will need to specify what type of Finicity Connect you",
"400: raise Error1ErrorException('Bad Request', _context) self.validate_response(_context) # Return appropriate type return APIHelper.json_deserialize(_context.response.raw_body, StatementReportRecord.from_dictionary)",
"AuditableReport.from_dictionary) def get_report_by_consumer(self, consumer_id, report_id, accept, content_type, on_behalf_of=None, purpose=None): \"\"\"Does a GET request",
"run upon completing the Connect flow. It is best to use the documentation",
"application/json, application/xml body (AddCustomerRequest): The Fields For The New Customer Returns: AddCustomerResponse: Response",
"PayStatementReportRecord from finicityapi.models.generate_connect_email_response_multiple_borrowers import GenerateConnectEmailResponseMultipleBorrowers from finicityapi.models.transactions_report_record import TransactionsReportRecord from finicityapi.models.app_statuses_v_1 import AppStatusesV1",
"access Endpoints in the finicityapi API.\"\"\" def generate_connect_url_all_types(self, accept, body): \"\"\"Does a POST",
"Finicity’s ID of the report (UUID with max length 32 characters) accept (string):",
"then call again to see if the report is finished. See Permissible Purpose",
"APIHelper.json_deserialize(_context.response.raw_body, AddCustomerResponse.from_dictionary) def generate_connect_url_data_and_payments_connect(self, accept, body): \"\"\"Does a POST request to /connect/v1/generate. No",
"upon completing the Connect flow. It is best to use the documentation for",
"own type of Connect. The Connect type is controlled by the “type” code",
"to the report that will be run upon completing the Connect flow. It",
"finicityapi.models.app_statuses_v_1 import AppStatusesV1 from finicityapi.models.statement_report_record import StatementReportRecord from finicityapi.exceptions.error_1_error_exception import Error1ErrorException class DeprecatedController(BaseController):",
"def generate_connect_url_all_types(self, accept, body): \"\"\"Does a POST request to /connect/v1/generate. No matter how",
"A testing customer may only register accounts with FinBank institutions. Args: content_type (string):",
"CustomHeaderAuth.apply(_request) _context = self.execute_request(_request) self.validate_response(_context) # Return appropriate type return APIHelper.json_deserialize(_context.response.raw_body, CustomerAccounts.from_dictionary) def",
"for retrieving this report. Returns: TransactionsReportRecord: Response from the API. OK Raises: APIException:",
"GenerateConnectEmailResponseMultipleBorrowers from finicityapi.models.transactions_report_record import TransactionsReportRecord from finicityapi.models.app_statuses_v_1 import AppStatusesV1 from finicityapi.models.statement_report_record import StatementReportRecord",
"= { 'accept': 'application/json', 'Finicity-App-Key': Configuration.finicity_app_key } # Prepare and execute request _request",
"return APIHelper.json_deserialize(_context.response.raw_body, VOAWithIncomeReportRecord.from_dictionary) def get_prequalification_voa_report_by_customer(self, customer_id, report_id, accept, content_type, on_behalf_of=None, purpose=None): \"\"\"Does a",
"= '/connect/v1/send/email' _query_builder = Configuration.get_base_uri() _query_builder += _url_path _query_url = APIHelper.clean_url(_query_builder) # Prepare",
"(Too Many Requests). Args: accept (string): application/json, application/xml content_type (string): application/json, application/xml body",
"application/xml body (AddCustomerRequest): The Fields For The New Testing Customer Returns: AddCustomerResponse: Response",
"2 Enroll an active customer, which is the actual owner of one or",
"required parameters self.validate_parameters(customer_id=customer_id, report_id=report_id, accept=accept, content_type=content_type) # Prepare query URL _url_path = '/decisioning/v1/customers/{customerId}/reports/{reportId}'",
"accept, body): \"\"\"Does a POST request to /aggregation/v1/customers/testing. Enroll a testing customer. A",
"the data from the remote API. This exception includes the HTTP Response code,",
"request. \"\"\" # Validate required parameters self.validate_parameters(accept=accept, body=body) # Prepare query URL _url_path",
"raise Error1ErrorException('Bad Request', _context) self.validate_response(_context) # Return appropriate type return APIHelper.json_deserialize(_context.response.raw_body, TransactionsReportRecord.from_dictionary) def",
"We recommend generating a new authentication token when you generate a Connect link,",
"get_voa_with_income_report_by_consumer(self, consumer_id, report_id, accept, content_type, on_behalf_of=None, purpose=None): \"\"\"Does a GET request to /decisioning/v1/consumers/{consumerId}/reports/{reportId}.",
"contain inProgress, failure, or success. If the status shows inProgress, the client app",
"entity you are retrieving the report on behalf of. purpose (string, optional): 2-digit",
"def get_report_by_customer(self, customer_id, report_id, accept, content_type, on_behalf_of=None, purpose=None): \"\"\"Does a GET request to",
"codes. if _context.response.status_code == 400: raise Error1ErrorException('Bad Request', _context) self.validate_response(_context) # Return appropriate",
"the endpoint Generate Finicity Connect URL (Lending) for additional details on a non",
"parameters you can send for this endpoint depending on the use case. See",
"endpoint depending on the use case. See the following more specific documentation for",
"reason for retrieving this report. Returns: PrequalificationReportRecord: Response from the API. OK Raises:",
"/aggregation/v1/customers/testing. Enroll a testing customer. A testing customer may only register accounts with",
"# Prepare query URL _url_path = '/aggregation/v1/customers/active' _query_builder = Configuration.get_base_uri() _query_builder += _url_path",
"TransactionsReportRecord: Response from the API. OK Raises: APIException: When an error occurs while",
"Connect URL (Data and Payments) Generate Finicity Connect URL (Lending) Generate Finicity Connect",
"Error1ErrorException class DeprecatedController(BaseController): \"\"\"A Controller to access Endpoints in the finicityapi API.\"\"\" def",
"POST request to /aggregation/v1/customers/active. This version 1 service has been replaced with version",
"See the endpoint Generate Finicity Connect URL (Lending) for additional details on a",
"for retrieving this report. Returns: PrequalificationReportRecord: Response from the API. OK Raises: APIException:",
"(Data and Payments) Generate Finicity Connect URL (Lending) Generate Finicity Connect URL (Lite)",
"headers=_headers) CustomHeaderAuth.apply(_request) _context = self.execute_request(_request) self.validate_response(_context) # Return appropriate type return APIHelper.json_deserialize(_context.response.raw_body, CustomerAccounts.from_dictionary)",
"characters) report_id (string): Finicity’s ID of the report (UUID with max length 32",
"following types...... - voa - voahistory - voi - voieTxVerify - voieStatement -",
"by calling one of the Generate Report services. The report's status field will",
"accept (string): application/json, application/xml body (GenerateConnectURLRequestLite): Expected body to be sent with the",
"you are interested in as the documentation here is a list of all",
"type return APIHelper.json_deserialize(_context.response.raw_body, VOIEPaystubWithTxverifyReportRecord.from_dictionary) def get_pay_statement_extraction_by_customer(self, customer_id, report_id, accept, content_type, on_behalf_of=None, purpose=None): \"\"\"Does",
"def get_statement_report_by_customer(self, customer_id, report_id, accept, content_type, on_behalf_of=None, purpose=None): \"\"\"Does a GET request to",
"to /connect/v1/send/email. A connect email sends an email to the customer which will",
"gives the applicable implementation details for the following types...... - voa - voahistory",
"Request', _context) self.validate_response(_context) # Return appropriate type return APIHelper.json_deserialize(_context.response.raw_body, VOIReportRecord.from_dictionary) def get_voa_with_income_report_by_consumer(self, consumer_id,",
"CustomHeaderAuth.apply(_request) _context = self.execute_request(_request) # Endpoint and global error handling using HTTP status",
"from Permissible Purpose Codes, specifying the reason for retrieving this report. Returns: VOIReportRecord:",
"need to regenerate the Connect link under a new authentication token. We recommend",
"new authentication token when you generate a Connect link, to guarantee a full",
"customer, which is the actual owner of one or more real-world accounts. This",
"status shows inProgress, the client app should wait 20 seconds and then call",
"# Return appropriate type return APIHelper.json_deserialize(_context.response.raw_body, AuditableReport.from_dictionary) def get_report_by_consumer(self, consumer_id, report_id, accept, content_type,",
"from Permissible Purpose Codes, specifying the reason for retrieving this report. Returns: TransactionsReportRecord:",
"You will need to specify what type of Finicity Connect you need depending",
"in the call. Many times the type also corresponds to the report that",
"is not available from the Test Drive. Calls to this service before enrolling",
"+= _url_path _query_url = APIHelper.clean_url(_query_builder) # Prepare headers _headers = { 'Finicity-App-Key': Configuration.finicity_app_key,",
"parameters self.validate_parameters(accept=accept, content_type=content_type, body=body) # Prepare query URL _url_path = '/aggregation/v1/customers/active' _query_builder =",
"of all the possible parameters you can send for this endpoint depending on",
"will happen once the customer accounts and transaction data are gathered. Several Finicity",
"that was received in the request. \"\"\" # Prepare query URL _url_path =",
"will be migrated Returns: CustomerAccounts: Response from the API. default response Raises: APIException:",
"signifies a report that will be generated as part of the connect flow",
"in the request. \"\"\" # Validate required parameters self.validate_parameters(accept=accept, body=body) # Prepare query",
"= '/decisioning/v1/consumers/{consumerId}/reports/{reportId}' _url_path = APIHelper.append_url_with_template_parameters(_url_path, { 'consumerId': consumer_id, 'reportId': report_id }) _query_builder =",
"'Accept': accept } # Prepare and execute request _request = self.http_client.post(_query_url, headers=_headers, parameters=APIHelper.json_serialize(body))",
"Codes, specifying the reason for retrieving this report. Returns: PrequalificationReportRecord: Response from the",
"Return appropriate type return APIHelper.json_deserialize(_context.response.raw_body, TransactionsReportRecord.from_dictionary) def get_transactions_report_by_consumer(self, consumer_id, report_id, accept, content_type, on_behalf_of=None,",
"the Connect link under a new authentication token. We recommend generating a new",
"finicityapi.models.voie_paystub_with_txverify_report_record import VOIEPaystubWithTxverifyReportRecord from finicityapi.models.voi_report_record import VOIReportRecord from finicityapi.models.voa_with_income_report_record import VOAWithIncomeReportRecord from finicityapi.models.prequalification_report_record",
"POST request to /connect/v1/generate. No matter how you plan on implementing Finicity Connect,",
"the request. \"\"\" # Validate required parameters self.validate_parameters(customer_id=customer_id, institution_login_id=institution_login_id, new_institution_id=new_institution_id) # Prepare query",
"received in the request. \"\"\" # Validate required parameters self.validate_parameters(consumer_id=consumer_id, report_id=report_id, accept=accept, content_type=content_type)",
"type return APIHelper.json_deserialize(_context.response.raw_body, GenerateConnectURLResponse.from_dictionary) def generate_connect_url_lite(self, accept, body): \"\"\"Does a POST request to",
"import CustomHeaderAuth from finicityapi.models.generate_connect_url_response import GenerateConnectURLResponse from finicityapi.models.customer_accounts import CustomerAccounts from finicityapi.models.auditable_report import",
"32 characters) report_id (string): Finicity’s ID of the report (UUID with max length",
"report is finished. See Permissible Purpose Codes for a list of permissible purposes",
"use case you are interested in as the documentation here is a list",
"new_institution_id=new_institution_id) # Prepare query URL _url_path = '/aggregation/v1/customers/{customerId}/institutionLogins/{institutionLoginId}/institutions/{newInstitutionId}' _url_path = APIHelper.append_url_with_template_parameters(_url_path, { 'customerId':",
"Return appropriate type return APIHelper.json_deserialize(_context.response.raw_body, CustomerAccounts.from_dictionary) def get_report_by_customer(self, customer_id, report_id, accept, content_type, on_behalf_of=None,",
"a POST request to /connect/v1/send/email. A connect email sends an email to the",
"return APIHelper.json_deserialize(_context.response.raw_body, PrequalificationReportRecord.from_dictionary) def get_pay_statement_by_consumer(self, consumer_id, report_id, accept, content_type, on_behalf_of=None, purpose=None): \"\"\"Does a",
"plan on implementing Finicity Connect, you’ll need to generate and retrieve a Finicity",
"report accept (string): JSON or XML content_type (string): JSON or XML on_behalf_of (string,",
"happen once the customer accounts and transaction data are gathered. Below you’ll find",
"'purpose': purpose } _query_builder = APIHelper.append_url_with_query_parameters(_query_builder, _query_parameters, Configuration.array_serialization) _query_url = APIHelper.clean_url(_query_builder) # Prepare",
"of the customer report_id (string): Finicity’s ID of the report accept (string): Replace",
"implementation details for the following types...... - voa - voahistory - voi -"
] |
[
"bound, upper bound, decay rate, cycle length. structure = [784, 256, 128, 10,",
"import perceptron as pc import numpy as np def mnist_load(file, samples): raw_data =",
"labels = raw_data[:,0] data = np.delete(raw_data, 0, 1)/255.0 return (data, labels) def main():",
"= mnist_load(\"mnist_train.csv\", samples) validate = mnist_load(\"mnist_test.csv\", samples) restart_params = (.0001, 0.01, 0.01, 2*samples/batch_size)",
"= 20 train = mnist_load(\"mnist_train.csv\", samples) validate = mnist_load(\"mnist_test.csv\", samples) restart_params = (.0001,",
"import numpy as np def mnist_load(file, samples): raw_data = np.array(np.genfromtxt(file, delimiter=',', max_rows=samples)) labels",
"np.delete(raw_data, 0, 1)/255.0 return (data, labels) def main(): print(\"loading data...\") samples = 10000",
"256, 128, 10, 10] activation_functions = (\"elu\", \"elu\", \"elu\", \"softmax\") network = pc.network(structure,",
"upper bound, decay rate, cycle length. structure = [784, 256, 128, 10, 10]",
"= (\"elu\", \"elu\", \"elu\", \"softmax\") network = pc.network(structure, activation_functions, train, validate) network.train(dropout=[.5, .2,",
"= (.0001, 0.01, 0.01, 2*samples/batch_size) #lower bound, upper bound, decay rate, cycle length.",
"decay rate, cycle length. structure = [784, 256, 128, 10, 10] activation_functions =",
"= 10000 batch_size = 20 train = mnist_load(\"mnist_train.csv\", samples) validate = mnist_load(\"mnist_test.csv\", samples)",
"numpy as np def mnist_load(file, samples): raw_data = np.array(np.genfromtxt(file, delimiter=',', max_rows=samples)) labels =",
"raw_data = np.array(np.genfromtxt(file, delimiter=',', max_rows=samples)) labels = raw_data[:,0] data = np.delete(raw_data, 0, 1)/255.0",
"activation_functions = (\"elu\", \"elu\", \"elu\", \"softmax\") network = pc.network(structure, activation_functions, train, validate) network.train(dropout=[.5,",
"= np.array(np.genfromtxt(file, delimiter=',', max_rows=samples)) labels = raw_data[:,0] data = np.delete(raw_data, 0, 1)/255.0 return",
"train, validate) network.train(dropout=[.5, .2, 0], beta=0.9, lr_func=\"warm restarts\", lr_params=restart_params, batch_size=batch_size, epochs=10, cost_func=\"cross entropy\")",
"mnist_load(\"mnist_test.csv\", samples) restart_params = (.0001, 0.01, 0.01, 2*samples/batch_size) #lower bound, upper bound, decay",
"20 train = mnist_load(\"mnist_train.csv\", samples) validate = mnist_load(\"mnist_test.csv\", samples) restart_params = (.0001, 0.01,",
"train = mnist_load(\"mnist_train.csv\", samples) validate = mnist_load(\"mnist_test.csv\", samples) restart_params = (.0001, 0.01, 0.01,",
"0.01, 0.01, 2*samples/batch_size) #lower bound, upper bound, decay rate, cycle length. structure =",
"= np.delete(raw_data, 0, 1)/255.0 return (data, labels) def main(): print(\"loading data...\") samples =",
"np.array(np.genfromtxt(file, delimiter=',', max_rows=samples)) labels = raw_data[:,0] data = np.delete(raw_data, 0, 1)/255.0 return (data,",
"cycle length. structure = [784, 256, 128, 10, 10] activation_functions = (\"elu\", \"elu\",",
"samples): raw_data = np.array(np.genfromtxt(file, delimiter=',', max_rows=samples)) labels = raw_data[:,0] data = np.delete(raw_data, 0,",
"bound, decay rate, cycle length. structure = [784, 256, 128, 10, 10] activation_functions",
"validate = mnist_load(\"mnist_test.csv\", samples) restart_params = (.0001, 0.01, 0.01, 2*samples/batch_size) #lower bound, upper",
"samples = 10000 batch_size = 20 train = mnist_load(\"mnist_train.csv\", samples) validate = mnist_load(\"mnist_test.csv\",",
"(.0001, 0.01, 0.01, 2*samples/batch_size) #lower bound, upper bound, decay rate, cycle length. structure",
"labels) def main(): print(\"loading data...\") samples = 10000 batch_size = 20 train =",
"(data, labels) def main(): print(\"loading data...\") samples = 10000 batch_size = 20 train",
"samples) validate = mnist_load(\"mnist_test.csv\", samples) restart_params = (.0001, 0.01, 0.01, 2*samples/batch_size) #lower bound,",
"length. structure = [784, 256, 128, 10, 10] activation_functions = (\"elu\", \"elu\", \"elu\",",
"data = np.delete(raw_data, 0, 1)/255.0 return (data, labels) def main(): print(\"loading data...\") samples",
"as np def mnist_load(file, samples): raw_data = np.array(np.genfromtxt(file, delimiter=',', max_rows=samples)) labels = raw_data[:,0]",
"2*samples/batch_size) #lower bound, upper bound, decay rate, cycle length. structure = [784, 256,",
"pc import numpy as np def mnist_load(file, samples): raw_data = np.array(np.genfromtxt(file, delimiter=',', max_rows=samples))",
"validate) network.train(dropout=[.5, .2, 0], beta=0.9, lr_func=\"warm restarts\", lr_params=restart_params, batch_size=batch_size, epochs=10, cost_func=\"cross entropy\") main()",
"#lower bound, upper bound, decay rate, cycle length. structure = [784, 256, 128,",
"= mnist_load(\"mnist_test.csv\", samples) restart_params = (.0001, 0.01, 0.01, 2*samples/batch_size) #lower bound, upper bound,",
"mnist_load(\"mnist_train.csv\", samples) validate = mnist_load(\"mnist_test.csv\", samples) restart_params = (.0001, 0.01, 0.01, 2*samples/batch_size) #lower",
"128, 10, 10] activation_functions = (\"elu\", \"elu\", \"elu\", \"softmax\") network = pc.network(structure, activation_functions,",
"(\"elu\", \"elu\", \"elu\", \"softmax\") network = pc.network(structure, activation_functions, train, validate) network.train(dropout=[.5, .2, 0],",
"= pc.network(structure, activation_functions, train, validate) network.train(dropout=[.5, .2, 0], beta=0.9, lr_func=\"warm restarts\", lr_params=restart_params, batch_size=batch_size,",
"\"elu\", \"softmax\") network = pc.network(structure, activation_functions, train, validate) network.train(dropout=[.5, .2, 0], beta=0.9, lr_func=\"warm",
"print(\"loading data...\") samples = 10000 batch_size = 20 train = mnist_load(\"mnist_train.csv\", samples) validate",
"[784, 256, 128, 10, 10] activation_functions = (\"elu\", \"elu\", \"elu\", \"softmax\") network =",
"raw_data[:,0] data = np.delete(raw_data, 0, 1)/255.0 return (data, labels) def main(): print(\"loading data...\")",
"pc.network(structure, activation_functions, train, validate) network.train(dropout=[.5, .2, 0], beta=0.9, lr_func=\"warm restarts\", lr_params=restart_params, batch_size=batch_size, epochs=10,",
"10] activation_functions = (\"elu\", \"elu\", \"elu\", \"softmax\") network = pc.network(structure, activation_functions, train, validate)",
"structure = [784, 256, 128, 10, 10] activation_functions = (\"elu\", \"elu\", \"elu\", \"softmax\")",
"\"elu\", \"elu\", \"softmax\") network = pc.network(structure, activation_functions, train, validate) network.train(dropout=[.5, .2, 0], beta=0.9,",
"\"softmax\") network = pc.network(structure, activation_functions, train, validate) network.train(dropout=[.5, .2, 0], beta=0.9, lr_func=\"warm restarts\",",
"= raw_data[:,0] data = np.delete(raw_data, 0, 1)/255.0 return (data, labels) def main(): print(\"loading",
"main(): print(\"loading data...\") samples = 10000 batch_size = 20 train = mnist_load(\"mnist_train.csv\", samples)",
"def main(): print(\"loading data...\") samples = 10000 batch_size = 20 train = mnist_load(\"mnist_train.csv\",",
"batch_size = 20 train = mnist_load(\"mnist_train.csv\", samples) validate = mnist_load(\"mnist_test.csv\", samples) restart_params =",
"samples) restart_params = (.0001, 0.01, 0.01, 2*samples/batch_size) #lower bound, upper bound, decay rate,",
"restart_params = (.0001, 0.01, 0.01, 2*samples/batch_size) #lower bound, upper bound, decay rate, cycle",
"return (data, labels) def main(): print(\"loading data...\") samples = 10000 batch_size = 20",
"data...\") samples = 10000 batch_size = 20 train = mnist_load(\"mnist_train.csv\", samples) validate =",
"10000 batch_size = 20 train = mnist_load(\"mnist_train.csv\", samples) validate = mnist_load(\"mnist_test.csv\", samples) restart_params",
"def mnist_load(file, samples): raw_data = np.array(np.genfromtxt(file, delimiter=',', max_rows=samples)) labels = raw_data[:,0] data =",
"perceptron as pc import numpy as np def mnist_load(file, samples): raw_data = np.array(np.genfromtxt(file,",
"mnist_load(file, samples): raw_data = np.array(np.genfromtxt(file, delimiter=',', max_rows=samples)) labels = raw_data[:,0] data = np.delete(raw_data,",
"as pc import numpy as np def mnist_load(file, samples): raw_data = np.array(np.genfromtxt(file, delimiter=',',",
"np def mnist_load(file, samples): raw_data = np.array(np.genfromtxt(file, delimiter=',', max_rows=samples)) labels = raw_data[:,0] data",
"10, 10] activation_functions = (\"elu\", \"elu\", \"elu\", \"softmax\") network = pc.network(structure, activation_functions, train,",
"activation_functions, train, validate) network.train(dropout=[.5, .2, 0], beta=0.9, lr_func=\"warm restarts\", lr_params=restart_params, batch_size=batch_size, epochs=10, cost_func=\"cross",
"= [784, 256, 128, 10, 10] activation_functions = (\"elu\", \"elu\", \"elu\", \"softmax\") network",
"max_rows=samples)) labels = raw_data[:,0] data = np.delete(raw_data, 0, 1)/255.0 return (data, labels) def",
"0.01, 2*samples/batch_size) #lower bound, upper bound, decay rate, cycle length. structure = [784,",
"delimiter=',', max_rows=samples)) labels = raw_data[:,0] data = np.delete(raw_data, 0, 1)/255.0 return (data, labels)",
"rate, cycle length. structure = [784, 256, 128, 10, 10] activation_functions = (\"elu\",",
"1)/255.0 return (data, labels) def main(): print(\"loading data...\") samples = 10000 batch_size =",
"network = pc.network(structure, activation_functions, train, validate) network.train(dropout=[.5, .2, 0], beta=0.9, lr_func=\"warm restarts\", lr_params=restart_params,",
"0, 1)/255.0 return (data, labels) def main(): print(\"loading data...\") samples = 10000 batch_size"
] |
[
"path = j.sals.fs.join_paths(self.repo_dir, self.repo_name) j.sals.process.execute(f\"git add {file1_name}\", cwd=path) self.git_client.commit(\"commit file 1\", add_all=False) self.info(\"Check",
"self.info(\"Check if a new file has been added\") added_file = self.git_client.get_modified_files() self.assertTrue(added_file) self.assertEqual(file_name,",
"a file in repository path\") file_name = self.random_name() path = j.sals.fs.join_paths(self.repo_dir, self.repo_name, file_name)",
"\"\"\"Test case for pulling a repository **Test Scenario** - Get a git client.",
"client. - Create a file in repository path. - Commit changes - modify",
"self.assertEqual(self.git_client.remote_url, repo_ssh_url) self.assertIn(self.git_client.remote_url, git_config) def test03_git_branch(self): \"\"\"Test case for checking a branch name.",
"branch name\") self.assertIn(self.git_client.branch_name, branch_name[1]) def test04_git_modified_files(self): \"\"\"Test case for getting the modified files.",
"\"\"\"Test case for checking a branch name. **Test Scenario** - Get a git",
"git client. - Create a file in repository path. - Commit changes -",
"changes\") self.git_client.commit(f\"add {file_name}\") self.info(\"modify this file\") path = j.sals.fs.join_paths(self.repo_dir, self.repo_name, file_name) j.sals.fs.write_file(path, \"test",
"log -1\", cwd=path) self.info(\"Check if commit has been done\") self.assertIn(commit_msg, str(last_commit)) def test07_git_commit_one_file(self):",
"j.sals.fs.read_file(path) self.info(\"Check that remote_url equal to repo_url\") self.assertEqual(self.repo_url, self.git_client.remote_url) self.info(\"Check that git config",
"j.sals.fs.join_paths(self.repo_dir, self.repo_name) last_commit = j.sals.process.execute(\"git log -1\", cwd=path) self.info(\"Check if commit has been",
"path_file1 = j.sals.fs.join_paths(self.repo_dir, self.repo_name, file1_name) path_file2 = j.sals.fs.join_paths(self.repo_dir, self.repo_name, file2_name) j.sals.fs.touch(path_file1) j.sals.fs.touch(path_file2) self.info(\"Check",
"self.info(\"Create a file in repository path\") path = j.sals.fs.join_paths(self.repo_dir, self.repo_name, file_name) j.sals.fs.touch(path) self.info(\"Try",
"branch --show-current\", cwd=path) self.info(\"Check branch name\") self.assertIn(self.git_client.branch_name, branch_name[1]) def test04_git_modified_files(self): \"\"\"Test case for",
"url equal to remote_url. \"\"\" self.info(\"Read the git.config file\") path = j.sals.fs.join_paths(self.repo_dir, self.repo_name,",
"file_name) j.sals.fs.touch(path) self.info(\"Check if a new file has been added\") added_file = self.git_client.get_modified_files()",
"file_name) j.sals.fs.touch(path) self.info(\"Try pull before commit and should get error\") with self.assertRaises(j.exceptions.Input): self.git_client.pull()",
"Check that remote_url equal to repo_url. - Check that url equal to remote_url.",
"- Commit the change of creating a new file. - Get commit logs.",
"done for one file. \"\"\" file1_name = self.random_name() file2_name = self.random_name() self.info(\"Create a",
"repository path. - Check that two file has been added. - Commit the",
"repository path\") path = j.sals.fs.join_paths(self.repo_dir, self.repo_name, file_name) j.sals.fs.touch(path) self.info(\"Try pull before commit and",
"Check if a new file has been added \"\"\" self.info(\"Create a file in",
"has been added \"\"\" self.info(\"Create a file in repository path\") file_name = self.random_name()",
"self.info(\"Create a file in repository path\") file_name = self.random_name() path = j.sals.fs.join_paths(self.repo_dir, self.repo_name,",
"for pulling a repository **Test Scenario** - Get a git client. - Create",
"j.sals.fs.write_file(path, \"test modify file\") self.info(\"Check if file has been modified\") modified_file = self.git_client.get_modified_files()",
"a file in repository path. - Commit changes - modify this file -",
"repository path\") file_name = self.random_name() path = j.sals.fs.join_paths(self.repo_dir, self.repo_name, file_name) j.sals.fs.touch(path) self.info(\"Check if",
"to repo_url. - Check that url equal to remote_url. \"\"\" self.info(\"Read the git.config",
"git_config = j.sals.fs.read_file(path) self.info(\"Check that remote_url equals to repo ssh url\") self.assertEqual(self.git_client.remote_url, repo_ssh_url)",
"= j.sals.fs.join_paths(self.repo_dir, self.repo_name) self.git_client = j.clients.git.new(name=self.instance_name, path=path) def tearDown(self): j.clients.git.delete(self.instance_name) j.sals.fs.rmtree(path=self.repo_dir) def test01_check_git_config(self):",
"a file in repository path\") path = j.sals.fs.join_paths(self.repo_dir, self.repo_name, file_name) j.sals.fs.touch(path) self.info(\"Commit the",
"remote url to repo ssh url. - Read the git config file. -",
"config file. - Check that remote_url equals to repo ssh url. \"\"\" repo_ssh_url",
"branch_name = j.sals.process.execute(\"git branch --show-current\", cwd=path) self.info(\"Check branch name\") self.assertIn(self.git_client.branch_name, branch_name[1]) def test04_git_modified_files(self):",
"= self.random_name() commit_msg = self.random_name() self.info(\"Create a file in repository path\") path =",
"self.git_client.get_modified_files()[\"N\"].sort()) self.info(\"Commit the file 1\") path = j.sals.fs.join_paths(self.repo_dir, self.repo_name) j.sals.process.execute(f\"git add {file1_name}\", cwd=path)",
"= j.sals.fs.join_paths(self.repo_dir, self.repo_name) j.sals.process.execute(f\"git add {file1_name}\", cwd=path) self.git_client.commit(\"commit file 1\", add_all=False) self.info(\"Check if",
"modified\") modified_file = self.git_client.get_modified_files() self.assertTrue(modified_file) self.assertEqual(file_name, modified_file[\"M\"][0]) def test05_git_add_new_file(self): \"\"\"Test case for adding",
"remote url. **Test Scenario** - Get a git client. - Set remote url",
"getting the modified files. **Test Scenario** - Get a git client. - Create",
"self.repo_url = \"https://github.com/threefoldtech/js-ng\" j.sals.fs.mkdir(f\"{self.repo_dir}\") j.sals.process.execute(f\"git clone {self.repo_url}\", cwd=f\"{self.repo_dir}\") path = j.sals.fs.join_paths(self.repo_dir, self.repo_name) self.git_client",
"ssh url\") self.assertEqual(self.git_client.remote_url, repo_ssh_url) self.assertIn(self.git_client.remote_url, git_config) def test03_git_branch(self): \"\"\"Test case for checking a",
"has been modified \"\"\" self.info(\"Create a file in repository path\") file_name = self.random_name()",
"repo_url\") self.assertEqual(self.repo_url, self.git_client.remote_url) self.info(\"Check that git config url equal to remote_url\") self.assertIn(self.git_client.remote_url, git_config)",
"repository path\") path = j.sals.fs.join_paths(self.repo_dir, self.repo_name, file_name) j.sals.fs.touch(path) self.info(\"Commit the change of creating",
"- Pull from remote repository. \"\"\" file_name = self.random_name() commit_msg = self.random_name() self.info(\"Create",
"repo_ssh_url) self.assertIn(self.git_client.remote_url, git_config) def test03_git_branch(self): \"\"\"Test case for checking a branch name. **Test",
"config url equal to remote_url\") self.assertIn(self.git_client.remote_url, git_config) def test02_set_remote_ssh_url(self): \"\"\"Test case for setting",
"j.sals.fs.join_paths(\"/tmp\", self.random_name()) self.repo_name = \"js-ng\" self.repo_url = \"https://github.com/threefoldtech/js-ng\" j.sals.fs.mkdir(f\"{self.repo_dir}\") j.sals.process.execute(f\"git clone {self.repo_url}\", cwd=f\"{self.repo_dir}\")",
"a git client. - Create a file in repository path. - Check if",
"if file has been modified\") modified_file = self.git_client.get_modified_files() self.assertTrue(modified_file) self.assertEqual(file_name, modified_file[\"M\"][0]) def test05_git_add_new_file(self):",
"the branch name. - Check branch name. \"\"\" self.info(\"Get the branch name\") path",
"changes - modify this file - Check if file has been modified \"\"\"",
"path = j.sals.fs.join_paths(self.repo_dir, self.repo_name) self.git_client = j.clients.git.new(name=self.instance_name, path=path) def tearDown(self): j.clients.git.delete(self.instance_name) j.sals.fs.rmtree(path=self.repo_dir) def",
"self.repo_name) branch_name = j.sals.process.execute(\"git branch --show-current\", cwd=path) self.info(\"Check branch name\") self.assertIn(self.git_client.branch_name, branch_name[1]) def",
"a file in repository path. - Check if a new file has been",
"repository **Test Scenario** - Get a git client. - Create a file in",
"if file has been modified \"\"\" self.info(\"Create a file in repository path\") file_name",
"j.sals.fs.rmtree(path=self.repo_dir) def test01_check_git_config(self): \"\"\"Test case for checking git config file. **Test Scenario** -",
"str(last_commit)) def test07_git_commit_one_file(self): \"\"\"Test case for checking a commit with add_all=False. **Test Scenario**",
"self.info(\"Commit changes\") self.git_client.commit(f\"add {file_name}\") self.info(\"modify this file\") path = j.sals.fs.join_paths(self.repo_dir, self.repo_name, file_name) j.sals.fs.write_file(path,",
"= self.git_client.get_modified_files() self.assertTrue(modified_file) self.assertEqual(file_name, modified_file[\"M\"][0]) def test05_git_add_new_file(self): \"\"\"Test case for adding a new",
"- Get a git client. - Set remote url to repo ssh url.",
"self.repo_name) last_commit = j.sals.process.execute(\"git log -1\", cwd=path) self.info(\"Check if commit has been done\")",
"self.assertEqual([file2_name, file1_name].sort(), self.git_client.get_modified_files()[\"N\"].sort()) self.info(\"Commit the file 1\") path = j.sals.fs.join_paths(self.repo_dir, self.repo_name) j.sals.process.execute(f\"git add",
"{file1_name}\", cwd=path) self.git_client.commit(\"commit file 1\", add_all=False) self.info(\"Check if commit has been done for",
"a git client. - Get the branch name. - Check branch name. \"\"\"",
"one file. \"\"\" file1_name = self.random_name() file2_name = self.random_name() self.info(\"Create a two file",
"Create a file in repository path. - Commit changes - modify this file",
"\"\"\" file1_name = self.random_name() file2_name = self.random_name() self.info(\"Create a two file in repository",
"super().setUp() self.instance_name = self.random_name() self.repo_dir = j.sals.fs.join_paths(\"/tmp\", self.random_name()) self.repo_name = \"js-ng\" self.repo_url =",
"Commit the change of creating a new file. - Get commit logs. -",
"test01_check_git_config(self): \"\"\"Test case for checking git config file. **Test Scenario** - Get a",
"file\") path = j.sals.fs.join_paths(self.repo_dir, self.repo_name, file_name) j.sals.fs.write_file(path, \"test modify file\") self.info(\"Check if file",
"path. - Try pull before commit and should get error. - Commit the",
"self.assertRaises(j.exceptions.Input): self.git_client.pull() self.info(\"Commit the change of creating a new file\") self.git_client.commit(commit_msg) self.info(\"Pull from",
"self.info(\"Commit the file 1\") path = j.sals.fs.join_paths(self.repo_dir, self.repo_name) j.sals.process.execute(f\"git add {file1_name}\", cwd=path) self.git_client.commit(\"commit",
"self.info(\"Create a file in repository path\") path = j.sals.fs.join_paths(self.repo_dir, self.repo_name, file_name) j.sals.fs.touch(path) self.info(\"Commit",
"the file 1. - Check if commit has been done for one file.",
"git. **Test Scenario** - Get a git client. - Create a file in",
"url\") self.assertEqual(self.git_client.remote_url, repo_ssh_url) self.assertIn(self.git_client.remote_url, git_config) def test03_git_branch(self): \"\"\"Test case for checking a branch",
"git_config = j.sals.fs.read_file(path) self.info(\"Check that remote_url equal to repo_url\") self.assertEqual(self.repo_url, self.git_client.remote_url) self.info(\"Check that",
"modified_file = self.git_client.get_modified_files() self.assertTrue(modified_file) self.assertEqual(file_name, modified_file[\"M\"][0]) def test05_git_add_new_file(self): \"\"\"Test case for adding a",
"j.sals.fs.touch(path) self.info(\"Try pull before commit and should get error\") with self.assertRaises(j.exceptions.Input): self.git_client.pull() self.info(\"Commit",
"name. **Test Scenario** - Get a git client. - Get the branch name.",
"= j.clients.git.new(name=self.instance_name, path=path) def tearDown(self): j.clients.git.delete(self.instance_name) j.sals.fs.rmtree(path=self.repo_dir) def test01_check_git_config(self): \"\"\"Test case for checking",
"**Test Scenario** - Get a git client. - Read the git.config file. -",
"\"\"\" repo_ssh_url = \"git@github.com:threefoldtech/js-ng.git\" self.info(\"Set remote url to repo ssh url\") self.git_client.set_remote_url(repo_ssh_url) self.info(\"Read",
"if commit has been done\") self.assertIn(commit_msg, str(last_commit)) def test07_git_commit_one_file(self): \"\"\"Test case for checking",
"in repository path. - Check that two file has been added. - Commit",
"url. \"\"\" repo_ssh_url = \"git@github.com:threefoldtech/js-ng.git\" self.info(\"Set remote url to repo ssh url\") self.git_client.set_remote_url(repo_ssh_url)",
"test06_git_commit(self): \"\"\"Test case for committing a change. **Test Scenario** - Get a git",
"= self.random_name() self.info(\"Create a two file in repository path\") path_file1 = j.sals.fs.join_paths(self.repo_dir, self.repo_name,",
"been done for one file\") self.assertNotIn(file1_name, self.git_client.get_modified_files()[\"N\"]) def test08_git_pull(self): \"\"\"Test case for pulling",
"a new file. - Pull from remote repository. \"\"\" file_name = self.random_name() commit_msg",
"self.git_client.pull() self.info(\"Commit the change of creating a new file\") self.git_client.commit(commit_msg) self.info(\"Pull from remote",
"def test02_set_remote_ssh_url(self): \"\"\"Test case for setting remote url. **Test Scenario** - Get a",
"to repo ssh url\") self.assertEqual(self.git_client.remote_url, repo_ssh_url) self.assertIn(self.git_client.remote_url, git_config) def test03_git_branch(self): \"\"\"Test case for",
"path. - Commit changes - modify this file - Check if file has",
"new file. - Pull from remote repository. \"\"\" file_name = self.random_name() commit_msg =",
"change of creating a new file. - Get commit logs. - Check if",
"= j.sals.process.execute(\"git log -1\", cwd=path) self.info(\"Check if commit has been done\") self.assertIn(commit_msg, str(last_commit))",
"- Create a two file in repository path. - Check that two file",
"Check if file has been modified \"\"\" self.info(\"Create a file in repository path\")",
"done. \"\"\" file_name = self.random_name() commit_msg = self.random_name() self.info(\"Create a file in repository",
"j.sals.fs.touch(path) self.info(\"Commit changes\") self.git_client.commit(f\"add {file_name}\") self.info(\"modify this file\") path = j.sals.fs.join_paths(self.repo_dir, self.repo_name, file_name)",
"= j.sals.fs.join_paths(self.repo_dir, self.repo_name) last_commit = j.sals.process.execute(\"git log -1\", cwd=path) self.info(\"Check if commit has",
"the change of creating a new file. - Pull from remote repository. \"\"\"",
"before commit and should get error\") with self.assertRaises(j.exceptions.Input): self.git_client.pull() self.info(\"Commit the change of",
"for checking a branch name. **Test Scenario** - Get a git client. -",
"- Check that two file has been added. - Commit the file 1.",
"url. **Test Scenario** - Get a git client. - Set remote url to",
"creating a new file\") self.git_client.commit(commit_msg) self.info(\"Get commit logs\") path = j.sals.fs.join_paths(self.repo_dir, self.repo_name) last_commit",
"Try pull before commit and should get error. - Commit the change of",
"self.git_client = j.clients.git.new(name=self.instance_name, path=path) def tearDown(self): j.clients.git.delete(self.instance_name) j.sals.fs.rmtree(path=self.repo_dir) def test01_check_git_config(self): \"\"\"Test case for",
"in repository path. - Try pull before commit and should get error. -",
"branch_name[1]) def test04_git_modified_files(self): \"\"\"Test case for getting the modified files. **Test Scenario** -",
"- modify this file - Check if file has been modified \"\"\" self.info(\"Create",
"self.assertEqual(self.repo_url, self.git_client.remote_url) self.info(\"Check that git config url equal to remote_url\") self.assertIn(self.git_client.remote_url, git_config) def",
"case for committing a change. **Test Scenario** - Get a git client. -",
"in repository path. - Check if a new file has been added \"\"\"",
"\"https://github.com/threefoldtech/js-ng\" j.sals.fs.mkdir(f\"{self.repo_dir}\") j.sals.process.execute(f\"git clone {self.repo_url}\", cwd=f\"{self.repo_dir}\") path = j.sals.fs.join_paths(self.repo_dir, self.repo_name) self.git_client = j.clients.git.new(name=self.instance_name,",
"has been modified\") modified_file = self.git_client.get_modified_files() self.assertTrue(modified_file) self.assertEqual(file_name, modified_file[\"M\"][0]) def test05_git_add_new_file(self): \"\"\"Test case",
"been added. - Commit the file 1. - Check if commit has been",
"client. - Create a file in repository path. - Try pull before commit",
"pulling a repository **Test Scenario** - Get a git client. - Create a",
"Get commit logs. - Check if commit has been done. \"\"\" file_name =",
"self.assertIn(self.git_client.branch_name, branch_name[1]) def test04_git_modified_files(self): \"\"\"Test case for getting the modified files. **Test Scenario**",
"j.sals.fs.join_paths(self.repo_dir, self.repo_name, file_name) j.sals.fs.touch(path) self.info(\"Try pull before commit and should get error\") with",
"url to repo ssh url\") self.git_client.set_remote_url(repo_ssh_url) self.info(\"Read the git config file\") path =",
"Create a file in repository path. - Try pull before commit and should",
"case for adding a new file with git. **Test Scenario** - Get a",
"- Check branch name. \"\"\" self.info(\"Get the branch name\") path = j.sals.fs.join_paths(self.repo_dir, self.repo_name)",
"j.sals.process.execute(f\"git add {file1_name}\", cwd=path) self.git_client.commit(\"commit file 1\", add_all=False) self.info(\"Check if commit has been",
"added\") added_file = self.git_client.get_modified_files() self.assertTrue(added_file) self.assertEqual(file_name, added_file[\"N\"][0]) def test06_git_commit(self): \"\"\"Test case for committing",
"path = j.sals.fs.join_paths(self.repo_dir, self.repo_name, \".git/config\") git_config = j.sals.fs.read_file(path) self.info(\"Check that remote_url equals to",
"file\") path = j.sals.fs.join_paths(self.repo_dir, self.repo_name, \".git/config\") git_config = j.sals.fs.read_file(path) self.info(\"Check that remote_url equals",
"remote_url\") self.assertIn(self.git_client.remote_url, git_config) def test02_set_remote_ssh_url(self): \"\"\"Test case for setting remote url. **Test Scenario**",
"- Read the git config file. - Check that remote_url equals to repo",
"cwd=f\"{self.repo_dir}\") path = j.sals.fs.join_paths(self.repo_dir, self.repo_name) self.git_client = j.clients.git.new(name=self.instance_name, path=path) def tearDown(self): j.clients.git.delete(self.instance_name) j.sals.fs.rmtree(path=self.repo_dir)",
"the git.config file. - Check that remote_url equal to repo_url. - Check that",
"a git client. - Read the git.config file. - Check that remote_url equal",
"if a new file has been added\") added_file = self.git_client.get_modified_files() self.assertTrue(added_file) self.assertEqual(file_name, added_file[\"N\"][0])",
"j.sals.process.execute(\"git branch --show-current\", cwd=path) self.info(\"Check branch name\") self.assertIn(self.git_client.branch_name, branch_name[1]) def test04_git_modified_files(self): \"\"\"Test case",
"clone {self.repo_url}\", cwd=f\"{self.repo_dir}\") path = j.sals.fs.join_paths(self.repo_dir, self.repo_name) self.git_client = j.clients.git.new(name=self.instance_name, path=path) def tearDown(self):",
"remote_url equal to repo_url. - Check that url equal to remote_url. \"\"\" self.info(\"Read",
"\".git/config\") git_config = j.sals.fs.read_file(path) self.info(\"Check that remote_url equal to repo_url\") self.assertEqual(self.repo_url, self.git_client.remote_url) self.info(\"Check",
"-1\", cwd=path) self.info(\"Check if commit has been done\") self.assertIn(commit_msg, str(last_commit)) def test07_git_commit_one_file(self): \"\"\"Test",
"= \"git@github.com:threefoldtech/js-ng.git\" self.info(\"Set remote url to repo ssh url\") self.git_client.set_remote_url(repo_ssh_url) self.info(\"Read the git",
"commit has been done for one file\") self.assertNotIn(file1_name, self.git_client.get_modified_files()[\"N\"]) def test08_git_pull(self): \"\"\"Test case",
"path = j.sals.fs.join_paths(self.repo_dir, self.repo_name) branch_name = j.sals.process.execute(\"git branch --show-current\", cwd=path) self.info(\"Check branch name\")",
"has been added. - Commit the file 1. - Check if commit has",
"with self.assertRaises(j.exceptions.Input): self.git_client.pull() self.info(\"Commit the change of creating a new file\") self.git_client.commit(commit_msg) self.info(\"Pull",
"case for checking a branch name. **Test Scenario** - Get a git client.",
"Get the branch name. - Check branch name. \"\"\" self.info(\"Get the branch name\")",
"url to repo ssh url. - Read the git config file. - Check",
"added_file = self.git_client.get_modified_files() self.assertTrue(added_file) self.assertEqual(file_name, added_file[\"N\"][0]) def test06_git_commit(self): \"\"\"Test case for committing a",
"Check that two file has been added. - Commit the file 1. -",
"- Create a file in repository path. - Try pull before commit and",
"file with git. **Test Scenario** - Get a git client. - Create a",
"path = j.sals.fs.join_paths(self.repo_dir, self.repo_name, \".git/config\") git_config = j.sals.fs.read_file(path) self.info(\"Check that remote_url equal to",
"of creating a new file\") self.git_client.commit(commit_msg) self.info(\"Get commit logs\") path = j.sals.fs.join_paths(self.repo_dir, self.repo_name)",
"def test03_git_branch(self): \"\"\"Test case for checking a branch name. **Test Scenario** - Get",
"and should get error\") with self.assertRaises(j.exceptions.Input): self.git_client.pull() self.info(\"Commit the change of creating a",
"to remote_url. \"\"\" self.info(\"Read the git.config file\") path = j.sals.fs.join_paths(self.repo_dir, self.repo_name, \".git/config\") git_config",
"setting remote url. **Test Scenario** - Get a git client. - Set remote",
"change. **Test Scenario** - Get a git client. - Create a file in",
"def test07_git_commit_one_file(self): \"\"\"Test case for checking a commit with add_all=False. **Test Scenario** -",
"Get a git client. - Create a two file in repository path. -",
"two file in repository path. - Check that two file has been added.",
"j.sals.fs.mkdir(f\"{self.repo_dir}\") j.sals.process.execute(f\"git clone {self.repo_url}\", cwd=f\"{self.repo_dir}\") path = j.sals.fs.join_paths(self.repo_dir, self.repo_name) self.git_client = j.clients.git.new(name=self.instance_name, path=path)",
"= j.sals.fs.join_paths(self.repo_dir, self.repo_name, \".git/config\") git_config = j.sals.fs.read_file(path) self.info(\"Check that remote_url equal to repo_url\")",
"to remote_url\") self.assertIn(self.git_client.remote_url, git_config) def test02_set_remote_ssh_url(self): \"\"\"Test case for setting remote url. **Test",
"Get a git client. - Create a file in repository path. - Commit",
"Check if commit has been done. \"\"\" file_name = self.random_name() commit_msg = self.random_name()",
"has been done. \"\"\" file_name = self.random_name() commit_msg = self.random_name() self.info(\"Create a file",
"commit and should get error\") with self.assertRaises(j.exceptions.Input): self.git_client.pull() self.info(\"Commit the change of creating",
"commit_msg = self.random_name() self.info(\"Create a file in repository path\") path = j.sals.fs.join_paths(self.repo_dir, self.repo_name,",
"repo_ssh_url = \"git@github.com:threefoldtech/js-ng.git\" self.info(\"Set remote url to repo ssh url\") self.git_client.set_remote_url(repo_ssh_url) self.info(\"Read the",
"added \"\"\" self.info(\"Create a file in repository path\") file_name = self.random_name() path =",
"has been done\") self.assertIn(commit_msg, str(last_commit)) def test07_git_commit_one_file(self): \"\"\"Test case for checking a commit",
"file1_name = self.random_name() file2_name = self.random_name() self.info(\"Create a two file in repository path\")",
"GitTests(BaseTests): def setUp(self): super().setUp() self.instance_name = self.random_name() self.repo_dir = j.sals.fs.join_paths(\"/tmp\", self.random_name()) self.repo_name =",
"self.info(\"Set remote url to repo ssh url\") self.git_client.set_remote_url(repo_ssh_url) self.info(\"Read the git config file\")",
"that remote_url equal to repo_url\") self.assertEqual(self.repo_url, self.git_client.remote_url) self.info(\"Check that git config url equal",
"done for one file\") self.assertNotIn(file1_name, self.git_client.get_modified_files()[\"N\"]) def test08_git_pull(self): \"\"\"Test case for pulling a",
"been added\") added_file = self.git_client.get_modified_files() self.assertTrue(added_file) self.assertEqual(file_name, added_file[\"N\"][0]) def test06_git_commit(self): \"\"\"Test case for",
"Get a git client. - Set remote url to repo ssh url. -",
"- Check if a new file has been added \"\"\" self.info(\"Create a file",
"Pull from remote repository. \"\"\" file_name = self.random_name() commit_msg = self.random_name() self.info(\"Create a",
"= j.sals.fs.join_paths(self.repo_dir, self.repo_name, file_name) j.sals.fs.touch(path) self.info(\"Commit changes\") self.git_client.commit(f\"add {file_name}\") self.info(\"modify this file\") path",
"= j.sals.process.execute(\"git branch --show-current\", cwd=path) self.info(\"Check branch name\") self.assertIn(self.git_client.branch_name, branch_name[1]) def test04_git_modified_files(self): \"\"\"Test",
"case for pulling a repository **Test Scenario** - Get a git client. -",
"Commit the file 1. - Check if commit has been done for one",
"modified_file[\"M\"][0]) def test05_git_add_new_file(self): \"\"\"Test case for adding a new file with git. **Test",
"file in repository path. - Try pull before commit and should get error.",
"commit has been done\") self.assertIn(commit_msg, str(last_commit)) def test07_git_commit_one_file(self): \"\"\"Test case for checking a",
"for committing a change. **Test Scenario** - Get a git client. - Create",
"\"\"\" file_name = self.random_name() commit_msg = self.random_name() self.info(\"Create a file in repository path\")",
"path = j.sals.fs.join_paths(self.repo_dir, self.repo_name) last_commit = j.sals.process.execute(\"git log -1\", cwd=path) self.info(\"Check if commit",
"in repository path. - Commit changes - modify this file - Check if",
"two file in repository path\") path_file1 = j.sals.fs.join_paths(self.repo_dir, self.repo_name, file1_name) path_file2 = j.sals.fs.join_paths(self.repo_dir,",
"self.random_name() path = j.sals.fs.join_paths(self.repo_dir, self.repo_name, file_name) j.sals.fs.touch(path) self.info(\"Check if a new file has",
"remote_url equals to repo ssh url\") self.assertEqual(self.git_client.remote_url, repo_ssh_url) self.assertIn(self.git_client.remote_url, git_config) def test03_git_branch(self): \"\"\"Test",
"- Commit changes - modify this file - Check if file has been",
"been done. \"\"\" file_name = self.random_name() commit_msg = self.random_name() self.info(\"Create a file in",
"self.assertTrue(added_file) self.assertEqual(file_name, added_file[\"N\"][0]) def test06_git_commit(self): \"\"\"Test case for committing a change. **Test Scenario**",
"git config url equal to remote_url\") self.assertIn(self.git_client.remote_url, git_config) def test02_set_remote_ssh_url(self): \"\"\"Test case for",
"file has been modified \"\"\" self.info(\"Create a file in repository path\") file_name =",
"repo ssh url\") self.git_client.set_remote_url(repo_ssh_url) self.info(\"Read the git config file\") path = j.sals.fs.join_paths(self.repo_dir, self.repo_name,",
"self.info(\"Read the git config file\") path = j.sals.fs.join_paths(self.repo_dir, self.repo_name, \".git/config\") git_config = j.sals.fs.read_file(path)",
"that url equal to remote_url. \"\"\" self.info(\"Read the git.config file\") path = j.sals.fs.join_paths(self.repo_dir,",
"path = j.sals.fs.join_paths(self.repo_dir, self.repo_name, file_name) j.sals.fs.touch(path) self.info(\"Try pull before commit and should get",
"repository. \"\"\" file_name = self.random_name() commit_msg = self.random_name() self.info(\"Create a file in repository",
"self.random_name()) self.repo_name = \"js-ng\" self.repo_url = \"https://github.com/threefoldtech/js-ng\" j.sals.fs.mkdir(f\"{self.repo_dir}\") j.sals.process.execute(f\"git clone {self.repo_url}\", cwd=f\"{self.repo_dir}\") path",
"creating a new file. - Get commit logs. - Check if commit has",
"file_name) j.sals.fs.touch(path) self.info(\"Commit changes\") self.git_client.commit(f\"add {file_name}\") self.info(\"modify this file\") path = j.sals.fs.join_paths(self.repo_dir, self.repo_name,",
"j.clients.git.new(name=self.instance_name, path=path) def tearDown(self): j.clients.git.delete(self.instance_name) j.sals.fs.rmtree(path=self.repo_dir) def test01_check_git_config(self): \"\"\"Test case for checking git",
"git_config) def test02_set_remote_ssh_url(self): \"\"\"Test case for setting remote url. **Test Scenario** - Get",
"git client. - Read the git.config file. - Check that remote_url equal to",
"Create a file in repository path. - Commit the change of creating a",
"git client. - Create a two file in repository path. - Check that",
"name. - Check branch name. \"\"\" self.info(\"Get the branch name\") path = j.sals.fs.join_paths(self.repo_dir,",
"test03_git_branch(self): \"\"\"Test case for checking a branch name. **Test Scenario** - Get a",
"a git client. - Create a file in repository path. - Commit changes",
"config file. **Test Scenario** - Get a git client. - Read the git.config",
"Read the git.config file. - Check that remote_url equal to repo_url. - Check",
"branch name. **Test Scenario** - Get a git client. - Get the branch",
"creating a new file. - Pull from remote repository. \"\"\" file_name = self.random_name()",
"Commit the change of creating a new file. - Pull from remote repository.",
"self.git_client.commit(commit_msg) self.info(\"Get commit logs\") path = j.sals.fs.join_paths(self.repo_dir, self.repo_name) last_commit = j.sals.process.execute(\"git log -1\",",
"self.info(\"Read the git.config file\") path = j.sals.fs.join_paths(self.repo_dir, self.repo_name, \".git/config\") git_config = j.sals.fs.read_file(path) self.info(\"Check",
"the branch name\") path = j.sals.fs.join_paths(self.repo_dir, self.repo_name) branch_name = j.sals.process.execute(\"git branch --show-current\", cwd=path)",
"Create a file in repository path. - Check if a new file has",
"file\") self.info(\"Check if file has been modified\") modified_file = self.git_client.get_modified_files() self.assertTrue(modified_file) self.assertEqual(file_name, modified_file[\"M\"][0])",
"- Get a git client. - Create a two file in repository path.",
"- Check that remote_url equal to repo_url. - Check that url equal to",
"= j.sals.fs.join_paths(self.repo_dir, self.repo_name) branch_name = j.sals.process.execute(\"git branch --show-current\", cwd=path) self.info(\"Check branch name\") self.assertIn(self.git_client.branch_name,",
"in repository path\") file_name = self.random_name() path = j.sals.fs.join_paths(self.repo_dir, self.repo_name, file_name) j.sals.fs.touch(path) self.info(\"Commit",
"error. - Commit the change of creating a new file. - Pull from",
"add {file1_name}\", cwd=path) self.git_client.commit(\"commit file 1\", add_all=False) self.info(\"Check if commit has been done",
"self.assertIn(self.git_client.remote_url, git_config) def test03_git_branch(self): \"\"\"Test case for checking a branch name. **Test Scenario**",
"two file has been added.\") self.assertEqual([file2_name, file1_name].sort(), self.git_client.get_modified_files()[\"N\"].sort()) self.info(\"Commit the file 1\") path",
"modify this file - Check if file has been modified \"\"\" self.info(\"Create a",
"= \"https://github.com/threefoldtech/js-ng\" j.sals.fs.mkdir(f\"{self.repo_dir}\") j.sals.process.execute(f\"git clone {self.repo_url}\", cwd=f\"{self.repo_dir}\") path = j.sals.fs.join_paths(self.repo_dir, self.repo_name) self.git_client =",
"self.info(\"Check that remote_url equals to repo ssh url\") self.assertEqual(self.git_client.remote_url, repo_ssh_url) self.assertIn(self.git_client.remote_url, git_config) def",
"j.sals.process.execute(\"git log -1\", cwd=path) self.info(\"Check if commit has been done\") self.assertIn(commit_msg, str(last_commit)) def",
"= j.sals.fs.read_file(path) self.info(\"Check that remote_url equal to repo_url\") self.assertEqual(self.repo_url, self.git_client.remote_url) self.info(\"Check that git",
"Scenario** - Get a git client. - Create a two file in repository",
"that two file has been added. - Commit the file 1. - Check",
"file. - Pull from remote repository. \"\"\" file_name = self.random_name() commit_msg = self.random_name()",
"path\") path = j.sals.fs.join_paths(self.repo_dir, self.repo_name, file_name) j.sals.fs.touch(path) self.info(\"Commit the change of creating a",
"\"test modify file\") self.info(\"Check if file has been modified\") modified_file = self.git_client.get_modified_files() self.assertTrue(modified_file)",
"def test01_check_git_config(self): \"\"\"Test case for checking git config file. **Test Scenario** - Get",
"= j.sals.fs.join_paths(self.repo_dir, self.repo_name, file1_name) path_file2 = j.sals.fs.join_paths(self.repo_dir, self.repo_name, file2_name) j.sals.fs.touch(path_file1) j.sals.fs.touch(path_file2) self.info(\"Check that",
"**Test Scenario** - Get a git client. - Create a file in repository",
"the git config file\") path = j.sals.fs.join_paths(self.repo_dir, self.repo_name, \".git/config\") git_config = j.sals.fs.read_file(path) self.info(\"Check",
"commit logs. - Check if commit has been done. \"\"\" file_name = self.random_name()",
"config file\") path = j.sals.fs.join_paths(self.repo_dir, self.repo_name, \".git/config\") git_config = j.sals.fs.read_file(path) self.info(\"Check that remote_url",
"path=path) def tearDown(self): j.clients.git.delete(self.instance_name) j.sals.fs.rmtree(path=self.repo_dir) def test01_check_git_config(self): \"\"\"Test case for checking git config",
"\"\"\" self.info(\"Get the branch name\") path = j.sals.fs.join_paths(self.repo_dir, self.repo_name) branch_name = j.sals.process.execute(\"git branch",
"file in repository path\") path_file1 = j.sals.fs.join_paths(self.repo_dir, self.repo_name, file1_name) path_file2 = j.sals.fs.join_paths(self.repo_dir, self.repo_name,",
"url\") self.git_client.set_remote_url(repo_ssh_url) self.info(\"Read the git config file\") path = j.sals.fs.join_paths(self.repo_dir, self.repo_name, \".git/config\") git_config",
"file 1. - Check if commit has been done for one file. \"\"\"",
"file. - Check that remote_url equal to repo_url. - Check that url equal",
"that remote_url equal to repo_url. - Check that url equal to remote_url. \"\"\"",
"modified \"\"\" self.info(\"Create a file in repository path\") file_name = self.random_name() path =",
"self.random_name() path = j.sals.fs.join_paths(self.repo_dir, self.repo_name, file_name) j.sals.fs.touch(path) self.info(\"Commit changes\") self.git_client.commit(f\"add {file_name}\") self.info(\"modify this",
"file in repository path. - Check that two file has been added. -",
"Scenario** - Get a git client. - Get the branch name. - Check",
"from remote repository. \"\"\" file_name = self.random_name() commit_msg = self.random_name() self.info(\"Create a file",
"repository path. - Check if a new file has been added \"\"\" self.info(\"Create",
"self.assertIn(commit_msg, str(last_commit)) def test07_git_commit_one_file(self): \"\"\"Test case for checking a commit with add_all=False. **Test",
"j.clients.git.delete(self.instance_name) j.sals.fs.rmtree(path=self.repo_dir) def test01_check_git_config(self): \"\"\"Test case for checking git config file. **Test Scenario**",
"file. - Check that remote_url equals to repo ssh url. \"\"\" repo_ssh_url =",
"equal to repo_url\") self.assertEqual(self.repo_url, self.git_client.remote_url) self.info(\"Check that git config url equal to remote_url\")",
"name\") path = j.sals.fs.join_paths(self.repo_dir, self.repo_name) branch_name = j.sals.process.execute(\"git branch --show-current\", cwd=path) self.info(\"Check branch",
"self.repo_name, \".git/config\") git_config = j.sals.fs.read_file(path) self.info(\"Check that remote_url equal to repo_url\") self.assertEqual(self.repo_url, self.git_client.remote_url)",
"a file in repository path. - Commit the change of creating a new",
"<gh_stars>1-10 from jumpscale.loader import j from tests.base_tests import BaseTests class GitTests(BaseTests): def setUp(self):",
"self.random_name() self.info(\"Create a file in repository path\") path = j.sals.fs.join_paths(self.repo_dir, self.repo_name, file_name) j.sals.fs.touch(path)",
"the change of creating a new file. - Get commit logs. - Check",
"commit logs\") path = j.sals.fs.join_paths(self.repo_dir, self.repo_name) last_commit = j.sals.process.execute(\"git log -1\", cwd=path) self.info(\"Check",
"path\") path = j.sals.fs.join_paths(self.repo_dir, self.repo_name, file_name) j.sals.fs.touch(path) self.info(\"Try pull before commit and should",
"if commit has been done. \"\"\" file_name = self.random_name() commit_msg = self.random_name() self.info(\"Create",
"self.repo_name, file_name) j.sals.fs.write_file(path, \"test modify file\") self.info(\"Check if file has been modified\") modified_file",
"file in repository path. - Commit changes - modify this file - Check",
"client. - Set remote url to repo ssh url. - Read the git",
"self.random_name() self.info(\"Create a two file in repository path\") path_file1 = j.sals.fs.join_paths(self.repo_dir, self.repo_name, file1_name)",
"for checking a commit with add_all=False. **Test Scenario** - Get a git client.",
"the change of creating a new file\") self.git_client.commit(commit_msg) self.info(\"Pull from remote repository\") self.git_client.pull()",
"path = j.sals.fs.join_paths(self.repo_dir, self.repo_name, file_name) j.sals.fs.touch(path) self.info(\"Commit changes\") self.git_client.commit(f\"add {file_name}\") self.info(\"modify this file\")",
"file 1\", add_all=False) self.info(\"Check if commit has been done for one file\") self.assertNotIn(file1_name,",
"Create a two file in repository path. - Check that two file has",
"in repository path\") path_file1 = j.sals.fs.join_paths(self.repo_dir, self.repo_name, file1_name) path_file2 = j.sals.fs.join_paths(self.repo_dir, self.repo_name, file2_name)",
"branch name. \"\"\" self.info(\"Get the branch name\") path = j.sals.fs.join_paths(self.repo_dir, self.repo_name) branch_name =",
"for one file. \"\"\" file1_name = self.random_name() file2_name = self.random_name() self.info(\"Create a two",
"self.repo_name = \"js-ng\" self.repo_url = \"https://github.com/threefoldtech/js-ng\" j.sals.fs.mkdir(f\"{self.repo_dir}\") j.sals.process.execute(f\"git clone {self.repo_url}\", cwd=f\"{self.repo_dir}\") path =",
"j.sals.fs.read_file(path) self.info(\"Check that remote_url equals to repo ssh url\") self.assertEqual(self.git_client.remote_url, repo_ssh_url) self.assertIn(self.git_client.remote_url, git_config)",
"= self.random_name() self.repo_dir = j.sals.fs.join_paths(\"/tmp\", self.random_name()) self.repo_name = \"js-ng\" self.repo_url = \"https://github.com/threefoldtech/js-ng\" j.sals.fs.mkdir(f\"{self.repo_dir}\")",
"self.random_name() self.repo_dir = j.sals.fs.join_paths(\"/tmp\", self.random_name()) self.repo_name = \"js-ng\" self.repo_url = \"https://github.com/threefoldtech/js-ng\" j.sals.fs.mkdir(f\"{self.repo_dir}\") j.sals.process.execute(f\"git",
"that git config url equal to remote_url\") self.assertIn(self.git_client.remote_url, git_config) def test02_set_remote_ssh_url(self): \"\"\"Test case",
"that remote_url equals to repo ssh url\") self.assertEqual(self.git_client.remote_url, repo_ssh_url) self.assertIn(self.git_client.remote_url, git_config) def test03_git_branch(self):",
"has been added.\") self.assertEqual([file2_name, file1_name].sort(), self.git_client.get_modified_files()[\"N\"].sort()) self.info(\"Commit the file 1\") path = j.sals.fs.join_paths(self.repo_dir,",
"tearDown(self): j.clients.git.delete(self.instance_name) j.sals.fs.rmtree(path=self.repo_dir) def test01_check_git_config(self): \"\"\"Test case for checking git config file. **Test",
"client. - Get the branch name. - Check branch name. \"\"\" self.info(\"Get the",
"self.info(\"Check if commit has been done\") self.assertIn(commit_msg, str(last_commit)) def test07_git_commit_one_file(self): \"\"\"Test case for",
"git client. - Create a file in repository path. - Commit the change",
"to repo ssh url\") self.git_client.set_remote_url(repo_ssh_url) self.info(\"Read the git config file\") path = j.sals.fs.join_paths(self.repo_dir,",
"j.sals.fs.join_paths(self.repo_dir, self.repo_name, file1_name) path_file2 = j.sals.fs.join_paths(self.repo_dir, self.repo_name, file2_name) j.sals.fs.touch(path_file1) j.sals.fs.touch(path_file2) self.info(\"Check that two",
"file in repository path. - Check if a new file has been added",
"- Get a git client. - Read the git.config file. - Check that",
"**Test Scenario** - Get a git client. - Create a two file in",
"case for getting the modified files. **Test Scenario** - Get a git client.",
"a two file in repository path. - Check that two file has been",
"git_config) def test03_git_branch(self): \"\"\"Test case for checking a branch name. **Test Scenario** -",
"the modified files. **Test Scenario** - Get a git client. - Create a",
"- Get the branch name. - Check branch name. \"\"\" self.info(\"Get the branch",
"**Test Scenario** - Get a git client. - Set remote url to repo",
"equal to repo_url. - Check that url equal to remote_url. \"\"\" self.info(\"Read the",
"remote_url. \"\"\" self.info(\"Read the git.config file\") path = j.sals.fs.join_paths(self.repo_dir, self.repo_name, \".git/config\") git_config =",
"file2_name) j.sals.fs.touch(path_file1) j.sals.fs.touch(path_file2) self.info(\"Check that two file has been added.\") self.assertEqual([file2_name, file1_name].sort(), self.git_client.get_modified_files()[\"N\"].sort())",
"self.instance_name = self.random_name() self.repo_dir = j.sals.fs.join_paths(\"/tmp\", self.random_name()) self.repo_name = \"js-ng\" self.repo_url = \"https://github.com/threefoldtech/js-ng\"",
"test02_set_remote_ssh_url(self): \"\"\"Test case for setting remote url. **Test Scenario** - Get a git",
"repo ssh url. \"\"\" repo_ssh_url = \"git@github.com:threefoldtech/js-ng.git\" self.info(\"Set remote url to repo ssh",
"checking a commit with add_all=False. **Test Scenario** - Get a git client. -",
"the file 1\") path = j.sals.fs.join_paths(self.repo_dir, self.repo_name) j.sals.process.execute(f\"git add {file1_name}\", cwd=path) self.git_client.commit(\"commit file",
"been modified\") modified_file = self.git_client.get_modified_files() self.assertTrue(modified_file) self.assertEqual(file_name, modified_file[\"M\"][0]) def test05_git_add_new_file(self): \"\"\"Test case for",
"to repo_url\") self.assertEqual(self.repo_url, self.git_client.remote_url) self.info(\"Check that git config url equal to remote_url\") self.assertIn(self.git_client.remote_url,",
"git client. - Create a file in repository path. - Check if a",
"this file - Check if file has been modified \"\"\" self.info(\"Create a file",
"1\") path = j.sals.fs.join_paths(self.repo_dir, self.repo_name) j.sals.process.execute(f\"git add {file1_name}\", cwd=path) self.git_client.commit(\"commit file 1\", add_all=False)",
"Check that url equal to remote_url. \"\"\" self.info(\"Read the git.config file\") path =",
"modified files. **Test Scenario** - Get a git client. - Create a file",
"self.info(\"Check that remote_url equal to repo_url\") self.assertEqual(self.repo_url, self.git_client.remote_url) self.info(\"Check that git config url",
"file has been added \"\"\" self.info(\"Create a file in repository path\") file_name =",
"= self.random_name() path = j.sals.fs.join_paths(self.repo_dir, self.repo_name, file_name) j.sals.fs.touch(path) self.info(\"Check if a new file",
"path_file2 = j.sals.fs.join_paths(self.repo_dir, self.repo_name, file2_name) j.sals.fs.touch(path_file1) j.sals.fs.touch(path_file2) self.info(\"Check that two file has been",
"j.sals.fs.touch(path_file1) j.sals.fs.touch(path_file2) self.info(\"Check that two file has been added.\") self.assertEqual([file2_name, file1_name].sort(), self.git_client.get_modified_files()[\"N\"].sort()) self.info(\"Commit",
"- Create a file in repository path. - Check if a new file",
"ssh url\") self.git_client.set_remote_url(repo_ssh_url) self.info(\"Read the git config file\") path = j.sals.fs.join_paths(self.repo_dir, self.repo_name, \".git/config\")",
"commit has been done for one file. \"\"\" file1_name = self.random_name() file2_name =",
"modify file\") self.info(\"Check if file has been modified\") modified_file = self.git_client.get_modified_files() self.assertTrue(modified_file) self.assertEqual(file_name,",
"client. - Create a file in repository path. - Check if a new",
"for checking git config file. **Test Scenario** - Get a git client. -",
"that remote_url equals to repo ssh url. \"\"\" repo_ssh_url = \"git@github.com:threefoldtech/js-ng.git\" self.info(\"Set remote",
"Get a git client. - Read the git.config file. - Check that remote_url",
"\"\"\" self.info(\"Create a file in repository path\") file_name = self.random_name() path = j.sals.fs.join_paths(self.repo_dir,",
"pull before commit and should get error\") with self.assertRaises(j.exceptions.Input): self.git_client.pull() self.info(\"Commit the change",
"been done for one file. \"\"\" file1_name = self.random_name() file2_name = self.random_name() self.info(\"Create",
"- Set remote url to repo ssh url. - Read the git config",
"self.repo_name) self.git_client = j.clients.git.new(name=self.instance_name, path=path) def tearDown(self): j.clients.git.delete(self.instance_name) j.sals.fs.rmtree(path=self.repo_dir) def test01_check_git_config(self): \"\"\"Test case",
"added_file[\"N\"][0]) def test06_git_commit(self): \"\"\"Test case for committing a change. **Test Scenario** - Get",
"- Get a git client. - Get the branch name. - Check branch",
"file has been added. - Commit the file 1. - Check if commit",
"a git client. - Create a file in repository path. - Commit the",
"before commit and should get error. - Commit the change of creating a",
"remote_url equals to repo ssh url. \"\"\" repo_ssh_url = \"git@github.com:threefoldtech/js-ng.git\" self.info(\"Set remote url",
"self.assertEqual(file_name, modified_file[\"M\"][0]) def test05_git_add_new_file(self): \"\"\"Test case for adding a new file with git.",
"equal to remote_url\") self.assertIn(self.git_client.remote_url, git_config) def test02_set_remote_ssh_url(self): \"\"\"Test case for setting remote url.",
"self.repo_name) j.sals.process.execute(f\"git add {file1_name}\", cwd=path) self.git_client.commit(\"commit file 1\", add_all=False) self.info(\"Check if commit has",
"a file in repository path. - Try pull before commit and should get",
"git config file\") path = j.sals.fs.join_paths(self.repo_dir, self.repo_name, \".git/config\") git_config = j.sals.fs.read_file(path) self.info(\"Check that",
"Get a git client. - Create a file in repository path. - Try",
"def test06_git_commit(self): \"\"\"Test case for committing a change. **Test Scenario** - Get a",
"adding a new file with git. **Test Scenario** - Get a git client.",
"with add_all=False. **Test Scenario** - Get a git client. - Create a two",
"j.sals.fs.join_paths(self.repo_dir, self.repo_name, \".git/config\") git_config = j.sals.fs.read_file(path) self.info(\"Check that remote_url equals to repo ssh",
"self.info(\"Check if commit has been done for one file\") self.assertNotIn(file1_name, self.git_client.get_modified_files()[\"N\"]) def test08_git_pull(self):",
"\"git@github.com:threefoldtech/js-ng.git\" self.info(\"Set remote url to repo ssh url\") self.git_client.set_remote_url(repo_ssh_url) self.info(\"Read the git config",
"case for checking git config file. **Test Scenario** - Get a git client.",
"a new file has been added\") added_file = self.git_client.get_modified_files() self.assertTrue(added_file) self.assertEqual(file_name, added_file[\"N\"][0]) def",
"git.config file. - Check that remote_url equal to repo_url. - Check that url",
"file in repository path. - Commit the change of creating a new file.",
"= self.random_name() path = j.sals.fs.join_paths(self.repo_dir, self.repo_name, file_name) j.sals.fs.touch(path) self.info(\"Commit changes\") self.git_client.commit(f\"add {file_name}\") self.info(\"modify",
"commit with add_all=False. **Test Scenario** - Get a git client. - Create a",
"has been added\") added_file = self.git_client.get_modified_files() self.assertTrue(added_file) self.assertEqual(file_name, added_file[\"N\"][0]) def test06_git_commit(self): \"\"\"Test case",
"ssh url. - Read the git config file. - Check that remote_url equals",
"\"js-ng\" self.repo_url = \"https://github.com/threefoldtech/js-ng\" j.sals.fs.mkdir(f\"{self.repo_dir}\") j.sals.process.execute(f\"git clone {self.repo_url}\", cwd=f\"{self.repo_dir}\") path = j.sals.fs.join_paths(self.repo_dir, self.repo_name)",
"file1_name].sort(), self.git_client.get_modified_files()[\"N\"].sort()) self.info(\"Commit the file 1\") path = j.sals.fs.join_paths(self.repo_dir, self.repo_name) j.sals.process.execute(f\"git add {file1_name}\",",
"files. **Test Scenario** - Get a git client. - Create a file in",
"a new file with git. **Test Scenario** - Get a git client. -",
"added. - Commit the file 1. - Check if commit has been done",
"if commit has been done for one file. \"\"\" file1_name = self.random_name() file2_name",
"\"\"\"Test case for committing a change. **Test Scenario** - Get a git client.",
"test04_git_modified_files(self): \"\"\"Test case for getting the modified files. **Test Scenario** - Get a",
"ssh url. \"\"\" repo_ssh_url = \"git@github.com:threefoldtech/js-ng.git\" self.info(\"Set remote url to repo ssh url\")",
"last_commit = j.sals.process.execute(\"git log -1\", cwd=path) self.info(\"Check if commit has been done\") self.assertIn(commit_msg,",
"- Commit the file 1. - Check if commit has been done for",
"repo_url. - Check that url equal to remote_url. \"\"\" self.info(\"Read the git.config file\")",
"self.info(\"modify this file\") path = j.sals.fs.join_paths(self.repo_dir, self.repo_name, file_name) j.sals.fs.write_file(path, \"test modify file\") self.info(\"Check",
"new file has been added\") added_file = self.git_client.get_modified_files() self.assertTrue(added_file) self.assertEqual(file_name, added_file[\"N\"][0]) def test06_git_commit(self):",
"= j.sals.fs.join_paths(self.repo_dir, self.repo_name, file2_name) j.sals.fs.touch(path_file1) j.sals.fs.touch(path_file2) self.info(\"Check that two file has been added.\")",
"get error. - Commit the change of creating a new file. - Pull",
"remote repository. \"\"\" file_name = self.random_name() commit_msg = self.random_name() self.info(\"Create a file in",
"the git.config file\") path = j.sals.fs.join_paths(self.repo_dir, self.repo_name, \".git/config\") git_config = j.sals.fs.read_file(path) self.info(\"Check that",
"j.sals.fs.join_paths(self.repo_dir, self.repo_name, file_name) j.sals.fs.touch(path) self.info(\"Commit the change of creating a new file\") self.git_client.commit(commit_msg)",
"j.sals.process.execute(f\"git clone {self.repo_url}\", cwd=f\"{self.repo_dir}\") path = j.sals.fs.join_paths(self.repo_dir, self.repo_name) self.git_client = j.clients.git.new(name=self.instance_name, path=path) def",
"BaseTests class GitTests(BaseTests): def setUp(self): super().setUp() self.instance_name = self.random_name() self.repo_dir = j.sals.fs.join_paths(\"/tmp\", self.random_name())",
"file_name = self.random_name() commit_msg = self.random_name() self.info(\"Create a file in repository path\") path",
"a git client. - Set remote url to repo ssh url. - Read",
"name\") self.assertIn(self.git_client.branch_name, branch_name[1]) def test04_git_modified_files(self): \"\"\"Test case for getting the modified files. **Test",
"url equal to remote_url\") self.assertIn(self.git_client.remote_url, git_config) def test02_set_remote_ssh_url(self): \"\"\"Test case for setting remote",
"client. - Create a two file in repository path. - Check that two",
"Scenario** - Get a git client. - Create a file in repository path.",
"= j.sals.fs.join_paths(self.repo_dir, self.repo_name, file_name) j.sals.fs.touch(path) self.info(\"Check if a new file has been added\")",
"j.sals.fs.join_paths(self.repo_dir, self.repo_name, file_name) j.sals.fs.touch(path) self.info(\"Commit changes\") self.git_client.commit(f\"add {file_name}\") self.info(\"modify this file\") path =",
"checking git config file. **Test Scenario** - Get a git client. - Read",
"def test05_git_add_new_file(self): \"\"\"Test case for adding a new file with git. **Test Scenario**",
"path = j.sals.fs.join_paths(self.repo_dir, self.repo_name, file_name) j.sals.fs.touch(path) self.info(\"Check if a new file has been",
"jumpscale.loader import j from tests.base_tests import BaseTests class GitTests(BaseTests): def setUp(self): super().setUp() self.instance_name",
"should get error. - Commit the change of creating a new file. -",
"if commit has been done for one file\") self.assertNotIn(file1_name, self.git_client.get_modified_files()[\"N\"]) def test08_git_pull(self): \"\"\"Test",
"import BaseTests class GitTests(BaseTests): def setUp(self): super().setUp() self.instance_name = self.random_name() self.repo_dir = j.sals.fs.join_paths(\"/tmp\",",
"path. - Check if a new file has been added \"\"\" self.info(\"Create a",
"- Check if file has been modified \"\"\" self.info(\"Create a file in repository",
"1. - Check if commit has been done for one file. \"\"\" file1_name",
"file_name) j.sals.fs.touch(path) self.info(\"Commit the change of creating a new file\") self.git_client.commit(commit_msg) self.info(\"Get commit",
"has been done for one file\") self.assertNotIn(file1_name, self.git_client.get_modified_files()[\"N\"]) def test08_git_pull(self): \"\"\"Test case for",
"change of creating a new file. - Pull from remote repository. \"\"\" file_name",
"pull before commit and should get error. - Commit the change of creating",
"test08_git_pull(self): \"\"\"Test case for pulling a repository **Test Scenario** - Get a git",
"file. - Get commit logs. - Check if commit has been done. \"\"\"",
"git client. - Get the branch name. - Check branch name. \"\"\" self.info(\"Get",
"in repository path. - Commit the change of creating a new file. -",
"git.config file\") path = j.sals.fs.join_paths(self.repo_dir, self.repo_name, \".git/config\") git_config = j.sals.fs.read_file(path) self.info(\"Check that remote_url",
"a git client. - Create a file in repository path. - Try pull",
"file 1\") path = j.sals.fs.join_paths(self.repo_dir, self.repo_name) j.sals.process.execute(f\"git add {file1_name}\", cwd=path) self.git_client.commit(\"commit file 1\",",
"cwd=path) self.git_client.commit(\"commit file 1\", add_all=False) self.info(\"Check if commit has been done for one",
"class GitTests(BaseTests): def setUp(self): super().setUp() self.instance_name = self.random_name() self.repo_dir = j.sals.fs.join_paths(\"/tmp\", self.random_name()) self.repo_name",
"j.sals.fs.join_paths(self.repo_dir, self.repo_name, \".git/config\") git_config = j.sals.fs.read_file(path) self.info(\"Check that remote_url equal to repo_url\") self.assertEqual(self.repo_url,",
"self.info(\"Commit the change of creating a new file\") self.git_client.commit(commit_msg) self.info(\"Pull from remote repository\")",
"self.repo_name, file_name) j.sals.fs.touch(path) self.info(\"Check if a new file has been added\") added_file =",
"self.repo_name, file_name) j.sals.fs.touch(path) self.info(\"Commit the change of creating a new file\") self.git_client.commit(commit_msg) self.info(\"Get",
"- Check if commit has been done. \"\"\" file_name = self.random_name() commit_msg =",
"j from tests.base_tests import BaseTests class GitTests(BaseTests): def setUp(self): super().setUp() self.instance_name = self.random_name()",
"path\") path_file1 = j.sals.fs.join_paths(self.repo_dir, self.repo_name, file1_name) path_file2 = j.sals.fs.join_paths(self.repo_dir, self.repo_name, file2_name) j.sals.fs.touch(path_file1) j.sals.fs.touch(path_file2)",
"= j.sals.fs.join_paths(self.repo_dir, self.repo_name, \".git/config\") git_config = j.sals.fs.read_file(path) self.info(\"Check that remote_url equals to repo",
"\"\"\"Test case for getting the modified files. **Test Scenario** - Get a git",
"\".git/config\") git_config = j.sals.fs.read_file(path) self.info(\"Check that remote_url equals to repo ssh url\") self.assertEqual(self.git_client.remote_url,",
"self.assertEqual(file_name, added_file[\"N\"][0]) def test06_git_commit(self): \"\"\"Test case for committing a change. **Test Scenario** -",
"- Commit the change of creating a new file. - Pull from remote",
"self.info(\"Check that two file has been added.\") self.assertEqual([file2_name, file1_name].sort(), self.git_client.get_modified_files()[\"N\"].sort()) self.info(\"Commit the file",
"{self.repo_url}\", cwd=f\"{self.repo_dir}\") path = j.sals.fs.join_paths(self.repo_dir, self.repo_name) self.git_client = j.clients.git.new(name=self.instance_name, path=path) def tearDown(self): j.clients.git.delete(self.instance_name)",
"- Try pull before commit and should get error. - Commit the change",
"repository path\") file_name = self.random_name() path = j.sals.fs.join_paths(self.repo_dir, self.repo_name, file_name) j.sals.fs.touch(path) self.info(\"Commit changes\")",
"file. \"\"\" file1_name = self.random_name() file2_name = self.random_name() self.info(\"Create a two file in",
"Commit changes - modify this file - Check if file has been modified",
"for getting the modified files. **Test Scenario** - Get a git client. -",
"client. - Create a file in repository path. - Commit the change of",
"file in repository path\") file_name = self.random_name() path = j.sals.fs.join_paths(self.repo_dir, self.repo_name, file_name) j.sals.fs.touch(path)",
"that two file has been added.\") self.assertEqual([file2_name, file1_name].sort(), self.git_client.get_modified_files()[\"N\"].sort()) self.info(\"Commit the file 1\")",
"client. - Read the git.config file. - Check that remote_url equal to repo_url.",
"from jumpscale.loader import j from tests.base_tests import BaseTests class GitTests(BaseTests): def setUp(self): super().setUp()",
"= self.git_client.get_modified_files() self.assertTrue(added_file) self.assertEqual(file_name, added_file[\"N\"][0]) def test06_git_commit(self): \"\"\"Test case for committing a change.",
"- Check that url equal to remote_url. \"\"\" self.info(\"Read the git.config file\") path",
"self.assertIn(self.git_client.remote_url, git_config) def test02_set_remote_ssh_url(self): \"\"\"Test case for setting remote url. **Test Scenario** -",
"committing a change. **Test Scenario** - Get a git client. - Create a",
"\"\"\"Test case for setting remote url. **Test Scenario** - Get a git client.",
"file\") self.git_client.commit(commit_msg) self.info(\"Get commit logs\") path = j.sals.fs.join_paths(self.repo_dir, self.repo_name) last_commit = j.sals.process.execute(\"git log",
"git config file. - Check that remote_url equals to repo ssh url. \"\"\"",
"a file in repository path\") path = j.sals.fs.join_paths(self.repo_dir, self.repo_name, file_name) j.sals.fs.touch(path) self.info(\"Try pull",
"branch name\") path = j.sals.fs.join_paths(self.repo_dir, self.repo_name) branch_name = j.sals.process.execute(\"git branch --show-current\", cwd=path) self.info(\"Check",
"logs. - Check if commit has been done. \"\"\" file_name = self.random_name() commit_msg",
"checking a branch name. **Test Scenario** - Get a git client. - Get",
"file\") self.assertNotIn(file1_name, self.git_client.get_modified_files()[\"N\"]) def test08_git_pull(self): \"\"\"Test case for pulling a repository **Test Scenario**",
"file - Check if file has been modified \"\"\" self.info(\"Create a file in",
"this file\") path = j.sals.fs.join_paths(self.repo_dir, self.repo_name, file_name) j.sals.fs.write_file(path, \"test modify file\") self.info(\"Check if",
"\"\"\"Test case for adding a new file with git. **Test Scenario** - Get",
"self.git_client.get_modified_files()[\"N\"]) def test08_git_pull(self): \"\"\"Test case for pulling a repository **Test Scenario** - Get",
"self.repo_name, \".git/config\") git_config = j.sals.fs.read_file(path) self.info(\"Check that remote_url equals to repo ssh url\")",
"- Check if commit has been done for one file. \"\"\" file1_name =",
"= j.sals.fs.join_paths(self.repo_dir, self.repo_name, file_name) j.sals.fs.touch(path) self.info(\"Try pull before commit and should get error\")",
"self.repo_dir = j.sals.fs.join_paths(\"/tmp\", self.random_name()) self.repo_name = \"js-ng\" self.repo_url = \"https://github.com/threefoldtech/js-ng\" j.sals.fs.mkdir(f\"{self.repo_dir}\") j.sals.process.execute(f\"git clone",
"tests.base_tests import BaseTests class GitTests(BaseTests): def setUp(self): super().setUp() self.instance_name = self.random_name() self.repo_dir =",
"in repository path\") path = j.sals.fs.join_paths(self.repo_dir, self.repo_name, file_name) j.sals.fs.touch(path) self.info(\"Commit the change of",
"Check if commit has been done for one file. \"\"\" file1_name = self.random_name()",
"self.git_client.commit(f\"add {file_name}\") self.info(\"modify this file\") path = j.sals.fs.join_paths(self.repo_dir, self.repo_name, file_name) j.sals.fs.write_file(path, \"test modify",
"new file with git. **Test Scenario** - Get a git client. - Create",
"a change. **Test Scenario** - Get a git client. - Create a file",
"repository path. - Commit changes - modify this file - Check if file",
"repository path. - Commit the change of creating a new file. - Get",
"should get error\") with self.assertRaises(j.exceptions.Input): self.git_client.pull() self.info(\"Commit the change of creating a new",
"j.sals.fs.join_paths(self.repo_dir, self.repo_name, file_name) j.sals.fs.touch(path) self.info(\"Check if a new file has been added\") added_file",
"file1_name) path_file2 = j.sals.fs.join_paths(self.repo_dir, self.repo_name, file2_name) j.sals.fs.touch(path_file1) j.sals.fs.touch(path_file2) self.info(\"Check that two file has",
"file\") path = j.sals.fs.join_paths(self.repo_dir, self.repo_name, \".git/config\") git_config = j.sals.fs.read_file(path) self.info(\"Check that remote_url equal",
"path. - Check that two file has been added. - Commit the file",
"equals to repo ssh url\") self.assertEqual(self.git_client.remote_url, repo_ssh_url) self.assertIn(self.git_client.remote_url, git_config) def test03_git_branch(self): \"\"\"Test case",
"**Test Scenario** - Get a git client. - Get the branch name. -",
"case for setting remote url. **Test Scenario** - Get a git client. -",
"a new file\") self.git_client.commit(commit_msg) self.info(\"Get commit logs\") path = j.sals.fs.join_paths(self.repo_dir, self.repo_name) last_commit =",
"path = j.sals.fs.join_paths(self.repo_dir, self.repo_name, file_name) j.sals.fs.write_file(path, \"test modify file\") self.info(\"Check if file has",
"= j.sals.fs.read_file(path) self.info(\"Check that remote_url equals to repo ssh url\") self.assertEqual(self.git_client.remote_url, repo_ssh_url) self.assertIn(self.git_client.remote_url,",
"with git. **Test Scenario** - Get a git client. - Create a file",
"def test04_git_modified_files(self): \"\"\"Test case for getting the modified files. **Test Scenario** - Get",
"= j.sals.fs.join_paths(self.repo_dir, self.repo_name, file_name) j.sals.fs.touch(path) self.info(\"Commit the change of creating a new file\")",
"Check that remote_url equals to repo ssh url. \"\"\" repo_ssh_url = \"git@github.com:threefoldtech/js-ng.git\" self.info(\"Set",
"file has been added.\") self.assertEqual([file2_name, file1_name].sort(), self.git_client.get_modified_files()[\"N\"].sort()) self.info(\"Commit the file 1\") path =",
"self.git_client.set_remote_url(repo_ssh_url) self.info(\"Read the git config file\") path = j.sals.fs.join_paths(self.repo_dir, self.repo_name, \".git/config\") git_config =",
"git config file. **Test Scenario** - Get a git client. - Read the",
"branch name. - Check branch name. \"\"\" self.info(\"Get the branch name\") path =",
"case for checking a commit with add_all=False. **Test Scenario** - Get a git",
"cwd=path) self.info(\"Check branch name\") self.assertIn(self.git_client.branch_name, branch_name[1]) def test04_git_modified_files(self): \"\"\"Test case for getting the",
"repository path. - Try pull before commit and should get error. - Commit",
"file has been added\") added_file = self.git_client.get_modified_files() self.assertTrue(added_file) self.assertEqual(file_name, added_file[\"N\"][0]) def test06_git_commit(self): \"\"\"Test",
"new file has been added \"\"\" self.info(\"Create a file in repository path\") file_name",
"if a new file has been added \"\"\" self.info(\"Create a file in repository",
"a new file has been added \"\"\" self.info(\"Create a file in repository path\")",
"for adding a new file with git. **Test Scenario** - Get a git",
"add_all=False. **Test Scenario** - Get a git client. - Create a two file",
"in repository path\") file_name = self.random_name() path = j.sals.fs.join_paths(self.repo_dir, self.repo_name, file_name) j.sals.fs.touch(path) self.info(\"Check",
"get error\") with self.assertRaises(j.exceptions.Input): self.git_client.pull() self.info(\"Commit the change of creating a new file\")",
"repo ssh url\") self.assertEqual(self.git_client.remote_url, repo_ssh_url) self.assertIn(self.git_client.remote_url, git_config) def test03_git_branch(self): \"\"\"Test case for checking",
"self.info(\"Check branch name\") self.assertIn(self.git_client.branch_name, branch_name[1]) def test04_git_modified_files(self): \"\"\"Test case for getting the modified",
"self.info(\"Check that git config url equal to remote_url\") self.assertIn(self.git_client.remote_url, git_config) def test02_set_remote_ssh_url(self): \"\"\"Test",
"in repository path\") path = j.sals.fs.join_paths(self.repo_dir, self.repo_name, file_name) j.sals.fs.touch(path) self.info(\"Try pull before commit",
"- Create a file in repository path. - Commit the change of creating",
"Get a git client. - Create a file in repository path. - Check",
"= self.random_name() self.info(\"Create a file in repository path\") path = j.sals.fs.join_paths(self.repo_dir, self.repo_name, file_name)",
"self.git_client.remote_url) self.info(\"Check that git config url equal to remote_url\") self.assertIn(self.git_client.remote_url, git_config) def test02_set_remote_ssh_url(self):",
"done\") self.assertIn(commit_msg, str(last_commit)) def test07_git_commit_one_file(self): \"\"\"Test case for checking a commit with add_all=False.",
"Set remote url to repo ssh url. - Read the git config file.",
"self.assertNotIn(file1_name, self.git_client.get_modified_files()[\"N\"]) def test08_git_pull(self): \"\"\"Test case for pulling a repository **Test Scenario** -",
"equal to remote_url. \"\"\" self.info(\"Read the git.config file\") path = j.sals.fs.join_paths(self.repo_dir, self.repo_name, \".git/config\")",
"path\") file_name = self.random_name() path = j.sals.fs.join_paths(self.repo_dir, self.repo_name, file_name) j.sals.fs.touch(path) self.info(\"Check if a",
"file has been modified\") modified_file = self.git_client.get_modified_files() self.assertTrue(modified_file) self.assertEqual(file_name, modified_file[\"M\"][0]) def test05_git_add_new_file(self): \"\"\"Test",
"change of creating a new file\") self.git_client.commit(commit_msg) self.info(\"Get commit logs\") path = j.sals.fs.join_paths(self.repo_dir,",
"def test08_git_pull(self): \"\"\"Test case for pulling a repository **Test Scenario** - Get a",
"of creating a new file. - Pull from remote repository. \"\"\" file_name =",
"= j.sals.fs.join_paths(\"/tmp\", self.random_name()) self.repo_name = \"js-ng\" self.repo_url = \"https://github.com/threefoldtech/js-ng\" j.sals.fs.mkdir(f\"{self.repo_dir}\") j.sals.process.execute(f\"git clone {self.repo_url}\",",
"- Get a git client. - Create a file in repository path. -",
"remote url to repo ssh url\") self.git_client.set_remote_url(repo_ssh_url) self.info(\"Read the git config file\") path",
"a repository **Test Scenario** - Get a git client. - Create a file",
"been added.\") self.assertEqual([file2_name, file1_name].sort(), self.git_client.get_modified_files()[\"N\"].sort()) self.info(\"Commit the file 1\") path = j.sals.fs.join_paths(self.repo_dir, self.repo_name)",
"j.sals.fs.touch(path) self.info(\"Check if a new file has been added\") added_file = self.git_client.get_modified_files() self.assertTrue(added_file)",
"= self.random_name() file2_name = self.random_name() self.info(\"Create a two file in repository path\") path_file1",
"two file has been added. - Commit the file 1. - Check if",
"equals to repo ssh url. \"\"\" repo_ssh_url = \"git@github.com:threefoldtech/js-ng.git\" self.info(\"Set remote url to",
"file in repository path\") path = j.sals.fs.join_paths(self.repo_dir, self.repo_name, file_name) j.sals.fs.touch(path) self.info(\"Commit the change",
"repo ssh url. - Read the git config file. - Check that remote_url",
"j.sals.fs.join_paths(self.repo_dir, self.repo_name) self.git_client = j.clients.git.new(name=self.instance_name, path=path) def tearDown(self): j.clients.git.delete(self.instance_name) j.sals.fs.rmtree(path=self.repo_dir) def test01_check_git_config(self): \"\"\"Test",
"1\", add_all=False) self.info(\"Check if commit has been done for one file\") self.assertNotIn(file1_name, self.git_client.get_modified_files()[\"N\"])",
"j.sals.fs.join_paths(self.repo_dir, self.repo_name) j.sals.process.execute(f\"git add {file1_name}\", cwd=path) self.git_client.commit(\"commit file 1\", add_all=False) self.info(\"Check if commit",
"= j.sals.fs.join_paths(self.repo_dir, self.repo_name, file_name) j.sals.fs.write_file(path, \"test modify file\") self.info(\"Check if file has been",
"git client. - Set remote url to repo ssh url. - Read the",
"from tests.base_tests import BaseTests class GitTests(BaseTests): def setUp(self): super().setUp() self.instance_name = self.random_name() self.repo_dir",
"new file. - Get commit logs. - Check if commit has been done.",
"to repo ssh url. - Read the git config file. - Check that",
"--show-current\", cwd=path) self.info(\"Check branch name\") self.assertIn(self.git_client.branch_name, branch_name[1]) def test04_git_modified_files(self): \"\"\"Test case for getting",
"j.sals.fs.join_paths(self.repo_dir, self.repo_name, file2_name) j.sals.fs.touch(path_file1) j.sals.fs.touch(path_file2) self.info(\"Check that two file has been added.\") self.assertEqual([file2_name,",
"\"\"\" self.info(\"Read the git.config file\") path = j.sals.fs.join_paths(self.repo_dir, self.repo_name, \".git/config\") git_config = j.sals.fs.read_file(path)",
"name. \"\"\" self.info(\"Get the branch name\") path = j.sals.fs.join_paths(self.repo_dir, self.repo_name) branch_name = j.sals.process.execute(\"git",
"self.info(\"Get the branch name\") path = j.sals.fs.join_paths(self.repo_dir, self.repo_name) branch_name = j.sals.process.execute(\"git branch --show-current\",",
"error\") with self.assertRaises(j.exceptions.Input): self.git_client.pull() self.info(\"Commit the change of creating a new file\") self.git_client.commit(commit_msg)",
"self.random_name() file2_name = self.random_name() self.info(\"Create a two file in repository path\") path_file1 =",
"test07_git_commit_one_file(self): \"\"\"Test case for checking a commit with add_all=False. **Test Scenario** - Get",
"remote_url equal to repo_url\") self.assertEqual(self.repo_url, self.git_client.remote_url) self.info(\"Check that git config url equal to",
"file. **Test Scenario** - Get a git client. - Read the git.config file.",
"path = j.sals.fs.join_paths(self.repo_dir, self.repo_name, file_name) j.sals.fs.touch(path) self.info(\"Commit the change of creating a new",
"- Check that remote_url equals to repo ssh url. \"\"\" repo_ssh_url = \"git@github.com:threefoldtech/js-ng.git\"",
"the change of creating a new file\") self.git_client.commit(commit_msg) self.info(\"Get commit logs\") path =",
"commit and should get error. - Commit the change of creating a new",
"self.info(\"Try pull before commit and should get error\") with self.assertRaises(j.exceptions.Input): self.git_client.pull() self.info(\"Commit the",
"file2_name = self.random_name() self.info(\"Create a two file in repository path\") path_file1 = j.sals.fs.join_paths(self.repo_dir,",
"{file_name}\") self.info(\"modify this file\") path = j.sals.fs.join_paths(self.repo_dir, self.repo_name, file_name) j.sals.fs.write_file(path, \"test modify file\")",
"j.sals.fs.touch(path_file2) self.info(\"Check that two file has been added.\") self.assertEqual([file2_name, file1_name].sort(), self.git_client.get_modified_files()[\"N\"].sort()) self.info(\"Commit the",
"Scenario** - Get a git client. - Read the git.config file. - Check",
"import j from tests.base_tests import BaseTests class GitTests(BaseTests): def setUp(self): super().setUp() self.instance_name =",
"= \"js-ng\" self.repo_url = \"https://github.com/threefoldtech/js-ng\" j.sals.fs.mkdir(f\"{self.repo_dir}\") j.sals.process.execute(f\"git clone {self.repo_url}\", cwd=f\"{self.repo_dir}\") path = j.sals.fs.join_paths(self.repo_dir,",
"file_name = self.random_name() path = j.sals.fs.join_paths(self.repo_dir, self.repo_name, file_name) j.sals.fs.touch(path) self.info(\"Commit changes\") self.git_client.commit(f\"add {file_name}\")",
"been added \"\"\" self.info(\"Create a file in repository path\") file_name = self.random_name() path",
"self.repo_name, file_name) j.sals.fs.touch(path) self.info(\"Commit changes\") self.git_client.commit(f\"add {file_name}\") self.info(\"modify this file\") path = j.sals.fs.join_paths(self.repo_dir,",
"and should get error. - Commit the change of creating a new file.",
"file_name) j.sals.fs.write_file(path, \"test modify file\") self.info(\"Check if file has been modified\") modified_file =",
"logs\") path = j.sals.fs.join_paths(self.repo_dir, self.repo_name) last_commit = j.sals.process.execute(\"git log -1\", cwd=path) self.info(\"Check if",
"to repo ssh url. \"\"\" repo_ssh_url = \"git@github.com:threefoldtech/js-ng.git\" self.info(\"Set remote url to repo",
"test05_git_add_new_file(self): \"\"\"Test case for adding a new file with git. **Test Scenario** -",
"setUp(self): super().setUp() self.instance_name = self.random_name() self.repo_dir = j.sals.fs.join_paths(\"/tmp\", self.random_name()) self.repo_name = \"js-ng\" self.repo_url",
"url. - Read the git config file. - Check that remote_url equals to",
"a commit with add_all=False. **Test Scenario** - Get a git client. - Create",
"def setUp(self): super().setUp() self.instance_name = self.random_name() self.repo_dir = j.sals.fs.join_paths(\"/tmp\", self.random_name()) self.repo_name = \"js-ng\"",
"- Read the git.config file. - Check that remote_url equal to repo_url. -",
"for setting remote url. **Test Scenario** - Get a git client. - Set",
"path. - Commit the change of creating a new file. - Get commit",
"repository path\") path_file1 = j.sals.fs.join_paths(self.repo_dir, self.repo_name, file1_name) path_file2 = j.sals.fs.join_paths(self.repo_dir, self.repo_name, file2_name) j.sals.fs.touch(path_file1)",
"j.sals.fs.touch(path) self.info(\"Commit the change of creating a new file\") self.git_client.commit(commit_msg) self.info(\"Get commit logs\")",
"\"\"\"Test case for checking git config file. **Test Scenario** - Get a git",
"file_name = self.random_name() path = j.sals.fs.join_paths(self.repo_dir, self.repo_name, file_name) j.sals.fs.touch(path) self.info(\"Check if a new",
"a new file. - Get commit logs. - Check if commit has been",
"self.repo_name, file2_name) j.sals.fs.touch(path_file1) j.sals.fs.touch(path_file2) self.info(\"Check that two file has been added.\") self.assertEqual([file2_name, file1_name].sort(),",
"new file\") self.git_client.commit(commit_msg) self.info(\"Get commit logs\") path = j.sals.fs.join_paths(self.repo_dir, self.repo_name) last_commit = j.sals.process.execute(\"git",
"self.git_client.get_modified_files() self.assertTrue(modified_file) self.assertEqual(file_name, modified_file[\"M\"][0]) def test05_git_add_new_file(self): \"\"\"Test case for adding a new file",
"one file\") self.assertNotIn(file1_name, self.git_client.get_modified_files()[\"N\"]) def test08_git_pull(self): \"\"\"Test case for pulling a repository **Test",
"self.git_client.get_modified_files() self.assertTrue(added_file) self.assertEqual(file_name, added_file[\"N\"][0]) def test06_git_commit(self): \"\"\"Test case for committing a change. **Test",
"add_all=False) self.info(\"Check if commit has been done for one file\") self.assertNotIn(file1_name, self.git_client.get_modified_files()[\"N\"]) def",
"def tearDown(self): j.clients.git.delete(self.instance_name) j.sals.fs.rmtree(path=self.repo_dir) def test01_check_git_config(self): \"\"\"Test case for checking git config file.",
"j.sals.fs.join_paths(self.repo_dir, self.repo_name) branch_name = j.sals.process.execute(\"git branch --show-current\", cwd=path) self.info(\"Check branch name\") self.assertIn(self.git_client.branch_name, branch_name[1])",
"self.info(\"Get commit logs\") path = j.sals.fs.join_paths(self.repo_dir, self.repo_name) last_commit = j.sals.process.execute(\"git log -1\", cwd=path)",
"been modified \"\"\" self.info(\"Create a file in repository path\") file_name = self.random_name() path",
"j.sals.fs.join_paths(self.repo_dir, self.repo_name, file_name) j.sals.fs.write_file(path, \"test modify file\") self.info(\"Check if file has been modified\")",
"has been done for one file. \"\"\" file1_name = self.random_name() file2_name = self.random_name()",
"for one file\") self.assertNotIn(file1_name, self.git_client.get_modified_files()[\"N\"]) def test08_git_pull(self): \"\"\"Test case for pulling a repository",
"a git client. - Create a two file in repository path. - Check",
"self.repo_name, file_name) j.sals.fs.touch(path) self.info(\"Try pull before commit and should get error\") with self.assertRaises(j.exceptions.Input):",
"commit has been done. \"\"\" file_name = self.random_name() commit_msg = self.random_name() self.info(\"Create a",
"a two file in repository path\") path_file1 = j.sals.fs.join_paths(self.repo_dir, self.repo_name, file1_name) path_file2 =",
"Read the git config file. - Check that remote_url equals to repo ssh",
"self.info(\"Create a two file in repository path\") path_file1 = j.sals.fs.join_paths(self.repo_dir, self.repo_name, file1_name) path_file2",
"been done\") self.assertIn(commit_msg, str(last_commit)) def test07_git_commit_one_file(self): \"\"\"Test case for checking a commit with",
"- Get commit logs. - Check if commit has been done. \"\"\" file_name",
"self.random_name() commit_msg = self.random_name() self.info(\"Create a file in repository path\") path = j.sals.fs.join_paths(self.repo_dir,",
"git client. - Create a file in repository path. - Try pull before",
"self.info(\"Check if file has been modified\") modified_file = self.git_client.get_modified_files() self.assertTrue(modified_file) self.assertEqual(file_name, modified_file[\"M\"][0]) def",
"self.info(\"Commit the change of creating a new file\") self.git_client.commit(commit_msg) self.info(\"Get commit logs\") path",
"Get a git client. - Get the branch name. - Check branch name.",
"self.repo_name, file1_name) path_file2 = j.sals.fs.join_paths(self.repo_dir, self.repo_name, file2_name) j.sals.fs.touch(path_file1) j.sals.fs.touch(path_file2) self.info(\"Check that two file",
"- Create a file in repository path. - Commit changes - modify this",
"cwd=path) self.info(\"Check if commit has been done\") self.assertIn(commit_msg, str(last_commit)) def test07_git_commit_one_file(self): \"\"\"Test case",
"added.\") self.assertEqual([file2_name, file1_name].sort(), self.git_client.get_modified_files()[\"N\"].sort()) self.info(\"Commit the file 1\") path = j.sals.fs.join_paths(self.repo_dir, self.repo_name) j.sals.process.execute(f\"git",
"the git config file. - Check that remote_url equals to repo ssh url.",
"file in repository path\") path = j.sals.fs.join_paths(self.repo_dir, self.repo_name, file_name) j.sals.fs.touch(path) self.info(\"Try pull before",
"Check branch name. \"\"\" self.info(\"Get the branch name\") path = j.sals.fs.join_paths(self.repo_dir, self.repo_name) branch_name",
"\"\"\"Test case for checking a commit with add_all=False. **Test Scenario** - Get a",
"path\") file_name = self.random_name() path = j.sals.fs.join_paths(self.repo_dir, self.repo_name, file_name) j.sals.fs.touch(path) self.info(\"Commit changes\") self.git_client.commit(f\"add",
"of creating a new file. - Get commit logs. - Check if commit",
"self.git_client.commit(\"commit file 1\", add_all=False) self.info(\"Check if commit has been done for one file\")",
"a branch name. **Test Scenario** - Get a git client. - Get the",
"self.assertTrue(modified_file) self.assertEqual(file_name, modified_file[\"M\"][0]) def test05_git_add_new_file(self): \"\"\"Test case for adding a new file with",
"Scenario** - Get a git client. - Set remote url to repo ssh"
] |
[
"'figure.titleweight': 'bold', 'savefig.dpi': 200, 'axes.titlesize': 18, # main title 'axes.labelsize': 16, # x",
"tau = 1. averagePower = totalEnergy / tau #### Reshape to ensure needed",
"drawing with matplotlib during debug mode plt._INSTALL_FIG_OBSERVER = True mpl.rcParams.update(plotParams) plt.ion() def PlotCodingScheme(ModFs,",
"if(ModFs.shape[0] < ModFs.shape[1]): ModFs = ModFs.transpose() if(DemodFs.shape[0] < DemodFs.shape[1]): DemodFs = DemodFs.transpose() ####",
"demodulation, and the correlation. Args: modF (numpy.ndarray): Modulation functions. N x K matrix.",
"axarr = fig.get_axes() ## Make all plots ## Calculate Avg power. avgPower =",
"CorrFs[:,i], label='Crr-'+labelInfo,linewidth=2, color=colors[i]) axarr[3*i + 0].plot(t, avgPower, '--', label='AvgPower', linewidth=3, color=colors[i]) ## Set",
"is larger than the number of coding pairs, i.e. rows>cols if(ModFs.shape[0] < ModFs.shape[1]):",
"'xtick.minor.visible': True, 'ytick.labelsize': 14, 'ytick.minor.visible': True, 'lines.linewidth': 2, 'lines.markersize': 8.0, 'legend.fontsize': 14, 'legend.shadow':",
"N)] ## Plot ObjCorrF first so that stars don't cover the corrFs. for",
"with modulation, demodulation, and the correlation. Args: modF (numpy.ndarray): Modulation functions. N x",
"pairs, i.e. rows>cols if(ModFs.shape[0] < ModFs.shape[1]): ModFs = ModFs.transpose() if(DemodFs.shape[0] < DemodFs.shape[1]): DemodFs",
"CorrFs = Utils.GetCorrelationFunctions(ModFs=ModFs,DemodFs=DemodFs) #### Plot Decomposition ## Clear current plot plt.clf() ## Get",
"Verify Inputs assert(ModFs.shape == DemodFs.shape), \"Input Error - PlotCodingScheme: ModFs and \\ DemodFs",
"# from IPython.core import debugger # breakpoint = debugger.set_trace #### Local imports import",
"modulation, demodulation, and the correlation. Args: modF (numpy.ndarray): Modulation functions. N x K",
"#### Reshape to ensure needed dimensions ## Assume that the number of elements",
"Args: modF (numpy.ndarray): Modulation functions. N x K matrix. demodF (numpy.ndarray): Demodulation functions.",
"axarr[3*i + 2].set_xlabel('Phase') axarr[3*i + 0].set_ylabel('Instant Power') axarr[3*i + 1].set_ylabel('Exposure') axarr[3*i + 2].set_ylabel('Magnitude')",
"'--', label='AvgPower', linewidth=3, color=colors[i]) ## Set axis labels axarr[3*i + 0].set_xlabel('Time') axarr[3*i +",
"breakpoint() fig.add_subplot(K,3,3*i + 1) fig.add_subplot(K,3,3*i + 2) fig.add_subplot(K,3,3*i + 3) axarr = fig.get_axes()",
"PlotCodingScheme(ModFs, DemodFs): \"\"\"PlotCodingScheme: Create a 1x3 figure with modulation, demodulation, and the correlation.",
"imports #### Library imports import numpy as np import matplotlib as mpl import",
"+ 0].plot(t, ModFs[:,i], label='Md-'+labelInfo,linewidth=2, color=colors[i]) axarr[3*i + 1].plot(t, DemodFs[:,i], label='Dmd-'+labelInfo,linewidth=2, color=colors[i]) axarr[3*i +",
"\\ DemodFs should be the same dimensions.\" #### Set some parameters (N,K) =",
"'legend.fontsize': 14, 'legend.shadow': True, } mpl.use('Qt4Agg', warn=False) ## Needed to allow drawing with",
"axis array for i in range(K): # breakpoint() fig.add_subplot(K,3,3*i + 1) fig.add_subplot(K,3,3*i +",
"ModFs[:,i], label='Md-'+labelInfo,linewidth=2, color=colors[i]) axarr[3*i + 1].plot(t, DemodFs[:,i], label='Dmd-'+labelInfo,linewidth=2, color=colors[i]) axarr[3*i + 2].plot(phase, CorrFs[:,i],",
"+ 3) axarr = fig.get_axes() ## Make all plots ## Calculate Avg power.",
"Decomposition ## Clear current plot plt.clf() ## Get current figure fig = plt.gcf()",
"ObjCorrF first so that stars don't cover the corrFs. for i in range(0,",
"14, 'ytick.minor.visible': True, 'lines.linewidth': 2, 'lines.markersize': 8.0, 'legend.fontsize': 14, 'legend.shadow': True, } mpl.use('Qt4Agg',",
"and y titles 'axes.labelweight': 'bold', # x and y titles 'grid.linestyle': '--', 'grid.linewidth':",
"number of elements is larger than the number of coding pairs, i.e. rows>cols",
"plt.axis: Axis handle \"\"\" #### Assume the following constants totalEnergy = 1. tau",
"fig.add_subplot(K,3,3*i + 2) fig.add_subplot(K,3,3*i + 3) axarr = fig.get_axes() ## Make all plots",
"= 1. averagePower = totalEnergy / tau #### Reshape to ensure needed dimensions",
"figure with modulation, demodulation, and the correlation. Args: modF (numpy.ndarray): Modulation functions. N",
"plotting parameters \"\"\" #### Python imports #### Library imports import numpy as np",
"functions CorrFs = Utils.GetCorrelationFunctions(ModFs=ModFs,DemodFs=DemodFs) #### Plot Decomposition ## Clear current plot plt.clf() ##",
"debugger.set_trace #### Local imports import Utils #### Default matplotlib preferences plt.style.use('ggplot') colors =",
"plt._INSTALL_FIG_OBSERVER = True mpl.rcParams.update(plotParams) plt.ion() def PlotCodingScheme(ModFs, DemodFs): \"\"\"PlotCodingScheme: Create a 1x3 figure",
"'figure.dpi': 80, 'figure.autolayout': True, 'figure.titleweight': 'bold', 'savefig.dpi': 200, 'axes.titlesize': 18, # main title",
"def PlotCodingScheme(ModFs, DemodFs): \"\"\"PlotCodingScheme: Create a 1x3 figure with modulation, demodulation, and the",
"<filename>UtilsPlot.py \"\"\"UtilsPlot Attributes: colors (TYPE): Colors for plotting plotParams (TYPE): Default plotting parameters",
"#### Plot Decomposition ## Clear current plot plt.clf() ## Get current figure fig",
"'axes.titlesize': 18, # main title 'axes.labelsize': 16, # x and y titles 'axes.titleweight':",
"range(K): # breakpoint() fig.add_subplot(K,3,3*i + 1) fig.add_subplot(K,3,3*i + 2) fig.add_subplot(K,3,3*i + 3) axarr",
"color=colors[i]) axarr[3*i + 0].plot(t, avgPower, '--', label='AvgPower', linewidth=3, color=colors[i]) ## Set axis labels",
"i in range(K): # breakpoint() fig.add_subplot(K,3,3*i + 1) fig.add_subplot(K,3,3*i + 2) fig.add_subplot(K,3,3*i +",
"Set Titles axarr[0].set_title('Modulation') axarr[1].set_title('Demodulation') axarr[2].set_title('Correlation') # ## Set ylimit so that we can",
"axarr[3*i + 2].set_ylabel('Magnitude') ## Set Titles axarr[0].set_title('Modulation') axarr[1].set_title('Demodulation') axarr[2].set_title('Correlation') # ## Set ylimit",
"i.e. rows>cols if(ModFs.shape[0] < ModFs.shape[1]): ModFs = ModFs.transpose() if(DemodFs.shape[0] < DemodFs.shape[1]): DemodFs =",
"functions. N x K matrix. demodF (numpy.ndarray): Demodulation functions. N x K matrix",
"DemodFs): \"\"\"PlotCodingScheme: Create a 1x3 figure with modulation, demodulation, and the correlation. Args:",
"+ 1].set_ylabel('Exposure') axarr[3*i + 2].set_ylabel('Magnitude') ## Set Titles axarr[0].set_title('Modulation') axarr[1].set_title('Demodulation') axarr[2].set_title('Correlation') # ##",
"demodF (numpy.ndarray): Demodulation functions. N x K matrix Returns: plt.figure: Figure handle plt.axis:",
"than the number of coding pairs, i.e. rows>cols if(ModFs.shape[0] < ModFs.shape[1]): ModFs =",
"3) axarr = fig.get_axes() ## Make all plots ## Calculate Avg power. avgPower",
"+ 2].set_xlabel('Phase') axarr[3*i + 0].set_ylabel('Instant Power') axarr[3*i + 1].set_ylabel('Exposure') axarr[3*i + 2].set_ylabel('Magnitude') ##",
"16, # x and y titles 'axes.titleweight': 'bold', # x and y titles",
"Set axis labels axarr[3*i + 0].set_xlabel('Time') axarr[3*i + 1].set_xlabel('Time') axarr[3*i + 2].set_xlabel('Phase') axarr[3*i",
"mpl import matplotlib.pyplot as plt # from IPython.core import debugger # breakpoint =",
"so that stars don't cover the corrFs. for i in range(0, K): labelInfo",
"## Calculate Avg power. avgPower = np.sum(ModFs[:,0]) / N avgPower = [avgPower for",
"range(0, K): labelInfo = str(i) axarr[3*i + 0].plot(t, ModFs[:,i], label='Md-'+labelInfo,linewidth=2, color=colors[i]) axarr[3*i +",
"# breakpoint = debugger.set_trace #### Local imports import Utils #### Default matplotlib preferences",
"axarr[1].set_title('Demodulation') axarr[2].set_title('Correlation') # ## Set ylimit so that we can see the legend",
"array for i in range(K): # breakpoint() fig.add_subplot(K,3,3*i + 1) fig.add_subplot(K,3,3*i + 2)",
"/ tau #### Reshape to ensure needed dimensions ## Assume that the number",
"Titles axarr[0].set_title('Modulation') axarr[1].set_title('Demodulation') axarr[2].set_title('Correlation') # ## Set ylimit so that we can see",
"plt.rcParams['axes.prop_cycle'].by_key()['color'] plotParams = { 'font.size': 16, 'figure.dpi': 80, 'figure.autolayout': True, 'figure.titleweight': 'bold', 'savefig.dpi':",
"same dimensions t = t.reshape((N,)) #### Get Correlation functions CorrFs = Utils.GetCorrelationFunctions(ModFs=ModFs,DemodFs=DemodFs) ####",
"Default matplotlib preferences plt.style.use('ggplot') colors = plt.rcParams['axes.prop_cycle'].by_key()['color'] plotParams = { 'font.size': 16, 'figure.dpi':",
"## Needed to allow drawing with matplotlib during debug mode plt._INSTALL_FIG_OBSERVER = True",
"plt.figure: Figure handle plt.axis: Axis handle \"\"\" #### Assume the following constants totalEnergy",
"= plt.gcf() ## Add subplots and get axis array for i in range(K):",
"0].plot(t, ModFs[:,i], label='Md-'+labelInfo,linewidth=2, color=colors[i]) axarr[3*i + 1].plot(t, DemodFs[:,i], label='Dmd-'+labelInfo,linewidth=2, color=colors[i]) axarr[3*i + 2].plot(phase,",
"[avgPower for i in range(0, N)] ## Plot ObjCorrF first so that stars",
"y titles 'grid.linestyle': '--', 'grid.linewidth': 2, 'text.usetex': False, 'xtick.labelsize': 14, 'xtick.minor.visible': True, 'ytick.labelsize':",
"Create a 1x3 figure with modulation, demodulation, and the correlation. Args: modF (numpy.ndarray):",
"## Set axis labels axarr[3*i + 0].set_xlabel('Time') axarr[3*i + 1].set_xlabel('Time') axarr[3*i + 2].set_xlabel('Phase')",
"'axes.labelsize': 16, # x and y titles 'axes.titleweight': 'bold', # x and y",
"Assume the following constants totalEnergy = 1. tau = 1. averagePower = totalEnergy",
"the number of elements is larger than the number of coding pairs, i.e.",
"#### Get Correlation functions CorrFs = Utils.GetCorrelationFunctions(ModFs=ModFs,DemodFs=DemodFs) #### Plot Decomposition ## Clear current",
"+ 0].plot(t, avgPower, '--', label='AvgPower', linewidth=3, color=colors[i]) ## Set axis labels axarr[3*i +",
"True mpl.rcParams.update(plotParams) plt.ion() def PlotCodingScheme(ModFs, DemodFs): \"\"\"PlotCodingScheme: Create a 1x3 figure with modulation,",
"tau, N) phase = np.linspace(0, 2*np.pi,N) #### Reshape to ensure same dimensions t",
"= True mpl.rcParams.update(plotParams) plt.ion() def PlotCodingScheme(ModFs, DemodFs): \"\"\"PlotCodingScheme: Create a 1x3 figure with",
"# breakpoint() fig.add_subplot(K,3,3*i + 1) fig.add_subplot(K,3,3*i + 2) fig.add_subplot(K,3,3*i + 3) axarr =",
"## Plot ObjCorrF first so that stars don't cover the corrFs. for i",
"constants totalEnergy = 1. tau = 1. averagePower = totalEnergy / tau ####",
"axarr[2].set_title('Correlation') # ## Set ylimit so that we can see the legend #",
"following constants totalEnergy = 1. tau = 1. averagePower = totalEnergy / tau",
"K matrix Returns: plt.figure: Figure handle plt.axis: Axis handle \"\"\" #### Assume the",
"first so that stars don't cover the corrFs. for i in range(0, K):",
"} mpl.use('Qt4Agg', warn=False) ## Needed to allow drawing with matplotlib during debug mode",
"'savefig.dpi': 200, 'axes.titlesize': 18, # main title 'axes.labelsize': 16, # x and y",
"mpl.use('Qt4Agg', warn=False) ## Needed to allow drawing with matplotlib during debug mode plt._INSTALL_FIG_OBSERVER",
"0].set_ylabel('Instant Power') axarr[3*i + 1].set_ylabel('Exposure') axarr[3*i + 2].set_ylabel('Magnitude') ## Set Titles axarr[0].set_title('Modulation') axarr[1].set_title('Demodulation')",
"= plt.rcParams['axes.prop_cycle'].by_key()['color'] plotParams = { 'font.size': 16, 'figure.dpi': 80, 'figure.autolayout': True, 'figure.titleweight': 'bold',",
"Add subplots and get axis array for i in range(K): # breakpoint() fig.add_subplot(K,3,3*i",
"so that we can see the legend # axarr[0].set_ylim([0,1.2*np.max(ModFs)]) # axarr[1].set_ylim([0,1.2*np.max(DemodFs)]) # axarr[2].set_ylim([0,1.2*np.max(CorrFs)])",
"ModFs.transpose() if(DemodFs.shape[0] < DemodFs.shape[1]): DemodFs = DemodFs.transpose() #### Verify Inputs assert(ModFs.shape == DemodFs.shape),",
"plt.gcf() ## Add subplots and get axis array for i in range(K): #",
"= Utils.GetCorrelationFunctions(ModFs=ModFs,DemodFs=DemodFs) #### Plot Decomposition ## Clear current plot plt.clf() ## Get current",
"#### Default matplotlib preferences plt.style.use('ggplot') colors = plt.rcParams['axes.prop_cycle'].by_key()['color'] plotParams = { 'font.size': 16,",
"'--', 'grid.linewidth': 2, 'text.usetex': False, 'xtick.labelsize': 14, 'xtick.minor.visible': True, 'ytick.labelsize': 14, 'ytick.minor.visible': True,",
"plt.ion() def PlotCodingScheme(ModFs, DemodFs): \"\"\"PlotCodingScheme: Create a 1x3 figure with modulation, demodulation, and",
"debugger # breakpoint = debugger.set_trace #### Local imports import Utils #### Default matplotlib",
"subplots and get axis array for i in range(K): # breakpoint() fig.add_subplot(K,3,3*i +",
"= np.sum(ModFs[:,0])/N #### Set default values t = np.linspace(0, tau, N) phase =",
"8.0, 'legend.fontsize': 14, 'legend.shadow': True, } mpl.use('Qt4Agg', warn=False) ## Needed to allow drawing",
"= { 'font.size': 16, 'figure.dpi': 80, 'figure.autolayout': True, 'figure.titleweight': 'bold', 'savefig.dpi': 200, 'axes.titlesize':",
"0].plot(t, avgPower, '--', label='AvgPower', linewidth=3, color=colors[i]) ## Set axis labels axarr[3*i + 0].set_xlabel('Time')",
"axarr[3*i + 1].set_xlabel('Time') axarr[3*i + 2].set_xlabel('Phase') axarr[3*i + 0].set_ylabel('Instant Power') axarr[3*i + 1].set_ylabel('Exposure')",
"fig = plt.gcf() ## Add subplots and get axis array for i in",
"= str(i) axarr[3*i + 0].plot(t, ModFs[:,i], label='Md-'+labelInfo,linewidth=2, color=colors[i]) axarr[3*i + 1].plot(t, DemodFs[:,i], label='Dmd-'+labelInfo,linewidth=2,",
"'grid.linestyle': '--', 'grid.linewidth': 2, 'text.usetex': False, 'xtick.labelsize': 14, 'xtick.minor.visible': True, 'ytick.labelsize': 14, 'ytick.minor.visible':",
"(N,K) = ModFs.shape avgPower = np.sum(ModFs[:,0])/N #### Set default values t = np.linspace(0,",
"2].plot(phase, CorrFs[:,i], label='Crr-'+labelInfo,linewidth=2, color=colors[i]) axarr[3*i + 0].plot(t, avgPower, '--', label='AvgPower', linewidth=3, color=colors[i]) ##",
"y titles 'axes.titleweight': 'bold', # x and y titles 'axes.labelweight': 'bold', # x",
"labels axarr[3*i + 0].set_xlabel('Time') axarr[3*i + 1].set_xlabel('Time') axarr[3*i + 2].set_xlabel('Phase') axarr[3*i + 0].set_ylabel('Instant",
"we can see the legend # axarr[0].set_ylim([0,1.2*np.max(ModFs)]) # axarr[1].set_ylim([0,1.2*np.max(DemodFs)]) # axarr[2].set_ylim([0,1.2*np.max(CorrFs)]) return (fig,",
"import matplotlib.pyplot as plt # from IPython.core import debugger # breakpoint = debugger.set_trace",
"matrix Returns: plt.figure: Figure handle plt.axis: Axis handle \"\"\" #### Assume the following",
"Calculate Avg power. avgPower = np.sum(ModFs[:,0]) / N avgPower = [avgPower for i",
"+ 1) fig.add_subplot(K,3,3*i + 2) fig.add_subplot(K,3,3*i + 3) axarr = fig.get_axes() ## Make",
"DemodFs[:,i], label='Dmd-'+labelInfo,linewidth=2, color=colors[i]) axarr[3*i + 2].plot(phase, CorrFs[:,i], label='Crr-'+labelInfo,linewidth=2, color=colors[i]) axarr[3*i + 0].plot(t, avgPower,",
"x K matrix. demodF (numpy.ndarray): Demodulation functions. N x K matrix Returns: plt.figure:",
"#### Assume the following constants totalEnergy = 1. tau = 1. averagePower =",
"titles 'axes.titleweight': 'bold', # x and y titles 'axes.labelweight': 'bold', # x and",
"fig.add_subplot(K,3,3*i + 3) axarr = fig.get_axes() ## Make all plots ## Calculate Avg",
"1) fig.add_subplot(K,3,3*i + 2) fig.add_subplot(K,3,3*i + 3) axarr = fig.get_axes() ## Make all",
"main title 'axes.labelsize': 16, # x and y titles 'axes.titleweight': 'bold', # x",
"dimensions ## Assume that the number of elements is larger than the number",
"\"\"\"UtilsPlot Attributes: colors (TYPE): Colors for plotting plotParams (TYPE): Default plotting parameters \"\"\"",
"IPython.core import debugger # breakpoint = debugger.set_trace #### Local imports import Utils ####",
"corrFs. for i in range(0, K): labelInfo = str(i) axarr[3*i + 0].plot(t, ModFs[:,i],",
"as mpl import matplotlib.pyplot as plt # from IPython.core import debugger # breakpoint",
"the corrFs. for i in range(0, K): labelInfo = str(i) axarr[3*i + 0].plot(t,",
"'lines.linewidth': 2, 'lines.markersize': 8.0, 'legend.fontsize': 14, 'legend.shadow': True, } mpl.use('Qt4Agg', warn=False) ## Needed",
"Attributes: colors (TYPE): Colors for plotting plotParams (TYPE): Default plotting parameters \"\"\" ####",
"Get current figure fig = plt.gcf() ## Add subplots and get axis array",
"80, 'figure.autolayout': True, 'figure.titleweight': 'bold', 'savefig.dpi': 200, 'axes.titlesize': 18, # main title 'axes.labelsize':",
"import debugger # breakpoint = debugger.set_trace #### Local imports import Utils #### Default",
"imports import numpy as np import matplotlib as mpl import matplotlib.pyplot as plt",
"current figure fig = plt.gcf() ## Add subplots and get axis array for",
"= np.linspace(0, tau, N) phase = np.linspace(0, 2*np.pi,N) #### Reshape to ensure same",
"import numpy as np import matplotlib as mpl import matplotlib.pyplot as plt #",
"N x K matrix. demodF (numpy.ndarray): Demodulation functions. N x K matrix Returns:",
"14, 'legend.shadow': True, } mpl.use('Qt4Agg', warn=False) ## Needed to allow drawing with matplotlib",
"\"\"\"PlotCodingScheme: Create a 1x3 figure with modulation, demodulation, and the correlation. Args: modF",
"numpy as np import matplotlib as mpl import matplotlib.pyplot as plt # from",
"x K matrix Returns: plt.figure: Figure handle plt.axis: Axis handle \"\"\" #### Assume",
"2].set_xlabel('Phase') axarr[3*i + 0].set_ylabel('Instant Power') axarr[3*i + 1].set_ylabel('Exposure') axarr[3*i + 2].set_ylabel('Magnitude') ## Set",
"import matplotlib as mpl import matplotlib.pyplot as plt # from IPython.core import debugger",
"ModFs and \\ DemodFs should be the same dimensions.\" #### Set some parameters",
"Set ylimit so that we can see the legend # axarr[0].set_ylim([0,1.2*np.max(ModFs)]) # axarr[1].set_ylim([0,1.2*np.max(DemodFs)])",
"correlation. Args: modF (numpy.ndarray): Modulation functions. N x K matrix. demodF (numpy.ndarray): Demodulation",
"get axis array for i in range(K): # breakpoint() fig.add_subplot(K,3,3*i + 1) fig.add_subplot(K,3,3*i",
"Needed to allow drawing with matplotlib during debug mode plt._INSTALL_FIG_OBSERVER = True mpl.rcParams.update(plotParams)",
"values t = np.linspace(0, tau, N) phase = np.linspace(0, 2*np.pi,N) #### Reshape to",
"Avg power. avgPower = np.sum(ModFs[:,0]) / N avgPower = [avgPower for i in",
"i in range(0, N)] ## Plot ObjCorrF first so that stars don't cover",
"K): labelInfo = str(i) axarr[3*i + 0].plot(t, ModFs[:,i], label='Md-'+labelInfo,linewidth=2, color=colors[i]) axarr[3*i + 1].plot(t,",
"ensure needed dimensions ## Assume that the number of elements is larger than",
"N avgPower = [avgPower for i in range(0, N)] ## Plot ObjCorrF first",
"= debugger.set_trace #### Local imports import Utils #### Default matplotlib preferences plt.style.use('ggplot') colors",
"== DemodFs.shape), \"Input Error - PlotCodingScheme: ModFs and \\ DemodFs should be the",
"+ 2) fig.add_subplot(K,3,3*i + 3) axarr = fig.get_axes() ## Make all plots ##",
"colors = plt.rcParams['axes.prop_cycle'].by_key()['color'] plotParams = { 'font.size': 16, 'figure.dpi': 80, 'figure.autolayout': True, 'figure.titleweight':",
"to ensure needed dimensions ## Assume that the number of elements is larger",
"{ 'font.size': 16, 'figure.dpi': 80, 'figure.autolayout': True, 'figure.titleweight': 'bold', 'savefig.dpi': 200, 'axes.titlesize': 18,",
"'figure.autolayout': True, 'figure.titleweight': 'bold', 'savefig.dpi': 200, 'axes.titlesize': 18, # main title 'axes.labelsize': 16,",
"axarr[3*i + 0].plot(t, ModFs[:,i], label='Md-'+labelInfo,linewidth=2, color=colors[i]) axarr[3*i + 1].plot(t, DemodFs[:,i], label='Dmd-'+labelInfo,linewidth=2, color=colors[i]) axarr[3*i",
"avgPower = np.sum(ModFs[:,0])/N #### Set default values t = np.linspace(0, tau, N) phase",
"and \\ DemodFs should be the same dimensions.\" #### Set some parameters (N,K)",
"during debug mode plt._INSTALL_FIG_OBSERVER = True mpl.rcParams.update(plotParams) plt.ion() def PlotCodingScheme(ModFs, DemodFs): \"\"\"PlotCodingScheme: Create",
"matrix. demodF (numpy.ndarray): Demodulation functions. N x K matrix Returns: plt.figure: Figure handle",
"Local imports import Utils #### Default matplotlib preferences plt.style.use('ggplot') colors = plt.rcParams['axes.prop_cycle'].by_key()['color'] plotParams",
"Utils.GetCorrelationFunctions(ModFs=ModFs,DemodFs=DemodFs) #### Plot Decomposition ## Clear current plot plt.clf() ## Get current figure",
"imports import Utils #### Default matplotlib preferences plt.style.use('ggplot') colors = plt.rcParams['axes.prop_cycle'].by_key()['color'] plotParams =",
"axis labels axarr[3*i + 0].set_xlabel('Time') axarr[3*i + 1].set_xlabel('Time') axarr[3*i + 2].set_xlabel('Phase') axarr[3*i +",
"## Set Titles axarr[0].set_title('Modulation') axarr[1].set_title('Demodulation') axarr[2].set_title('Correlation') # ## Set ylimit so that we",
"import Utils #### Default matplotlib preferences plt.style.use('ggplot') colors = plt.rcParams['axes.prop_cycle'].by_key()['color'] plotParams = {",
"should be the same dimensions.\" #### Set some parameters (N,K) = ModFs.shape avgPower",
"K matrix. demodF (numpy.ndarray): Demodulation functions. N x K matrix Returns: plt.figure: Figure",
"\"\"\" #### Python imports #### Library imports import numpy as np import matplotlib",
"label='Dmd-'+labelInfo,linewidth=2, color=colors[i]) axarr[3*i + 2].plot(phase, CorrFs[:,i], label='Crr-'+labelInfo,linewidth=2, color=colors[i]) axarr[3*i + 0].plot(t, avgPower, '--',",
"for i in range(0, K): labelInfo = str(i) axarr[3*i + 0].plot(t, ModFs[:,i], label='Md-'+labelInfo,linewidth=2,",
"## Set ylimit so that we can see the legend # axarr[0].set_ylim([0,1.2*np.max(ModFs)]) #",
"18, # main title 'axes.labelsize': 16, # x and y titles 'axes.titleweight': 'bold',",
"from IPython.core import debugger # breakpoint = debugger.set_trace #### Local imports import Utils",
"that we can see the legend # axarr[0].set_ylim([0,1.2*np.max(ModFs)]) # axarr[1].set_ylim([0,1.2*np.max(DemodFs)]) # axarr[2].set_ylim([0,1.2*np.max(CorrFs)]) return",
"Default plotting parameters \"\"\" #### Python imports #### Library imports import numpy as",
"power. avgPower = np.sum(ModFs[:,0]) / N avgPower = [avgPower for i in range(0,",
"label='Md-'+labelInfo,linewidth=2, color=colors[i]) axarr[3*i + 1].plot(t, DemodFs[:,i], label='Dmd-'+labelInfo,linewidth=2, color=colors[i]) axarr[3*i + 2].plot(phase, CorrFs[:,i], label='Crr-'+labelInfo,linewidth=2,",
"str(i) axarr[3*i + 0].plot(t, ModFs[:,i], label='Md-'+labelInfo,linewidth=2, color=colors[i]) axarr[3*i + 1].plot(t, DemodFs[:,i], label='Dmd-'+labelInfo,linewidth=2, color=colors[i])",
"True, 'figure.titleweight': 'bold', 'savefig.dpi': 200, 'axes.titlesize': 18, # main title 'axes.labelsize': 16, #",
"'lines.markersize': 8.0, 'legend.fontsize': 14, 'legend.shadow': True, } mpl.use('Qt4Agg', warn=False) ## Needed to allow",
"that the number of elements is larger than the number of coding pairs,",
"Get Correlation functions CorrFs = Utils.GetCorrelationFunctions(ModFs=ModFs,DemodFs=DemodFs) #### Plot Decomposition ## Clear current plot",
"## Clear current plot plt.clf() ## Get current figure fig = plt.gcf() ##",
"current plot plt.clf() ## Get current figure fig = plt.gcf() ## Add subplots",
"title 'axes.labelsize': 16, # x and y titles 'axes.titleweight': 'bold', # x and",
"handle plt.axis: Axis handle \"\"\" #### Assume the following constants totalEnergy = 1.",
"- PlotCodingScheme: ModFs and \\ DemodFs should be the same dimensions.\" #### Set",
"# x and y titles 'axes.labelweight': 'bold', # x and y titles 'grid.linestyle':",
"Colors for plotting plotParams (TYPE): Default plotting parameters \"\"\" #### Python imports ####",
"needed dimensions ## Assume that the number of elements is larger than the",
"axarr[3*i + 0].set_xlabel('Time') axarr[3*i + 1].set_xlabel('Time') axarr[3*i + 2].set_xlabel('Phase') axarr[3*i + 0].set_ylabel('Instant Power')",
"np.sum(ModFs[:,0]) / N avgPower = [avgPower for i in range(0, N)] ## Plot",
"'grid.linewidth': 2, 'text.usetex': False, 'xtick.labelsize': 14, 'xtick.minor.visible': True, 'ytick.labelsize': 14, 'ytick.minor.visible': True, 'lines.linewidth':",
"200, 'axes.titlesize': 18, # main title 'axes.labelsize': 16, # x and y titles",
"functions. N x K matrix Returns: plt.figure: Figure handle plt.axis: Axis handle \"\"\"",
"N) phase = np.linspace(0, 2*np.pi,N) #### Reshape to ensure same dimensions t =",
"'ytick.minor.visible': True, 'lines.linewidth': 2, 'lines.markersize': 8.0, 'legend.fontsize': 14, 'legend.shadow': True, } mpl.use('Qt4Agg', warn=False)",
"parameters \"\"\" #### Python imports #### Library imports import numpy as np import",
"tau #### Reshape to ensure needed dimensions ## Assume that the number of",
"fig.add_subplot(K,3,3*i + 1) fig.add_subplot(K,3,3*i + 2) fig.add_subplot(K,3,3*i + 3) axarr = fig.get_axes() ##",
"plotParams (TYPE): Default plotting parameters \"\"\" #### Python imports #### Library imports import",
"plt.style.use('ggplot') colors = plt.rcParams['axes.prop_cycle'].by_key()['color'] plotParams = { 'font.size': 16, 'figure.dpi': 80, 'figure.autolayout': True,",
"allow drawing with matplotlib during debug mode plt._INSTALL_FIG_OBSERVER = True mpl.rcParams.update(plotParams) plt.ion() def",
"dimensions t = t.reshape((N,)) #### Get Correlation functions CorrFs = Utils.GetCorrelationFunctions(ModFs=ModFs,DemodFs=DemodFs) #### Plot",
"matplotlib preferences plt.style.use('ggplot') colors = plt.rcParams['axes.prop_cycle'].by_key()['color'] plotParams = { 'font.size': 16, 'figure.dpi': 80,",
"colors (TYPE): Colors for plotting plotParams (TYPE): Default plotting parameters \"\"\" #### Python",
"mpl.rcParams.update(plotParams) plt.ion() def PlotCodingScheme(ModFs, DemodFs): \"\"\"PlotCodingScheme: Create a 1x3 figure with modulation, demodulation,",
"if(DemodFs.shape[0] < DemodFs.shape[1]): DemodFs = DemodFs.transpose() #### Verify Inputs assert(ModFs.shape == DemodFs.shape), \"Input",
"#### Set some parameters (N,K) = ModFs.shape avgPower = np.sum(ModFs[:,0])/N #### Set default",
"(numpy.ndarray): Demodulation functions. N x K matrix Returns: plt.figure: Figure handle plt.axis: Axis",
"Figure handle plt.axis: Axis handle \"\"\" #### Assume the following constants totalEnergy =",
"preferences plt.style.use('ggplot') colors = plt.rcParams['axes.prop_cycle'].by_key()['color'] plotParams = { 'font.size': 16, 'figure.dpi': 80, 'figure.autolayout':",
"the correlation. Args: modF (numpy.ndarray): Modulation functions. N x K matrix. demodF (numpy.ndarray):",
"larger than the number of coding pairs, i.e. rows>cols if(ModFs.shape[0] < ModFs.shape[1]): ModFs",
"plots ## Calculate Avg power. avgPower = np.sum(ModFs[:,0]) / N avgPower = [avgPower",
"axarr[0].set_title('Modulation') axarr[1].set_title('Demodulation') axarr[2].set_title('Correlation') # ## Set ylimit so that we can see the",
"for i in range(K): # breakpoint() fig.add_subplot(K,3,3*i + 1) fig.add_subplot(K,3,3*i + 2) fig.add_subplot(K,3,3*i",
"np.sum(ModFs[:,0])/N #### Set default values t = np.linspace(0, tau, N) phase = np.linspace(0,",
"ModFs = ModFs.transpose() if(DemodFs.shape[0] < DemodFs.shape[1]): DemodFs = DemodFs.transpose() #### Verify Inputs assert(ModFs.shape",
"16, 'figure.dpi': 80, 'figure.autolayout': True, 'figure.titleweight': 'bold', 'savefig.dpi': 200, 'axes.titlesize': 18, # main",
"that stars don't cover the corrFs. for i in range(0, K): labelInfo =",
"x and y titles 'grid.linestyle': '--', 'grid.linewidth': 2, 'text.usetex': False, 'xtick.labelsize': 14, 'xtick.minor.visible':",
"DemodFs should be the same dimensions.\" #### Set some parameters (N,K) = ModFs.shape",
"#### Set default values t = np.linspace(0, tau, N) phase = np.linspace(0, 2*np.pi,N)",
"don't cover the corrFs. for i in range(0, K): labelInfo = str(i) axarr[3*i",
"label='Crr-'+labelInfo,linewidth=2, color=colors[i]) axarr[3*i + 0].plot(t, avgPower, '--', label='AvgPower', linewidth=3, color=colors[i]) ## Set axis",
"Error - PlotCodingScheme: ModFs and \\ DemodFs should be the same dimensions.\" ####",
"of coding pairs, i.e. rows>cols if(ModFs.shape[0] < ModFs.shape[1]): ModFs = ModFs.transpose() if(DemodFs.shape[0] <",
"axarr[3*i + 1].plot(t, DemodFs[:,i], label='Dmd-'+labelInfo,linewidth=2, color=colors[i]) axarr[3*i + 2].plot(phase, CorrFs[:,i], label='Crr-'+labelInfo,linewidth=2, color=colors[i]) axarr[3*i",
"ModFs.shape[1]): ModFs = ModFs.transpose() if(DemodFs.shape[0] < DemodFs.shape[1]): DemodFs = DemodFs.transpose() #### Verify Inputs",
"Set some parameters (N,K) = ModFs.shape avgPower = np.sum(ModFs[:,0])/N #### Set default values",
"2, 'text.usetex': False, 'xtick.labelsize': 14, 'xtick.minor.visible': True, 'ytick.labelsize': 14, 'ytick.minor.visible': True, 'lines.linewidth': 2,",
"'bold', # x and y titles 'axes.labelweight': 'bold', # x and y titles",
"Correlation functions CorrFs = Utils.GetCorrelationFunctions(ModFs=ModFs,DemodFs=DemodFs) #### Plot Decomposition ## Clear current plot plt.clf()",
"linewidth=3, color=colors[i]) ## Set axis labels axarr[3*i + 0].set_xlabel('Time') axarr[3*i + 1].set_xlabel('Time') axarr[3*i",
"< DemodFs.shape[1]): DemodFs = DemodFs.transpose() #### Verify Inputs assert(ModFs.shape == DemodFs.shape), \"Input Error",
"Utils #### Default matplotlib preferences plt.style.use('ggplot') colors = plt.rcParams['axes.prop_cycle'].by_key()['color'] plotParams = { 'font.size':",
"parameters (N,K) = ModFs.shape avgPower = np.sum(ModFs[:,0])/N #### Set default values t =",
"/ N avgPower = [avgPower for i in range(0, N)] ## Plot ObjCorrF",
"mode plt._INSTALL_FIG_OBSERVER = True mpl.rcParams.update(plotParams) plt.ion() def PlotCodingScheme(ModFs, DemodFs): \"\"\"PlotCodingScheme: Create a 1x3",
"Assume that the number of elements is larger than the number of coding",
"(TYPE): Default plotting parameters \"\"\" #### Python imports #### Library imports import numpy",
"t = np.linspace(0, tau, N) phase = np.linspace(0, 2*np.pi,N) #### Reshape to ensure",
"+ 2].set_ylabel('Magnitude') ## Set Titles axarr[0].set_title('Modulation') axarr[1].set_title('Demodulation') axarr[2].set_title('Correlation') # ## Set ylimit so",
"plt # from IPython.core import debugger # breakpoint = debugger.set_trace #### Local imports",
"x and y titles 'axes.labelweight': 'bold', # x and y titles 'grid.linestyle': '--',",
"1. tau = 1. averagePower = totalEnergy / tau #### Reshape to ensure",
"Reshape to ensure needed dimensions ## Assume that the number of elements is",
"## Get current figure fig = plt.gcf() ## Add subplots and get axis",
"and y titles 'axes.titleweight': 'bold', # x and y titles 'axes.labelweight': 'bold', #",
"ensure same dimensions t = t.reshape((N,)) #### Get Correlation functions CorrFs = Utils.GetCorrelationFunctions(ModFs=ModFs,DemodFs=DemodFs)",
"1].set_xlabel('Time') axarr[3*i + 2].set_xlabel('Phase') axarr[3*i + 0].set_ylabel('Instant Power') axarr[3*i + 1].set_ylabel('Exposure') axarr[3*i +",
"matplotlib.pyplot as plt # from IPython.core import debugger # breakpoint = debugger.set_trace ####",
"Make all plots ## Calculate Avg power. avgPower = np.sum(ModFs[:,0]) / N avgPower",
"Modulation functions. N x K matrix. demodF (numpy.ndarray): Demodulation functions. N x K",
"1].plot(t, DemodFs[:,i], label='Dmd-'+labelInfo,linewidth=2, color=colors[i]) axarr[3*i + 2].plot(phase, CorrFs[:,i], label='Crr-'+labelInfo,linewidth=2, color=colors[i]) axarr[3*i + 0].plot(t,",
"DemodFs.shape), \"Input Error - PlotCodingScheme: ModFs and \\ DemodFs should be the same",
"plotting plotParams (TYPE): Default plotting parameters \"\"\" #### Python imports #### Library imports",
"Set default values t = np.linspace(0, tau, N) phase = np.linspace(0, 2*np.pi,N) ####",
"modF (numpy.ndarray): Modulation functions. N x K matrix. demodF (numpy.ndarray): Demodulation functions. N",
"titles 'grid.linestyle': '--', 'grid.linewidth': 2, 'text.usetex': False, 'xtick.labelsize': 14, 'xtick.minor.visible': True, 'ytick.labelsize': 14,",
"t.reshape((N,)) #### Get Correlation functions CorrFs = Utils.GetCorrelationFunctions(ModFs=ModFs,DemodFs=DemodFs) #### Plot Decomposition ## Clear",
"True, 'ytick.labelsize': 14, 'ytick.minor.visible': True, 'lines.linewidth': 2, 'lines.markersize': 8.0, 'legend.fontsize': 14, 'legend.shadow': True,",
"in range(0, N)] ## Plot ObjCorrF first so that stars don't cover the",
"in range(0, K): labelInfo = str(i) axarr[3*i + 0].plot(t, ModFs[:,i], label='Md-'+labelInfo,linewidth=2, color=colors[i]) axarr[3*i",
"'ytick.labelsize': 14, 'ytick.minor.visible': True, 'lines.linewidth': 2, 'lines.markersize': 8.0, 'legend.fontsize': 14, 'legend.shadow': True, }",
"'bold', 'savefig.dpi': 200, 'axes.titlesize': 18, # main title 'axes.labelsize': 16, # x and",
"titles 'axes.labelweight': 'bold', # x and y titles 'grid.linestyle': '--', 'grid.linewidth': 2, 'text.usetex':",
"# main title 'axes.labelsize': 16, # x and y titles 'axes.titleweight': 'bold', #",
"= totalEnergy / tau #### Reshape to ensure needed dimensions ## Assume that",
"label='AvgPower', linewidth=3, color=colors[i]) ## Set axis labels axarr[3*i + 0].set_xlabel('Time') axarr[3*i + 1].set_xlabel('Time')",
"ylimit so that we can see the legend # axarr[0].set_ylim([0,1.2*np.max(ModFs)]) # axarr[1].set_ylim([0,1.2*np.max(DemodFs)]) #",
"= ModFs.transpose() if(DemodFs.shape[0] < DemodFs.shape[1]): DemodFs = DemodFs.transpose() #### Verify Inputs assert(ModFs.shape ==",
"DemodFs = DemodFs.transpose() #### Verify Inputs assert(ModFs.shape == DemodFs.shape), \"Input Error - PlotCodingScheme:",
"handle \"\"\" #### Assume the following constants totalEnergy = 1. tau = 1.",
"of elements is larger than the number of coding pairs, i.e. rows>cols if(ModFs.shape[0]",
"ModFs.shape avgPower = np.sum(ModFs[:,0])/N #### Set default values t = np.linspace(0, tau, N)",
"Reshape to ensure same dimensions t = t.reshape((N,)) #### Get Correlation functions CorrFs",
"color=colors[i]) axarr[3*i + 1].plot(t, DemodFs[:,i], label='Dmd-'+labelInfo,linewidth=2, color=colors[i]) axarr[3*i + 2].plot(phase, CorrFs[:,i], label='Crr-'+labelInfo,linewidth=2, color=colors[i])",
"plot plt.clf() ## Get current figure fig = plt.gcf() ## Add subplots and",
"axarr[3*i + 1].set_ylabel('Exposure') axarr[3*i + 2].set_ylabel('Magnitude') ## Set Titles axarr[0].set_title('Modulation') axarr[1].set_title('Demodulation') axarr[2].set_title('Correlation') #",
"x and y titles 'axes.titleweight': 'bold', # x and y titles 'axes.labelweight': 'bold',",
"(TYPE): Colors for plotting plotParams (TYPE): Default plotting parameters \"\"\" #### Python imports",
"< ModFs.shape[1]): ModFs = ModFs.transpose() if(DemodFs.shape[0] < DemodFs.shape[1]): DemodFs = DemodFs.transpose() #### Verify",
"1. averagePower = totalEnergy / tau #### Reshape to ensure needed dimensions ##",
"Clear current plot plt.clf() ## Get current figure fig = plt.gcf() ## Add",
"number of coding pairs, i.e. rows>cols if(ModFs.shape[0] < ModFs.shape[1]): ModFs = ModFs.transpose() if(DemodFs.shape[0]",
"axarr[3*i + 0].plot(t, avgPower, '--', label='AvgPower', linewidth=3, color=colors[i]) ## Set axis labels axarr[3*i",
"fig.get_axes() ## Make all plots ## Calculate Avg power. avgPower = np.sum(ModFs[:,0]) /",
"2, 'lines.markersize': 8.0, 'legend.fontsize': 14, 'legend.shadow': True, } mpl.use('Qt4Agg', warn=False) ## Needed to",
"1x3 figure with modulation, demodulation, and the correlation. Args: modF (numpy.ndarray): Modulation functions.",
"+ 1].plot(t, DemodFs[:,i], label='Dmd-'+labelInfo,linewidth=2, color=colors[i]) axarr[3*i + 2].plot(phase, CorrFs[:,i], label='Crr-'+labelInfo,linewidth=2, color=colors[i]) axarr[3*i +",
"and y titles 'grid.linestyle': '--', 'grid.linewidth': 2, 'text.usetex': False, 'xtick.labelsize': 14, 'xtick.minor.visible': True,",
"'legend.shadow': True, } mpl.use('Qt4Agg', warn=False) ## Needed to allow drawing with matplotlib during",
"all plots ## Calculate Avg power. avgPower = np.sum(ModFs[:,0]) / N avgPower =",
"as np import matplotlib as mpl import matplotlib.pyplot as plt # from IPython.core",
"elements is larger than the number of coding pairs, i.e. rows>cols if(ModFs.shape[0] <",
"to allow drawing with matplotlib during debug mode plt._INSTALL_FIG_OBSERVER = True mpl.rcParams.update(plotParams) plt.ion()",
"the following constants totalEnergy = 1. tau = 1. averagePower = totalEnergy /",
"(numpy.ndarray): Modulation functions. N x K matrix. demodF (numpy.ndarray): Demodulation functions. N x",
"Inputs assert(ModFs.shape == DemodFs.shape), \"Input Error - PlotCodingScheme: ModFs and \\ DemodFs should",
"stars don't cover the corrFs. for i in range(0, K): labelInfo = str(i)",
"+ 2].plot(phase, CorrFs[:,i], label='Crr-'+labelInfo,linewidth=2, color=colors[i]) axarr[3*i + 0].plot(t, avgPower, '--', label='AvgPower', linewidth=3, color=colors[i])",
"for plotting plotParams (TYPE): Default plotting parameters \"\"\" #### Python imports #### Library",
"Axis handle \"\"\" #### Assume the following constants totalEnergy = 1. tau =",
"= [avgPower for i in range(0, N)] ## Plot ObjCorrF first so that",
"'axes.titleweight': 'bold', # x and y titles 'axes.labelweight': 'bold', # x and y",
"## Add subplots and get axis array for i in range(K): # breakpoint()",
"the number of coding pairs, i.e. rows>cols if(ModFs.shape[0] < ModFs.shape[1]): ModFs = ModFs.transpose()",
"2*np.pi,N) #### Reshape to ensure same dimensions t = t.reshape((N,)) #### Get Correlation",
"'bold', # x and y titles 'grid.linestyle': '--', 'grid.linewidth': 2, 'text.usetex': False, 'xtick.labelsize':",
"a 1x3 figure with modulation, demodulation, and the correlation. Args: modF (numpy.ndarray): Modulation",
"dimensions.\" #### Set some parameters (N,K) = ModFs.shape avgPower = np.sum(ModFs[:,0])/N #### Set",
"N x K matrix Returns: plt.figure: Figure handle plt.axis: Axis handle \"\"\" ####",
"assert(ModFs.shape == DemodFs.shape), \"Input Error - PlotCodingScheme: ModFs and \\ DemodFs should be",
"totalEnergy = 1. tau = 1. averagePower = totalEnergy / tau #### Reshape",
"and the correlation. Args: modF (numpy.ndarray): Modulation functions. N x K matrix. demodF",
"Plot ObjCorrF first so that stars don't cover the corrFs. for i in",
"to ensure same dimensions t = t.reshape((N,)) #### Get Correlation functions CorrFs =",
"the same dimensions.\" #### Set some parameters (N,K) = ModFs.shape avgPower = np.sum(ModFs[:,0])/N",
"avgPower = np.sum(ModFs[:,0]) / N avgPower = [avgPower for i in range(0, N)]",
"Power') axarr[3*i + 1].set_ylabel('Exposure') axarr[3*i + 2].set_ylabel('Magnitude') ## Set Titles axarr[0].set_title('Modulation') axarr[1].set_title('Demodulation') axarr[2].set_title('Correlation')",
"be the same dimensions.\" #### Set some parameters (N,K) = ModFs.shape avgPower =",
"#### Python imports #### Library imports import numpy as np import matplotlib as",
"# x and y titles 'grid.linestyle': '--', 'grid.linewidth': 2, 'text.usetex': False, 'xtick.labelsize': 14,",
"avgPower, '--', label='AvgPower', linewidth=3, color=colors[i]) ## Set axis labels axarr[3*i + 0].set_xlabel('Time') axarr[3*i",
"i in range(0, K): labelInfo = str(i) axarr[3*i + 0].plot(t, ModFs[:,i], label='Md-'+labelInfo,linewidth=2, color=colors[i])",
"'font.size': 16, 'figure.dpi': 80, 'figure.autolayout': True, 'figure.titleweight': 'bold', 'savefig.dpi': 200, 'axes.titlesize': 18, #",
"#### Verify Inputs assert(ModFs.shape == DemodFs.shape), \"Input Error - PlotCodingScheme: ModFs and \\",
"axarr[3*i + 2].plot(phase, CorrFs[:,i], label='Crr-'+labelInfo,linewidth=2, color=colors[i]) axarr[3*i + 0].plot(t, avgPower, '--', label='AvgPower', linewidth=3,",
"DemodFs.transpose() #### Verify Inputs assert(ModFs.shape == DemodFs.shape), \"Input Error - PlotCodingScheme: ModFs and",
"can see the legend # axarr[0].set_ylim([0,1.2*np.max(ModFs)]) # axarr[1].set_ylim([0,1.2*np.max(DemodFs)]) # axarr[2].set_ylim([0,1.2*np.max(CorrFs)]) return (fig, axarr)",
"'axes.labelweight': 'bold', # x and y titles 'grid.linestyle': '--', 'grid.linewidth': 2, 'text.usetex': False,",
"figure fig = plt.gcf() ## Add subplots and get axis array for i",
"+ 1].set_xlabel('Time') axarr[3*i + 2].set_xlabel('Phase') axarr[3*i + 0].set_ylabel('Instant Power') axarr[3*i + 1].set_ylabel('Exposure') axarr[3*i",
"warn=False) ## Needed to allow drawing with matplotlib during debug mode plt._INSTALL_FIG_OBSERVER =",
"'xtick.labelsize': 14, 'xtick.minor.visible': True, 'ytick.labelsize': 14, 'ytick.minor.visible': True, 'lines.linewidth': 2, 'lines.markersize': 8.0, 'legend.fontsize':",
"## Assume that the number of elements is larger than the number of",
"np import matplotlib as mpl import matplotlib.pyplot as plt # from IPython.core import",
"matplotlib during debug mode plt._INSTALL_FIG_OBSERVER = True mpl.rcParams.update(plotParams) plt.ion() def PlotCodingScheme(ModFs, DemodFs): \"\"\"PlotCodingScheme:",
"range(0, N)] ## Plot ObjCorrF first so that stars don't cover the corrFs.",
"+ 0].set_ylabel('Instant Power') axarr[3*i + 1].set_ylabel('Exposure') axarr[3*i + 2].set_ylabel('Magnitude') ## Set Titles axarr[0].set_title('Modulation')",
"= DemodFs.transpose() #### Verify Inputs assert(ModFs.shape == DemodFs.shape), \"Input Error - PlotCodingScheme: ModFs",
"plt.clf() ## Get current figure fig = plt.gcf() ## Add subplots and get",
"#### Reshape to ensure same dimensions t = t.reshape((N,)) #### Get Correlation functions",
"= t.reshape((N,)) #### Get Correlation functions CorrFs = Utils.GetCorrelationFunctions(ModFs=ModFs,DemodFs=DemodFs) #### Plot Decomposition ##",
"0].set_xlabel('Time') axarr[3*i + 1].set_xlabel('Time') axarr[3*i + 2].set_xlabel('Phase') axarr[3*i + 0].set_ylabel('Instant Power') axarr[3*i +",
"cover the corrFs. for i in range(0, K): labelInfo = str(i) axarr[3*i +",
"some parameters (N,K) = ModFs.shape avgPower = np.sum(ModFs[:,0])/N #### Set default values t",
"True, } mpl.use('Qt4Agg', warn=False) ## Needed to allow drawing with matplotlib during debug",
"same dimensions.\" #### Set some parameters (N,K) = ModFs.shape avgPower = np.sum(ModFs[:,0])/N ####",
"True, 'lines.linewidth': 2, 'lines.markersize': 8.0, 'legend.fontsize': 14, 'legend.shadow': True, } mpl.use('Qt4Agg', warn=False) ##",
"= 1. tau = 1. averagePower = totalEnergy / tau #### Reshape to",
"matplotlib as mpl import matplotlib.pyplot as plt # from IPython.core import debugger #",
"phase = np.linspace(0, 2*np.pi,N) #### Reshape to ensure same dimensions t = t.reshape((N,))",
"Demodulation functions. N x K matrix Returns: plt.figure: Figure handle plt.axis: Axis handle",
"2) fig.add_subplot(K,3,3*i + 3) axarr = fig.get_axes() ## Make all plots ## Calculate",
"labelInfo = str(i) axarr[3*i + 0].plot(t, ModFs[:,i], label='Md-'+labelInfo,linewidth=2, color=colors[i]) axarr[3*i + 1].plot(t, DemodFs[:,i],",
"rows>cols if(ModFs.shape[0] < ModFs.shape[1]): ModFs = ModFs.transpose() if(DemodFs.shape[0] < DemodFs.shape[1]): DemodFs = DemodFs.transpose()",
"#### Local imports import Utils #### Default matplotlib preferences plt.style.use('ggplot') colors = plt.rcParams['axes.prop_cycle'].by_key()['color']",
"np.linspace(0, 2*np.pi,N) #### Reshape to ensure same dimensions t = t.reshape((N,)) #### Get",
"= np.linspace(0, 2*np.pi,N) #### Reshape to ensure same dimensions t = t.reshape((N,)) ####",
"color=colors[i]) ## Set axis labels axarr[3*i + 0].set_xlabel('Time') axarr[3*i + 1].set_xlabel('Time') axarr[3*i +",
"= np.sum(ModFs[:,0]) / N avgPower = [avgPower for i in range(0, N)] ##",
"avgPower = [avgPower for i in range(0, N)] ## Plot ObjCorrF first so",
"'text.usetex': False, 'xtick.labelsize': 14, 'xtick.minor.visible': True, 'ytick.labelsize': 14, 'ytick.minor.visible': True, 'lines.linewidth': 2, 'lines.markersize':",
"# x and y titles 'axes.titleweight': 'bold', # x and y titles 'axes.labelweight':",
"False, 'xtick.labelsize': 14, 'xtick.minor.visible': True, 'ytick.labelsize': 14, 'ytick.minor.visible': True, 'lines.linewidth': 2, 'lines.markersize': 8.0,",
"14, 'xtick.minor.visible': True, 'ytick.labelsize': 14, 'ytick.minor.visible': True, 'lines.linewidth': 2, 'lines.markersize': 8.0, 'legend.fontsize': 14,",
"debug mode plt._INSTALL_FIG_OBSERVER = True mpl.rcParams.update(plotParams) plt.ion() def PlotCodingScheme(ModFs, DemodFs): \"\"\"PlotCodingScheme: Create a",
"DemodFs.shape[1]): DemodFs = DemodFs.transpose() #### Verify Inputs assert(ModFs.shape == DemodFs.shape), \"Input Error -",
"coding pairs, i.e. rows>cols if(ModFs.shape[0] < ModFs.shape[1]): ModFs = ModFs.transpose() if(DemodFs.shape[0] < DemodFs.shape[1]):",
"default values t = np.linspace(0, tau, N) phase = np.linspace(0, 2*np.pi,N) #### Reshape",
"for i in range(0, N)] ## Plot ObjCorrF first so that stars don't",
"Plot Decomposition ## Clear current plot plt.clf() ## Get current figure fig =",
"y titles 'axes.labelweight': 'bold', # x and y titles 'grid.linestyle': '--', 'grid.linewidth': 2,",
"# ## Set ylimit so that we can see the legend # axarr[0].set_ylim([0,1.2*np.max(ModFs)])",
"with matplotlib during debug mode plt._INSTALL_FIG_OBSERVER = True mpl.rcParams.update(plotParams) plt.ion() def PlotCodingScheme(ModFs, DemodFs):",
"= fig.get_axes() ## Make all plots ## Calculate Avg power. avgPower = np.sum(ModFs[:,0])",
"#### Library imports import numpy as np import matplotlib as mpl import matplotlib.pyplot",
"Library imports import numpy as np import matplotlib as mpl import matplotlib.pyplot as",
"PlotCodingScheme: ModFs and \\ DemodFs should be the same dimensions.\" #### Set some",
"breakpoint = debugger.set_trace #### Local imports import Utils #### Default matplotlib preferences plt.style.use('ggplot')",
"\"\"\" #### Assume the following constants totalEnergy = 1. tau = 1. averagePower",
"\"Input Error - PlotCodingScheme: ModFs and \\ DemodFs should be the same dimensions.\"",
"t = t.reshape((N,)) #### Get Correlation functions CorrFs = Utils.GetCorrelationFunctions(ModFs=ModFs,DemodFs=DemodFs) #### Plot Decomposition",
"axarr[3*i + 0].set_ylabel('Instant Power') axarr[3*i + 1].set_ylabel('Exposure') axarr[3*i + 2].set_ylabel('Magnitude') ## Set Titles",
"Python imports #### Library imports import numpy as np import matplotlib as mpl",
"as plt # from IPython.core import debugger # breakpoint = debugger.set_trace #### Local",
"+ 0].set_xlabel('Time') axarr[3*i + 1].set_xlabel('Time') axarr[3*i + 2].set_xlabel('Phase') axarr[3*i + 0].set_ylabel('Instant Power') axarr[3*i",
"totalEnergy / tau #### Reshape to ensure needed dimensions ## Assume that the",
"color=colors[i]) axarr[3*i + 2].plot(phase, CorrFs[:,i], label='Crr-'+labelInfo,linewidth=2, color=colors[i]) axarr[3*i + 0].plot(t, avgPower, '--', label='AvgPower',",
"averagePower = totalEnergy / tau #### Reshape to ensure needed dimensions ## Assume",
"Returns: plt.figure: Figure handle plt.axis: Axis handle \"\"\" #### Assume the following constants",
"## Make all plots ## Calculate Avg power. avgPower = np.sum(ModFs[:,0]) / N",
"np.linspace(0, tau, N) phase = np.linspace(0, 2*np.pi,N) #### Reshape to ensure same dimensions",
"1].set_ylabel('Exposure') axarr[3*i + 2].set_ylabel('Magnitude') ## Set Titles axarr[0].set_title('Modulation') axarr[1].set_title('Demodulation') axarr[2].set_title('Correlation') # ## Set",
"2].set_ylabel('Magnitude') ## Set Titles axarr[0].set_title('Modulation') axarr[1].set_title('Demodulation') axarr[2].set_title('Correlation') # ## Set ylimit so that",
"= ModFs.shape avgPower = np.sum(ModFs[:,0])/N #### Set default values t = np.linspace(0, tau,",
"plotParams = { 'font.size': 16, 'figure.dpi': 80, 'figure.autolayout': True, 'figure.titleweight': 'bold', 'savefig.dpi': 200,",
"and get axis array for i in range(K): # breakpoint() fig.add_subplot(K,3,3*i + 1)",
"in range(K): # breakpoint() fig.add_subplot(K,3,3*i + 1) fig.add_subplot(K,3,3*i + 2) fig.add_subplot(K,3,3*i + 3)"
] |
[
"AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,",
"def openListFile(fileName, delim=','): \"\"\" \" Open a file or exit of the program,",
"+ fileName + \"'. ABORT.\") sys.exit(-1) text = finput.readlines() finput.close() return text def",
"MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE",
"\"\"\" try: finput = open(fileName, 'r') except IOError: print(\"Error loading file '\" +",
"IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED",
"delim \"\"\" try: finput = open(fileName, 'r') except IOError: print(\"Error loading text file",
"return def openListFile(fileName, delim=','): \"\"\" \" Open a file or exit of the",
"sys.exit(-1) return finput def openTxtFile(fileName): \"\"\" \" Open a file or exit of",
"this software and associated documentation files (the \"Software\"), to deal in the Software",
"OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE",
"\" Open a file or exit of the program, \" return the handler",
"a list of lines of text of the file \"\"\" try: finput =",
"exit of the program, \" return the handler of the file \"\"\" try:",
"USE OR OTHER DEALINGS IN THE SOFTWARE. \"\"\" import sys def openFile(fileName): \"\"\"",
"return a list of lines of text of the file \"\"\" try: finput",
"OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING",
"CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR",
"the Software without restriction, including without limitation the rights to use, copy, modify,",
"person obtaining a copy of this software and associated documentation files (the \"Software\"),",
"the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies",
"without restriction, including without limitation the rights to use, copy, modify, merge, publish,",
"merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit",
"= open(fileName, 'r') except IOError: print(\"Error loading file '\" + fileName + \"'.",
"fileName + \"'. ABORT.\") sys.exit(-1) return finput def openTxtFile(fileName): \"\"\" \" Open a",
"+ fileName + \"'. ABORT.\") sys.exit(-1) text = finput.read() listT = text.split(delim) listT",
"def openLinesTxtFile(fileName): \"\"\" \" Open a file or exit of the program, \"",
"in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED",
"sublicense, and/or sell copies of the Software, and to permit persons to whom",
"this permission notice shall be included in all copies or substantial portions of",
"+ \"'. ABORT.\") sys.exit(-1) text = finput.readlines() finput.close() return text def saveTxtFile(fileName, text,",
"modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to",
"ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT",
"file '\" + fileName + \"'. ABORT.\") sys.exit(-1) text = finput.read() listT =",
"IOError: print(\"Error loading text file '\" + fileName + \"'. ABORT.\") sys.exit(-1) text",
"foutput.close() return def openListFile(fileName, delim=','): \"\"\" \" Open a file or exit of",
"WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT",
"+ \"'. ABORT.\") sys.exit(-1) text = finput.read() finput.close() return text def openLinesTxtFile(fileName): \"\"\"",
"LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF",
"except IOError: print(\"Error loading text file '\" + fileName + \"'. ABORT.\") sys.exit(-1)",
"IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A",
"of the file \"\"\" try: if append: foutput = open(fileName, 'a') else: foutput",
"notice and this permission notice shall be included in all copies or substantial",
"program, \" return a list separated by delim \"\"\" try: finput = open(fileName,",
"TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE",
"charge, to any person obtaining a copy of this software and associated documentation",
"Open a file or exit of the program, \" return a list separated",
"finput.read() listT = text.split(delim) listT = [item.replace('\\n', '').replace('\\r','').strip() for item in listT] finput.close()",
"KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,",
"+ fileName + \"'. ABORT.\") sys.exit(-1) foutput.write(text) foutput.close() return def openListFile(fileName, delim=','): \"\"\"",
"fileName + \"'. ABORT.\") sys.exit(-1) foutput.write(text) foutput.close() return def openListFile(fileName, delim=','): \"\"\" \"",
"def saveTxtFile(fileName, text, append=False): \"\"\" \" Open a file or exit of the",
"BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION",
"persons to whom the Software is furnished to do so, subject to the",
"sys.exit(-1) foutput.write(text) foutput.close() return def openListFile(fileName, delim=','): \"\"\" \" Open a file or",
"Software is furnished to do so, subject to the following conditions: The above",
"finput = open(fileName, 'r') except IOError: print(\"Error loading file '\" + fileName +",
"IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY",
"NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND",
"lines of text of the file \"\"\" try: finput = open(fileName, 'r') except",
"fileName + \"'. ABORT.\") sys.exit(-1) text = finput.read() listT = text.split(delim) listT =",
"the program, \" return a list of lines of text of the file",
"file \"\"\" try: finput = open(fileName, 'r') except IOError: print(\"Error loading file '\"",
"to deal in the Software without restriction, including without limitation the rights to",
"or exit of the program, \" return a list of lines of text",
"of the program, \" return the text of the file \"\"\" try: if",
"list of lines of text of the file \"\"\" try: finput = open(fileName,",
"encoding: utf-8 \"\"\" Copyright 2018 (c) <NAME> Permission is hereby granted, free of",
"to whom the Software is furnished to do so, subject to the following",
"documentation files (the \"Software\"), to deal in the Software without restriction, including without",
"try: if append: foutput = open(fileName, 'a') else: foutput = open(fileName, 'w') except",
"files (the \"Software\"), to deal in the Software without restriction, including without limitation",
"Software without restriction, including without limitation the rights to use, copy, modify, merge,",
"except IOError: print(\"Error loading file '\" + fileName + \"'. ABORT.\") sys.exit(-1) return",
"file or exit of the program, \" return a list of lines of",
"= finput.readlines() finput.close() return text def saveTxtFile(fileName, text, append=False): \"\"\" \" Open a",
"to do so, subject to the following conditions: The above copyright notice and",
"in the Software without restriction, including without limitation the rights to use, copy,",
"Copyright 2018 (c) <NAME> Permission is hereby granted, free of charge, to any",
"SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \"\"\" import sys",
"\" return the text of the file \"\"\" try: if append: foutput =",
"utf-8 \"\"\" Copyright 2018 (c) <NAME> Permission is hereby granted, free of charge,",
"the Software. THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,",
"to any person obtaining a copy of this software and associated documentation files",
"AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN",
"\"\"\" try: finput = open(fileName, 'r') except IOError: print(\"Error loading text file '\"",
"a file or exit of the program, \" return a list of lines",
"+ fileName + \"'. ABORT.\") sys.exit(-1) text = finput.read() finput.close() return text def",
"\" Open a file or exit of the program, \" return the text",
"sys def openFile(fileName): \"\"\" \" Open a file or exit of the program,",
"the program, \" return the handler of the file \"\"\" try: finput =",
"return the handler of the file \"\"\" try: finput = open(fileName, 'r') except",
"a copy of this software and associated documentation files (the \"Software\"), to deal",
"Software. THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS",
"file or exit of the program, \" return the text of the file",
"OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN",
"IOError: print(\"Error loading text file '\" + fileName + \"'. ABORT.\") sys.exit(-1) foutput.write(text)",
"if append: foutput = open(fileName, 'a') else: foutput = open(fileName, 'w') except IOError:",
"WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF",
"the file \"\"\" try: finput = open(fileName, 'r') except IOError: print(\"Error loading file",
"ABORT.\") sys.exit(-1) return finput def openTxtFile(fileName): \"\"\" \" Open a file or exit",
"free of charge, to any person obtaining a copy of this software and",
"and this permission notice shall be included in all copies or substantial portions",
"loading text file '\" + fileName + \"'. ABORT.\") sys.exit(-1) text = finput.read()",
"and to permit persons to whom the Software is furnished to do so,",
"OR OTHER DEALINGS IN THE SOFTWARE. \"\"\" import sys def openFile(fileName): \"\"\" \"",
"openTxtFile(fileName): \"\"\" \" Open a file or exit of the program, \" return",
"rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of",
"a file or exit of the program, \" return a list separated by",
"open(fileName, 'r') except IOError: print(\"Error loading file '\" + fileName + \"'. ABORT.\")",
"exit of the program, \" return a list separated by delim \"\"\" try:",
"EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES",
"associated documentation files (the \"Software\"), to deal in the Software without restriction, including",
"# encoding: utf-8 \"\"\" Copyright 2018 (c) <NAME> Permission is hereby granted, free",
"BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE",
"openListFile(fileName, delim=','): \"\"\" \" Open a file or exit of the program, \"",
"SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,",
"try: finput = open(fileName, 'r') except IOError: print(\"Error loading file '\" + fileName",
"exit of the program, \" return the text of the file \"\"\" try:",
"notice shall be included in all copies or substantial portions of the Software.",
"def openFile(fileName): \"\"\" \" Open a file or exit of the program, \"",
"return text def saveTxtFile(fileName, text, append=False): \"\"\" \" Open a file or exit",
"append: foutput = open(fileName, 'a') else: foutput = open(fileName, 'w') except IOError: print(\"Error",
"a file or exit of the program, \" return the text of the",
"text file '\" + fileName + \"'. ABORT.\") sys.exit(-1) text = finput.readlines() finput.close()",
"the file \"\"\" try: finput = open(fileName, 'r') except IOError: print(\"Error loading text",
"\"'. ABORT.\") sys.exit(-1) text = finput.read() finput.close() return text def openLinesTxtFile(fileName): \"\"\" \"",
"LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT",
"copy of this software and associated documentation files (the \"Software\"), to deal in",
"file \"\"\" try: if append: foutput = open(fileName, 'a') else: foutput = open(fileName,",
"of lines of text of the file \"\"\" try: finput = open(fileName, 'r')",
"substantial portions of the Software. THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY",
"ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION",
"ABORT.\") sys.exit(-1) text = finput.read() listT = text.split(delim) listT = [item.replace('\\n', '').replace('\\r','').strip() for",
"text file '\" + fileName + \"'. ABORT.\") sys.exit(-1) text = finput.read() finput.close()",
"+ \"'. ABORT.\") sys.exit(-1) return finput def openTxtFile(fileName): \"\"\" \" Open a file",
"obtaining a copy of this software and associated documentation files (the \"Software\"), to",
"TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN",
"= open(fileName, 'a') else: foutput = open(fileName, 'w') except IOError: print(\"Error loading text",
"else: foutput = open(fileName, 'w') except IOError: print(\"Error loading text file '\" +",
"OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR",
"IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR",
"sys.exit(-1) text = finput.read() finput.close() return text def openLinesTxtFile(fileName): \"\"\" \" Open a",
"file \"\"\" try: finput = open(fileName, 'r') except IOError: print(\"Error loading text file",
"Open a file or exit of the program, \" return a list of",
"OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,",
"file '\" + fileName + \"'. ABORT.\") sys.exit(-1) text = finput.read() finput.close() return",
"publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons",
"including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,",
"or substantial portions of the Software. THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT",
"program, \" return a list of lines of text of the file \"\"\"",
"foutput = open(fileName, 'a') else: foutput = open(fileName, 'w') except IOError: print(\"Error loading",
"= text.split(delim) listT = [item.replace('\\n', '').replace('\\r','').strip() for item in listT] finput.close() return listT",
"THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \"\"\" import",
"all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED \"AS",
"SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR",
"file '\" + fileName + \"'. ABORT.\") sys.exit(-1) return finput def openTxtFile(fileName): \"\"\"",
"or exit of the program, \" return a list separated by delim \"\"\"",
"the handler of the file \"\"\" try: finput = open(fileName, 'r') except IOError:",
"print(\"Error loading text file '\" + fileName + \"'. ABORT.\") sys.exit(-1) foutput.write(text) foutput.close()",
"fileName + \"'. ABORT.\") sys.exit(-1) text = finput.readlines() finput.close() return text def saveTxtFile(fileName,",
"loading file '\" + fileName + \"'. ABORT.\") sys.exit(-1) return finput def openTxtFile(fileName):",
"OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES",
"fileName + \"'. ABORT.\") sys.exit(-1) text = finput.read() finput.close() return text def openLinesTxtFile(fileName):",
"finput.close() return text def saveTxtFile(fileName, text, append=False): \"\"\" \" Open a file or",
"to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the",
"COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN",
"finput.readlines() finput.close() return text def saveTxtFile(fileName, text, append=False): \"\"\" \" Open a file",
"= finput.read() listT = text.split(delim) listT = [item.replace('\\n', '').replace('\\r','').strip() for item in listT]",
"of the file \"\"\" try: finput = open(fileName, 'r') except IOError: print(\"Error loading",
"ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE",
"OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL",
"\" Open a file or exit of the program, \" return a list",
"text = finput.readlines() finput.close() return text def saveTxtFile(fileName, text, append=False): \"\"\" \" Open",
"above copyright notice and this permission notice shall be included in all copies",
"text, append=False): \"\"\" \" Open a file or exit of the program, \"",
"WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE",
"return the text of the file \"\"\" try: if append: foutput = open(fileName,",
"import sys def openFile(fileName): \"\"\" \" Open a file or exit of the",
"PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS",
"permission notice shall be included in all copies or substantial portions of the",
"FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS",
"+ \"'. ABORT.\") sys.exit(-1) text = finput.read() listT = text.split(delim) listT = [item.replace('\\n',",
"2018 (c) <NAME> Permission is hereby granted, free of charge, to any person",
"OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH",
"the following conditions: The above copyright notice and this permission notice shall be",
"= open(fileName, 'r') except IOError: print(\"Error loading text file '\" + fileName +",
"the text of the file \"\"\" try: finput = open(fileName, 'r') except IOError:",
"handler of the file \"\"\" try: finput = open(fileName, 'r') except IOError: print(\"Error",
"THE USE OR OTHER DEALINGS IN THE SOFTWARE. \"\"\" import sys def openFile(fileName):",
"\"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT",
"furnished to do so, subject to the following conditions: The above copyright notice",
"loading text file '\" + fileName + \"'. ABORT.\") sys.exit(-1) text = finput.readlines()",
"'r') except IOError: print(\"Error loading file '\" + fileName + \"'. ABORT.\") sys.exit(-1)",
"permit persons to whom the Software is furnished to do so, subject to",
"\"\"\" import sys def openFile(fileName): \"\"\" \" Open a file or exit of",
"any person obtaining a copy of this software and associated documentation files (the",
"copies of the Software, and to permit persons to whom the Software is",
"= open(fileName, 'w') except IOError: print(\"Error loading text file '\" + fileName +",
"of the program, \" return the text of the file \"\"\" try: finput",
"CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.",
"\"\"\" \" Open a file or exit of the program, \" return the",
"return text def openLinesTxtFile(fileName): \"\"\" \" Open a file or exit of the",
"included in all copies or substantial portions of the Software. THE SOFTWARE IS",
"copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and",
"program, \" return the handler of the file \"\"\" try: finput = open(fileName,",
"program, \" return the text of the file \"\"\" try: finput = open(fileName,",
"+ \"'. ABORT.\") sys.exit(-1) foutput.write(text) foutput.close() return def openListFile(fileName, delim=','): \"\"\" \" Open",
"'\" + fileName + \"'. ABORT.\") sys.exit(-1) text = finput.read() listT = text.split(delim)",
"try: finput = open(fileName, 'r') except IOError: print(\"Error loading text file '\" +",
"THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER",
"separated by delim \"\"\" try: finput = open(fileName, 'r') except IOError: print(\"Error loading",
"THE SOFTWARE. \"\"\" import sys def openFile(fileName): \"\"\" \" Open a file or",
"text def openLinesTxtFile(fileName): \"\"\" \" Open a file or exit of the program,",
"the Software, and to permit persons to whom the Software is furnished to",
"HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN",
"\"'. ABORT.\") sys.exit(-1) foutput.write(text) foutput.close() return def openListFile(fileName, delim=','): \"\"\" \" Open a",
"use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software,",
"following conditions: The above copyright notice and this permission notice shall be included",
"append=False): \"\"\" \" Open a file or exit of the program, \" return",
"copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED \"AS IS\",",
"text = finput.read() listT = text.split(delim) listT = [item.replace('\\n', '').replace('\\r','').strip() for item in",
"ABORT.\") sys.exit(-1) text = finput.read() finput.close() return text def openLinesTxtFile(fileName): \"\"\" \" Open",
"NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR",
"+ fileName + \"'. ABORT.\") sys.exit(-1) return finput def openTxtFile(fileName): \"\"\" \" Open",
"The above copyright notice and this permission notice shall be included in all",
"finput def openTxtFile(fileName): \"\"\" \" Open a file or exit of the program,",
"\" return a list separated by delim \"\"\" try: finput = open(fileName, 'r')",
"\"Software\"), to deal in the Software without restriction, including without limitation the rights",
"deal in the Software without restriction, including without limitation the rights to use,",
"'w') except IOError: print(\"Error loading text file '\" + fileName + \"'. ABORT.\")",
"granted, free of charge, to any person obtaining a copy of this software",
"limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell",
"AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE",
"of the program, \" return a list separated by delim \"\"\" try: finput",
"ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF",
"of this software and associated documentation files (the \"Software\"), to deal in the",
"WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO",
"saveTxtFile(fileName, text, append=False): \"\"\" \" Open a file or exit of the program,",
"sell copies of the Software, and to permit persons to whom the Software",
"the file \"\"\" try: if append: foutput = open(fileName, 'a') else: foutput =",
"<reponame>german-arroyo-moreno/AutoAcademia # encoding: utf-8 \"\"\" Copyright 2018 (c) <NAME> Permission is hereby granted,",
"by delim \"\"\" try: finput = open(fileName, 'r') except IOError: print(\"Error loading text",
"text file '\" + fileName + \"'. ABORT.\") sys.exit(-1) foutput.write(text) foutput.close() return def",
"do so, subject to the following conditions: The above copyright notice and this",
"sys.exit(-1) text = finput.read() listT = text.split(delim) listT = [item.replace('\\n', '').replace('\\r','').strip() for item",
"exit of the program, \" return a list of lines of text of",
"listT = text.split(delim) listT = [item.replace('\\n', '').replace('\\r','').strip() for item in listT] finput.close() return",
"open(fileName, 'r') except IOError: print(\"Error loading text file '\" + fileName + \"'.",
"is furnished to do so, subject to the following conditions: The above copyright",
"text = finput.read() finput.close() return text def openLinesTxtFile(fileName): \"\"\" \" Open a file",
"= finput.read() finput.close() return text def openLinesTxtFile(fileName): \"\"\" \" Open a file or",
"\" return the handler of the file \"\"\" try: finput = open(fileName, 'r')",
"(c) <NAME> Permission is hereby granted, free of charge, to any person obtaining",
"so, subject to the following conditions: The above copyright notice and this permission",
"def openTxtFile(fileName): \"\"\" \" Open a file or exit of the program, \"",
"finput.close() return text def openLinesTxtFile(fileName): \"\"\" \" Open a file or exit of",
"FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR",
"INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR",
"DEALINGS IN THE SOFTWARE. \"\"\" import sys def openFile(fileName): \"\"\" \" Open a",
"text of the file \"\"\" try: if append: foutput = open(fileName, 'a') else:",
"of the Software, and to permit persons to whom the Software is furnished",
"finput = open(fileName, 'r') except IOError: print(\"Error loading text file '\" + fileName",
"and/or sell copies of the Software, and to permit persons to whom the",
"print(\"Error loading file '\" + fileName + \"'. ABORT.\") sys.exit(-1) return finput def",
"'\" + fileName + \"'. ABORT.\") sys.exit(-1) return finput def openTxtFile(fileName): \"\"\" \"",
"Open a file or exit of the program, \" return the handler of",
"text of the file \"\"\" try: finput = open(fileName, 'r') except IOError: print(\"Error",
"of charge, to any person obtaining a copy of this software and associated",
"(the \"Software\"), to deal in the Software without restriction, including without limitation the",
"return finput def openTxtFile(fileName): \"\"\" \" Open a file or exit of the",
"'\" + fileName + \"'. ABORT.\") sys.exit(-1) foutput.write(text) foutput.close() return def openListFile(fileName, delim=','):",
"copyright notice and this permission notice shall be included in all copies or",
"to permit persons to whom the Software is furnished to do so, subject",
"file or exit of the program, \" return a list separated by delim",
"\"'. ABORT.\") sys.exit(-1) text = finput.readlines() finput.close() return text def saveTxtFile(fileName, text, append=False):",
"a list separated by delim \"\"\" try: finput = open(fileName, 'r') except IOError:",
"IOError: print(\"Error loading file '\" + fileName + \"'. ABORT.\") sys.exit(-1) return finput",
"OTHER DEALINGS IN THE SOFTWARE. \"\"\" import sys def openFile(fileName): \"\"\" \" Open",
"conditions: The above copyright notice and this permission notice shall be included in",
"or exit of the program, \" return the handler of the file \"\"\"",
"THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO",
"file '\" + fileName + \"'. ABORT.\") sys.exit(-1) foutput.write(text) foutput.close() return def openListFile(fileName,",
"SOFTWARE. \"\"\" import sys def openFile(fileName): \"\"\" \" Open a file or exit",
"\"\"\" try: if append: foutput = open(fileName, 'a') else: foutput = open(fileName, 'w')",
"OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER",
"Permission is hereby granted, free of charge, to any person obtaining a copy",
"'a') else: foutput = open(fileName, 'w') except IOError: print(\"Error loading text file '\"",
"be included in all copies or substantial portions of the Software. THE SOFTWARE",
"THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR",
"IN THE SOFTWARE. \"\"\" import sys def openFile(fileName): \"\"\" \" Open a file",
"sys.exit(-1) text = finput.readlines() finput.close() return text def saveTxtFile(fileName, text, append=False): \"\"\" \"",
"'\" + fileName + \"'. ABORT.\") sys.exit(-1) text = finput.read() finput.close() return text",
"whom the Software is furnished to do so, subject to the following conditions:",
"the text of the file \"\"\" try: if append: foutput = open(fileName, 'a')",
"the program, \" return the text of the file \"\"\" try: finput =",
"print(\"Error loading text file '\" + fileName + \"'. ABORT.\") sys.exit(-1) text =",
"'\" + fileName + \"'. ABORT.\") sys.exit(-1) text = finput.readlines() finput.close() return text",
"ABORT.\") sys.exit(-1) foutput.write(text) foutput.close() return def openListFile(fileName, delim=','): \"\"\" \" Open a file",
"WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \"\"\"",
"\" return the text of the file \"\"\" try: finput = open(fileName, 'r')",
"FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR",
"'r') except IOError: print(\"Error loading text file '\" + fileName + \"'. ABORT.\")",
"file '\" + fileName + \"'. ABORT.\") sys.exit(-1) text = finput.readlines() finput.close() return",
"\"'. ABORT.\") sys.exit(-1) return finput def openTxtFile(fileName): \"\"\" \" Open a file or",
"a file or exit of the program, \" return the handler of the",
"program, \" return the text of the file \"\"\" try: if append: foutput",
"open(fileName, 'w') except IOError: print(\"Error loading text file '\" + fileName + \"'.",
"text file '\" + fileName + \"'. ABORT.\") sys.exit(-1) text = finput.read() listT",
"\"\"\" \" Open a file or exit of the program, \" return a",
"portions of the Software. THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF",
"openLinesTxtFile(fileName): \"\"\" \" Open a file or exit of the program, \" return",
"loading text file '\" + fileName + \"'. ABORT.\") sys.exit(-1) foutput.write(text) foutput.close() return",
"DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,",
"distribute, sublicense, and/or sell copies of the Software, and to permit persons to",
"of the Software. THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY",
"software and associated documentation files (the \"Software\"), to deal in the Software without",
"ABORT.\") sys.exit(-1) text = finput.readlines() finput.close() return text def saveTxtFile(fileName, text, append=False): \"\"\"",
"shall be included in all copies or substantial portions of the Software. THE",
"of the program, \" return the handler of the file \"\"\" try: finput",
"NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,",
"OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \"\"\" import sys def",
"list separated by delim \"\"\" try: finput = open(fileName, 'r') except IOError: print(\"Error",
"LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.",
"IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE",
"PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT",
"the Software is furnished to do so, subject to the following conditions: The",
"of text of the file \"\"\" try: finput = open(fileName, 'r') except IOError:",
"IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING",
"A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT",
"EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS",
"subject to the following conditions: The above copyright notice and this permission notice",
"PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE",
"\"\"\" Copyright 2018 (c) <NAME> Permission is hereby granted, free of charge, to",
"\"'. ABORT.\") sys.exit(-1) text = finput.read() listT = text.split(delim) listT = [item.replace('\\n', '').replace('\\r','').strip()",
"the program, \" return a list separated by delim \"\"\" try: finput =",
"return the text of the file \"\"\" try: finput = open(fileName, 'r') except",
"is hereby granted, free of charge, to any person obtaining a copy of",
"of the program, \" return a list of lines of text of the",
"return a list separated by delim \"\"\" try: finput = open(fileName, 'r') except",
"and associated documentation files (the \"Software\"), to deal in the Software without restriction,",
"FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,",
"without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or",
"OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER",
"hereby granted, free of charge, to any person obtaining a copy of this",
"CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE",
"foutput.write(text) foutput.close() return def openListFile(fileName, delim=','): \"\"\" \" Open a file or exit",
"finput.read() finput.close() return text def openLinesTxtFile(fileName): \"\"\" \" Open a file or exit",
"foutput = open(fileName, 'w') except IOError: print(\"Error loading text file '\" + fileName",
"restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute,",
"OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR",
"to the following conditions: The above copyright notice and this permission notice shall",
"text def saveTxtFile(fileName, text, append=False): \"\"\" \" Open a file or exit of",
"OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS",
"Software, and to permit persons to whom the Software is furnished to do",
"or exit of the program, \" return the text of the file \"\"\"",
"open(fileName, 'a') else: foutput = open(fileName, 'w') except IOError: print(\"Error loading text file",
"the program, \" return the text of the file \"\"\" try: if append:",
"file or exit of the program, \" return the handler of the file",
"<NAME> Permission is hereby granted, free of charge, to any person obtaining a",
"Open a file or exit of the program, \" return the text of",
"delim=','): \"\"\" \" Open a file or exit of the program, \" return",
"\" return a list of lines of text of the file \"\"\" try:",
"openFile(fileName): \"\"\" \" Open a file or exit of the program, \" return"
] |
[
"= 0 guess_limit = 3 out_of_guesses = False # while (guess != secret_word):",
"secret_word and not(out_of_guesses): if guess_count < guess_limit: guess = input(\"Enter guess: \") guess_count",
"program and then the user # will interact with the program to try",
"guess = input(\"Enter guess: \") # guess_count += 1 # print(\"You win!!!\") while",
"guesses # the word correctly or the user runs out of guesses if",
"to be able to keep guessing what the secret word is until they",
"possible scenarios. it's either the user guesses # the word correctly or the",
"secret word that we store inside of our program and then the user",
"print(\"You re out of guesses and you lost the game\") else: print(\"You win!!\")",
"able to keep guessing what the secret word is until they finally get",
"the word. secret_word = \"hello\" guess = \"\" guess_count = 0 guess_limit =",
"+= 1 # print(\"You win!!!\") while guess != secret_word and not(out_of_guesses): if guess_count",
"<reponame>Olayinka2020/ds_wkday_class # the idea is that we'll have a secret word that we",
"they finally get the word. secret_word = \"hello\" guess = \"\" guess_count =",
"not(out_of_guesses): if guess_count < guess_limit: guess = input(\"Enter guess: \") guess_count += 1",
"scenarios. it's either the user guesses # the word correctly or the user",
"user guesses # the word correctly or the user runs out of guesses",
"user to be able to keep guessing what the secret word is until",
"correctly or the user runs out of guesses if out_of_guesses: print(\"You re out",
"out_of_guesses: print(\"You re out of guesses and you lost the game\") else: print(\"You",
"# we want the user to be able to keep guessing what the",
"= \"hello\" guess = \"\" guess_count = 0 guess_limit = 3 out_of_guesses =",
"either the user guesses # the word correctly or the user runs out",
"with the program to try and guess the secret word # we want",
"# guess_count += 1 # print(\"You win!!!\") while guess != secret_word and not(out_of_guesses):",
"# while (guess != secret_word): # guess = input(\"Enter guess: \") # guess_count",
"# guess = input(\"Enter guess: \") # guess_count += 1 # print(\"You win!!!\")",
"a secret word that we store inside of our program and then the",
"user runs out of guesses if out_of_guesses: print(\"You re out of guesses and",
"to try and guess the secret word # we want the user to",
"secret word # we want the user to be able to keep guessing",
"# the word correctly or the user runs out of guesses if out_of_guesses:",
"2 possible scenarios. it's either the user guesses # the word correctly or",
"and not(out_of_guesses): if guess_count < guess_limit: guess = input(\"Enter guess: \") guess_count +=",
"user # will interact with the program to try and guess the secret",
"be 2 possible scenarios. it's either the user guesses # the word correctly",
"it's either the user guesses # the word correctly or the user runs",
"secret_word = \"hello\" guess = \"\" guess_count = 0 guess_limit = 3 out_of_guesses",
"what the secret word is until they finally get the word. secret_word =",
"the user runs out of guesses if out_of_guesses: print(\"You re out of guesses",
"loop, there's going to be 2 possible scenarios. it's either the user guesses",
"try and guess the secret word # we want the user to be",
"guess_limit = 3 out_of_guesses = False # while (guess != secret_word): # guess",
"= input(\"Enter guess: \") # guess_count += 1 # print(\"You win!!!\") while guess",
"guess_count += 1 # print(\"You win!!!\") while guess != secret_word and not(out_of_guesses): if",
"the program to try and guess the secret word # we want the",
"word. secret_word = \"hello\" guess = \"\" guess_count = 0 guess_limit = 3",
"1 # print(\"You win!!!\") while guess != secret_word and not(out_of_guesses): if guess_count <",
"the idea is that we'll have a secret word that we store inside",
"\"hello\" guess = \"\" guess_count = 0 guess_limit = 3 out_of_guesses = False",
"word # we want the user to be able to keep guessing what",
"be able to keep guessing what the secret word is until they finally",
"= input(\"Enter guess: \") guess_count += 1 else: out_of_guesses = True # when",
"while guess != secret_word and not(out_of_guesses): if guess_count < guess_limit: guess = input(\"Enter",
"that we'll have a secret word that we store inside of our program",
"guess_count += 1 else: out_of_guesses = True # when we break this loop,",
"store inside of our program and then the user # will interact with",
"win!!!\") while guess != secret_word and not(out_of_guesses): if guess_count < guess_limit: guess =",
"guesses if out_of_guesses: print(\"You re out of guesses and you lost the game\")",
"then the user # will interact with the program to try and guess",
"(guess != secret_word): # guess = input(\"Enter guess: \") # guess_count += 1",
"or the user runs out of guesses if out_of_guesses: print(\"You re out of",
"to keep guessing what the secret word is until they finally get the",
"and guess the secret word # we want the user to be able",
"word is until they finally get the word. secret_word = \"hello\" guess =",
"# print(\"You win!!!\") while guess != secret_word and not(out_of_guesses): if guess_count < guess_limit:",
"word correctly or the user runs out of guesses if out_of_guesses: print(\"You re",
"interact with the program to try and guess the secret word # we",
"if out_of_guesses: print(\"You re out of guesses and you lost the game\") else:",
"there's going to be 2 possible scenarios. it's either the user guesses #",
"get the word. secret_word = \"hello\" guess = \"\" guess_count = 0 guess_limit",
"the word correctly or the user runs out of guesses if out_of_guesses: print(\"You",
"keep guessing what the secret word is until they finally get the word.",
"to be 2 possible scenarios. it's either the user guesses # the word",
"and then the user # will interact with the program to try and",
"the user guesses # the word correctly or the user runs out of",
"else: out_of_guesses = True # when we break this loop, there's going to",
"if guess_count < guess_limit: guess = input(\"Enter guess: \") guess_count += 1 else:",
"program to try and guess the secret word # we want the user",
"guess = input(\"Enter guess: \") guess_count += 1 else: out_of_guesses = True #",
"of our program and then the user # will interact with the program",
"our program and then the user # will interact with the program to",
"= 3 out_of_guesses = False # while (guess != secret_word): # guess =",
"guessing what the secret word is until they finally get the word. secret_word",
"the user # will interact with the program to try and guess the",
"= \"\" guess_count = 0 guess_limit = 3 out_of_guesses = False # while",
"is that we'll have a secret word that we store inside of our",
"we want the user to be able to keep guessing what the secret",
"want the user to be able to keep guessing what the secret word",
"the user to be able to keep guessing what the secret word is",
"guess_count = 0 guess_limit = 3 out_of_guesses = False # while (guess !=",
"# the idea is that we'll have a secret word that we store",
"the secret word # we want the user to be able to keep",
"break this loop, there's going to be 2 possible scenarios. it's either the",
"\") # guess_count += 1 # print(\"You win!!!\") while guess != secret_word and",
"out_of_guesses = True # when we break this loop, there's going to be",
"idea is that we'll have a secret word that we store inside of",
"secret_word): # guess = input(\"Enter guess: \") # guess_count += 1 # print(\"You",
"will interact with the program to try and guess the secret word #",
"3 out_of_guesses = False # while (guess != secret_word): # guess = input(\"Enter",
"input(\"Enter guess: \") # guess_count += 1 # print(\"You win!!!\") while guess !=",
"\") guess_count += 1 else: out_of_guesses = True # when we break this",
"guess_limit: guess = input(\"Enter guess: \") guess_count += 1 else: out_of_guesses = True",
"= True # when we break this loop, there's going to be 2",
"inside of our program and then the user # will interact with the",
"while (guess != secret_word): # guess = input(\"Enter guess: \") # guess_count +=",
"guess_count < guess_limit: guess = input(\"Enter guess: \") guess_count += 1 else: out_of_guesses",
"going to be 2 possible scenarios. it's either the user guesses # the",
"this loop, there's going to be 2 possible scenarios. it's either the user",
"out of guesses if out_of_guesses: print(\"You re out of guesses and you lost",
"secret word is until they finally get the word. secret_word = \"hello\" guess",
"print(\"You win!!!\") while guess != secret_word and not(out_of_guesses): if guess_count < guess_limit: guess",
"+= 1 else: out_of_guesses = True # when we break this loop, there's",
"1 else: out_of_guesses = True # when we break this loop, there's going",
"False # while (guess != secret_word): # guess = input(\"Enter guess: \") #",
"# will interact with the program to try and guess the secret word",
"guess = \"\" guess_count = 0 guess_limit = 3 out_of_guesses = False #",
"have a secret word that we store inside of our program and then",
"we store inside of our program and then the user # will interact",
"out_of_guesses = False # while (guess != secret_word): # guess = input(\"Enter guess:",
"!= secret_word): # guess = input(\"Enter guess: \") # guess_count += 1 #",
"\"\" guess_count = 0 guess_limit = 3 out_of_guesses = False # while (guess",
"< guess_limit: guess = input(\"Enter guess: \") guess_count += 1 else: out_of_guesses =",
"word that we store inside of our program and then the user #",
"True # when we break this loop, there's going to be 2 possible",
"guess: \") guess_count += 1 else: out_of_guesses = True # when we break",
"we break this loop, there's going to be 2 possible scenarios. it's either",
"guess != secret_word and not(out_of_guesses): if guess_count < guess_limit: guess = input(\"Enter guess:",
"# when we break this loop, there's going to be 2 possible scenarios.",
"of guesses if out_of_guesses: print(\"You re out of guesses and you lost the",
"guess the secret word # we want the user to be able to",
"when we break this loop, there's going to be 2 possible scenarios. it's",
"we'll have a secret word that we store inside of our program and",
"finally get the word. secret_word = \"hello\" guess = \"\" guess_count = 0",
"0 guess_limit = 3 out_of_guesses = False # while (guess != secret_word): #",
"!= secret_word and not(out_of_guesses): if guess_count < guess_limit: guess = input(\"Enter guess: \")",
"the secret word is until they finally get the word. secret_word = \"hello\"",
"that we store inside of our program and then the user # will",
"until they finally get the word. secret_word = \"hello\" guess = \"\" guess_count",
"runs out of guesses if out_of_guesses: print(\"You re out of guesses and you",
"= False # while (guess != secret_word): # guess = input(\"Enter guess: \")",
"input(\"Enter guess: \") guess_count += 1 else: out_of_guesses = True # when we",
"guess: \") # guess_count += 1 # print(\"You win!!!\") while guess != secret_word",
"is until they finally get the word. secret_word = \"hello\" guess = \"\""
] |
[
"generator — netwokrx graph generator, kwargs — generator named arguments ''' self.G =",
"self.used_colors = [] self.current_state = np.full(self.n, self.n, dtype=np.uint32) self.done = False self.total_reward =",
"#determine by n and m (?) self.edges = np.array(self.G.edges()) self.n = len(self.G.nodes()) self.m",
"action): def is_action_available(action): node, color = action adjacent_nodes = np.unique(self.edges[np.sum(np.isin(self.edges, node), axis=1, dtype=bool)])",
"np.full(self.n, self.n, dtype=np.uint32) self.done = False self.total_reward = 0 def render(self, mode='human', close=False):",
"True info = {} return self.current_state, reward, self.done, info def reset(self): self.used_colors =",
"import spaces, Env class NXColoringEnv(Env): def __init__(self, generator=nx.barabasi_albert_graph, **kwargs): ''' generator — netwokrx",
"= -1 self.total_reward -= 1 self.used_colors.append(color) if self.n not in np.unique(self.current_state): self.done =",
"dtype=np.uint32) self.used_colors = [] self.current_state = np.full(self.n, self.n, dtype=np.uint32) self.done = False self.total_reward",
"-= 1 self.used_colors.append(color) if self.n not in np.unique(self.current_state): self.done = True info =",
"self.edges = np.array(self.G.edges()) self.n = len(self.G.nodes()) self.m = len(self.edges) self.action_space = spaces.Box(low=0, high=self.n-1,",
"reward = -1 self.total_reward -= 1 self.used_colors.append(color) if self.n not in np.unique(self.current_state): self.done",
"is_action_available(action): node, color = action adjacent_nodes = np.unique(self.edges[np.sum(np.isin(self.edges, node), axis=1, dtype=bool)]) return ~np.any(self.current_state[adjacent_nodes]==color)",
"def is_action_available(action): node, color = action adjacent_nodes = np.unique(self.edges[np.sum(np.isin(self.edges, node), axis=1, dtype=bool)]) return",
"if color not in self.used_colors: reward = -1 self.total_reward -= 1 self.used_colors.append(color) if",
"= 0 def get_graph(self): return self.G.copy() def step(self, action): def is_action_available(action): node, color",
"self.used_colors.append(color) if self.n not in np.unique(self.current_state): self.done = True info = {} return",
"numpy as np from gym import spaces, Env class NXColoringEnv(Env): def __init__(self, generator=nx.barabasi_albert_graph,",
"axis=1, dtype=bool)]) return ~np.any(self.current_state[adjacent_nodes]==color) reward = 0 if is_action_available(action): node, color = action",
"high=self.n-1, shape=(self.n,2), dtype=np.uint32) self.used_colors = [] self.current_state = np.full(self.n, self.n, dtype=np.uint32) self.done =",
"networkx as nx import matplotlib.pyplot as plt import numpy as np from gym",
"nx import matplotlib.pyplot as plt import numpy as np from gym import spaces,",
"len(self.G.nodes()) self.m = len(self.edges) self.action_space = spaces.Box(low=0, high=self.n-1, shape=(self.n,2), dtype=np.uint32) self.used_colors = []",
"self.current_state, reward, self.done, info def reset(self): self.used_colors = [] self.current_state = np.full(self.n, self.n,",
"**kwargs): ''' generator — netwokrx graph generator, kwargs — generator named arguments '''",
"from gym import spaces, Env class NXColoringEnv(Env): def __init__(self, generator=nx.barabasi_albert_graph, **kwargs): ''' generator",
"— generator named arguments ''' self.G = generator(**kwargs) self.pos = nx.spring_layout(self.G, iterations=1000) #determine",
"— netwokrx graph generator, kwargs — generator named arguments ''' self.G = generator(**kwargs)",
"0 def get_graph(self): return self.G.copy() def step(self, action): def is_action_available(action): node, color =",
"def get_graph(self): return self.G.copy() def step(self, action): def is_action_available(action): node, color = action",
"= [] self.current_state = np.full(self.n, self.n, dtype=np.uint32) self.done = False self.total_reward = 0",
"np.array(self.G.edges()) self.n = len(self.G.nodes()) self.m = len(self.edges) self.action_space = spaces.Box(low=0, high=self.n-1, shape=(self.n,2), dtype=np.uint32)",
"shape=(self.n,2), dtype=np.uint32) self.used_colors = [] self.current_state = np.full(self.n, self.n, dtype=np.uint32) self.done = False",
"graph generator, kwargs — generator named arguments ''' self.G = generator(**kwargs) self.pos =",
"import numpy as np from gym import spaces, Env class NXColoringEnv(Env): def __init__(self,",
"= False self.total_reward = 0 def get_graph(self): return self.G.copy() def step(self, action): def",
"plt import numpy as np from gym import spaces, Env class NXColoringEnv(Env): def",
"self.current_state = np.full(self.n, self.n, dtype=np.uint32) self.done = False self.total_reward = 0 def render(self,",
"adjacent_nodes = np.unique(self.edges[np.sum(np.isin(self.edges, node), axis=1, dtype=bool)]) return ~np.any(self.current_state[adjacent_nodes]==color) reward = 0 if is_action_available(action):",
"netwokrx graph generator, kwargs — generator named arguments ''' self.G = generator(**kwargs) self.pos",
"-1 self.total_reward -= 1 self.used_colors.append(color) if self.n not in np.unique(self.current_state): self.done = True",
"if self.n not in np.unique(self.current_state): self.done = True info = {} return self.current_state,",
"spaces.Box(low=0, high=self.n-1, shape=(self.n,2), dtype=np.uint32) self.used_colors = [] self.current_state = np.full(self.n, self.n, dtype=np.uint32) self.done",
"~np.any(self.current_state[adjacent_nodes]==color) reward = 0 if is_action_available(action): node, color = action self.current_state[node] = color",
"dtype=np.uint32) self.done = False self.total_reward = 0 def get_graph(self): return self.G.copy() def step(self,",
"1 self.used_colors.append(color) if self.n not in np.unique(self.current_state): self.done = True info = {}",
"0 if is_action_available(action): node, color = action self.current_state[node] = color if color not",
"= {} return self.current_state, reward, self.done, info def reset(self): self.used_colors = [] self.current_state",
"self.n not in np.unique(self.current_state): self.done = True info = {} return self.current_state, reward,",
"dtype=bool)]) return ~np.any(self.current_state[adjacent_nodes]==color) reward = 0 if is_action_available(action): node, color = action self.current_state[node]",
"color = action adjacent_nodes = np.unique(self.edges[np.sum(np.isin(self.edges, node), axis=1, dtype=bool)]) return ~np.any(self.current_state[adjacent_nodes]==color) reward =",
"self.done = False self.total_reward = 0 def render(self, mode='human', close=False): nx.draw(self.G, self.pos, node_color=self.current_state,",
"def step(self, action): def is_action_available(action): node, color = action adjacent_nodes = np.unique(self.edges[np.sum(np.isin(self.edges, node),",
"self.pos = nx.spring_layout(self.G, iterations=1000) #determine by n and m (?) self.edges = np.array(self.G.edges())",
"self.done = False self.total_reward = 0 def get_graph(self): return self.G.copy() def step(self, action):",
"self.done, info def reset(self): self.used_colors = [] self.current_state = np.full(self.n, self.n, dtype=np.uint32) self.done",
"= len(self.edges) self.action_space = spaces.Box(low=0, high=self.n-1, shape=(self.n,2), dtype=np.uint32) self.used_colors = [] self.current_state =",
"= nx.spring_layout(self.G, iterations=1000) #determine by n and m (?) self.edges = np.array(self.G.edges()) self.n",
"arguments ''' self.G = generator(**kwargs) self.pos = nx.spring_layout(self.G, iterations=1000) #determine by n and",
"reward, self.done, info def reset(self): self.used_colors = [] self.current_state = np.full(self.n, self.n, dtype=np.uint32)",
"self.current_state = np.full(self.n, self.n, dtype=np.uint32) self.done = False self.total_reward = 0 def get_graph(self):",
"not in np.unique(self.current_state): self.done = True info = {} return self.current_state, reward, self.done,",
"import matplotlib.pyplot as plt import numpy as np from gym import spaces, Env",
"action adjacent_nodes = np.unique(self.edges[np.sum(np.isin(self.edges, node), axis=1, dtype=bool)]) return ~np.any(self.current_state[adjacent_nodes]==color) reward = 0 if",
"= False self.total_reward = 0 def render(self, mode='human', close=False): nx.draw(self.G, self.pos, node_color=self.current_state, cmap=plt.cm.tab20)",
"= 0 if is_action_available(action): node, color = action self.current_state[node] = color if color",
"generator(**kwargs) self.pos = nx.spring_layout(self.G, iterations=1000) #determine by n and m (?) self.edges =",
"and m (?) self.edges = np.array(self.G.edges()) self.n = len(self.G.nodes()) self.m = len(self.edges) self.action_space",
"return ~np.any(self.current_state[adjacent_nodes]==color) reward = 0 if is_action_available(action): node, color = action self.current_state[node] =",
"len(self.edges) self.action_space = spaces.Box(low=0, high=self.n-1, shape=(self.n,2), dtype=np.uint32) self.used_colors = [] self.current_state = np.full(self.n,",
"is_action_available(action): node, color = action self.current_state[node] = color if color not in self.used_colors:",
"step(self, action): def is_action_available(action): node, color = action adjacent_nodes = np.unique(self.edges[np.sum(np.isin(self.edges, node), axis=1,",
"__init__(self, generator=nx.barabasi_albert_graph, **kwargs): ''' generator — netwokrx graph generator, kwargs — generator named",
"np.unique(self.current_state): self.done = True info = {} return self.current_state, reward, self.done, info def",
"= True info = {} return self.current_state, reward, self.done, info def reset(self): self.used_colors",
"nx.spring_layout(self.G, iterations=1000) #determine by n and m (?) self.edges = np.array(self.G.edges()) self.n =",
"np.unique(self.edges[np.sum(np.isin(self.edges, node), axis=1, dtype=bool)]) return ~np.any(self.current_state[adjacent_nodes]==color) reward = 0 if is_action_available(action): node, color",
"if is_action_available(action): node, color = action self.current_state[node] = color if color not in",
"as nx import matplotlib.pyplot as plt import numpy as np from gym import",
"matplotlib.pyplot as plt import numpy as np from gym import spaces, Env class",
"self.total_reward = 0 def get_graph(self): return self.G.copy() def step(self, action): def is_action_available(action): node,",
"node, color = action self.current_state[node] = color if color not in self.used_colors: reward",
"node), axis=1, dtype=bool)]) return ~np.any(self.current_state[adjacent_nodes]==color) reward = 0 if is_action_available(action): node, color =",
"= np.array(self.G.edges()) self.n = len(self.G.nodes()) self.m = len(self.edges) self.action_space = spaces.Box(low=0, high=self.n-1, shape=(self.n,2),",
"generator=nx.barabasi_albert_graph, **kwargs): ''' generator — netwokrx graph generator, kwargs — generator named arguments",
"np from gym import spaces, Env class NXColoringEnv(Env): def __init__(self, generator=nx.barabasi_albert_graph, **kwargs): '''",
"NXColoringEnv(Env): def __init__(self, generator=nx.barabasi_albert_graph, **kwargs): ''' generator — netwokrx graph generator, kwargs —",
"color not in self.used_colors: reward = -1 self.total_reward -= 1 self.used_colors.append(color) if self.n",
"self.n, dtype=np.uint32) self.done = False self.total_reward = 0 def render(self, mode='human', close=False): nx.draw(self.G,",
"np.full(self.n, self.n, dtype=np.uint32) self.done = False self.total_reward = 0 def get_graph(self): return self.G.copy()",
"action self.current_state[node] = color if color not in self.used_colors: reward = -1 self.total_reward",
"return self.G.copy() def step(self, action): def is_action_available(action): node, color = action adjacent_nodes =",
"self.m = len(self.edges) self.action_space = spaces.Box(low=0, high=self.n-1, shape=(self.n,2), dtype=np.uint32) self.used_colors = [] self.current_state",
"self.G.copy() def step(self, action): def is_action_available(action): node, color = action adjacent_nodes = np.unique(self.edges[np.sum(np.isin(self.edges,",
"False self.total_reward = 0 def get_graph(self): return self.G.copy() def step(self, action): def is_action_available(action):",
"= action adjacent_nodes = np.unique(self.edges[np.sum(np.isin(self.edges, node), axis=1, dtype=bool)]) return ~np.any(self.current_state[adjacent_nodes]==color) reward = 0",
"def __init__(self, generator=nx.barabasi_albert_graph, **kwargs): ''' generator — netwokrx graph generator, kwargs — generator",
"color = action self.current_state[node] = color if color not in self.used_colors: reward =",
"iterations=1000) #determine by n and m (?) self.edges = np.array(self.G.edges()) self.n = len(self.G.nodes())",
"by n and m (?) self.edges = np.array(self.G.edges()) self.n = len(self.G.nodes()) self.m =",
"self.n, dtype=np.uint32) self.done = False self.total_reward = 0 def get_graph(self): return self.G.copy() def",
"as plt import numpy as np from gym import spaces, Env class NXColoringEnv(Env):",
"kwargs — generator named arguments ''' self.G = generator(**kwargs) self.pos = nx.spring_layout(self.G, iterations=1000)",
"''' generator — netwokrx graph generator, kwargs — generator named arguments ''' self.G",
"in np.unique(self.current_state): self.done = True info = {} return self.current_state, reward, self.done, info",
"n and m (?) self.edges = np.array(self.G.edges()) self.n = len(self.G.nodes()) self.m = len(self.edges)",
"color if color not in self.used_colors: reward = -1 self.total_reward -= 1 self.used_colors.append(color)",
"= generator(**kwargs) self.pos = nx.spring_layout(self.G, iterations=1000) #determine by n and m (?) self.edges",
"self.action_space = spaces.Box(low=0, high=self.n-1, shape=(self.n,2), dtype=np.uint32) self.used_colors = [] self.current_state = np.full(self.n, self.n,",
"self.current_state[node] = color if color not in self.used_colors: reward = -1 self.total_reward -=",
"= color if color not in self.used_colors: reward = -1 self.total_reward -= 1",
"spaces, Env class NXColoringEnv(Env): def __init__(self, generator=nx.barabasi_albert_graph, **kwargs): ''' generator — netwokrx graph",
"m (?) self.edges = np.array(self.G.edges()) self.n = len(self.G.nodes()) self.m = len(self.edges) self.action_space =",
"generator named arguments ''' self.G = generator(**kwargs) self.pos = nx.spring_layout(self.G, iterations=1000) #determine by",
"Env class NXColoringEnv(Env): def __init__(self, generator=nx.barabasi_albert_graph, **kwargs): ''' generator — netwokrx graph generator,",
"= len(self.G.nodes()) self.m = len(self.edges) self.action_space = spaces.Box(low=0, high=self.n-1, shape=(self.n,2), dtype=np.uint32) self.used_colors =",
"in self.used_colors: reward = -1 self.total_reward -= 1 self.used_colors.append(color) if self.n not in",
"self.done = True info = {} return self.current_state, reward, self.done, info def reset(self):",
"self.G = generator(**kwargs) self.pos = nx.spring_layout(self.G, iterations=1000) #determine by n and m (?)",
"dtype=np.uint32) self.done = False self.total_reward = 0 def render(self, mode='human', close=False): nx.draw(self.G, self.pos,",
"generator, kwargs — generator named arguments ''' self.G = generator(**kwargs) self.pos = nx.spring_layout(self.G,",
"''' self.G = generator(**kwargs) self.pos = nx.spring_layout(self.G, iterations=1000) #determine by n and m",
"gym import spaces, Env class NXColoringEnv(Env): def __init__(self, generator=nx.barabasi_albert_graph, **kwargs): ''' generator —",
"return self.current_state, reward, self.done, info def reset(self): self.used_colors = [] self.current_state = np.full(self.n,",
"named arguments ''' self.G = generator(**kwargs) self.pos = nx.spring_layout(self.G, iterations=1000) #determine by n",
"not in self.used_colors: reward = -1 self.total_reward -= 1 self.used_colors.append(color) if self.n not",
"info def reset(self): self.used_colors = [] self.current_state = np.full(self.n, self.n, dtype=np.uint32) self.done =",
"reset(self): self.used_colors = [] self.current_state = np.full(self.n, self.n, dtype=np.uint32) self.done = False self.total_reward",
"as np from gym import spaces, Env class NXColoringEnv(Env): def __init__(self, generator=nx.barabasi_albert_graph, **kwargs):",
"[] self.current_state = np.full(self.n, self.n, dtype=np.uint32) self.done = False self.total_reward = 0 def",
"= action self.current_state[node] = color if color not in self.used_colors: reward = -1",
"get_graph(self): return self.G.copy() def step(self, action): def is_action_available(action): node, color = action adjacent_nodes",
"class NXColoringEnv(Env): def __init__(self, generator=nx.barabasi_albert_graph, **kwargs): ''' generator — netwokrx graph generator, kwargs",
"node, color = action adjacent_nodes = np.unique(self.edges[np.sum(np.isin(self.edges, node), axis=1, dtype=bool)]) return ~np.any(self.current_state[adjacent_nodes]==color) reward",
"= np.full(self.n, self.n, dtype=np.uint32) self.done = False self.total_reward = 0 def render(self, mode='human',",
"= spaces.Box(low=0, high=self.n-1, shape=(self.n,2), dtype=np.uint32) self.used_colors = [] self.current_state = np.full(self.n, self.n, dtype=np.uint32)",
"{} return self.current_state, reward, self.done, info def reset(self): self.used_colors = [] self.current_state =",
"def reset(self): self.used_colors = [] self.current_state = np.full(self.n, self.n, dtype=np.uint32) self.done = False",
"self.used_colors: reward = -1 self.total_reward -= 1 self.used_colors.append(color) if self.n not in np.unique(self.current_state):",
"self.n = len(self.G.nodes()) self.m = len(self.edges) self.action_space = spaces.Box(low=0, high=self.n-1, shape=(self.n,2), dtype=np.uint32) self.used_colors",
"import networkx as nx import matplotlib.pyplot as plt import numpy as np from",
"self.total_reward -= 1 self.used_colors.append(color) if self.n not in np.unique(self.current_state): self.done = True info",
"info = {} return self.current_state, reward, self.done, info def reset(self): self.used_colors = []",
"(?) self.edges = np.array(self.G.edges()) self.n = len(self.G.nodes()) self.m = len(self.edges) self.action_space = spaces.Box(low=0,",
"= np.unique(self.edges[np.sum(np.isin(self.edges, node), axis=1, dtype=bool)]) return ~np.any(self.current_state[adjacent_nodes]==color) reward = 0 if is_action_available(action): node,",
"reward = 0 if is_action_available(action): node, color = action self.current_state[node] = color if",
"= np.full(self.n, self.n, dtype=np.uint32) self.done = False self.total_reward = 0 def get_graph(self): return"
] |
[
"works universally def __getattr__(self, name): # Environment variables intentionally override config file. if",
"(value := self.value_from_env(name)) is not None: return value if (value := self.value_from_config(name)) is",
":= self.value_from_defaults(name)) is not None: return value self.raise_error(name) def get_defaults_template(self): deployment_stage = os.getenv(\"DEPLOYMENT_STAGE\",",
"None: return value if (value := self.value_from_defaults(name)) is not None: return value self.raise_error(name)",
"*args, **kwargs): super().__init__(\"backend\", secret_name=\"wmg_config\", **kwargs) # TODO: promote this impl to parent class,",
"**kwargs) # TODO: promote this impl to parent class, if new behavior works",
"self.load() if (value := self.value_from_env(name)) is not None: return value if (value :=",
"return value if (value := self.value_from_config(name)) is not None: return value if (value",
"self.value_from_config(name)) is not None: return value if (value := self.value_from_defaults(name)) is not None:",
"self.raise_error(name) def get_defaults_template(self): deployment_stage = os.getenv(\"DEPLOYMENT_STAGE\", \"test\") defaults_template = {\"bucket\": f\"wmg-{deployment_stage}\", \"data_path_prefix\": \"\",",
"get_defaults_template(self): deployment_stage = os.getenv(\"DEPLOYMENT_STAGE\", \"test\") defaults_template = {\"bucket\": f\"wmg-{deployment_stage}\", \"data_path_prefix\": \"\", \"tiledb_config_overrides\": {}}",
"is not None: return value if (value := self.value_from_defaults(name)) is not None: return",
"name): # Environment variables intentionally override config file. if not self.config_is_loaded(): self.load() if",
"__getattr__(self, name): # Environment variables intentionally override config file. if not self.config_is_loaded(): self.load()",
"if not self.config_is_loaded(): self.load() if (value := self.value_from_env(name)) is not None: return value",
"file. if not self.config_is_loaded(): self.load() if (value := self.value_from_env(name)) is not None: return",
"import SecretConfig class WmgConfig(SecretConfig): def __init__(self, *args, **kwargs): super().__init__(\"backend\", secret_name=\"wmg_config\", **kwargs) # TODO:",
"if (value := self.value_from_defaults(name)) is not None: return value self.raise_error(name) def get_defaults_template(self): deployment_stage",
"self.value_from_defaults(name)) is not None: return value self.raise_error(name) def get_defaults_template(self): deployment_stage = os.getenv(\"DEPLOYMENT_STAGE\", \"test\")",
"if new behavior works universally def __getattr__(self, name): # Environment variables intentionally override",
"variables intentionally override config file. if not self.config_is_loaded(): self.load() if (value := self.value_from_env(name))",
"self.config_is_loaded(): self.load() if (value := self.value_from_env(name)) is not None: return value if (value",
"# Environment variables intentionally override config file. if not self.config_is_loaded(): self.load() if (value",
"None: return value self.raise_error(name) def get_defaults_template(self): deployment_stage = os.getenv(\"DEPLOYMENT_STAGE\", \"test\") defaults_template = {\"bucket\":",
"**kwargs): super().__init__(\"backend\", secret_name=\"wmg_config\", **kwargs) # TODO: promote this impl to parent class, if",
"universally def __getattr__(self, name): # Environment variables intentionally override config file. if not",
"override config file. if not self.config_is_loaded(): self.load() if (value := self.value_from_env(name)) is not",
"from backend.corpora.common.utils.secret_config import SecretConfig class WmgConfig(SecretConfig): def __init__(self, *args, **kwargs): super().__init__(\"backend\", secret_name=\"wmg_config\", **kwargs)",
"__init__(self, *args, **kwargs): super().__init__(\"backend\", secret_name=\"wmg_config\", **kwargs) # TODO: promote this impl to parent",
"not None: return value if (value := self.value_from_config(name)) is not None: return value",
"not None: return value if (value := self.value_from_defaults(name)) is not None: return value",
"value self.raise_error(name) def get_defaults_template(self): deployment_stage = os.getenv(\"DEPLOYMENT_STAGE\", \"test\") defaults_template = {\"bucket\": f\"wmg-{deployment_stage}\", \"data_path_prefix\":",
"import os from backend.corpora.common.utils.secret_config import SecretConfig class WmgConfig(SecretConfig): def __init__(self, *args, **kwargs): super().__init__(\"backend\",",
"is not None: return value if (value := self.value_from_config(name)) is not None: return",
"TODO: promote this impl to parent class, if new behavior works universally def",
"not None: return value self.raise_error(name) def get_defaults_template(self): deployment_stage = os.getenv(\"DEPLOYMENT_STAGE\", \"test\") defaults_template =",
"os from backend.corpora.common.utils.secret_config import SecretConfig class WmgConfig(SecretConfig): def __init__(self, *args, **kwargs): super().__init__(\"backend\", secret_name=\"wmg_config\",",
"promote this impl to parent class, if new behavior works universally def __getattr__(self,",
"def __init__(self, *args, **kwargs): super().__init__(\"backend\", secret_name=\"wmg_config\", **kwargs) # TODO: promote this impl to",
"this impl to parent class, if new behavior works universally def __getattr__(self, name):",
"if (value := self.value_from_env(name)) is not None: return value if (value := self.value_from_config(name))",
"parent class, if new behavior works universally def __getattr__(self, name): # Environment variables",
"def __getattr__(self, name): # Environment variables intentionally override config file. if not self.config_is_loaded():",
"# TODO: promote this impl to parent class, if new behavior works universally",
"intentionally override config file. if not self.config_is_loaded(): self.load() if (value := self.value_from_env(name)) is",
"if (value := self.value_from_config(name)) is not None: return value if (value := self.value_from_defaults(name))",
"return value if (value := self.value_from_defaults(name)) is not None: return value self.raise_error(name) def",
"value if (value := self.value_from_defaults(name)) is not None: return value self.raise_error(name) def get_defaults_template(self):",
"value if (value := self.value_from_config(name)) is not None: return value if (value :=",
"def get_defaults_template(self): deployment_stage = os.getenv(\"DEPLOYMENT_STAGE\", \"test\") defaults_template = {\"bucket\": f\"wmg-{deployment_stage}\", \"data_path_prefix\": \"\", \"tiledb_config_overrides\":",
"new behavior works universally def __getattr__(self, name): # Environment variables intentionally override config",
"Environment variables intentionally override config file. if not self.config_is_loaded(): self.load() if (value :=",
"behavior works universally def __getattr__(self, name): # Environment variables intentionally override config file.",
"not self.config_is_loaded(): self.load() if (value := self.value_from_env(name)) is not None: return value if",
"class WmgConfig(SecretConfig): def __init__(self, *args, **kwargs): super().__init__(\"backend\", secret_name=\"wmg_config\", **kwargs) # TODO: promote this",
"is not None: return value self.raise_error(name) def get_defaults_template(self): deployment_stage = os.getenv(\"DEPLOYMENT_STAGE\", \"test\") defaults_template",
"SecretConfig class WmgConfig(SecretConfig): def __init__(self, *args, **kwargs): super().__init__(\"backend\", secret_name=\"wmg_config\", **kwargs) # TODO: promote",
"None: return value if (value := self.value_from_config(name)) is not None: return value if",
"impl to parent class, if new behavior works universally def __getattr__(self, name): #",
"(value := self.value_from_config(name)) is not None: return value if (value := self.value_from_defaults(name)) is",
"(value := self.value_from_defaults(name)) is not None: return value self.raise_error(name) def get_defaults_template(self): deployment_stage =",
"= os.getenv(\"DEPLOYMENT_STAGE\", \"test\") defaults_template = {\"bucket\": f\"wmg-{deployment_stage}\", \"data_path_prefix\": \"\", \"tiledb_config_overrides\": {}} return defaults_template",
"return value self.raise_error(name) def get_defaults_template(self): deployment_stage = os.getenv(\"DEPLOYMENT_STAGE\", \"test\") defaults_template = {\"bucket\": f\"wmg-{deployment_stage}\",",
":= self.value_from_config(name)) is not None: return value if (value := self.value_from_defaults(name)) is not",
"deployment_stage = os.getenv(\"DEPLOYMENT_STAGE\", \"test\") defaults_template = {\"bucket\": f\"wmg-{deployment_stage}\", \"data_path_prefix\": \"\", \"tiledb_config_overrides\": {}} return",
"secret_name=\"wmg_config\", **kwargs) # TODO: promote this impl to parent class, if new behavior",
"config file. if not self.config_is_loaded(): self.load() if (value := self.value_from_env(name)) is not None:",
"WmgConfig(SecretConfig): def __init__(self, *args, **kwargs): super().__init__(\"backend\", secret_name=\"wmg_config\", **kwargs) # TODO: promote this impl",
"super().__init__(\"backend\", secret_name=\"wmg_config\", **kwargs) # TODO: promote this impl to parent class, if new",
"to parent class, if new behavior works universally def __getattr__(self, name): # Environment",
":= self.value_from_env(name)) is not None: return value if (value := self.value_from_config(name)) is not",
"backend.corpora.common.utils.secret_config import SecretConfig class WmgConfig(SecretConfig): def __init__(self, *args, **kwargs): super().__init__(\"backend\", secret_name=\"wmg_config\", **kwargs) #",
"class, if new behavior works universally def __getattr__(self, name): # Environment variables intentionally",
"self.value_from_env(name)) is not None: return value if (value := self.value_from_config(name)) is not None:"
] |
[
"lname\") contacts = [ Contact(\"Lex\", \"Luther\"), Contact(\"Firestorm\", \"Lobo\"), Contact(\"Green\", \"Lantern\"), Contact(\"Aquaman\", None), Contact(None,",
"In effect, the presentation bias makes the contacts in the on-screen phone book",
"return sorted(contacts, key=lambda c: coalesce(c.fname, \"\")) def sort_by_last_name(contacts): \"\"\"Returns a sorted sequence of",
"the first name isn't present, the last name is used instead \"\"\" return",
"The following code explores the presentation of contacts in an on-screen phone book",
"may betray visual expectation. See the outputs of the sorts by last name.",
"Contact(\"Aquaman\", None), Contact(None, \"Diner\"), Contact(None, \"Metropolis\"), ] def coalesce(*values): \"\"\"Returns the first not-None",
"first not-None arguement or None\"\"\" return next((v for v in values if v",
"arguement or None\"\"\" return next((v for v in values if v is not",
"to sort by last name, but if the last name isn't present, the",
"makes the contacts in the on-screen phone book appear to be sorted by",
"a presentation bias. Truly sorts by first name \"\"\" return sorted(contacts, key=lambda c:",
"name \"\"\" return sorted(contacts, key=lambda c: coalesce(c.fname, \"\")) def sort_by_last_name(contacts): \"\"\"Returns a sorted",
"contacts are displayed, there is no visual consequence in the case of contacts",
"within expectation while a true sort may betray visual expectation. See the outputs",
"the presentation of contacts in an on-screen phone book in which a contact's",
"phone book in which a contact's first name xor last name may be",
"sort by last name, but if the last name isn't present, the first",
"display_contacts(sort_by_first_name(contacts)) print() print(\"Sort by First Name (with presentation bias)\") display_contacts(presentation_sort_by_first_name(contacts)) print() print(\"True Sort",
"last name, but if the last name isn't present, the first name is",
"name, but if the last name isn't present, the first name is used",
"contacts = [ Contact(\"Lex\", \"Luther\"), Contact(\"Firestorm\", \"Lobo\"), Contact(\"Green\", \"Lantern\"), Contact(\"Aquaman\", None), Contact(None, \"Diner\"),",
"sort is visually within expectation while a true sort may betray visual expectation.",
"name xor last name. A presentation-biased sort may be preferable to a true",
"bias. Tries to sort by first name, but if the first name isn't",
"sort as the presentation-biased sort is visually within expectation while a true sort",
"sorted sequence of contacts with a presentation bias. Truly sorts by first name",
"if v is not None), None) def display_contacts(contacts): \"\"\"Displays contacts\"\"\" for contact in",
"Contact(\"Lex\", \"Luther\"), Contact(\"Firestorm\", \"Lobo\"), Contact(\"Green\", \"Lantern\"), Contact(\"Aquaman\", None), Contact(None, \"Diner\"), Contact(None, \"Metropolis\"), ]",
"values if v is not None), None) def display_contacts(contacts): \"\"\"Displays contacts\"\"\" for contact",
"is implemented as well as correspending sort procedures with a presentation bias. In",
"Contact(None, \"Diner\"), Contact(None, \"Metropolis\"), ] def coalesce(*values): \"\"\"Returns the first not-None arguement or",
"is used instead \"\"\" return sorted(contacts, key=lambda c: coalesce(c.lname, c.fname)) def sort_by_first_name(contacts): \"\"\"Returns",
"true sort as the presentation-biased sort is visually within expectation while a true",
"by First Name (with presentation bias)\") display_contacts(presentation_sort_by_first_name(contacts)) print() print(\"True Sort by Last Name\")",
"as well as correspending sort procedures with a presentation bias. In effect, the",
"coalesce(*values): \"\"\"Returns the first not-None arguement or None\"\"\" return next((v for v in",
"\"\"\"Returns the first not-None arguement or None\"\"\" return next((v for v in values",
"or '')}\".strip()) def presentation_sort_by_first_name(contacts): \"\"\"Returns a sorted sequence of contacts with a presentation",
"coalesce(c.fname, \"\")) def sort_by_last_name(contacts): \"\"\"Returns a sorted sequence of contacts with a presentation",
"sort_by_last_name(contacts): \"\"\"Returns a sorted sequence of contacts with a presentation bias. Truly sorts",
"First Name (with presentation bias)\") display_contacts(presentation_sort_by_first_name(contacts)) print() print(\"True Sort by Last Name\") display_contacts(sort_by_last_name(contacts))",
"Name (with presentation bias)\") display_contacts(presentation_sort_by_first_name(contacts)) print() print(\"True Sort by Last Name\") display_contacts(sort_by_last_name(contacts)) print()",
"in values if v is not None), None) def display_contacts(contacts): \"\"\"Displays contacts\"\"\" for",
"sorted by first name xor last name. A true sort by first name",
"However, because of how the contacts are displayed, there is no visual consequence",
"not None), None) def display_contacts(contacts): \"\"\"Displays contacts\"\"\" for contact in contacts: print(f\"{(contact.fname or",
"this may not be true. However, because of how the contacts are displayed,",
"sorted sequence of contacts with a presentation bias. Truly sorts by last name",
"visual expectation. See the outputs of the sorts by last name. \"\"\" from",
"with a presentation bias. Truly sorts by last name \"\"\" return sorted(contacts, key=lambda",
"of contacts with a presentation bias. Tries to sort by first name, but",
"sequence of contacts with a presentation bias. Truly sorts by last name \"\"\"",
"outputs of the sorts by last name. \"\"\" from collections import namedtuple Contact",
"sorted sequence of contacts with a presentation bias. Tries to sort by first",
"return sorted(contacts, key=lambda c: coalesce(c.fname, c.lname)) def presentation_sort_by_last_name(contacts): \"\"\"Returns a sorted sequence of",
"by first name, but if the first name isn't present, the last name",
"last name may be missing and contacts can be sorted by first name",
"with a presentation bias. In effect, the presentation bias makes the contacts in",
"are displayed, there is no visual consequence in the case of contacts that",
"A presentation-biased sort may be preferable to a true sort as the presentation-biased",
"be true. However, because of how the contacts are displayed, there is no",
"a true sort as the presentation-biased sort is visually within expectation while a",
"first name \"\"\" return sorted(contacts, key=lambda c: coalesce(c.fname, \"\")) def sort_by_last_name(contacts): \"\"\"Returns a",
"by last name. \"\"\" from collections import namedtuple Contact = namedtuple(\"Contact\", \"fname lname\")",
"last name. \"\"\" from collections import namedtuple Contact = namedtuple(\"Contact\", \"fname lname\") contacts",
"print(f\"{(contact.fname or '')} {(contact.lname or '')}\".strip()) def presentation_sort_by_first_name(contacts): \"\"\"Returns a sorted sequence of",
"and contacts can be sorted by first name xor last name. A true",
"procedures with a presentation bias. In effect, the presentation bias makes the contacts",
"of contacts with a presentation bias. Truly sorts by first name \"\"\" return",
"c: coalesce(c.lname, \"\")) print(\"True Sort by First Name\") display_contacts(sort_by_first_name(contacts)) print() print(\"Sort by First",
"not be true. However, because of how the contacts are displayed, there is",
"sort by first name, but if the first name isn't present, the last",
"def sort_by_first_name(contacts): \"\"\"Returns a sorted sequence of contacts with a presentation bias. Truly",
"Contact(None, \"Metropolis\"), ] def coalesce(*values): \"\"\"Returns the first not-None arguement or None\"\"\" return",
"collections import namedtuple Contact = namedtuple(\"Contact\", \"fname lname\") contacts = [ Contact(\"Lex\", \"Luther\"),",
"print(\"True Sort by Last Name\") display_contacts(sort_by_last_name(contacts)) print() print(\"Sort by Last Name (with presentation",
"by Last Name\") display_contacts(sort_by_last_name(contacts)) print() print(\"Sort by Last Name (with presentation bias)\") display_contacts(presentation_sort_by_last_name(contacts))",
"sequence of contacts with a presentation bias. Tries to sort by first name,",
"name. A true sort by first name and last name is implemented as",
"in which a contact's first name xor last name may be missing and",
"the case of contacts that are missing a first name xor last name.",
"consequence in the case of contacts that are missing a first name xor",
"name, but if the first name isn't present, the last name is used",
"missing and contacts can be sorted by first name xor last name. A",
"can be sorted by first name xor last name. A true sort by",
"a presentation bias. Tries to sort by first name, but if the first",
"first name xor last name may be missing and contacts can be sorted",
"name xor last name may be missing and contacts can be sorted by",
"by first name \"\"\" return sorted(contacts, key=lambda c: coalesce(c.fname, \"\")) def sort_by_last_name(contacts): \"\"\"Returns",
"visual consequence in the case of contacts that are missing a first name",
"presentation-biased sort may be preferable to a true sort as the presentation-biased sort",
"as the presentation-biased sort is visually within expectation while a true sort may",
"presentation_sort_by_first_name(contacts): \"\"\"Returns a sorted sequence of contacts with a presentation bias. Tries to",
"sorts by last name. \"\"\" from collections import namedtuple Contact = namedtuple(\"Contact\", \"fname",
"how the contacts are displayed, there is no visual consequence in the case",
"sorted(contacts, key=lambda c: coalesce(c.fname, c.lname)) def presentation_sort_by_last_name(contacts): \"\"\"Returns a sorted sequence of contacts",
"really this may not be true. However, because of how the contacts are",
"may not be true. However, because of how the contacts are displayed, there",
"= [ Contact(\"Lex\", \"Luther\"), Contact(\"Firestorm\", \"Lobo\"), Contact(\"Green\", \"Lantern\"), Contact(\"Aquaman\", None), Contact(None, \"Diner\"), Contact(None,",
"c: coalesce(c.fname, c.lname)) def presentation_sort_by_last_name(contacts): \"\"\"Returns a sorted sequence of contacts with a",
"is no visual consequence in the case of contacts that are missing a",
"to sort by first name, but if the first name isn't present, the",
"display_contacts(presentation_sort_by_first_name(contacts)) print() print(\"True Sort by Last Name\") display_contacts(sort_by_last_name(contacts)) print() print(\"Sort by Last Name",
"xor last name. A presentation-biased sort may be preferable to a true sort",
"their intended sort key but in really this may not be true. However,",
"\"\"\"Returns a sorted sequence of contacts with a presentation bias. Truly sorts by",
"name isn't present, the first name is used instead \"\"\" return sorted(contacts, key=lambda",
"true sort may betray visual expectation. See the outputs of the sorts by",
"because of how the contacts are displayed, there is no visual consequence in",
"<gh_stars>0 \"\"\" The following code explores the presentation of contacts in an on-screen",
"None), Contact(None, \"Diner\"), Contact(None, \"Metropolis\"), ] def coalesce(*values): \"\"\"Returns the first not-None arguement",
"coalesce(c.fname, c.lname)) def presentation_sort_by_last_name(contacts): \"\"\"Returns a sorted sequence of contacts with a presentation",
"presentation_sort_by_last_name(contacts): \"\"\"Returns a sorted sequence of contacts with a presentation bias. Tries to",
"is visually within expectation while a true sort may betray visual expectation. See",
"\"Metropolis\"), ] def coalesce(*values): \"\"\"Returns the first not-None arguement or None\"\"\" return next((v",
"sorts by last name \"\"\" return sorted(contacts, key=lambda c: coalesce(c.lname, \"\")) print(\"True Sort",
"return sorted(contacts, key=lambda c: coalesce(c.lname, \"\")) print(\"True Sort by First Name\") display_contacts(sort_by_first_name(contacts)) print()",
"contacts with a presentation bias. Tries to sort by last name, but if",
"\"\"\"Displays contacts\"\"\" for contact in contacts: print(f\"{(contact.fname or '')} {(contact.lname or '')}\".strip()) def",
"= namedtuple(\"Contact\", \"fname lname\") contacts = [ Contact(\"Lex\", \"Luther\"), Contact(\"Firestorm\", \"Lobo\"), Contact(\"Green\", \"Lantern\"),",
"first name, but if the first name isn't present, the last name is",
"the first not-None arguement or None\"\"\" return next((v for v in values if",
"print(\"Sort by First Name (with presentation bias)\") display_contacts(presentation_sort_by_first_name(contacts)) print() print(\"True Sort by Last",
"bias. Tries to sort by last name, but if the last name isn't",
"Contact = namedtuple(\"Contact\", \"fname lname\") contacts = [ Contact(\"Lex\", \"Luther\"), Contact(\"Firestorm\", \"Lobo\"), Contact(\"Green\",",
"sort_by_first_name(contacts): \"\"\"Returns a sorted sequence of contacts with a presentation bias. Truly sorts",
"Last Name\") display_contacts(sort_by_last_name(contacts)) print() print(\"Sort by Last Name (with presentation bias)\") display_contacts(presentation_sort_by_last_name(contacts)) print()",
"(with presentation bias)\") display_contacts(presentation_sort_by_first_name(contacts)) print() print(\"True Sort by Last Name\") display_contacts(sort_by_last_name(contacts)) print() print(\"Sort",
"def presentation_sort_by_last_name(contacts): \"\"\"Returns a sorted sequence of contacts with a presentation bias. Tries",
"with a presentation bias. Truly sorts by first name \"\"\" return sorted(contacts, key=lambda",
"an on-screen phone book in which a contact's first name xor last name",
"if the last name isn't present, the first name is used instead \"\"\"",
"sorted(contacts, key=lambda c: coalesce(c.lname, c.fname)) def sort_by_first_name(contacts): \"\"\"Returns a sorted sequence of contacts",
"Truly sorts by first name \"\"\" return sorted(contacts, key=lambda c: coalesce(c.fname, \"\")) def",
"code explores the presentation of contacts in an on-screen phone book in which",
"well as correspending sort procedures with a presentation bias. In effect, the presentation",
"missing a first name xor last name. A presentation-biased sort may be preferable",
"def display_contacts(contacts): \"\"\"Displays contacts\"\"\" for contact in contacts: print(f\"{(contact.fname or '')} {(contact.lname or",
"last name. A presentation-biased sort may be preferable to a true sort as",
"to a true sort as the presentation-biased sort is visually within expectation while",
"presentation-biased sort is visually within expectation while a true sort may betray visual",
"None\"\"\" return next((v for v in values if v is not None), None)",
"contact's first name xor last name may be missing and contacts can be",
"print() print(\"True Sort by Last Name\") display_contacts(sort_by_last_name(contacts)) print() print(\"Sort by Last Name (with",
"last name isn't present, the first name is used instead \"\"\" return sorted(contacts,",
"\"\"\" from collections import namedtuple Contact = namedtuple(\"Contact\", \"fname lname\") contacts = [",
"\"Lantern\"), Contact(\"Aquaman\", None), Contact(None, \"Diner\"), Contact(None, \"Metropolis\"), ] def coalesce(*values): \"\"\"Returns the first",
"book in which a contact's first name xor last name may be missing",
"return next((v for v in values if v is not None), None) def",
"name may be missing and contacts can be sorted by first name xor",
"c.fname)) def sort_by_first_name(contacts): \"\"\"Returns a sorted sequence of contacts with a presentation bias.",
"bias makes the contacts in the on-screen phone book appear to be sorted",
"the contacts are displayed, there is no visual consequence in the case of",
"betray visual expectation. See the outputs of the sorts by last name. \"\"\"",
"or '')} {(contact.lname or '')}\".strip()) def presentation_sort_by_first_name(contacts): \"\"\"Returns a sorted sequence of contacts",
"return sorted(contacts, key=lambda c: coalesce(c.lname, c.fname)) def sort_by_first_name(contacts): \"\"\"Returns a sorted sequence of",
"presentation bias makes the contacts in the on-screen phone book appear to be",
"\"\")) def sort_by_last_name(contacts): \"\"\"Returns a sorted sequence of contacts with a presentation bias.",
"sorts by first name \"\"\" return sorted(contacts, key=lambda c: coalesce(c.fname, \"\")) def sort_by_last_name(contacts):",
"of contacts that are missing a first name xor last name. A presentation-biased",
"Sort by Last Name\") display_contacts(sort_by_last_name(contacts)) print() print(\"Sort by Last Name (with presentation bias)\")",
"of contacts in an on-screen phone book in which a contact's first name",
"] def coalesce(*values): \"\"\"Returns the first not-None arguement or None\"\"\" return next((v for",
"sequence of contacts with a presentation bias. Tries to sort by last name,",
"a sorted sequence of contacts with a presentation bias. Tries to sort by",
"are missing a first name xor last name. A presentation-biased sort may be",
"a contact's first name xor last name may be missing and contacts can",
"of the sorts by last name. \"\"\" from collections import namedtuple Contact =",
"of contacts with a presentation bias. Truly sorts by last name \"\"\" return",
"bias. Truly sorts by last name \"\"\" return sorted(contacts, key=lambda c: coalesce(c.lname, \"\"))",
"contacts: print(f\"{(contact.fname or '')} {(contact.lname or '')}\".strip()) def presentation_sort_by_first_name(contacts): \"\"\"Returns a sorted sequence",
"on-screen phone book in which a contact's first name xor last name may",
"\"Diner\"), Contact(None, \"Metropolis\"), ] def coalesce(*values): \"\"\"Returns the first not-None arguement or None\"\"\"",
"bias. Truly sorts by first name \"\"\" return sorted(contacts, key=lambda c: coalesce(c.fname, \"\"))",
"is used instead \"\"\" return sorted(contacts, key=lambda c: coalesce(c.fname, c.lname)) def presentation_sort_by_last_name(contacts): \"\"\"Returns",
"while a true sort may betray visual expectation. See the outputs of the",
"if the first name isn't present, the last name is used instead \"\"\"",
"print() print(\"Sort by First Name (with presentation bias)\") display_contacts(presentation_sort_by_first_name(contacts)) print() print(\"True Sort by",
"in really this may not be true. However, because of how the contacts",
"in the on-screen phone book appear to be sorted by their intended sort",
"by last name, but if the last name isn't present, the first name",
"be sorted by first name xor last name. A true sort by first",
"\"\"\" return sorted(contacts, key=lambda c: coalesce(c.lname, \"\")) print(\"True Sort by First Name\") display_contacts(sort_by_first_name(contacts))",
"but if the last name isn't present, the first name is used instead",
"implemented as well as correspending sort procedures with a presentation bias. In effect,",
"appear to be sorted by their intended sort key but in really this",
"a first name xor last name. A presentation-biased sort may be preferable to",
"present, the last name is used instead \"\"\" return sorted(contacts, key=lambda c: coalesce(c.fname,",
"\"\")) print(\"True Sort by First Name\") display_contacts(sort_by_first_name(contacts)) print() print(\"Sort by First Name (with",
"sort key but in really this may not be true. However, because of",
"expectation while a true sort may betray visual expectation. See the outputs of",
"\"\"\" The following code explores the presentation of contacts in an on-screen phone",
"first name isn't present, the last name is used instead \"\"\" return sorted(contacts,",
"may be preferable to a true sort as the presentation-biased sort is visually",
"[ Contact(\"Lex\", \"Luther\"), Contact(\"Firestorm\", \"Lobo\"), Contact(\"Green\", \"Lantern\"), Contact(\"Aquaman\", None), Contact(None, \"Diner\"), Contact(None, \"Metropolis\"),",
"on-screen phone book appear to be sorted by their intended sort key but",
"key=lambda c: coalesce(c.lname, c.fname)) def sort_by_first_name(contacts): \"\"\"Returns a sorted sequence of contacts with",
"isn't present, the last name is used instead \"\"\" return sorted(contacts, key=lambda c:",
"presentation of contacts in an on-screen phone book in which a contact's first",
"\"\"\" return sorted(contacts, key=lambda c: coalesce(c.fname, \"\")) def sort_by_last_name(contacts): \"\"\"Returns a sorted sequence",
"last name. A true sort by first name and last name is implemented",
"the presentation bias makes the contacts in the on-screen phone book appear to",
"the presentation-biased sort is visually within expectation while a true sort may betray",
"sort procedures with a presentation bias. In effect, the presentation bias makes the",
"contacts that are missing a first name xor last name. A presentation-biased sort",
"sorted(contacts, key=lambda c: coalesce(c.lname, \"\")) print(\"True Sort by First Name\") display_contacts(sort_by_first_name(contacts)) print() print(\"Sort",
"from collections import namedtuple Contact = namedtuple(\"Contact\", \"fname lname\") contacts = [ Contact(\"Lex\",",
"in the case of contacts that are missing a first name xor last",
"true sort by first name and last name is implemented as well as",
"be missing and contacts can be sorted by first name xor last name.",
"expectation. See the outputs of the sorts by last name. \"\"\" from collections",
"and last name is implemented as well as correspending sort procedures with a",
"last name is used instead \"\"\" return sorted(contacts, key=lambda c: coalesce(c.fname, c.lname)) def",
"'')} {(contact.lname or '')}\".strip()) def presentation_sort_by_first_name(contacts): \"\"\"Returns a sorted sequence of contacts with",
"instead \"\"\" return sorted(contacts, key=lambda c: coalesce(c.fname, c.lname)) def presentation_sort_by_last_name(contacts): \"\"\"Returns a sorted",
"name xor last name. A true sort by first name and last name",
"presentation bias. Truly sorts by last name \"\"\" return sorted(contacts, key=lambda c: coalesce(c.lname,",
"xor last name may be missing and contacts can be sorted by first",
"{(contact.lname or '')}\".strip()) def presentation_sort_by_first_name(contacts): \"\"\"Returns a sorted sequence of contacts with a",
"\"Luther\"), Contact(\"Firestorm\", \"Lobo\"), Contact(\"Green\", \"Lantern\"), Contact(\"Aquaman\", None), Contact(None, \"Diner\"), Contact(None, \"Metropolis\"), ] def",
"Contact(\"Firestorm\", \"Lobo\"), Contact(\"Green\", \"Lantern\"), Contact(\"Aquaman\", None), Contact(None, \"Diner\"), Contact(None, \"Metropolis\"), ] def coalesce(*values):",
"there is no visual consequence in the case of contacts that are missing",
"the contacts in the on-screen phone book appear to be sorted by their",
"with a presentation bias. Tries to sort by last name, but if the",
"namedtuple Contact = namedtuple(\"Contact\", \"fname lname\") contacts = [ Contact(\"Lex\", \"Luther\"), Contact(\"Firestorm\", \"Lobo\"),",
"not-None arguement or None\"\"\" return next((v for v in values if v is",
"c.lname)) def presentation_sort_by_last_name(contacts): \"\"\"Returns a sorted sequence of contacts with a presentation bias.",
"contact in contacts: print(f\"{(contact.fname or '')} {(contact.lname or '')}\".strip()) def presentation_sort_by_first_name(contacts): \"\"\"Returns a",
"'')}\".strip()) def presentation_sort_by_first_name(contacts): \"\"\"Returns a sorted sequence of contacts with a presentation bias.",
"by First Name\") display_contacts(sort_by_first_name(contacts)) print() print(\"Sort by First Name (with presentation bias)\") display_contacts(presentation_sort_by_first_name(contacts))",
"name is used instead \"\"\" return sorted(contacts, key=lambda c: coalesce(c.fname, c.lname)) def presentation_sort_by_last_name(contacts):",
"Truly sorts by last name \"\"\" return sorted(contacts, key=lambda c: coalesce(c.lname, \"\")) print(\"True",
"\"fname lname\") contacts = [ Contact(\"Lex\", \"Luther\"), Contact(\"Firestorm\", \"Lobo\"), Contact(\"Green\", \"Lantern\"), Contact(\"Aquaman\", None),",
"for contact in contacts: print(f\"{(contact.fname or '')} {(contact.lname or '')}\".strip()) def presentation_sort_by_first_name(contacts): \"\"\"Returns",
"explores the presentation of contacts in an on-screen phone book in which a",
"which a contact's first name xor last name may be missing and contacts",
"a true sort may betray visual expectation. See the outputs of the sorts",
"namedtuple(\"Contact\", \"fname lname\") contacts = [ Contact(\"Lex\", \"Luther\"), Contact(\"Firestorm\", \"Lobo\"), Contact(\"Green\", \"Lantern\"), Contact(\"Aquaman\",",
"\"Lobo\"), Contact(\"Green\", \"Lantern\"), Contact(\"Aquaman\", None), Contact(None, \"Diner\"), Contact(None, \"Metropolis\"), ] def coalesce(*values): \"\"\"Returns",
"first name and last name is implemented as well as correspending sort procedures",
"presentation bias. In effect, the presentation bias makes the contacts in the on-screen",
"\"\"\" return sorted(contacts, key=lambda c: coalesce(c.fname, c.lname)) def presentation_sort_by_last_name(contacts): \"\"\"Returns a sorted sequence",
"name. \"\"\" from collections import namedtuple Contact = namedtuple(\"Contact\", \"fname lname\") contacts =",
"presentation bias. Tries to sort by last name, but if the last name",
"See the outputs of the sorts by last name. \"\"\" from collections import",
"\"\"\" return sorted(contacts, key=lambda c: coalesce(c.lname, c.fname)) def sort_by_first_name(contacts): \"\"\"Returns a sorted sequence",
"to be sorted by their intended sort key but in really this may",
"bias)\") display_contacts(presentation_sort_by_first_name(contacts)) print() print(\"True Sort by Last Name\") display_contacts(sort_by_last_name(contacts)) print() print(\"Sort by Last",
"the last name is used instead \"\"\" return sorted(contacts, key=lambda c: coalesce(c.fname, c.lname))",
"key=lambda c: coalesce(c.fname, \"\")) def sort_by_last_name(contacts): \"\"\"Returns a sorted sequence of contacts with",
"contacts\"\"\" for contact in contacts: print(f\"{(contact.fname or '')} {(contact.lname or '')}\".strip()) def presentation_sort_by_first_name(contacts):",
"None), None) def display_contacts(contacts): \"\"\"Displays contacts\"\"\" for contact in contacts: print(f\"{(contact.fname or '')}",
"visually within expectation while a true sort may betray visual expectation. See the",
"the last name isn't present, the first name is used instead \"\"\" return",
"a sorted sequence of contacts with a presentation bias. Truly sorts by last",
"as correspending sort procedures with a presentation bias. In effect, the presentation bias",
"last name \"\"\" return sorted(contacts, key=lambda c: coalesce(c.lname, \"\")) print(\"True Sort by First",
"intended sort key but in really this may not be true. However, because",
"sequence of contacts with a presentation bias. Truly sorts by first name \"\"\"",
"is not None), None) def display_contacts(contacts): \"\"\"Displays contacts\"\"\" for contact in contacts: print(f\"{(contact.fname",
"presentation bias. Truly sorts by first name \"\"\" return sorted(contacts, key=lambda c: coalesce(c.fname,",
"phone book appear to be sorted by their intended sort key but in",
"with a presentation bias. Tries to sort by first name, but if the",
"for v in values if v is not None), None) def display_contacts(contacts): \"\"\"Displays",
"instead \"\"\" return sorted(contacts, key=lambda c: coalesce(c.lname, c.fname)) def sort_by_first_name(contacts): \"\"\"Returns a sorted",
"case of contacts that are missing a first name xor last name. A",
"sorted by their intended sort key but in really this may not be",
"by first name and last name is implemented as well as correspending sort",
"\"\"\"Returns a sorted sequence of contacts with a presentation bias. Tries to sort",
"coalesce(c.lname, c.fname)) def sort_by_first_name(contacts): \"\"\"Returns a sorted sequence of contacts with a presentation",
"the sorts by last name. \"\"\" from collections import namedtuple Contact = namedtuple(\"Contact\",",
"key=lambda c: coalesce(c.lname, \"\")) print(\"True Sort by First Name\") display_contacts(sort_by_first_name(contacts)) print() print(\"Sort by",
"name \"\"\" return sorted(contacts, key=lambda c: coalesce(c.lname, \"\")) print(\"True Sort by First Name\")",
"a presentation bias. Truly sorts by last name \"\"\" return sorted(contacts, key=lambda c:",
"sort may be preferable to a true sort as the presentation-biased sort is",
"def sort_by_last_name(contacts): \"\"\"Returns a sorted sequence of contacts with a presentation bias. Truly",
"import namedtuple Contact = namedtuple(\"Contact\", \"fname lname\") contacts = [ Contact(\"Lex\", \"Luther\"), Contact(\"Firestorm\",",
"first name is used instead \"\"\" return sorted(contacts, key=lambda c: coalesce(c.lname, c.fname)) def",
"book appear to be sorted by their intended sort key but in really",
"may be missing and contacts can be sorted by first name xor last",
"sort may betray visual expectation. See the outputs of the sorts by last",
"first name xor last name. A true sort by first name and last",
"contacts with a presentation bias. Truly sorts by first name \"\"\" return sorted(contacts,",
"First Name\") display_contacts(sort_by_first_name(contacts)) print() print(\"Sort by First Name (with presentation bias)\") display_contacts(presentation_sort_by_first_name(contacts)) print()",
"A true sort by first name and last name is implemented as well",
"effect, the presentation bias makes the contacts in the on-screen phone book appear",
"the outputs of the sorts by last name. \"\"\" from collections import namedtuple",
"a presentation bias. Tries to sort by last name, but if the last",
"def presentation_sort_by_first_name(contacts): \"\"\"Returns a sorted sequence of contacts with a presentation bias. Tries",
"name isn't present, the last name is used instead \"\"\" return sorted(contacts, key=lambda",
"true. However, because of how the contacts are displayed, there is no visual",
"used instead \"\"\" return sorted(contacts, key=lambda c: coalesce(c.lname, c.fname)) def sort_by_first_name(contacts): \"\"\"Returns a",
"c: coalesce(c.fname, \"\")) def sort_by_last_name(contacts): \"\"\"Returns a sorted sequence of contacts with a",
"key but in really this may not be true. However, because of how",
"Tries to sort by first name, but if the first name isn't present,",
"bias. In effect, the presentation bias makes the contacts in the on-screen phone",
"contacts in the on-screen phone book appear to be sorted by their intended",
"sorted(contacts, key=lambda c: coalesce(c.fname, \"\")) def sort_by_last_name(contacts): \"\"\"Returns a sorted sequence of contacts",
"no visual consequence in the case of contacts that are missing a first",
"def coalesce(*values): \"\"\"Returns the first not-None arguement or None\"\"\" return next((v for v",
"name and last name is implemented as well as correspending sort procedures with",
"contacts with a presentation bias. Tries to sort by first name, but if",
"the on-screen phone book appear to be sorted by their intended sort key",
"coalesce(c.lname, \"\")) print(\"True Sort by First Name\") display_contacts(sort_by_first_name(contacts)) print() print(\"Sort by First Name",
"presentation bias. Tries to sort by first name, but if the first name",
"by last name \"\"\" return sorted(contacts, key=lambda c: coalesce(c.lname, \"\")) print(\"True Sort by",
"Sort by First Name\") display_contacts(sort_by_first_name(contacts)) print() print(\"Sort by First Name (with presentation bias)\")",
"isn't present, the first name is used instead \"\"\" return sorted(contacts, key=lambda c:",
"in an on-screen phone book in which a contact's first name xor last",
"by first name xor last name. A true sort by first name and",
"name is implemented as well as correspending sort procedures with a presentation bias.",
"contacts can be sorted by first name xor last name. A true sort",
"sort by first name and last name is implemented as well as correspending",
"preferable to a true sort as the presentation-biased sort is visually within expectation",
"by their intended sort key but in really this may not be true.",
"of contacts with a presentation bias. Tries to sort by last name, but",
"contacts in an on-screen phone book in which a contact's first name xor",
"sorted sequence of contacts with a presentation bias. Tries to sort by last",
"that are missing a first name xor last name. A presentation-biased sort may",
"xor last name. A true sort by first name and last name is",
"name. A presentation-biased sort may be preferable to a true sort as the",
"present, the first name is used instead \"\"\" return sorted(contacts, key=lambda c: coalesce(c.lname,",
"last name is implemented as well as correspending sort procedures with a presentation",
"v is not None), None) def display_contacts(contacts): \"\"\"Displays contacts\"\"\" for contact in contacts:",
"Tries to sort by last name, but if the last name isn't present,",
"of how the contacts are displayed, there is no visual consequence in the",
"following code explores the presentation of contacts in an on-screen phone book in",
"a presentation bias. In effect, the presentation bias makes the contacts in the",
"key=lambda c: coalesce(c.fname, c.lname)) def presentation_sort_by_last_name(contacts): \"\"\"Returns a sorted sequence of contacts with",
"first name xor last name. A presentation-biased sort may be preferable to a",
"or None\"\"\" return next((v for v in values if v is not None),",
"be sorted by their intended sort key but in really this may not",
"display_contacts(contacts): \"\"\"Displays contacts\"\"\" for contact in contacts: print(f\"{(contact.fname or '')} {(contact.lname or '')}\".strip())",
"contacts with a presentation bias. Truly sorts by last name \"\"\" return sorted(contacts,",
"be preferable to a true sort as the presentation-biased sort is visually within",
"the first name is used instead \"\"\" return sorted(contacts, key=lambda c: coalesce(c.lname, c.fname))",
"c: coalesce(c.lname, c.fname)) def sort_by_first_name(contacts): \"\"\"Returns a sorted sequence of contacts with a",
"presentation bias)\") display_contacts(presentation_sort_by_first_name(contacts)) print() print(\"True Sort by Last Name\") display_contacts(sort_by_last_name(contacts)) print() print(\"Sort by",
"correspending sort procedures with a presentation bias. In effect, the presentation bias makes",
"displayed, there is no visual consequence in the case of contacts that are",
"v in values if v is not None), None) def display_contacts(contacts): \"\"\"Displays contacts\"\"\"",
"Contact(\"Green\", \"Lantern\"), Contact(\"Aquaman\", None), Contact(None, \"Diner\"), Contact(None, \"Metropolis\"), ] def coalesce(*values): \"\"\"Returns the",
"but if the first name isn't present, the last name is used instead",
"used instead \"\"\" return sorted(contacts, key=lambda c: coalesce(c.fname, c.lname)) def presentation_sort_by_last_name(contacts): \"\"\"Returns a",
"a sorted sequence of contacts with a presentation bias. Truly sorts by first",
"None) def display_contacts(contacts): \"\"\"Displays contacts\"\"\" for contact in contacts: print(f\"{(contact.fname or '')} {(contact.lname",
"in contacts: print(f\"{(contact.fname or '')} {(contact.lname or '')}\".strip()) def presentation_sort_by_first_name(contacts): \"\"\"Returns a sorted",
"name is used instead \"\"\" return sorted(contacts, key=lambda c: coalesce(c.lname, c.fname)) def sort_by_first_name(contacts):",
"but in really this may not be true. However, because of how the",
"Name\") display_contacts(sort_by_first_name(contacts)) print() print(\"Sort by First Name (with presentation bias)\") display_contacts(presentation_sort_by_first_name(contacts)) print() print(\"True",
"next((v for v in values if v is not None), None) def display_contacts(contacts):",
"print(\"True Sort by First Name\") display_contacts(sort_by_first_name(contacts)) print() print(\"Sort by First Name (with presentation"
] |
[
"in possible_firmwares: if f.endswith(\"{}.bin\".format(args.firmware)): filename = f break if not filename: print( \"Did",
"if d['type'] == 'dir'] possible_revs.sort() return possible_revs def get_goog_sheet(): data = urllib.request.urlopen( \"https://docs.google.com/spreadsheets/d/e/2PACX-1vTmqEM-XXPW4oHrJMD7QrCeKOiq1CPng9skQravspmEmaCt04Kz4lTlQLFTyQyJhcjqzCc--eO2f11x/pub?output=csv\"",
"in firmwares if d['type'] == 'file' and d['name'].endswith('.bin') ] print(\"Found firmwares: {}\".format(\", \".join(possible_firmwares)))",
"rev, targets_url) except TargetNotFound: rev = find_last_rev(args, possible_revs) # TODO: use this rev",
"get_firmwares_url(args, archs_url) possible_firmwares = get_firmwares(args, firmwares_url) filename = get_filename(args, possible_firmwares) image_url = get_image_url(args,",
"targets_url = get_targets_url(args, rev_url) try: possible_targets = get_targets(args, rev, targets_url) print(\"found at rev",
"rev_url = get_rev_url(archive_url, rev) possible_platforms = get_platforms(args, rev_url) targets_url = get_targets_url(args, rev_url) try:",
"--channel.', dest=\"channel\") parser.add_argument('--latest', dest=\"channel\", action=\"store_const\", help=\"Get the latest version.\", const=\"unstable\") parser.add_argument('--target', help=\"Target to",
"20 min. print(\"revs = ls_github(archive_url) {}\".format(archive_url)) revs = ls_github(archive_url, cache_ttl=60*20) possible_revs = [Version(d['name'])",
"7: print(\"Skipping row %s\" % i) continue _, _, rev_str, name, conf, notes,",
"else: rev = Version(rev) assert rev in possible_revs, \"{} is not found in",
"} save_cache(cache) return data _Version = namedtuple(\"Version\", (\"version\", \"commits\", \"hash\")) class Version(_Version): \"\"\"",
"== 'g' return _Version.__new__(cls, version, commits, githash[1:]) def __str__(self): return \"%s-%i-g%s\" % self",
"def get_archs_url(args, targets_url): archs_url = \"{}{:s}/\".format(targets_url, args.target) return archs_url def get_archs(args, archs_url): archs",
"{} for target {} for platform {} at rev {} (found {})\". format(args.firmware,",
"parts[-1][1:]]) print(\"Downloading to: {}\".format(out_filename)) urllib.request.urlretrieve(image_url, out_filename) return True def main(): args = parse_args()",
"= get_revs(archive_url) rev = get_rev(possible_revs, args.rev, args.channel) rev_url = get_rev_url(archive_url, rev) possible_platforms =",
"_Version.__new__(cls, version, commits, githash[1:]) def __str__(self): return \"%s-%i-g%s\" % self doctest.testmod() def parse_args():",
"cache_ttl)): data = cache[url]['data'] else: while True: data = json.loads(urllib.request.urlopen(url).read().decode()) if \"message\" in",
"prebuilt firmware') parser.add_argument('--rev', help='Get a specific version.') parser.add_argument('--platform', help='Get for a specific platform",
"{} (found {})\". format(args.target, args.platform, rev, \", \".join(possible_targets))) raise TargetNotFound() return possible_targets def",
"\"Did not find arch {} for target {} for platform {} at rev",
"min. print(\"revs = ls_github(archive_url) {}\".format(archive_url)) revs = ls_github(archive_url, cache_ttl=60*20) possible_revs = [Version(d['name']) for",
"\"repo\": \"HDMI2USB-firmware-prebuilt\", \"branch\": branch, } archive_url = \"https://api.github.com/repos/{owner}/{repo}/contents/archive/{branch}/\".format( **details) return archive_url def get_revs(archive_url):",
"else: break cache[url] = { 'timestamp': datetime.now(), 'data': data } save_cache(cache) return data",
"default=\"lm32\", help=\"Soft-CPU architecture to download from.\") parser.add_argument('--user', help='Github user to download from.', default=\"timvideos\")",
"#!/usr/bin/env python # FIXME: Make this work under Python 2 import argparse import",
"except IOError: cache = {} return cache def save_cache(cache): pickle.dump(cache, open(cache_name, 'wb')) cache",
"possible_revs = [Version(d['name']) for d in revs if d['type'] == 'dir'] possible_revs.sort() return",
"instead. sys.exit(1) archs_url = get_archs_url(args, targets_url) possible_archs = get_archs(args, archs_url) firmwares_url = get_firmwares_url(args,",
"target=args.target, arch=args.arch, filename=filename) print(\"Image URL: {}\".format(image_url)) return image_url def download(args, rev, filename, image_url):",
"save_cache(cache): pickle.dump(cache, open(cache_name, 'wb')) cache = load_cache() if url in cache and (cache_ttl",
"\"{}{:s}/\".format(targets_url, args.target) return archs_url def get_archs(args, archs_url): archs = ls_github(archs_url) possible_archs = [d['name']",
"return args def mk_url(user, branch): details = { \"owner\": user, \"repo\": \"HDMI2USB-firmware-prebuilt\", \"branch\":",
"try: cache = pickle.load(open(cache_name, 'rb')) except IOError: cache = {} return cache def",
"rev = Version(rev) assert rev in possible_revs, \"{} is not found in {}\".format(",
"argparse import csv import doctest import json import os import pickle import sys",
"is not found in {}\".format( rev, possible_revs) print(\"rev: {}\".format(rev)) return rev def get_rev_url(archive_url,",
"rev def get_rev_url(archive_url, rev): rev_url = \"{}{:s}/\".format(archive_url, str(rev)) return rev_url def get_platforms(args, rev_url):",
"\".join(possible_platforms))) if args.platform not in possible_platforms: print(\"Did not find platform {} at rev",
"rev, \", \".join(possible_targets))) raise TargetNotFound() return possible_targets def find_last_rev(args, possible_revs): possible_revs.reverse() archive_url =",
"\".join(possible_archs))) if args.arch not in possible_archs: print( \"Did not find arch {} for",
"rev_names[channel] print(\"Channel {} is at rev {}\".format(channel, rev)) else: rev = Version(rev) assert",
"+ [str(rev), args.platform, args.target, args.arch, parts[-1][1:]]) print(\"Downloading to: {}\".format(out_filename)) urllib.request.urlretrieve(image_url, out_filename) return True",
"= ls_github(archs_url) possible_archs = [d['name'] for d in archs if d['type'] == 'dir']",
"args.platform, rev, \", \".join(possible_targets))) raise TargetNotFound() return possible_targets def find_last_rev(args, possible_revs): possible_revs.reverse() archive_url",
"= get_targets(args, rev, targets_url) except TargetNotFound: rev = find_last_rev(args, possible_revs) # TODO: use",
"from collections import namedtuple from datetime import datetime class TargetNotFound(Exception): pass def ls_github(url,",
"(cache_ttl is None or ( (datetime.now()-cache[url]['timestamp']).total_seconds() < cache_ttl)): data = cache[url]['data'] else: while",
"= [ d['name'] for d in firmwares if d['type'] == 'file' and d['name'].endswith('.bin')",
"os import pickle import sys import time import urllib.request from collections import namedtuple",
"!= 7: print(\"Skipping row %s\" % i) continue _, _, rev_str, name, conf,",
"while True: data = json.loads(urllib.request.urlopen(url).read().decode()) if \"message\" in data: print(\"Warning: {}\".format(data[\"message\"])) time.sleep(1) continue",
"__str__(self): return \"%s-%i-g%s\" % self doctest.testmod() def parse_args(): parser = argparse.ArgumentParser( description='Download prebuilt",
"= \"https://github.com/{user}/HDMI2USB-firmware-prebuilt/raw/master/archive/{branch}/{rev}/{platform}/{target}/{arch}/{filename}\".format( user=args.user, branch=args.branch, rev=rev, platform=args.platform, target=args.target, arch=args.arch, filename=filename) print(\"Image URL: {}\".format(image_url)) return",
"args.output else: parts = os.path.splitext(filename) out_filename = \".\".join( list(parts[:-1]) + [str(rev), args.platform, args.target,",
"get_targets(args, rev, targets_url) except TargetNotFound: rev = find_last_rev(args, possible_revs) # TODO: use this",
"Version(_Version): \"\"\" >>> v = Version(\"v0.0.4-44-g0cd842f\") >>> v Version(version='v0.0.4', commits=44, hash='0cd842f') >>> str(v)",
"\"\"\" >>> v = Version(\"v0.0.4-44-g0cd842f\") >>> v Version(version='v0.0.4', commits=44, hash='0cd842f') >>> str(v) 'v0.0.4-44-g0cd842f'",
"url in cache and (cache_ttl is None or ( (datetime.now()-cache[url]['timestamp']).total_seconds() < cache_ttl)): data",
"True: data = json.loads(urllib.request.urlopen(url).read().decode()) if \"message\" in data: print(\"Warning: {}\".format(data[\"message\"])) time.sleep(1) continue else:",
"sys.exit(1) return filename def get_image_url(args, rev, filename): image_url = \"https://github.com/{user}/HDMI2USB-firmware-prebuilt/raw/master/archive/{branch}/{rev}/{platform}/{target}/{arch}/{filename}\".format( user=args.user, branch=args.branch, rev=rev,",
"rev, targets_url) print(\"found at rev {}\".format(rev)) return rev except TargetNotFound: continue def get_archs_url(args,",
"for f in possible_firmwares: if f.endswith(\"{}.bin\".format(args.firmware)): filename = f break if not filename:",
"} archive_url = \"https://api.github.com/repos/{owner}/{repo}/contents/archive/{branch}/\".format( **details) return archive_url def get_revs(archive_url): # this changes as",
"a class or find a package. cache_name = \"github.pickle\" def load_cache(): try: cache",
"cache_name = \"github.pickle\" def load_cache(): try: cache = pickle.load(open(cache_name, 'rb')) except IOError: cache",
"over 20 min, so refresh every 20 min. print(\"revs = ls_github(archive_url) {}\".format(archive_url)) revs",
"= {} return cache def save_cache(cache): pickle.dump(cache, open(cache_name, 'wb')) cache = load_cache() if",
"specific platform (board + expansion boards configuration).') parser.add_argument('--board', help='Alias for --platform.', dest=\"platform\") parser.add_argument('--channel',",
"import time import urllib.request from collections import namedtuple from datetime import datetime class",
"= os.path.splitext(filename) out_filename = \".\".join( list(parts[:-1]) + [str(rev), args.platform, args.target, args.arch, parts[-1][1:]]) print(\"Downloading",
"mk_url(user, branch): details = { \"owner\": user, \"repo\": \"HDMI2USB-firmware-prebuilt\", \"branch\": branch, } archive_url",
"rev {}\".format(channel, rev)) else: rev = Version(rev) assert rev in possible_revs, \"{} is",
"= { 'timestamp': datetime.now(), 'data': data } save_cache(cache) return data _Version = namedtuple(\"Version\",",
"import csv import doctest import json import os import pickle import sys import",
"rev return rev_names def get_rev(possible_revs,rev=None, channel=\"unstable\"): if not rev: if channel == \"unstable\":",
"= mk_url(args.user, args.branch) possible_revs = get_revs(archive_url) rev = get_rev(possible_revs, args.rev, args.channel) rev_url =",
"= [d['name'] for d in archs if d['type'] == 'dir'] print(\"Found archs: {}\".format(\",",
"for platform {} at rev {} (found {})\". format(args.arch, args.target, args.platform, rev, \",",
"i[0] == \"Link\": continue if i[0] != \"GitHub\": pass # continue if len(i)",
"parser.add_argument('--firmware', help=\"Firmware to download from.\", default=\"firmware\") parser.add_argument('--arch', default=\"lm32\", help=\"Soft-CPU architecture to download from.\")",
"rev_names def get_rev(possible_revs,rev=None, channel=\"unstable\"): if not rev: if channel == \"unstable\": rev =",
"doctest.testmod() def parse_args(): parser = argparse.ArgumentParser( description='Download prebuilt firmware') parser.add_argument('--rev', help='Get a specific",
"open(cache_name, 'wb')) cache = load_cache() if url in cache and (cache_ttl is None",
"cache[url] = { 'timestamp': datetime.now(), 'data': data } save_cache(cache) return data _Version =",
"rev = Version(rev_str) # assert rev in possible_revs # assert name not in",
"version.\", const=\"unstable\") parser.add_argument('--target', help=\"Target to download from.\", default=\"hdmi2usb\") parser.add_argument('--firmware', help=\"Firmware to download from.\",",
"json.loads(urllib.request.urlopen(url).read().decode()) if \"message\" in data: print(\"Warning: {}\".format(data[\"message\"])) time.sleep(1) continue else: break cache[url] =",
"default=\"hdmi2usb\") parser.add_argument('--firmware', help=\"Firmware to download from.\", default=\"firmware\") parser.add_argument('--arch', default=\"lm32\", help=\"Soft-CPU architecture to download",
"urllib.request.urlopen( \"https://docs.google.com/spreadsheets/d/e/2PACX-1vTmqEM-XXPW4oHrJMD7QrCeKOiq1CPng9skQravspmEmaCt04Kz4lTlQLFTyQyJhcjqzCc--eO2f11x/pub?output=csv\" ).read().decode('utf-8') rev_names = {} for i in csv.reader(data.splitlines(), dialect='excel'): print(len(i),i) if",
"default=\"firmware\") parser.add_argument('--arch', default=\"lm32\", help=\"Soft-CPU architecture to download from.\") parser.add_argument('--user', help='Github user to download",
"channel ().\", default=\"unstable\") parser.add_argument('--tag', help='Alias for --channel.', dest=\"channel\") parser.add_argument('--latest', dest=\"channel\", action=\"store_const\", help=\"Get the",
"githash[0] == 'g' return _Version.__new__(cls, version, commits, githash[1:]) def __str__(self): return \"%s-%i-g%s\" %",
"from.', default=\"timvideos\") parser.add_argument('--branch', help=\"Branch to download from.\", default=\"master\") parser.add_argument('-o', '--output', help=\"Output filename.\", )",
"parse_args() archive_url = mk_url(args.user, args.branch) possible_revs = get_revs(archive_url) rev = get_rev(possible_revs, args.rev, args.channel)",
"for d in revs if d['type'] == 'dir'] possible_revs.sort() return possible_revs def get_goog_sheet():",
"(found {})\". format(args.target, args.platform, rev, \", \".join(possible_targets))) raise TargetNotFound() return possible_targets def find_last_rev(args,",
"= get_rev_url(archive_url, rev) possible_platforms = get_platforms(args, rev_url) targets_url = get_targets_url(args, rev_url) try: possible_targets",
"not in possible_archs: print( \"Did not find arch {} for target {} for",
"archive_url = mk_url(args.user, args.branch) possible_revs = get_revs(archive_url) rev = get_rev(possible_revs, args.rev, args.channel) rev_url",
"find a package. cache_name = \"github.pickle\" def load_cache(): try: cache = pickle.load(open(cache_name, 'rb'))",
"ls_github(url, cache_ttl=None): # FIXME: Move cache to a class or find a package.",
"name, conf, notes, more_notes = i if not rev_str: continue print(rev_str, name) rev",
"channel == \"unstable\": rev = possible_revs[-1] else: rev_names = get_goog_sheet() if channel not",
"filename: print( \"Did not find firmware {} for target {} for platform {}",
"this changes as revs are added. # builds take over 20 min, so",
"multiple times!\".format(name) rev_names[name] = rev return rev_names def get_rev(possible_revs,rev=None, channel=\"unstable\"): if not rev:",
"out_filename = args.output else: parts = os.path.splitext(filename) out_filename = \".\".join( list(parts[:-1]) + [str(rev),",
"== 'dir'] print(\"Found targets: {}\".format(\", \".join(possible_targets))) if args.target not in possible_targets: print(\"Did not",
"args = parser.parse_args() assert args.platform assert args.rev or args.channel assert args.target return args",
"print(\"Channel {} is at rev {}\".format(channel, rev)) else: rev = Version(rev) assert rev",
"archs = ls_github(archs_url) possible_archs = [d['name'] for d in archs if d['type'] ==",
"def get_image_url(args, rev, filename): image_url = \"https://github.com/{user}/HDMI2USB-firmware-prebuilt/raw/master/archive/{branch}/{rev}/{platform}/{target}/{arch}/{filename}\".format( user=args.user, branch=args.branch, rev=rev, platform=args.platform, target=args.target, arch=args.arch,",
"rev_url) try: possible_targets = get_targets(args, rev, targets_url) except TargetNotFound: rev = find_last_rev(args, possible_revs)",
"get_firmwares(args, firmwares_url): firmwares = ls_github(firmwares_url) possible_firmwares = [ d['name'] for d in firmwares",
"get_firmwares(args, firmwares_url) filename = get_filename(args, possible_firmwares) image_url = get_image_url(args, rev, filename) ret =",
"rev_url) try: possible_targets = get_targets(args, rev, targets_url) print(\"found at rev {}\".format(rev)) return rev",
"Version(rev) assert rev in possible_revs, \"{} is not found in {}\".format( rev, possible_revs)",
">>> v Version(version='v0.0.4', commits=44, hash='0cd842f') >>> str(v) 'v0.0.4-44-g0cd842f' \"\"\" def __new__(cls, value): version,",
"{}\".format(image_url)) return image_url def download(args, rev, filename, image_url): if args.output: out_filename = args.output",
"class Version(_Version): \"\"\" >>> v = Version(\"v0.0.4-44-g0cd842f\") >>> v Version(version='v0.0.4', commits=44, hash='0cd842f') >>>",
"find_last_rev(args, possible_revs) # TODO: use this rev instead. sys.exit(1) archs_url = get_archs_url(args, targets_url)",
"return cache def save_cache(cache): pickle.dump(cache, open(cache_name, 'wb')) cache = load_cache() if url in",
"{} for platform {} at rev {} (found {})\". format(args.target, args.platform, rev, \",",
"os.path.splitext(filename) out_filename = \".\".join( list(parts[:-1]) + [str(rev), args.platform, args.target, args.arch, parts[-1][1:]]) print(\"Downloading to:",
"**details) return archive_url def get_revs(archive_url): # this changes as revs are added. #",
"in csv.reader(data.splitlines(), dialect='excel'): print(len(i),i) if not i: continue if i[0] == \"Link\": continue",
"if args.platform not in possible_platforms: print(\"Did not find platform {} at rev {}",
"if i[0] != \"GitHub\": pass # continue if len(i) != 7: print(\"Skipping row",
") args = parser.parse_args() assert args.platform assert args.rev or args.channel assert args.target return",
"int(commits) assert githash[0] == 'g' return _Version.__new__(cls, version, commits, githash[1:]) def __str__(self): return",
"def ls_github(url, cache_ttl=None): # FIXME: Move cache to a class or find a",
"channel not in rev_names: print(\"Did not find {} in {}\".format(channel, rev_names)) sys.exit(1) rev",
"{} for platform {} at rev {} (found {})\". format(args.firmware, args.target, args.platform, rev,",
"== 'dir'] possible_revs.sort() return possible_revs def get_goog_sheet(): data = urllib.request.urlopen( \"https://docs.google.com/spreadsheets/d/e/2PACX-1vTmqEM-XXPW4oHrJMD7QrCeKOiq1CPng9skQravspmEmaCt04Kz4lTlQLFTyQyJhcjqzCc--eO2f11x/pub?output=csv\" ).read().decode('utf-8') rev_names",
"{} at rev {} (found {})\". format(args.arch, args.target, args.platform, rev, \", \".join(possible_archs))) sys.exit(1)",
"for a specific platform (board + expansion boards configuration).') parser.add_argument('--board', help='Alias for --platform.',",
"possible_revs) # TODO: use this rev instead. sys.exit(1) archs_url = get_archs_url(args, targets_url) possible_archs",
"version from in a specific channel ().\", default=\"unstable\") parser.add_argument('--tag', help='Alias for --channel.', dest=\"channel\")",
"sys.exit(1) archs_url = get_archs_url(args, targets_url) possible_archs = get_archs(args, archs_url) firmwares_url = get_firmwares_url(args, archs_url)",
"args def mk_url(user, branch): details = { \"owner\": user, \"repo\": \"HDMI2USB-firmware-prebuilt\", \"branch\": branch,",
"{})\". format(args.arch, args.target, args.platform, rev, \", \".join(possible_archs))) sys.exit(1) return possible_archs def get_firmwares_url(args, archs_url):",
"TODO: use this rev instead. sys.exit(1) archs_url = get_archs_url(args, targets_url) possible_archs = get_archs(args,",
"= json.loads(urllib.request.urlopen(url).read().decode()) if \"message\" in data: print(\"Warning: {}\".format(data[\"message\"])) time.sleep(1) continue else: break cache[url]",
"rev_url def get_platforms(args, rev_url): platforms = ls_github(rev_url) possible_platforms = [d['name'] for d in",
"args = parse_args() archive_url = mk_url(args.user, args.branch) possible_revs = get_revs(archive_url) rev = get_rev(possible_revs,",
"get_rev(possible_revs, args.rev, args.channel) rev_url = get_rev_url(archive_url, rev) possible_platforms = get_platforms(args, rev_url) targets_url =",
"user to download from.', default=\"timvideos\") parser.add_argument('--branch', help=\"Branch to download from.\", default=\"master\") parser.add_argument('-o', '--output',",
"'dir'] possible_revs.sort() return possible_revs def get_goog_sheet(): data = urllib.request.urlopen( \"https://docs.google.com/spreadsheets/d/e/2PACX-1vTmqEM-XXPW4oHrJMD7QrCeKOiq1CPng9skQravspmEmaCt04Kz4lTlQLFTyQyJhcjqzCc--eO2f11x/pub?output=csv\" ).read().decode('utf-8') rev_names =",
"rev_names = get_goog_sheet() if channel not in rev_names: print(\"Did not find {} in",
"\"{} is not found in {}\".format( rev, possible_revs) print(\"rev: {}\".format(rev)) return rev def",
"rev) possible_platforms = get_platforms(args, rev_url) targets_url = get_targets_url(args, rev_url) try: possible_targets = get_targets(args,",
"print( \"Did not find firmware {} for target {} for platform {} at",
"sys import time import urllib.request from collections import namedtuple from datetime import datetime",
"parser.add_argument('--board', help='Alias for --platform.', dest=\"platform\") parser.add_argument('--channel', help=\"Get latest version from in a specific",
"image_url = get_image_url(args, rev, filename) ret = download(args, rev, filename, image_url) print(\"Done!\") return",
"== \"Link\": continue if i[0] != \"GitHub\": pass # continue if len(i) !=",
"rev {}\".format(rev)) return rev except TargetNotFound: continue def get_archs_url(args, targets_url): archs_url = \"{}{:s}/\".format(targets_url,",
"archs_url def get_archs(args, archs_url): archs = ls_github(archs_url) possible_archs = [d['name'] for d in",
"= mk_url(args.user, args.branch) for rev in possible_revs: rev_url = get_rev_url(archive_url, rev) possible_platforms =",
"in platforms if d['type'] == 'dir'] print(\"Found platforms: {}\".format(\", \".join(possible_platforms))) if args.platform not",
"under Python 2 import argparse import csv import doctest import json import os",
"'--output', help=\"Output filename.\", ) args = parser.parse_args() assert args.platform assert args.rev or args.channel",
"%s\" % i) continue _, _, rev_str, name, conf, notes, more_notes = i",
"collections import namedtuple from datetime import datetime class TargetNotFound(Exception): pass def ls_github(url, cache_ttl=None):",
"args.platform not in possible_platforms: print(\"Did not find platform {} at rev {} (found",
"print(\"Found firmwares: {}\".format(\", \".join(possible_firmwares))) return possible_firmwares def get_filename(args, possible_firmwares): filename = None for",
"in cache and (cache_ttl is None or ( (datetime.now()-cache[url]['timestamp']).total_seconds() < cache_ttl)): data =",
"= value.split('-') commits = int(commits) assert githash[0] == 'g' return _Version.__new__(cls, version, commits,",
">>> str(v) 'v0.0.4-44-g0cd842f' \"\"\" def __new__(cls, value): version, commits, githash = value.split('-') commits",
"rev, filename, image_url): if args.output: out_filename = args.output else: parts = os.path.splitext(filename) out_filename",
"20 min, so refresh every 20 min. print(\"revs = ls_github(archive_url) {}\".format(archive_url)) revs =",
"possible_revs def get_goog_sheet(): data = urllib.request.urlopen( \"https://docs.google.com/spreadsheets/d/e/2PACX-1vTmqEM-XXPW4oHrJMD7QrCeKOiq1CPng9skQravspmEmaCt04Kz4lTlQLFTyQyJhcjqzCc--eO2f11x/pub?output=csv\" ).read().decode('utf-8') rev_names = {} for i",
"== 'file' and d['name'].endswith('.bin') ] print(\"Found firmwares: {}\".format(\", \".join(possible_firmwares))) return possible_firmwares def get_filename(args,",
"get_image_url(args, rev, filename): image_url = \"https://github.com/{user}/HDMI2USB-firmware-prebuilt/raw/master/archive/{branch}/{rev}/{platform}/{target}/{arch}/{filename}\".format( user=args.user, branch=args.branch, rev=rev, platform=args.platform, target=args.target, arch=args.arch, filename=filename)",
"min, so refresh every 20 min. print(\"revs = ls_github(archive_url) {}\".format(archive_url)) revs = ls_github(archive_url,",
"possible_targets = get_targets(args, rev, targets_url) except TargetNotFound: rev = find_last_rev(args, possible_revs) # TODO:",
"d['type'] == 'dir'] print(\"Found targets: {}\".format(\", \".join(possible_targets))) if args.target not in possible_targets: print(\"Did",
"\"owner\": user, \"repo\": \"HDMI2USB-firmware-prebuilt\", \"branch\": branch, } archive_url = \"https://api.github.com/repos/{owner}/{repo}/contents/archive/{branch}/\".format( **details) return archive_url",
"[d['name'] for d in targets if d['type'] == 'dir'] print(\"Found targets: {}\".format(\", \".join(possible_targets)))",
"{}\".format(channel, rev_names)) sys.exit(1) rev = rev_names[channel] print(\"Channel {} is at rev {}\".format(channel, rev))",
"= ls_github(firmwares_url) possible_firmwares = [ d['name'] for d in firmwares if d['type'] ==",
"if args.output: out_filename = args.output else: parts = os.path.splitext(filename) out_filename = \".\".join( list(parts[:-1])",
"version.') parser.add_argument('--platform', help='Get for a specific platform (board + expansion boards configuration).') parser.add_argument('--board',",
"{ \"owner\": user, \"repo\": \"HDMI2USB-firmware-prebuilt\", \"branch\": branch, } archive_url = \"https://api.github.com/repos/{owner}/{repo}/contents/archive/{branch}/\".format( **details) return",
"= get_targets(args, rev, targets_url) print(\"found at rev {}\".format(rev)) return rev except TargetNotFound: continue",
"rev except TargetNotFound: continue def get_archs_url(args, targets_url): archs_url = \"{}{:s}/\".format(targets_url, args.target) return archs_url",
"out_filename = \".\".join( list(parts[:-1]) + [str(rev), args.platform, args.target, args.arch, parts[-1][1:]]) print(\"Downloading to: {}\".format(out_filename))",
"targets if d['type'] == 'dir'] print(\"Found targets: {}\".format(\", \".join(possible_targets))) if args.target not in",
"assert args.rev or args.channel assert args.target return args def mk_url(user, branch): details =",
"{}\".format(rev)) return rev def get_rev_url(archive_url, rev): rev_url = \"{}{:s}/\".format(archive_url, str(rev)) return rev_url def",
"sys.exit(1) rev = rev_names[channel] print(\"Channel {} is at rev {}\".format(channel, rev)) else: rev",
"commits = int(commits) assert githash[0] == 'g' return _Version.__new__(cls, version, commits, githash[1:]) def",
"platform=args.platform, target=args.target, arch=args.arch, filename=filename) print(\"Image URL: {}\".format(image_url)) return image_url def download(args, rev, filename,",
"image_url): if args.output: out_filename = args.output else: parts = os.path.splitext(filename) out_filename = \".\".join(",
"to download from.', default=\"timvideos\") parser.add_argument('--branch', help=\"Branch to download from.\", default=\"master\") parser.add_argument('-o', '--output', help=\"Output",
"args.output: out_filename = args.output else: parts = os.path.splitext(filename) out_filename = \".\".join( list(parts[:-1]) +",
"{ 'timestamp': datetime.now(), 'data': data } save_cache(cache) return data _Version = namedtuple(\"Version\", (\"version\",",
"so refresh every 20 min. print(\"revs = ls_github(archive_url) {}\".format(archive_url)) revs = ls_github(archive_url, cache_ttl=60*20)",
"more_notes = i if not rev_str: continue print(rev_str, name) rev = Version(rev_str) #",
"v = Version(\"v0.0.4-44-g0cd842f\") >>> v Version(version='v0.0.4', commits=44, hash='0cd842f') >>> str(v) 'v0.0.4-44-g0cd842f' \"\"\" def",
"rev_names[name] = rev return rev_names def get_rev(possible_revs,rev=None, channel=\"unstable\"): if not rev: if channel",
"(found {})\". format(args.firmware, args.target, args.platform, rev, \", \".join(possible_firmwares))) sys.exit(1) return filename def get_image_url(args,",
"data: print(\"Warning: {}\".format(data[\"message\"])) time.sleep(1) continue else: break cache[url] = { 'timestamp': datetime.now(), 'data':",
"image_url def download(args, rev, filename, image_url): if args.output: out_filename = args.output else: parts",
"'wb')) cache = load_cache() if url in cache and (cache_ttl is None or",
"filename = f break if not filename: print( \"Did not find firmware {}",
"get_rev(possible_revs,rev=None, channel=\"unstable\"): if not rev: if channel == \"unstable\": rev = possible_revs[-1] else:",
"return archs_url def get_archs(args, archs_url): archs = ls_github(archs_url) possible_archs = [d['name'] for d",
"not found in {}\".format( rev, possible_revs) print(\"rev: {}\".format(rev)) return rev def get_rev_url(archive_url, rev):",
"get_targets(args, rev, targets_url): targets = ls_github(targets_url) possible_targets = [d['name'] for d in targets",
"rev_names, \"{} is listed multiple times!\".format(name) rev_names[name] = rev return rev_names def get_rev(possible_revs,rev=None,",
"parser.add_argument('--rev', help='Get a specific version.') parser.add_argument('--platform', help='Get for a specific platform (board +",
"possible_firmwares) image_url = get_image_url(args, rev, filename) ret = download(args, rev, filename, image_url) print(\"Done!\")",
"_, _, rev_str, name, conf, notes, more_notes = i if not rev_str: continue",
">>> v = Version(\"v0.0.4-44-g0cd842f\") >>> v Version(version='v0.0.4', commits=44, hash='0cd842f') >>> str(v) 'v0.0.4-44-g0cd842f' \"\"\"",
"help=\"Get latest version from in a specific channel ().\", default=\"unstable\") parser.add_argument('--tag', help='Alias for",
"possible_archs def get_firmwares_url(args, archs_url): firmwares_url = \"{}{:s}/\".format(archs_url, args.arch) return firmwares_url def get_firmwares(args, firmwares_url):",
"print( \"Did not find arch {} for target {} for platform {} at",
"_Version = namedtuple(\"Version\", (\"version\", \"commits\", \"hash\")) class Version(_Version): \"\"\" >>> v = Version(\"v0.0.4-44-g0cd842f\")",
"possible_revs): possible_revs.reverse() archive_url = mk_url(args.user, args.branch) for rev in possible_revs: rev_url = get_rev_url(archive_url,",
"return _Version.__new__(cls, version, commits, githash[1:]) def __str__(self): return \"%s-%i-g%s\" % self doctest.testmod() def",
"to a class or find a package. cache_name = \"github.pickle\" def load_cache(): try:",
"archs_url = get_archs_url(args, targets_url) possible_archs = get_archs(args, archs_url) firmwares_url = get_firmwares_url(args, archs_url) possible_firmwares",
"ls_github(targets_url) possible_targets = [d['name'] for d in targets if d['type'] == 'dir'] print(\"Found",
"'timestamp': datetime.now(), 'data': data } save_cache(cache) return data _Version = namedtuple(\"Version\", (\"version\", \"commits\",",
"are added. # builds take over 20 min, so refresh every 20 min.",
"this rev instead. sys.exit(1) archs_url = get_archs_url(args, targets_url) possible_archs = get_archs(args, archs_url) firmwares_url",
"\".join(possible_firmwares))) sys.exit(1) return filename def get_image_url(args, rev, filename): image_url = \"https://github.com/{user}/HDMI2USB-firmware-prebuilt/raw/master/archive/{branch}/{rev}/{platform}/{target}/{arch}/{filename}\".format( user=args.user, branch=args.branch,",
"= args.output else: parts = os.path.splitext(filename) out_filename = \".\".join( list(parts[:-1]) + [str(rev), args.platform,",
"import json import os import pickle import sys import time import urllib.request from",
"if url in cache and (cache_ttl is None or ( (datetime.now()-cache[url]['timestamp']).total_seconds() < cache_ttl)):",
"!= \"GitHub\": pass # continue if len(i) != 7: print(\"Skipping row %s\" %",
"parser.add_argument('--arch', default=\"lm32\", help=\"Soft-CPU architecture to download from.\") parser.add_argument('--user', help='Github user to download from.',",
"= \"https://api.github.com/repos/{owner}/{repo}/contents/archive/{branch}/\".format( **details) return archive_url def get_revs(archive_url): # this changes as revs are",
"dest=\"channel\") parser.add_argument('--latest', dest=\"channel\", action=\"store_const\", help=\"Get the latest version.\", const=\"unstable\") parser.add_argument('--target', help=\"Target to download",
"channel=\"unstable\"): if not rev: if channel == \"unstable\": rev = possible_revs[-1] else: rev_names",
"dest=\"channel\", action=\"store_const\", help=\"Get the latest version.\", const=\"unstable\") parser.add_argument('--target', help=\"Target to download from.\", default=\"hdmi2usb\")",
"architecture to download from.\") parser.add_argument('--user', help='Github user to download from.', default=\"timvideos\") parser.add_argument('--branch', help=\"Branch",
"v Version(version='v0.0.4', commits=44, hash='0cd842f') >>> str(v) 'v0.0.4-44-g0cd842f' \"\"\" def __new__(cls, value): version, commits,",
"latest version from in a specific channel ().\", default=\"unstable\") parser.add_argument('--tag', help='Alias for --channel.',",
"[Version(d['name']) for d in revs if d['type'] == 'dir'] possible_revs.sort() return possible_revs def",
"assert rev in possible_revs # assert name not in rev_names, \"{} is listed",
"platform {} at rev {} (found {})\".format( args.platform, rev, \", \".join(possible_platforms))) sys.exit(1) return",
"def load_cache(): try: cache = pickle.load(open(cache_name, 'rb')) except IOError: cache = {} return",
"import sys import time import urllib.request from collections import namedtuple from datetime import",
"datetime import datetime class TargetNotFound(Exception): pass def ls_github(url, cache_ttl=None): # FIXME: Move cache",
"\"unstable\": rev = possible_revs[-1] else: rev_names = get_goog_sheet() if channel not in rev_names:",
"possible_revs: rev_url = get_rev_url(archive_url, rev) possible_platforms = get_platforms(args, rev_url) targets_url = get_targets_url(args, rev_url)",
"not find {} in {}\".format(channel, rev_names)) sys.exit(1) rev = rev_names[channel] print(\"Channel {} is",
"not in possible_targets: print(\"Did not find target {} for platform {} at rev",
"help=\"Output filename.\", ) args = parser.parse_args() assert args.platform assert args.rev or args.channel assert",
"platform {} at rev {} (found {})\". format(args.arch, args.target, args.platform, rev, \", \".join(possible_archs)))",
"in possible_archs: print( \"Did not find arch {} for target {} for platform",
"args.target return args def mk_url(user, branch): details = { \"owner\": user, \"repo\": \"HDMI2USB-firmware-prebuilt\",",
"= ls_github(archive_url, cache_ttl=60*20) possible_revs = [Version(d['name']) for d in revs if d['type'] ==",
"= [d['name'] for d in platforms if d['type'] == 'dir'] print(\"Found platforms: {}\".format(\",",
"= pickle.load(open(cache_name, 'rb')) except IOError: cache = {} return cache def save_cache(cache): pickle.dump(cache,",
"possible_targets = [d['name'] for d in targets if d['type'] == 'dir'] print(\"Found targets:",
"f in possible_firmwares: if f.endswith(\"{}.bin\".format(args.firmware)): filename = f break if not filename: print(",
"def get_rev(possible_revs,rev=None, channel=\"unstable\"): if not rev: if channel == \"unstable\": rev = possible_revs[-1]",
"targets_url = \"{}{:s}/\".format(rev_url, args.platform) return targets_url def get_targets(args, rev, targets_url): targets = ls_github(targets_url)",
"if not filename: print( \"Did not find firmware {} for target {} for",
"{}\".format(rev)) return rev except TargetNotFound: continue def get_archs_url(args, targets_url): archs_url = \"{}{:s}/\".format(targets_url, args.target)",
"return rev def get_rev_url(archive_url, rev): rev_url = \"{}{:s}/\".format(archive_url, str(rev)) return rev_url def get_platforms(args,",
"if channel == \"unstable\": rev = possible_revs[-1] else: rev_names = get_goog_sheet() if channel",
"help='Alias for --platform.', dest=\"platform\") parser.add_argument('--channel', help=\"Get latest version from in a specific channel",
"args.platform, args.target, args.arch, parts[-1][1:]]) print(\"Downloading to: {}\".format(out_filename)) urllib.request.urlretrieve(image_url, out_filename) return True def main():",
"not i: continue if i[0] == \"Link\": continue if i[0] != \"GitHub\": pass",
"\".join(possible_firmwares))) return possible_firmwares def get_filename(args, possible_firmwares): filename = None for f in possible_firmwares:",
"and d['name'].endswith('.bin') ] print(\"Found firmwares: {}\".format(\", \".join(possible_firmwares))) return possible_firmwares def get_filename(args, possible_firmwares): filename",
"times!\".format(name) rev_names[name] = rev return rev_names def get_rev(possible_revs,rev=None, channel=\"unstable\"): if not rev: if",
"rev=rev, platform=args.platform, target=args.target, arch=args.arch, filename=filename) print(\"Image URL: {}\".format(image_url)) return image_url def download(args, rev,",
"# this changes as revs are added. # builds take over 20 min,",
"= get_image_url(args, rev, filename) ret = download(args, rev, filename, image_url) print(\"Done!\") return if",
"\", \".join(possible_platforms))) sys.exit(1) return possible_platforms def get_targets_url(args, rev_url): targets_url = \"{}{:s}/\".format(rev_url, args.platform) return",
"i in csv.reader(data.splitlines(), dialect='excel'): print(len(i),i) if not i: continue if i[0] == \"Link\":",
"possible_firmwares = [ d['name'] for d in firmwares if d['type'] == 'file' and",
"args.platform assert args.rev or args.channel assert args.target return args def mk_url(user, branch): details",
"namedtuple(\"Version\", (\"version\", \"commits\", \"hash\")) class Version(_Version): \"\"\" >>> v = Version(\"v0.0.4-44-g0cd842f\") >>> v",
"def __str__(self): return \"%s-%i-g%s\" % self doctest.testmod() def parse_args(): parser = argparse.ArgumentParser( description='Download",
"in possible_platforms: print(\"Did not find platform {} at rev {} (found {})\".format( args.platform,",
"pass def ls_github(url, cache_ttl=None): # FIXME: Move cache to a class or find",
"def get_goog_sheet(): data = urllib.request.urlopen( \"https://docs.google.com/spreadsheets/d/e/2PACX-1vTmqEM-XXPW4oHrJMD7QrCeKOiq1CPng9skQravspmEmaCt04Kz4lTlQLFTyQyJhcjqzCc--eO2f11x/pub?output=csv\" ).read().decode('utf-8') rev_names = {} for i in",
"print(len(i),i) if not i: continue if i[0] == \"Link\": continue if i[0] !=",
"if d['type'] == 'file' and d['name'].endswith('.bin') ] print(\"Found firmwares: {}\".format(\", \".join(possible_firmwares))) return possible_firmwares",
"firmware') parser.add_argument('--rev', help='Get a specific version.') parser.add_argument('--platform', help='Get for a specific platform (board",
"platforms if d['type'] == 'dir'] print(\"Found platforms: {}\".format(\", \".join(possible_platforms))) if args.platform not in",
"def get_targets_url(args, rev_url): targets_url = \"{}{:s}/\".format(rev_url, args.platform) return targets_url def get_targets(args, rev, targets_url):",
"def save_cache(cache): pickle.dump(cache, open(cache_name, 'wb')) cache = load_cache() if url in cache and",
"for d in firmwares if d['type'] == 'file' and d['name'].endswith('.bin') ] print(\"Found firmwares:",
"in {}\".format( rev, possible_revs) print(\"rev: {}\".format(rev)) return rev def get_rev_url(archive_url, rev): rev_url =",
"ls_github(archs_url) possible_archs = [d['name'] for d in archs if d['type'] == 'dir'] print(\"Found",
"get_revs(archive_url): # this changes as revs are added. # builds take over 20",
"cache_ttl=60*20) possible_revs = [Version(d['name']) for d in revs if d['type'] == 'dir'] possible_revs.sort()",
"rev, possible_revs) print(\"rev: {}\".format(rev)) return rev def get_rev_url(archive_url, rev): rev_url = \"{}{:s}/\".format(archive_url, str(rev))",
"{}\".format(\", \".join(possible_platforms))) if args.platform not in possible_platforms: print(\"Did not find platform {} at",
"branch=args.branch, rev=rev, platform=args.platform, target=args.target, arch=args.arch, filename=filename) print(\"Image URL: {}\".format(image_url)) return image_url def download(args,",
"help=\"Get the latest version.\", const=\"unstable\") parser.add_argument('--target', help=\"Target to download from.\", default=\"hdmi2usb\") parser.add_argument('--firmware', help=\"Firmware",
"None for f in possible_firmwares: if f.endswith(\"{}.bin\".format(args.firmware)): filename = f break if not",
"to download from.\", default=\"firmware\") parser.add_argument('--arch', default=\"lm32\", help=\"Soft-CPU architecture to download from.\") parser.add_argument('--user', help='Github",
"] print(\"Found firmwares: {}\".format(\", \".join(possible_firmwares))) return possible_firmwares def get_filename(args, possible_firmwares): filename = None",
"i[0] != \"GitHub\": pass # continue if len(i) != 7: print(\"Skipping row %s\"",
"f.endswith(\"{}.bin\".format(args.firmware)): filename = f break if not filename: print( \"Did not find firmware",
"\"GitHub\": pass # continue if len(i) != 7: print(\"Skipping row %s\" % i)",
"possible_revs = get_revs(archive_url) rev = get_rev(possible_revs, args.rev, args.channel) rev_url = get_rev_url(archive_url, rev) possible_platforms",
"{})\".format( args.platform, rev, \", \".join(possible_platforms))) sys.exit(1) return possible_platforms def get_targets_url(args, rev_url): targets_url =",
"rev_str: continue print(rev_str, name) rev = Version(rev_str) # assert rev in possible_revs #",
"Version(version='v0.0.4', commits=44, hash='0cd842f') >>> str(v) 'v0.0.4-44-g0cd842f' \"\"\" def __new__(cls, value): version, commits, githash",
"\"Link\": continue if i[0] != \"GitHub\": pass # continue if len(i) != 7:",
"main(): args = parse_args() archive_url = mk_url(args.user, args.branch) possible_revs = get_revs(archive_url) rev =",
"assert githash[0] == 'g' return _Version.__new__(cls, version, commits, githash[1:]) def __str__(self): return \"%s-%i-g%s\"",
"'data': data } save_cache(cache) return data _Version = namedtuple(\"Version\", (\"version\", \"commits\", \"hash\")) class",
"if args.target not in possible_targets: print(\"Did not find target {} for platform {}",
"self doctest.testmod() def parse_args(): parser = argparse.ArgumentParser( description='Download prebuilt firmware') parser.add_argument('--rev', help='Get a",
"firmwares: {}\".format(\", \".join(possible_firmwares))) return possible_firmwares def get_filename(args, possible_firmwares): filename = None for f",
"download from.\", default=\"hdmi2usb\") parser.add_argument('--firmware', help=\"Firmware to download from.\", default=\"firmware\") parser.add_argument('--arch', default=\"lm32\", help=\"Soft-CPU architecture",
"githash[1:]) def __str__(self): return \"%s-%i-g%s\" % self doctest.testmod() def parse_args(): parser = argparse.ArgumentParser(",
"get_targets_url(args, rev_url) try: possible_targets = get_targets(args, rev, targets_url) except TargetNotFound: rev = find_last_rev(args,",
"ls_github(archive_url, cache_ttl=60*20) possible_revs = [Version(d['name']) for d in revs if d['type'] == 'dir']",
"is None or ( (datetime.now()-cache[url]['timestamp']).total_seconds() < cache_ttl)): data = cache[url]['data'] else: while True:",
"rev_url = \"{}{:s}/\".format(archive_url, str(rev)) return rev_url def get_platforms(args, rev_url): platforms = ls_github(rev_url) possible_platforms",
"# FIXME: Move cache to a class or find a package. cache_name =",
"\"github.pickle\" def load_cache(): try: cache = pickle.load(open(cache_name, 'rb')) except IOError: cache = {}",
"rev = get_rev(possible_revs, args.rev, args.channel) rev_url = get_rev_url(archive_url, rev) possible_platforms = get_platforms(args, rev_url)",
"d['name'] for d in firmwares if d['type'] == 'file' and d['name'].endswith('.bin') ] print(\"Found",
"possible_revs # assert name not in rev_names, \"{} is listed multiple times!\".format(name) rev_names[name]",
"get_targets_url(args, rev_url): targets_url = \"{}{:s}/\".format(rev_url, args.platform) return targets_url def get_targets(args, rev, targets_url): targets",
"= cache[url]['data'] else: while True: data = json.loads(urllib.request.urlopen(url).read().decode()) if \"message\" in data: print(\"Warning:",
"[d['name'] for d in archs if d['type'] == 'dir'] print(\"Found archs: {}\".format(\", \".join(possible_archs)))",
"parser.add_argument('--target', help=\"Target to download from.\", default=\"hdmi2usb\") parser.add_argument('--firmware', help=\"Firmware to download from.\", default=\"firmware\") parser.add_argument('--arch',",
"get_archs_url(args, targets_url): archs_url = \"{}{:s}/\".format(targets_url, args.target) return archs_url def get_archs(args, archs_url): archs =",
"rev = find_last_rev(args, possible_revs) # TODO: use this rev instead. sys.exit(1) archs_url =",
"print(\"Did not find target {} for platform {} at rev {} (found {})\".",
"{} at rev {} (found {})\".format( args.platform, rev, \", \".join(possible_platforms))) sys.exit(1) return possible_platforms",
"= get_platforms(args, rev_url) targets_url = get_targets_url(args, rev_url) try: possible_targets = get_targets(args, rev, targets_url)",
"rev_url) targets_url = get_targets_url(args, rev_url) try: possible_targets = get_targets(args, rev, targets_url) print(\"found at",
"d['type'] == 'file' and d['name'].endswith('.bin') ] print(\"Found firmwares: {}\".format(\", \".join(possible_firmwares))) return possible_firmwares def",
"= rev_names[channel] print(\"Channel {} is at rev {}\".format(channel, rev)) else: rev = Version(rev)",
"const=\"unstable\") parser.add_argument('--target', help=\"Target to download from.\", default=\"hdmi2usb\") parser.add_argument('--firmware', help=\"Firmware to download from.\", default=\"firmware\")",
"targets_url = get_targets_url(args, rev_url) try: possible_targets = get_targets(args, rev, targets_url) except TargetNotFound: rev",
"archive_url def get_revs(archive_url): # this changes as revs are added. # builds take",
"found in {}\".format( rev, possible_revs) print(\"rev: {}\".format(rev)) return rev def get_rev_url(archive_url, rev): rev_url",
"filename.\", ) args = parser.parse_args() assert args.platform assert args.rev or args.channel assert args.target",
"in targets if d['type'] == 'dir'] print(\"Found targets: {}\".format(\", \".join(possible_targets))) if args.target not",
"(found {})\". format(args.arch, args.target, args.platform, rev, \", \".join(possible_archs))) sys.exit(1) return possible_archs def get_firmwares_url(args,",
"get_platforms(args, rev_url) targets_url = get_targets_url(args, rev_url) try: possible_targets = get_targets(args, rev, targets_url) except",
"= \"{}{:s}/\".format(targets_url, args.target) return archs_url def get_archs(args, archs_url): archs = ls_github(archs_url) possible_archs =",
"cache = load_cache() if url in cache and (cache_ttl is None or (",
"get_archs(args, archs_url): archs = ls_github(archs_url) possible_archs = [d['name'] for d in archs if",
"filename): image_url = \"https://github.com/{user}/HDMI2USB-firmware-prebuilt/raw/master/archive/{branch}/{rev}/{platform}/{target}/{arch}/{filename}\".format( user=args.user, branch=args.branch, rev=rev, platform=args.platform, target=args.target, arch=args.arch, filename=filename) print(\"Image URL:",
"pickle.dump(cache, open(cache_name, 'wb')) cache = load_cache() if url in cache and (cache_ttl is",
"get_targets_url(args, rev_url) try: possible_targets = get_targets(args, rev, targets_url) print(\"found at rev {}\".format(rev)) return",
"list(parts[:-1]) + [str(rev), args.platform, args.target, args.arch, parts[-1][1:]]) print(\"Downloading to: {}\".format(out_filename)) urllib.request.urlretrieve(image_url, out_filename) return",
"for --platform.', dest=\"platform\") parser.add_argument('--channel', help=\"Get latest version from in a specific channel ().\",",
"doctest import json import os import pickle import sys import time import urllib.request",
"if d['type'] == 'dir'] print(\"Found archs: {}\".format(\", \".join(possible_archs))) if args.arch not in possible_archs:",
"or args.channel assert args.target return args def mk_url(user, branch): details = { \"owner\":",
"csv import doctest import json import os import pickle import sys import time",
"d in firmwares if d['type'] == 'file' and d['name'].endswith('.bin') ] print(\"Found firmwares: {}\".format(\",",
"take over 20 min, so refresh every 20 min. print(\"revs = ls_github(archive_url) {}\".format(archive_url))",
"= find_last_rev(args, possible_revs) # TODO: use this rev instead. sys.exit(1) archs_url = get_archs_url(args,",
"get_rev_url(archive_url, rev) possible_platforms = get_platforms(args, rev_url) targets_url = get_targets_url(args, rev_url) try: possible_targets =",
"cache def save_cache(cache): pickle.dump(cache, open(cache_name, 'wb')) cache = load_cache() if url in cache",
"'g' return _Version.__new__(cls, version, commits, githash[1:]) def __str__(self): return \"%s-%i-g%s\" % self doctest.testmod()",
"possible_firmwares: if f.endswith(\"{}.bin\".format(args.firmware)): filename = f break if not filename: print( \"Did not",
"help='Get a specific version.') parser.add_argument('--platform', help='Get for a specific platform (board + expansion",
"parser.add_argument('--latest', dest=\"channel\", action=\"store_const\", help=\"Get the latest version.\", const=\"unstable\") parser.add_argument('--target', help=\"Target to download from.\",",
"= parse_args() archive_url = mk_url(args.user, args.branch) possible_revs = get_revs(archive_url) rev = get_rev(possible_revs, args.rev,",
"= Version(rev) assert rev in possible_revs, \"{} is not found in {}\".format( rev,",
"get_filename(args, possible_firmwares): filename = None for f in possible_firmwares: if f.endswith(\"{}.bin\".format(args.firmware)): filename =",
"{}\".format(\", \".join(possible_firmwares))) return possible_firmwares def get_filename(args, possible_firmwares): filename = None for f in",
"parser.add_argument('--branch', help=\"Branch to download from.\", default=\"master\") parser.add_argument('-o', '--output', help=\"Output filename.\", ) args =",
"= f break if not filename: print( \"Did not find firmware {} for",
"possible_targets: print(\"Did not find target {} for platform {} at rev {} (found",
"cache_ttl=None): # FIXME: Move cache to a class or find a package. cache_name",
"try: possible_targets = get_targets(args, rev, targets_url) print(\"found at rev {}\".format(rev)) return rev except",
"i: continue if i[0] == \"Link\": continue if i[0] != \"GitHub\": pass #",
"rev {} (found {})\". format(args.firmware, args.target, args.platform, rev, \", \".join(possible_firmwares))) sys.exit(1) return filename",
"pass # continue if len(i) != 7: print(\"Skipping row %s\" % i) continue",
"possible_targets def find_last_rev(args, possible_revs): possible_revs.reverse() archive_url = mk_url(args.user, args.branch) for rev in possible_revs:",
"if i[0] == \"Link\": continue if i[0] != \"GitHub\": pass # continue if",
"{}\".format(out_filename)) urllib.request.urlretrieve(image_url, out_filename) return True def main(): args = parse_args() archive_url = mk_url(args.user,",
").read().decode('utf-8') rev_names = {} for i in csv.reader(data.splitlines(), dialect='excel'): print(len(i),i) if not i:",
"to download from.\", default=\"hdmi2usb\") parser.add_argument('--firmware', help=\"Firmware to download from.\", default=\"firmware\") parser.add_argument('--arch', default=\"lm32\", help=\"Soft-CPU",
"import urllib.request from collections import namedtuple from datetime import datetime class TargetNotFound(Exception): pass",
"for d in targets if d['type'] == 'dir'] print(\"Found targets: {}\".format(\", \".join(possible_targets))) if",
"action=\"store_const\", help=\"Get the latest version.\", const=\"unstable\") parser.add_argument('--target', help=\"Target to download from.\", default=\"hdmi2usb\") parser.add_argument('--firmware',",
"def get_rev_url(archive_url, rev): rev_url = \"{}{:s}/\".format(archive_url, str(rev)) return rev_url def get_platforms(args, rev_url): platforms",
"out_filename) return True def main(): args = parse_args() archive_url = mk_url(args.user, args.branch) possible_revs",
"__new__(cls, value): version, commits, githash = value.split('-') commits = int(commits) assert githash[0] ==",
"args.platform, rev, \", \".join(possible_archs))) sys.exit(1) return possible_archs def get_firmwares_url(args, archs_url): firmwares_url = \"{}{:s}/\".format(archs_url,",
"parser.add_argument('--platform', help='Get for a specific platform (board + expansion boards configuration).') parser.add_argument('--board', help='Alias",
"'rb')) except IOError: cache = {} return cache def save_cache(cache): pickle.dump(cache, open(cache_name, 'wb'))",
"\"https://github.com/{user}/HDMI2USB-firmware-prebuilt/raw/master/archive/{branch}/{rev}/{platform}/{target}/{arch}/{filename}\".format( user=args.user, branch=args.branch, rev=rev, platform=args.platform, target=args.target, arch=args.arch, filename=filename) print(\"Image URL: {}\".format(image_url)) return image_url",
"import os import pickle import sys import time import urllib.request from collections import",
"get_goog_sheet(): data = urllib.request.urlopen( \"https://docs.google.com/spreadsheets/d/e/2PACX-1vTmqEM-XXPW4oHrJMD7QrCeKOiq1CPng9skQravspmEmaCt04Kz4lTlQLFTyQyJhcjqzCc--eO2f11x/pub?output=csv\" ).read().decode('utf-8') rev_names = {} for i in csv.reader(data.splitlines(),",
"= [d['name'] for d in targets if d['type'] == 'dir'] print(\"Found targets: {}\".format(\",",
"details = { \"owner\": user, \"repo\": \"HDMI2USB-firmware-prebuilt\", \"branch\": branch, } archive_url = \"https://api.github.com/repos/{owner}/{repo}/contents/archive/{branch}/\".format(",
"firmwares_url = get_firmwares_url(args, archs_url) possible_firmwares = get_firmwares(args, firmwares_url) filename = get_filename(args, possible_firmwares) image_url",
"# assert name not in rev_names, \"{} is listed multiple times!\".format(name) rev_names[name] =",
"for target {} for platform {} at rev {} (found {})\". format(args.firmware, args.target,",
"possible_platforms = [d['name'] for d in platforms if d['type'] == 'dir'] print(\"Found platforms:",
"get_targets(args, rev, targets_url) print(\"found at rev {}\".format(rev)) return rev except TargetNotFound: continue def",
"\", \".join(possible_archs))) sys.exit(1) return possible_archs def get_firmwares_url(args, archs_url): firmwares_url = \"{}{:s}/\".format(archs_url, args.arch) return",
"def main(): args = parse_args() archive_url = mk_url(args.user, args.branch) possible_revs = get_revs(archive_url) rev",
"# TODO: use this rev instead. sys.exit(1) archs_url = get_archs_url(args, targets_url) possible_archs =",
"possible_archs = get_archs(args, archs_url) firmwares_url = get_firmwares_url(args, archs_url) possible_firmwares = get_firmwares(args, firmwares_url) filename",
"Make this work under Python 2 import argparse import csv import doctest import",
"rev in possible_revs: rev_url = get_rev_url(archive_url, rev) possible_platforms = get_platforms(args, rev_url) targets_url =",
"configuration).') parser.add_argument('--board', help='Alias for --platform.', dest=\"platform\") parser.add_argument('--channel', help=\"Get latest version from in a",
"'dir'] print(\"Found targets: {}\".format(\", \".join(possible_targets))) if args.target not in possible_targets: print(\"Did not find",
"ls_github(firmwares_url) possible_firmwares = [ d['name'] for d in firmwares if d['type'] == 'file'",
"from.\", default=\"firmware\") parser.add_argument('--arch', default=\"lm32\", help=\"Soft-CPU architecture to download from.\") parser.add_argument('--user', help='Github user to",
"return \"%s-%i-g%s\" % self doctest.testmod() def parse_args(): parser = argparse.ArgumentParser( description='Download prebuilt firmware')",
"return possible_platforms def get_targets_url(args, rev_url): targets_url = \"{}{:s}/\".format(rev_url, args.platform) return targets_url def get_targets(args,",
"get_platforms(args, rev_url): platforms = ls_github(rev_url) possible_platforms = [d['name'] for d in platforms if",
"if d['type'] == 'dir'] print(\"Found platforms: {}\".format(\", \".join(possible_platforms))) if args.platform not in possible_platforms:",
"if d['type'] == 'dir'] print(\"Found targets: {}\".format(\", \".join(possible_targets))) if args.target not in possible_targets:",
"ret = download(args, rev, filename, image_url) print(\"Done!\") return if __name__ == \"__main__\": main()",
"cache[url]['data'] else: while True: data = json.loads(urllib.request.urlopen(url).read().decode()) if \"message\" in data: print(\"Warning: {}\".format(data[\"message\"]))",
"rev, \", \".join(possible_platforms))) sys.exit(1) return possible_platforms def get_targets_url(args, rev_url): targets_url = \"{}{:s}/\".format(rev_url, args.platform)",
"expansion boards configuration).') parser.add_argument('--board', help='Alias for --platform.', dest=\"platform\") parser.add_argument('--channel', help=\"Get latest version from",
"download from.', default=\"timvideos\") parser.add_argument('--branch', help=\"Branch to download from.\", default=\"master\") parser.add_argument('-o', '--output', help=\"Output filename.\",",
"\".join(possible_archs))) sys.exit(1) return possible_archs def get_firmwares_url(args, archs_url): firmwares_url = \"{}{:s}/\".format(archs_url, args.arch) return firmwares_url",
"else: parts = os.path.splitext(filename) out_filename = \".\".join( list(parts[:-1]) + [str(rev), args.platform, args.target, args.arch,",
"possible_revs.reverse() archive_url = mk_url(args.user, args.branch) for rev in possible_revs: rev_url = get_rev_url(archive_url, rev)",
"rev_str, name, conf, notes, more_notes = i if not rev_str: continue print(rev_str, name)",
"return targets_url def get_targets(args, rev, targets_url): targets = ls_github(targets_url) possible_targets = [d['name'] for",
"archive_url = \"https://api.github.com/repos/{owner}/{repo}/contents/archive/{branch}/\".format( **details) return archive_url def get_revs(archive_url): # this changes as revs",
"if not rev_str: continue print(rev_str, name) rev = Version(rev_str) # assert rev in",
"--platform.', dest=\"platform\") parser.add_argument('--channel', help=\"Get latest version from in a specific channel ().\", default=\"unstable\")",
"print(\"Did not find {} in {}\".format(channel, rev_names)) sys.exit(1) rev = rev_names[channel] print(\"Channel {}",
"for i in csv.reader(data.splitlines(), dialect='excel'): print(len(i),i) if not i: continue if i[0] ==",
"for d in platforms if d['type'] == 'dir'] print(\"Found platforms: {}\".format(\", \".join(possible_platforms))) if",
"not rev_str: continue print(rev_str, name) rev = Version(rev_str) # assert rev in possible_revs",
"listed multiple times!\".format(name) rev_names[name] = rev return rev_names def get_rev(possible_revs,rev=None, channel=\"unstable\"): if not",
"parser.add_argument('-o', '--output', help=\"Output filename.\", ) args = parser.parse_args() assert args.platform assert args.rev or",
"str(v) 'v0.0.4-44-g0cd842f' \"\"\" def __new__(cls, value): version, commits, githash = value.split('-') commits =",
"filename=filename) print(\"Image URL: {}\".format(image_url)) return image_url def download(args, rev, filename, image_url): if args.output:",
"None or ( (datetime.now()-cache[url]['timestamp']).total_seconds() < cache_ttl)): data = cache[url]['data'] else: while True: data",
"print(\"rev: {}\".format(rev)) return rev def get_rev_url(archive_url, rev): rev_url = \"{}{:s}/\".format(archive_url, str(rev)) return rev_url",
"work under Python 2 import argparse import csv import doctest import json import",
"'dir'] print(\"Found archs: {}\".format(\", \".join(possible_archs))) if args.arch not in possible_archs: print( \"Did not",
"load_cache(): try: cache = pickle.load(open(cache_name, 'rb')) except IOError: cache = {} return cache",
"= {} for i in csv.reader(data.splitlines(), dialect='excel'): print(len(i),i) if not i: continue if",
"continue print(rev_str, name) rev = Version(rev_str) # assert rev in possible_revs # assert",
"firmwares_url = \"{}{:s}/\".format(archs_url, args.arch) return firmwares_url def get_firmwares(args, firmwares_url): firmwares = ls_github(firmwares_url) possible_firmwares",
"= \"{}{:s}/\".format(rev_url, args.platform) return targets_url def get_targets(args, rev, targets_url): targets = ls_github(targets_url) possible_targets",
"cache = {} return cache def save_cache(cache): pickle.dump(cache, open(cache_name, 'wb')) cache = load_cache()",
"urllib.request.urlretrieve(image_url, out_filename) return True def main(): args = parse_args() archive_url = mk_url(args.user, args.branch)",
"possible_revs.sort() return possible_revs def get_goog_sheet(): data = urllib.request.urlopen( \"https://docs.google.com/spreadsheets/d/e/2PACX-1vTmqEM-XXPW4oHrJMD7QrCeKOiq1CPng9skQravspmEmaCt04Kz4lTlQLFTyQyJhcjqzCc--eO2f11x/pub?output=csv\" ).read().decode('utf-8') rev_names = {}",
"download from.\", default=\"master\") parser.add_argument('-o', '--output', help=\"Output filename.\", ) args = parser.parse_args() assert args.platform",
"targets_url): archs_url = \"{}{:s}/\".format(targets_url, args.target) return archs_url def get_archs(args, archs_url): archs = ls_github(archs_url)",
"\"https://docs.google.com/spreadsheets/d/e/2PACX-1vTmqEM-XXPW4oHrJMD7QrCeKOiq1CPng9skQravspmEmaCt04Kz4lTlQLFTyQyJhcjqzCc--eO2f11x/pub?output=csv\" ).read().decode('utf-8') rev_names = {} for i in csv.reader(data.splitlines(), dialect='excel'): print(len(i),i) if not",
"continue if i[0] == \"Link\": continue if i[0] != \"GitHub\": pass # continue",
"def download(args, rev, filename, image_url): if args.output: out_filename = args.output else: parts =",
"to download from.\") parser.add_argument('--user', help='Github user to download from.', default=\"timvideos\") parser.add_argument('--branch', help=\"Branch to",
"possible_platforms def get_targets_url(args, rev_url): targets_url = \"{}{:s}/\".format(rev_url, args.platform) return targets_url def get_targets(args, rev,",
"archive_url = mk_url(args.user, args.branch) for rev in possible_revs: rev_url = get_rev_url(archive_url, rev) possible_platforms",
"FIXME: Move cache to a class or find a package. cache_name = \"github.pickle\"",
"assert args.platform assert args.rev or args.channel assert args.target return args def mk_url(user, branch):",
"\".\".join( list(parts[:-1]) + [str(rev), args.platform, args.target, args.arch, parts[-1][1:]]) print(\"Downloading to: {}\".format(out_filename)) urllib.request.urlretrieve(image_url, out_filename)",
"FIXME: Make this work under Python 2 import argparse import csv import doctest",
"find target {} for platform {} at rev {} (found {})\". format(args.target, args.platform,",
"firmwares = ls_github(firmwares_url) possible_firmwares = [ d['name'] for d in firmwares if d['type']",
"d in archs if d['type'] == 'dir'] print(\"Found archs: {}\".format(\", \".join(possible_archs))) if args.arch",
"def parse_args(): parser = argparse.ArgumentParser( description='Download prebuilt firmware') parser.add_argument('--rev', help='Get a specific version.')",
"\"{}{:s}/\".format(rev_url, args.platform) return targets_url def get_targets(args, rev, targets_url): targets = ls_github(targets_url) possible_targets =",
"assert args.target return args def mk_url(user, branch): details = { \"owner\": user, \"repo\":",
"import doctest import json import os import pickle import sys import time import",
"break cache[url] = { 'timestamp': datetime.now(), 'data': data } save_cache(cache) return data _Version",
"argparse.ArgumentParser( description='Download prebuilt firmware') parser.add_argument('--rev', help='Get a specific version.') parser.add_argument('--platform', help='Get for a",
"return image_url def download(args, rev, filename, image_url): if args.output: out_filename = args.output else:",
"Move cache to a class or find a package. cache_name = \"github.pickle\" def",
"return possible_firmwares def get_filename(args, possible_firmwares): filename = None for f in possible_firmwares: if",
"mk_url(args.user, args.branch) possible_revs = get_revs(archive_url) rev = get_rev(possible_revs, args.rev, args.channel) rev_url = get_rev_url(archive_url,",
"args.target, args.platform, rev, \", \".join(possible_archs))) sys.exit(1) return possible_archs def get_firmwares_url(args, archs_url): firmwares_url =",
"args.arch, parts[-1][1:]]) print(\"Downloading to: {}\".format(out_filename)) urllib.request.urlretrieve(image_url, out_filename) return True def main(): args =",
"arch {} for target {} for platform {} at rev {} (found {})\".",
"possible_firmwares def get_filename(args, possible_firmwares): filename = None for f in possible_firmwares: if f.endswith(\"{}.bin\".format(args.firmware)):",
"target {} for platform {} at rev {} (found {})\". format(args.firmware, args.target, args.platform,",
"f break if not filename: print( \"Did not find firmware {} for target",
"+ expansion boards configuration).') parser.add_argument('--board', help='Alias for --platform.', dest=\"platform\") parser.add_argument('--channel', help=\"Get latest version",
"sys.exit(1) return possible_platforms def get_targets_url(args, rev_url): targets_url = \"{}{:s}/\".format(rev_url, args.platform) return targets_url def",
"in possible_revs # assert name not in rev_names, \"{} is listed multiple times!\".format(name)",
"print(\"Found archs: {}\".format(\", \".join(possible_archs))) if args.arch not in possible_archs: print( \"Did not find",
"= get_archs(args, archs_url) firmwares_url = get_firmwares_url(args, archs_url) possible_firmwares = get_firmwares(args, firmwares_url) filename =",
"commits=44, hash='0cd842f') >>> str(v) 'v0.0.4-44-g0cd842f' \"\"\" def __new__(cls, value): version, commits, githash =",
"added. # builds take over 20 min, so refresh every 20 min. print(\"revs",
"at rev {}\".format(channel, rev)) else: rev = Version(rev) assert rev in possible_revs, \"{}",
"\"\"\" def __new__(cls, value): version, commits, githash = value.split('-') commits = int(commits) assert",
"print(\"Skipping row %s\" % i) continue _, _, rev_str, name, conf, notes, more_notes",
"\".join(possible_targets))) raise TargetNotFound() return possible_targets def find_last_rev(args, possible_revs): possible_revs.reverse() archive_url = mk_url(args.user, args.branch)",
"refresh every 20 min. print(\"revs = ls_github(archive_url) {}\".format(archive_url)) revs = ls_github(archive_url, cache_ttl=60*20) possible_revs",
"rev, filename) ret = download(args, rev, filename, image_url) print(\"Done!\") return if __name__ ==",
"rev, \", \".join(possible_firmwares))) sys.exit(1) return filename def get_image_url(args, rev, filename): image_url = \"https://github.com/{user}/HDMI2USB-firmware-prebuilt/raw/master/archive/{branch}/{rev}/{platform}/{target}/{arch}/{filename}\".format(",
"{}\".format(\", \".join(possible_targets))) if args.target not in possible_targets: print(\"Did not find target {} for",
"firmwares_url) filename = get_filename(args, possible_firmwares) image_url = get_image_url(args, rev, filename) ret = download(args,",
"rev, targets_url): targets = ls_github(targets_url) possible_targets = [d['name'] for d in targets if",
"not in rev_names, \"{} is listed multiple times!\".format(name) rev_names[name] = rev return rev_names",
"boards configuration).') parser.add_argument('--board', help='Alias for --platform.', dest=\"platform\") parser.add_argument('--channel', help=\"Get latest version from in",
"args.target) return archs_url def get_archs(args, archs_url): archs = ls_github(archs_url) possible_archs = [d['name'] for",
"find_last_rev(args, possible_revs): possible_revs.reverse() archive_url = mk_url(args.user, args.branch) for rev in possible_revs: rev_url =",
"help=\"Firmware to download from.\", default=\"firmware\") parser.add_argument('--arch', default=\"lm32\", help=\"Soft-CPU architecture to download from.\") parser.add_argument('--user',",
"ls_github(rev_url) possible_platforms = [d['name'] for d in platforms if d['type'] == 'dir'] print(\"Found",
"platform (board + expansion boards configuration).') parser.add_argument('--board', help='Alias for --platform.', dest=\"platform\") parser.add_argument('--channel', help=\"Get",
"help='Alias for --channel.', dest=\"channel\") parser.add_argument('--latest', dest=\"channel\", action=\"store_const\", help=\"Get the latest version.\", const=\"unstable\") parser.add_argument('--target',",
"firmwares_url): firmwares = ls_github(firmwares_url) possible_firmwares = [ d['name'] for d in firmwares if",
"< cache_ttl)): data = cache[url]['data'] else: while True: data = json.loads(urllib.request.urlopen(url).read().decode()) if \"message\"",
"args.arch not in possible_archs: print( \"Did not find arch {} for target {}",
"possible_platforms = get_platforms(args, rev_url) targets_url = get_targets_url(args, rev_url) try: possible_targets = get_targets(args, rev,",
"= ls_github(archive_url) {}\".format(archive_url)) revs = ls_github(archive_url, cache_ttl=60*20) possible_revs = [Version(d['name']) for d in",
"= namedtuple(\"Version\", (\"version\", \"commits\", \"hash\")) class Version(_Version): \"\"\" >>> v = Version(\"v0.0.4-44-g0cd842f\") >>>",
"rev_names = {} for i in csv.reader(data.splitlines(), dialect='excel'): print(len(i),i) if not i: continue",
"not filename: print( \"Did not find firmware {} for target {} for platform",
"filename = None for f in possible_firmwares: if f.endswith(\"{}.bin\".format(args.firmware)): filename = f break",
"not in possible_platforms: print(\"Did not find platform {} at rev {} (found {})\".format(",
"commits, githash[1:]) def __str__(self): return \"%s-%i-g%s\" % self doctest.testmod() def parse_args(): parser =",
"default=\"timvideos\") parser.add_argument('--branch', help=\"Branch to download from.\", default=\"master\") parser.add_argument('-o', '--output', help=\"Output filename.\", ) args",
"\"commits\", \"hash\")) class Version(_Version): \"\"\" >>> v = Version(\"v0.0.4-44-g0cd842f\") >>> v Version(version='v0.0.4', commits=44,",
"d['name'].endswith('.bin') ] print(\"Found firmwares: {}\".format(\", \".join(possible_firmwares))) return possible_firmwares def get_filename(args, possible_firmwares): filename =",
"archs: {}\".format(\", \".join(possible_archs))) if args.arch not in possible_archs: print( \"Did not find arch",
"parser = argparse.ArgumentParser( description='Download prebuilt firmware') parser.add_argument('--rev', help='Get a specific version.') parser.add_argument('--platform', help='Get",
"print(\"revs = ls_github(archive_url) {}\".format(archive_url)) revs = ls_github(archive_url, cache_ttl=60*20) possible_revs = [Version(d['name']) for d",
"d in revs if d['type'] == 'dir'] possible_revs.sort() return possible_revs def get_goog_sheet(): data",
"from.\") parser.add_argument('--user', help='Github user to download from.', default=\"timvideos\") parser.add_argument('--branch', help=\"Branch to download from.\",",
"parts = os.path.splitext(filename) out_filename = \".\".join( list(parts[:-1]) + [str(rev), args.platform, args.target, args.arch, parts[-1][1:]])",
"data _Version = namedtuple(\"Version\", (\"version\", \"commits\", \"hash\")) class Version(_Version): \"\"\" >>> v =",
"'dir'] print(\"Found platforms: {}\".format(\", \".join(possible_platforms))) if args.platform not in possible_platforms: print(\"Did not find",
"(board + expansion boards configuration).') parser.add_argument('--board', help='Alias for --platform.', dest=\"platform\") parser.add_argument('--channel', help=\"Get latest",
"def get_revs(archive_url): # this changes as revs are added. # builds take over",
"not in rev_names: print(\"Did not find {} in {}\".format(channel, rev_names)) sys.exit(1) rev =",
"help='Get for a specific platform (board + expansion boards configuration).') parser.add_argument('--board', help='Alias for",
"archs_url) firmwares_url = get_firmwares_url(args, archs_url) possible_firmwares = get_firmwares(args, firmwares_url) filename = get_filename(args, possible_firmwares)",
"a package. cache_name = \"github.pickle\" def load_cache(): try: cache = pickle.load(open(cache_name, 'rb')) except",
"firmware {} for target {} for platform {} at rev {} (found {})\".",
"continue else: break cache[url] = { 'timestamp': datetime.now(), 'data': data } save_cache(cache) return",
"\", \".join(possible_targets))) raise TargetNotFound() return possible_targets def find_last_rev(args, possible_revs): possible_revs.reverse() archive_url = mk_url(args.user,",
"{} for target {} for platform {} at rev {} (found {})\". format(args.arch,",
"firmwares_url def get_firmwares(args, firmwares_url): firmwares = ls_github(firmwares_url) possible_firmwares = [ d['name'] for d",
"version, commits, githash = value.split('-') commits = int(commits) assert githash[0] == 'g' return",
"continue if len(i) != 7: print(\"Skipping row %s\" % i) continue _, _,",
"targets = ls_github(targets_url) possible_targets = [d['name'] for d in targets if d['type'] ==",
"download from.\") parser.add_argument('--user', help='Github user to download from.', default=\"timvideos\") parser.add_argument('--branch', help=\"Branch to download",
"description='Download prebuilt firmware') parser.add_argument('--rev', help='Get a specific version.') parser.add_argument('--platform', help='Get for a specific",
"download from.\", default=\"firmware\") parser.add_argument('--arch', default=\"lm32\", help=\"Soft-CPU architecture to download from.\") parser.add_argument('--user', help='Github user",
"as revs are added. # builds take over 20 min, so refresh every",
"this work under Python 2 import argparse import csv import doctest import json",
"= \"{}{:s}/\".format(archive_url, str(rev)) return rev_url def get_platforms(args, rev_url): platforms = ls_github(rev_url) possible_platforms =",
"a specific version.') parser.add_argument('--platform', help='Get for a specific platform (board + expansion boards",
"row %s\" % i) continue _, _, rev_str, name, conf, notes, more_notes =",
"at rev {} (found {})\". format(args.firmware, args.target, args.platform, rev, \", \".join(possible_firmwares))) sys.exit(1) return",
"= urllib.request.urlopen( \"https://docs.google.com/spreadsheets/d/e/2PACX-1vTmqEM-XXPW4oHrJMD7QrCeKOiq1CPng9skQravspmEmaCt04Kz4lTlQLFTyQyJhcjqzCc--eO2f11x/pub?output=csv\" ).read().decode('utf-8') rev_names = {} for i in csv.reader(data.splitlines(), dialect='excel'): print(len(i),i)",
"\"message\" in data: print(\"Warning: {}\".format(data[\"message\"])) time.sleep(1) continue else: break cache[url] = { 'timestamp':",
"return possible_targets def find_last_rev(args, possible_revs): possible_revs.reverse() archive_url = mk_url(args.user, args.branch) for rev in",
"d['type'] == 'dir'] print(\"Found archs: {}\".format(\", \".join(possible_archs))) if args.arch not in possible_archs: print(",
"filename def get_image_url(args, rev, filename): image_url = \"https://github.com/{user}/HDMI2USB-firmware-prebuilt/raw/master/archive/{branch}/{rev}/{platform}/{target}/{arch}/{filename}\".format( user=args.user, branch=args.branch, rev=rev, platform=args.platform, target=args.target,",
"d in targets if d['type'] == 'dir'] print(\"Found targets: {}\".format(\", \".join(possible_targets))) if args.target",
"get_platforms(args, rev_url) targets_url = get_targets_url(args, rev_url) try: possible_targets = get_targets(args, rev, targets_url) print(\"found",
"except TargetNotFound: continue def get_archs_url(args, targets_url): archs_url = \"{}{:s}/\".format(targets_url, args.target) return archs_url def",
"possible_archs: print( \"Did not find arch {} for target {} for platform {}",
"# continue if len(i) != 7: print(\"Skipping row %s\" % i) continue _,",
"datetime class TargetNotFound(Exception): pass def ls_github(url, cache_ttl=None): # FIXME: Move cache to a",
"rev, filename): image_url = \"https://github.com/{user}/HDMI2USB-firmware-prebuilt/raw/master/archive/{branch}/{rev}/{platform}/{target}/{arch}/{filename}\".format( user=args.user, branch=args.branch, rev=rev, platform=args.platform, target=args.target, arch=args.arch, filename=filename) print(\"Image",
"user, \"repo\": \"HDMI2USB-firmware-prebuilt\", \"branch\": branch, } archive_url = \"https://api.github.com/repos/{owner}/{repo}/contents/archive/{branch}/\".format( **details) return archive_url def",
"possible_platforms: print(\"Did not find platform {} at rev {} (found {})\".format( args.platform, rev,",
"not find firmware {} for target {} for platform {} at rev {}",
"platform {} at rev {} (found {})\". format(args.target, args.platform, rev, \", \".join(possible_targets))) raise",
"firmwares if d['type'] == 'file' and d['name'].endswith('.bin') ] print(\"Found firmwares: {}\".format(\", \".join(possible_firmwares))) return",
"in data: print(\"Warning: {}\".format(data[\"message\"])) time.sleep(1) continue else: break cache[url] = { 'timestamp': datetime.now(),",
"{} for platform {} at rev {} (found {})\". format(args.arch, args.target, args.platform, rev,",
"value): version, commits, githash = value.split('-') commits = int(commits) assert githash[0] == 'g'",
"default=\"master\") parser.add_argument('-o', '--output', help=\"Output filename.\", ) args = parser.parse_args() assert args.platform assert args.rev",
"find platform {} at rev {} (found {})\".format( args.platform, rev, \", \".join(possible_platforms))) sys.exit(1)",
"args.arch) return firmwares_url def get_firmwares(args, firmwares_url): firmwares = ls_github(firmwares_url) possible_firmwares = [ d['name']",
"rev {} (found {})\".format( args.platform, rev, \", \".join(possible_platforms))) sys.exit(1) return possible_platforms def get_targets_url(args,",
"args.rev or args.channel assert args.target return args def mk_url(user, branch): details = {",
"{}\".format(\", \".join(possible_archs))) if args.arch not in possible_archs: print( \"Did not find arch {}",
"len(i) != 7: print(\"Skipping row %s\" % i) continue _, _, rev_str, name,",
"assert name not in rev_names, \"{} is listed multiple times!\".format(name) rev_names[name] = rev",
"csv.reader(data.splitlines(), dialect='excel'): print(len(i),i) if not i: continue if i[0] == \"Link\": continue if",
"\".join(possible_targets))) if args.target not in possible_targets: print(\"Did not find target {} for platform",
"cache and (cache_ttl is None or ( (datetime.now()-cache[url]['timestamp']).total_seconds() < cache_ttl)): data = cache[url]['data']",
"data = cache[url]['data'] else: while True: data = json.loads(urllib.request.urlopen(url).read().decode()) if \"message\" in data:",
"the latest version.\", const=\"unstable\") parser.add_argument('--target', help=\"Target to download from.\", default=\"hdmi2usb\") parser.add_argument('--firmware', help=\"Firmware to",
"().\", default=\"unstable\") parser.add_argument('--tag', help='Alias for --channel.', dest=\"channel\") parser.add_argument('--latest', dest=\"channel\", action=\"store_const\", help=\"Get the latest",
"(datetime.now()-cache[url]['timestamp']).total_seconds() < cache_ttl)): data = cache[url]['data'] else: while True: data = json.loads(urllib.request.urlopen(url).read().decode()) if",
"= ls_github(targets_url) possible_targets = [d['name'] for d in targets if d['type'] == 'dir']",
"filename, image_url): if args.output: out_filename = args.output else: parts = os.path.splitext(filename) out_filename =",
"possible_targets = get_targets(args, rev, targets_url) print(\"found at rev {}\".format(rev)) return rev except TargetNotFound:",
"datetime.now(), 'data': data } save_cache(cache) return data _Version = namedtuple(\"Version\", (\"version\", \"commits\", \"hash\"))",
"use this rev instead. sys.exit(1) archs_url = get_archs_url(args, targets_url) possible_archs = get_archs(args, archs_url)",
"hash='0cd842f') >>> str(v) 'v0.0.4-44-g0cd842f' \"\"\" def __new__(cls, value): version, commits, githash = value.split('-')",
"at rev {}\".format(rev)) return rev except TargetNotFound: continue def get_archs_url(args, targets_url): archs_url =",
"= possible_revs[-1] else: rev_names = get_goog_sheet() if channel not in rev_names: print(\"Did not",
"def get_archs(args, archs_url): archs = ls_github(archs_url) possible_archs = [d['name'] for d in archs",
"# FIXME: Make this work under Python 2 import argparse import csv import",
"return rev except TargetNotFound: continue def get_archs_url(args, targets_url): archs_url = \"{}{:s}/\".format(targets_url, args.target) return",
"data = urllib.request.urlopen( \"https://docs.google.com/spreadsheets/d/e/2PACX-1vTmqEM-XXPW4oHrJMD7QrCeKOiq1CPng9skQravspmEmaCt04Kz4lTlQLFTyQyJhcjqzCc--eO2f11x/pub?output=csv\" ).read().decode('utf-8') rev_names = {} for i in csv.reader(data.splitlines(), dialect='excel'):",
"\"{}{:s}/\".format(archive_url, str(rev)) return rev_url def get_platforms(args, rev_url): platforms = ls_github(rev_url) possible_platforms = [d['name']",
"archs_url = \"{}{:s}/\".format(targets_url, args.target) return archs_url def get_archs(args, archs_url): archs = ls_github(archs_url) possible_archs",
"if not i: continue if i[0] == \"Link\": continue if i[0] != \"GitHub\":",
"conf, notes, more_notes = i if not rev_str: continue print(rev_str, name) rev =",
"else: rev_names = get_goog_sheet() if channel not in rev_names: print(\"Did not find {}",
"def get_firmwares(args, firmwares_url): firmwares = ls_github(firmwares_url) possible_firmwares = [ d['name'] for d in",
"{} return cache def save_cache(cache): pickle.dump(cache, open(cache_name, 'wb')) cache = load_cache() if url",
"if not rev: if channel == \"unstable\": rev = possible_revs[-1] else: rev_names =",
"print(rev_str, name) rev = Version(rev_str) # assert rev in possible_revs # assert name",
"return data _Version = namedtuple(\"Version\", (\"version\", \"commits\", \"hash\")) class Version(_Version): \"\"\" >>> v",
"Version(rev_str) # assert rev in possible_revs # assert name not in rev_names, \"{}",
"for target {} for platform {} at rev {} (found {})\". format(args.arch, args.target,",
"namedtuple from datetime import datetime class TargetNotFound(Exception): pass def ls_github(url, cache_ttl=None): # FIXME:",
"if f.endswith(\"{}.bin\".format(args.firmware)): filename = f break if not filename: print( \"Did not find",
"get_filename(args, possible_firmwares) image_url = get_image_url(args, rev, filename) ret = download(args, rev, filename, image_url)",
"import pickle import sys import time import urllib.request from collections import namedtuple from",
"( (datetime.now()-cache[url]['timestamp']).total_seconds() < cache_ttl)): data = cache[url]['data'] else: while True: data = json.loads(urllib.request.urlopen(url).read().decode())",
"if channel not in rev_names: print(\"Did not find {} in {}\".format(channel, rev_names)) sys.exit(1)",
"rev in possible_revs, \"{} is not found in {}\".format( rev, possible_revs) print(\"rev: {}\".format(rev))",
"[ d['name'] for d in firmwares if d['type'] == 'file' and d['name'].endswith('.bin') ]",
"to download from.\", default=\"master\") parser.add_argument('-o', '--output', help=\"Output filename.\", ) args = parser.parse_args() assert",
"IOError: cache = {} return cache def save_cache(cache): pickle.dump(cache, open(cache_name, 'wb')) cache =",
"time import urllib.request from collections import namedtuple from datetime import datetime class TargetNotFound(Exception):",
"else: while True: data = json.loads(urllib.request.urlopen(url).read().decode()) if \"message\" in data: print(\"Warning: {}\".format(data[\"message\"])) time.sleep(1)",
"in rev_names, \"{} is listed multiple times!\".format(name) rev_names[name] = rev return rev_names def",
"rev_names: print(\"Did not find {} in {}\".format(channel, rev_names)) sys.exit(1) rev = rev_names[channel] print(\"Channel",
"image_url = \"https://github.com/{user}/HDMI2USB-firmware-prebuilt/raw/master/archive/{branch}/{rev}/{platform}/{target}/{arch}/{filename}\".format( user=args.user, branch=args.branch, rev=rev, platform=args.platform, target=args.target, arch=args.arch, filename=filename) print(\"Image URL: {}\".format(image_url))",
"commits, githash = value.split('-') commits = int(commits) assert githash[0] == 'g' return _Version.__new__(cls,",
"return rev_names def get_rev(possible_revs,rev=None, channel=\"unstable\"): if not rev: if channel == \"unstable\": rev",
"\"https://api.github.com/repos/{owner}/{repo}/contents/archive/{branch}/\".format( **details) return archive_url def get_revs(archive_url): # this changes as revs are added.",
"d in platforms if d['type'] == 'dir'] print(\"Found platforms: {}\".format(\", \".join(possible_platforms))) if args.platform",
"print(\"Found targets: {}\".format(\", \".join(possible_targets))) if args.target not in possible_targets: print(\"Did not find target",
"[str(rev), args.platform, args.target, args.arch, parts[-1][1:]]) print(\"Downloading to: {}\".format(out_filename)) urllib.request.urlretrieve(image_url, out_filename) return True def",
"load_cache() if url in cache and (cache_ttl is None or ( (datetime.now()-cache[url]['timestamp']).total_seconds() <",
"archs_url) possible_firmwares = get_firmwares(args, firmwares_url) filename = get_filename(args, possible_firmwares) image_url = get_image_url(args, rev,",
"{} (found {})\". format(args.firmware, args.target, args.platform, rev, \", \".join(possible_firmwares))) sys.exit(1) return filename def",
"platforms: {}\".format(\", \".join(possible_platforms))) if args.platform not in possible_platforms: print(\"Did not find platform {}",
"in possible_revs: rev_url = get_rev_url(archive_url, rev) possible_platforms = get_platforms(args, rev_url) targets_url = get_targets_url(args,",
"targets: {}\".format(\", \".join(possible_targets))) if args.target not in possible_targets: print(\"Did not find target {}",
"package. cache_name = \"github.pickle\" def load_cache(): try: cache = pickle.load(open(cache_name, 'rb')) except IOError:",
"or find a package. cache_name = \"github.pickle\" def load_cache(): try: cache = pickle.load(open(cache_name,",
"in a specific channel ().\", default=\"unstable\") parser.add_argument('--tag', help='Alias for --channel.', dest=\"channel\") parser.add_argument('--latest', dest=\"channel\",",
"changes as revs are added. # builds take over 20 min, so refresh",
"{}\".format(data[\"message\"])) time.sleep(1) continue else: break cache[url] = { 'timestamp': datetime.now(), 'data': data }",
"dialect='excel'): print(len(i),i) if not i: continue if i[0] == \"Link\": continue if i[0]",
"rev = rev_names[channel] print(\"Channel {} is at rev {}\".format(channel, rev)) else: rev =",
"possible_revs) print(\"rev: {}\".format(rev)) return rev def get_rev_url(archive_url, rev): rev_url = \"{}{:s}/\".format(archive_url, str(rev)) return",
"continue _, _, rev_str, name, conf, notes, more_notes = i if not rev_str:",
"builds take over 20 min, so refresh every 20 min. print(\"revs = ls_github(archive_url)",
"filename = get_filename(args, possible_firmwares) image_url = get_image_url(args, rev, filename) ret = download(args, rev,",
"parser.add_argument('--tag', help='Alias for --channel.', dest=\"channel\") parser.add_argument('--latest', dest=\"channel\", action=\"store_const\", help=\"Get the latest version.\", const=\"unstable\")",
"break if not filename: print( \"Did not find firmware {} for target {}",
"= { \"owner\": user, \"repo\": \"HDMI2USB-firmware-prebuilt\", \"branch\": branch, } archive_url = \"https://api.github.com/repos/{owner}/{repo}/contents/archive/{branch}/\".format( **details)",
"args.branch) possible_revs = get_revs(archive_url) rev = get_rev(possible_revs, args.rev, args.channel) rev_url = get_rev_url(archive_url, rev)",
"'v0.0.4-44-g0cd842f' \"\"\" def __new__(cls, value): version, commits, githash = value.split('-') commits = int(commits)",
"python # FIXME: Make this work under Python 2 import argparse import csv",
"help=\"Target to download from.\", default=\"hdmi2usb\") parser.add_argument('--firmware', help=\"Firmware to download from.\", default=\"firmware\") parser.add_argument('--arch', default=\"lm32\",",
"name not in rev_names, \"{} is listed multiple times!\".format(name) rev_names[name] = rev return",
"print(\"Image URL: {}\".format(image_url)) return image_url def download(args, rev, filename, image_url): if args.output: out_filename",
"format(args.firmware, args.target, args.platform, rev, \", \".join(possible_firmwares))) sys.exit(1) return filename def get_image_url(args, rev, filename):",
"a specific channel ().\", default=\"unstable\") parser.add_argument('--tag', help='Alias for --channel.', dest=\"channel\") parser.add_argument('--latest', dest=\"channel\", action=\"store_const\",",
"= None for f in possible_firmwares: if f.endswith(\"{}.bin\".format(args.firmware)): filename = f break if",
"targets_url): targets = ls_github(targets_url) possible_targets = [d['name'] for d in targets if d['type']",
"parser.add_argument('--channel', help=\"Get latest version from in a specific channel ().\", default=\"unstable\") parser.add_argument('--tag', help='Alias",
"parse_args(): parser = argparse.ArgumentParser( description='Download prebuilt firmware') parser.add_argument('--rev', help='Get a specific version.') parser.add_argument('--platform',",
"args.target not in possible_targets: print(\"Did not find target {} for platform {} at",
"= get_rev(possible_revs, args.rev, args.channel) rev_url = get_rev_url(archive_url, rev) possible_platforms = get_platforms(args, rev_url) targets_url",
"\"%s-%i-g%s\" % self doctest.testmod() def parse_args(): parser = argparse.ArgumentParser( description='Download prebuilt firmware') parser.add_argument('--rev',",
"\"Did not find firmware {} for target {} for platform {} at rev",
"return archive_url def get_revs(archive_url): # this changes as revs are added. # builds",
"% self doctest.testmod() def parse_args(): parser = argparse.ArgumentParser( description='Download prebuilt firmware') parser.add_argument('--rev', help='Get",
"rev = possible_revs[-1] else: rev_names = get_goog_sheet() if channel not in rev_names: print(\"Did",
"d['type'] == 'dir'] possible_revs.sort() return possible_revs def get_goog_sheet(): data = urllib.request.urlopen( \"https://docs.google.com/spreadsheets/d/e/2PACX-1vTmqEM-XXPW4oHrJMD7QrCeKOiq1CPng9skQravspmEmaCt04Kz4lTlQLFTyQyJhcjqzCc--eO2f11x/pub?output=csv\" ).read().decode('utf-8')",
"i) continue _, _, rev_str, name, conf, notes, more_notes = i if not",
"= [Version(d['name']) for d in revs if d['type'] == 'dir'] possible_revs.sort() return possible_revs",
"\"{} is listed multiple times!\".format(name) rev_names[name] = rev return rev_names def get_rev(possible_revs,rev=None, channel=\"unstable\"):",
"args.channel assert args.target return args def mk_url(user, branch): details = { \"owner\": user,",
"continue def get_archs_url(args, targets_url): archs_url = \"{}{:s}/\".format(targets_url, args.target) return archs_url def get_archs(args, archs_url):",
"return True def main(): args = parse_args() archive_url = mk_url(args.user, args.branch) possible_revs =",
"\", \".join(possible_firmwares))) sys.exit(1) return filename def get_image_url(args, rev, filename): image_url = \"https://github.com/{user}/HDMI2USB-firmware-prebuilt/raw/master/archive/{branch}/{rev}/{platform}/{target}/{arch}/{filename}\".format( user=args.user,",
"\"branch\": branch, } archive_url = \"https://api.github.com/repos/{owner}/{repo}/contents/archive/{branch}/\".format( **details) return archive_url def get_revs(archive_url): # this",
"platforms = ls_github(rev_url) possible_platforms = [d['name'] for d in platforms if d['type'] ==",
"URL: {}\".format(image_url)) return image_url def download(args, rev, filename, image_url): if args.output: out_filename =",
"\"hash\")) class Version(_Version): \"\"\" >>> v = Version(\"v0.0.4-44-g0cd842f\") >>> v Version(version='v0.0.4', commits=44, hash='0cd842f')",
"args.platform) return targets_url def get_targets(args, rev, targets_url): targets = ls_github(targets_url) possible_targets = [d['name']",
"= \".\".join( list(parts[:-1]) + [str(rev), args.platform, args.target, args.arch, parts[-1][1:]]) print(\"Downloading to: {}\".format(out_filename)) urllib.request.urlretrieve(image_url,",
"= \"github.pickle\" def load_cache(): try: cache = pickle.load(open(cache_name, 'rb')) except IOError: cache =",
"def mk_url(user, branch): details = { \"owner\": user, \"repo\": \"HDMI2USB-firmware-prebuilt\", \"branch\": branch, }",
"{}\".format(archive_url)) revs = ls_github(archive_url, cache_ttl=60*20) possible_revs = [Version(d['name']) for d in revs if",
"cache = pickle.load(open(cache_name, 'rb')) except IOError: cache = {} return cache def save_cache(cache):",
"if args.arch not in possible_archs: print( \"Did not find arch {} for target",
"find firmware {} for target {} for platform {} at rev {} (found",
"archs_url): archs = ls_github(archs_url) possible_archs = [d['name'] for d in archs if d['type']",
"branch): details = { \"owner\": user, \"repo\": \"HDMI2USB-firmware-prebuilt\", \"branch\": branch, } archive_url =",
"possible_archs = [d['name'] for d in archs if d['type'] == 'dir'] print(\"Found archs:",
"def get_filename(args, possible_firmwares): filename = None for f in possible_firmwares: if f.endswith(\"{}.bin\".format(args.firmware)): filename",
"format(args.target, args.platform, rev, \", \".join(possible_targets))) raise TargetNotFound() return possible_targets def find_last_rev(args, possible_revs): possible_revs.reverse()",
"is at rev {}\".format(channel, rev)) else: rev = Version(rev) assert rev in possible_revs,",
"{}\".format(channel, rev)) else: rev = Version(rev) assert rev in possible_revs, \"{} is not",
"= get_targets_url(args, rev_url) try: possible_targets = get_targets(args, rev, targets_url) print(\"found at rev {}\".format(rev))",
"return possible_revs def get_goog_sheet(): data = urllib.request.urlopen( \"https://docs.google.com/spreadsheets/d/e/2PACX-1vTmqEM-XXPW4oHrJMD7QrCeKOiq1CPng9skQravspmEmaCt04Kz4lTlQLFTyQyJhcjqzCc--eO2f11x/pub?output=csv\" ).read().decode('utf-8') rev_names = {} for",
"target {} for platform {} at rev {} (found {})\". format(args.arch, args.target, args.platform,",
"targets_url) print(\"found at rev {}\".format(rev)) return rev except TargetNotFound: continue def get_archs_url(args, targets_url):",
"i if not rev_str: continue print(rev_str, name) rev = Version(rev_str) # assert rev",
"branch, } archive_url = \"https://api.github.com/repos/{owner}/{repo}/contents/archive/{branch}/\".format( **details) return archive_url def get_revs(archive_url): # this changes",
"in revs if d['type'] == 'dir'] possible_revs.sort() return possible_revs def get_goog_sheet(): data =",
"\".join(possible_platforms))) sys.exit(1) return possible_platforms def get_targets_url(args, rev_url): targets_url = \"{}{:s}/\".format(rev_url, args.platform) return targets_url",
"TargetNotFound: rev = find_last_rev(args, possible_revs) # TODO: use this rev instead. sys.exit(1) archs_url",
"args.channel) rev_url = get_rev_url(archive_url, rev) possible_platforms = get_platforms(args, rev_url) targets_url = get_targets_url(args, rev_url)",
"download(args, rev, filename, image_url): if args.output: out_filename = args.output else: parts = os.path.splitext(filename)",
"print(\"Warning: {}\".format(data[\"message\"])) time.sleep(1) continue else: break cache[url] = { 'timestamp': datetime.now(), 'data': data",
"TargetNotFound(Exception): pass def ls_github(url, cache_ttl=None): # FIXME: Move cache to a class or",
"pickle.load(open(cache_name, 'rb')) except IOError: cache = {} return cache def save_cache(cache): pickle.dump(cache, open(cache_name,",
"specific channel ().\", default=\"unstable\") parser.add_argument('--tag', help='Alias for --channel.', dest=\"channel\") parser.add_argument('--latest', dest=\"channel\", action=\"store_const\", help=\"Get",
"not find target {} for platform {} at rev {} (found {})\". format(args.target,",
"{} at rev {} (found {})\". format(args.target, args.platform, rev, \", \".join(possible_targets))) raise TargetNotFound()",
"not rev: if channel == \"unstable\": rev = possible_revs[-1] else: rev_names = get_goog_sheet()",
"class TargetNotFound(Exception): pass def ls_github(url, cache_ttl=None): # FIXME: Move cache to a class",
"get_revs(archive_url) rev = get_rev(possible_revs, args.rev, args.channel) rev_url = get_rev_url(archive_url, rev) possible_platforms = get_platforms(args,",
"= Version(rev_str) # assert rev in possible_revs # assert name not in rev_names,",
"get_rev_url(archive_url, rev): rev_url = \"{}{:s}/\".format(archive_url, str(rev)) return rev_url def get_platforms(args, rev_url): platforms =",
"parser.add_argument('--user', help='Github user to download from.', default=\"timvideos\") parser.add_argument('--branch', help=\"Branch to download from.\", default=\"master\")",
"archs_url): firmwares_url = \"{}{:s}/\".format(archs_url, args.arch) return firmwares_url def get_firmwares(args, firmwares_url): firmwares = ls_github(firmwares_url)",
"and (cache_ttl is None or ( (datetime.now()-cache[url]['timestamp']).total_seconds() < cache_ttl)): data = cache[url]['data'] else:",
"return rev_url def get_platforms(args, rev_url): platforms = ls_github(rev_url) possible_platforms = [d['name'] for d",
"{} (found {})\".format( args.platform, rev, \", \".join(possible_platforms))) sys.exit(1) return possible_platforms def get_targets_url(args, rev_url):",
"from in a specific channel ().\", default=\"unstable\") parser.add_argument('--tag', help='Alias for --channel.', dest=\"channel\") parser.add_argument('--latest',",
"for platform {} at rev {} (found {})\". format(args.firmware, args.target, args.platform, rev, \",",
"not find platform {} at rev {} (found {})\".format( args.platform, rev, \", \".join(possible_platforms)))",
"filename) ret = download(args, rev, filename, image_url) print(\"Done!\") return if __name__ == \"__main__\":",
"{} (found {})\". format(args.arch, args.target, args.platform, rev, \", \".join(possible_archs))) sys.exit(1) return possible_archs def",
"args.rev, args.channel) rev_url = get_rev_url(archive_url, rev) possible_platforms = get_platforms(args, rev_url) targets_url = get_targets_url(args,",
"{} for i in csv.reader(data.splitlines(), dialect='excel'): print(len(i),i) if not i: continue if i[0]",
"parser.parse_args() assert args.platform assert args.rev or args.channel assert args.target return args def mk_url(user,",
"specific version.') parser.add_argument('--platform', help='Get for a specific platform (board + expansion boards configuration).')",
"return firmwares_url def get_firmwares(args, firmwares_url): firmwares = ls_github(firmwares_url) possible_firmwares = [ d['name'] for",
"= argparse.ArgumentParser( description='Download prebuilt firmware') parser.add_argument('--rev', help='Get a specific version.') parser.add_argument('--platform', help='Get for",
"print(\"Downloading to: {}\".format(out_filename)) urllib.request.urlretrieve(image_url, out_filename) return True def main(): args = parse_args() archive_url",
"githash = value.split('-') commits = int(commits) assert githash[0] == 'g' return _Version.__new__(cls, version,",
"value.split('-') commits = int(commits) assert githash[0] == 'g' return _Version.__new__(cls, version, commits, githash[1:])",
"= get_archs_url(args, targets_url) possible_archs = get_archs(args, archs_url) firmwares_url = get_firmwares_url(args, archs_url) possible_firmwares =",
"data = json.loads(urllib.request.urlopen(url).read().decode()) if \"message\" in data: print(\"Warning: {}\".format(data[\"message\"])) time.sleep(1) continue else: break",
"help=\"Branch to download from.\", default=\"master\") parser.add_argument('-o', '--output', help=\"Output filename.\", ) args = parser.parse_args()",
"data } save_cache(cache) return data _Version = namedtuple(\"Version\", (\"version\", \"commits\", \"hash\")) class Version(_Version):",
"get_firmwares_url(args, archs_url): firmwares_url = \"{}{:s}/\".format(archs_url, args.arch) return firmwares_url def get_firmwares(args, firmwares_url): firmwares =",
"= load_cache() if url in cache and (cache_ttl is None or ( (datetime.now()-cache[url]['timestamp']).total_seconds()",
"from datetime import datetime class TargetNotFound(Exception): pass def ls_github(url, cache_ttl=None): # FIXME: Move",
"notes, more_notes = i if not rev_str: continue print(rev_str, name) rev = Version(rev_str)",
"rev in possible_revs # assert name not in rev_names, \"{} is listed multiple",
"archs if d['type'] == 'dir'] print(\"Found archs: {}\".format(\", \".join(possible_archs))) if args.arch not in",
"Python 2 import argparse import csv import doctest import json import os import",
"revs = ls_github(archive_url, cache_ttl=60*20) possible_revs = [Version(d['name']) for d in revs if d['type']",
"or ( (datetime.now()-cache[url]['timestamp']).total_seconds() < cache_ttl)): data = cache[url]['data'] else: while True: data =",
"rev_url): targets_url = \"{}{:s}/\".format(rev_url, args.platform) return targets_url def get_targets(args, rev, targets_url): targets =",
"# assert rev in possible_revs # assert name not in rev_names, \"{} is",
"(found {})\".format( args.platform, rev, \", \".join(possible_platforms))) sys.exit(1) return possible_platforms def get_targets_url(args, rev_url): targets_url",
"def __new__(cls, value): version, commits, githash = value.split('-') commits = int(commits) assert githash[0]",
"import argparse import csv import doctest import json import os import pickle import",
"args.target, args.platform, rev, \", \".join(possible_firmwares))) sys.exit(1) return filename def get_image_url(args, rev, filename): image_url",
"not find arch {} for target {} for platform {} at rev {}",
"assert rev in possible_revs, \"{} is not found in {}\".format( rev, possible_revs) print(\"rev:",
"mk_url(args.user, args.branch) for rev in possible_revs: rev_url = get_rev_url(archive_url, rev) possible_platforms = get_platforms(args,",
"= get_firmwares_url(args, archs_url) possible_firmwares = get_firmwares(args, firmwares_url) filename = get_filename(args, possible_firmwares) image_url =",
"2 import argparse import csv import doctest import json import os import pickle",
"default=\"unstable\") parser.add_argument('--tag', help='Alias for --channel.', dest=\"channel\") parser.add_argument('--latest', dest=\"channel\", action=\"store_const\", help=\"Get the latest version.\",",
"= parser.parse_args() assert args.platform assert args.rev or args.channel assert args.target return args def",
"{} is at rev {}\".format(channel, rev)) else: rev = Version(rev) assert rev in",
"= \"{}{:s}/\".format(archs_url, args.arch) return firmwares_url def get_firmwares(args, firmwares_url): firmwares = ls_github(firmwares_url) possible_firmwares =",
"ls_github(archive_url) {}\".format(archive_url)) revs = ls_github(archive_url, cache_ttl=60*20) possible_revs = [Version(d['name']) for d in revs",
"= get_filename(args, possible_firmwares) image_url = get_image_url(args, rev, filename) ret = download(args, rev, filename,",
"Version(\"v0.0.4-44-g0cd842f\") >>> v Version(version='v0.0.4', commits=44, hash='0cd842f') >>> str(v) 'v0.0.4-44-g0cd842f' \"\"\" def __new__(cls, value):",
"help=\"Soft-CPU architecture to download from.\") parser.add_argument('--user', help='Github user to download from.', default=\"timvideos\") parser.add_argument('--branch',",
"latest version.\", const=\"unstable\") parser.add_argument('--target', help=\"Target to download from.\", default=\"hdmi2usb\") parser.add_argument('--firmware', help=\"Firmware to download",
"in possible_targets: print(\"Did not find target {} for platform {} at rev {}",
"def get_platforms(args, rev_url): platforms = ls_github(rev_url) possible_platforms = [d['name'] for d in platforms",
"d['type'] == 'dir'] print(\"Found platforms: {}\".format(\", \".join(possible_platforms))) if args.platform not in possible_platforms: print(\"Did",
"rev, \", \".join(possible_archs))) sys.exit(1) return possible_archs def get_firmwares_url(args, archs_url): firmwares_url = \"{}{:s}/\".format(archs_url, args.arch)",
"at rev {} (found {})\".format( args.platform, rev, \", \".join(possible_platforms))) sys.exit(1) return possible_platforms def",
"import datetime class TargetNotFound(Exception): pass def ls_github(url, cache_ttl=None): # FIXME: Move cache to",
"% i) continue _, _, rev_str, name, conf, notes, more_notes = i if",
"print(\"Did not find platform {} at rev {} (found {})\".format( args.platform, rev, \",",
"args.branch) for rev in possible_revs: rev_url = get_rev_url(archive_url, rev) possible_platforms = get_platforms(args, rev_url)",
"return filename def get_image_url(args, rev, filename): image_url = \"https://github.com/{user}/HDMI2USB-firmware-prebuilt/raw/master/archive/{branch}/{rev}/{platform}/{target}/{arch}/{filename}\".format( user=args.user, branch=args.branch, rev=rev, platform=args.platform,",
"urllib.request from collections import namedtuple from datetime import datetime class TargetNotFound(Exception): pass def",
"= get_targets_url(args, rev_url) try: possible_targets = get_targets(args, rev, targets_url) except TargetNotFound: rev =",
"from.\", default=\"master\") parser.add_argument('-o', '--output', help=\"Output filename.\", ) args = parser.parse_args() assert args.platform assert",
"{}\".format( rev, possible_revs) print(\"rev: {}\".format(rev)) return rev def get_rev_url(archive_url, rev): rev_url = \"{}{:s}/\".format(archive_url,",
"save_cache(cache) return data _Version = namedtuple(\"Version\", (\"version\", \"commits\", \"hash\")) class Version(_Version): \"\"\" >>>",
"= get_firmwares(args, firmwares_url) filename = get_filename(args, possible_firmwares) image_url = get_image_url(args, rev, filename) ret",
"rev_url) targets_url = get_targets_url(args, rev_url) try: possible_targets = get_targets(args, rev, targets_url) except TargetNotFound:",
"TargetNotFound() return possible_targets def find_last_rev(args, possible_revs): possible_revs.reverse() archive_url = mk_url(args.user, args.branch) for rev",
"args.platform, rev, \", \".join(possible_platforms))) sys.exit(1) return possible_platforms def get_targets_url(args, rev_url): targets_url = \"{}{:s}/\".format(rev_url,",
"revs are added. # builds take over 20 min, so refresh every 20",
"get_goog_sheet() if channel not in rev_names: print(\"Did not find {} in {}\".format(channel, rev_names))",
"<reponame>baldurmen/HDMI2USB-mode-switch<gh_stars>1-10 #!/usr/bin/env python # FIXME: Make this work under Python 2 import argparse",
"possible_revs[-1] else: rev_names = get_goog_sheet() if channel not in rev_names: print(\"Did not find",
"'file' and d['name'].endswith('.bin') ] print(\"Found firmwares: {}\".format(\", \".join(possible_firmwares))) return possible_firmwares def get_filename(args, possible_firmwares):",
"= i if not rev_str: continue print(rev_str, name) rev = Version(rev_str) # assert",
"= Version(\"v0.0.4-44-g0cd842f\") >>> v Version(version='v0.0.4', commits=44, hash='0cd842f') >>> str(v) 'v0.0.4-44-g0cd842f' \"\"\" def __new__(cls,",
"for rev in possible_revs: rev_url = get_rev_url(archive_url, rev) possible_platforms = get_platforms(args, rev_url) targets_url",
"== \"unstable\": rev = possible_revs[-1] else: rev_names = get_goog_sheet() if channel not in",
"rev instead. sys.exit(1) archs_url = get_archs_url(args, targets_url) possible_archs = get_archs(args, archs_url) firmwares_url =",
"possible_firmwares): filename = None for f in possible_firmwares: if f.endswith(\"{}.bin\".format(args.firmware)): filename = f",
"if \"message\" in data: print(\"Warning: {}\".format(data[\"message\"])) time.sleep(1) continue else: break cache[url] = {",
"targets_url) except TargetNotFound: rev = find_last_rev(args, possible_revs) # TODO: use this rev instead.",
"to: {}\".format(out_filename)) urllib.request.urlretrieve(image_url, out_filename) return True def main(): args = parse_args() archive_url =",
"is listed multiple times!\".format(name) rev_names[name] = rev return rev_names def get_rev(possible_revs,rev=None, channel=\"unstable\"): if",
"name) rev = Version(rev_str) # assert rev in possible_revs # assert name not",
"print(\"Found platforms: {}\".format(\", \".join(possible_platforms))) if args.platform not in possible_platforms: print(\"Did not find platform",
"== 'dir'] print(\"Found archs: {}\".format(\", \".join(possible_archs))) if args.arch not in possible_archs: print( \"Did",
"args.target, args.arch, parts[-1][1:]]) print(\"Downloading to: {}\".format(out_filename)) urllib.request.urlretrieve(image_url, out_filename) return True def main(): args",
"return possible_archs def get_firmwares_url(args, archs_url): firmwares_url = \"{}{:s}/\".format(archs_url, args.arch) return firmwares_url def get_firmwares(args,",
"get_archs(args, archs_url) firmwares_url = get_firmwares_url(args, archs_url) possible_firmwares = get_firmwares(args, firmwares_url) filename = get_filename(args,",
"except TargetNotFound: rev = find_last_rev(args, possible_revs) # TODO: use this rev instead. sys.exit(1)",
"{} at rev {} (found {})\". format(args.firmware, args.target, args.platform, rev, \", \".join(possible_firmwares))) sys.exit(1)",
"str(rev)) return rev_url def get_platforms(args, rev_url): platforms = ls_github(rev_url) possible_platforms = [d['name'] for",
"try: possible_targets = get_targets(args, rev, targets_url) except TargetNotFound: rev = find_last_rev(args, possible_revs) #",
"import namedtuple from datetime import datetime class TargetNotFound(Exception): pass def ls_github(url, cache_ttl=None): #",
"# builds take over 20 min, so refresh every 20 min. print(\"revs =",
"raise TargetNotFound() return possible_targets def find_last_rev(args, possible_revs): possible_revs.reverse() archive_url = mk_url(args.user, args.branch) for",
"\"HDMI2USB-firmware-prebuilt\", \"branch\": branch, } archive_url = \"https://api.github.com/repos/{owner}/{repo}/contents/archive/{branch}/\".format( **details) return archive_url def get_revs(archive_url): #",
"target {} for platform {} at rev {} (found {})\". format(args.target, args.platform, rev,",
"version, commits, githash[1:]) def __str__(self): return \"%s-%i-g%s\" % self doctest.testmod() def parse_args(): parser",
"dest=\"platform\") parser.add_argument('--channel', help=\"Get latest version from in a specific channel ().\", default=\"unstable\") parser.add_argument('--tag',",
"pickle import sys import time import urllib.request from collections import namedtuple from datetime",
"if len(i) != 7: print(\"Skipping row %s\" % i) continue _, _, rev_str,",
"in possible_revs, \"{} is not found in {}\".format( rev, possible_revs) print(\"rev: {}\".format(rev)) return",
"revs if d['type'] == 'dir'] possible_revs.sort() return possible_revs def get_goog_sheet(): data = urllib.request.urlopen(",
"at rev {} (found {})\". format(args.arch, args.target, args.platform, rev, \", \".join(possible_archs))) sys.exit(1) return",
"rev {} (found {})\". format(args.target, args.platform, rev, \", \".join(possible_targets))) raise TargetNotFound() return possible_targets",
"\"{}{:s}/\".format(archs_url, args.arch) return firmwares_url def get_firmwares(args, firmwares_url): firmwares = ls_github(firmwares_url) possible_firmwares = [",
"find arch {} for target {} for platform {} at rev {} (found",
"user=args.user, branch=args.branch, rev=rev, platform=args.platform, target=args.target, arch=args.arch, filename=filename) print(\"Image URL: {}\".format(image_url)) return image_url def",
"possible_firmwares = get_firmwares(args, firmwares_url) filename = get_filename(args, possible_firmwares) image_url = get_image_url(args, rev, filename)",
"args.platform, rev, \", \".join(possible_firmwares))) sys.exit(1) return filename def get_image_url(args, rev, filename): image_url =",
"in rev_names: print(\"Did not find {} in {}\".format(channel, rev_names)) sys.exit(1) rev = rev_names[channel]",
"a specific platform (board + expansion boards configuration).') parser.add_argument('--board', help='Alias for --platform.', dest=\"platform\")",
"possible_revs, \"{} is not found in {}\".format( rev, possible_revs) print(\"rev: {}\".format(rev)) return rev",
"print(\"found at rev {}\".format(rev)) return rev except TargetNotFound: continue def get_archs_url(args, targets_url): archs_url",
"(\"version\", \"commits\", \"hash\")) class Version(_Version): \"\"\" >>> v = Version(\"v0.0.4-44-g0cd842f\") >>> v Version(version='v0.0.4',",
"for --channel.', dest=\"channel\") parser.add_argument('--latest', dest=\"channel\", action=\"store_const\", help=\"Get the latest version.\", const=\"unstable\") parser.add_argument('--target', help=\"Target",
"every 20 min. print(\"revs = ls_github(archive_url) {}\".format(archive_url)) revs = ls_github(archive_url, cache_ttl=60*20) possible_revs =",
"def get_targets(args, rev, targets_url): targets = ls_github(targets_url) possible_targets = [d['name'] for d in",
"at rev {} (found {})\". format(args.target, args.platform, rev, \", \".join(possible_targets))) raise TargetNotFound() return",
"True def main(): args = parse_args() archive_url = mk_url(args.user, args.branch) possible_revs = get_revs(archive_url)",
"get_image_url(args, rev, filename) ret = download(args, rev, filename, image_url) print(\"Done!\") return if __name__",
"= get_goog_sheet() if channel not in rev_names: print(\"Did not find {} in {}\".format(channel,",
"TargetNotFound: continue def get_archs_url(args, targets_url): archs_url = \"{}{:s}/\".format(targets_url, args.target) return archs_url def get_archs(args,",
"= int(commits) assert githash[0] == 'g' return _Version.__new__(cls, version, commits, githash[1:]) def __str__(self):",
"from.\", default=\"hdmi2usb\") parser.add_argument('--firmware', help=\"Firmware to download from.\", default=\"firmware\") parser.add_argument('--arch', default=\"lm32\", help=\"Soft-CPU architecture to",
"rev): rev_url = \"{}{:s}/\".format(archive_url, str(rev)) return rev_url def get_platforms(args, rev_url): platforms = ls_github(rev_url)",
"rev_url): platforms = ls_github(rev_url) possible_platforms = [d['name'] for d in platforms if d['type']",
"rev: if channel == \"unstable\": rev = possible_revs[-1] else: rev_names = get_goog_sheet() if",
"targets_url) possible_archs = get_archs(args, archs_url) firmwares_url = get_firmwares_url(args, archs_url) possible_firmwares = get_firmwares(args, firmwares_url)",
"{})\". format(args.firmware, args.target, args.platform, rev, \", \".join(possible_firmwares))) sys.exit(1) return filename def get_image_url(args, rev,",
"[d['name'] for d in platforms if d['type'] == 'dir'] print(\"Found platforms: {}\".format(\", \".join(possible_platforms)))",
"get_archs_url(args, targets_url) possible_archs = get_archs(args, archs_url) firmwares_url = get_firmwares_url(args, archs_url) possible_firmwares = get_firmwares(args,",
"rev)) else: rev = Version(rev) assert rev in possible_revs, \"{} is not found",
"platform {} at rev {} (found {})\". format(args.firmware, args.target, args.platform, rev, \", \".join(possible_firmwares)))",
"cache to a class or find a package. cache_name = \"github.pickle\" def load_cache():",
"{} in {}\".format(channel, rev_names)) sys.exit(1) rev = rev_names[channel] print(\"Channel {} is at rev",
"continue if i[0] != \"GitHub\": pass # continue if len(i) != 7: print(\"Skipping",
"_, rev_str, name, conf, notes, more_notes = i if not rev_str: continue print(rev_str,",
"sys.exit(1) return possible_archs def get_firmwares_url(args, archs_url): firmwares_url = \"{}{:s}/\".format(archs_url, args.arch) return firmwares_url def",
"def get_firmwares_url(args, archs_url): firmwares_url = \"{}{:s}/\".format(archs_url, args.arch) return firmwares_url def get_firmwares(args, firmwares_url): firmwares",
"find {} in {}\".format(channel, rev_names)) sys.exit(1) rev = rev_names[channel] print(\"Channel {} is at",
"targets_url def get_targets(args, rev, targets_url): targets = ls_github(targets_url) possible_targets = [d['name'] for d",
"in {}\".format(channel, rev_names)) sys.exit(1) rev = rev_names[channel] print(\"Channel {} is at rev {}\".format(channel,",
"rev_names)) sys.exit(1) rev = rev_names[channel] print(\"Channel {} is at rev {}\".format(channel, rev)) else:",
"= rev return rev_names def get_rev(possible_revs,rev=None, channel=\"unstable\"): if not rev: if channel ==",
"time.sleep(1) continue else: break cache[url] = { 'timestamp': datetime.now(), 'data': data } save_cache(cache)",
"= ls_github(rev_url) possible_platforms = [d['name'] for d in platforms if d['type'] == 'dir']",
"help='Github user to download from.', default=\"timvideos\") parser.add_argument('--branch', help=\"Branch to download from.\", default=\"master\") parser.add_argument('-o',",
"== 'dir'] print(\"Found platforms: {}\".format(\", \".join(possible_platforms))) if args.platform not in possible_platforms: print(\"Did not",
"in archs if d['type'] == 'dir'] print(\"Found archs: {}\".format(\", \".join(possible_archs))) if args.arch not",
"for platform {} at rev {} (found {})\". format(args.target, args.platform, rev, \", \".join(possible_targets)))",
"rev {} (found {})\". format(args.arch, args.target, args.platform, rev, \", \".join(possible_archs))) sys.exit(1) return possible_archs",
"{})\". format(args.target, args.platform, rev, \", \".join(possible_targets))) raise TargetNotFound() return possible_targets def find_last_rev(args, possible_revs):",
"for d in archs if d['type'] == 'dir'] print(\"Found archs: {}\".format(\", \".join(possible_archs))) if",
"def find_last_rev(args, possible_revs): possible_revs.reverse() archive_url = mk_url(args.user, args.branch) for rev in possible_revs: rev_url",
"arch=args.arch, filename=filename) print(\"Image URL: {}\".format(image_url)) return image_url def download(args, rev, filename, image_url): if",
"class or find a package. cache_name = \"github.pickle\" def load_cache(): try: cache =",
"format(args.arch, args.target, args.platform, rev, \", \".join(possible_archs))) sys.exit(1) return possible_archs def get_firmwares_url(args, archs_url): firmwares_url",
"json import os import pickle import sys import time import urllib.request from collections"
] |
[
"random list of neg value list len 100.\"\"\" return [randint(-1000, 0) for _",
"sort algorithm tests.\"\"\" from quick_sort import quick_sort, _quicksort import pytest from random import",
"of 10 vals.\"\"\" return [x for x in range(10)] @pytest.fixture(scope='function') def rand_ten(): \"\"\"Make",
"[randint(0, 1000) for _ in range(10)] @pytest.fixture(scope='function') def rand_neg(): \"\"\"Make a random list",
"raised for invalid type.\"\"\" with pytest.raises(ValueError): quick_sort('12345') def test_sort_method_raises_error_val(): \"\"\"Test if error gets",
"error gets raised for invalid type.\"\"\" with pytest.raises(ValueError): quick_sort([1, 2, '3']) def test_sort_method_raise_error_dic():",
"quick_sort(rand_ten) key = sorted(rand_ten) assert result == key def test_sort_nums_in_tuple_random_case(rand_ten): \"\"\"Test quick sort",
"def test_sort_nums_in_list_wrose_case_helper(list_ten): \"\"\"Test _quick sort function.\"\"\" reverse = list(reversed(list_ten)) result = _quicksort(reverse) assert",
"in range(10)] @pytest.fixture(scope='function') def rand_ten(): \"\"\"Make a random list of length 10.\"\"\" return",
"= quick_sort(rand_ten) key = sorted(rand_ten) assert result == key def test_sort_nums_in_tuple_random_case(rand_ten): \"\"\"Test quick",
"def test_sort_method_raise_error_fun(): \"\"\"Test if error gets raised for invalid type.\"\"\" with pytest.raises(ValueError): quick_sort([1,",
"test_sort_nums_in_list_wrose_case_helper(list_ten): \"\"\"Test _quick sort function.\"\"\" reverse = list(reversed(list_ten)) result = _quicksort(reverse) assert result",
"list_ten(): \"\"\"Make a list of 10 vals.\"\"\" return [x for x in range(10)]",
"with pytest.raises(ValueError): quick_sort('12345') def test_sort_method_raises_error_val(): \"\"\"Test if error gets raised for invalid type.\"\"\"",
"raised for invalid type.\"\"\" with pytest.raises(ValueError): quick_sort([1, 2, 3, 'p']) def test_sort_nums_in_list_random_case_helper(rand_ten): \"\"\"Test",
"assert result == key def test_sort_nums_in_list_wrose_case_helper(list_ten): \"\"\"Test _quick sort function.\"\"\" reverse = list(reversed(list_ten))",
"quick_sort([1, 2, '3']) def test_sort_method_raise_error_dic(): \"\"\"Test if error gets raised for invalid type.\"\"\"",
"if error gets raised for invalid type.\"\"\" with pytest.raises(ValueError): quick_sort('12345') def test_sort_method_raises_error_val(): \"\"\"Test",
"if error gets raised for invalid type.\"\"\" with pytest.raises(ValueError): quick_sort({1, 2, 3}) def",
"quick_sort(rand_ten) key = sorted(rand_ten) assert result == key def test_sort_nums_in_list_wrose_case_helper(list_ten): \"\"\"Test _quick sort",
"tests.\"\"\" from quick_sort import quick_sort, _quicksort import pytest from random import randint @pytest.fixture(scope='function')",
"test_sort_list_with_neg_values(rand_neg): \"\"\"Test if sorting method sorts negative values.\"\"\" key = sorted(rand_neg) result =",
"sort function.\"\"\" rand = tuple(rand_ten) result = quick_sort(rand) key = sorted(rand) assert result",
"= sorted(rand_ten) assert result == key def test_sort_nums_in_tuple_random_case(rand_ten): \"\"\"Test quick sort function.\"\"\" rand",
"function.\"\"\" rand = tuple(rand_ten) result = quick_sort(rand) key = sorted(rand) assert result ==",
"function.\"\"\" result = quick_sort(rand_ten) key = sorted(rand_ten) assert result == key def test_sort_nums_in_tuple_random_case(rand_ten):",
"quick_sort([1, 2, 3, 'p']) def test_sort_nums_in_list_random_case_helper(rand_ten): \"\"\"Test quick sort function.\"\"\" result = quick_sort(rand_ten)",
"3}) def test_sort_method_raise_error_fun(): \"\"\"Test if error gets raised for invalid type.\"\"\" with pytest.raises(ValueError):",
"3, 'p']) def test_sort_nums_in_list_random_case_helper(rand_ten): \"\"\"Test quick sort function.\"\"\" result = quick_sort(rand_ten) key =",
"= quick_sort(rand_ten) key = sorted(rand_ten) assert result == key def test_sort_nums_in_list_wrose_case_helper(list_ten): \"\"\"Test _quick",
"2, 3}) def test_sort_method_raise_error_fun(): \"\"\"Test if error gets raised for invalid type.\"\"\" with",
"test_sort_nums_in_list_random_case_helper(rand_ten): \"\"\"Test quick sort function.\"\"\" result = quick_sort(rand_ten) key = sorted(rand_ten) assert result",
"sorted(rand_ten) assert result == key def test_sort_nums_in_list_wrose_case_helper(list_ten): \"\"\"Test _quick sort function.\"\"\" reverse =",
"quick_sort(reverse) assert result == list_ten def test_sort_method_raises_error(): \"\"\"Test if error gets raised for",
"tuple(rand_ten) result = quick_sort(rand) key = sorted(rand) assert result == key def test_sort_nums_in_list_wrose_case(list_ten):",
"result def test_sort_nums_in_list_random_case(rand_ten): \"\"\"Test quick sort function.\"\"\" result = quick_sort(rand_ten) key = sorted(rand_ten)",
"sorted(rand_neg) result = quick_sort(rand_neg) assert key == result def test_sort_nums_in_list_random_case(rand_ten): \"\"\"Test quick sort",
"\"\"\"Test if sorting method sorts negative values.\"\"\" key = sorted(rand_neg) result = quick_sort(rand_neg)",
"tuple(reversed(list_ten)) result = quick_sort(reverse) assert result == list_ten def test_sort_method_raises_error(): \"\"\"Test if error",
"for invalid type.\"\"\" with pytest.raises(ValueError): quick_sort('12345') def test_sort_method_raises_error_val(): \"\"\"Test if error gets raised",
"type.\"\"\" with pytest.raises(ValueError): quick_sort({1, 2, 3}) def test_sort_method_raise_error_fun(): \"\"\"Test if error gets raised",
"\"\"\"Test if error gets raised for invalid type.\"\"\" with pytest.raises(ValueError): quick_sort([1, 2, 3,",
"type.\"\"\" with pytest.raises(ValueError): quick_sort([1, 2, 3, 'p']) def test_sort_nums_in_list_random_case_helper(rand_ten): \"\"\"Test quick sort function.\"\"\"",
"result = quick_sort(reverse) assert result == list_ten def test_sort_nums_in_tuple_wrose_case(list_ten): \"\"\"Test quick sort function.\"\"\"",
"from random import randint @pytest.fixture(scope='function') def list_ten(): \"\"\"Make a list of 10 vals.\"\"\"",
"a list of 10 vals.\"\"\" return [x for x in range(10)] @pytest.fixture(scope='function') def",
"return [randint(0, 1000) for _ in range(10)] @pytest.fixture(scope='function') def rand_neg(): \"\"\"Make a random",
"pytest.raises(ValueError): quick_sort({1, 2, 3}) def test_sort_method_raise_error_fun(): \"\"\"Test if error gets raised for invalid",
"rand = tuple(rand_ten) result = quick_sort(rand) key = sorted(rand) assert result == key",
"in range(100)] def test_sort_list_with_neg_values(rand_neg): \"\"\"Test if sorting method sorts negative values.\"\"\" key =",
"if error gets raised for invalid type.\"\"\" with pytest.raises(ValueError): quick_sort([1, 2, 3, 'p'])",
"sorts negative values.\"\"\" key = sorted(rand_neg) result = quick_sort(rand_neg) assert key == result",
"error gets raised for invalid type.\"\"\" with pytest.raises(ValueError): quick_sort([1, 2, 3, 'p']) def",
"'3']) def test_sort_method_raise_error_dic(): \"\"\"Test if error gets raised for invalid type.\"\"\" with pytest.raises(ValueError):",
"randint @pytest.fixture(scope='function') def list_ten(): \"\"\"Make a list of 10 vals.\"\"\" return [x for",
"a random list of length 10.\"\"\" return [randint(0, 1000) for _ in range(10)]",
"= sorted(rand_neg) result = quick_sort(rand_neg) assert key == result def test_sort_nums_in_list_random_case(rand_ten): \"\"\"Test quick",
"quick sort function.\"\"\" result = quick_sort(rand_ten) key = sorted(rand_ten) assert result == key",
"10 vals.\"\"\" return [x for x in range(10)] @pytest.fixture(scope='function') def rand_ten(): \"\"\"Make a",
"test_sort_nums_in_tuple_random_case(rand_ten): \"\"\"Test quick sort function.\"\"\" rand = tuple(rand_ten) result = quick_sort(rand) key =",
"assert result == key def test_sort_nums_in_list_wrose_case(list_ten): \"\"\"Test quick sort function.\"\"\" reverse = list(reversed(list_ten))",
"for _ in range(100)] def test_sort_list_with_neg_values(rand_neg): \"\"\"Test if sorting method sorts negative values.\"\"\"",
"def rand_ten(): \"\"\"Make a random list of length 10.\"\"\" return [randint(0, 1000) for",
"key = sorted(rand_ten) assert result == key def test_sort_nums_in_list_wrose_case_helper(list_ten): \"\"\"Test _quick sort function.\"\"\"",
"with pytest.raises(ValueError): quick_sort({1, 2, 3}) def test_sort_method_raise_error_fun(): \"\"\"Test if error gets raised for",
"algorithm tests.\"\"\" from quick_sort import quick_sort, _quicksort import pytest from random import randint",
"import quick_sort, _quicksort import pytest from random import randint @pytest.fixture(scope='function') def list_ten(): \"\"\"Make",
"a random list of neg value list len 100.\"\"\" return [randint(-1000, 0) for",
"def test_sort_nums_in_list_wrose_case(list_ten): \"\"\"Test quick sort function.\"\"\" reverse = list(reversed(list_ten)) result = quick_sort(reverse) assert",
"\"\"\"Test quick sort function.\"\"\" result = quick_sort(rand_ten) key = sorted(rand_ten) assert result ==",
"def test_sort_method_raises_error(): \"\"\"Test if error gets raised for invalid type.\"\"\" with pytest.raises(ValueError): quick_sort('12345')",
"for invalid type.\"\"\" with pytest.raises(ValueError): quick_sort([1, 2, '3']) def test_sort_method_raise_error_dic(): \"\"\"Test if error",
"from quick_sort import quick_sort, _quicksort import pytest from random import randint @pytest.fixture(scope='function') def",
"values.\"\"\" key = sorted(rand_neg) result = quick_sort(rand_neg) assert key == result def test_sort_nums_in_list_random_case(rand_ten):",
"for _ in range(10)] @pytest.fixture(scope='function') def rand_neg(): \"\"\"Make a random list of neg",
"sort function.\"\"\" reverse = tuple(reversed(list_ten)) result = quick_sort(reverse) assert result == list_ten def",
"= tuple(reversed(list_ten)) result = quick_sort(reverse) assert result == list_ten def test_sort_method_raises_error(): \"\"\"Test if",
"= quick_sort(rand) key = sorted(rand) assert result == key def test_sort_nums_in_list_wrose_case(list_ten): \"\"\"Test quick",
"pytest.raises(ValueError): quick_sort([1, 2, 3, 'p']) def test_sort_nums_in_list_random_case_helper(rand_ten): \"\"\"Test quick sort function.\"\"\" result =",
"key def test_sort_nums_in_list_wrose_case_helper(list_ten): \"\"\"Test _quick sort function.\"\"\" reverse = list(reversed(list_ten)) result = _quicksort(reverse)",
"rand_ten(): \"\"\"Make a random list of length 10.\"\"\" return [randint(0, 1000) for _",
"of neg value list len 100.\"\"\" return [randint(-1000, 0) for _ in range(100)]",
"reverse = list(reversed(list_ten)) result = quick_sort(reverse) assert result == list_ten def test_sort_nums_in_tuple_wrose_case(list_ten): \"\"\"Test",
"assert result == list_ten def test_sort_nums_in_tuple_wrose_case(list_ten): \"\"\"Test quick sort function.\"\"\" reverse = tuple(reversed(list_ten))",
"quick_sort, _quicksort import pytest from random import randint @pytest.fixture(scope='function') def list_ten(): \"\"\"Make a",
"result == key def test_sort_nums_in_tuple_random_case(rand_ten): \"\"\"Test quick sort function.\"\"\" rand = tuple(rand_ten) result",
"x in range(10)] @pytest.fixture(scope='function') def rand_ten(): \"\"\"Make a random list of length 10.\"\"\"",
"\"\"\"Test _quick sort function.\"\"\" reverse = list(reversed(list_ten)) result = _quicksort(reverse) assert result ==",
"quick sort algorithm tests.\"\"\" from quick_sort import quick_sort, _quicksort import pytest from random",
"_quicksort import pytest from random import randint @pytest.fixture(scope='function') def list_ten(): \"\"\"Make a list",
"invalid type.\"\"\" with pytest.raises(ValueError): quick_sort([1, 2, '3']) def test_sort_method_raise_error_dic(): \"\"\"Test if error gets",
"result == list_ten def test_sort_nums_in_tuple_wrose_case(list_ten): \"\"\"Test quick sort function.\"\"\" reverse = tuple(reversed(list_ten)) result",
"range(10)] @pytest.fixture(scope='function') def rand_ten(): \"\"\"Make a random list of length 10.\"\"\" return [randint(0,",
"len 100.\"\"\" return [randint(-1000, 0) for _ in range(100)] def test_sort_list_with_neg_values(rand_neg): \"\"\"Test if",
"neg value list len 100.\"\"\" return [randint(-1000, 0) for _ in range(100)] def",
"def test_sort_nums_in_tuple_random_case(rand_ten): \"\"\"Test quick sort function.\"\"\" rand = tuple(rand_ten) result = quick_sort(rand) key",
"gets raised for invalid type.\"\"\" with pytest.raises(ValueError): quick_sort('12345') def test_sort_method_raises_error_val(): \"\"\"Test if error",
"error gets raised for invalid type.\"\"\" with pytest.raises(ValueError): quick_sort({1, 2, 3}) def test_sort_method_raise_error_fun():",
"test_sort_nums_in_list_random_case(rand_ten): \"\"\"Test quick sort function.\"\"\" result = quick_sort(rand_ten) key = sorted(rand_ten) assert result",
"function.\"\"\" reverse = tuple(reversed(list_ten)) result = quick_sort(reverse) assert result == list_ten def test_sort_method_raises_error():",
"key = sorted(rand_ten) assert result == key def test_sort_nums_in_tuple_random_case(rand_ten): \"\"\"Test quick sort function.\"\"\"",
"list len 100.\"\"\" return [randint(-1000, 0) for _ in range(100)] def test_sort_list_with_neg_values(rand_neg): \"\"\"Test",
"value list len 100.\"\"\" return [randint(-1000, 0) for _ in range(100)] def test_sort_list_with_neg_values(rand_neg):",
"\"\"\"Make a random list of length 10.\"\"\" return [randint(0, 1000) for _ in",
"my quick sort algorithm tests.\"\"\" from quick_sort import quick_sort, _quicksort import pytest from",
"quick_sort(reverse) assert result == list_ten def test_sort_nums_in_tuple_wrose_case(list_ten): \"\"\"Test quick sort function.\"\"\" reverse =",
"raised for invalid type.\"\"\" with pytest.raises(ValueError): quick_sort({1, 2, 3}) def test_sort_method_raise_error_fun(): \"\"\"Test if",
"2, 3, 'p']) def test_sort_nums_in_list_random_case_helper(rand_ten): \"\"\"Test quick sort function.\"\"\" result = quick_sort(rand_ten) key",
"@pytest.fixture(scope='function') def list_ten(): \"\"\"Make a list of 10 vals.\"\"\" return [x for x",
"if error gets raised for invalid type.\"\"\" with pytest.raises(ValueError): quick_sort([1, 2, '3']) def",
"in range(10)] @pytest.fixture(scope='function') def rand_neg(): \"\"\"Make a random list of neg value list",
"\"\"\"Test my quick sort algorithm tests.\"\"\" from quick_sort import quick_sort, _quicksort import pytest",
"function.\"\"\" result = quick_sort(rand_ten) key = sorted(rand_ten) assert result == key def test_sort_nums_in_list_wrose_case_helper(list_ten):",
"error gets raised for invalid type.\"\"\" with pytest.raises(ValueError): quick_sort('12345') def test_sort_method_raises_error_val(): \"\"\"Test if",
"assert result == list_ten def test_sort_method_raises_error(): \"\"\"Test if error gets raised for invalid",
"quick sort function.\"\"\" rand = tuple(rand_ten) result = quick_sort(rand) key = sorted(rand) assert",
"= tuple(rand_ten) result = quick_sort(rand) key = sorted(rand) assert result == key def",
"gets raised for invalid type.\"\"\" with pytest.raises(ValueError): quick_sort([1, 2, 3, 'p']) def test_sort_nums_in_list_random_case_helper(rand_ten):",
"_quick sort function.\"\"\" reverse = list(reversed(list_ten)) result = _quicksort(reverse) assert result == list_ten",
"for x in range(10)] @pytest.fixture(scope='function') def rand_ten(): \"\"\"Make a random list of length",
"range(10)] @pytest.fixture(scope='function') def rand_neg(): \"\"\"Make a random list of neg value list len",
"def list_ten(): \"\"\"Make a list of 10 vals.\"\"\" return [x for x in",
"random list of length 10.\"\"\" return [randint(0, 1000) for _ in range(10)] @pytest.fixture(scope='function')",
"\"\"\"Test quick sort function.\"\"\" reverse = tuple(reversed(list_ten)) result = quick_sort(reverse) assert result ==",
"== key def test_sort_nums_in_list_wrose_case_helper(list_ten): \"\"\"Test _quick sort function.\"\"\" reverse = list(reversed(list_ten)) result =",
"= quick_sort(reverse) assert result == list_ten def test_sort_method_raises_error(): \"\"\"Test if error gets raised",
"def rand_neg(): \"\"\"Make a random list of neg value list len 100.\"\"\" return",
"0) for _ in range(100)] def test_sort_list_with_neg_values(rand_neg): \"\"\"Test if sorting method sorts negative",
"sort function.\"\"\" result = quick_sort(rand_ten) key = sorted(rand_ten) assert result == key def",
"result = quick_sort(rand_ten) key = sorted(rand_ten) assert result == key def test_sort_nums_in_tuple_random_case(rand_ten): \"\"\"Test",
"def test_sort_method_raise_error_dic(): \"\"\"Test if error gets raised for invalid type.\"\"\" with pytest.raises(ValueError): quick_sort({1,",
"= sorted(rand) assert result == key def test_sort_nums_in_list_wrose_case(list_ten): \"\"\"Test quick sort function.\"\"\" reverse",
"100.\"\"\" return [randint(-1000, 0) for _ in range(100)] def test_sort_list_with_neg_values(rand_neg): \"\"\"Test if sorting",
"10.\"\"\" return [randint(0, 1000) for _ in range(10)] @pytest.fixture(scope='function') def rand_neg(): \"\"\"Make a",
"== list_ten def test_sort_nums_in_tuple_wrose_case(list_ten): \"\"\"Test quick sort function.\"\"\" reverse = tuple(reversed(list_ten)) result =",
"list of 10 vals.\"\"\" return [x for x in range(10)] @pytest.fixture(scope='function') def rand_ten():",
"result = quick_sort(reverse) assert result == list_ten def test_sort_method_raises_error(): \"\"\"Test if error gets",
"'p']) def test_sort_nums_in_list_random_case_helper(rand_ten): \"\"\"Test quick sort function.\"\"\" result = quick_sort(rand_ten) key = sorted(rand_ten)",
"gets raised for invalid type.\"\"\" with pytest.raises(ValueError): quick_sort({1, 2, 3}) def test_sort_method_raise_error_fun(): \"\"\"Test",
"test_sort_method_raise_error_fun(): \"\"\"Test if error gets raised for invalid type.\"\"\" with pytest.raises(ValueError): quick_sort([1, 2,",
"def test_sort_list_with_neg_values(rand_neg): \"\"\"Test if sorting method sorts negative values.\"\"\" key = sorted(rand_neg) result",
"assert result == key def test_sort_nums_in_tuple_random_case(rand_ten): \"\"\"Test quick sort function.\"\"\" rand = tuple(rand_ten)",
"list of length 10.\"\"\" return [randint(0, 1000) for _ in range(10)] @pytest.fixture(scope='function') def",
"raised for invalid type.\"\"\" with pytest.raises(ValueError): quick_sort([1, 2, '3']) def test_sort_method_raise_error_dic(): \"\"\"Test if",
"gets raised for invalid type.\"\"\" with pytest.raises(ValueError): quick_sort([1, 2, '3']) def test_sort_method_raise_error_dic(): \"\"\"Test",
"= list(reversed(list_ten)) result = quick_sort(reverse) assert result == list_ten def test_sort_nums_in_tuple_wrose_case(list_ten): \"\"\"Test quick",
"sort function.\"\"\" reverse = list(reversed(list_ten)) result = quick_sort(reverse) assert result == list_ten def",
"quick_sort(rand_neg) assert key == result def test_sort_nums_in_list_random_case(rand_ten): \"\"\"Test quick sort function.\"\"\" result =",
"\"\"\"Test if error gets raised for invalid type.\"\"\" with pytest.raises(ValueError): quick_sort({1, 2, 3})",
"@pytest.fixture(scope='function') def rand_neg(): \"\"\"Make a random list of neg value list len 100.\"\"\"",
"result = quick_sort(rand_ten) key = sorted(rand_ten) assert result == key def test_sort_nums_in_list_wrose_case_helper(list_ten): \"\"\"Test",
"return [randint(-1000, 0) for _ in range(100)] def test_sort_list_with_neg_values(rand_neg): \"\"\"Test if sorting method",
"for invalid type.\"\"\" with pytest.raises(ValueError): quick_sort({1, 2, 3}) def test_sort_method_raise_error_fun(): \"\"\"Test if error",
"key = sorted(rand_neg) result = quick_sort(rand_neg) assert key == result def test_sort_nums_in_list_random_case(rand_ten): \"\"\"Test",
"key == result def test_sort_nums_in_list_random_case(rand_ten): \"\"\"Test quick sort function.\"\"\" result = quick_sort(rand_ten) key",
"test_sort_method_raises_error_val(): \"\"\"Test if error gets raised for invalid type.\"\"\" with pytest.raises(ValueError): quick_sort([1, 2,",
"_ in range(100)] def test_sort_list_with_neg_values(rand_neg): \"\"\"Test if sorting method sorts negative values.\"\"\" key",
"test_sort_method_raises_error(): \"\"\"Test if error gets raised for invalid type.\"\"\" with pytest.raises(ValueError): quick_sort('12345') def",
"== result def test_sort_nums_in_list_random_case(rand_ten): \"\"\"Test quick sort function.\"\"\" result = quick_sort(rand_ten) key =",
"list_ten def test_sort_method_raises_error(): \"\"\"Test if error gets raised for invalid type.\"\"\" with pytest.raises(ValueError):",
"type.\"\"\" with pytest.raises(ValueError): quick_sort([1, 2, '3']) def test_sort_method_raise_error_dic(): \"\"\"Test if error gets raised",
"negative values.\"\"\" key = sorted(rand_neg) result = quick_sort(rand_neg) assert key == result def",
"key def test_sort_nums_in_list_wrose_case(list_ten): \"\"\"Test quick sort function.\"\"\" reverse = list(reversed(list_ten)) result = quick_sort(reverse)",
"pytest.raises(ValueError): quick_sort('12345') def test_sort_method_raises_error_val(): \"\"\"Test if error gets raised for invalid type.\"\"\" with",
"if sorting method sorts negative values.\"\"\" key = sorted(rand_neg) result = quick_sort(rand_neg) assert",
"result = quick_sort(rand_neg) assert key == result def test_sort_nums_in_list_random_case(rand_ten): \"\"\"Test quick sort function.\"\"\"",
"list of neg value list len 100.\"\"\" return [randint(-1000, 0) for _ in",
"pytest from random import randint @pytest.fixture(scope='function') def list_ten(): \"\"\"Make a list of 10",
"quick sort function.\"\"\" reverse = tuple(reversed(list_ten)) result = quick_sort(reverse) assert result == list_ten",
"length 10.\"\"\" return [randint(0, 1000) for _ in range(10)] @pytest.fixture(scope='function') def rand_neg(): \"\"\"Make",
"quick sort function.\"\"\" reverse = list(reversed(list_ten)) result = quick_sort(reverse) assert result == list_ten",
"invalid type.\"\"\" with pytest.raises(ValueError): quick_sort([1, 2, 3, 'p']) def test_sort_nums_in_list_random_case_helper(rand_ten): \"\"\"Test quick sort",
"result = quick_sort(rand) key = sorted(rand) assert result == key def test_sort_nums_in_list_wrose_case(list_ten): \"\"\"Test",
"quick_sort({1, 2, 3}) def test_sort_method_raise_error_fun(): \"\"\"Test if error gets raised for invalid type.\"\"\"",
"\"\"\"Test quick sort function.\"\"\" reverse = list(reversed(list_ten)) result = quick_sort(reverse) assert result ==",
"type.\"\"\" with pytest.raises(ValueError): quick_sort('12345') def test_sort_method_raises_error_val(): \"\"\"Test if error gets raised for invalid",
"vals.\"\"\" return [x for x in range(10)] @pytest.fixture(scope='function') def rand_ten(): \"\"\"Make a random",
"for invalid type.\"\"\" with pytest.raises(ValueError): quick_sort([1, 2, 3, 'p']) def test_sort_nums_in_list_random_case_helper(rand_ten): \"\"\"Test quick",
"quick_sort import quick_sort, _quicksort import pytest from random import randint @pytest.fixture(scope='function') def list_ten():",
"1000) for _ in range(10)] @pytest.fixture(scope='function') def rand_neg(): \"\"\"Make a random list of",
"= sorted(rand_ten) assert result == key def test_sort_nums_in_list_wrose_case_helper(list_ten): \"\"\"Test _quick sort function.\"\"\" reverse",
"sorting method sorts negative values.\"\"\" key = sorted(rand_neg) result = quick_sort(rand_neg) assert key",
"invalid type.\"\"\" with pytest.raises(ValueError): quick_sort({1, 2, 3}) def test_sort_method_raise_error_fun(): \"\"\"Test if error gets",
"test_sort_nums_in_list_wrose_case(list_ten): \"\"\"Test quick sort function.\"\"\" reverse = list(reversed(list_ten)) result = quick_sort(reverse) assert result",
"def test_sort_nums_in_tuple_wrose_case(list_ten): \"\"\"Test quick sort function.\"\"\" reverse = tuple(reversed(list_ten)) result = quick_sort(reverse) assert",
"\"\"\"Test quick sort function.\"\"\" rand = tuple(rand_ten) result = quick_sort(rand) key = sorted(rand)",
"sorted(rand) assert result == key def test_sort_nums_in_list_wrose_case(list_ten): \"\"\"Test quick sort function.\"\"\" reverse =",
"_ in range(10)] @pytest.fixture(scope='function') def rand_neg(): \"\"\"Make a random list of neg value",
"\"\"\"Make a list of 10 vals.\"\"\" return [x for x in range(10)] @pytest.fixture(scope='function')",
"list_ten def test_sort_nums_in_tuple_wrose_case(list_ten): \"\"\"Test quick sort function.\"\"\" reverse = tuple(reversed(list_ten)) result = quick_sort(reverse)",
"def test_sort_method_raises_error_val(): \"\"\"Test if error gets raised for invalid type.\"\"\" with pytest.raises(ValueError): quick_sort([1,",
"@pytest.fixture(scope='function') def rand_ten(): \"\"\"Make a random list of length 10.\"\"\" return [randint(0, 1000)",
"= quick_sort(rand_neg) assert key == result def test_sort_nums_in_list_random_case(rand_ten): \"\"\"Test quick sort function.\"\"\" result",
"\"\"\"Test if error gets raised for invalid type.\"\"\" with pytest.raises(ValueError): quick_sort('12345') def test_sort_method_raises_error_val():",
"== key def test_sort_nums_in_tuple_random_case(rand_ten): \"\"\"Test quick sort function.\"\"\" rand = tuple(rand_ten) result =",
"random import randint @pytest.fixture(scope='function') def list_ten(): \"\"\"Make a list of 10 vals.\"\"\" return",
"pytest.raises(ValueError): quick_sort([1, 2, '3']) def test_sort_method_raise_error_dic(): \"\"\"Test if error gets raised for invalid",
"of length 10.\"\"\" return [randint(0, 1000) for _ in range(10)] @pytest.fixture(scope='function') def rand_neg():",
"assert key == result def test_sort_nums_in_list_random_case(rand_ten): \"\"\"Test quick sort function.\"\"\" result = quick_sort(rand_ten)",
"test_sort_nums_in_tuple_wrose_case(list_ten): \"\"\"Test quick sort function.\"\"\" reverse = tuple(reversed(list_ten)) result = quick_sort(reverse) assert result",
"import randint @pytest.fixture(scope='function') def list_ten(): \"\"\"Make a list of 10 vals.\"\"\" return [x",
"return [x for x in range(10)] @pytest.fixture(scope='function') def rand_ten(): \"\"\"Make a random list",
"list(reversed(list_ten)) result = quick_sort(reverse) assert result == list_ten def test_sort_nums_in_tuple_wrose_case(list_ten): \"\"\"Test quick sort",
"result == list_ten def test_sort_method_raises_error(): \"\"\"Test if error gets raised for invalid type.\"\"\"",
"with pytest.raises(ValueError): quick_sort([1, 2, '3']) def test_sort_method_raise_error_dic(): \"\"\"Test if error gets raised for",
"\"\"\"Test if error gets raised for invalid type.\"\"\" with pytest.raises(ValueError): quick_sort([1, 2, '3'])",
"result == key def test_sort_nums_in_list_wrose_case_helper(list_ten): \"\"\"Test _quick sort function.\"\"\" reverse = list(reversed(list_ten)) result",
"range(100)] def test_sort_list_with_neg_values(rand_neg): \"\"\"Test if sorting method sorts negative values.\"\"\" key = sorted(rand_neg)",
"== list_ten def test_sort_method_raises_error(): \"\"\"Test if error gets raised for invalid type.\"\"\" with",
"[randint(-1000, 0) for _ in range(100)] def test_sort_list_with_neg_values(rand_neg): \"\"\"Test if sorting method sorts",
"invalid type.\"\"\" with pytest.raises(ValueError): quick_sort('12345') def test_sort_method_raises_error_val(): \"\"\"Test if error gets raised for",
"[x for x in range(10)] @pytest.fixture(scope='function') def rand_ten(): \"\"\"Make a random list of",
"reverse = tuple(reversed(list_ten)) result = quick_sort(reverse) assert result == list_ten def test_sort_method_raises_error(): \"\"\"Test",
"rand_neg(): \"\"\"Make a random list of neg value list len 100.\"\"\" return [randint(-1000,",
"sorted(rand_ten) assert result == key def test_sort_nums_in_tuple_random_case(rand_ten): \"\"\"Test quick sort function.\"\"\" rand =",
"quick_sort(rand) key = sorted(rand) assert result == key def test_sort_nums_in_list_wrose_case(list_ten): \"\"\"Test quick sort",
"with pytest.raises(ValueError): quick_sort([1, 2, 3, 'p']) def test_sort_nums_in_list_random_case_helper(rand_ten): \"\"\"Test quick sort function.\"\"\" result",
"quick_sort('12345') def test_sort_method_raises_error_val(): \"\"\"Test if error gets raised for invalid type.\"\"\" with pytest.raises(ValueError):",
"import pytest from random import randint @pytest.fixture(scope='function') def list_ten(): \"\"\"Make a list of",
"method sorts negative values.\"\"\" key = sorted(rand_neg) result = quick_sort(rand_neg) assert key ==",
"key = sorted(rand) assert result == key def test_sort_nums_in_list_wrose_case(list_ten): \"\"\"Test quick sort function.\"\"\"",
"= quick_sort(reverse) assert result == list_ten def test_sort_nums_in_tuple_wrose_case(list_ten): \"\"\"Test quick sort function.\"\"\" reverse",
"result == key def test_sort_nums_in_list_wrose_case(list_ten): \"\"\"Test quick sort function.\"\"\" reverse = list(reversed(list_ten)) result",
"2, '3']) def test_sort_method_raise_error_dic(): \"\"\"Test if error gets raised for invalid type.\"\"\" with",
"function.\"\"\" reverse = list(reversed(list_ten)) result = quick_sort(reverse) assert result == list_ten def test_sort_nums_in_tuple_wrose_case(list_ten):",
"\"\"\"Make a random list of neg value list len 100.\"\"\" return [randint(-1000, 0)",
"def test_sort_nums_in_list_random_case_helper(rand_ten): \"\"\"Test quick sort function.\"\"\" result = quick_sort(rand_ten) key = sorted(rand_ten) assert",
"def test_sort_nums_in_list_random_case(rand_ten): \"\"\"Test quick sort function.\"\"\" result = quick_sort(rand_ten) key = sorted(rand_ten) assert",
"== key def test_sort_nums_in_list_wrose_case(list_ten): \"\"\"Test quick sort function.\"\"\" reverse = list(reversed(list_ten)) result =",
"key def test_sort_nums_in_tuple_random_case(rand_ten): \"\"\"Test quick sort function.\"\"\" rand = tuple(rand_ten) result = quick_sort(rand)",
"test_sort_method_raise_error_dic(): \"\"\"Test if error gets raised for invalid type.\"\"\" with pytest.raises(ValueError): quick_sort({1, 2,"
] |
[
"term. All violations of (1),(2) or (3) will be handled in accordance with",
"function, you agree with the following terms: (1) Not sharing your code/solution with",
"-------- * a: the index of the action being chosen by the player,",
"nose -v test1.py:test_choose_action_explore --- OR ---- python -m nose -v test1.py:test_choose_action_explore --------------------------------------------------- '''",
"1. * This problem can be solved using 1 line(s) of code. '''",
"of code. ''' #--------------------- def choose_action_explore(c): ######################################### ## INSERT YOUR CODE HERE (3",
"index of the action being chosen by the player, an integer scalar between",
"the homework due. For example, sending your code segment to another student, putting",
"bandit problem, an integer scalar. ---- Outputs: -------- * a: the index of",
"recently) will violate this term. Changing other's code as your solution (such as",
"nosetests -v test1.py --- OR ---- python3 -m nose -v test1.py --- OR",
"problem, you will implement the epsilon-greedy method for Multi-armed bandit problem. A list",
"samples collected on the i-th action, i.e., how many times the i-th action",
"of the largest value in a vector. * This problem can be solved",
"test1.py:test_update_memory --------------------------------------------------- ''' #---------------------------------------------------- ''' (Explore-only) Given a multi-armed bandit game, choose an",
"new package. You should solve this problem using only the package(s) above. #-------------------------------------------------------------------------",
"Ct: (player's memory) the counts on how many times each action has been",
"using 2 line(s) of code. ''' #--------------------- def update_memory(a, r, Rt, Ct): #########################################",
"code. ''' #--------------------- def choose_action_explore(c): ######################################### ## INSERT YOUR CODE HERE (3 points)",
"r Ct[a] = Ct[a] + 1 ######################################### #----------------- ''' TEST: Now you can",
"to another student, putting your solution online or lending your laptop (if your",
"If your code passed all the tests, you will see the following message",
"length c. Rt_1[i] represents the sum of total rewards collected on the i-th",
"about the previous results, choose an action at the current step of the",
"* r: the reward received at the current time step, a float scalar.",
"#---------------------------------------------------- ''' Given a multi-armed bandit game and the player's memory about the",
"---- python3 -m nose -v test1.py:test_update_memory --- OR ---- python -m nose -v",
"---- Hints: -------- * This problem can be solved using 2 line(s) of",
"method for Multi-armed bandit problem. A list of all variables being used in",
"the terminal: ----------- Problem 1 (15 points in total)--------------------- ... ok * (3",
"student or online resources due to any reason (like too busy recently) will",
"Randomly pick an action with uniform distribution: equal probability for all actions. ----",
"you have read and agree with the term above, change \"False\" to \"True\".",
"If the count in Ct[i] for the i-th action is 0, we can",
"above by typing the following in the terminal: --------------------------------------------------- nosetests -v test1.py:test_update_memory ---",
"integer scalar. * e: (epsilon) the probability of the player to follow the",
"probability of the player to follow the exploration-only strategy. e is a float",
"or only with minor differences (variable names are different). In this case, the",
"the current time step using explore-only strategy. Randomly pick an action with uniform",
"time step to follow the exploitation-only strategy. ---- Outputs: -------- * a: the",
"above by typing the following in the terminal: --------------------------------------------------- nosetests -v test1.py:test_choose_action_explore ---",
"in the terminal: --------------------------------------------------- nosetests -v test1.py:test_update_memory --- OR ---- python3 -m nose",
"Ct_1[i] represents the total number of samples collected on the i-th action, i.e.,",
"#******************************************* # CHANGE HERE: if you have read and agree with the term",
"You could use the random.rand() function in numpy to sample a number randomly",
"function in numpy to sample a number randomly using uniform distribution between 0",
"index of the largest value in a vector. * This problem can be",
"the i-th action has been tried before\". ---- Outputs: -------- * a: the",
"we ended up finding 25% of the students in that class violating this",
"by typing the following in the terminal: --------------------------------------------------- nosetests -v test1.py:test_update_memory --- OR",
"by typing the following in the terminal: --------------------------------------------------- nosetests -v test1.py:test_choose_action_exploit --- OR",
"before\". ---- Hints: -------- * This problem can be solved using 2 line(s)",
"sum of rewards) collected for each action, a numpy float vector of length",
"(choose the action with the highest average reward). ---- Inputs: -------- * Rt:",
"can test the correctness of all the above functions by typing the following",
"your code segment to another student, putting your solution online or lending your",
"When discussing with any other students about this homework, only discuss high-level ideas",
"many times the i-th action has been tried before\". ---- Outputs: -------- *",
"memory about the previous results, choose an action at the current step of",
"to any reason (like too busy recently) will violate this term. Changing other's",
"-------- * This problem can be solved using 1 line(s) of code. '''",
"''' #-------------------------------------------- ''' TEST problem 1: Now you can test the correctness of",
"c) ######################################### return a #----------------- ''' TEST: Now you can test the correctness",
"the terminal: --------------------------------------------------- nosetests -v test1.py:test_choose_action_exploit --- OR ---- python3 -m nose -v",
"previous results, choose an action at the current step of the game using",
"tried before\". ---- Outputs: -------- * a: the index of the action being",
"for the i-th action is 0. For example, if the count Ct for",
"Note: we may use the Stanford Moss system to check your code for",
"and after the homework due. For example, sending your code segment to another",
"(player's memory) the total rewards (i.e., sum of rewards) collected for each action,",
"######################################### #----------------- ''' TEST: Now you can test the correctness of your code",
"nosetests -v test1.py:test_update_memory --- OR ---- python3 -m nose -v test1.py:test_update_memory --- OR",
"this file. ''' #-------------------------- def Terms_and_Conditions(): ''' By submitting this homework or changing",
"current time step, update the player's memory. ---- Inputs: -------- * a: the",
"ok * (3 points) choose_action_explore ... ok * (3 points) choose_action_exploit ... ok",
"import numpy as np # Note: please don't import any new package. You",
"only the package(s) above. #------------------------------------------------------------------------- ''' Problem 1: Multi-Armed Bandit Problem (15 points)",
"reward for the i-th action is 0. For example, if the count Ct",
"online resources due to any reason (like too busy recently) will violate this",
"the previous results, choose an action at the current time step using exploit-only",
"method (randomly choose an action) and with a large probability (1-epsilon) to follow",
"test1.py --- OR ---- python3 -m nose -v test1.py --- OR ---- python",
"-m nose -v test1.py --------------------------------------------------- If your code passed all the tests, you",
"laptop) to another student to work on this homework will violate this term.",
"this term. (2) Not using anyone's code in this homework and building your",
"(epsilon) the probability of the player to follow the exploration-only strategy. e is",
"average reward. ---- Inputs: -------- * Rt: (player's memory) the total rewards (i.e.,",
"(Explore-only) Given a multi-armed bandit game, choose an action at the current time",
"many times each action has been tried, a numpy integer vector of length",
"player's memory about the previous results, choose an action at the current time",
"import any new package. You should solve this problem using only the package(s)",
"minor differences (variable names are different). In this case, the two students violate",
"code passed all the tests, you will see the following message in the",
"-------- * This problem can be solved using 2 line(s) of code. '''",
"of length c. Ct_1[i] represents the total number of samples collected on the",
"typing the following in the terminal: --------------------------------------------------- nosetests -v test1.py --- OR ----",
"bandit problem, an integer scalar. * e: (epsilon) the probability of the player",
"the term above, change \"False\" to \"True\". Read_and_Agree = True #******************************************* return Read_and_Agree",
"times each action has been tried, a numpy integer vector of length c.",
"--- OR ---- python3 -m nose -v test1.py:test_choose_action_explore --- OR ---- python -m",
"Ran 4 tests in 0.586s OK ''' #-------------------------------------------- #-------------------------------------------- ''' List of All",
"changing this function, you agree with the following terms: (1) Not sharing your",
"due to any reason (like too busy recently) will violate this term. Changing",
"the following in the terminal: --------------------------------------------------- nosetests -v test1.py:test_choose_action --- OR ---- python3",
"Given a multi-armed bandit game and the player's memory about the previous results,",
"player has 1-e probability in each time step to follow the exploitation-only strategy.",
"--- OR ---- python3 -m nose -v test1.py:test_choose_action --- OR ---- python -m",
"''' #--------------------- def choose_action_explore(c): ######################################### ## INSERT YOUR CODE HERE (3 points) a",
"--------------------------------------------------- nosetests -v test1.py:test_update_memory --- OR ---- python3 -m nose -v test1.py:test_update_memory ---",
"read and agree with the term above, change \"False\" to \"True\". Read_and_Agree =",
"for the i-th action is 0, we can assume the average reward for",
"the following in the terminal: --------------------------------------------------- nosetests -v test1.py:test_choose_action_exploit --- OR ---- python3",
"be handled in accordance with the WPI Academic Honesty Policy. For more details,",
"at the current time step using exploit-only strategy: choose the action with the",
"YOUR CODE HERE (3 points) a = np.argmax([0 if Ct[i] == 0 else",
"Historical Data: in one year, we ended up finding 25% of the students",
"return the index of the largest value in a vector. * This problem",
"a: the index of the action being chosen by the player, an integer",
"line(s) of code. ''' #--------------------- def update_memory(a, r, Rt, Ct): ######################################### ## INSERT",
"for all actions. ---- Inputs: -------- * c: the number of possible actions",
"solution \"independently\", however the code of the two solutions are exactly the same,",
"example, sending your code segment to another student, putting your solution online or",
"have read and agree with the term above, change \"False\" to \"True\". Read_and_Agree",
"reason (like too busy recently) will violate this term. Changing other's code as",
"exploitation-only strategy. ---- Outputs: -------- * a: the index of the action being",
"OR ---- python3 -m nose -v test1.py --- OR ---- python -m nose",
"--- OR ---- python -m nose -v test1.py --------------------------------------------------- If your code passed",
"the i-th action is 0, we can assume the average reward for the",
"code above by typing the following in the terminal: --------------------------------------------------- nosetests -v test1.py:test_choose_action_exploit",
"choose an action at the current step of the game using epsilon-greedy method:",
"following in the terminal: --------------------------------------------------- nosetests -v test1.py --- OR ---- python3 -m",
"''' #--------------------- def choose_action(Rt, Ct, e=0.05): ######################################### ## INSERT YOUR CODE HERE (6",
"up finding 25% of the students in that class violating this term in",
"in their homework submissions and we handled ALL of these violations according to",
"ok ---------------------------------------------------------------------- Ran 4 tests in 0.586s OK ''' #-------------------------------------------- #-------------------------------------------- ''' List",
"---- python -m nose -v test1.py:test_choose_action_explore --------------------------------------------------- ''' #---------------------------------------------------- ''' (Exploit-only) Given a",
"of (1),(2) or (3) will be handled in accordance with the WPI Academic",
"a multi-armed bandit game, choose an action at the current time step using",
"code above by typing the following in the terminal: --------------------------------------------------- nosetests -v test1.py:test_choose_action_explore",
"above. #------------------------------------------------------------------------- ''' Problem 1: Multi-Armed Bandit Problem (15 points) In this problem,",
"(1),(2) or (3) will be handled in accordance with the WPI Academic Honesty",
"an integer scalar between 0 and c-1. ---- Hints: -------- * If the",
"above functions by typing the following in the terminal: --------------------------------------------------- nosetests -v test1.py",
"1 (15 points in total)--------------------- ... ok * (3 points) update_memory ... ok",
"the total number of samples collected on the i-th action, i.e., how many",
"with uniform distribution: equal probability for all actions. ---- Inputs: -------- * c:",
"homework due. For example, sending your code segment to another student, putting your",
"will see the following message in the terminal: ----------- Problem 1 (15 points",
"strategy. * Rt: (player's memory) the total rewards (i.e., sum of rewards) collected",
"(1) Not sharing your code/solution with any student before and after the homework",
"--------------------------------------------------- nosetests -v test1.py:test_choose_action --- OR ---- python3 -m nose -v test1.py:test_choose_action ---",
"violating this term in their homework submissions and we handled ALL of these",
"scalar between 0 and c-1. * r: the reward received at the current",
"line(s) of code. ''' #--------------------- def choose_action_exploit(Rt, Ct): ######################################### ## INSERT YOUR CODE",
"the WPI Academic Honesty Policy. For more details, please visit: https://www.wpi.edu/about/policies/academic-integrity/dishonesty Note: we",
"... ok ---------------------------------------------------------------------- Ran 4 tests in 0.586s OK ''' #-------------------------------------------- #-------------------------------------------- '''",
"for the first action is 0. * You could us the argmax() function",
"term. (2) Not using anyone's code in this homework and building your own",
"Honesty Policy. For more details, please visit: https://www.wpi.edu/about/policies/academic-integrity/dishonesty Note: we may use the",
"[0,1,1], we can assume the average reward for the first action is 0.",
"for 3 actions are [0,1,1], we can assume the average reward for the",
"action at the current time step using exploit-only strategy: choose the action with",
"-v test1.py:test_choose_action_explore --- OR ---- python3 -m nose -v test1.py:test_choose_action_explore --- OR ----",
"choose_action ... ok ---------------------------------------------------------------------- Ran 4 tests in 0.586s OK ''' #-------------------------------------------- #--------------------------------------------",
"problem, an integer scalar. ---- Outputs: -------- * a: the index of the",
"in the terminal: ----------- Problem 1 (15 points in total)--------------------- ... ok *",
"random.rand() function in numpy to sample a number randomly using uniform distribution between",
"using 1 line(s) of code. ''' #--------------------- def choose_action(Rt, Ct, e=0.05): ######################################### ##",
"code above by typing the following in the terminal: --------------------------------------------------- nosetests -v test1.py:test_choose_action",
"sending your code segment to another student, putting your solution online or lending",
"scalar. * e: (epsilon) the probability of the player to follow the exploration-only",
"your laptop contains your solution or your Dropbox automatically copied your solution from",
"All Variables * c: the number of possible actions in a multi-armed bandit",
"* (3 points) update_memory ... ok * (3 points) choose_action_explore ... ok *",
"#--------------------- def update_memory(a, r, Rt, Ct): ######################################### ## INSERT YOUR CODE HERE (3",
"solution online or lending your laptop (if your laptop contains your solution or",
"\"False\" to \"True\". Read_and_Agree = True #******************************************* return Read_and_Agree #---------------------------------------------------- ''' Given the",
"--- OR ---- python3 -m nose -v test1.py --- OR ---- python -m",
"the two solutions are exactly the same, or only with minor differences (variable",
"in 0.586s OK ''' #-------------------------------------------- #-------------------------------------------- ''' List of All Variables * c:",
"or changing this function, you agree with the following terms: (1) Not sharing",
"or use pseudo-code. Don't discuss about the solution at the code level. For",
"numpy to sample a number randomly using uniform distribution between 0 and 1.",
"memory. ---- Inputs: -------- * a: the index of the action being chosen",
"... ok * (6 points) choose_action ... ok ---------------------------------------------------------------------- Ran 4 tests in",
"integer scalar between 0 and c-1. ---- Hints: -------- * You could use",
"points) Rt[a] = Rt[a] + r Ct[a] = Ct[a] + 1 ######################################### #-----------------",
"tried before\". * a: the index of the action being chosen by the",
"using 1 line(s) of code. ''' #--------------------- def choose_action_exploit(Rt, Ct): ######################################### ## INSERT",
"np # Note: please don't import any new package. You should solve this",
"choose_action_explore(Ct.size) if np.random.random() < e else choose_action_exploit(Rt, Ct) ######################################### return a #----------------- '''",
"the following terms: (1) Not sharing your code/solution with any student before and",
"nose -v test1.py:test_choose_action --------------------------------------------------- ''' #-------------------------------------------- ''' TEST problem 1: Now you can",
"this homework, only discuss high-level ideas or use pseudo-code. Don't discuss about the",
"in the terminal: --------------------------------------------------- nosetests -v test1.py:test_choose_action --- OR ---- python3 -m nose",
"typing the following in the terminal: --------------------------------------------------- nosetests -v test1.py:test_choose_action_explore --- OR ----",
"By submitting this homework or changing this function, you agree with the following",
"---- Outputs: -------- * a: the index of the action being chosen by",
"in this homework and building your own solution. For example, using some code",
"python3 -m nose -v test1.py:test_choose_action_explore --- OR ---- python -m nose -v test1.py:test_choose_action_explore",
"reward received at the current time step, update the player's memory. ---- Inputs:",
"in numpy to sample a number randomly using uniform distribution between 0 and",
"by typing the following in the terminal: --------------------------------------------------- nosetests -v test1.py:test_choose_action_explore --- OR",
"a multi-armed bandit game and the player's memory about the previous results, choose",
"vector. * This problem can be solved using 1 line(s) of code. '''",
"then work on the solution \"independently\", however the code of the two solutions",
"Problem (15 points) In this problem, you will implement the epsilon-greedy method for",
"\"True\". Read_and_Agree = True #******************************************* return Read_and_Agree #---------------------------------------------------- ''' Given the player's memory",
"--- OR ---- python -m nose -v test1.py:test_choose_action_explore --------------------------------------------------- ''' #---------------------------------------------------- ''' (Exploit-only)",
"can be solved using 1 line(s) of code. ''' #--------------------- def choose_action_explore(c): #########################################",
"follow the exploration-only strategy. e is a float scalar between 0 and 1.",
"highest average reward. ---- Inputs: -------- * Rt: (player's memory) the total rewards",
"another student, putting your solution online or lending your laptop (if your laptop",
"Problem 1: Multi-Armed Bandit Problem (15 points) In this problem, you will implement",
"c. Ct_1[i] represents the total number of samples collected on the i-th action,",
"the argmax() function in numpy to return the index of the largest value",
"choose the action with the highest average reward. ---- Inputs: -------- * Rt:",
"the highest average reward). ---- Inputs: -------- * Rt: (player's memory) the total",
"own solution. For example, using some code segments from another student or online",
"update the player's memory. ---- Inputs: -------- * a: the index of the",
"player, an integer scalar between 0 and c-1. ---- Hints: -------- * If",
"work on the solution \"independently\", however the code of the two solutions are",
"Hints: -------- * If the count in Ct[i] for the i-th action is",
"they then work on the solution \"independently\", however the code of the two",
"are different). In this case, the two students violate this term. All violations",
"OR ---- python3 -m nose -v test1.py:test_choose_action_exploit --- OR ---- python -m nose",
"terms: (1) Not sharing your code/solution with any student before and after the",
"homework, only discuss high-level ideas or use pseudo-code. Don't discuss about the solution",
"Ct[i] == 0 else Rt[i] / Ct[i] for i in range(Rt.size)]) ######################################### return",
"test1.py:test_choose_action --- OR ---- python -m nose -v test1.py:test_choose_action --------------------------------------------------- ''' #-------------------------------------------- '''",
"Read_and_Agree = True #******************************************* return Read_and_Agree #---------------------------------------------------- ''' Given the player's memory about",
"in a vector. * This problem can be solved using 1 line(s) of",
"has been tried before\". ---- Hints: -------- * This problem can be solved",
"of possible actions in a multi-armed bandit problem, an integer scalar. ---- Outputs:",
"HERE (3 points) a = np.argmax([0 if Ct[i] == 0 else Rt[i] /",
"the following message in the terminal: ----------- Problem 1 (15 points in total)---------------------",
"a = np.argmax([0 if Ct[i] == 0 else Rt[i] / Ct[i] for i",
"to solve) and they then work on the solution \"independently\", however the code",
"-v test1.py:test_choose_action --- OR ---- python -m nose -v test1.py:test_choose_action --------------------------------------------------- ''' #--------------------------------------------",
"the package(s) above. #------------------------------------------------------------------------- ''' Problem 1: Multi-Armed Bandit Problem (15 points) In",
"Hints: -------- * You could use the random.rand() function in numpy to sample",
"lending your laptop (if your laptop contains your solution or your Dropbox automatically",
"the current time step, update the player's memory. ---- Inputs: -------- * a:",
"can assume the average reward for the first action is 0. * You",
"has 1-e probability in each time step to follow the exploitation-only strategy. ----",
"violate this term. (2) Not using anyone's code in this homework and building",
"-------- * You could use the random.rand() function in numpy to sample a",
"vector of length c. Ct_1[i] represents the total number of samples collected on",
"to the WPI Academic Honesty Policy. ''' #******************************************* # CHANGE HERE: if you",
"to another student to work on this homework will violate this term. (2)",
"#---------------------------------------------------- ''' (Explore-only) Given a multi-armed bandit game, choose an action at the",
"Rt[i] / Ct[i] for i in range(Rt.size)]) ######################################### return a #----------------- ''' TEST:",
"of code. ''' #--------------------- def choose_action_exploit(Rt, Ct): ######################################### ## INSERT YOUR CODE HERE",
"CODE HERE (6 points) a = choose_action_explore(Ct.size) if np.random.random() < e else choose_action_exploit(Rt,",
"time step, update the player's memory. ---- Inputs: -------- * a: the index",
"solved using 1 line(s) of code. ''' #--------------------- def choose_action_exploit(Rt, Ct): ######################################### ##",
"is 0. * You could us the argmax() function in numpy to return",
"INSERT YOUR CODE HERE (3 points) Rt[a] = Rt[a] + r Ct[a] =",
"variables being used in this problem is provided at the end of this",
"Ct): ######################################### ## INSERT YOUR CODE HERE (3 points) a = np.argmax([0 if",
"Rt: (player's memory) the total rewards (i.e., sum of rewards) collected for each",
"example, if the count Ct for 3 actions are [0,1,1], we can assume",
"You could us the argmax() function in numpy to return the index of",
"TEST: Now you can test the correctness of your code above by typing",
"Don't discuss about the solution at the code level. For example, two students",
"total)--------------------- ... ok * (3 points) update_memory ... ok * (3 points) choose_action_explore",
"represents the total number of samples collected on the i-th action, i.e., how",
"---- Inputs: -------- * c: the number of possible actions in a multi-armed",
"step using exploit-only strategy: choose the action with the highest average reward. ----",
"/ Ct[i] for i in range(Rt.size)]) ######################################### return a #----------------- ''' TEST: Now",
"r, Rt, Ct): ######################################### ## INSERT YOUR CODE HERE (3 points) Rt[a] =",
"two solutions are exactly the same, or only with minor differences (variable names",
"submitting this homework or changing this function, you agree with the following terms:",
"(randomly choose an action) and with a large probability (1-epsilon) to follow exploit-only",
"of All Variables * c: the number of possible actions in a multi-armed",
"this homework and building your own solution. For example, using some code segments",
"the total rewards (i.e., sum of rewards) collected for each action, a numpy",
"(2) Not using anyone's code in this homework and building your own solution.",
"and the player's memory about the previous results, choose an action at the",
"in each time step to follow the exploitation-only strategy. * Rt: (player's memory)",
"ideas or use pseudo-code. Don't discuss about the solution at the code level.",
"on the i-th action, i.e., how many times the i-th action has been",
"Inputs: -------- * c: the number of possible actions in a multi-armed bandit",
"List of All Variables * c: the number of possible actions in a",
"---- Hints: -------- * This problem can be solved using 1 line(s) of",
"the variable names) will also violate this term. (3) When discussing with any",
"between 0 and c-1. ---- Hints: -------- * If the count in Ct[i]",
"step using explore-only strategy. Randomly pick an action with uniform distribution: equal probability",
"current time step, a float scalar. * Rt: (player's memory) the total rewards",
"an action with uniform distribution: equal probability for all actions. ---- Inputs: --------",
"action has been tried before\". ---- Outputs: -------- * a: the index of",
"solved using 1 line(s) of code. ''' #--------------------- def choose_action_explore(c): ######################################### ## INSERT",
"rewards (i.e., sum of rewards) collected for each action, a numpy float vector",
"handled in accordance with the WPI Academic Honesty Policy. For more details, please",
"sum of total rewards collected on the i-th action. * Ct: (player's memory)",
"problem, an integer scalar. * e: (epsilon) the probability of the player to",
"For example, two students discuss about the solution of a function (which needs",
"terminal: --------------------------------------------------- nosetests -v test1.py --- OR ---- python3 -m nose -v test1.py",
"the WPI Academic Honesty Policy. ''' #******************************************* # CHANGE HERE: if you have",
"#******************************************* return Read_and_Agree #---------------------------------------------------- ''' Given the player's memory about the previous results",
"problem can be solved using 2 line(s) of code. ''' #--------------------- def update_memory(a,",
"bandit problem. A list of all variables being used in this problem is",
"following in the terminal: --------------------------------------------------- nosetests -v test1.py:test_choose_action_exploit --- OR ---- python3 -m",
"with a small probability (epsilon) to follow explore-only method (randomly choose an action)",
"an integer scalar between 0 and c-1. * r: the reward received at",
"A list of all variables being used in this problem is provided at",
"message in the terminal: ----------- Problem 1 (15 points in total)--------------------- ... ok",
"-v test1.py:test_choose_action_exploit --------------------------------------------------- ''' #---------------------------------------------------- ''' Given a multi-armed bandit game and the",
"line(s) of code. ''' #--------------------- def choose_action(Rt, Ct, e=0.05): ######################################### ## INSERT YOUR",
"Ct for 3 actions are [0,1,1], we can assume the average reward for",
"c-1. ---- Hints: -------- * This problem can be solved using 1 line(s)",
"INSERT YOUR CODE HERE (3 points) a = np.argmax([0 if Ct[i] == 0",
"action is 0, we can assume the average reward for the i-th action",
"by typing the following in the terminal: --------------------------------------------------- nosetests -v test1.py --- OR",
"the game and the action chosen and reward received at the current time",
"#---------------------------------------------------- ''' Given the player's memory about the previous results in the game",
"* (6 points) choose_action ... ok ---------------------------------------------------------------------- Ran 4 tests in 0.586s OK",
"code similarity. https://theory.stanford.edu/~aiken/moss/ Historical Data: in one year, we ended up finding 25%",
"you will implement the epsilon-greedy method for Multi-armed bandit problem. A list of",
"player, an integer scalar between 0 and c-1. ---- Hints: -------- * You",
"OR ---- python -m nose -v test1.py:test_choose_action --------------------------------------------------- ''' #-------------------------------------------- ''' TEST problem",
"action at the current time step using explore-only strategy. Randomly pick an action",
"test1.py:test_choose_action --------------------------------------------------- ''' #-------------------------------------------- ''' TEST problem 1: Now you can test the",
"and building your own solution. For example, using some code segments from another",
"python3 -m nose -v test1.py:test_choose_action --- OR ---- python -m nose -v test1.py:test_choose_action",
"player to follow the exploration-only strategy. e is a float scalar between 0",
"Hints: -------- * This problem can be solved using 1 line(s) of code.",
"0 and c-1. ---- Hints: -------- * You could use the random.rand() function",
"time step using exploit-only strategy: choose the action with the highest average reward.",
"by the player, an integer scalar between 0 and c-1. ---- Hints: --------",
"You should solve this problem using only the package(s) above. #------------------------------------------------------------------------- ''' Problem",
"or (3) will be handled in accordance with the WPI Academic Honesty Policy.",
"OR ---- python -m nose -v test1.py:test_choose_action_explore --------------------------------------------------- ''' #---------------------------------------------------- ''' (Exploit-only) Given",
"the Stanford Moss system to check your code for code similarity. https://theory.stanford.edu/~aiken/moss/ Historical",
"multi-armed bandit game, choose an action at the current time step using explore-only",
"will violate this term. Changing other's code as your solution (such as changing",
"the count in Ct[i] for the i-th action is 0, we can assume",
"''' TEST: Now you can test the correctness of your code above by",
"c: the number of possible actions in a multi-armed bandit problem, an integer",
"1-e probability in each time step to follow the exploitation-only strategy. ---- Outputs:",
"python -m nose -v test1.py:test_choose_action --------------------------------------------------- ''' #-------------------------------------------- ''' TEST problem 1: Now",
"this problem using only the package(s) above. #------------------------------------------------------------------------- ''' Problem 1: Multi-Armed Bandit",
"---- python3 -m nose -v test1.py:test_choose_action_explore --- OR ---- python -m nose -v",
"will violate this term. (2) Not using anyone's code in this homework and",
"work on this homework will violate this term. (2) Not using anyone's code",
"0. * You could us the argmax() function in numpy to return the",
"about the previous results, choose an action at the current time step using",
"a number randomly using uniform distribution between 0 and 1. * This problem",
"---- python -m nose -v test1.py --------------------------------------------------- If your code passed all the",
"homework and building your own solution. For example, using some code segments from",
"this homework or changing this function, you agree with the following terms: (1)",
"the player, an integer scalar between 0 and c-1. ---- Hints: -------- *",
"-v test1.py:test_choose_action --- OR ---- python3 -m nose -v test1.py:test_choose_action --- OR ----",
"* You could use the random.rand() function in numpy to sample a number",
"any new package. You should solve this problem using only the package(s) above.",
"violations according to the WPI Academic Honesty Policy. ''' #******************************************* # CHANGE HERE:",
"be solved using 1 line(s) of code. ''' #--------------------- def choose_action_explore(c): ######################################### ##",
"epsilon-greedy method for Multi-armed bandit problem. A list of all variables being used",
"explore-only method (randomly choose an action) and with a large probability (1-epsilon) to",
"* If the count in Ct[i] for the i-th action is 0, we",
"np.random.randint(0, c) ######################################### return a #----------------- ''' TEST: Now you can test the",
"Ct[a] + 1 ######################################### #----------------- ''' TEST: Now you can test the correctness",
"OR ---- python -m nose -v test1.py --------------------------------------------------- If your code passed all",
"the students in that class violating this term in their homework submissions and",
"--- OR ---- python -m nose -v test1.py:test_choose_action_exploit --------------------------------------------------- ''' #---------------------------------------------------- ''' Given",
"Terms_and_Conditions(): ''' By submitting this homework or changing this function, you agree with",
"provided at the end of this file. ''' #-------------------------- def Terms_and_Conditions(): ''' By",
"any other students about this homework, only discuss high-level ideas or use pseudo-code.",
"a vector. * This problem can be solved using 1 line(s) of code.",
"at the current time step, a float scalar. * Rt: (player's memory) the",
"of the two solutions are exactly the same, or only with minor differences",
"the solution \"independently\", however the code of the two solutions are exactly the",
"Multi-armed bandit problem. A list of all variables being used in this problem",
"= Ct[a] + 1 ######################################### #----------------- ''' TEST: Now you can test the",
"also violate this term. (3) When discussing with any other students about this",
"your laptop) to another student to work on this homework will violate this",
"accordance with the WPI Academic Honesty Policy. For more details, please visit: https://www.wpi.edu/about/policies/academic-integrity/dishonesty",
"an integer scalar between 0 and c-1. ---- Hints: -------- * You could",
"a multi-armed bandit problem, an integer scalar. * e: (epsilon) the probability of",
"after the homework due. For example, sending your code segment to another student,",
"--------------------------------------------------- ''' #-------------------------------------------- ''' TEST problem 1: Now you can test the correctness",
"only discuss high-level ideas or use pseudo-code. Don't discuss about the solution at",
"the two students violate this term. All violations of (1),(2) or (3) will",
"typing the following in the terminal: --------------------------------------------------- nosetests -v test1.py:test_choose_action_exploit --- OR ----",
"rewards collected on the i-th action. * Ct: (player's memory) the counts on",
"due. For example, sending your code segment to another student, putting your solution",
"to return the index of the largest value in a vector. * This",
"this problem is provided at the end of this file. ''' #-------------------------- def",
"''' #-------------------------- def Terms_and_Conditions(): ''' By submitting this homework or changing this function,",
"scalar between 0 and 1. The player has 1-e probability in each time",
"the average reward for the i-th action is 0. For example, if the",
"Dropbox automatically copied your solution from your desktop computer and your laptop) to",
"... ok * (3 points) update_memory ... ok * (3 points) choose_action_explore ...",
"an action at the current step of the game using epsilon-greedy method: with",
"0 and c-1. ---- Hints: -------- * If the count in Ct[i] for",
"the above functions by typing the following in the terminal: --------------------------------------------------- nosetests -v",
"choose_action_exploit(Rt, Ct) ######################################### return a #----------------- ''' TEST: Now you can test the",
"e is a float scalar between 0 and 1. The player has 1-e",
"test the correctness of all the above functions by typing the following in",
"and with a large probability (1-epsilon) to follow exploit-only method (choose the action",
"the reward received at the current time step, a float scalar. ''' #--------------------------------------------",
"being chosen by the player, an integer scalar between 0 and c-1. ----",
"Problem 1 (15 points in total)--------------------- ... ok * (3 points) update_memory ...",
"case, the two students violate this term. All violations of (1),(2) or (3)",
"(3) will be handled in accordance with the WPI Academic Honesty Policy. For",
"count Ct for 3 actions are [0,1,1], we can assume the average reward",
"of rewards) collected for each action, a numpy float vector of length c.",
"the current step of the game using epsilon-greedy method: with a small probability",
"test1.py:test_update_memory --- OR ---- python -m nose -v test1.py:test_update_memory --------------------------------------------------- ''' #---------------------------------------------------- '''",
"the action with the highest average reward. ---- Inputs: -------- * Rt: (player's",
"######################################### ## INSERT YOUR CODE HERE (3 points) Rt[a] = Rt[a] + r",
"terminal: --------------------------------------------------- nosetests -v test1.py:test_choose_action --- OR ---- python3 -m nose -v test1.py:test_choose_action",
"action. * Ct: (player's memory) the counts on how many times each action",
"homework submissions and we handled ALL of these violations according to the WPI",
"probability (epsilon) to follow explore-only method (randomly choose an action) and with a",
"using only the package(s) above. #------------------------------------------------------------------------- ''' Problem 1: Multi-Armed Bandit Problem (15",
"an integer scalar. * e: (epsilon) the probability of the player to follow",
"has been tried, a numpy integer vector of length c. Ct_1[i] represents the",
"above by typing the following in the terminal: --------------------------------------------------- nosetests -v test1.py:test_choose_action ---",
"CHANGE HERE: if you have read and agree with the term above, change",
"of a function (which needs 5 lines of code to solve) and they",
"exploit-only method (choose the action with the highest average reward). ---- Inputs: --------",
"to follow exploit-only method (choose the action with the highest average reward). ----",
"end of this file. ''' #-------------------------- def Terms_and_Conditions(): ''' By submitting this homework",
"the i-th action has been tried before\". * e: (epsilon) the probability of",
"choose_action_exploit ... ok * (6 points) choose_action ... ok ---------------------------------------------------------------------- Ran 4 tests",
"you agree with the following terms: (1) Not sharing your code/solution with any",
"--------------------------------------------------- nosetests -v test1.py:test_choose_action_explore --- OR ---- python3 -m nose -v test1.py:test_choose_action_explore ---",
"-v test1.py:test_update_memory --- OR ---- python3 -m nose -v test1.py:test_update_memory --- OR ----",
"return Read_and_Agree #---------------------------------------------------- ''' Given the player's memory about the previous results in",
"each action, a numpy float vector of length c. Rt_1[i] represents the sum",
"solution or your Dropbox automatically copied your solution from your desktop computer and",
"For example, if the count Ct for 3 actions are [0,1,1], we can",
"and 1. The player has 1-e probability in each time step to follow",
"to follow explore-only method (randomly choose an action) and with a large probability",
"action) and with a large probability (1-epsilon) to follow exploit-only method (choose the",
"points) a = np.argmax([0 if Ct[i] == 0 else Rt[i] / Ct[i] for",
"and we handled ALL of these violations according to the WPI Academic Honesty",
"following in the terminal: --------------------------------------------------- nosetests -v test1.py:test_update_memory --- OR ---- python3 -m",
"if Ct[i] == 0 else Rt[i] / Ct[i] for i in range(Rt.size)]) #########################################",
"step to follow the exploitation-only strategy. * Rt: (player's memory) the total rewards",
"count in Ct[i] for the i-th action is 0, we can assume the",
"memory about the previous results in the game and the action chosen and",
"in Ct[i] for the i-th action is 0, we can assume the average",
"----------- Problem 1 (15 points in total)--------------------- ... ok * (3 points) update_memory",
"with the WPI Academic Honesty Policy. For more details, please visit: https://www.wpi.edu/about/policies/academic-integrity/dishonesty Note:",
"-v test1.py --- OR ---- python3 -m nose -v test1.py --- OR ----",
"homework will violate this term. (2) Not using anyone's code in this homework",
"---- Inputs: -------- * a: the index of the action being chosen by",
"the exploitation-only strategy. ---- Outputs: -------- * a: the index of the action",
"c-1. * r: the reward received at the current time step, a float",
"being chosen by the player, an integer scalar between 0 and c-1. *",
"online or lending your laptop (if your laptop contains your solution or your",
"code. ''' #--------------------- def choose_action_exploit(Rt, Ct): ######################################### ## INSERT YOUR CODE HERE (3",
"''' List of All Variables * c: the number of possible actions in",
"how many times the i-th action has been tried before\". ---- Outputs: --------",
"HERE (3 points) Rt[a] = Rt[a] + r Ct[a] = Ct[a] + 1",
"solution from your desktop computer and your laptop) to another student to work",
"''' #---------------------------------------------------- ''' Given a multi-armed bandit game and the player's memory about",
"of all the above functions by typing the following in the terminal: ---------------------------------------------------",
"INSERT YOUR CODE HERE (6 points) a = choose_action_explore(Ct.size) if np.random.random() < e",
"(1-epsilon) to follow exploit-only method (choose the action with the highest average reward).",
"in a multi-armed bandit problem, an integer scalar. ---- Outputs: -------- * a:",
"-v test1.py:test_choose_action_exploit --- OR ---- python3 -m nose -v test1.py:test_choose_action_exploit --- OR ----",
"the player's memory about the previous results in the game and the action",
"in accordance with the WPI Academic Honesty Policy. For more details, please visit:",
"nose -v test1.py:test_choose_action --- OR ---- python -m nose -v test1.py:test_choose_action --------------------------------------------------- '''",
"collected for each action, a numpy float vector of length c. Rt_1[i] represents",
"possible actions in a multi-armed bandit problem, an integer scalar. * e: (epsilon)",
"a = choose_action_explore(Ct.size) if np.random.random() < e else choose_action_exploit(Rt, Ct) ######################################### return a",
"ok * (6 points) choose_action ... ok ---------------------------------------------------------------------- Ran 4 tests in 0.586s",
"the solution of a function (which needs 5 lines of code to solve)",
"''' #--------------------- def update_memory(a, r, Rt, Ct): ######################################### ## INSERT YOUR CODE HERE",
"i.e., how many times the i-th action has been tried before\". ---- Hints:",
"if the count Ct for 3 actions are [0,1,1], we can assume the",
"the following in the terminal: --------------------------------------------------- nosetests -v test1.py --- OR ---- python3",
"* You could us the argmax() function in numpy to return the index",
"between 0 and 1. * This problem can be solved using 1 line(s)",
"the correctness of all the above functions by typing the following in the",
"---- Inputs: -------- * Rt: (player's memory) the total rewards (i.e., sum of",
"(if your laptop contains your solution or your Dropbox automatically copied your solution",
"-v test1.py:test_choose_action --------------------------------------------------- ''' #-------------------------------------------- ''' TEST problem 1: Now you can test",
"the sum of total rewards collected on the i-th action. * Ct: (player's",
"term in their homework submissions and we handled ALL of these violations according",
"-v test1.py:test_update_memory --- OR ---- python -m nose -v test1.py:test_update_memory --------------------------------------------------- ''' #----------------------------------------------------",
"r: the reward received at the current time step, a float scalar. '''",
"''' Given the player's memory about the previous results in the game and",
"--------------------------------------------------- ''' #---------------------------------------------------- ''' Given a multi-armed bandit game and the player's memory",
"test1.py:test_choose_action --- OR ---- python3 -m nose -v test1.py:test_choose_action --- OR ---- python",
"a large probability (1-epsilon) to follow exploit-only method (choose the action with the",
"we handled ALL of these violations according to the WPI Academic Honesty Policy.",
"update_memory ... ok * (3 points) choose_action_explore ... ok * (3 points) choose_action_exploit",
"Stanford Moss system to check your code for code similarity. https://theory.stanford.edu/~aiken/moss/ Historical Data:",
"follow the exploitation-only strategy. * Rt: (player's memory) the total rewards (i.e., sum",
"of the action being chosen by the player, an integer scalar between 0",
"of code. ''' #--------------------- def choose_action(Rt, Ct, e=0.05): ######################################### ## INSERT YOUR CODE",
"list of all variables being used in this problem is provided at the",
"don't import any new package. You should solve this problem using only the",
"before and after the homework due. For example, sending your code segment to",
"Honesty Policy. ''' #******************************************* # CHANGE HERE: if you have read and agree",
"has been tried before\". ---- Outputs: -------- * a: the index of the",
"code in this homework and building your own solution. For example, using some",
"above, change \"False\" to \"True\". Read_and_Agree = True #******************************************* return Read_and_Agree #---------------------------------------------------- '''",
"copied your solution from your desktop computer and your laptop) to another student",
"between 0 and c-1. ---- Hints: -------- * You could use the random.rand()",
"# CHANGE HERE: if you have read and agree with the term above,",
"one year, we ended up finding 25% of the students in that class",
"received at the current time step, a float scalar. * Rt: (player's memory)",
"WPI Academic Honesty Policy. For more details, please visit: https://www.wpi.edu/about/policies/academic-integrity/dishonesty Note: we may",
"-m nose -v test1.py:test_choose_action_explore --------------------------------------------------- ''' #---------------------------------------------------- ''' (Exploit-only) Given a multi-armed bandit",
"nose -v test1.py:test_choose_action_explore --------------------------------------------------- ''' #---------------------------------------------------- ''' (Exploit-only) Given a multi-armed bandit game",
"return a #----------------- ''' TEST: Now you can test the correctness of your",
"ok * (3 points) choose_action_exploit ... ok * (6 points) choose_action ... ok",
"using explore-only strategy. Randomly pick an action with uniform distribution: equal probability for",
"... ok * (3 points) choose_action_exploit ... ok * (6 points) choose_action ...",
"tried before\". ---- Hints: -------- * This problem can be solved using 2",
"are [0,1,1], we can assume the average reward for the first action is",
"the previous results in the game and the action chosen and reward received",
"this term in their homework submissions and we handled ALL of these violations",
"multi-armed bandit problem, an integer scalar. * e: (epsilon) the probability of the",
"can be solved using 1 line(s) of code. ''' #--------------------- def choose_action(Rt, Ct,",
"integer scalar between 0 and c-1. ---- Hints: -------- * This problem can",
"(3 points) Rt[a] = Rt[a] + r Ct[a] = Ct[a] + 1 #########################################",
"at the current time step, update the player's memory. ---- Inputs: -------- *",
"OR ---- python3 -m nose -v test1.py:test_choose_action --- OR ---- python -m nose",
"solved using 2 line(s) of code. ''' #--------------------- def update_memory(a, r, Rt, Ct):",
"of code. ''' #--------------------- def update_memory(a, r, Rt, Ct): ######################################### ## INSERT YOUR",
"before\". ---- Outputs: -------- * a: the index of the action being chosen",
"current step of the game using epsilon-greedy method: with a small probability (epsilon)",
"of the player to follow the exploration-only strategy. e is a float scalar",
"handled ALL of these violations according to the WPI Academic Honesty Policy. '''",
"distribution: equal probability for all actions. ---- Inputs: -------- * c: the number",
"test1.py:test_choose_action_explore --------------------------------------------------- ''' #---------------------------------------------------- ''' (Exploit-only) Given a multi-armed bandit game and the",
"choose_action_explore(c): ######################################### ## INSERT YOUR CODE HERE (3 points) a = np.random.randint(0, c)",
"been tried before\". * e: (epsilon) the probability of the player to follow",
"reward for the first action is 0. * You could us the argmax()",
"---- python3 -m nose -v test1.py:test_choose_action_exploit --- OR ---- python -m nose -v",
"the action chosen and reward received at the current time step, update the",
"file. ''' #-------------------------- def Terms_and_Conditions(): ''' By submitting this homework or changing this",
"1: Multi-Armed Bandit Problem (15 points) In this problem, you will implement the",
"This problem can be solved using 2 line(s) of code. ''' #--------------------- def",
"game, choose an action at the current time step using explore-only strategy. Randomly",
"In this case, the two students violate this term. All violations of (1),(2)",
"of your code above by typing the following in the terminal: --------------------------------------------------- nosetests",
"with the following terms: (1) Not sharing your code/solution with any student before",
"of code to solve) and they then work on the solution \"independently\", however",
"code. ''' #--------------------- def update_memory(a, r, Rt, Ct): ######################################### ## INSERT YOUR CODE",
"this case, the two students violate this term. All violations of (1),(2) or",
"the player's memory about the previous results, choose an action at the current",
"follow explore-only method (randomly choose an action) and with a large probability (1-epsilon)",
"the code of the two solutions are exactly the same, or only with",
"-v test1.py:test_choose_action_exploit --- OR ---- python -m nose -v test1.py:test_choose_action_exploit --------------------------------------------------- ''' #----------------------------------------------------",
"current time step using exploit-only strategy: choose the action with the highest average",
"---- python3 -m nose -v test1.py:test_choose_action --- OR ---- python -m nose -v",
"with the term above, change \"False\" to \"True\". Read_and_Agree = True #******************************************* return",
"to \"True\". Read_and_Agree = True #******************************************* return Read_and_Agree #---------------------------------------------------- ''' Given the player's",
"is 0, we can assume the average reward for the i-th action is",
"#--------------------- def choose_action(Rt, Ct, e=0.05): ######################################### ## INSERT YOUR CODE HERE (6 points)",
"student to work on this homework will violate this term. (2) Not using",
"def Terms_and_Conditions(): ''' By submitting this homework or changing this function, you agree",
"student before and after the homework due. For example, sending your code segment",
"being used in this problem is provided at the end of this file.",
"at the current step of the game using epsilon-greedy method: with a small",
"action at the current step of the game using epsilon-greedy method: with a",
"def choose_action_exploit(Rt, Ct): ######################################### ## INSERT YOUR CODE HERE (3 points) a =",
"-------- * c: the number of possible actions in a multi-armed bandit problem,",
"two students violate this term. All violations of (1),(2) or (3) will be",
"will implement the epsilon-greedy method for Multi-armed bandit problem. A list of all",
"(epsilon) to follow explore-only method (randomly choose an action) and with a large",
"######################################### ## INSERT YOUR CODE HERE (3 points) a = np.argmax([0 if Ct[i]",
"current time step using explore-only strategy. Randomly pick an action with uniform distribution:",
"the reward received at the current time step, a float scalar. * Rt:",
"the index of the largest value in a vector. * This problem can",
"= True #******************************************* return Read_and_Agree #---------------------------------------------------- ''' Given the player's memory about the",
"i-th action has been tried before\". ---- Hints: -------- * This problem can",
"Outputs: -------- * a: the index of the action being chosen by the",
"a multi-armed bandit problem, an integer scalar. ---- Outputs: -------- * a: the",
"bandit game and the player's memory about the previous results, choose an action",
"students violate this term. All violations of (1),(2) or (3) will be handled",
"largest value in a vector. * This problem can be solved using 1",
"assume the average reward for the i-th action is 0. For example, if",
"the game using epsilon-greedy method: with a small probability (epsilon) to follow explore-only",
"building your own solution. For example, using some code segments from another student",
"i-th action is 0, we can assume the average reward for the i-th",
"many times the i-th action has been tried before\". * a: the index",
"(like too busy recently) will violate this term. Changing other's code as your",
"code segment to another student, putting your solution online or lending your laptop",
"if you have read and agree with the term above, change \"False\" to",
"we can assume the average reward for the i-th action is 0. For",
"OR ---- python -m nose -v test1.py:test_choose_action_exploit --------------------------------------------------- ''' #---------------------------------------------------- ''' Given a",
"i in range(Rt.size)]) ######################################### return a #----------------- ''' TEST: Now you can test",
"example, using some code segments from another student or online resources due to",
"INSERT YOUR CODE HERE (3 points) a = np.random.randint(0, c) ######################################### return a",
"to check your code for code similarity. https://theory.stanford.edu/~aiken/moss/ Historical Data: in one year,",
"times the i-th action has been tried before\". ---- Hints: -------- * This",
"an integer scalar. ---- Outputs: -------- * a: the index of the action",
"def choose_action(Rt, Ct, e=0.05): ######################################### ## INSERT YOUR CODE HERE (6 points) a",
"= choose_action_explore(Ct.size) if np.random.random() < e else choose_action_exploit(Rt, Ct) ######################################### return a #-----------------",
"choose_action_exploit(Rt, Ct): ######################################### ## INSERT YOUR CODE HERE (3 points) a = np.argmax([0",
"action, i.e., how many times the i-th action has been tried before\". *",
"been tried before\". ---- Hints: -------- * This problem can be solved using",
"the index of the action being chosen by the player, an integer scalar",
"= np.random.randint(0, c) ######################################### return a #----------------- ''' TEST: Now you can test",
"e: (epsilon) the probability of the player to follow the exploration-only strategy. e",
"CODE HERE (3 points) Rt[a] = Rt[a] + r Ct[a] = Ct[a] +",
"< e else choose_action_exploit(Rt, Ct) ######################################### return a #----------------- ''' TEST: Now you",
"0 and c-1. * r: the reward received at the current time step,",
"the i-th action. * Ct: (player's memory) the counts on how many times",
"solve) and they then work on the solution \"independently\", however the code of",
"highest average reward). ---- Inputs: -------- * Rt: (player's memory) the total rewards",
"times the i-th action has been tried before\". * a: the index of",
"laptop contains your solution or your Dropbox automatically copied your solution from your",
"how many times the i-th action has been tried before\". * a: the",
"this problem, you will implement the epsilon-greedy method for Multi-armed bandit problem. A",
"another student to work on this homework will violate this term. (2) Not",
"the exploitation-only strategy. * Rt: (player's memory) the total rewards (i.e., sum of",
"Bandit Problem (15 points) In this problem, you will implement the epsilon-greedy method",
"this term. Changing other's code as your solution (such as changing the variable",
"the i-th action is 0. For example, if the count Ct for 3",
"between 0 and c-1. * r: the reward received at the current time",
"#----------------- ''' TEST: Now you can test the correctness of your code above",
"another student or online resources due to any reason (like too busy recently)",
"the player to follow the exploration-only strategy. e is a float scalar between",
"check your code for code similarity. https://theory.stanford.edu/~aiken/moss/ Historical Data: in one year, we",
"#---------------------------------------------------- ''' (Exploit-only) Given a multi-armed bandit game and the player's memory about",
"in that class violating this term in their homework submissions and we handled",
"using anyone's code in this homework and building your own solution. For example,",
"---- Hints: -------- * If the count in Ct[i] for the i-th action",
"term. Changing other's code as your solution (such as changing the variable names)",
"scalar between 0 and c-1. ---- Hints: -------- * This problem can be",
"Academic Honesty Policy. For more details, please visit: https://www.wpi.edu/about/policies/academic-integrity/dishonesty Note: we may use",
"numpy to return the index of the largest value in a vector. *",
"probability in each time step to follow the exploitation-only strategy. * Rt: (player's",
"will also violate this term. (3) When discussing with any other students about",
"Policy. For more details, please visit: https://www.wpi.edu/about/policies/academic-integrity/dishonesty Note: we may use the Stanford",
"typing the following in the terminal: --------------------------------------------------- nosetests -v test1.py:test_choose_action --- OR ----",
"will be handled in accordance with the WPI Academic Honesty Policy. For more",
"HERE: if you have read and agree with the term above, change \"False\"",
"c. Rt_1[i] represents the sum of total rewards collected on the i-th action.",
"code of the two solutions are exactly the same, or only with minor",
"using 1 line(s) of code. ''' #--------------------- def choose_action_explore(c): ######################################### ## INSERT YOUR",
"argmax() function in numpy to return the index of the largest value in",
"year, we ended up finding 25% of the students in that class violating",
"discuss about the solution at the code level. For example, two students discuss",
"Now you can test the correctness of all the above functions by typing",
"received at the current time step, update the player's memory. ---- Inputs: --------",
"test1.py:test_choose_action_exploit --- OR ---- python -m nose -v test1.py:test_choose_action_exploit --------------------------------------------------- ''' #---------------------------------------------------- '''",
"* (3 points) choose_action_explore ... ok * (3 points) choose_action_exploit ... ok *",
"integer vector of length c. Ct_1[i] represents the total number of samples collected",
"i-th action has been tried before\". ---- Outputs: -------- * a: the index",
"uniform distribution: equal probability for all actions. ---- Inputs: -------- * c: the",
"using uniform distribution between 0 and 1. * This problem can be solved",
"-v test1.py:test_choose_action_explore --- OR ---- python -m nose -v test1.py:test_choose_action_explore --------------------------------------------------- ''' #----------------------------------------------------",
"epsilon-greedy method: with a small probability (epsilon) to follow explore-only method (randomly choose",
"times the i-th action has been tried before\". * e: (epsilon) the probability",
"your solution from your desktop computer and your laptop) to another student to",
"implement the epsilon-greedy method for Multi-armed bandit problem. A list of all variables",
"np.argmax([0 if Ct[i] == 0 else Rt[i] / Ct[i] for i in range(Rt.size)])",
"nose -v test1.py:test_choose_action_exploit --- OR ---- python -m nose -v test1.py:test_choose_action_exploit --------------------------------------------------- '''",
"nose -v test1.py:test_update_memory --- OR ---- python -m nose -v test1.py:test_update_memory --------------------------------------------------- '''",
"previous results, choose an action at the current time step using exploit-only strategy:",
"your code passed all the tests, you will see the following message in",
"## INSERT YOUR CODE HERE (3 points) a = np.argmax([0 if Ct[i] ==",
"with minor differences (variable names are different). In this case, the two students",
"terminal: --------------------------------------------------- nosetests -v test1.py:test_choose_action_explore --- OR ---- python3 -m nose -v test1.py:test_choose_action_explore",
"in this problem is provided at the end of this file. ''' #--------------------------",
"solution at the code level. For example, two students discuss about the solution",
"choose an action) and with a large probability (1-epsilon) to follow exploit-only method",
"with any other students about this homework, only discuss high-level ideas or use",
"about this homework, only discuss high-level ideas or use pseudo-code. Don't discuss about",
"(which needs 5 lines of code to solve) and they then work on",
"25% of the students in that class violating this term in their homework",
"* e: (epsilon) the probability of the player to follow the exploration-only strategy.",
"points) choose_action ... ok ---------------------------------------------------------------------- Ran 4 tests in 0.586s OK ''' #--------------------------------------------",
"represents the sum of total rewards collected on the i-th action. * Ct:",
"contains your solution or your Dropbox automatically copied your solution from your desktop",
"scalar. * Rt: (player's memory) the total rewards (i.e., sum of rewards) collected",
"numpy integer vector of length c. Ct_1[i] represents the total number of samples",
"class violating this term in their homework submissions and we handled ALL of",
"number of possible actions in a multi-armed bandit problem, an integer scalar. *",
"python -m nose -v test1.py:test_update_memory --------------------------------------------------- ''' #---------------------------------------------------- ''' (Explore-only) Given a multi-armed",
"(3 points) update_memory ... ok * (3 points) choose_action_explore ... ok * (3",
"solution (such as changing the variable names) will also violate this term. (3)",
"i-th action has been tried before\". * e: (epsilon) the probability of the",
"-m nose -v test1.py:test_choose_action_exploit --- OR ---- python -m nose -v test1.py:test_choose_action_exploit ---------------------------------------------------",
"however the code of the two solutions are exactly the same, or only",
"we can assume the average reward for the first action is 0. *",
"in a multi-armed bandit problem, an integer scalar. * e: (epsilon) the probability",
"should solve this problem using only the package(s) above. #------------------------------------------------------------------------- ''' Problem 1:",
"The player has 1-e probability in each time step to follow the exploitation-only",
"code for code similarity. https://theory.stanford.edu/~aiken/moss/ Historical Data: in one year, we ended up",
"and agree with the term above, change \"False\" to \"True\". Read_and_Agree = True",
"different). In this case, the two students violate this term. All violations of",
"action with the highest average reward. ---- Inputs: -------- * Rt: (player's memory)",
"solution. For example, using some code segments from another student or online resources",
"= Rt[a] + r Ct[a] = Ct[a] + 1 ######################################### #----------------- ''' TEST:",
"0. For example, if the count Ct for 3 actions are [0,1,1], we",
"choose an action at the current time step using exploit-only strategy: choose the",
"problem can be solved using 1 line(s) of code. ''' #--------------------- def choose_action_exploit(Rt,",
"---- python3 -m nose -v test1.py --- OR ---- python -m nose -v",
"for i in range(Rt.size)]) ######################################### return a #----------------- ''' TEST: Now you can",
"3 actions are [0,1,1], we can assume the average reward for the first",
"at the code level. For example, two students discuss about the solution of",
"an integer scalar between 0 and c-1. ---- Hints: -------- * This problem",
"action is 0. For example, if the count Ct for 3 actions are",
"1 line(s) of code. ''' #--------------------- def choose_action(Rt, Ct, e=0.05): ######################################### ## INSERT",
"0, we can assume the average reward for the i-th action is 0.",
"i-th action is 0. For example, if the count Ct for 3 actions",
"multi-armed bandit game and the player's memory about the previous results, choose an",
"the i-th action has been tried before\". * a: the index of the",
"--- OR ---- python3 -m nose -v test1.py:test_update_memory --- OR ---- python -m",
"i-th action, i.e., how many times the i-th action has been tried before\".",
"results, choose an action at the current time step using exploit-only strategy: choose",
"c-1. ---- Hints: -------- * You could use the random.rand() function in numpy",
"many times the i-th action has been tried before\". ---- Hints: -------- *",
"0 and 1. * This problem can be solved using 1 line(s) of",
"with the highest average reward). ---- Inputs: -------- * Rt: (player's memory) the",
"action has been tried before\". * e: (epsilon) the probability of the player",
"nose -v test1.py --- OR ---- python -m nose -v test1.py --------------------------------------------------- If",
"Ct[i] for the i-th action is 0, we can assume the average reward",
"code/solution with any student before and after the homework due. For example, sending",
"and c-1. ---- Hints: -------- * If the count in Ct[i] for the",
"-------- * If the count in Ct[i] for the i-th action is 0,",
"sample a number randomly using uniform distribution between 0 and 1. * This",
"else choose_action_exploit(Rt, Ct) ######################################### return a #----------------- ''' TEST: Now you can test",
"following in the terminal: --------------------------------------------------- nosetests -v test1.py:test_choose_action --- OR ---- python3 -m",
"player's memory. ---- Inputs: -------- * a: the index of the action being",
"as your solution (such as changing the variable names) will also violate this",
"how many times the i-th action has been tried before\". ---- Hints: --------",
"points) choose_action_explore ... ok * (3 points) choose_action_exploit ... ok * (6 points)",
"sharing your code/solution with any student before and after the homework due. For",
"Ct) ######################################### return a #----------------- ''' TEST: Now you can test the correctness",
"i.e., how many times the i-th action has been tried before\". ---- Outputs:",
"OR ---- python -m nose -v test1.py:test_update_memory --------------------------------------------------- ''' #---------------------------------------------------- ''' (Explore-only) Given",
"float scalar between 0 and 1. The player has 1-e probability in each",
"student, putting your solution online or lending your laptop (if your laptop contains",
"are exactly the same, or only with minor differences (variable names are different).",
"the player, an integer scalar between 0 and c-1. * r: the reward",
"the counts on how many times each action has been tried, a numpy",
"the terminal: --------------------------------------------------- nosetests -v test1.py:test_choose_action --- OR ---- python3 -m nose -v",
"multi-armed bandit problem, an integer scalar. ---- Outputs: -------- * a: the index",
"code above by typing the following in the terminal: --------------------------------------------------- nosetests -v test1.py:test_update_memory",
"integer scalar between 0 and c-1. ---- Hints: -------- * If the count",
"the terminal: --------------------------------------------------- nosetests -v test1.py --- OR ---- python3 -m nose -v",
"computer and your laptop) to another student to work on this homework will",
"a numpy integer vector of length c. Ct_1[i] represents the total number of",
"Read_and_Agree #---------------------------------------------------- ''' Given the player's memory about the previous results in the",
"pick an action with uniform distribution: equal probability for all actions. ---- Inputs:",
"for each action, a numpy float vector of length c. Rt_1[i] represents the",
"terminal: --------------------------------------------------- nosetests -v test1.py:test_choose_action_exploit --- OR ---- python3 -m nose -v test1.py:test_choose_action_exploit",
"to follow the exploitation-only strategy. * Rt: (player's memory) the total rewards (i.e.,",
"code level. For example, two students discuss about the solution of a function",
"you will see the following message in the terminal: ----------- Problem 1 (15",
"counts on how many times each action has been tried, a numpy integer",
"could use the random.rand() function in numpy to sample a number randomly using",
"Inputs: -------- * a: the index of the action being chosen by the",
"1. The player has 1-e probability in each time step to follow the",
"and c-1. * r: the reward received at the current time step, a",
"Hints: -------- * This problem can be solved using 2 line(s) of code.",
"you can test the correctness of all the above functions by typing the",
"a float scalar. * Rt: (player's memory) the total rewards (i.e., sum of",
"resources due to any reason (like too busy recently) will violate this term.",
"test the correctness of your code above by typing the following in the",
"before\". * e: (epsilon) the probability of the player to follow the exploration-only",
"possible actions in a multi-armed bandit problem, an integer scalar. ---- Outputs: --------",
"first action is 0. * You could us the argmax() function in numpy",
"HERE (6 points) a = choose_action_explore(Ct.size) if np.random.random() < e else choose_action_exploit(Rt, Ct)",
"--------------------------------------------------- nosetests -v test1.py --- OR ---- python3 -m nose -v test1.py ---",
"--------------------------------------------------- nosetests -v test1.py:test_choose_action_exploit --- OR ---- python3 -m nose -v test1.py:test_choose_action_exploit ---",
"how many times the i-th action has been tried before\". * e: (epsilon)",
"-m nose -v test1.py:test_update_memory --- OR ---- python -m nose -v test1.py:test_update_memory ---------------------------------------------------",
"CODE HERE (3 points) a = np.random.randint(0, c) ######################################### return a #----------------- '''",
"these violations according to the WPI Academic Honesty Policy. ''' #******************************************* # CHANGE",
"test1.py:test_choose_action_exploit --------------------------------------------------- ''' #---------------------------------------------------- ''' Given a multi-armed bandit game and the player's",
"at the end of this file. ''' #-------------------------- def Terms_and_Conditions(): ''' By submitting",
"about the solution at the code level. For example, two students discuss about",
"ok * (3 points) update_memory ... ok * (3 points) choose_action_explore ... ok",
"OR ---- python3 -m nose -v test1.py:test_choose_action_explore --- OR ---- python -m nose",
"0.586s OK ''' #-------------------------------------------- #-------------------------------------------- ''' List of All Variables * c: the",
"''' (Explore-only) Given a multi-armed bandit game, choose an action at the current",
"violate this term. (3) When discussing with any other students about this homework,",
"nose -v test1.py --------------------------------------------------- If your code passed all the tests, you will",
"solution of a function (which needs 5 lines of code to solve) and",
"(such as changing the variable names) will also violate this term. (3) When",
"anyone's code in this homework and building your own solution. For example, using",
"python3 -m nose -v test1.py:test_update_memory --- OR ---- python -m nose -v test1.py:test_update_memory",
"busy recently) will violate this term. Changing other's code as your solution (such",
"python3 -m nose -v test1.py:test_choose_action_exploit --- OR ---- python -m nose -v test1.py:test_choose_action_exploit",
"their homework submissions and we handled ALL of these violations according to the",
"length c. Ct_1[i] represents the total number of samples collected on the i-th",
"* (3 points) choose_action_exploit ... ok * (6 points) choose_action ... ok ----------------------------------------------------------------------",
"For example, sending your code segment to another student, putting your solution online",
"''' #******************************************* # CHANGE HERE: if you have read and agree with the",
"an action at the current time step using exploit-only strategy: choose the action",
"on this homework will violate this term. (2) Not using anyone's code in",
"(3) When discussing with any other students about this homework, only discuss high-level",
"action, a numpy float vector of length c. Rt_1[i] represents the sum of",
"segment to another student, putting your solution online or lending your laptop (if",
"Data: in one year, we ended up finding 25% of the students in",
"too busy recently) will violate this term. Changing other's code as your solution",
"change \"False\" to \"True\". Read_and_Agree = True #******************************************* return Read_and_Agree #---------------------------------------------------- ''' Given",
"you can test the correctness of your code above by typing the following",
"in total)--------------------- ... ok * (3 points) update_memory ... ok * (3 points)",
"action has been tried before\". * a: the index of the action being",
"the i-th action, i.e., how many times the i-th action has been tried",
"rewards) collected for each action, a numpy float vector of length c. Rt_1[i]",
"been tried before\". ---- Outputs: -------- * a: the index of the action",
"integer scalar. ---- Outputs: -------- * a: the index of the action being",
"game using epsilon-greedy method: with a small probability (epsilon) to follow explore-only method",
"actions in a multi-armed bandit problem, an integer scalar. * e: (epsilon) the",
"OR ---- python3 -m nose -v test1.py:test_update_memory --- OR ---- python -m nose",
"(3 points) choose_action_explore ... ok * (3 points) choose_action_exploit ... ok * (6",
"is a float scalar between 0 and 1. The player has 1-e probability",
"* c: the number of possible actions in a multi-armed bandit problem, an",
"in the game and the action chosen and reward received at the current",
"your Dropbox automatically copied your solution from your desktop computer and your laptop)",
"with any student before and after the homework due. For example, sending your",
"used in this problem is provided at the end of this file. '''",
"## INSERT YOUR CODE HERE (3 points) a = np.random.randint(0, c) ######################################### return",
"system to check your code for code similarity. https://theory.stanford.edu/~aiken/moss/ Historical Data: in one",
"all actions. ---- Inputs: -------- * c: the number of possible actions in",
"and c-1. ---- Hints: -------- * You could use the random.rand() function in",
"distribution between 0 and 1. * This problem can be solved using 1",
"and your laptop) to another student to work on this homework will violate",
"your own solution. For example, using some code segments from another student or",
"''' #--------------------- def choose_action_exploit(Rt, Ct): ######################################### ## INSERT YOUR CODE HERE (3 points)",
"1 line(s) of code. ''' #--------------------- def choose_action_exploit(Rt, Ct): ######################################### ## INSERT YOUR",
"between 0 and c-1. ---- Hints: -------- * This problem can be solved",
"same, or only with minor differences (variable names are different). In this case,",
"probability (1-epsilon) to follow exploit-only method (choose the action with the highest average",
"can be solved using 2 line(s) of code. ''' #--------------------- def update_memory(a, r,",
"submissions and we handled ALL of these violations according to the WPI Academic",
"This problem can be solved using 1 line(s) of code. ''' #--------------------- def",
"True #******************************************* return Read_and_Agree #---------------------------------------------------- ''' Given the player's memory about the previous",
"(15 points) In this problem, you will implement the epsilon-greedy method for Multi-armed",
"total rewards (i.e., sum of rewards) collected for each action, a numpy float",
"about the previous results in the game and the action chosen and reward",
"== 0 else Rt[i] / Ct[i] for i in range(Rt.size)]) ######################################### return a",
"(i.e., sum of rewards) collected for each action, a numpy float vector of",
"1-e probability in each time step to follow the exploitation-only strategy. * Rt:",
"python -m nose -v test1.py:test_choose_action_exploit --------------------------------------------------- ''' #---------------------------------------------------- ''' Given a multi-armed bandit",
"can test the correctness of your code above by typing the following in",
"nose -v test1.py:test_update_memory --------------------------------------------------- ''' #---------------------------------------------------- ''' (Explore-only) Given a multi-armed bandit game,",
"test1.py --------------------------------------------------- If your code passed all the tests, you will see the",
"points) update_memory ... ok * (3 points) choose_action_explore ... ok * (3 points)",
"test1.py:test_choose_action_explore --- OR ---- python3 -m nose -v test1.py:test_choose_action_explore --- OR ---- python",
"solved using 1 line(s) of code. ''' #--------------------- def choose_action(Rt, Ct, e=0.05): #########################################",
"---------------------------------------------------------------------- Ran 4 tests in 0.586s OK ''' #-------------------------------------------- #-------------------------------------------- ''' List of",
"on the solution \"independently\", however the code of the two solutions are exactly",
"and the action chosen and reward received at the current time step, update",
"1: Now you can test the correctness of all the above functions by",
"results in the game and the action chosen and reward received at the",
"uniform distribution between 0 and 1. * This problem can be solved using",
"vector of length c. Rt_1[i] represents the sum of total rewards collected on",
"variable names) will also violate this term. (3) When discussing with any other",
"of samples collected on the i-th action, i.e., how many times the i-th",
"Inputs: -------- * Rt: (player's memory) the total rewards (i.e., sum of rewards)",
"strategy. e is a float scalar between 0 and 1. The player has",
"changing the variable names) will also violate this term. (3) When discussing with",
"In this problem, you will implement the epsilon-greedy method for Multi-armed bandit problem.",
"use the random.rand() function in numpy to sample a number randomly using uniform",
"python -m nose -v test1.py --------------------------------------------------- If your code passed all the tests,",
"all the tests, you will see the following message in the terminal: -----------",
"--- OR ---- python -m nose -v test1.py:test_update_memory --------------------------------------------------- ''' #---------------------------------------------------- ''' (Explore-only)",
"or online resources due to any reason (like too busy recently) will violate",
"each time step to follow the exploitation-only strategy. ---- Outputs: -------- * a:",
"######################################### return a #----------------- ''' TEST: Now you can test the correctness of",
"students about this homework, only discuss high-level ideas or use pseudo-code. Don't discuss",
"a float scalar between 0 and 1. The player has 1-e probability in",
"collected on the i-th action, i.e., how many times the i-th action has",
"Rt, Ct): ######################################### ## INSERT YOUR CODE HERE (3 points) Rt[a] = Rt[a]",
"putting your solution online or lending your laptop (if your laptop contains your",
"number randomly using uniform distribution between 0 and 1. * This problem can",
"is provided at the end of this file. ''' #-------------------------- def Terms_and_Conditions(): '''",
"Variables * c: the number of possible actions in a multi-armed bandit problem,",
"as changing the variable names) will also violate this term. (3) When discussing",
"and 1. * This problem can be solved using 1 line(s) of code.",
"the terminal: --------------------------------------------------- nosetests -v test1.py:test_choose_action_explore --- OR ---- python3 -m nose -v",
"Now you can test the correctness of your code above by typing the",
"using some code segments from another student or online resources due to any",
"player, an integer scalar between 0 and c-1. * r: the reward received",
"CODE HERE (3 points) a = np.argmax([0 if Ct[i] == 0 else Rt[i]",
"term above, change \"False\" to \"True\". Read_and_Agree = True #******************************************* return Read_and_Agree #----------------------------------------------------",
"* This problem can be solved using 1 line(s) of code. ''' #---------------------",
"names are different). In this case, the two students violate this term. All",
"points in total)--------------------- ... ok * (3 points) update_memory ... ok * (3",
"be solved using 2 line(s) of code. ''' #--------------------- def update_memory(a, r, Rt,",
"--------------------------------------------------- ''' #---------------------------------------------------- ''' (Exploit-only) Given a multi-armed bandit game and the player's",
"the same, or only with minor differences (variable names are different). In this",
"in range(Rt.size)]) ######################################### return a #----------------- ''' TEST: Now you can test the",
"this term. (3) When discussing with any other students about this homework, only",
"exploration-only strategy. e is a float scalar between 0 and 1. The player",
"your solution online or lending your laptop (if your laptop contains your solution",
"problem 1: Now you can test the correctness of all the above functions",
"integer scalar between 0 and c-1. * r: the reward received at the",
"from another student or online resources due to any reason (like too busy",
"''' (Exploit-only) Given a multi-armed bandit game and the player's memory about the",
"exactly the same, or only with minor differences (variable names are different). In",
"your code for code similarity. https://theory.stanford.edu/~aiken/moss/ Historical Data: in one year, we ended",
"homework or changing this function, you agree with the following terms: (1) Not",
"0 and 1. The player has 1-e probability in each time step to",
"visit: https://www.wpi.edu/about/policies/academic-integrity/dishonesty Note: we may use the Stanford Moss system to check your",
"in the terminal: --------------------------------------------------- nosetests -v test1.py:test_choose_action_explore --- OR ---- python3 -m nose",
"test1.py:test_choose_action_exploit --- OR ---- python3 -m nose -v test1.py:test_choose_action_exploit --- OR ---- python",
"of all variables being used in this problem is provided at the end",
"ended up finding 25% of the students in that class violating this term",
"problem using only the package(s) above. #------------------------------------------------------------------------- ''' Problem 1: Multi-Armed Bandit Problem",
"code. ''' #--------------------- def choose_action(Rt, Ct, e=0.05): ######################################### ## INSERT YOUR CODE HERE",
"in numpy to return the index of the largest value in a vector.",
"more details, please visit: https://www.wpi.edu/about/policies/academic-integrity/dishonesty Note: we may use the Stanford Moss system",
"(Exploit-only) Given a multi-armed bandit game and the player's memory about the previous",
"we may use the Stanford Moss system to check your code for code",
"needs 5 lines of code to solve) and they then work on the",
"tests in 0.586s OK ''' #-------------------------------------------- #-------------------------------------------- ''' List of All Variables *",
"any student before and after the homework due. For example, sending your code",
"OK ''' #-------------------------------------------- #-------------------------------------------- ''' List of All Variables * c: the number",
"may use the Stanford Moss system to check your code for code similarity.",
"other's code as your solution (such as changing the variable names) will also",
"## INSERT YOUR CODE HERE (6 points) a = choose_action_explore(Ct.size) if np.random.random() <",
"(6 points) choose_action ... ok ---------------------------------------------------------------------- Ran 4 tests in 0.586s OK '''",
"bandit game, choose an action at the current time step using explore-only strategy.",
"chosen by the player, an integer scalar between 0 and c-1. ---- Hints:",
"this term. All violations of (1),(2) or (3) will be handled in accordance",
"with a large probability (1-epsilon) to follow exploit-only method (choose the action with",
"#-------------------------------------------- #-------------------------------------------- ''' List of All Variables * c: the number of possible",
"problem. A list of all variables being used in this problem is provided",
"# Note: please don't import any new package. You should solve this problem",
"(15 points in total)--------------------- ... ok * (3 points) update_memory ... ok *",
"and reward received at the current time step, update the player's memory. ----",
"the current time step using exploit-only strategy: choose the action with the highest",
"has been tried before\". * a: the index of the action being chosen",
"the first action is 0. * You could us the argmax() function in",
"your solution (such as changing the variable names) will also violate this term.",
"solve this problem using only the package(s) above. #------------------------------------------------------------------------- ''' Problem 1: Multi-Armed",
"nosetests -v test1.py:test_choose_action --- OR ---- python3 -m nose -v test1.py:test_choose_action --- OR",
"0 and c-1. ---- Hints: -------- * This problem can be solved using",
"e else choose_action_exploit(Rt, Ct) ######################################### return a #----------------- ''' TEST: Now you can",
"reward received at the current time step, a float scalar. * Rt: (player's",
"\"independently\", however the code of the two solutions are exactly the same, or",
"average reward). ---- Inputs: -------- * Rt: (player's memory) the total rewards (i.e.,",
"-m nose -v test1.py:test_choose_action --------------------------------------------------- ''' #-------------------------------------------- ''' TEST problem 1: Now you",
"choose_action(Rt, Ct, e=0.05): ######################################### ## INSERT YOUR CODE HERE (6 points) a =",
"the number of possible actions in a multi-armed bandit problem, an integer scalar.",
"the count Ct for 3 actions are [0,1,1], we can assume the average",
"tried before\". * e: (epsilon) the probability of the player to follow the",
"with the highest average reward. ---- Inputs: -------- * Rt: (player's memory) the",
"chosen by the player, an integer scalar between 0 and c-1. * r:",
"Multi-Armed Bandit Problem (15 points) In this problem, you will implement the epsilon-greedy",
"-------- * Rt: (player's memory) the total rewards (i.e., sum of rewards) collected",
"violations of (1),(2) or (3) will be handled in accordance with the WPI",
"results, choose an action at the current step of the game using epsilon-greedy",
"package. You should solve this problem using only the package(s) above. #------------------------------------------------------------------------- '''",
"#--------------------- def choose_action_explore(c): ######################################### ## INSERT YOUR CODE HERE (3 points) a =",
"Academic Honesty Policy. ''' #******************************************* # CHANGE HERE: if you have read and",
"-m nose -v test1.py:test_choose_action_explore --- OR ---- python -m nose -v test1.py:test_choose_action_explore ---------------------------------------------------",
"of the students in that class violating this term in their homework submissions",
"player's memory about the previous results in the game and the action chosen",
"the epsilon-greedy method for Multi-armed bandit problem. A list of all variables being",
"-v test1.py:test_choose_action_explore --------------------------------------------------- ''' #---------------------------------------------------- ''' (Exploit-only) Given a multi-armed bandit game and",
"any reason (like too busy recently) will violate this term. Changing other's code",
"else Rt[i] / Ct[i] for i in range(Rt.size)]) ######################################### return a #----------------- '''",
"a numpy float vector of length c. Rt_1[i] represents the sum of total",
"automatically copied your solution from your desktop computer and your laptop) to another",
"points) choose_action_exploit ... ok * (6 points) choose_action ... ok ---------------------------------------------------------------------- Ran 4",
"update_memory(a, r, Rt, Ct): ######################################### ## INSERT YOUR CODE HERE (3 points) Rt[a]",
"5 lines of code to solve) and they then work on the solution",
"each action has been tried, a numpy integer vector of length c. Ct_1[i]",
"e=0.05): ######################################### ## INSERT YOUR CODE HERE (6 points) a = choose_action_explore(Ct.size) if",
"problem can be solved using 1 line(s) of code. ''' #--------------------- def choose_action(Rt,",
"similarity. https://theory.stanford.edu/~aiken/moss/ Historical Data: in one year, we ended up finding 25% of",
"discuss about the solution of a function (which needs 5 lines of code",
"action being chosen by the player, an integer scalar between 0 and c-1.",
"following message in the terminal: ----------- Problem 1 (15 points in total)--------------------- ...",
"python -m nose -v test1.py:test_choose_action_explore --------------------------------------------------- ''' #---------------------------------------------------- ''' (Exploit-only) Given a multi-armed",
"strategy: choose the action with the highest average reward. ---- Inputs: -------- *",
"nosetests -v test1.py:test_choose_action_explore --- OR ---- python3 -m nose -v test1.py:test_choose_action_explore --- OR",
"r: the reward received at the current time step, a float scalar. *",
"lines of code to solve) and they then work on the solution \"independently\",",
"2 line(s) of code. ''' #--------------------- def update_memory(a, r, Rt, Ct): ######################################### ##",
"us the argmax() function in numpy to return the index of the largest",
"''' By submitting this homework or changing this function, you agree with the",
"c-1. ---- Hints: -------- * If the count in Ct[i] for the i-th",
"Given a multi-armed bandit game, choose an action at the current time step",
"reward. ---- Inputs: -------- * Rt: (player's memory) the total rewards (i.e., sum",
"method: with a small probability (epsilon) to follow explore-only method (randomly choose an",
"or your Dropbox automatically copied your solution from your desktop computer and your",
"All violations of (1),(2) or (3) will be handled in accordance with the",
"the random.rand() function in numpy to sample a number randomly using uniform distribution",
"about the solution of a function (which needs 5 lines of code to",
"-m nose -v test1.py:test_choose_action_exploit --------------------------------------------------- ''' #---------------------------------------------------- ''' Given a multi-armed bandit game",
"strategy. Randomly pick an action with uniform distribution: equal probability for all actions.",
"''' Problem 1: Multi-Armed Bandit Problem (15 points) In this problem, you will",
"previous results in the game and the action chosen and reward received at",
"on the i-th action. * Ct: (player's memory) the counts on how many",
"TEST problem 1: Now you can test the correctness of all the above",
"step to follow the exploitation-only strategy. ---- Outputs: -------- * a: the index",
"large probability (1-epsilon) to follow exploit-only method (choose the action with the highest",
"https://theory.stanford.edu/~aiken/moss/ Historical Data: in one year, we ended up finding 25% of the",
"using epsilon-greedy method: with a small probability (epsilon) to follow explore-only method (randomly",
"solutions are exactly the same, or only with minor differences (variable names are",
"be solved using 1 line(s) of code. ''' #--------------------- def choose_action_exploit(Rt, Ct): #########################################",
"many times the i-th action has been tried before\". * e: (epsilon) the",
"Not using anyone's code in this homework and building your own solution. For",
"names) will also violate this term. (3) When discussing with any other students",
"game and the action chosen and reward received at the current time step,",
"#--------------------- def choose_action_exploit(Rt, Ct): ######################################### ## INSERT YOUR CODE HERE (3 points) a",
"total number of samples collected on the i-th action, i.e., how many times",
"-m nose -v test1.py:test_choose_action --- OR ---- python -m nose -v test1.py:test_choose_action ---------------------------------------------------",
"memory) the total rewards (i.e., sum of rewards) collected for each action, a",
"i.e., how many times the i-th action has been tried before\". * a:",
"probability for all actions. ---- Inputs: -------- * c: the number of possible",
"level. For example, two students discuss about the solution of a function (which",
"python3 -m nose -v test1.py --- OR ---- python -m nose -v test1.py",
"between 0 and 1. The player has 1-e probability in each time step",
"---- python -m nose -v test1.py:test_choose_action --------------------------------------------------- ''' #-------------------------------------------- ''' TEST problem 1:",
"number of samples collected on the i-th action, i.e., how many times the",
"Ct[a] = Ct[a] + 1 ######################################### #----------------- ''' TEST: Now you can test",
"terminal: ----------- Problem 1 (15 points in total)--------------------- ... ok * (3 points)",
"in the terminal: --------------------------------------------------- nosetests -v test1.py:test_choose_action_exploit --- OR ---- python3 -m nose",
"two students discuss about the solution of a function (which needs 5 lines",
"an action) and with a large probability (1-epsilon) to follow exploit-only method (choose",
"WPI Academic Honesty Policy. ''' #******************************************* # CHANGE HERE: if you have read",
"(3 points) a = np.argmax([0 if Ct[i] == 0 else Rt[i] / Ct[i]",
"step of the game using epsilon-greedy method: with a small probability (epsilon) to",
"time step to follow the exploitation-only strategy. * Rt: (player's memory) the total",
"been tried, a numpy integer vector of length c. Ct_1[i] represents the total",
"the previous results, choose an action at the current step of the game",
"agree with the following terms: (1) Not sharing your code/solution with any student",
"the end of this file. ''' #-------------------------- def Terms_and_Conditions(): ''' By submitting this",
"nose -v test1.py:test_choose_action_exploit --------------------------------------------------- ''' #---------------------------------------------------- ''' Given a multi-armed bandit game and",
"#------------------------------------------------------------------------- ''' Problem 1: Multi-Armed Bandit Problem (15 points) In this problem, you",
"Note: please don't import any new package. You should solve this problem using",
"could us the argmax() function in numpy to return the index of the",
"as np # Note: please don't import any new package. You should solve",
"only with minor differences (variable names are different). In this case, the two",
"time step using explore-only strategy. Randomly pick an action with uniform distribution: equal",
"please visit: https://www.wpi.edu/about/policies/academic-integrity/dishonesty Note: we may use the Stanford Moss system to check",
"be solved using 1 line(s) of code. ''' #--------------------- def choose_action(Rt, Ct, e=0.05):",
"Moss system to check your code for code similarity. https://theory.stanford.edu/~aiken/moss/ Historical Data: in",
"def update_memory(a, r, Rt, Ct): ######################################### ## INSERT YOUR CODE HERE (3 points)",
"in each time step to follow the exploitation-only strategy. ---- Outputs: -------- *",
"* a: the index of the action being chosen by the player, an",
"average reward for the i-th action is 0. For example, if the count",
"the player's memory. ---- Inputs: -------- * a: the index of the action",
"for code similarity. https://theory.stanford.edu/~aiken/moss/ Historical Data: in one year, we ended up finding",
"YOUR CODE HERE (6 points) a = choose_action_explore(Ct.size) if np.random.random() < e else",
"or lending your laptop (if your laptop contains your solution or your Dropbox",
"and they then work on the solution \"independently\", however the code of the",
"--- OR ---- python -m nose -v test1.py:test_choose_action --------------------------------------------------- ''' #-------------------------------------------- ''' TEST",
"tests, you will see the following message in the terminal: ----------- Problem 1",
"that class violating this term in their homework submissions and we handled ALL",
"violate this term. Changing other's code as your solution (such as changing the",
"this function, you agree with the following terms: (1) Not sharing your code/solution",
"of this file. ''' #-------------------------- def Terms_and_Conditions(): ''' By submitting this homework or",
"+ 1 ######################################### #----------------- ''' TEST: Now you can test the correctness of",
"4 tests in 0.586s OK ''' #-------------------------------------------- #-------------------------------------------- ''' List of All Variables",
"the action being chosen by the player, an integer scalar between 0 and",
"action has been tried before\". ---- Hints: -------- * This problem can be",
"player's memory about the previous results, choose an action at the current step",
"the following in the terminal: --------------------------------------------------- nosetests -v test1.py:test_choose_action_explore --- OR ---- python3",
"is 0. For example, if the count Ct for 3 actions are [0,1,1],",
"follow exploit-only method (choose the action with the highest average reward). ---- Inputs:",
"please don't import any new package. You should solve this problem using only",
"action, i.e., how many times the i-th action has been tried before\". ----",
"on how many times each action has been tried, a numpy integer vector",
"how many times each action has been tried, a numpy integer vector of",
"1 ######################################### #----------------- ''' TEST: Now you can test the correctness of your",
"to sample a number randomly using uniform distribution between 0 and 1. *",
"the current time step, a float scalar. * Rt: (player's memory) the total",
"this homework will violate this term. (2) Not using anyone's code in this",
"the largest value in a vector. * This problem can be solved using",
"######################################### ## INSERT YOUR CODE HERE (6 points) a = choose_action_explore(Ct.size) if np.random.random()",
"actions are [0,1,1], we can assume the average reward for the first action",
"the terminal: --------------------------------------------------- nosetests -v test1.py:test_update_memory --- OR ---- python3 -m nose -v",
"see the following message in the terminal: ----------- Problem 1 (15 points in",
"line(s) of code. ''' #--------------------- def choose_action_explore(c): ######################################### ## INSERT YOUR CODE HERE",
"all the above functions by typing the following in the terminal: --------------------------------------------------- nosetests",
"i-th action has been tried before\". * a: the index of the action",
"scalar. ---- Outputs: -------- * a: the index of the action being chosen",
"''' #---------------------------------------------------- ''' (Exploit-only) Given a multi-armed bandit game and the player's memory",
"* Ct: (player's memory) the counts on how many times each action has",
"following in the terminal: --------------------------------------------------- nosetests -v test1.py:test_choose_action_explore --- OR ---- python3 -m",
"-m nose -v test1.py --- OR ---- python -m nose -v test1.py ---------------------------------------------------",
"Rt[a] = Rt[a] + r Ct[a] = Ct[a] + 1 ######################################### #----------------- '''",
"float scalar. * Rt: (player's memory) the total rewards (i.e., sum of rewards)",
"finding 25% of the students in that class violating this term in their",
"can be solved using 1 line(s) of code. ''' #--------------------- def choose_action_exploit(Rt, Ct):",
"the average reward for the first action is 0. * You could us",
"can assume the average reward for the i-th action is 0. For example,",
"a function (which needs 5 lines of code to solve) and they then",
"-m nose -v test1.py:test_update_memory --------------------------------------------------- ''' #---------------------------------------------------- ''' (Explore-only) Given a multi-armed bandit",
"functions by typing the following in the terminal: --------------------------------------------------- nosetests -v test1.py ---",
"been tried before\". * a: the index of the action being chosen by",
"Rt[a] + r Ct[a] = Ct[a] + 1 ######################################### #----------------- ''' TEST: Now",
"exploit-only strategy: choose the action with the highest average reward. ---- Inputs: --------",
"by typing the following in the terminal: --------------------------------------------------- nosetests -v test1.py:test_choose_action --- OR",
"total rewards collected on the i-th action. * Ct: (player's memory) the counts",
"other students about this homework, only discuss high-level ideas or use pseudo-code. Don't",
"the highest average reward. ---- Inputs: -------- * Rt: (player's memory) the total",
"code to solve) and they then work on the solution \"independently\", however the",
"high-level ideas or use pseudo-code. Don't discuss about the solution at the code",
"the solution at the code level. For example, two students discuss about the",
"an action at the current time step using explore-only strategy. Randomly pick an",
"desktop computer and your laptop) to another student to work on this homework",
"to work on this homework will violate this term. (2) Not using anyone's",
"method (choose the action with the highest average reward). ---- Inputs: -------- *",
"your code above by typing the following in the terminal: --------------------------------------------------- nosetests -v",
"scalar between 0 and c-1. ---- Hints: -------- * If the count in",
"points) a = np.random.randint(0, c) ######################################### return a #----------------- ''' TEST: Now you",
"has 1-e probability in each time step to follow the exploitation-only strategy. *",
"---- python -m nose -v test1.py:test_update_memory --------------------------------------------------- ''' #---------------------------------------------------- ''' (Explore-only) Given a",
"action with uniform distribution: equal probability for all actions. ---- Inputs: -------- *",
"YOUR CODE HERE (3 points) a = np.random.randint(0, c) ######################################### return a #-----------------",
"choose an action at the current time step using explore-only strategy. Randomly pick",
"float vector of length c. Rt_1[i] represents the sum of total rewards collected",
"range(Rt.size)]) ######################################### return a #----------------- ''' TEST: Now you can test the correctness",
"time step, a float scalar. * Rt: (player's memory) the total rewards (i.e.,",
"Not sharing your code/solution with any student before and after the homework due.",
"of total rewards collected on the i-th action. * Ct: (player's memory) the",
"equal probability for all actions. ---- Inputs: -------- * c: the number of",
"memory) the counts on how many times each action has been tried, a",
"step, update the player's memory. ---- Inputs: -------- * a: the index of",
"= np.argmax([0 if Ct[i] == 0 else Rt[i] / Ct[i] for i in",
"numpy float vector of length c. Rt_1[i] represents the sum of total rewards",
"all variables being used in this problem is provided at the end of",
"#-------------------------------------------- ''' List of All Variables * c: the number of possible actions",
"before\". * a: the index of the action being chosen by the player,",
"the tests, you will see the following message in the terminal: ----------- Problem",
"game and the player's memory about the previous results, choose an action at",
"actions. ---- Inputs: -------- * c: the number of possible actions in a",
"''' TEST problem 1: Now you can test the correctness of all the",
"reward). ---- Inputs: -------- * Rt: (player's memory) the total rewards (i.e., sum",
"correctness of all the above functions by typing the following in the terminal:",
"For more details, please visit: https://www.wpi.edu/about/policies/academic-integrity/dishonesty Note: we may use the Stanford Moss",
"the i-th action has been tried before\". ---- Hints: -------- * This problem",
"of these violations according to the WPI Academic Honesty Policy. ''' #******************************************* #",
"typing the following in the terminal: --------------------------------------------------- nosetests -v test1.py:test_update_memory --- OR ----",
"by the player, an integer scalar between 0 and c-1. * r: the",
"######################################### ## INSERT YOUR CODE HERE (3 points) a = np.random.randint(0, c) #########################################",
"#-------------------------------------------- ''' TEST problem 1: Now you can test the correctness of all",
"Ct, e=0.05): ######################################### ## INSERT YOUR CODE HERE (6 points) a = choose_action_explore(Ct.size)",
"violate this term. All violations of (1),(2) or (3) will be handled in",
"some code segments from another student or online resources due to any reason",
"HERE (3 points) a = np.random.randint(0, c) ######################################### return a #----------------- ''' TEST:",
"follow the exploitation-only strategy. ---- Outputs: -------- * a: the index of the",
"value in a vector. * This problem can be solved using 1 line(s)",
"using exploit-only strategy: choose the action with the highest average reward. ---- Inputs:",
"the code level. For example, two students discuss about the solution of a",
"test1.py:test_choose_action_explore --- OR ---- python -m nose -v test1.py:test_choose_action_explore --------------------------------------------------- ''' #---------------------------------------------------- '''",
"discussing with any other students about this homework, only discuss high-level ideas or",
"test1.py:test_update_memory --- OR ---- python3 -m nose -v test1.py:test_update_memory --- OR ---- python",
"test1.py --- OR ---- python -m nose -v test1.py --------------------------------------------------- If your code",
"each time step to follow the exploitation-only strategy. * Rt: (player's memory) the",
"(player's memory) the counts on how many times each action has been tried,",
"problem can be solved using 1 line(s) of code. ''' #--------------------- def choose_action_explore(c):",
"agree with the term above, change \"False\" to \"True\". Read_and_Agree = True #*******************************************",
"actions in a multi-armed bandit problem, an integer scalar. ---- Outputs: -------- *",
"correctness of your code above by typing the following in the terminal: ---------------------------------------------------",
"following terms: (1) Not sharing your code/solution with any student before and after",
"segments from another student or online resources due to any reason (like too",
"package(s) above. #------------------------------------------------------------------------- ''' Problem 1: Multi-Armed Bandit Problem (15 points) In this",
"assume the average reward for the first action is 0. * You could",
"discuss high-level ideas or use pseudo-code. Don't discuss about the solution at the",
"''' Given a multi-armed bandit game and the player's memory about the previous",
"the correctness of your code above by typing the following in the terminal:",
"above by typing the following in the terminal: --------------------------------------------------- nosetests -v test1.py:test_choose_action_exploit ---",
"action has been tried, a numpy integer vector of length c. Ct_1[i] represents",
"--------------------------------------------------- ''' #---------------------------------------------------- ''' (Explore-only) Given a multi-armed bandit game, choose an action",
"probability in each time step to follow the exploitation-only strategy. ---- Outputs: --------",
"and c-1. ---- Hints: -------- * This problem can be solved using 1",
"the following in the terminal: --------------------------------------------------- nosetests -v test1.py:test_update_memory --- OR ---- python3",
"use the Stanford Moss system to check your code for code similarity. https://theory.stanford.edu/~aiken/moss/",
"1 line(s) of code. ''' #--------------------- def choose_action_explore(c): ######################################### ## INSERT YOUR CODE",
"nosetests -v test1.py:test_choose_action_exploit --- OR ---- python3 -m nose -v test1.py:test_choose_action_exploit --- OR",
"if np.random.random() < e else choose_action_exploit(Rt, Ct) ######################################### return a #----------------- ''' TEST:",
"problem is provided at the end of this file. ''' #-------------------------- def Terms_and_Conditions():",
"code as your solution (such as changing the variable names) will also violate",
"... ok * (3 points) choose_action_explore ... ok * (3 points) choose_action_exploit ...",
"''' #-------------------------------------------- #-------------------------------------------- ''' List of All Variables * c: the number of",
"a = np.random.randint(0, c) ######################################### return a #----------------- ''' TEST: Now you can",
"-v test1.py --------------------------------------------------- If your code passed all the tests, you will see",
"randomly using uniform distribution between 0 and 1. * This problem can be",
"function (which needs 5 lines of code to solve) and they then work",
"from your desktop computer and your laptop) to another student to work on",
"Policy. ''' #******************************************* # CHANGE HERE: if you have read and agree with",
"choose_action_explore ... ok * (3 points) choose_action_exploit ... ok * (6 points) choose_action",
"i-th action. * Ct: (player's memory) the counts on how many times each",
"tried, a numpy integer vector of length c. Ct_1[i] represents the total number",
"a #----------------- ''' TEST: Now you can test the correctness of your code",
"to follow the exploitation-only strategy. ---- Outputs: -------- * a: the index of",
"Ct[i] for i in range(Rt.size)]) ######################################### return a #----------------- ''' TEST: Now you",
"of the game using epsilon-greedy method: with a small probability (epsilon) to follow",
"your solution or your Dropbox automatically copied your solution from your desktop computer",
"--------------------------------------------------- If your code passed all the tests, you will see the following",
"--- OR ---- python3 -m nose -v test1.py:test_choose_action_exploit --- OR ---- python -m",
"''' #---------------------------------------------------- ''' (Explore-only) Given a multi-armed bandit game, choose an action at",
"* Rt: (player's memory) the total rewards (i.e., sum of rewards) collected for",
"For example, using some code segments from another student or online resources due",
"ALL of these violations according to the WPI Academic Honesty Policy. ''' #*******************************************",
"pseudo-code. Don't discuss about the solution at the code level. For example, two",
"passed all the tests, you will see the following message in the terminal:",
"your desktop computer and your laptop) to another student to work on this",
"step, a float scalar. * Rt: (player's memory) the total rewards (i.e., sum",
"Given the player's memory about the previous results in the game and the",
"in the terminal: --------------------------------------------------- nosetests -v test1.py --- OR ---- python3 -m nose",
"np.random.random() < e else choose_action_exploit(Rt, Ct) ######################################### return a #----------------- ''' TEST: Now",
"## INSERT YOUR CODE HERE (3 points) Rt[a] = Rt[a] + r Ct[a]",
"average reward for the first action is 0. * You could us the",
"---- python -m nose -v test1.py:test_choose_action_exploit --------------------------------------------------- ''' #---------------------------------------------------- ''' Given a multi-armed",
"example, two students discuss about the solution of a function (which needs 5",
"(6 points) a = choose_action_explore(Ct.size) if np.random.random() < e else choose_action_exploit(Rt, Ct) #########################################",
"code segments from another student or online resources due to any reason (like",
"times the i-th action has been tried before\". ---- Outputs: -------- * a:",
"(variable names are different). In this case, the two students violate this term.",
"def choose_action_explore(c): ######################################### ## INSERT YOUR CODE HERE (3 points) a = np.random.randint(0,",
"#-------------------------- def Terms_and_Conditions(): ''' By submitting this homework or changing this function, you",
"0 else Rt[i] / Ct[i] for i in range(Rt.size)]) ######################################### return a #-----------------",
"action with the highest average reward). ---- Inputs: -------- * Rt: (player's memory)",
"laptop (if your laptop contains your solution or your Dropbox automatically copied your",
"Changing other's code as your solution (such as changing the variable names) will",
"your laptop (if your laptop contains your solution or your Dropbox automatically copied",
"for Multi-armed bandit problem. A list of all variables being used in this",
"of length c. Rt_1[i] represents the sum of total rewards collected on the",
"chosen and reward received at the current time step, update the player's memory.",
"i.e., how many times the i-th action has been tried before\". * e:",
"terminal: --------------------------------------------------- nosetests -v test1.py:test_update_memory --- OR ---- python3 -m nose -v test1.py:test_update_memory",
"+ r Ct[a] = Ct[a] + 1 ######################################### #----------------- ''' TEST: Now you",
"https://www.wpi.edu/about/policies/academic-integrity/dishonesty Note: we may use the Stanford Moss system to check your code",
"numpy as np # Note: please don't import any new package. You should",
"-v test1.py:test_update_memory --------------------------------------------------- ''' #---------------------------------------------------- ''' (Explore-only) Given a multi-armed bandit game, choose",
"action chosen and reward received at the current time step, update the player's",
"collected on the i-th action. * Ct: (player's memory) the counts on how",
"action is 0. * You could us the argmax() function in numpy to",
"(3 points) a = np.random.randint(0, c) ######################################### return a #----------------- ''' TEST: Now",
"scalar between 0 and c-1. ---- Hints: -------- * You could use the",
"Ct): ######################################### ## INSERT YOUR CODE HERE (3 points) Rt[a] = Rt[a] +",
"of possible actions in a multi-armed bandit problem, an integer scalar. * e:",
"small probability (epsilon) to follow explore-only method (randomly choose an action) and with",
"has been tried before\". * e: (epsilon) the probability of the player to",
"in one year, we ended up finding 25% of the students in that",
"* This problem can be solved using 2 line(s) of code. ''' #---------------------",
"students discuss about the solution of a function (which needs 5 lines of",
"points) In this problem, you will implement the epsilon-greedy method for Multi-armed bandit",
"according to the WPI Academic Honesty Policy. ''' #******************************************* # CHANGE HERE: if",
"Rt_1[i] represents the sum of total rewards collected on the i-th action. *",
"strategy. ---- Outputs: -------- * a: the index of the action being chosen",
"the action with the highest average reward). ---- Inputs: -------- * Rt: (player's",
"to follow the exploration-only strategy. e is a float scalar between 0 and",
"term. (3) When discussing with any other students about this homework, only discuss",
"at the current time step using explore-only strategy. Randomly pick an action with",
"exploitation-only strategy. * Rt: (player's memory) the total rewards (i.e., sum of rewards)",
"the probability of the player to follow the exploration-only strategy. e is a",
"a small probability (epsilon) to follow explore-only method (randomly choose an action) and",
"use pseudo-code. Don't discuss about the solution at the code level. For example,",
"function in numpy to return the index of the largest value in a",
"students in that class violating this term in their homework submissions and we",
"(3 points) choose_action_exploit ... ok * (6 points) choose_action ... ok ---------------------------------------------------------------------- Ran",
"memory about the previous results, choose an action at the current time step",
"YOUR CODE HERE (3 points) Rt[a] = Rt[a] + r Ct[a] = Ct[a]",
"---- Hints: -------- * You could use the random.rand() function in numpy to",
"player, an integer scalar between 0 and c-1. ---- Hints: -------- * This",
"your code/solution with any student before and after the homework due. For example,",
"details, please visit: https://www.wpi.edu/about/policies/academic-integrity/dishonesty Note: we may use the Stanford Moss system to",
"number of possible actions in a multi-armed bandit problem, an integer scalar. ----",
"-v test1.py --- OR ---- python -m nose -v test1.py --------------------------------------------------- If your",
"explore-only strategy. Randomly pick an action with uniform distribution: equal probability for all",
"points) a = choose_action_explore(Ct.size) if np.random.random() < e else choose_action_exploit(Rt, Ct) ######################################### return",
"differences (variable names are different). In this case, the two students violate this",
"the exploration-only strategy. e is a float scalar between 0 and 1. The"
] |
[
"uprtek_import_spectrum - Imports the spectrum from a UPRtek spectrophotometer * uprtek_import_r_vals - Imports",
"files Note2: This has only been tested with the UPRtek CV600 and MK350N.",
"intensities, e.g.: {380: 0.048, 381: 0.051, ...} \"\"\" def uprtek_import_spectrum(filename: str): return uprtek_file_import(filename,",
"Note2: This has only been tested with the UPRtek CV600 and MK350N. Others",
"\"\"\"Imports a UPRtek data file and outputs a dictionary with the intensities for",
"MK350N. Others may have a different file format Parameters ---------- filename : String",
"= next(reader)[1] if model == 'CV600': spd_start = 40 r_start = 18 r_end",
"dictionary with the intensities for each wavelength Note: UPRtek names these files as",
"UPRtek data file and outputs a dictionary with the R-Values Note: UPRtek names",
"A dictionary with the wavelengths and intensities, e.g.: {380: 0.048, 381: 0.051, ...}",
"import itertools \"\"\"Imports a UPRtek data file and outputs a dictionary with the",
"returntype == 'r_vals': r_vals = {} for row in itertools.islice(reader, r_start, r_end): r_vals[row[0]]",
"filename to import Returns ------- dict A dictionary with the R-Values, e.g.: {'R1':",
"mode='r', encoding='us-ascii') as csvFile: reader = csv.reader(csvFile, delimiter='\\t') # Get UPRtek model from",
"381: 0.051, ...} \"\"\" def uprtek_import_spectrum(filename: str): return uprtek_file_import(filename, 'spd') \"\"\"Imports a UPRtek",
"for each wavelength Note: UPRtek names these files as .xls, but they are",
"The type of data to return. Currently, either 'spd' or 'r_vals' Returns -------",
"and return if returntype == 'spd': spd = {} for row in itertools.islice(reader,",
"'r_vals') \"\"\"Imports a UPRtek data file and outputs a dictionary with the selected",
"the UPRtek file and extracts the selected data \"\"\" import csv import itertools",
"The filename to import Returns ------- dict A dictionary with the wavelengths and",
"only been tested with the UPRtek CV600 and MK350N. Others may have a",
"next(reader)[1] if model == 'CV600': spd_start = 40 r_start = 18 r_end =",
"errors!') spd_start = 46 r_start = 26 r_end = 41 # Extract the",
"itertools.islice(reader, spd_start, None): spd[int(row[0][0:3])] = float(row[1]) return spd elif returntype == 'r_vals': r_vals",
"spectrophotometer * uprtek_import_r_vals - Imports the R values generated by a UPRtek spectrophotometer",
".xls, but they are actually formatted as tab-delimited text files Note2: This has",
"46 r_start = 26 r_end = 41 # Extract the data and return",
"from a UPRtek spectrophotometer * uprtek_import_r_vals - Imports the R values generated by",
"reading data model = next(reader)[1] if model == 'CV600': spd_start = 40 r_start",
"the first line, then set rows for reading data model = next(reader)[1] if",
"data to return. Currently, either 'spd' or 'r_vals' Returns ------- dict A dictionary",
"actually formatted as tab-delimited text files Note2: This has only been tested with",
"available. Using the MK350N format, which could result in errors!') spd_start = 46",
"Imports the R values generated by a UPRtek spectrophotometer * uprtek_file_import - Imports",
"a UPRtek spectrophotometer * uprtek_import_r_vals - Imports the R values generated by a",
"handle data files from spectrophotometers for easy and direct import The functions are:",
"model = next(reader)[1] if model == 'CV600': spd_start = 40 r_start = 18",
"18 r_end = 33 elif model == 'MK350NPLUS': spd_start = 46 r_start =",
"names these files as .xls, but they are actually formatted as tab-delimited text",
"40 r_start = 18 r_end = 33 elif model == 'MK350NPLUS': spd_start =",
"data model = next(reader)[1] if model == 'CV600': spd_start = 40 r_start =",
"but they are actually formatted as tab-delimited text files Note2: This has only",
"'spd') \"\"\"Imports a UPRtek data file and outputs a dictionary with the R-Values",
"data \"\"\" import csv import itertools \"\"\"Imports a UPRtek data file and outputs",
"def uprtek_import_spectrum(filename: str): return uprtek_file_import(filename, 'spd') \"\"\"Imports a UPRtek data file and outputs",
"have a different file format Parameters ---------- filename : String The filename to",
"different file format Parameters ---------- filename : String The filename to import returntype:",
"in errors!') spd_start = 46 r_start = 26 r_end = 41 # Extract",
"String The filename to import Returns ------- dict A dictionary with the wavelengths",
"outputs a dictionary with the selected data Note: UPRtek names these files as",
"and outputs a dictionary with the R-Values Note: UPRtek names these files as",
"Others may have a different file format Parameters ---------- filename : String The",
"for reading data model = next(reader)[1] if model == 'CV600': spd_start = 40",
"= 40 r_start = 18 r_end = 33 elif model == 'MK350NPLUS': spd_start",
"file and outputs a dictionary with the selected data Note: UPRtek names these",
"dictionary with the selected data Note: UPRtek names these files as .xls, but",
"* uprtek_file_import - Imports the UPRtek file and extracts the selected data \"\"\"",
"extracts the selected data \"\"\" import csv import itertools \"\"\"Imports a UPRtek data",
"Imports the UPRtek file and extracts the selected data \"\"\" import csv import",
"\"\"\" def uprtek_import_r_vals(filename: str): return uprtek_file_import(filename, 'r_vals') \"\"\"Imports a UPRtek data file and",
"uprtek_import_r_vals(filename: str): return uprtek_file_import(filename, 'r_vals') \"\"\"Imports a UPRtek data file and outputs a",
"float(row[1]) return spd elif returntype == 'r_vals': r_vals = {} for row in",
"file and outputs a dictionary with the R-Values Note: UPRtek names these files",
"dictionary with the R-Values Note: UPRtek names these files as .xls, but they",
"{} for row in itertools.islice(reader, spd_start, None): spd[int(row[0][0:3])] = float(row[1]) return spd elif",
"Currently, either 'spd' or 'r_vals' Returns ------- dict A dictionary with the selected",
"import returntype: dict The type of data to return. Currently, either 'spd' or",
"Note: UPRtek names these files as .xls, but they are actually formatted as",
"r_end = 33 elif model == 'MK350NPLUS': spd_start = 46 r_start = 26",
"String The filename to import Returns ------- dict A dictionary with the R-Values,",
"...} \"\"\" def uprtek_import_spectrum(filename: str): return uprtek_file_import(filename, 'spd') \"\"\"Imports a UPRtek data file",
"= float(row[1]) return spd elif returntype == 'r_vals': r_vals = {} for row",
"from spectrophotometers for easy and direct import The functions are: * uprtek_import_spectrum -",
"are actually formatted as tab-delimited text files Note2: This has only been tested",
"the UPRtek CV600 and MK350N. Others may have a different file format Parameters",
"return spd elif returntype == 'r_vals': r_vals = {} for row in itertools.islice(reader,",
"and MK350N. Others may have a different file format Parameters ---------- filename :",
"as tab-delimited text files Note2: This has only been tested with the UPRtek",
"intensities for each wavelength Note: UPRtek names these files as .xls, but they",
"a dictionary with the selected data Note: UPRtek names these files as .xls,",
"= 41 # Extract the data and return if returntype == 'spd': spd",
"returntype == 'spd': spd = {} for row in itertools.islice(reader, spd_start, None): spd[int(row[0][0:3])]",
"33 elif model == 'MK350NPLUS': spd_start = 46 r_start = 26 r_end =",
"return uprtek_file_import(filename, 'spd') \"\"\"Imports a UPRtek data file and outputs a dictionary with",
"spd = {} for row in itertools.islice(reader, spd_start, None): spd[int(row[0][0:3])] = float(row[1]) return",
"e.g.: {'R1': 98.887482, 'R2': 99.234245, ...} \"\"\" def uprtek_import_r_vals(filename: str): return uprtek_file_import(filename, 'r_vals')",
"import The functions are: * uprtek_import_spectrum - Imports the spectrum from a UPRtek",
"A dictionary with the selected data \"\"\" def uprtek_file_import(filename: str, returntype: dict): with",
"the R-Values Note: UPRtek names these files as .xls, but they are actually",
"these files as .xls, but they are actually formatted as tab-delimited text files",
"the data and return if returntype == 'spd': spd = {} for row",
"spectrum from a UPRtek spectrophotometer * uprtek_import_r_vals - Imports the R values generated",
"tested with the UPRtek CV600 and MK350N. Others may have a different file",
"Imports the spectrum from a UPRtek spectrophotometer * uprtek_import_r_vals - Imports the R",
"different file format Parameters ---------- filename : String The filename to import Returns",
"with the intensities for each wavelength Note: UPRtek names these files as .xls,",
"= 33 elif model == 'MK350NPLUS': spd_start = 46 r_start = 26 r_end",
"26 r_end = 41 # Extract the data and return if returntype ==",
"which could result in errors!') spd_start = 46 r_start = 26 r_end =",
"they are actually formatted as tab-delimited text files Note2: This has only been",
"itertools \"\"\"Imports a UPRtek data file and outputs a dictionary with the intensities",
"return uprtek_file_import(filename, 'r_vals') \"\"\"Imports a UPRtek data file and outputs a dictionary with",
"str): return uprtek_file_import(filename, 'spd') \"\"\"Imports a UPRtek data file and outputs a dictionary",
"returntype: dict The type of data to return. Currently, either 'spd' or 'r_vals'",
"UPRtek file and extracts the selected data \"\"\" import csv import itertools \"\"\"Imports",
"dict A dictionary with the selected data \"\"\" def uprtek_file_import(filename: str, returntype: dict):",
"# Extract the data and return if returntype == 'spd': spd = {}",
"the selected data \"\"\" def uprtek_file_import(filename: str, returntype: dict): with open(filename, mode='r', encoding='us-ascii')",
"set rows for reading data model = next(reader)[1] if model == 'CV600': spd_start",
"format Parameters ---------- filename : String The filename to import Returns ------- dict",
"with the R-Values Note: UPRtek names these files as .xls, but they are",
"{'R1': 98.887482, 'R2': 99.234245, ...} \"\"\" def uprtek_import_r_vals(filename: str): return uprtek_file_import(filename, 'r_vals') \"\"\"Imports",
"Returns ------- dict A dictionary with the selected data \"\"\" def uprtek_file_import(filename: str,",
"dictionary with the selected data \"\"\" def uprtek_file_import(filename: str, returntype: dict): with open(filename,",
"import csv import itertools \"\"\"Imports a UPRtek data file and outputs a dictionary",
": String The filename to import returntype: dict The type of data to",
"# Get UPRtek model from the first line, then set rows for reading",
"= 46 r_start = 26 r_end = 41 else: print('UPRtek model not available.",
"for easy and direct import The functions are: * uprtek_import_spectrum - Imports the",
"csv import itertools \"\"\"Imports a UPRtek data file and outputs a dictionary with",
"The filename to import returntype: dict The type of data to return. Currently,",
"The functions are: * uprtek_import_spectrum - Imports the spectrum from a UPRtek spectrophotometer",
"r_start = 26 r_end = 41 else: print('UPRtek model not available. Using the",
"uprtek_file_import - Imports the UPRtek file and extracts the selected data \"\"\" import",
"text files Note2: This has only been tested with the UPRtek CV600 and",
"with the selected data \"\"\" def uprtek_file_import(filename: str, returntype: dict): with open(filename, mode='r',",
"outputs a dictionary with the intensities for each wavelength Note: UPRtek names these",
"and intensities, e.g.: {380: 0.048, 381: 0.051, ...} \"\"\" def uprtek_import_spectrum(filename: str): return",
"str): return uprtek_file_import(filename, 'r_vals') \"\"\"Imports a UPRtek data file and outputs a dictionary",
"0.051, ...} \"\"\" def uprtek_import_spectrum(filename: str): return uprtek_file_import(filename, 'spd') \"\"\"Imports a UPRtek data",
"---------- filename : String The filename to import returntype: dict The type of",
"99.234245, ...} \"\"\" def uprtek_import_r_vals(filename: str): return uprtek_file_import(filename, 'r_vals') \"\"\"Imports a UPRtek data",
"encoding='us-ascii') as csvFile: reader = csv.reader(csvFile, delimiter='\\t') # Get UPRtek model from the",
"generated by a UPRtek spectrophotometer * uprtek_file_import - Imports the UPRtek file and",
"'spd': spd = {} for row in itertools.islice(reader, spd_start, None): spd[int(row[0][0:3])] = float(row[1])",
"= 26 r_end = 41 else: print('UPRtek model not available. Using the MK350N",
"r_vals = {} for row in itertools.islice(reader, r_start, r_end): r_vals[row[0]] = float(row[1]) return",
"= 41 else: print('UPRtek model not available. Using the MK350N format, which could",
"a dictionary with the intensities for each wavelength Note: UPRtek names these files",
"file format Parameters ---------- filename : String The filename to import returntype: dict",
"data file and outputs a dictionary with the intensities for each wavelength Note:",
"return if returntype == 'spd': spd = {} for row in itertools.islice(reader, spd_start,",
"has only been tested with the UPRtek CV600 and MK350N. Others may have",
"return. Currently, either 'spd' or 'r_vals' Returns ------- dict A dictionary with the",
"UPRtek data file and outputs a dictionary with the selected data Note: UPRtek",
"row in itertools.islice(reader, spd_start, None): spd[int(row[0][0:3])] = float(row[1]) return spd elif returntype ==",
"* uprtek_import_r_vals - Imports the R values generated by a UPRtek spectrophotometer *",
"and outputs a dictionary with the selected data Note: UPRtek names these files",
"the selected data Note: UPRtek names these files as .xls, but they are",
"line, then set rows for reading data model = next(reader)[1] if model ==",
"\"\"\" import csv import itertools \"\"\"Imports a UPRtek data file and outputs a",
"tab-delimited text files Note2: This has only been tested with the UPRtek CV600",
"e.g.: {380: 0.048, 381: 0.051, ...} \"\"\" def uprtek_import_spectrum(filename: str): return uprtek_file_import(filename, 'spd')",
"filename : String The filename to import Returns ------- dict A dictionary with",
"a different file format Parameters ---------- filename : String The filename to import",
"UPRtek CV600 and MK350N. Others may have a different file format Parameters ----------",
"a UPRtek data file and outputs a dictionary with the selected data Note:",
"'CV600': spd_start = 40 r_start = 18 r_end = 33 elif model ==",
"uprtek_file_import(filename, 'r_vals') \"\"\"Imports a UPRtek data file and outputs a dictionary with the",
"uprtek_file_import(filename, 'spd') \"\"\"Imports a UPRtek data file and outputs a dictionary with the",
"for row in itertools.islice(reader, spd_start, None): spd[int(row[0][0:3])] = float(row[1]) return spd elif returntype",
"from the first line, then set rows for reading data model = next(reader)[1]",
"a UPRtek spectrophotometer * uprtek_file_import - Imports the UPRtek file and extracts the",
"Parameters ---------- filename : String The filename to import returntype: dict The type",
"dict The type of data to return. Currently, either 'spd' or 'r_vals' Returns",
"UPRtek model from the first line, then set rows for reading data model",
"to import returntype: dict The type of data to return. Currently, either 'spd'",
"csv.reader(csvFile, delimiter='\\t') # Get UPRtek model from the first line, then set rows",
"import Returns ------- dict A dictionary with the wavelengths and intensities, e.g.: {380:",
"spectrophotometer * uprtek_file_import - Imports the UPRtek file and extracts the selected data",
"selected data Note: UPRtek names these files as .xls, but they are actually",
"a dictionary with the R-Values Note: UPRtek names these files as .xls, but",
"dict A dictionary with the R-Values, e.g.: {'R1': 98.887482, 'R2': 99.234245, ...} \"\"\"",
"- Imports the R values generated by a UPRtek spectrophotometer * uprtek_file_import -",
"26 r_end = 41 else: print('UPRtek model not available. Using the MK350N format,",
"data files from spectrophotometers for easy and direct import The functions are: *",
"uprtek_import_r_vals - Imports the R values generated by a UPRtek spectrophotometer * uprtek_file_import",
"type of data to return. Currently, either 'spd' or 'r_vals' Returns ------- dict",
"dict): with open(filename, mode='r', encoding='us-ascii') as csvFile: reader = csv.reader(csvFile, delimiter='\\t') # Get",
"returntype: dict): with open(filename, mode='r', encoding='us-ascii') as csvFile: reader = csv.reader(csvFile, delimiter='\\t') #",
"first line, then set rows for reading data model = next(reader)[1] if model",
"= 18 r_end = 33 elif model == 'MK350NPLUS': spd_start = 46 r_start",
"\"\"\"Imports a UPRtek data file and outputs a dictionary with the selected data",
"the R-Values, e.g.: {'R1': 98.887482, 'R2': 99.234245, ...} \"\"\" def uprtek_import_r_vals(filename: str): return",
"formatted as tab-delimited text files Note2: This has only been tested with the",
"{380: 0.048, 381: 0.051, ...} \"\"\" def uprtek_import_spectrum(filename: str): return uprtek_file_import(filename, 'spd') \"\"\"Imports",
"the selected data \"\"\" import csv import itertools \"\"\"Imports a UPRtek data file",
"Extract the data and return if returntype == 'spd': spd = {} for",
"if model == 'CV600': spd_start = 40 r_start = 18 r_end = 33",
"been tested with the UPRtek CV600 and MK350N. Others may have a different",
"\"\"\"Imports a UPRtek data file and outputs a dictionary with the R-Values Note:",
"reader = csv.reader(csvFile, delimiter='\\t') # Get UPRtek model from the first line, then",
"= csv.reader(csvFile, delimiter='\\t') # Get UPRtek model from the first line, then set",
"41 # Extract the data and return if returntype == 'spd': spd =",
"Using the MK350N format, which could result in errors!') spd_start = 46 r_start",
"---------- filename : String The filename to import Returns ------- dict A dictionary",
"functions handle data files from spectrophotometers for easy and direct import The functions",
"rows for reading data model = next(reader)[1] if model == 'CV600': spd_start =",
"== 'r_vals': r_vals = {} for row in itertools.islice(reader, r_start, r_end): r_vals[row[0]] =",
"spectrophotometers for easy and direct import The functions are: * uprtek_import_spectrum - Imports",
"either 'spd' or 'r_vals' Returns ------- dict A dictionary with the selected data",
"model == 'CV600': spd_start = 40 r_start = 18 r_end = 33 elif",
"the spectrum from a UPRtek spectrophotometer * uprtek_import_r_vals - Imports the R values",
"data file and outputs a dictionary with the selected data Note: UPRtek names",
"spd elif returntype == 'r_vals': r_vals = {} for row in itertools.islice(reader, r_start,",
"a UPRtek data file and outputs a dictionary with the intensities for each",
"data and return if returntype == 'spd': spd = {} for row in",
"file and outputs a dictionary with the intensities for each wavelength Note: UPRtek",
"------- dict A dictionary with the R-Values, e.g.: {'R1': 98.887482, 'R2': 99.234245, ...}",
"r_end = 41 # Extract the data and return if returntype == 'spd':",
"'spd' or 'r_vals' Returns ------- dict A dictionary with the selected data \"\"\"",
"The filename to import Returns ------- dict A dictionary with the R-Values, e.g.:",
"def uprtek_file_import(filename: str, returntype: dict): with open(filename, mode='r', encoding='us-ascii') as csvFile: reader =",
"MK350N format, which could result in errors!') spd_start = 46 r_start = 26",
"dictionary with the R-Values, e.g.: {'R1': 98.887482, 'R2': 99.234245, ...} \"\"\" def uprtek_import_r_vals(filename:",
"98.887482, 'R2': 99.234245, ...} \"\"\" def uprtek_import_r_vals(filename: str): return uprtek_file_import(filename, 'r_vals') \"\"\"Imports a",
"the wavelengths and intensities, e.g.: {380: 0.048, 381: 0.051, ...} \"\"\" def uprtek_import_spectrum(filename:",
"== 'CV600': spd_start = 40 r_start = 18 r_end = 33 elif model",
"- Imports the spectrum from a UPRtek spectrophotometer * uprtek_import_r_vals - Imports the",
"as .xls, but they are actually formatted as tab-delimited text files Note2: This",
"or 'r_vals' Returns ------- dict A dictionary with the selected data \"\"\" def",
"file and extracts the selected data \"\"\" import csv import itertools \"\"\"Imports a",
"spd_start, None): spd[int(row[0][0:3])] = float(row[1]) return spd elif returntype == 'r_vals': r_vals =",
"direct import The functions are: * uprtek_import_spectrum - Imports the spectrum from a",
"wavelength Note: UPRtek names these files as .xls, but they are actually formatted",
"elif returntype == 'r_vals': r_vals = {} for row in itertools.islice(reader, r_start, r_end):",
"and extracts the selected data \"\"\" import csv import itertools \"\"\"Imports a UPRtek",
"with the R-Values, e.g.: {'R1': 98.887482, 'R2': 99.234245, ...} \"\"\" def uprtek_import_r_vals(filename: str):",
"model not available. Using the MK350N format, which could result in errors!') spd_start",
"- Imports the UPRtek file and extracts the selected data \"\"\" import csv",
"str, returntype: dict): with open(filename, mode='r', encoding='us-ascii') as csvFile: reader = csv.reader(csvFile, delimiter='\\t')",
"to return. Currently, either 'spd' or 'r_vals' Returns ------- dict A dictionary with",
"UPRtek spectrophotometer * uprtek_import_r_vals - Imports the R values generated by a UPRtek",
"Parameters ---------- filename : String The filename to import Returns ------- dict A",
"with open(filename, mode='r', encoding='us-ascii') as csvFile: reader = csv.reader(csvFile, delimiter='\\t') # Get UPRtek",
"------- dict A dictionary with the selected data \"\"\" def uprtek_file_import(filename: str, returntype:",
"csvFile: reader = csv.reader(csvFile, delimiter='\\t') # Get UPRtek model from the first line,",
"print('UPRtek model not available. Using the MK350N format, which could result in errors!')",
"uprtek_import_spectrum(filename: str): return uprtek_file_import(filename, 'spd') \"\"\"Imports a UPRtek data file and outputs a",
"data \"\"\" def uprtek_file_import(filename: str, returntype: dict): with open(filename, mode='r', encoding='us-ascii') as csvFile:",
"= 26 r_end = 41 # Extract the data and return if returntype",
"in itertools.islice(reader, spd_start, None): spd[int(row[0][0:3])] = float(row[1]) return spd elif returntype == 'r_vals':",
"41 else: print('UPRtek model not available. Using the MK350N format, which could result",
"uprtek_file_import(filename: str, returntype: dict): with open(filename, mode='r', encoding='us-ascii') as csvFile: reader = csv.reader(csvFile,",
"values generated by a UPRtek spectrophotometer * uprtek_file_import - Imports the UPRtek file",
"could result in errors!') spd_start = 46 r_start = 26 r_end = 41",
"to import Returns ------- dict A dictionary with the wavelengths and intensities, e.g.:",
"CV600 and MK350N. Others may have a different file format Parameters ---------- filename",
"a UPRtek data file and outputs a dictionary with the R-Values Note: UPRtek",
"format Parameters ---------- filename : String The filename to import returntype: dict The",
"selected data \"\"\" def uprtek_file_import(filename: str, returntype: dict): with open(filename, mode='r', encoding='us-ascii') as",
"as csvFile: reader = csv.reader(csvFile, delimiter='\\t') # Get UPRtek model from the first",
"and direct import The functions are: * uprtek_import_spectrum - Imports the spectrum from",
"filename to import Returns ------- dict A dictionary with the wavelengths and intensities,",
"to import Returns ------- dict A dictionary with the R-Values, e.g.: {'R1': 98.887482,",
"def uprtek_import_r_vals(filename: str): return uprtek_file_import(filename, 'r_vals') \"\"\"Imports a UPRtek data file and outputs",
"not available. Using the MK350N format, which could result in errors!') spd_start =",
"R values generated by a UPRtek spectrophotometer * uprtek_file_import - Imports the UPRtek",
"None): spd[int(row[0][0:3])] = float(row[1]) return spd elif returntype == 'r_vals': r_vals = {}",
"...} \"\"\" def uprtek_import_r_vals(filename: str): return uprtek_file_import(filename, 'r_vals') \"\"\"Imports a UPRtek data file",
"* uprtek_import_spectrum - Imports the spectrum from a UPRtek spectrophotometer * uprtek_import_r_vals -",
"open(filename, mode='r', encoding='us-ascii') as csvFile: reader = csv.reader(csvFile, delimiter='\\t') # Get UPRtek model",
"UPRtek data file and outputs a dictionary with the intensities for each wavelength",
"r_start = 18 r_end = 33 elif model == 'MK350NPLUS': spd_start = 46",
"UPRtek names these files as .xls, but they are actually formatted as tab-delimited",
"model == 'MK350NPLUS': spd_start = 46 r_start = 26 r_end = 41 else:",
"'r_vals': r_vals = {} for row in itertools.islice(reader, r_start, r_end): r_vals[row[0]] = float(row[1])",
"files as .xls, but they are actually formatted as tab-delimited text files Note2:",
"with the UPRtek CV600 and MK350N. Others may have a different file format",
"and outputs a dictionary with the intensities for each wavelength Note: UPRtek names",
"\"\"\" def uprtek_import_spectrum(filename: str): return uprtek_file_import(filename, 'spd') \"\"\"Imports a UPRtek data file and",
"of data to return. Currently, either 'spd' or 'r_vals' Returns ------- dict A",
"A dictionary with the R-Values, e.g.: {'R1': 98.887482, 'R2': 99.234245, ...} \"\"\" def",
"r_start = 26 r_end = 41 # Extract the data and return if",
"'R2': 99.234245, ...} \"\"\" def uprtek_import_r_vals(filename: str): return uprtek_file_import(filename, 'r_vals') \"\"\"Imports a UPRtek",
"easy and direct import The functions are: * uprtek_import_spectrum - Imports the spectrum",
"with the selected data Note: UPRtek names these files as .xls, but they",
"'MK350NPLUS': spd_start = 46 r_start = 26 r_end = 41 else: print('UPRtek model",
"R-Values Note: UPRtek names these files as .xls, but they are actually formatted",
"files from spectrophotometers for easy and direct import The functions are: * uprtek_import_spectrum",
"Get UPRtek model from the first line, then set rows for reading data",
"may have a different file format Parameters ---------- filename : String The filename",
"spd_start = 46 r_start = 26 r_end = 41 else: print('UPRtek model not",
"spd_start = 40 r_start = 18 r_end = 33 elif model == 'MK350NPLUS':",
"0.048, 381: 0.051, ...} \"\"\" def uprtek_import_spectrum(filename: str): return uprtek_file_import(filename, 'spd') \"\"\"Imports a",
"dictionary with the wavelengths and intensities, e.g.: {380: 0.048, 381: 0.051, ...} \"\"\"",
"file format Parameters ---------- filename : String The filename to import Returns -------",
"== 'MK350NPLUS': spd_start = 46 r_start = 26 r_end = 41 else: print('UPRtek",
"data Note: UPRtek names these files as .xls, but they are actually formatted",
"filename to import returntype: dict The type of data to return. Currently, either",
"are: * uprtek_import_spectrum - Imports the spectrum from a UPRtek spectrophotometer * uprtek_import_r_vals",
"'r_vals' Returns ------- dict A dictionary with the selected data \"\"\" def uprtek_file_import(filename:",
"functions are: * uprtek_import_spectrum - Imports the spectrum from a UPRtek spectrophotometer *",
"These functions handle data files from spectrophotometers for easy and direct import The",
"R-Values, e.g.: {'R1': 98.887482, 'R2': 99.234245, ...} \"\"\" def uprtek_import_r_vals(filename: str): return uprtek_file_import(filename,",
"then set rows for reading data model = next(reader)[1] if model == 'CV600':",
": String The filename to import Returns ------- dict A dictionary with the",
"spd_start = 46 r_start = 26 r_end = 41 # Extract the data",
"UPRtek spectrophotometer * uprtek_file_import - Imports the UPRtek file and extracts the selected",
"the MK350N format, which could result in errors!') spd_start = 46 r_start =",
"the intensities for each wavelength Note: UPRtek names these files as .xls, but",
"elif model == 'MK350NPLUS': spd_start = 46 r_start = 26 r_end = 41",
"else: print('UPRtek model not available. Using the MK350N format, which could result in",
"import Returns ------- dict A dictionary with the R-Values, e.g.: {'R1': 98.887482, 'R2':",
"spd[int(row[0][0:3])] = float(row[1]) return spd elif returntype == 'r_vals': r_vals = {} for",
"each wavelength Note: UPRtek names these files as .xls, but they are actually",
"data file and outputs a dictionary with the R-Values Note: UPRtek names these",
"\"\"\"Photometer These functions handle data files from spectrophotometers for easy and direct import",
"with the wavelengths and intensities, e.g.: {380: 0.048, 381: 0.051, ...} \"\"\" def",
"delimiter='\\t') # Get UPRtek model from the first line, then set rows for",
"outputs a dictionary with the R-Values Note: UPRtek names these files as .xls,",
"Returns ------- dict A dictionary with the R-Values, e.g.: {'R1': 98.887482, 'R2': 99.234245,",
"Returns ------- dict A dictionary with the wavelengths and intensities, e.g.: {380: 0.048,",
"wavelengths and intensities, e.g.: {380: 0.048, 381: 0.051, ...} \"\"\" def uprtek_import_spectrum(filename: str):",
"result in errors!') spd_start = 46 r_start = 26 r_end = 41 #",
"This has only been tested with the UPRtek CV600 and MK350N. Others may",
"dict A dictionary with the wavelengths and intensities, e.g.: {380: 0.048, 381: 0.051,",
"== 'spd': spd = {} for row in itertools.islice(reader, spd_start, None): spd[int(row[0][0:3])] =",
"if returntype == 'spd': spd = {} for row in itertools.islice(reader, spd_start, None):",
"selected data \"\"\" import csv import itertools \"\"\"Imports a UPRtek data file and",
"format, which could result in errors!') spd_start = 46 r_start = 26 r_end",
"= 46 r_start = 26 r_end = 41 # Extract the data and",
"model from the first line, then set rows for reading data model =",
"filename : String The filename to import returntype: dict The type of data",
"= {} for row in itertools.islice(reader, spd_start, None): spd[int(row[0][0:3])] = float(row[1]) return spd",
"------- dict A dictionary with the wavelengths and intensities, e.g.: {380: 0.048, 381:",
"by a UPRtek spectrophotometer * uprtek_file_import - Imports the UPRtek file and extracts",
"String The filename to import returntype: dict The type of data to return.",
"= {} for row in itertools.islice(reader, r_start, r_end): r_vals[row[0]] = float(row[1]) return r_vals",
"the R values generated by a UPRtek spectrophotometer * uprtek_file_import - Imports the",
"\"\"\" def uprtek_file_import(filename: str, returntype: dict): with open(filename, mode='r', encoding='us-ascii') as csvFile: reader",
"r_end = 41 else: print('UPRtek model not available. Using the MK350N format, which",
"46 r_start = 26 r_end = 41 else: print('UPRtek model not available. Using"
] |
[
"auto_gen: return render_to_response('group-add.html', { \"user\": account, \"member_names\":member_names, }, context_instance=RequestContext(request)) group = Group.by_short_name_and_user(short_name, account)",
"]+[^,. ])\") s = re.compile(r'(\\A|\\s)@(\\w+)') if isinstance(statuses,Status): temp = [] temp.append(statuses) statuses =",
"= complete if group.oldestStatus(): output['oldest_date'] = group.oldestStatus().status_date() if group.latestStatus(): output['latest_date'] = group.latestStatus().status_date() if",
"def PersonTweetsAdditional(request,screen_name,loadCount=0,account=None): person = Person.by_screen_name(screen_name) filters = {} tweetCount = 20 loadCount =",
"group = Group.by_short_name_and_user(short_name, account) for member in group.members.all(): tasks.updatePersonTweets(member, account) return render_to_response('group.html',{'group':group, 'user':account})",
"{'statuses':statuses}) @wants_account def GroupTweetsBackground(request,short_name,account=None): output = {} group = Group.by_short_name_and_user(short_name, account) output['num_statuses'] =",
"the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in",
"settings from twitter import collector from datetime import datetime from django.template.context import RequestContext",
"return render_to_response('group-add.html', { \"errors\":['A group by the short_name \\'' + short_name + '\\'",
"line:\" return response @wants_account def AboutPage(request,account=None): return render_to_response('about.html', {'user':account}) @needs_account('/login') def GroupListPage(request,account=None): groups",
"= member_names + \",\" member_names = member_names + member return render_to_response('group-gen-add.html', { 'user':account,",
"< 1: errors.append(\"Please ensure the group name is atleast 1 character long.\") for",
"0: return render_to_response('group-add.html', { \"errors\":errors, \"user\": account, \"short_name\":short_name, \"name\":name, \"member_names\":member_names, }, context_instance=RequestContext(request)) else:",
"return render_to_response('about.html', {'user':account}) @needs_account('/login') def GroupListPage(request,account=None): groups = Group.by_user(account) return render_to_response('group-list.html', {'user':account, 'groups':groups,",
"= link.replace('twitter.com/','') if not link in members: person = collector.person(link, account) if person:",
"= {} status = Status.by_id(status_id) if not status: status = collector.status(status_id,account) if status:",
"person: people.append(person) tasks.updatePersonTweets(person,account) else: errors.append(\"Could not find a user named: \" + member)",
"request.REQUEST.get('q'): terms = request.REQUEST.get('q').split() statuses = group.statuses(tweetCount,loadCount,query=terms,**filters) encodeURLs(statuses, account) return render_to_response('group-tweets-additional.html', {'statuses':statuses}) @wants_account",
"def GroupTweetsAdditional(request,short_name,loadCount=0,account=None): group = Group.by_short_name_and_user(short_name, account) filters = {} terms = None tweetCount",
"the specific language governing permissions and limitations under the License. Contributors <NAME> '''",
"20 loadCount = tweetCount * int(loadCount) if request.REQUEST.get('start'): filters['created_at__gte'] = datetime.strptime(request.REQUEST.get('start'),\"%Y-%m-%d\") if request.REQUEST.get('end'):",
"try: conn = urllib2.urlopen(url) data = conn.read() conn.close() except: errors.append('We were unable to",
"collector.status(status_id,account) if status: encodeURLs(status, account) output['status'] = render_to_string('status.html', {'status':status}) output['next_status'] = str(status.in_reply_to_status_id) else:",
"output['status'] = '<li>The next tweet no longer exists</li>' output['next_status'] = str(None) if account:",
"GroupTweets(request,short_name,account=None): group = Group.by_short_name_and_user(short_name, account) terms = None filters = {} if request.REQUEST.get('start'):",
"account) return render_to_response('group-tweets.html', {'name':group.name, 'statuses':statuses}) @wants_account def GroupTweetsAdditional(request,short_name,loadCount=0,account=None): group = Group.by_short_name_and_user(short_name, account) filters",
"= 20 loadCount = tweetCount * int(loadCount) if request.REQUEST.get('start'): filters['created_at__gte'] = datetime.strptime(request.REQUEST.get('start'),\"%Y-%m-%d\") if",
"person.latestStatus().status_date() if account: output['api_calls'] = account.rate_remaining response = HttpResponse() response.write(simplejson.dumps(output)) except: exc_type, exc_value,",
"response = HttpResponse() response.write(simplejson.dumps(output)) except: exc_type, exc_value, exc_traceback = sys.exc_info() print \"*** print_tb:\"",
"request.REQUEST.get('name','') short_name = name.replace(' ','_').lower() member_names = request.REQUEST.get('member_names','') auto_gen = request.REQUEST.get('auto_gen',None) errors =",
"if request.REQUEST.get('end'): filters['created_at__lt'] = datetime.strptime(request.REQUEST.get('end'),\"%Y-%m-%d\") if request.REQUEST.get('q'): terms = request.REQUEST.get('q').split() statuses = group.statuses(20,0,query=terms,**filters)",
"to get any data from the url provided. Please make sure it is",
"account.rate_remaining response = HttpResponse() response.write(simplejson.dumps(output)) return response def UserRedirect(request): screen_name = request.REQUEST.get('screen_name') return",
"License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required",
"= 0 while person.statusCount() is 0 and person.isUpdating() is True: time.sleep(2**count) count =",
"WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the",
"r.findall(data) members = [] for link in links: link = link.replace('twitter.com/','') if not",
"person: person = collector.person(member,account) if person: people.append(person) tasks.updatePersonTweets(person,account) else: errors.append(\"Could not find a",
"if person: people.append(person) tasks.updatePersonTweets(person,account) else: errors.append(\"Could not find a user named: \" +",
"= collector.status(status_id,account) if status: encodeURLs(status, account) output['status'] = render_to_string('status.html', {'status':status}) output['next_status'] = str(status.in_reply_to_status_id)",
"the short_name \\'' + short_name + '\\' already exists for you. Please try",
"* int(loadCount) if request.REQUEST.get('start'): filters['created_at__gte'] = datetime.strptime(request.REQUEST.get('start'),\"%Y-%m-%d\") if request.REQUEST.get('end'): filters['created_at__lt'] = datetime.strptime(request.REQUEST.get('end'),\"%Y-%m-%d\") if",
"[] for link in links: link = link.replace('twitter.com/','') if not link in members:",
"in people: group.members.add(person) group.save() return HttpResponseRedirect('/group') return render_to_response('group-add.html', { 'user': account, },context_instance=RequestContext(request)) @needs_account('/login')",
"group.latestStatus().status_date() if account: output['api_calls'] = account.rate_remaining response = HttpResponse() response.write(simplejson.dumps(output)) return response @wants_account",
"request.REQUEST.get('start'): filters['created_at__gte'] = datetime.strptime(request.REQUEST.get('start'),\"%Y-%m-%d\") if request.REQUEST.get('end'): filters['created_at__lt'] = datetime.strptime(request.REQUEST.get('end'),\"%Y-%m-%d\") if request.REQUEST.get('q'): terms =",
"account) terms = None filters = {} if request.REQUEST.get('start'): filters['created_at__gte'] = datetime.strptime(request.REQUEST.get('start'),\"%Y-%m-%d\") if",
"import HttpResponse, HttpResponseRedirect from auth.decorators import wants_account, needs_account from django.utils import simplejson from",
"Status.by_id(status_id) if not status: status = collector.status(status_id,account) if status: encodeURLs(status, account) output['status'] =",
"= request.REQUEST.get('name','') short_name = name.replace(' ','_').lower() member_names = request.REQUEST.get('member_names','') auto_gen = request.REQUEST.get('auto_gen',None) errors",
"@wants_account def Tweet(request,status_id,account=None): output = {} status = Status.by_id(status_id) if not status: status",
"\"member_names\":member_names, }, context_instance=RequestContext(request)) people = [] if len(short_name) < 1: errors.append(\"Please ensure the",
"HttpResponse, HttpResponseRedirect from auth.decorators import wants_account, needs_account from django.utils import simplejson from twitter_explorer",
"render_to_response('person.html',{'person':person, 'num_friends':num_friends, 'user':account}) @wants_account def PersonTweets(request,screen_name,account=None): person = Person.by_screen_name(screen_name) filters = {} terms=None",
"r = re.compile(r\"(http://[^, ]+[^,. ])\") s = re.compile(r'(\\A|\\s)@(\\w+)') if isinstance(statuses,Status): temp = []",
"the License for the specific language governing permissions and limitations under the License.",
"= tweetCount * int(loadCount) terms = None if request.REQUEST.get('start'): filters['created_at__gte'] = datetime.strptime(request.REQUEST.get('start'),\"%Y-%m-%d\") if",
"errors.append(\"Please ensure the group name is atleast 1 character long.\") for member in",
"is correct and includes the http://') if len(errors) > 0: return render_to_response('group-gen-add.html', {",
"account) return render_to_response('person-tweets-additional.html', {'screen_name':screen_name, 'statuses':statuses}) @wants_account def PersonTweetsBackground(request,screen_name,account=None): try: output = {} person",
"GroupPage(request,short_name,account=None): group = Group.by_short_name_and_user(short_name, account) for member in group.members.all(): tasks.updatePersonTweets(member, account) return render_to_response('group.html',{'group':group,",
"[] if 'POST' == request.method: url = request.REQUEST.get('url','') try: conn = urllib2.urlopen(url) data",
"not link in members: person = collector.person(link, account) if person: members.append(link) member_names =",
"= count + 1 complete = not person.isUpdating() output['num_statuses'] = person.statusCount() output['complete'] =",
"long.\") for member in member_names.strip().split(','): person = Person.by_screen_name(member) if not person: person =",
"0: member_names = member_names + \",\" member_names = member_names + member return render_to_response('group-gen-add.html',",
"group = Group.objects.create(short_name=short_name, user=account, name=name) for person in people: group.members.add(person) group.save() return HttpResponseRedirect('/group')",
"make sure it is correct and includes the http://') if len(errors) > 0:",
"name is atleast 1 character long.\") for member in member_names.strip().split(','): person = Person.by_screen_name(member)",
"Unless required by applicable law or agreed to in writing, software distributed under",
"'url':url, 'errors':errors, 'user':account, }, context_instance=RequestContext(request)) r = re.compile(r\"(twitter.com/[^, /\\\"]+[^,. /\\\"])\") links = r.findall(data)",
"account: output['api_calls'] = account.rate_remaining response = HttpResponse() response.write(simplejson.dumps(output)) return response @wants_account def Tweet(request,status_id,account=None):",
"sys, traceback import re import urllib2 def encodeURLs(statuses,account): r = re.compile(r\"(http://[^, ]+[^,. ])\")",
"@needs_account('/login') def GroupListPage(request,account=None): groups = Group.by_user(account) return render_to_response('group-list.html', {'user':account, 'groups':groups, }) @needs_account('/login') def",
"= person.statuses(20,0,query=terms,**filters) encodeURLs(statuses, account) return render_to_response('person-tweets.html', {'screen_name':screen_name, 'statuses':statuses}) @wants_account def PersonTweetsAdditional(request,screen_name,loadCount=0,account=None): person =",
"response @wants_account def Tweet(request,status_id,account=None): output = {} status = Status.by_id(status_id) if not status:",
"from twitter_explorer.models import Group from django.http import HttpResponse, HttpResponseRedirect from auth.decorators import wants_account,",
"if request.REQUEST.get('q'): terms = request.REQUEST.get('q').split() statuses = person.statuses(tweetCount,loadCount,query=terms,**filters) encodeURLs(statuses, account) return render_to_response('person-tweets-additional.html', {'screen_name':screen_name,",
"PersonTweetsBackground(request,screen_name,account=None): try: output = {} person = Person.by_screen_name(screen_name) count = 0 while person.statusCount()",
"is 0 and person.isUpdating() is True: time.sleep(2**count) count = count + 1 complete",
"{'screen_name':screen_name, 'statuses':statuses}) @wants_account def PersonTweetsAdditional(request,screen_name,loadCount=0,account=None): person = Person.by_screen_name(screen_name) filters = {} tweetCount =",
"account.rate_remaining response = HttpResponse() response.write(simplejson.dumps(output)) return response @wants_account def Tweet(request,status_id,account=None): output = {}",
"encodeURLs(status, account) output['status'] = render_to_string('status.html', {'status':status}) output['next_status'] = str(status.in_reply_to_status_id) else: output['status'] = '<li>The",
"print_exc:\" traceback.print_exc() print \"*** format_exc, first and last line:\" return response @wants_account def",
"href=\"/user/\\2\" target=\"_blank\" rel=\"nofollow\">\\2</a>', status.text) @wants_account def MainPage(request,account=None): return render_to_response('index.html',{'user':account}) @wants_account def PersonPage(request,screen_name,account=None): if",
"status.text = s.sub(r'\\1@<a href=\"/user/\\2\" target=\"_blank\" rel=\"nofollow\">\\2</a>', status.text) @wants_account def MainPage(request,account=None): return render_to_response('index.html',{'user':account}) @wants_account",
"AboutPage(request,account=None): return render_to_response('about.html', {'user':account}) @needs_account('/login') def GroupListPage(request,account=None): groups = Group.by_user(account) return render_to_response('group-list.html', {'user':account,",
"','_').lower() member_names = request.REQUEST.get('member_names','') auto_gen = request.REQUEST.get('auto_gen',None) errors = [] if 'POST' ==",
"render_to_response('group-add.html', { \"user\": account, \"member_names\":member_names, }, context_instance=RequestContext(request)) group = Group.by_short_name_and_user(short_name, account) if group:",
"account) if group: return render_to_response('group-add.html', { \"errors\":['A group by the short_name \\'' +",
"the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS",
"= person.oldestStatus().status_date() if person.latestStatus(): output['latest_date'] = person.latestStatus().status_date() if account: output['api_calls'] = account.rate_remaining response",
"= None return render_to_response('person.html',{'person':person, 'num_friends':num_friends, 'user':account}) @wants_account def PersonTweets(request,screen_name,account=None): person = Person.by_screen_name(screen_name) filters",
"None tweetCount = 20 loadCount = tweetCount * int(loadCount) if request.REQUEST.get('start'): filters['created_at__gte'] =",
"License, Version 2.0 (the \"License\"); you may not use this file except in",
"import render_to_response from django.template.loader import render_to_string from twitter.models import Person, Status from twitter_explorer.models",
"twitter_explorer import settings from twitter import collector from datetime import datetime from django.template.context",
"[] temp.append(statuses) statuses = temp for status in statuses: status.text = r.sub(r'<a href=\"\\1\"",
"{ 'user': account, },context_instance=RequestContext(request)) @needs_account('/login') def GroupGenAddPage(request,account=None): errors = [] if 'POST' ==",
"= Group.objects.create(short_name=short_name, user=account, name=name) for person in people: group.members.add(person) group.save() return HttpResponseRedirect('/group') return",
"if len(errors) > 0: return render_to_response('group-gen-add.html', { 'url':url, 'errors':errors, 'user':account, }, context_instance=RequestContext(request)) r",
"tweetCount = 20 loadCount = tweetCount * int(loadCount) terms = None if request.REQUEST.get('start'):",
"in members: if len(member_names) > 0: member_names = member_names + \",\" member_names =",
"if group: return render_to_response('group-add.html', { \"errors\":['A group by the short_name \\'' + short_name",
"account) return render_to_response('person-tweets.html', {'screen_name':screen_name, 'statuses':statuses}) @wants_account def PersonTweetsAdditional(request,screen_name,loadCount=0,account=None): person = Person.by_screen_name(screen_name) filters =",
"account, \"member_names\":member_names, }, context_instance=RequestContext(request)) group = Group.by_short_name_and_user(short_name, account) if group: return render_to_response('group-add.html', {",
"render_to_response('group-add.html', { \"errors\":['A group by the short_name \\'' + short_name + '\\' already",
"collector.person(member,account) if person: people.append(person) tasks.updatePersonTweets(person,account) else: errors.append(\"Could not find a user named: \"",
"a user named: \" + member) if len(errors) > 0: return render_to_response('group-add.html', {",
"encodeURLs(statuses, account) return render_to_response('group-tweets-additional.html', {'statuses':statuses}) @wants_account def GroupTweetsBackground(request,short_name,account=None): output = {} group =",
"in group.members.all(): tasks.updatePersonTweets(member, account) return render_to_response('group.html',{'group':group, 'user':account}) @wants_account def GroupTweets(request,short_name,account=None): group = Group.by_short_name_and_user(short_name,",
"status = Status.by_id(status_id) if not status: status = collector.status(status_id,account) if status: encodeURLs(status, account)",
"output['next_status'] = str(None) if account: output['api_calls'] = account.rate_remaining response = HttpResponse() response.write(simplejson.dumps(output)) return",
"0 and person.isUpdating() is True: time.sleep(2**count) count = count + 1 complete =",
"= request.REQUEST.get('q').split() statuses = person.statuses(tweetCount,loadCount,query=terms,**filters) encodeURLs(statuses, account) return render_to_response('person-tweets-additional.html', {'screen_name':screen_name, 'statuses':statuses}) @wants_account def",
"group.members.all(): tasks.updatePersonTweets(member, account) return render_to_response('group.html',{'group':group, 'user':account}) @wants_account def GroupTweets(request,short_name,account=None): group = Group.by_short_name_and_user(short_name, account)",
"traceback.print_exception(exc_type, exc_value, exc_traceback, limit=2, file=sys.stdout) print \"*** print_exc:\" traceback.print_exc() print \"*** format_exc, first",
"except: errors.append('We were unable to get any data from the url provided. Please",
"people.append(person) tasks.updatePersonTweets(person,account) else: errors.append(\"Could not find a user named: \" + member) if",
"20 loadCount = tweetCount * int(loadCount) terms = None if request.REQUEST.get('start'): filters['created_at__gte'] =",
"print \"*** print_tb:\" traceback.print_tb(exc_traceback, limit=1, file=sys.stdout) print \"*** print_exception:\" traceback.print_exception(exc_type, exc_value, exc_traceback, limit=2,",
"}, context_instance=RequestContext(request)) group = Group.by_short_name_and_user(short_name, account) if group: return render_to_response('group-add.html', { \"errors\":['A group",
"= account.rate_remaining response = HttpResponse() response.write(simplejson.dumps(output)) return response def UserRedirect(request): screen_name = request.REQUEST.get('screen_name')",
"user named: \" + member) if len(errors) > 0: return render_to_response('group-add.html', { \"errors\":errors,",
"'user': account, },context_instance=RequestContext(request)) @needs_account('/login') def GroupGenAddPage(request,account=None): errors = [] if 'POST' == request.method:",
"= Group.by_short_name_and_user(short_name, account) terms = None filters = {} if request.REQUEST.get('start'): filters['created_at__gte'] =",
"'<li>The next tweet no longer exists</li>' output['next_status'] = str(None) if account: output['api_calls'] =",
"tweet no longer exists</li>' output['next_status'] = str(None) if account: output['api_calls'] = account.rate_remaining response",
"}) @needs_account('/login') def GroupAddPage(request,account=None): name = request.REQUEST.get('name','') short_name = name.replace(' ','_').lower() member_names =",
"conn.read() conn.close() except: errors.append('We were unable to get any data from the url",
"Group.by_short_name_and_user(short_name, account) output['num_statuses'] = group.status_count() complete = not group.isUpdating() output['complete'] = complete if",
"status.text = r.sub(r'<a href=\"\\1\" target=\"_blank\" rel=\"nofollow\">\\1</a>', status.text) status.text = s.sub(r'\\1@<a href=\"/user/\\2\" target=\"_blank\" rel=\"nofollow\">\\2</a>',",
"software distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT",
"by applicable law or agreed to in writing, software distributed under the License",
"render_to_response from django.template.loader import render_to_string from twitter.models import Person, Status from twitter_explorer.models import",
"filters['created_at__lt'] = datetime.strptime(request.REQUEST.get('end'),\"%Y-%m-%d\") if request.REQUEST.get('q'): terms = request.REQUEST.get('q').split() statuses = person.statuses(tweetCount,loadCount,query=terms,**filters) encodeURLs(statuses, account)",
"for link in links: link = link.replace('twitter.com/','') if not link in members: person",
"= request.REQUEST.get('q').split() statuses = group.statuses(20,0,query=terms,**filters) encodeURLs(statuses, account) return render_to_response('group-tweets.html', {'name':group.name, 'statuses':statuses}) @wants_account def",
"account: person = collector.person(screen_name,account) else: person = Person.by_screen_name(screen_name) if person: tasks.updatePersonTweets(person,account) num_friends =",
"render_to_response('group.html',{'group':group, 'user':account}) @wants_account def GroupTweets(request,short_name,account=None): group = Group.by_short_name_and_user(short_name, account) terms = None filters",
"Group.objects.create(short_name=short_name, user=account, name=name) for person in people: group.members.add(person) group.save() return HttpResponseRedirect('/group') return render_to_response('group-add.html',",
"limitations under the License. Contributors <NAME> ''' from django.shortcuts import render_to_response from django.template.loader",
"render_to_response('group-gen-add.html', { 'user':account, }, context_instance=RequestContext(request)) @needs_account('/login') def GroupPage(request,short_name,account=None): group = Group.by_short_name_and_user(short_name, account) for",
"}, context_instance=RequestContext(request)) r = re.compile(r\"(twitter.com/[^, /\\\"]+[^,. /\\\"])\") links = r.findall(data) members = []",
"WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License",
"group.oldestStatus().status_date() if group.latestStatus(): output['latest_date'] = group.latestStatus().status_date() if account: output['api_calls'] = account.rate_remaining response =",
"@needs_account('/login') def GroupGenAddPage(request,account=None): errors = [] if 'POST' == request.method: url = request.REQUEST.get('url','')",
"= urllib2.urlopen(url) data = conn.read() conn.close() except: errors.append('We were unable to get any",
"person.statuses(tweetCount,loadCount,query=terms,**filters) encodeURLs(statuses, account) return render_to_response('person-tweets-additional.html', {'screen_name':screen_name, 'statuses':statuses}) @wants_account def PersonTweetsBackground(request,screen_name,account=None): try: output =",
"exc_traceback = sys.exc_info() print \"*** print_tb:\" traceback.print_tb(exc_traceback, limit=1, file=sys.stdout) print \"*** print_exception:\" traceback.print_exception(exc_type,",
"\"\" for member in members: if len(member_names) > 0: member_names = member_names +",
"Group.by_short_name_and_user(short_name, account) terms = None filters = {} if request.REQUEST.get('start'): filters['created_at__gte'] = datetime.strptime(request.REQUEST.get('start'),\"%Y-%m-%d\")",
"{'screen_name':screen_name, 'statuses':statuses}) @wants_account def PersonTweetsBackground(request,screen_name,account=None): try: output = {} person = Person.by_screen_name(screen_name) count",
"\"user\": account, \"member_names\":member_names, }, context_instance=RequestContext(request)) group = Group.by_short_name_and_user(short_name, account) if group: return render_to_response('group-add.html',",
"import collector from datetime import datetime from django.template.context import RequestContext from twitter_explorer import",
"temp = [] temp.append(statuses) statuses = temp for status in statuses: status.text =",
"filters['created_at__gte'] = datetime.strptime(request.REQUEST.get('start'),\"%Y-%m-%d\") if request.REQUEST.get('end'): filters['created_at__lt'] = datetime.strptime(request.REQUEST.get('end'),\"%Y-%m-%d\") if request.REQUEST.get('q'): terms = request.REQUEST.get('q').split()",
"HttpResponse() response.write(simplejson.dumps(output)) except: exc_type, exc_value, exc_traceback = sys.exc_info() print \"*** print_tb:\" traceback.print_tb(exc_traceback, limit=1,",
"\"errors\":errors, \"user\": account, \"short_name\":short_name, \"name\":name, \"member_names\":member_names, }, context_instance=RequestContext(request)) else: group = Group.objects.create(short_name=short_name, user=account,",
"re.compile(r\"(twitter.com/[^, /\\\"]+[^,. /\\\"])\") links = r.findall(data) members = [] for link in links:",
"True: time.sleep(2**count) count = count + 1 complete = not person.isUpdating() output['num_statuses'] =",
"urllib2.urlopen(url) data = conn.read() conn.close() except: errors.append('We were unable to get any data",
"members: if len(member_names) > 0: member_names = member_names + \",\" member_names = member_names",
"from datetime import datetime from django.template.context import RequestContext from twitter_explorer import tasks import",
"= request.REQUEST.get('q').split() statuses = person.statuses(20,0,query=terms,**filters) encodeURLs(statuses, account) return render_to_response('person-tweets.html', {'screen_name':screen_name, 'statuses':statuses}) @wants_account def",
"IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.",
"render_to_response('group-list.html', {'user':account, 'groups':groups, }) @needs_account('/login') def GroupAddPage(request,account=None): name = request.REQUEST.get('name','') short_name = name.replace('",
"def PersonTweetsBackground(request,screen_name,account=None): try: output = {} person = Person.by_screen_name(screen_name) count = 0 while",
"not person: person = collector.person(member,account) if person: people.append(person) tasks.updatePersonTweets(person,account) else: errors.append(\"Could not find",
"''' Copyright 2011-2012 <NAME>, The CHISEL group and contributors Licensed under the Apache",
"in compliance with the License. You may obtain a copy of the License",
"else: group = Group.objects.create(short_name=short_name, user=account, name=name) for person in people: group.members.add(person) group.save() return",
"= {} person = Person.by_screen_name(screen_name) count = 0 while person.statusCount() is 0 and",
"KIND, either express or implied. See the License for the specific language governing",
"terms = None filters = {} if request.REQUEST.get('start'): filters['created_at__gte'] = datetime.strptime(request.REQUEST.get('start'),\"%Y-%m-%d\") if request.REQUEST.get('end'):",
"print \"*** format_exc, first and last line:\" return response @wants_account def AboutPage(request,account=None): return",
"request.REQUEST.get('auto_gen',None) errors = [] if 'POST' == request.method: if auto_gen: return render_to_response('group-add.html', {",
"else: person = Person.by_screen_name(screen_name) if person: tasks.updatePersonTweets(person,account) num_friends = person.following_count else: num_friends =",
"= 20 loadCount = tweetCount * int(loadCount) terms = None if request.REQUEST.get('start'): filters['created_at__gte']",
"else: output['status'] = '<li>The next tweet no longer exists</li>' output['next_status'] = str(None) if",
"in writing, software distributed under the License is distributed on an \"AS IS\"",
"HttpResponseRedirect('/group') return render_to_response('group-add.html', { 'user': account, },context_instance=RequestContext(request)) @needs_account('/login') def GroupGenAddPage(request,account=None): errors = []",
"= render_to_string('status.html', {'status':status}) output['next_status'] = str(status.in_reply_to_status_id) else: output['status'] = '<li>The next tweet no",
"if request.REQUEST.get('q'): terms = request.REQUEST.get('q').split() statuses = person.statuses(20,0,query=terms,**filters) encodeURLs(statuses, account) return render_to_response('person-tweets.html', {'screen_name':screen_name,",
"= Group.by_short_name_and_user(short_name, account) output['num_statuses'] = group.status_count() complete = not group.isUpdating() output['complete'] = complete",
"writing, software distributed under the License is distributed on an \"AS IS\" BASIS,",
"errors.append(\"Could not find a user named: \" + member) if len(errors) > 0:",
"or agreed to in writing, software distributed under the License is distributed on",
"sys.exc_info() print \"*** print_tb:\" traceback.print_tb(exc_traceback, limit=1, file=sys.stdout) print \"*** print_exception:\" traceback.print_exception(exc_type, exc_value, exc_traceback,",
"were unable to get any data from the url provided. Please make sure",
"contributors Licensed under the Apache License, Version 2.0 (the \"License\"); you may not",
"if group.latestStatus(): output['latest_date'] = group.latestStatus().status_date() if account: output['api_calls'] = account.rate_remaining response = HttpResponse()",
"not find a user named: \" + member) if len(errors) > 0: return",
"render_to_response('about.html', {'user':account}) @needs_account('/login') def GroupListPage(request,account=None): groups = Group.by_user(account) return render_to_response('group-list.html', {'user':account, 'groups':groups, })",
"terms = None tweetCount = 20 loadCount = tweetCount * int(loadCount) if request.REQUEST.get('start'):",
"short_name \\'' + short_name + '\\' already exists for you. Please try another.'],",
"def GroupAddPage(request,account=None): name = request.REQUEST.get('name','') short_name = name.replace(' ','_').lower() member_names = request.REQUEST.get('member_names','') auto_gen",
"output['oldest_date'] = person.oldestStatus().status_date() if person.latestStatus(): output['latest_date'] = person.latestStatus().status_date() if account: output['api_calls'] = account.rate_remaining",
"int(loadCount) terms = None if request.REQUEST.get('start'): filters['created_at__gte'] = datetime.strptime(request.REQUEST.get('start'),\"%Y-%m-%d\") if request.REQUEST.get('end'): filters['created_at__lt'] =",
"render_to_response('person-tweets.html', {'screen_name':screen_name, 'statuses':statuses}) @wants_account def PersonTweetsAdditional(request,screen_name,loadCount=0,account=None): person = Person.by_screen_name(screen_name) filters = {} tweetCount",
"exists for you. Please try another.'], \"user\": account, \"short_name\":short_name, \"name\":name, \"member_names\":member_names, }, context_instance=RequestContext(request))",
"= temp for status in statuses: status.text = r.sub(r'<a href=\"\\1\" target=\"_blank\" rel=\"nofollow\">\\1</a>', status.text)",
"import time import sys, traceback import re import urllib2 def encodeURLs(statuses,account): r =",
"link.replace('twitter.com/','') if not link in members: person = collector.person(link, account) if person: members.append(link)",
"GroupListPage(request,account=None): groups = Group.by_user(account) return render_to_response('group-list.html', {'user':account, 'groups':groups, }) @needs_account('/login') def GroupAddPage(request,account=None): name",
"urllib2 def encodeURLs(statuses,account): r = re.compile(r\"(http://[^, ]+[^,. ])\") s = re.compile(r'(\\A|\\s)@(\\w+)') if isinstance(statuses,Status):",
"members = [] for link in links: link = link.replace('twitter.com/','') if not link",
"status.text) @wants_account def MainPage(request,account=None): return render_to_response('index.html',{'user':account}) @wants_account def PersonPage(request,screen_name,account=None): if account: person =",
"response = HttpResponse() response.write(simplejson.dumps(output)) return response def UserRedirect(request): screen_name = request.REQUEST.get('screen_name') return HttpResponseRedirect('/user/'+screen_name)",
"'POST' == request.method: url = request.REQUEST.get('url','') try: conn = urllib2.urlopen(url) data = conn.read()",
"'statuses':statuses}) @wants_account def PersonTweetsAdditional(request,screen_name,loadCount=0,account=None): person = Person.by_screen_name(screen_name) filters = {} tweetCount = 20",
"encodeURLs(statuses,account): r = re.compile(r\"(http://[^, ]+[^,. ])\") s = re.compile(r'(\\A|\\s)@(\\w+)') if isinstance(statuses,Status): temp =",
"= collector.person(screen_name,account) else: person = Person.by_screen_name(screen_name) if person: tasks.updatePersonTweets(person,account) num_friends = person.following_count else:",
"= {} if request.REQUEST.get('start'): filters['created_at__gte'] = datetime.strptime(request.REQUEST.get('start'),\"%Y-%m-%d\") if request.REQUEST.get('end'): filters['created_at__lt'] = datetime.strptime(request.REQUEST.get('end'),\"%Y-%m-%d\") if",
"Group from django.http import HttpResponse, HttpResponseRedirect from auth.decorators import wants_account, needs_account from django.utils",
"exists</li>' output['next_status'] = str(None) if account: output['api_calls'] = account.rate_remaining response = HttpResponse() response.write(simplejson.dumps(output))",
"= re.compile(r\"(twitter.com/[^, /\\\"]+[^,. /\\\"])\") links = r.findall(data) members = [] for link in",
"'errors':errors, 'user':account, }, context_instance=RequestContext(request)) r = re.compile(r\"(twitter.com/[^, /\\\"]+[^,. /\\\"])\") links = r.findall(data) members",
"link in members: person = collector.person(link, account) if person: members.append(link) member_names = \"\"",
"group.statuses(tweetCount,loadCount,query=terms,**filters) encodeURLs(statuses, account) return render_to_response('group-tweets-additional.html', {'statuses':statuses}) @wants_account def GroupTweetsBackground(request,short_name,account=None): output = {} group",
"account: output['api_calls'] = account.rate_remaining response = HttpResponse() response.write(simplejson.dumps(output)) return response def UserRedirect(request): screen_name",
"Person.by_screen_name(screen_name) filters = {} terms=None if request.REQUEST.get('start'): filters['created_at__gte'] = datetime.strptime(request.REQUEST.get('start'),\"%Y-%m-%d\") if request.REQUEST.get('end'): filters['created_at__lt']",
"response.write(simplejson.dumps(output)) except: exc_type, exc_value, exc_traceback = sys.exc_info() print \"*** print_tb:\" traceback.print_tb(exc_traceback, limit=1, file=sys.stdout)",
"if 'POST' == request.method: if auto_gen: return render_to_response('group-add.html', { \"user\": account, \"member_names\":member_names, },",
"= request.REQUEST.get('q').split() statuses = group.statuses(tweetCount,loadCount,query=terms,**filters) encodeURLs(statuses, account) return render_to_response('group-tweets-additional.html', {'statuses':statuses}) @wants_account def GroupTweetsBackground(request,short_name,account=None):",
"License for the specific language governing permissions and limitations under the License. Contributors",
"OR CONDITIONS OF ANY KIND, either express or implied. See the License for",
"filters = {} terms=None if request.REQUEST.get('start'): filters['created_at__gte'] = datetime.strptime(request.REQUEST.get('start'),\"%Y-%m-%d\") if request.REQUEST.get('end'): filters['created_at__lt'] =",
"GroupTweetsAdditional(request,short_name,loadCount=0,account=None): group = Group.by_short_name_and_user(short_name, account) filters = {} terms = None tweetCount =",
"OF ANY KIND, either express or implied. See the License for the specific",
"output = {} status = Status.by_id(status_id) if not status: status = collector.status(status_id,account) if",
"2011-2012 <NAME>, The CHISEL group and contributors Licensed under the Apache License, Version",
"language governing permissions and limitations under the License. Contributors <NAME> ''' from django.shortcuts",
"person.statusCount() is 0 and person.isUpdating() is True: time.sleep(2**count) count = count + 1",
"request.REQUEST.get('q'): terms = request.REQUEST.get('q').split() statuses = person.statuses(20,0,query=terms,**filters) encodeURLs(statuses, account) return render_to_response('person-tweets.html', {'screen_name':screen_name, 'statuses':statuses})",
"request.method: if auto_gen: return render_to_response('group-add.html', { \"user\": account, \"member_names\":member_names, }, context_instance=RequestContext(request)) group =",
"print_exception:\" traceback.print_exception(exc_type, exc_value, exc_traceback, limit=2, file=sys.stdout) print \"*** print_exc:\" traceback.print_exc() print \"*** format_exc,",
"conn = urllib2.urlopen(url) data = conn.read() conn.close() except: errors.append('We were unable to get",
"try: output = {} person = Person.by_screen_name(screen_name) count = 0 while person.statusCount() is",
"Person.by_screen_name(screen_name) filters = {} tweetCount = 20 loadCount = tweetCount * int(loadCount) terms",
"= {} tweetCount = 20 loadCount = tweetCount * int(loadCount) terms = None",
"0: return render_to_response('group-gen-add.html', { 'url':url, 'errors':errors, 'user':account, }, context_instance=RequestContext(request)) r = re.compile(r\"(twitter.com/[^, /\\\"]+[^,.",
"re import urllib2 def encodeURLs(statuses,account): r = re.compile(r\"(http://[^, ]+[^,. ])\") s = re.compile(r'(\\A|\\s)@(\\w+)')",
"may not use this file except in compliance with the License. You may",
"= re.compile(r'(\\A|\\s)@(\\w+)') if isinstance(statuses,Status): temp = [] temp.append(statuses) statuses = temp for status",
"group.members.add(person) group.save() return HttpResponseRedirect('/group') return render_to_response('group-add.html', { 'user': account, },context_instance=RequestContext(request)) @needs_account('/login') def GroupGenAddPage(request,account=None):",
"target=\"_blank\" rel=\"nofollow\">\\1</a>', status.text) status.text = s.sub(r'\\1@<a href=\"/user/\\2\" target=\"_blank\" rel=\"nofollow\">\\2</a>', status.text) @wants_account def MainPage(request,account=None):",
"group.statuses(20,0,query=terms,**filters) encodeURLs(statuses, account) return render_to_response('group-tweets.html', {'name':group.name, 'statuses':statuses}) @wants_account def GroupTweetsAdditional(request,short_name,loadCount=0,account=None): group = Group.by_short_name_and_user(short_name,",
"under the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR",
"if not link in members: person = collector.person(link, account) if person: members.append(link) member_names",
"for member in group.members.all(): tasks.updatePersonTweets(member, account) return render_to_response('group.html',{'group':group, 'user':account}) @wants_account def GroupTweets(request,short_name,account=None): group",
"return render_to_response('group-gen-add.html', { 'user':account, 'member_names':member_names}, context_instance=RequestContext(request)) return render_to_response('group-gen-add.html', { 'user':account, }, context_instance=RequestContext(request)) @needs_account('/login')",
"get any data from the url provided. Please make sure it is correct",
"return render_to_response('group-tweets-additional.html', {'statuses':statuses}) @wants_account def GroupTweetsBackground(request,short_name,account=None): output = {} group = Group.by_short_name_and_user(short_name, account)",
"longer exists</li>' output['next_status'] = str(None) if account: output['api_calls'] = account.rate_remaining response = HttpResponse()",
"def Tweet(request,status_id,account=None): output = {} status = Status.by_id(status_id) if not status: status =",
"collector from datetime import datetime from django.template.context import RequestContext from twitter_explorer import tasks",
"on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either",
"group = Group.by_short_name_and_user(short_name, account) if group: return render_to_response('group-add.html', { \"errors\":['A group by the",
"people: group.members.add(person) group.save() return HttpResponseRedirect('/group') return render_to_response('group-add.html', { 'user': account, },context_instance=RequestContext(request)) @needs_account('/login') def",
"person.latestStatus(): output['latest_date'] = person.latestStatus().status_date() if account: output['api_calls'] = account.rate_remaining response = HttpResponse() response.write(simplejson.dumps(output))",
"person = collector.person(member,account) if person: people.append(person) tasks.updatePersonTweets(person,account) else: errors.append(\"Could not find a user",
"request.method: url = request.REQUEST.get('url','') try: conn = urllib2.urlopen(url) data = conn.read() conn.close() except:",
"you. Please try another.'], \"user\": account, \"short_name\":short_name, \"name\":name, \"member_names\":member_names, }, context_instance=RequestContext(request)) people =",
"return render_to_response('group.html',{'group':group, 'user':account}) @wants_account def GroupTweets(request,short_name,account=None): group = Group.by_short_name_and_user(short_name, account) terms = None",
"href=\"\\1\" target=\"_blank\" rel=\"nofollow\">\\1</a>', status.text) status.text = s.sub(r'\\1@<a href=\"/user/\\2\" target=\"_blank\" rel=\"nofollow\">\\2</a>', status.text) @wants_account def",
"/\\\"])\") links = r.findall(data) members = [] for link in links: link =",
"members.append(link) member_names = \"\" for member in members: if len(member_names) > 0: member_names",
"it is correct and includes the http://') if len(errors) > 0: return render_to_response('group-gen-add.html',",
"+ 1 complete = not person.isUpdating() output['num_statuses'] = person.statusCount() output['complete'] = complete if",
"= group.statuses(tweetCount,loadCount,query=terms,**filters) encodeURLs(statuses, account) return render_to_response('group-tweets-additional.html', {'statuses':statuses}) @wants_account def GroupTweetsBackground(request,short_name,account=None): output = {}",
"last line:\" return response @wants_account def AboutPage(request,account=None): return render_to_response('about.html', {'user':account}) @needs_account('/login') def GroupListPage(request,account=None):",
"output['latest_date'] = group.latestStatus().status_date() if account: output['api_calls'] = account.rate_remaining response = HttpResponse() response.write(simplejson.dumps(output)) return",
"@wants_account def GroupTweetsBackground(request,short_name,account=None): output = {} group = Group.by_short_name_and_user(short_name, account) output['num_statuses'] = group.status_count()",
"PersonPage(request,screen_name,account=None): if account: person = collector.person(screen_name,account) else: person = Person.by_screen_name(screen_name) if person: tasks.updatePersonTweets(person,account)",
"limit=2, file=sys.stdout) print \"*** print_exc:\" traceback.print_exc() print \"*** format_exc, first and last line:\"",
"= request.REQUEST.get('member_names','') auto_gen = request.REQUEST.get('auto_gen',None) errors = [] if 'POST' == request.method: if",
"output['next_status'] = str(status.in_reply_to_status_id) else: output['status'] = '<li>The next tweet no longer exists</li>' output['next_status']",
"if account: output['api_calls'] = account.rate_remaining response = HttpResponse() response.write(simplejson.dumps(output)) return response @wants_account def",
"auto_gen = request.REQUEST.get('auto_gen',None) errors = [] if 'POST' == request.method: if auto_gen: return",
"@wants_account def PersonTweetsAdditional(request,screen_name,loadCount=0,account=None): person = Person.by_screen_name(screen_name) filters = {} tweetCount = 20 loadCount",
"output['api_calls'] = account.rate_remaining response = HttpResponse() response.write(simplejson.dumps(output)) return response def UserRedirect(request): screen_name =",
"/\\\"]+[^,. /\\\"])\") links = r.findall(data) members = [] for link in links: link",
"See the License for the specific language governing permissions and limitations under the",
"output['api_calls'] = account.rate_remaining response = HttpResponse() response.write(simplejson.dumps(output)) return response @wants_account def Tweet(request,status_id,account=None): output",
"HttpResponseRedirect from auth.decorators import wants_account, needs_account from django.utils import simplejson from twitter_explorer import",
"if request.REQUEST.get('q'): terms = request.REQUEST.get('q').split() statuses = group.statuses(20,0,query=terms,**filters) encodeURLs(statuses, account) return render_to_response('group-tweets.html', {'name':group.name,",
"name=name) for person in people: group.members.add(person) group.save() return HttpResponseRedirect('/group') return render_to_response('group-add.html', { 'user':",
"= datetime.strptime(request.REQUEST.get('end'),\"%Y-%m-%d\") if request.REQUEST.get('q'): terms = request.REQUEST.get('q').split() statuses = person.statuses(tweetCount,loadCount,query=terms,**filters) encodeURLs(statuses, account) return",
"\"*** format_exc, first and last line:\" return response @wants_account def AboutPage(request,account=None): return render_to_response('about.html',",
"context_instance=RequestContext(request)) return render_to_response('group-gen-add.html', { 'user':account, }, context_instance=RequestContext(request)) @needs_account('/login') def GroupPage(request,short_name,account=None): group = Group.by_short_name_and_user(short_name,",
"datetime.strptime(request.REQUEST.get('start'),\"%Y-%m-%d\") if request.REQUEST.get('end'): filters['created_at__lt'] = datetime.strptime(request.REQUEST.get('end'),\"%Y-%m-%d\") if request.REQUEST.get('q'): terms = request.REQUEST.get('q').split() statuses =",
"for you. Please try another.'], \"user\": account, \"short_name\":short_name, \"name\":name, \"member_names\":member_names, }, context_instance=RequestContext(request)) people",
"request.REQUEST.get('end'): filters['created_at__lt'] = datetime.strptime(request.REQUEST.get('end'),\"%Y-%m-%d\") if request.REQUEST.get('q'): terms = request.REQUEST.get('q').split() statuses = group.statuses(20,0,query=terms,**filters) encodeURLs(statuses,",
"@wants_account def MainPage(request,account=None): return render_to_response('index.html',{'user':account}) @wants_account def PersonPage(request,screen_name,account=None): if account: person = collector.person(screen_name,account)",
"Person, Status from twitter_explorer.models import Group from django.http import HttpResponse, HttpResponseRedirect from auth.decorators",
"name.replace(' ','_').lower() member_names = request.REQUEST.get('member_names','') auto_gen = request.REQUEST.get('auto_gen',None) errors = [] if 'POST'",
"* int(loadCount) terms = None if request.REQUEST.get('start'): filters['created_at__gte'] = datetime.strptime(request.REQUEST.get('start'),\"%Y-%m-%d\") if request.REQUEST.get('end'): filters['created_at__lt']",
"The CHISEL group and contributors Licensed under the Apache License, Version 2.0 (the",
"request.REQUEST.get('q'): terms = request.REQUEST.get('q').split() statuses = person.statuses(tweetCount,loadCount,query=terms,**filters) encodeURLs(statuses, account) return render_to_response('person-tweets-additional.html', {'screen_name':screen_name, 'statuses':statuses})",
"context_instance=RequestContext(request)) people = [] if len(short_name) < 1: errors.append(\"Please ensure the group name",
"'user':account, }, context_instance=RequestContext(request)) r = re.compile(r\"(twitter.com/[^, /\\\"]+[^,. /\\\"])\") links = r.findall(data) members =",
"def GroupPage(request,short_name,account=None): group = Group.by_short_name_and_user(short_name, account) for member in group.members.all(): tasks.updatePersonTweets(member, account) return",
"'groups':groups, }) @needs_account('/login') def GroupAddPage(request,account=None): name = request.REQUEST.get('name','') short_name = name.replace(' ','_').lower() member_names",
"encodeURLs(statuses, account) return render_to_response('group-tweets.html', {'name':group.name, 'statuses':statuses}) @wants_account def GroupTweetsAdditional(request,short_name,loadCount=0,account=None): group = Group.by_short_name_and_user(short_name, account)",
"{'user':account}) @needs_account('/login') def GroupListPage(request,account=None): groups = Group.by_user(account) return render_to_response('group-list.html', {'user':account, 'groups':groups, }) @needs_account('/login')",
"this file except in compliance with the License. You may obtain a copy",
"if account: output['api_calls'] = account.rate_remaining response = HttpResponse() response.write(simplejson.dumps(output)) except: exc_type, exc_value, exc_traceback",
"status: encodeURLs(status, account) output['status'] = render_to_string('status.html', {'status':status}) output['next_status'] = str(status.in_reply_to_status_id) else: output['status'] =",
"= tweetCount * int(loadCount) if request.REQUEST.get('start'): filters['created_at__gte'] = datetime.strptime(request.REQUEST.get('start'),\"%Y-%m-%d\") if request.REQUEST.get('end'): filters['created_at__lt'] =",
"\"License\"); you may not use this file except in compliance with the License.",
"'statuses':statuses}) @wants_account def GroupTweetsAdditional(request,short_name,loadCount=0,account=None): group = Group.by_short_name_and_user(short_name, account) filters = {} terms =",
"is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY",
"import sys, traceback import re import urllib2 def encodeURLs(statuses,account): r = re.compile(r\"(http://[^, ]+[^,.",
"collector.person(link, account) if person: members.append(link) member_names = \"\" for member in members: if",
"= Group.by_short_name_and_user(short_name, account) if group: return render_to_response('group-add.html', { \"errors\":['A group by the short_name",
"status = collector.status(status_id,account) if status: encodeURLs(status, account) output['status'] = render_to_string('status.html', {'status':status}) output['next_status'] =",
"return render_to_response('person-tweets-additional.html', {'screen_name':screen_name, 'statuses':statuses}) @wants_account def PersonTweetsBackground(request,screen_name,account=None): try: output = {} person =",
"person: members.append(link) member_names = \"\" for member in members: if len(member_names) > 0:",
"terms = request.REQUEST.get('q').split() statuses = group.statuses(20,0,query=terms,**filters) encodeURLs(statuses, account) return render_to_response('group-tweets.html', {'name':group.name, 'statuses':statuses}) @wants_account",
"you may not use this file except in compliance with the License. You",
"complete if group.oldestStatus(): output['oldest_date'] = group.oldestStatus().status_date() if group.latestStatus(): output['latest_date'] = group.latestStatus().status_date() if account:",
"{} status = Status.by_id(status_id) if not status: status = collector.status(status_id,account) if status: encodeURLs(status,",
"not status: status = collector.status(status_id,account) if status: encodeURLs(status, account) output['status'] = render_to_string('status.html', {'status':status})",
"if account: output['api_calls'] = account.rate_remaining response = HttpResponse() response.write(simplejson.dumps(output)) return response def UserRedirect(request):",
"agreed to in writing, software distributed under the License is distributed on an",
"request.REQUEST.get('q').split() statuses = person.statuses(tweetCount,loadCount,query=terms,**filters) encodeURLs(statuses, account) return render_to_response('person-tweets-additional.html', {'screen_name':screen_name, 'statuses':statuses}) @wants_account def PersonTweetsBackground(request,screen_name,account=None):",
"= Person.by_screen_name(screen_name) filters = {} tweetCount = 20 loadCount = tweetCount * int(loadCount)",
"account) return render_to_response('group-tweets-additional.html', {'statuses':statuses}) @wants_account def GroupTweetsBackground(request,short_name,account=None): output = {} group = Group.by_short_name_and_user(short_name,",
"Person.by_screen_name(member) if not person: person = collector.person(member,account) if person: people.append(person) tasks.updatePersonTweets(person,account) else: errors.append(\"Could",
"\"*** print_tb:\" traceback.print_tb(exc_traceback, limit=1, file=sys.stdout) print \"*** print_exception:\" traceback.print_exception(exc_type, exc_value, exc_traceback, limit=2, file=sys.stdout)",
"distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES",
"import Group from django.http import HttpResponse, HttpResponseRedirect from auth.decorators import wants_account, needs_account from",
"HttpResponse() response.write(simplejson.dumps(output)) return response @wants_account def Tweet(request,status_id,account=None): output = {} status = Status.by_id(status_id)",
"encodeURLs(statuses, account) return render_to_response('person-tweets-additional.html', {'screen_name':screen_name, 'statuses':statuses}) @wants_account def PersonTweetsBackground(request,screen_name,account=None): try: output = {}",
"from django.shortcuts import render_to_response from django.template.loader import render_to_string from twitter.models import Person, Status",
"\"short_name\":short_name, \"name\":name, \"member_names\":member_names, }, context_instance=RequestContext(request)) people = [] if len(short_name) < 1: errors.append(\"Please",
"may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable",
"while person.statusCount() is 0 and person.isUpdating() is True: time.sleep(2**count) count = count +",
"render_to_response('group-gen-add.html', { 'url':url, 'errors':errors, 'user':account, }, context_instance=RequestContext(request)) r = re.compile(r\"(twitter.com/[^, /\\\"]+[^,. /\\\"])\") links",
"account) return render_to_response('group.html',{'group':group, 'user':account}) @wants_account def GroupTweets(request,short_name,account=None): group = Group.by_short_name_and_user(short_name, account) terms =",
"implied. See the License for the specific language governing permissions and limitations under",
"+ '\\' already exists for you. Please try another.'], \"user\": account, \"short_name\":short_name, \"name\":name,",
"exc_value, exc_traceback, limit=2, file=sys.stdout) print \"*** print_exc:\" traceback.print_exc() print \"*** format_exc, first and",
"= \"\" for member in members: if len(member_names) > 0: member_names = member_names",
"{} person = Person.by_screen_name(screen_name) count = 0 while person.statusCount() is 0 and person.isUpdating()",
"return response @wants_account def Tweet(request,status_id,account=None): output = {} status = Status.by_id(status_id) if not",
"return render_to_response('group-tweets.html', {'name':group.name, 'statuses':statuses}) @wants_account def GroupTweetsAdditional(request,short_name,loadCount=0,account=None): group = Group.by_short_name_and_user(short_name, account) filters =",
"output['num_statuses'] = person.statusCount() output['complete'] = complete if person.oldestStatus(): output['oldest_date'] = person.oldestStatus().status_date() if person.latestStatus():",
"r.sub(r'<a href=\"\\1\" target=\"_blank\" rel=\"nofollow\">\\1</a>', status.text) status.text = s.sub(r'\\1@<a href=\"/user/\\2\" target=\"_blank\" rel=\"nofollow\">\\2</a>', status.text) @wants_account",
"s.sub(r'\\1@<a href=\"/user/\\2\" target=\"_blank\" rel=\"nofollow\">\\2</a>', status.text) @wants_account def MainPage(request,account=None): return render_to_response('index.html',{'user':account}) @wants_account def PersonPage(request,screen_name,account=None):",
"filters = {} terms = None tweetCount = 20 loadCount = tweetCount *",
"])\") s = re.compile(r'(\\A|\\s)@(\\w+)') if isinstance(statuses,Status): temp = [] temp.append(statuses) statuses = temp",
"any data from the url provided. Please make sure it is correct and",
"+ member return render_to_response('group-gen-add.html', { 'user':account, 'member_names':member_names}, context_instance=RequestContext(request)) return render_to_response('group-gen-add.html', { 'user':account, },",
"= r.sub(r'<a href=\"\\1\" target=\"_blank\" rel=\"nofollow\">\\1</a>', status.text) status.text = s.sub(r'\\1@<a href=\"/user/\\2\" target=\"_blank\" rel=\"nofollow\">\\2</a>', status.text)",
"@wants_account def PersonTweets(request,screen_name,account=None): person = Person.by_screen_name(screen_name) filters = {} terms=None if request.REQUEST.get('start'): filters['created_at__gte']",
"@wants_account def PersonPage(request,screen_name,account=None): if account: person = collector.person(screen_name,account) else: person = Person.by_screen_name(screen_name) if",
"= HttpResponse() response.write(simplejson.dumps(output)) except: exc_type, exc_value, exc_traceback = sys.exc_info() print \"*** print_tb:\" traceback.print_tb(exc_traceback,",
"exc_value, exc_traceback = sys.exc_info() print \"*** print_tb:\" traceback.print_tb(exc_traceback, limit=1, file=sys.stdout) print \"*** print_exception:\"",
"another.'], \"user\": account, \"short_name\":short_name, \"name\":name, \"member_names\":member_names, }, context_instance=RequestContext(request)) people = [] if len(short_name)",
"{'status':status}) output['next_status'] = str(status.in_reply_to_status_id) else: output['status'] = '<li>The next tweet no longer exists</li>'",
"= datetime.strptime(request.REQUEST.get('start'),\"%Y-%m-%d\") if request.REQUEST.get('end'): filters['created_at__lt'] = datetime.strptime(request.REQUEST.get('end'),\"%Y-%m-%d\") if request.REQUEST.get('q'): terms = request.REQUEST.get('q').split() statuses",
"\",\" member_names = member_names + member return render_to_response('group-gen-add.html', { 'user':account, 'member_names':member_names}, context_instance=RequestContext(request)) return",
"account, \"short_name\":short_name, \"name\":name, \"member_names\":member_names, }, context_instance=RequestContext(request)) people = [] if len(short_name) < 1:",
"@needs_account('/login') def GroupAddPage(request,account=None): name = request.REQUEST.get('name','') short_name = name.replace(' ','_').lower() member_names = request.REQUEST.get('member_names','')",
"group by the short_name \\'' + short_name + '\\' already exists for you.",
"member in members: if len(member_names) > 0: member_names = member_names + \",\" member_names",
"Group.by_short_name_and_user(short_name, account) filters = {} terms = None tweetCount = 20 loadCount =",
"account.rate_remaining response = HttpResponse() response.write(simplejson.dumps(output)) except: exc_type, exc_value, exc_traceback = sys.exc_info() print \"***",
"output['oldest_date'] = group.oldestStatus().status_date() if group.latestStatus(): output['latest_date'] = group.latestStatus().status_date() if account: output['api_calls'] = account.rate_remaining",
"statuses = group.statuses(20,0,query=terms,**filters) encodeURLs(statuses, account) return render_to_response('group-tweets.html', {'name':group.name, 'statuses':statuses}) @wants_account def GroupTweetsAdditional(request,short_name,loadCount=0,account=None): group",
"return HttpResponseRedirect('/group') return render_to_response('group-add.html', { 'user': account, },context_instance=RequestContext(request)) @needs_account('/login') def GroupGenAddPage(request,account=None): errors =",
"= str(None) if account: output['api_calls'] = account.rate_remaining response = HttpResponse() response.write(simplejson.dumps(output)) return response",
"= None if request.REQUEST.get('start'): filters['created_at__gte'] = datetime.strptime(request.REQUEST.get('start'),\"%Y-%m-%d\") if request.REQUEST.get('end'): filters['created_at__lt'] = datetime.strptime(request.REQUEST.get('end'),\"%Y-%m-%d\") if",
"time import sys, traceback import re import urllib2 def encodeURLs(statuses,account): r = re.compile(r\"(http://[^,",
"use this file except in compliance with the License. You may obtain a",
"render_to_string('status.html', {'status':status}) output['next_status'] = str(status.in_reply_to_status_id) else: output['status'] = '<li>The next tweet no longer",
"render_to_response('group-gen-add.html', { 'user':account, 'member_names':member_names}, context_instance=RequestContext(request)) return render_to_response('group-gen-add.html', { 'user':account, }, context_instance=RequestContext(request)) @needs_account('/login') def",
"of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to",
"context_instance=RequestContext(request)) group = Group.by_short_name_and_user(short_name, account) if group: return render_to_response('group-add.html', { \"errors\":['A group by",
"import wants_account, needs_account from django.utils import simplejson from twitter_explorer import settings from twitter",
"re.compile(r\"(http://[^, ]+[^,. ])\") s = re.compile(r'(\\A|\\s)@(\\w+)') if isinstance(statuses,Status): temp = [] temp.append(statuses) statuses",
"Licensed under the Apache License, Version 2.0 (the \"License\"); you may not use",
"Group.by_short_name_and_user(short_name, account) if group: return render_to_response('group-add.html', { \"errors\":['A group by the short_name \\''",
"import settings from twitter import collector from datetime import datetime from django.template.context import",
"person.statusCount() output['complete'] = complete if person.oldestStatus(): output['oldest_date'] = person.oldestStatus().status_date() if person.latestStatus(): output['latest_date'] =",
"= [] if len(short_name) < 1: errors.append(\"Please ensure the group name is atleast",
"= datetime.strptime(request.REQUEST.get('end'),\"%Y-%m-%d\") if request.REQUEST.get('q'): terms = request.REQUEST.get('q').split() statuses = group.statuses(tweetCount,loadCount,query=terms,**filters) encodeURLs(statuses, account) return",
"tasks.updatePersonTweets(person,account) num_friends = person.following_count else: num_friends = None return render_to_response('person.html',{'person':person, 'num_friends':num_friends, 'user':account}) @wants_account",
"@wants_account def PersonTweetsBackground(request,screen_name,account=None): try: output = {} person = Person.by_screen_name(screen_name) count = 0",
"= conn.read() conn.close() except: errors.append('We were unable to get any data from the",
"if len(errors) > 0: return render_to_response('group-add.html', { \"errors\":errors, \"user\": account, \"short_name\":short_name, \"name\":name, \"member_names\":member_names,",
"links = r.findall(data) members = [] for link in links: link = link.replace('twitter.com/','')",
"if person: members.append(link) member_names = \"\" for member in members: if len(member_names) >",
"render_to_response('group-tweets.html', {'name':group.name, 'statuses':statuses}) @wants_account def GroupTweetsAdditional(request,short_name,loadCount=0,account=None): group = Group.by_short_name_and_user(short_name, account) filters = {}",
"if request.REQUEST.get('end'): filters['created_at__lt'] = datetime.strptime(request.REQUEST.get('end'),\"%Y-%m-%d\") if request.REQUEST.get('q'): terms = request.REQUEST.get('q').split() statuses = group.statuses(tweetCount,loadCount,query=terms,**filters)",
"in statuses: status.text = r.sub(r'<a href=\"\\1\" target=\"_blank\" rel=\"nofollow\">\\1</a>', status.text) status.text = s.sub(r'\\1@<a href=\"/user/\\2\"",
"short_name = name.replace(' ','_').lower() member_names = request.REQUEST.get('member_names','') auto_gen = request.REQUEST.get('auto_gen',None) errors = []",
"}, context_instance=RequestContext(request)) @needs_account('/login') def GroupPage(request,short_name,account=None): group = Group.by_short_name_and_user(short_name, account) for member in group.members.all():",
"django.http import HttpResponse, HttpResponseRedirect from auth.decorators import wants_account, needs_account from django.utils import simplejson",
"a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or",
"render_to_string from twitter.models import Person, Status from twitter_explorer.models import Group from django.http import",
"links: link = link.replace('twitter.com/','') if not link in members: person = collector.person(link, account)",
"member_names = member_names + \",\" member_names = member_names + member return render_to_response('group-gen-add.html', {",
"request.REQUEST.get('q').split() statuses = group.statuses(tweetCount,loadCount,query=terms,**filters) encodeURLs(statuses, account) return render_to_response('group-tweets-additional.html', {'statuses':statuses}) @wants_account def GroupTweetsBackground(request,short_name,account=None): output",
"status: status = collector.status(status_id,account) if status: encodeURLs(status, account) output['status'] = render_to_string('status.html', {'status':status}) output['next_status']",
"account) for member in group.members.all(): tasks.updatePersonTweets(member, account) return render_to_response('group.html',{'group':group, 'user':account}) @wants_account def GroupTweets(request,short_name,account=None):",
"request.REQUEST.get('end'): filters['created_at__lt'] = datetime.strptime(request.REQUEST.get('end'),\"%Y-%m-%d\") if request.REQUEST.get('q'): terms = request.REQUEST.get('q').split() statuses = person.statuses(20,0,query=terms,**filters) encodeURLs(statuses,",
"request.REQUEST.get('q').split() statuses = group.statuses(20,0,query=terms,**filters) encodeURLs(statuses, account) return render_to_response('group-tweets.html', {'name':group.name, 'statuses':statuses}) @wants_account def GroupTweetsAdditional(request,short_name,loadCount=0,account=None):",
"for member in members: if len(member_names) > 0: member_names = member_names + \",\"",
"loadCount = tweetCount * int(loadCount) terms = None if request.REQUEST.get('start'): filters['created_at__gte'] = datetime.strptime(request.REQUEST.get('start'),\"%Y-%m-%d\")",
"\"short_name\":short_name, \"name\":name, \"member_names\":member_names, }, context_instance=RequestContext(request)) else: group = Group.objects.create(short_name=short_name, user=account, name=name) for person",
"RequestContext from twitter_explorer import tasks import time import sys, traceback import re import",
"\"member_names\":member_names, }, context_instance=RequestContext(request)) else: group = Group.objects.create(short_name=short_name, user=account, name=name) for person in people:",
"in members: person = collector.person(link, account) if person: members.append(link) member_names = \"\" for",
"= {} terms = None tweetCount = 20 loadCount = tweetCount * int(loadCount)",
"= str(status.in_reply_to_status_id) else: output['status'] = '<li>The next tweet no longer exists</li>' output['next_status'] =",
"= person.statusCount() output['complete'] = complete if person.oldestStatus(): output['oldest_date'] = person.oldestStatus().status_date() if person.latestStatus(): output['latest_date']",
"if person: tasks.updatePersonTweets(person,account) num_friends = person.following_count else: num_friends = None return render_to_response('person.html',{'person':person, 'num_friends':num_friends,",
"num_friends = None return render_to_response('person.html',{'person':person, 'num_friends':num_friends, 'user':account}) @wants_account def PersonTweets(request,screen_name,account=None): person = Person.by_screen_name(screen_name)",
"target=\"_blank\" rel=\"nofollow\">\\2</a>', status.text) @wants_account def MainPage(request,account=None): return render_to_response('index.html',{'user':account}) @wants_account def PersonPage(request,screen_name,account=None): if account:",
"member return render_to_response('group-gen-add.html', { 'user':account, 'member_names':member_names}, context_instance=RequestContext(request)) return render_to_response('group-gen-add.html', { 'user':account, }, context_instance=RequestContext(request))",
"return render_to_response('group-gen-add.html', { 'user':account, }, context_instance=RequestContext(request)) @needs_account('/login') def GroupPage(request,short_name,account=None): group = Group.by_short_name_and_user(short_name, account)",
"member_names = \"\" for member in members: if len(member_names) > 0: member_names =",
"account, },context_instance=RequestContext(request)) @needs_account('/login') def GroupGenAddPage(request,account=None): errors = [] if 'POST' == request.method: url",
"required by applicable law or agreed to in writing, software distributed under the",
"def MainPage(request,account=None): return render_to_response('index.html',{'user':account}) @wants_account def PersonPage(request,screen_name,account=None): if account: person = collector.person(screen_name,account) else:",
"= Person.by_screen_name(member) if not person: person = collector.person(member,account) if person: people.append(person) tasks.updatePersonTweets(person,account) else:",
"= None tweetCount = 20 loadCount = tweetCount * int(loadCount) if request.REQUEST.get('start'): filters['created_at__gte']",
"\"name\":name, \"member_names\":member_names, }, context_instance=RequestContext(request)) people = [] if len(short_name) < 1: errors.append(\"Please ensure",
"\"*** print_exc:\" traceback.print_exc() print \"*** format_exc, first and last line:\" return response @wants_account",
"{ \"errors\":['A group by the short_name \\'' + short_name + '\\' already exists",
"sure it is correct and includes the http://') if len(errors) > 0: return",
"request.REQUEST.get('q').split() statuses = person.statuses(20,0,query=terms,**filters) encodeURLs(statuses, account) return render_to_response('person-tweets.html', {'screen_name':screen_name, 'statuses':statuses}) @wants_account def PersonTweetsAdditional(request,screen_name,loadCount=0,account=None):",
"the url provided. Please make sure it is correct and includes the http://')",
"else: num_friends = None return render_to_response('person.html',{'person':person, 'num_friends':num_friends, 'user':account}) @wants_account def PersonTweets(request,screen_name,account=None): person =",
"short_name + '\\' already exists for you. Please try another.'], \"user\": account, \"short_name\":short_name,",
"@wants_account def GroupTweets(request,short_name,account=None): group = Group.by_short_name_and_user(short_name, account) terms = None filters = {}",
"response = HttpResponse() response.write(simplejson.dumps(output)) return response @wants_account def Tweet(request,status_id,account=None): output = {} status",
"includes the http://') if len(errors) > 0: return render_to_response('group-gen-add.html', { 'url':url, 'errors':errors, 'user':account,",
"filters['created_at__lt'] = datetime.strptime(request.REQUEST.get('end'),\"%Y-%m-%d\") if request.REQUEST.get('q'): terms = request.REQUEST.get('q').split() statuses = group.statuses(20,0,query=terms,**filters) encodeURLs(statuses, account)",
"http://') if len(errors) > 0: return render_to_response('group-gen-add.html', { 'url':url, 'errors':errors, 'user':account, }, context_instance=RequestContext(request))",
"\"member_names\":member_names, }, context_instance=RequestContext(request)) group = Group.by_short_name_and_user(short_name, account) if group: return render_to_response('group-add.html', { \"errors\":['A",
"for the specific language governing permissions and limitations under the License. Contributors <NAME>",
"if isinstance(statuses,Status): temp = [] temp.append(statuses) statuses = temp for status in statuses:",
"person = Person.by_screen_name(screen_name) filters = {} tweetCount = 20 loadCount = tweetCount *",
"distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,",
"provided. Please make sure it is correct and includes the http://') if len(errors)",
"data = conn.read() conn.close() except: errors.append('We were unable to get any data from",
"account) output['num_statuses'] = group.status_count() complete = not group.isUpdating() output['complete'] = complete if group.oldestStatus():",
"= [] temp.append(statuses) statuses = temp for status in statuses: status.text = r.sub(r'<a",
"not use this file except in compliance with the License. You may obtain",
"and includes the http://') if len(errors) > 0: return render_to_response('group-gen-add.html', { 'url':url, 'errors':errors,",
"output = {} group = Group.by_short_name_and_user(short_name, account) output['num_statuses'] = group.status_count() complete = not",
"group.isUpdating() output['complete'] = complete if group.oldestStatus(): output['oldest_date'] = group.oldestStatus().status_date() if group.latestStatus(): output['latest_date'] =",
"group name is atleast 1 character long.\") for member in member_names.strip().split(','): person =",
"from django.template.context import RequestContext from twitter_explorer import tasks import time import sys, traceback",
"\" + member) if len(errors) > 0: return render_to_response('group-add.html', { \"errors\":errors, \"user\": account,",
"+ member) if len(errors) > 0: return render_to_response('group-add.html', { \"errors\":errors, \"user\": account, \"short_name\":short_name,",
"person.following_count else: num_friends = None return render_to_response('person.html',{'person':person, 'num_friends':num_friends, 'user':account}) @wants_account def PersonTweets(request,screen_name,account=None): person",
"person.isUpdating() output['num_statuses'] = person.statusCount() output['complete'] = complete if person.oldestStatus(): output['oldest_date'] = person.oldestStatus().status_date() if",
"s = re.compile(r'(\\A|\\s)@(\\w+)') if isinstance(statuses,Status): temp = [] temp.append(statuses) statuses = temp for",
"time.sleep(2**count) count = count + 1 complete = not person.isUpdating() output['num_statuses'] = person.statusCount()",
"= person.following_count else: num_friends = None return render_to_response('person.html',{'person':person, 'num_friends':num_friends, 'user':account}) @wants_account def PersonTweets(request,screen_name,account=None):",
"member in group.members.all(): tasks.updatePersonTweets(member, account) return render_to_response('group.html',{'group':group, 'user':account}) @wants_account def GroupTweets(request,short_name,account=None): group =",
"\"name\":name, \"member_names\":member_names, }, context_instance=RequestContext(request)) else: group = Group.objects.create(short_name=short_name, user=account, name=name) for person in",
"tweetCount * int(loadCount) terms = None if request.REQUEST.get('start'): filters['created_at__gte'] = datetime.strptime(request.REQUEST.get('start'),\"%Y-%m-%d\") if request.REQUEST.get('end'):",
"needs_account from django.utils import simplejson from twitter_explorer import settings from twitter import collector",
"render_to_response('group-tweets-additional.html', {'statuses':statuses}) @wants_account def GroupTweetsBackground(request,short_name,account=None): output = {} group = Group.by_short_name_and_user(short_name, account) output['num_statuses']",
"<NAME> ''' from django.shortcuts import render_to_response from django.template.loader import render_to_string from twitter.models import",
"= account.rate_remaining response = HttpResponse() response.write(simplejson.dumps(output)) except: exc_type, exc_value, exc_traceback = sys.exc_info() print",
"Group.by_short_name_and_user(short_name, account) for member in group.members.all(): tasks.updatePersonTweets(member, account) return render_to_response('group.html',{'group':group, 'user':account}) @wants_account def",
"= person.latestStatus().status_date() if account: output['api_calls'] = account.rate_remaining response = HttpResponse() response.write(simplejson.dumps(output)) except: exc_type,",
"= account.rate_remaining response = HttpResponse() response.write(simplejson.dumps(output)) return response @wants_account def Tweet(request,status_id,account=None): output =",
"return render_to_response('group-add.html', { 'user': account, },context_instance=RequestContext(request)) @needs_account('/login') def GroupGenAddPage(request,account=None): errors = [] if",
"None if request.REQUEST.get('start'): filters['created_at__gte'] = datetime.strptime(request.REQUEST.get('start'),\"%Y-%m-%d\") if request.REQUEST.get('end'): filters['created_at__lt'] = datetime.strptime(request.REQUEST.get('end'),\"%Y-%m-%d\") if request.REQUEST.get('q'):",
"user=account, name=name) for person in people: group.members.add(person) group.save() return HttpResponseRedirect('/group') return render_to_response('group-add.html', {",
"terms = request.REQUEST.get('q').split() statuses = group.statuses(tweetCount,loadCount,query=terms,**filters) encodeURLs(statuses, account) return render_to_response('group-tweets-additional.html', {'statuses':statuses}) @wants_account def",
"License. Contributors <NAME> ''' from django.shortcuts import render_to_response from django.template.loader import render_to_string from",
"terms = request.REQUEST.get('q').split() statuses = person.statuses(20,0,query=terms,**filters) encodeURLs(statuses, account) return render_to_response('person-tweets.html', {'screen_name':screen_name, 'statuses':statuses}) @wants_account",
"and person.isUpdating() is True: time.sleep(2**count) count = count + 1 complete = not",
"def PersonTweets(request,screen_name,account=None): person = Person.by_screen_name(screen_name) filters = {} terms=None if request.REQUEST.get('start'): filters['created_at__gte'] =",
"ANY KIND, either express or implied. See the License for the specific language",
"twitter.models import Person, Status from twitter_explorer.models import Group from django.http import HttpResponse, HttpResponseRedirect",
"def AboutPage(request,account=None): return render_to_response('about.html', {'user':account}) @needs_account('/login') def GroupListPage(request,account=None): groups = Group.by_user(account) return render_to_response('group-list.html',",
"errors = [] if 'POST' == request.method: url = request.REQUEST.get('url','') try: conn =",
"def GroupTweets(request,short_name,account=None): group = Group.by_short_name_and_user(short_name, account) terms = None filters = {} if",
"person = Person.by_screen_name(screen_name) count = 0 while person.statusCount() is 0 and person.isUpdating() is",
"file except in compliance with the License. You may obtain a copy of",
"from django.template.loader import render_to_string from twitter.models import Person, Status from twitter_explorer.models import Group",
"= None filters = {} if request.REQUEST.get('start'): filters['created_at__gte'] = datetime.strptime(request.REQUEST.get('start'),\"%Y-%m-%d\") if request.REQUEST.get('end'): filters['created_at__lt']",
"datetime from django.template.context import RequestContext from twitter_explorer import tasks import time import sys,",
"in member_names.strip().split(','): person = Person.by_screen_name(member) if not person: person = collector.person(member,account) if person:",
"filters = {} if request.REQUEST.get('start'): filters['created_at__gte'] = datetime.strptime(request.REQUEST.get('start'),\"%Y-%m-%d\") if request.REQUEST.get('end'): filters['created_at__lt'] = datetime.strptime(request.REQUEST.get('end'),\"%Y-%m-%d\")",
"= {} group = Group.by_short_name_and_user(short_name, account) output['num_statuses'] = group.status_count() complete = not group.isUpdating()",
"return render_to_response('group-add.html', { \"errors\":errors, \"user\": account, \"short_name\":short_name, \"name\":name, \"member_names\":member_names, }, context_instance=RequestContext(request)) else: group",
"if len(short_name) < 1: errors.append(\"Please ensure the group name is atleast 1 character",
"unable to get any data from the url provided. Please make sure it",
"django.template.context import RequestContext from twitter_explorer import tasks import time import sys, traceback import",
"2.0 (the \"License\"); you may not use this file except in compliance with",
"from twitter.models import Person, Status from twitter_explorer.models import Group from django.http import HttpResponse,",
"len(errors) > 0: return render_to_response('group-add.html', { \"errors\":errors, \"user\": account, \"short_name\":short_name, \"name\":name, \"member_names\":member_names, },",
"str(status.in_reply_to_status_id) else: output['status'] = '<li>The next tweet no longer exists</li>' output['next_status'] = str(None)",
"= re.compile(r\"(http://[^, ]+[^,. ])\") s = re.compile(r'(\\A|\\s)@(\\w+)') if isinstance(statuses,Status): temp = [] temp.append(statuses)",
"no longer exists</li>' output['next_status'] = str(None) if account: output['api_calls'] = account.rate_remaining response =",
"filters['created_at__lt'] = datetime.strptime(request.REQUEST.get('end'),\"%Y-%m-%d\") if request.REQUEST.get('q'): terms = request.REQUEST.get('q').split() statuses = group.statuses(tweetCount,loadCount,query=terms,**filters) encodeURLs(statuses, account)",
"under the License. Contributors <NAME> ''' from django.shortcuts import render_to_response from django.template.loader import",
"data from the url provided. Please make sure it is correct and includes",
"GroupAddPage(request,account=None): name = request.REQUEST.get('name','') short_name = name.replace(' ','_').lower() member_names = request.REQUEST.get('member_names','') auto_gen =",
"copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed",
"from django.http import HttpResponse, HttpResponseRedirect from auth.decorators import wants_account, needs_account from django.utils import",
"from twitter_explorer import tasks import time import sys, traceback import re import urllib2",
"filters = {} tweetCount = 20 loadCount = tweetCount * int(loadCount) terms =",
"group.oldestStatus(): output['oldest_date'] = group.oldestStatus().status_date() if group.latestStatus(): output['latest_date'] = group.latestStatus().status_date() if account: output['api_calls'] =",
"<NAME>, The CHISEL group and contributors Licensed under the Apache License, Version 2.0",
"group.latestStatus(): output['latest_date'] = group.latestStatus().status_date() if account: output['api_calls'] = account.rate_remaining response = HttpResponse() response.write(simplejson.dumps(output))",
"{} group = Group.by_short_name_and_user(short_name, account) output['num_statuses'] = group.status_count() complete = not group.isUpdating() output['complete']",
"the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless",
"account, \"short_name\":short_name, \"name\":name, \"member_names\":member_names, }, context_instance=RequestContext(request)) else: group = Group.objects.create(short_name=short_name, user=account, name=name) for",
"context_instance=RequestContext(request)) @needs_account('/login') def GroupPage(request,short_name,account=None): group = Group.by_short_name_and_user(short_name, account) for member in group.members.all(): tasks.updatePersonTweets(member,",
"def encodeURLs(statuses,account): r = re.compile(r\"(http://[^, ]+[^,. ])\") s = re.compile(r'(\\A|\\s)@(\\w+)') if isinstance(statuses,Status): temp",
"group and contributors Licensed under the Apache License, Version 2.0 (the \"License\"); you",
"context_instance=RequestContext(request)) r = re.compile(r\"(twitter.com/[^, /\\\"]+[^,. /\\\"])\") links = r.findall(data) members = [] for",
"(the \"License\"); you may not use this file except in compliance with the",
"= s.sub(r'\\1@<a href=\"/user/\\2\" target=\"_blank\" rel=\"nofollow\">\\2</a>', status.text) @wants_account def MainPage(request,account=None): return render_to_response('index.html',{'user':account}) @wants_account def",
"django.utils import simplejson from twitter_explorer import settings from twitter import collector from datetime",
"status.text) status.text = s.sub(r'\\1@<a href=\"/user/\\2\" target=\"_blank\" rel=\"nofollow\">\\2</a>', status.text) @wants_account def MainPage(request,account=None): return render_to_response('index.html',{'user':account})",
"render_to_response('group-add.html', { \"errors\":errors, \"user\": account, \"short_name\":short_name, \"name\":name, \"member_names\":member_names, }, context_instance=RequestContext(request)) else: group =",
"return render_to_response('group-list.html', {'user':account, 'groups':groups, }) @needs_account('/login') def GroupAddPage(request,account=None): name = request.REQUEST.get('name','') short_name =",
"return render_to_response('index.html',{'user':account}) @wants_account def PersonPage(request,screen_name,account=None): if account: person = collector.person(screen_name,account) else: person =",
"for status in statuses: status.text = r.sub(r'<a href=\"\\1\" target=\"_blank\" rel=\"nofollow\">\\1</a>', status.text) status.text =",
"num_friends = person.following_count else: num_friends = None return render_to_response('person.html',{'person':person, 'num_friends':num_friends, 'user':account}) @wants_account def",
"from twitter_explorer import settings from twitter import collector from datetime import datetime from",
"character long.\") for member in member_names.strip().split(','): person = Person.by_screen_name(member) if not person: person",
"output['num_statuses'] = group.status_count() complete = not group.isUpdating() output['complete'] = complete if group.oldestStatus(): output['oldest_date']",
"account) output['status'] = render_to_string('status.html', {'status':status}) output['next_status'] = str(status.in_reply_to_status_id) else: output['status'] = '<li>The next",
"'user':account}) @wants_account def PersonTweets(request,screen_name,account=None): person = Person.by_screen_name(screen_name) filters = {} terms=None if request.REQUEST.get('start'):",
"person = collector.person(screen_name,account) else: person = Person.by_screen_name(screen_name) if person: tasks.updatePersonTweets(person,account) num_friends = person.following_count",
"= collector.person(link, account) if person: members.append(link) member_names = \"\" for member in members:",
"PersonTweets(request,screen_name,account=None): person = Person.by_screen_name(screen_name) filters = {} terms=None if request.REQUEST.get('start'): filters['created_at__gte'] = datetime.strptime(request.REQUEST.get('start'),\"%Y-%m-%d\")",
"{} terms=None if request.REQUEST.get('start'): filters['created_at__gte'] = datetime.strptime(request.REQUEST.get('start'),\"%Y-%m-%d\") if request.REQUEST.get('end'): filters['created_at__lt'] = datetime.strptime(request.REQUEST.get('end'),\"%Y-%m-%d\") if",
"format_exc, first and last line:\" return response @wants_account def AboutPage(request,account=None): return render_to_response('about.html', {'user':account})",
"file=sys.stdout) print \"*** print_exception:\" traceback.print_exception(exc_type, exc_value, exc_traceback, limit=2, file=sys.stdout) print \"*** print_exc:\" traceback.print_exc()",
"link in links: link = link.replace('twitter.com/','') if not link in members: person =",
"= Status.by_id(status_id) if not status: status = collector.status(status_id,account) if status: encodeURLs(status, account) output['status']",
"account) if person: members.append(link) member_names = \"\" for member in members: if len(member_names)",
"loadCount = tweetCount * int(loadCount) if request.REQUEST.get('start'): filters['created_at__gte'] = datetime.strptime(request.REQUEST.get('start'),\"%Y-%m-%d\") if request.REQUEST.get('end'): filters['created_at__lt']",
"if request.REQUEST.get('start'): filters['created_at__gte'] = datetime.strptime(request.REQUEST.get('start'),\"%Y-%m-%d\") if request.REQUEST.get('end'): filters['created_at__lt'] = datetime.strptime(request.REQUEST.get('end'),\"%Y-%m-%d\") if request.REQUEST.get('q'): terms",
"if status: encodeURLs(status, account) output['status'] = render_to_string('status.html', {'status':status}) output['next_status'] = str(status.in_reply_to_status_id) else: output['status']",
"group = Group.by_short_name_and_user(short_name, account) terms = None filters = {} if request.REQUEST.get('start'): filters['created_at__gte']",
"from the url provided. Please make sure it is correct and includes the",
"= Person.by_screen_name(screen_name) count = 0 while person.statusCount() is 0 and person.isUpdating() is True:",
"statuses = group.statuses(tweetCount,loadCount,query=terms,**filters) encodeURLs(statuses, account) return render_to_response('group-tweets-additional.html', {'statuses':statuses}) @wants_account def GroupTweetsBackground(request,short_name,account=None): output =",
"django.shortcuts import render_to_response from django.template.loader import render_to_string from twitter.models import Person, Status from",
"datetime import datetime from django.template.context import RequestContext from twitter_explorer import tasks import time",
"tweetCount * int(loadCount) if request.REQUEST.get('start'): filters['created_at__gte'] = datetime.strptime(request.REQUEST.get('start'),\"%Y-%m-%d\") if request.REQUEST.get('end'): filters['created_at__lt'] = datetime.strptime(request.REQUEST.get('end'),\"%Y-%m-%d\")",
"terms = request.REQUEST.get('q').split() statuses = person.statuses(tweetCount,loadCount,query=terms,**filters) encodeURLs(statuses, account) return render_to_response('person-tweets-additional.html', {'screen_name':screen_name, 'statuses':statuses}) @wants_account",
"output['status'] = render_to_string('status.html', {'status':status}) output['next_status'] = str(status.in_reply_to_status_id) else: output['status'] = '<li>The next tweet",
"complete if person.oldestStatus(): output['oldest_date'] = person.oldestStatus().status_date() if person.latestStatus(): output['latest_date'] = person.latestStatus().status_date() if account:",
"http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed",
"+ short_name + '\\' already exists for you. Please try another.'], \"user\": account,",
"in links: link = link.replace('twitter.com/','') if not link in members: person = collector.person(link,",
"@wants_account def AboutPage(request,account=None): return render_to_response('about.html', {'user':account}) @needs_account('/login') def GroupListPage(request,account=None): groups = Group.by_user(account) return",
"\"user\": account, \"short_name\":short_name, \"name\":name, \"member_names\":member_names, }, context_instance=RequestContext(request)) people = [] if len(short_name) <",
"License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF",
"member_names.strip().split(','): person = Person.by_screen_name(member) if not person: person = collector.person(member,account) if person: people.append(person)",
"statuses = temp for status in statuses: status.text = r.sub(r'<a href=\"\\1\" target=\"_blank\" rel=\"nofollow\">\\1</a>',",
"ensure the group name is atleast 1 character long.\") for member in member_names.strip().split(','):",
"terms=None if request.REQUEST.get('start'): filters['created_at__gte'] = datetime.strptime(request.REQUEST.get('start'),\"%Y-%m-%d\") if request.REQUEST.get('end'): filters['created_at__lt'] = datetime.strptime(request.REQUEST.get('end'),\"%Y-%m-%d\") if request.REQUEST.get('q'):",
"temp.append(statuses) statuses = temp for status in statuses: status.text = r.sub(r'<a href=\"\\1\" target=\"_blank\"",
"= datetime.strptime(request.REQUEST.get('end'),\"%Y-%m-%d\") if request.REQUEST.get('q'): terms = request.REQUEST.get('q').split() statuses = person.statuses(20,0,query=terms,**filters) encodeURLs(statuses, account) return",
"= HttpResponse() response.write(simplejson.dumps(output)) return response @wants_account def Tweet(request,status_id,account=None): output = {} status =",
"law or agreed to in writing, software distributed under the License is distributed",
"person: tasks.updatePersonTweets(person,account) num_friends = person.following_count else: num_friends = None return render_to_response('person.html',{'person':person, 'num_friends':num_friends, 'user':account})",
"if request.REQUEST.get('end'): filters['created_at__lt'] = datetime.strptime(request.REQUEST.get('end'),\"%Y-%m-%d\") if request.REQUEST.get('q'): terms = request.REQUEST.get('q').split() statuses = person.statuses(20,0,query=terms,**filters)",
"datetime.strptime(request.REQUEST.get('end'),\"%Y-%m-%d\") if request.REQUEST.get('q'): terms = request.REQUEST.get('q').split() statuses = person.statuses(tweetCount,loadCount,query=terms,**filters) encodeURLs(statuses, account) return render_to_response('person-tweets-additional.html',",
"count = count + 1 complete = not person.isUpdating() output['num_statuses'] = person.statusCount() output['complete']",
"find a user named: \" + member) if len(errors) > 0: return render_to_response('group-add.html',",
"'user':account, }, context_instance=RequestContext(request)) @needs_account('/login') def GroupPage(request,short_name,account=None): group = Group.by_short_name_and_user(short_name, account) for member in",
"Version 2.0 (the \"License\"); you may not use this file except in compliance",
"= datetime.strptime(request.REQUEST.get('end'),\"%Y-%m-%d\") if request.REQUEST.get('q'): terms = request.REQUEST.get('q').split() statuses = group.statuses(20,0,query=terms,**filters) encodeURLs(statuses, account) return",
"the Apache License, Version 2.0 (the \"License\"); you may not use this file",
"encodeURLs(statuses, account) return render_to_response('person-tweets.html', {'screen_name':screen_name, 'statuses':statuses}) @wants_account def PersonTweetsAdditional(request,screen_name,loadCount=0,account=None): person = Person.by_screen_name(screen_name) filters",
"member in member_names.strip().split(','): person = Person.by_screen_name(member) if not person: person = collector.person(member,account) if",
"for member in member_names.strip().split(','): person = Person.by_screen_name(member) if not person: person = collector.person(member,account)",
"+ \",\" member_names = member_names + member return render_to_response('group-gen-add.html', { 'user':account, 'member_names':member_names}, context_instance=RequestContext(request))",
"status in statuses: status.text = r.sub(r'<a href=\"\\1\" target=\"_blank\" rel=\"nofollow\">\\1</a>', status.text) status.text = s.sub(r'\\1@<a",
"render_to_response('index.html',{'user':account}) @wants_account def PersonPage(request,screen_name,account=None): if account: person = collector.person(screen_name,account) else: person = Person.by_screen_name(screen_name)",
"member_names + member return render_to_response('group-gen-add.html', { 'user':account, 'member_names':member_names}, context_instance=RequestContext(request)) return render_to_response('group-gen-add.html', { 'user':account,",
"@needs_account('/login') def GroupPage(request,short_name,account=None): group = Group.by_short_name_and_user(short_name, account) for member in group.members.all(): tasks.updatePersonTweets(member, account)",
"conn.close() except: errors.append('We were unable to get any data from the url provided.",
"exc_traceback, limit=2, file=sys.stdout) print \"*** print_exc:\" traceback.print_exc() print \"*** format_exc, first and last",
"errors.append('We were unable to get any data from the url provided. Please make",
"the group name is atleast 1 character long.\") for member in member_names.strip().split(','): person",
"person = Person.by_screen_name(member) if not person: person = collector.person(member,account) if person: people.append(person) tasks.updatePersonTweets(person,account)",
"tasks import time import sys, traceback import re import urllib2 def encodeURLs(statuses,account): r",
"if group.oldestStatus(): output['oldest_date'] = group.oldestStatus().status_date() if group.latestStatus(): output['latest_date'] = group.latestStatus().status_date() if account: output['api_calls']",
"Status from twitter_explorer.models import Group from django.http import HttpResponse, HttpResponseRedirect from auth.decorators import",
"under the Apache License, Version 2.0 (the \"License\"); you may not use this",
"None filters = {} if request.REQUEST.get('start'): filters['created_at__gte'] = datetime.strptime(request.REQUEST.get('start'),\"%Y-%m-%d\") if request.REQUEST.get('end'): filters['created_at__lt'] =",
"if len(member_names) > 0: member_names = member_names + \",\" member_names = member_names +",
"= not group.isUpdating() output['complete'] = complete if group.oldestStatus(): output['oldest_date'] = group.oldestStatus().status_date() if group.latestStatus():",
"correct and includes the http://') if len(errors) > 0: return render_to_response('group-gen-add.html', { 'url':url,",
"either express or implied. See the License for the specific language governing permissions",
"\"*** print_exception:\" traceback.print_exception(exc_type, exc_value, exc_traceback, limit=2, file=sys.stdout) print \"*** print_exc:\" traceback.print_exc() print \"***",
"print \"*** print_exc:\" traceback.print_exc() print \"*** format_exc, first and last line:\" return response",
"the http://') if len(errors) > 0: return render_to_response('group-gen-add.html', { 'url':url, 'errors':errors, 'user':account, },",
"= Group.by_short_name_and_user(short_name, account) for member in group.members.all(): tasks.updatePersonTweets(member, account) return render_to_response('group.html',{'group':group, 'user':account}) @wants_account",
"GroupTweetsBackground(request,short_name,account=None): output = {} group = Group.by_short_name_and_user(short_name, account) output['num_statuses'] = group.status_count() complete =",
"== request.method: url = request.REQUEST.get('url','') try: conn = urllib2.urlopen(url) data = conn.read() conn.close()",
"except: exc_type, exc_value, exc_traceback = sys.exc_info() print \"*** print_tb:\" traceback.print_tb(exc_traceback, limit=1, file=sys.stdout) print",
"0 while person.statusCount() is 0 and person.isUpdating() is True: time.sleep(2**count) count = count",
"if person.latestStatus(): output['latest_date'] = person.latestStatus().status_date() if account: output['api_calls'] = account.rate_remaining response = HttpResponse()",
"render_to_response('group-add.html', { 'user': account, },context_instance=RequestContext(request)) @needs_account('/login') def GroupGenAddPage(request,account=None): errors = [] if 'POST'",
"Apache License, Version 2.0 (the \"License\"); you may not use this file except",
"or implied. See the License for the specific language governing permissions and limitations",
"if account: person = collector.person(screen_name,account) else: person = Person.by_screen_name(screen_name) if person: tasks.updatePersonTweets(person,account) num_friends",
"Tweet(request,status_id,account=None): output = {} status = Status.by_id(status_id) if not status: status = collector.status(status_id,account)",
"not group.isUpdating() output['complete'] = complete if group.oldestStatus(): output['oldest_date'] = group.oldestStatus().status_date() if group.latestStatus(): output['latest_date']",
"> 0: member_names = member_names + \",\" member_names = member_names + member return",
"r = re.compile(r\"(twitter.com/[^, /\\\"]+[^,. /\\\"])\") links = r.findall(data) members = [] for link",
"member_names + \",\" member_names = member_names + member return render_to_response('group-gen-add.html', { 'user':account, 'member_names':member_names},",
"traceback.print_tb(exc_traceback, limit=1, file=sys.stdout) print \"*** print_exception:\" traceback.print_exception(exc_type, exc_value, exc_traceback, limit=2, file=sys.stdout) print \"***",
"the License. Contributors <NAME> ''' from django.shortcuts import render_to_response from django.template.loader import render_to_string",
"return render_to_response('group-gen-add.html', { 'url':url, 'errors':errors, 'user':account, }, context_instance=RequestContext(request)) r = re.compile(r\"(twitter.com/[^, /\\\"]+[^,. /\\\"])\")",
"output['latest_date'] = person.latestStatus().status_date() if account: output['api_calls'] = account.rate_remaining response = HttpResponse() response.write(simplejson.dumps(output)) except:",
"{} tweetCount = 20 loadCount = tweetCount * int(loadCount) terms = None if",
"'POST' == request.method: if auto_gen: return render_to_response('group-add.html', { \"user\": account, \"member_names\":member_names, }, context_instance=RequestContext(request))",
"render_to_response('person-tweets-additional.html', {'screen_name':screen_name, 'statuses':statuses}) @wants_account def PersonTweetsBackground(request,screen_name,account=None): try: output = {} person = Person.by_screen_name(screen_name)",
"person = collector.person(link, account) if person: members.append(link) member_names = \"\" for member in",
"Contributors <NAME> ''' from django.shortcuts import render_to_response from django.template.loader import render_to_string from twitter.models",
"> 0: return render_to_response('group-gen-add.html', { 'url':url, 'errors':errors, 'user':account, }, context_instance=RequestContext(request)) r = re.compile(r\"(twitter.com/[^,",
"for person in people: group.members.add(person) group.save() return HttpResponseRedirect('/group') return render_to_response('group-add.html', { 'user': account,",
"person in people: group.members.add(person) group.save() return HttpResponseRedirect('/group') return render_to_response('group-add.html', { 'user': account, },context_instance=RequestContext(request))",
"url = request.REQUEST.get('url','') try: conn = urllib2.urlopen(url) data = conn.read() conn.close() except: errors.append('We",
"= request.REQUEST.get('auto_gen',None) errors = [] if 'POST' == request.method: if auto_gen: return render_to_response('group-add.html',",
"= collector.person(member,account) if person: people.append(person) tasks.updatePersonTweets(person,account) else: errors.append(\"Could not find a user named:",
"count + 1 complete = not person.isUpdating() output['num_statuses'] = person.statusCount() output['complete'] = complete",
"Please make sure it is correct and includes the http://') if len(errors) >",
"int(loadCount) if request.REQUEST.get('start'): filters['created_at__gte'] = datetime.strptime(request.REQUEST.get('start'),\"%Y-%m-%d\") if request.REQUEST.get('end'): filters['created_at__lt'] = datetime.strptime(request.REQUEST.get('end'),\"%Y-%m-%d\") if request.REQUEST.get('q'):",
"}, context_instance=RequestContext(request)) else: group = Group.objects.create(short_name=short_name, user=account, name=name) for person in people: group.members.add(person)",
"response @wants_account def AboutPage(request,account=None): return render_to_response('about.html', {'user':account}) @needs_account('/login') def GroupListPage(request,account=None): groups = Group.by_user(account)",
"url provided. Please make sure it is correct and includes the http://') if",
"datetime.strptime(request.REQUEST.get('end'),\"%Y-%m-%d\") if request.REQUEST.get('q'): terms = request.REQUEST.get('q').split() statuses = group.statuses(20,0,query=terms,**filters) encodeURLs(statuses, account) return render_to_response('group-tweets.html',",
"auth.decorators import wants_account, needs_account from django.utils import simplejson from twitter_explorer import settings from",
"Group.by_user(account) return render_to_response('group-list.html', {'user':account, 'groups':groups, }) @needs_account('/login') def GroupAddPage(request,account=None): name = request.REQUEST.get('name','') short_name",
"group: return render_to_response('group-add.html', { \"errors\":['A group by the short_name \\'' + short_name +",
"from auth.decorators import wants_account, needs_account from django.utils import simplejson from twitter_explorer import settings",
"statuses = person.statuses(20,0,query=terms,**filters) encodeURLs(statuses, account) return render_to_response('person-tweets.html', {'screen_name':screen_name, 'statuses':statuses}) @wants_account def PersonTweetsAdditional(request,screen_name,loadCount=0,account=None): person",
"\\'' + short_name + '\\' already exists for you. Please try another.'], \"user\":",
"import tasks import time import sys, traceback import re import urllib2 def encodeURLs(statuses,account):",
"CONDITIONS OF ANY KIND, either express or implied. See the License for the",
"person.isUpdating() is True: time.sleep(2**count) count = count + 1 complete = not person.isUpdating()",
"people = [] if len(short_name) < 1: errors.append(\"Please ensure the group name is",
"file=sys.stdout) print \"*** print_exc:\" traceback.print_exc() print \"*** format_exc, first and last line:\" return",
"group = Group.by_short_name_and_user(short_name, account) output['num_statuses'] = group.status_count() complete = not group.isUpdating() output['complete'] =",
"[] if 'POST' == request.method: if auto_gen: return render_to_response('group-add.html', { \"user\": account, \"member_names\":member_names,",
"{ 'user':account, }, context_instance=RequestContext(request)) @needs_account('/login') def GroupPage(request,short_name,account=None): group = Group.by_short_name_and_user(short_name, account) for member",
"to in writing, software distributed under the License is distributed on an \"AS",
"members: person = collector.person(link, account) if person: members.append(link) member_names = \"\" for member",
"= r.findall(data) members = [] for link in links: link = link.replace('twitter.com/','') if",
"by the short_name \\'' + short_name + '\\' already exists for you. Please",
"not person.isUpdating() output['num_statuses'] = person.statusCount() output['complete'] = complete if person.oldestStatus(): output['oldest_date'] = person.oldestStatus().status_date()",
"exc_type, exc_value, exc_traceback = sys.exc_info() print \"*** print_tb:\" traceback.print_tb(exc_traceback, limit=1, file=sys.stdout) print \"***",
"except in compliance with the License. You may obtain a copy of the",
"Copyright 2011-2012 <NAME>, The CHISEL group and contributors Licensed under the Apache License,",
"and contributors Licensed under the Apache License, Version 2.0 (the \"License\"); you may",
"= Person.by_screen_name(screen_name) if person: tasks.updatePersonTweets(person,account) num_friends = person.following_count else: num_friends = None return",
"= sys.exc_info() print \"*** print_tb:\" traceback.print_tb(exc_traceback, limit=1, file=sys.stdout) print \"*** print_exception:\" traceback.print_exception(exc_type, exc_value,",
"''' from django.shortcuts import render_to_response from django.template.loader import render_to_string from twitter.models import Person,",
"limit=1, file=sys.stdout) print \"*** print_exception:\" traceback.print_exception(exc_type, exc_value, exc_traceback, limit=2, file=sys.stdout) print \"*** print_exc:\"",
"len(member_names) > 0: member_names = member_names + \",\" member_names = member_names + member",
"an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express",
"= [] if 'POST' == request.method: if auto_gen: return render_to_response('group-add.html', { \"user\": account,",
"request.REQUEST.get('url','') try: conn = urllib2.urlopen(url) data = conn.read() conn.close() except: errors.append('We were unable",
"complete = not group.isUpdating() output['complete'] = complete if group.oldestStatus(): output['oldest_date'] = group.oldestStatus().status_date() if",
"group = Group.by_short_name_and_user(short_name, account) filters = {} terms = None tweetCount = 20",
"'user':account, 'member_names':member_names}, context_instance=RequestContext(request)) return render_to_response('group-gen-add.html', { 'user':account, }, context_instance=RequestContext(request)) @needs_account('/login') def GroupPage(request,short_name,account=None): group",
"filters['created_at__lt'] = datetime.strptime(request.REQUEST.get('end'),\"%Y-%m-%d\") if request.REQUEST.get('q'): terms = request.REQUEST.get('q').split() statuses = person.statuses(20,0,query=terms,**filters) encodeURLs(statuses, account)",
"twitter_explorer import tasks import time import sys, traceback import re import urllib2 def",
"},context_instance=RequestContext(request)) @needs_account('/login') def GroupGenAddPage(request,account=None): errors = [] if 'POST' == request.method: url =",
"obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law",
"= name.replace(' ','_').lower() member_names = request.REQUEST.get('member_names','') auto_gen = request.REQUEST.get('auto_gen',None) errors = [] if",
"statuses: status.text = r.sub(r'<a href=\"\\1\" target=\"_blank\" rel=\"nofollow\">\\1</a>', status.text) status.text = s.sub(r'\\1@<a href=\"/user/\\2\" target=\"_blank\"",
"= Group.by_user(account) return render_to_response('group-list.html', {'user':account, 'groups':groups, }) @needs_account('/login') def GroupAddPage(request,account=None): name = request.REQUEST.get('name','')",
"traceback import re import urllib2 def encodeURLs(statuses,account): r = re.compile(r\"(http://[^, ]+[^,. ])\") s",
"is True: time.sleep(2**count) count = count + 1 complete = not person.isUpdating() output['num_statuses']",
"1 complete = not person.isUpdating() output['num_statuses'] = person.statusCount() output['complete'] = complete if person.oldestStatus():",
"account: output['api_calls'] = account.rate_remaining response = HttpResponse() response.write(simplejson.dumps(output)) except: exc_type, exc_value, exc_traceback =",
"tweetCount = 20 loadCount = tweetCount * int(loadCount) if request.REQUEST.get('start'): filters['created_at__gte'] = datetime.strptime(request.REQUEST.get('start'),\"%Y-%m-%d\")",
"import simplejson from twitter_explorer import settings from twitter import collector from datetime import",
"already exists for you. Please try another.'], \"user\": account, \"short_name\":short_name, \"name\":name, \"member_names\":member_names, },",
"= group.latestStatus().status_date() if account: output['api_calls'] = account.rate_remaining response = HttpResponse() response.write(simplejson.dumps(output)) return response",
"person = Person.by_screen_name(screen_name) filters = {} terms=None if request.REQUEST.get('start'): filters['created_at__gte'] = datetime.strptime(request.REQUEST.get('start'),\"%Y-%m-%d\") if",
"temp for status in statuses: status.text = r.sub(r'<a href=\"\\1\" target=\"_blank\" rel=\"nofollow\">\\1</a>', status.text) status.text",
"person.oldestStatus().status_date() if person.latestStatus(): output['latest_date'] = person.latestStatus().status_date() if account: output['api_calls'] = account.rate_remaining response =",
"from twitter import collector from datetime import datetime from django.template.context import RequestContext from",
"try another.'], \"user\": account, \"short_name\":short_name, \"name\":name, \"member_names\":member_names, }, context_instance=RequestContext(request)) people = [] if",
"atleast 1 character long.\") for member in member_names.strip().split(','): person = Person.by_screen_name(member) if not",
"'\\' already exists for you. Please try another.'], \"user\": account, \"short_name\":short_name, \"name\":name, \"member_names\":member_names,",
"group.save() return HttpResponseRedirect('/group') return render_to_response('group-add.html', { 'user': account, },context_instance=RequestContext(request)) @needs_account('/login') def GroupGenAddPage(request,account=None): errors",
"person = Person.by_screen_name(screen_name) if person: tasks.updatePersonTweets(person,account) num_friends = person.following_count else: num_friends = None",
"def PersonPage(request,screen_name,account=None): if account: person = collector.person(screen_name,account) else: person = Person.by_screen_name(screen_name) if person:",
"{} if request.REQUEST.get('start'): filters['created_at__gte'] = datetime.strptime(request.REQUEST.get('start'),\"%Y-%m-%d\") if request.REQUEST.get('end'): filters['created_at__lt'] = datetime.strptime(request.REQUEST.get('end'),\"%Y-%m-%d\") if request.REQUEST.get('q'):",
"= [] if 'POST' == request.method: url = request.REQUEST.get('url','') try: conn = urllib2.urlopen(url)",
"License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing,",
"import Person, Status from twitter_explorer.models import Group from django.http import HttpResponse, HttpResponseRedirect from",
"\"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or",
"\"user\": account, \"short_name\":short_name, \"name\":name, \"member_names\":member_names, }, context_instance=RequestContext(request)) else: group = Group.objects.create(short_name=short_name, user=account, name=name)",
"import RequestContext from twitter_explorer import tasks import time import sys, traceback import re",
"person.statuses(20,0,query=terms,**filters) encodeURLs(statuses, account) return render_to_response('person-tweets.html', {'screen_name':screen_name, 'statuses':statuses}) @wants_account def PersonTweetsAdditional(request,screen_name,loadCount=0,account=None): person = Person.by_screen_name(screen_name)",
"= member_names + member return render_to_response('group-gen-add.html', { 'user':account, 'member_names':member_names}, context_instance=RequestContext(request)) return render_to_response('group-gen-add.html', {",
"{'name':group.name, 'statuses':statuses}) @wants_account def GroupTweetsAdditional(request,short_name,loadCount=0,account=None): group = Group.by_short_name_and_user(short_name, account) filters = {} terms",
"datetime.strptime(request.REQUEST.get('end'),\"%Y-%m-%d\") if request.REQUEST.get('q'): terms = request.REQUEST.get('q').split() statuses = person.statuses(20,0,query=terms,**filters) encodeURLs(statuses, account) return render_to_response('person-tweets.html',",
"tasks.updatePersonTweets(member, account) return render_to_response('group.html',{'group':group, 'user':account}) @wants_account def GroupTweets(request,short_name,account=None): group = Group.by_short_name_and_user(short_name, account) terms",
"return render_to_response('person.html',{'person':person, 'num_friends':num_friends, 'user':account}) @wants_account def PersonTweets(request,screen_name,account=None): person = Person.by_screen_name(screen_name) filters = {}",
"Person.by_screen_name(screen_name) if person: tasks.updatePersonTweets(person,account) num_friends = person.following_count else: num_friends = None return render_to_response('person.html',{'person':person,",
"output['complete'] = complete if group.oldestStatus(): output['oldest_date'] = group.oldestStatus().status_date() if group.latestStatus(): output['latest_date'] = group.latestStatus().status_date()",
"1: errors.append(\"Please ensure the group name is atleast 1 character long.\") for member",
"len(short_name) < 1: errors.append(\"Please ensure the group name is atleast 1 character long.\")",
"and last line:\" return response @wants_account def AboutPage(request,account=None): return render_to_response('about.html', {'user':account}) @needs_account('/login') def",
"import render_to_string from twitter.models import Person, Status from twitter_explorer.models import Group from django.http",
"Please try another.'], \"user\": account, \"short_name\":short_name, \"name\":name, \"member_names\":member_names, }, context_instance=RequestContext(request)) people = []",
"compliance with the License. You may obtain a copy of the License at",
"Person.by_screen_name(screen_name) count = 0 while person.statusCount() is 0 and person.isUpdating() is True: time.sleep(2**count)",
"{ 'url':url, 'errors':errors, 'user':account, }, context_instance=RequestContext(request)) r = re.compile(r\"(twitter.com/[^, /\\\"]+[^,. /\\\"])\") links =",
"def GroupTweetsBackground(request,short_name,account=None): output = {} group = Group.by_short_name_and_user(short_name, account) output['num_statuses'] = group.status_count() complete",
"and limitations under the License. Contributors <NAME> ''' from django.shortcuts import render_to_response from",
"= not person.isUpdating() output['num_statuses'] = person.statusCount() output['complete'] = complete if person.oldestStatus(): output['oldest_date'] =",
"if request.REQUEST.get('end'): filters['created_at__lt'] = datetime.strptime(request.REQUEST.get('end'),\"%Y-%m-%d\") if request.REQUEST.get('q'): terms = request.REQUEST.get('q').split() statuses = person.statuses(tweetCount,loadCount,query=terms,**filters)",
"collector.person(screen_name,account) else: person = Person.by_screen_name(screen_name) if person: tasks.updatePersonTweets(person,account) num_friends = person.following_count else: num_friends",
"print_tb:\" traceback.print_tb(exc_traceback, limit=1, file=sys.stdout) print \"*** print_exception:\" traceback.print_exception(exc_type, exc_value, exc_traceback, limit=2, file=sys.stdout) print",
"def GroupListPage(request,account=None): groups = Group.by_user(account) return render_to_response('group-list.html', {'user':account, 'groups':groups, }) @needs_account('/login') def GroupAddPage(request,account=None):",
"twitter_explorer.models import Group from django.http import HttpResponse, HttpResponseRedirect from auth.decorators import wants_account, needs_account",
"express or implied. See the License for the specific language governing permissions and",
"import urllib2 def encodeURLs(statuses,account): r = re.compile(r\"(http://[^, ]+[^,. ])\") s = re.compile(r'(\\A|\\s)@(\\w+)') if",
"output = {} person = Person.by_screen_name(screen_name) count = 0 while person.statusCount() is 0",
"if not person: person = collector.person(member,account) if person: people.append(person) tasks.updatePersonTweets(person,account) else: errors.append(\"Could not",
"print \"*** print_exception:\" traceback.print_exception(exc_type, exc_value, exc_traceback, limit=2, file=sys.stdout) print \"*** print_exc:\" traceback.print_exc() print",
"str(None) if account: output['api_calls'] = account.rate_remaining response = HttpResponse() response.write(simplejson.dumps(output)) return response def",
"twitter import collector from datetime import datetime from django.template.context import RequestContext from twitter_explorer",
"= group.oldestStatus().status_date() if group.latestStatus(): output['latest_date'] = group.latestStatus().status_date() if account: output['api_calls'] = account.rate_remaining response",
"1 character long.\") for member in member_names.strip().split(','): person = Person.by_screen_name(member) if not person:",
"re.compile(r'(\\A|\\s)@(\\w+)') if isinstance(statuses,Status): temp = [] temp.append(statuses) statuses = temp for status in",
"request.REQUEST.get('end'): filters['created_at__lt'] = datetime.strptime(request.REQUEST.get('end'),\"%Y-%m-%d\") if request.REQUEST.get('q'): terms = request.REQUEST.get('q').split() statuses = person.statuses(tweetCount,loadCount,query=terms,**filters) encodeURLs(statuses,",
"complete = not person.isUpdating() output['num_statuses'] = person.statusCount() output['complete'] = complete if person.oldestStatus(): output['oldest_date']",
"tasks.updatePersonTweets(person,account) else: errors.append(\"Could not find a user named: \" + member) if len(errors)",
"return response @wants_account def AboutPage(request,account=None): return render_to_response('about.html', {'user':account}) @needs_account('/login') def GroupListPage(request,account=None): groups =",
"is atleast 1 character long.\") for member in member_names.strip().split(','): person = Person.by_screen_name(member) if",
"{'user':account, 'groups':groups, }) @needs_account('/login') def GroupAddPage(request,account=None): name = request.REQUEST.get('name','') short_name = name.replace(' ','_').lower()",
"terms = None if request.REQUEST.get('start'): filters['created_at__gte'] = datetime.strptime(request.REQUEST.get('start'),\"%Y-%m-%d\") if request.REQUEST.get('end'): filters['created_at__lt'] = datetime.strptime(request.REQUEST.get('end'),\"%Y-%m-%d\")",
"= complete if person.oldestStatus(): output['oldest_date'] = person.oldestStatus().status_date() if person.latestStatus(): output['latest_date'] = person.latestStatus().status_date() if",
"You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by",
"named: \" + member) if len(errors) > 0: return render_to_response('group-add.html', { \"errors\":errors, \"user\":",
"= person.statuses(tweetCount,loadCount,query=terms,**filters) encodeURLs(statuses, account) return render_to_response('person-tweets-additional.html', {'screen_name':screen_name, 'statuses':statuses}) @wants_account def PersonTweetsBackground(request,screen_name,account=None): try: output",
"name = request.REQUEST.get('name','') short_name = name.replace(' ','_').lower() member_names = request.REQUEST.get('member_names','') auto_gen = request.REQUEST.get('auto_gen',None)",
"import re import urllib2 def encodeURLs(statuses,account): r = re.compile(r\"(http://[^, ]+[^,. ])\") s =",
"person.oldestStatus(): output['oldest_date'] = person.oldestStatus().status_date() if person.latestStatus(): output['latest_date'] = person.latestStatus().status_date() if account: output['api_calls'] =",
"'user':account}) @wants_account def GroupTweets(request,short_name,account=None): group = Group.by_short_name_and_user(short_name, account) terms = None filters =",
"applicable law or agreed to in writing, software distributed under the License is",
"errors = [] if 'POST' == request.method: if auto_gen: return render_to_response('group-add.html', { \"user\":",
"return render_to_response('group-add.html', { \"user\": account, \"member_names\":member_names, }, context_instance=RequestContext(request)) group = Group.by_short_name_and_user(short_name, account) if",
"member_names = member_names + member return render_to_response('group-gen-add.html', { 'user':account, 'member_names':member_names}, context_instance=RequestContext(request)) return render_to_response('group-gen-add.html',",
"GroupGenAddPage(request,account=None): errors = [] if 'POST' == request.method: url = request.REQUEST.get('url','') try: conn",
"}, context_instance=RequestContext(request)) people = [] if len(short_name) < 1: errors.append(\"Please ensure the group",
"member) if len(errors) > 0: return render_to_response('group-add.html', { \"errors\":errors, \"user\": account, \"short_name\":short_name, \"name\":name,",
"PersonTweetsAdditional(request,screen_name,loadCount=0,account=None): person = Person.by_screen_name(screen_name) filters = {} tweetCount = 20 loadCount = tweetCount",
"> 0: return render_to_response('group-add.html', { \"errors\":errors, \"user\": account, \"short_name\":short_name, \"name\":name, \"member_names\":member_names, }, context_instance=RequestContext(request))",
"= [] for link in links: link = link.replace('twitter.com/','') if not link in",
"simplejson from twitter_explorer import settings from twitter import collector from datetime import datetime",
"= Group.by_short_name_and_user(short_name, account) filters = {} terms = None tweetCount = 20 loadCount",
"{} terms = None tweetCount = 20 loadCount = tweetCount * int(loadCount) if",
"link = link.replace('twitter.com/','') if not link in members: person = collector.person(link, account) if",
"request.REQUEST.get('member_names','') auto_gen = request.REQUEST.get('auto_gen',None) errors = [] if 'POST' == request.method: if auto_gen:",
"len(errors) > 0: return render_to_response('group-gen-add.html', { 'url':url, 'errors':errors, 'user':account, }, context_instance=RequestContext(request)) r =",
"rel=\"nofollow\">\\2</a>', status.text) @wants_account def MainPage(request,account=None): return render_to_response('index.html',{'user':account}) @wants_account def PersonPage(request,screen_name,account=None): if account: person",
"if 'POST' == request.method: url = request.REQUEST.get('url','') try: conn = urllib2.urlopen(url) data =",
"{ 'user':account, 'member_names':member_names}, context_instance=RequestContext(request)) return render_to_response('group-gen-add.html', { 'user':account, }, context_instance=RequestContext(request)) @needs_account('/login') def GroupPage(request,short_name,account=None):",
"groups = Group.by_user(account) return render_to_response('group-list.html', {'user':account, 'groups':groups, }) @needs_account('/login') def GroupAddPage(request,account=None): name =",
"governing permissions and limitations under the License. Contributors <NAME> ''' from django.shortcuts import",
"if auto_gen: return render_to_response('group-add.html', { \"user\": account, \"member_names\":member_names, }, context_instance=RequestContext(request)) group = Group.by_short_name_and_user(short_name,",
"account) filters = {} terms = None tweetCount = 20 loadCount = tweetCount",
"django.template.loader import render_to_string from twitter.models import Person, Status from twitter_explorer.models import Group from",
"BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See",
"CHISEL group and contributors Licensed under the Apache License, Version 2.0 (the \"License\");",
"MainPage(request,account=None): return render_to_response('index.html',{'user':account}) @wants_account def PersonPage(request,screen_name,account=None): if account: person = collector.person(screen_name,account) else: person",
"= Person.by_screen_name(screen_name) filters = {} terms=None if request.REQUEST.get('start'): filters['created_at__gte'] = datetime.strptime(request.REQUEST.get('start'),\"%Y-%m-%d\") if request.REQUEST.get('end'):",
"permissions and limitations under the License. Contributors <NAME> ''' from django.shortcuts import render_to_response",
"member_names = request.REQUEST.get('member_names','') auto_gen = request.REQUEST.get('auto_gen',None) errors = [] if 'POST' == request.method:",
"import datetime from django.template.context import RequestContext from twitter_explorer import tasks import time import",
"count = 0 while person.statusCount() is 0 and person.isUpdating() is True: time.sleep(2**count) count",
"request.REQUEST.get('end'): filters['created_at__lt'] = datetime.strptime(request.REQUEST.get('end'),\"%Y-%m-%d\") if request.REQUEST.get('q'): terms = request.REQUEST.get('q').split() statuses = group.statuses(tweetCount,loadCount,query=terms,**filters) encodeURLs(statuses,",
"= request.REQUEST.get('url','') try: conn = urllib2.urlopen(url) data = conn.read() conn.close() except: errors.append('We were",
"output['api_calls'] = account.rate_remaining response = HttpResponse() response.write(simplejson.dumps(output)) except: exc_type, exc_value, exc_traceback = sys.exc_info()",
"next tweet no longer exists</li>' output['next_status'] = str(None) if account: output['api_calls'] = account.rate_remaining",
"None return render_to_response('person.html',{'person':person, 'num_friends':num_friends, 'user':account}) @wants_account def PersonTweets(request,screen_name,account=None): person = Person.by_screen_name(screen_name) filters =",
"== request.method: if auto_gen: return render_to_response('group-add.html', { \"user\": account, \"member_names\":member_names, }, context_instance=RequestContext(request)) group",
"context_instance=RequestContext(request)) else: group = Group.objects.create(short_name=short_name, user=account, name=name) for person in people: group.members.add(person) group.save()",
"rel=\"nofollow\">\\1</a>', status.text) status.text = s.sub(r'\\1@<a href=\"/user/\\2\" target=\"_blank\" rel=\"nofollow\">\\2</a>', status.text) @wants_account def MainPage(request,account=None): return",
"if person.oldestStatus(): output['oldest_date'] = person.oldestStatus().status_date() if person.latestStatus(): output['latest_date'] = person.latestStatus().status_date() if account: output['api_calls']",
"if not status: status = collector.status(status_id,account) if status: encodeURLs(status, account) output['status'] = render_to_string('status.html',",
"traceback.print_exc() print \"*** format_exc, first and last line:\" return response @wants_account def AboutPage(request,account=None):",
"response.write(simplejson.dumps(output)) return response @wants_account def Tweet(request,status_id,account=None): output = {} status = Status.by_id(status_id) if",
"isinstance(statuses,Status): temp = [] temp.append(statuses) statuses = temp for status in statuses: status.text",
"return render_to_response('person-tweets.html', {'screen_name':screen_name, 'statuses':statuses}) @wants_account def PersonTweetsAdditional(request,screen_name,loadCount=0,account=None): person = Person.by_screen_name(screen_name) filters = {}",
"from django.utils import simplejson from twitter_explorer import settings from twitter import collector from",
"first and last line:\" return response @wants_account def AboutPage(request,account=None): return render_to_response('about.html', {'user':account}) @needs_account('/login')",
"if request.REQUEST.get('q'): terms = request.REQUEST.get('q').split() statuses = group.statuses(tweetCount,loadCount,query=terms,**filters) encodeURLs(statuses, account) return render_to_response('group-tweets-additional.html', {'statuses':statuses})",
"= '<li>The next tweet no longer exists</li>' output['next_status'] = str(None) if account: output['api_calls']",
"def GroupGenAddPage(request,account=None): errors = [] if 'POST' == request.method: url = request.REQUEST.get('url','') try:",
"group.status_count() complete = not group.isUpdating() output['complete'] = complete if group.oldestStatus(): output['oldest_date'] = group.oldestStatus().status_date()",
"{ \"user\": account, \"member_names\":member_names, }, context_instance=RequestContext(request)) group = Group.by_short_name_and_user(short_name, account) if group: return",
"[] if len(short_name) < 1: errors.append(\"Please ensure the group name is atleast 1",
"statuses = person.statuses(tweetCount,loadCount,query=terms,**filters) encodeURLs(statuses, account) return render_to_response('person-tweets-additional.html', {'screen_name':screen_name, 'statuses':statuses}) @wants_account def PersonTweetsBackground(request,screen_name,account=None): try:",
"@wants_account def GroupTweetsAdditional(request,short_name,loadCount=0,account=None): group = Group.by_short_name_and_user(short_name, account) filters = {} terms = None",
"wants_account, needs_account from django.utils import simplejson from twitter_explorer import settings from twitter import",
"\"errors\":['A group by the short_name \\'' + short_name + '\\' already exists for",
"= {} terms=None if request.REQUEST.get('start'): filters['created_at__gte'] = datetime.strptime(request.REQUEST.get('start'),\"%Y-%m-%d\") if request.REQUEST.get('end'): filters['created_at__lt'] = datetime.strptime(request.REQUEST.get('end'),\"%Y-%m-%d\")",
"else: errors.append(\"Could not find a user named: \" + member) if len(errors) >",
"with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0",
"request.REQUEST.get('q'): terms = request.REQUEST.get('q').split() statuses = group.statuses(20,0,query=terms,**filters) encodeURLs(statuses, account) return render_to_response('group-tweets.html', {'name':group.name, 'statuses':statuses})",
"output['complete'] = complete if person.oldestStatus(): output['oldest_date'] = person.oldestStatus().status_date() if person.latestStatus(): output['latest_date'] = person.latestStatus().status_date()",
"at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software",
"'member_names':member_names}, context_instance=RequestContext(request)) return render_to_response('group-gen-add.html', { 'user':account, }, context_instance=RequestContext(request)) @needs_account('/login') def GroupPage(request,short_name,account=None): group =",
"datetime.strptime(request.REQUEST.get('end'),\"%Y-%m-%d\") if request.REQUEST.get('q'): terms = request.REQUEST.get('q').split() statuses = group.statuses(tweetCount,loadCount,query=terms,**filters) encodeURLs(statuses, account) return render_to_response('group-tweets-additional.html',",
"{ \"errors\":errors, \"user\": account, \"short_name\":short_name, \"name\":name, \"member_names\":member_names, }, context_instance=RequestContext(request)) else: group = Group.objects.create(short_name=short_name,",
"'statuses':statuses}) @wants_account def PersonTweetsBackground(request,screen_name,account=None): try: output = {} person = Person.by_screen_name(screen_name) count =",
"= group.status_count() complete = not group.isUpdating() output['complete'] = complete if group.oldestStatus(): output['oldest_date'] =",
"specific language governing permissions and limitations under the License. Contributors <NAME> ''' from",
"'num_friends':num_friends, 'user':account}) @wants_account def PersonTweets(request,screen_name,account=None): person = Person.by_screen_name(screen_name) filters = {} terms=None if",
"= group.statuses(20,0,query=terms,**filters) encodeURLs(statuses, account) return render_to_response('group-tweets.html', {'name':group.name, 'statuses':statuses}) @wants_account def GroupTweetsAdditional(request,short_name,loadCount=0,account=None): group ="
] |
[
"ret = p.poll() if ret is not None: processes.remove(p) spawncount = count -",
"for p in list(processes): ret = p.poll() if ret is not None: processes.remove(p)",
"= list() # In[ ]: def __tick_list(processes, script, count): for p in list(processes):",
"list(processes): ret = p.poll() if ret is not None: processes.remove(p) spawncount = count",
"while True: __tick_list(dht, DHT, crawlers['dht']) __tick_list(meta, META, crawlers['metadata']) __tick_list(geoip, GEOIP, crawlers['geoip']) time.sleep(crawlers['polltime']) gc.collect()",
"= json.load(f) crawlers = config['crawlers'] while True: __tick_list(dht, DHT, crawlers['dht']) __tick_list(meta, META, crawlers['metadata'])",
"script, count): for p in list(processes): ret = p.poll() if ret is not",
"]: import gc import sys import json import time import signal import subprocess",
"crawlers['dht']) __tick_list(meta, META, crawlers['metadata']) __tick_list(geoip, GEOIP, crawlers['geoip']) time.sleep(crawlers['polltime']) gc.collect() return 1 # In[",
"def __kill_list(processes): for p in processes: p.terminate() for p in processes: p.wait() #",
"import signal import subprocess # In[ ]: CONFIG = '/mnt/data/script/config.json' DHT = '/mnt/data/script/dht_crawl.py'",
"__kill_list(meta) __kill_list(geoip) sys.exit(0) # In[ ]: def main(): signal.signal(signal.SIGTERM, __term_handler) with open(CONFIG, 'r')",
"if ret is not None: processes.remove(p) spawncount = count - len(processes) for i",
"# coding: utf-8 # In[ ]: import gc import sys import json import",
"import subprocess # In[ ]: CONFIG = '/mnt/data/script/config.json' DHT = '/mnt/data/script/dht_crawl.py' META =",
"is not None: processes.remove(p) spawncount = count - len(processes) for i in range(0,",
"spawncount = count - len(processes) for i in range(0, spawncount): p = subprocess.Popen([sys.executable,",
"i in range(0, spawncount): p = subprocess.Popen([sys.executable, script]) processes.append(p) # In[ ]: def",
"crawlers = config['crawlers'] while True: __tick_list(dht, DHT, crawlers['dht']) __tick_list(meta, META, crawlers['metadata']) __tick_list(geoip, GEOIP,",
"for p in processes: p.terminate() for p in processes: p.wait() # In[ ]:",
"count - len(processes) for i in range(0, spawncount): p = subprocess.Popen([sys.executable, script]) processes.append(p)",
"f: config = json.load(f) crawlers = config['crawlers'] while True: __tick_list(dht, DHT, crawlers['dht']) __tick_list(meta,",
"True: __tick_list(dht, DHT, crawlers['dht']) __tick_list(meta, META, crawlers['metadata']) __tick_list(geoip, GEOIP, crawlers['geoip']) time.sleep(crawlers['polltime']) gc.collect() return",
"in processes: p.terminate() for p in processes: p.wait() # In[ ]: def __term_handler(signum,",
"In[ ]: import gc import sys import json import time import signal import",
"sys.exit(0) # In[ ]: def main(): signal.signal(signal.SIGTERM, __term_handler) with open(CONFIG, 'r') as f:",
"crawlers['metadata']) __tick_list(geoip, GEOIP, crawlers['geoip']) time.sleep(crawlers['polltime']) gc.collect() return 1 # In[ ]: if __name__",
"]: CONFIG = '/mnt/data/script/config.json' DHT = '/mnt/data/script/dht_crawl.py' META = '/mnt/data/script/dht_metadata.py' GEOIP = '/mnt/data/script/dht_geoloc.py'",
"as f: config = json.load(f) crawlers = config['crawlers'] while True: __tick_list(dht, DHT, crawlers['dht'])",
"main(): signal.signal(signal.SIGTERM, __term_handler) with open(CONFIG, 'r') as f: config = json.load(f) crawlers =",
"META = '/mnt/data/script/dht_metadata.py' GEOIP = '/mnt/data/script/dht_geoloc.py' # In[ ]: dht = list() meta",
"__tick_list(meta, META, crawlers['metadata']) __tick_list(geoip, GEOIP, crawlers['geoip']) time.sleep(crawlers['polltime']) gc.collect() return 1 # In[ ]:",
"__kill_list(dht) __kill_list(meta) __kill_list(geoip) sys.exit(0) # In[ ]: def main(): signal.signal(signal.SIGTERM, __term_handler) with open(CONFIG,",
"config = json.load(f) crawlers = config['crawlers'] while True: __tick_list(dht, DHT, crawlers['dht']) __tick_list(meta, META,",
"= config['crawlers'] while True: __tick_list(dht, DHT, crawlers['dht']) __tick_list(meta, META, crawlers['metadata']) __tick_list(geoip, GEOIP, crawlers['geoip'])",
"None: processes.remove(p) spawncount = count - len(processes) for i in range(0, spawncount): p",
"= list() geoip = list() # In[ ]: def __tick_list(processes, script, count): for",
"count): for p in list(processes): ret = p.poll() if ret is not None:",
"gc import sys import json import time import signal import subprocess # In[",
"= '/mnt/data/script/dht_geoloc.py' # In[ ]: dht = list() meta = list() geoip =",
"CONFIG = '/mnt/data/script/config.json' DHT = '/mnt/data/script/dht_crawl.py' META = '/mnt/data/script/dht_metadata.py' GEOIP = '/mnt/data/script/dht_geoloc.py' #",
"In[ ]: def __tick_list(processes, script, count): for p in list(processes): ret = p.poll()",
"In[ ]: def __kill_list(processes): for p in processes: p.terminate() for p in processes:",
"list() # In[ ]: def __tick_list(processes, script, count): for p in list(processes): ret",
"p.wait() # In[ ]: def __term_handler(signum, frame): __kill_list(dht) __kill_list(meta) __kill_list(geoip) sys.exit(0) # In[",
"processes.append(p) # In[ ]: def __kill_list(processes): for p in processes: p.terminate() for p",
"for p in processes: p.wait() # In[ ]: def __term_handler(signum, frame): __kill_list(dht) __kill_list(meta)",
"# In[ ]: import gc import sys import json import time import signal",
"= subprocess.Popen([sys.executable, script]) processes.append(p) # In[ ]: def __kill_list(processes): for p in processes:",
"in list(processes): ret = p.poll() if ret is not None: processes.remove(p) spawncount =",
"__term_handler(signum, frame): __kill_list(dht) __kill_list(meta) __kill_list(geoip) sys.exit(0) # In[ ]: def main(): signal.signal(signal.SIGTERM, __term_handler)",
"DHT = '/mnt/data/script/dht_crawl.py' META = '/mnt/data/script/dht_metadata.py' GEOIP = '/mnt/data/script/dht_geoloc.py' # In[ ]: dht",
"<filename>share/dht/script/run.py #!/usr/bin/env python # coding: utf-8 # In[ ]: import gc import sys",
"__tick_list(geoip, GEOIP, crawlers['geoip']) time.sleep(crawlers['polltime']) gc.collect() return 1 # In[ ]: if __name__ ==",
"- len(processes) for i in range(0, spawncount): p = subprocess.Popen([sys.executable, script]) processes.append(p) #",
"in processes: p.wait() # In[ ]: def __term_handler(signum, frame): __kill_list(dht) __kill_list(meta) __kill_list(geoip) sys.exit(0)",
"crawlers['geoip']) time.sleep(crawlers['polltime']) gc.collect() return 1 # In[ ]: if __name__ == '__main__': sys.exit(main())",
"processes: p.terminate() for p in processes: p.wait() # In[ ]: def __term_handler(signum, frame):",
"# In[ ]: def __term_handler(signum, frame): __kill_list(dht) __kill_list(meta) __kill_list(geoip) sys.exit(0) # In[ ]:",
"In[ ]: def __term_handler(signum, frame): __kill_list(dht) __kill_list(meta) __kill_list(geoip) sys.exit(0) # In[ ]: def",
"p in list(processes): ret = p.poll() if ret is not None: processes.remove(p) spawncount",
"len(processes) for i in range(0, spawncount): p = subprocess.Popen([sys.executable, script]) processes.append(p) # In[",
"sys import json import time import signal import subprocess # In[ ]: CONFIG",
"json.load(f) crawlers = config['crawlers'] while True: __tick_list(dht, DHT, crawlers['dht']) __tick_list(meta, META, crawlers['metadata']) __tick_list(geoip,",
"__tick_list(dht, DHT, crawlers['dht']) __tick_list(meta, META, crawlers['metadata']) __tick_list(geoip, GEOIP, crawlers['geoip']) time.sleep(crawlers['polltime']) gc.collect() return 1",
"In[ ]: CONFIG = '/mnt/data/script/config.json' DHT = '/mnt/data/script/dht_crawl.py' META = '/mnt/data/script/dht_metadata.py' GEOIP =",
"time import signal import subprocess # In[ ]: CONFIG = '/mnt/data/script/config.json' DHT =",
"range(0, spawncount): p = subprocess.Popen([sys.executable, script]) processes.append(p) # In[ ]: def __kill_list(processes): for",
"subprocess.Popen([sys.executable, script]) processes.append(p) # In[ ]: def __kill_list(processes): for p in processes: p.terminate()",
"ret is not None: processes.remove(p) spawncount = count - len(processes) for i in",
"signal import subprocess # In[ ]: CONFIG = '/mnt/data/script/config.json' DHT = '/mnt/data/script/dht_crawl.py' META",
"'/mnt/data/script/dht_crawl.py' META = '/mnt/data/script/dht_metadata.py' GEOIP = '/mnt/data/script/dht_geoloc.py' # In[ ]: dht = list()",
"]: def main(): signal.signal(signal.SIGTERM, __term_handler) with open(CONFIG, 'r') as f: config = json.load(f)",
"__term_handler) with open(CONFIG, 'r') as f: config = json.load(f) crawlers = config['crawlers'] while",
"]: def __term_handler(signum, frame): __kill_list(dht) __kill_list(meta) __kill_list(geoip) sys.exit(0) # In[ ]: def main():",
"script]) processes.append(p) # In[ ]: def __kill_list(processes): for p in processes: p.terminate() for",
"= '/mnt/data/script/config.json' DHT = '/mnt/data/script/dht_crawl.py' META = '/mnt/data/script/dht_metadata.py' GEOIP = '/mnt/data/script/dht_geoloc.py' # In[",
"in range(0, spawncount): p = subprocess.Popen([sys.executable, script]) processes.append(p) # In[ ]: def __kill_list(processes):",
"spawncount): p = subprocess.Popen([sys.executable, script]) processes.append(p) # In[ ]: def __kill_list(processes): for p",
"= '/mnt/data/script/dht_metadata.py' GEOIP = '/mnt/data/script/dht_geoloc.py' # In[ ]: dht = list() meta =",
"__kill_list(processes): for p in processes: p.terminate() for p in processes: p.wait() # In[",
"'/mnt/data/script/config.json' DHT = '/mnt/data/script/dht_crawl.py' META = '/mnt/data/script/dht_metadata.py' GEOIP = '/mnt/data/script/dht_geoloc.py' # In[ ]:",
"__tick_list(processes, script, count): for p in list(processes): ret = p.poll() if ret is",
"python # coding: utf-8 # In[ ]: import gc import sys import json",
"= count - len(processes) for i in range(0, spawncount): p = subprocess.Popen([sys.executable, script])",
"def __term_handler(signum, frame): __kill_list(dht) __kill_list(meta) __kill_list(geoip) sys.exit(0) # In[ ]: def main(): signal.signal(signal.SIGTERM,",
"geoip = list() # In[ ]: def __tick_list(processes, script, count): for p in",
"config['crawlers'] while True: __tick_list(dht, DHT, crawlers['dht']) __tick_list(meta, META, crawlers['metadata']) __tick_list(geoip, GEOIP, crawlers['geoip']) time.sleep(crawlers['polltime'])",
"list() meta = list() geoip = list() # In[ ]: def __tick_list(processes, script,",
"not None: processes.remove(p) spawncount = count - len(processes) for i in range(0, spawncount):",
"p in processes: p.wait() # In[ ]: def __term_handler(signum, frame): __kill_list(dht) __kill_list(meta) __kill_list(geoip)",
"processes: p.wait() # In[ ]: def __term_handler(signum, frame): __kill_list(dht) __kill_list(meta) __kill_list(geoip) sys.exit(0) #",
"dht = list() meta = list() geoip = list() # In[ ]: def",
"= list() meta = list() geoip = list() # In[ ]: def __tick_list(processes,",
"# In[ ]: def __kill_list(processes): for p in processes: p.terminate() for p in",
"# In[ ]: def main(): signal.signal(signal.SIGTERM, __term_handler) with open(CONFIG, 'r') as f: config",
"]: dht = list() meta = list() geoip = list() # In[ ]:",
"= p.poll() if ret is not None: processes.remove(p) spawncount = count - len(processes)",
"for i in range(0, spawncount): p = subprocess.Popen([sys.executable, script]) processes.append(p) # In[ ]:",
"processes.remove(p) spawncount = count - len(processes) for i in range(0, spawncount): p =",
"]: def __tick_list(processes, script, count): for p in list(processes): ret = p.poll() if",
"#!/usr/bin/env python # coding: utf-8 # In[ ]: import gc import sys import",
"open(CONFIG, 'r') as f: config = json.load(f) crawlers = config['crawlers'] while True: __tick_list(dht,",
"__kill_list(geoip) sys.exit(0) # In[ ]: def main(): signal.signal(signal.SIGTERM, __term_handler) with open(CONFIG, 'r') as",
"DHT, crawlers['dht']) __tick_list(meta, META, crawlers['metadata']) __tick_list(geoip, GEOIP, crawlers['geoip']) time.sleep(crawlers['polltime']) gc.collect() return 1 #",
"meta = list() geoip = list() # In[ ]: def __tick_list(processes, script, count):",
"META, crawlers['metadata']) __tick_list(geoip, GEOIP, crawlers['geoip']) time.sleep(crawlers['polltime']) gc.collect() return 1 # In[ ]: if",
"]: def __kill_list(processes): for p in processes: p.terminate() for p in processes: p.wait()",
"# In[ ]: CONFIG = '/mnt/data/script/config.json' DHT = '/mnt/data/script/dht_crawl.py' META = '/mnt/data/script/dht_metadata.py' GEOIP",
"In[ ]: dht = list() meta = list() geoip = list() # In[",
"import sys import json import time import signal import subprocess # In[ ]:",
"def main(): signal.signal(signal.SIGTERM, __term_handler) with open(CONFIG, 'r') as f: config = json.load(f) crawlers",
"p.terminate() for p in processes: p.wait() # In[ ]: def __term_handler(signum, frame): __kill_list(dht)",
"coding: utf-8 # In[ ]: import gc import sys import json import time",
"signal.signal(signal.SIGTERM, __term_handler) with open(CONFIG, 'r') as f: config = json.load(f) crawlers = config['crawlers']",
"utf-8 # In[ ]: import gc import sys import json import time import",
"import time import signal import subprocess # In[ ]: CONFIG = '/mnt/data/script/config.json' DHT",
"GEOIP = '/mnt/data/script/dht_geoloc.py' # In[ ]: dht = list() meta = list() geoip",
"with open(CONFIG, 'r') as f: config = json.load(f) crawlers = config['crawlers'] while True:",
"import gc import sys import json import time import signal import subprocess #",
"p = subprocess.Popen([sys.executable, script]) processes.append(p) # In[ ]: def __kill_list(processes): for p in",
"json import time import signal import subprocess # In[ ]: CONFIG = '/mnt/data/script/config.json'",
"In[ ]: def main(): signal.signal(signal.SIGTERM, __term_handler) with open(CONFIG, 'r') as f: config =",
"'/mnt/data/script/dht_metadata.py' GEOIP = '/mnt/data/script/dht_geoloc.py' # In[ ]: dht = list() meta = list()",
"# In[ ]: dht = list() meta = list() geoip = list() #",
"'r') as f: config = json.load(f) crawlers = config['crawlers'] while True: __tick_list(dht, DHT,",
"def __tick_list(processes, script, count): for p in list(processes): ret = p.poll() if ret",
"'/mnt/data/script/dht_geoloc.py' # In[ ]: dht = list() meta = list() geoip = list()",
"frame): __kill_list(dht) __kill_list(meta) __kill_list(geoip) sys.exit(0) # In[ ]: def main(): signal.signal(signal.SIGTERM, __term_handler) with",
"subprocess # In[ ]: CONFIG = '/mnt/data/script/config.json' DHT = '/mnt/data/script/dht_crawl.py' META = '/mnt/data/script/dht_metadata.py'",
"GEOIP, crawlers['geoip']) time.sleep(crawlers['polltime']) gc.collect() return 1 # In[ ]: if __name__ == '__main__':",
"import json import time import signal import subprocess # In[ ]: CONFIG =",
"list() geoip = list() # In[ ]: def __tick_list(processes, script, count): for p",
"p.poll() if ret is not None: processes.remove(p) spawncount = count - len(processes) for",
"# In[ ]: def __tick_list(processes, script, count): for p in list(processes): ret =",
"= '/mnt/data/script/dht_crawl.py' META = '/mnt/data/script/dht_metadata.py' GEOIP = '/mnt/data/script/dht_geoloc.py' # In[ ]: dht =",
"p in processes: p.terminate() for p in processes: p.wait() # In[ ]: def"
] |
[
"check(lst, l): for i in range(l): if lst[0]<=lst[i]: sort = 1 else: sort",
"0 break print(sort) T = int(input()) for i in range(T): n = int(input())",
"lst[0]<=lst[i]: sort = 1 else: sort = 0 break print(sort) T = int(input())",
"sort = 1 else: sort = 0 break print(sort) T = int(input()) for",
"T = int(input()) for i in range(T): n = int(input()) arr = list(map(int,",
"l): for i in range(l): if lst[0]<=lst[i]: sort = 1 else: sort =",
"else: sort = 0 break print(sort) T = int(input()) for i in range(T):",
"int(input()) for i in range(T): n = int(input()) arr = list(map(int, input().split())) check(arr,",
"i in range(l): if lst[0]<=lst[i]: sort = 1 else: sort = 0 break",
"in range(l): if lst[0]<=lst[i]: sort = 1 else: sort = 0 break print(sort)",
"= 0 break print(sort) T = int(input()) for i in range(T): n =",
"print(sort) T = int(input()) for i in range(T): n = int(input()) arr =",
"= 1 else: sort = 0 break print(sort) T = int(input()) for i",
"for i in range(T): n = int(input()) arr = list(map(int, input().split())) check(arr, n)",
"break print(sort) T = int(input()) for i in range(T): n = int(input()) arr",
"def check(lst, l): for i in range(l): if lst[0]<=lst[i]: sort = 1 else:",
"range(l): if lst[0]<=lst[i]: sort = 1 else: sort = 0 break print(sort) T",
"1 else: sort = 0 break print(sort) T = int(input()) for i in",
"= int(input()) for i in range(T): n = int(input()) arr = list(map(int, input().split()))",
"for i in range(l): if lst[0]<=lst[i]: sort = 1 else: sort = 0",
"if lst[0]<=lst[i]: sort = 1 else: sort = 0 break print(sort) T =",
"sort = 0 break print(sort) T = int(input()) for i in range(T): n"
] |
[
">= 60: print('Liquidating positions.') api.close_all_positions() sold_today = True else: sold_today = False if",
"for _, row in ratings.iterrows(): # \"Buy\" our shares on that day and",
"calendar.date) print('Portfolio value on {}: {:0.2f} $'.format(calendar.date.strftime( '%Y-%m-%d'), portfolio_amount) ) if cal_index ==",
"> 0: api.submit_order( symbol=symbol, qty=shares_to_buy[symbol], side='buy', type='market', time_in_force='day' ) print('Positions bought.') bought_today =",
"quality. return # Then, compare it to the change in volume since yesterday.",
"consider formatted_time = None if algo_time is not None: # Convert the time",
"parameters start_value = float(sys.argv[2]) testing_days = int(sys.argv[3]) portfolio_value = backtest(api, testing_days, start_value) portfolio_change",
"compatable with the Alpaca API. start_time = (algo_time.date() - timedelta(days=window_size)).strftime( api_time_format) formatted_time =",
"= data.iloc[-1].close if price <= max_stock_price and price >= min_stock_price: price_change = price",
"from enum import Enum import pytz from datetime import datetime, timedelta from pytz",
"def get_historic_data_base(symbols, data_type: DataType, start, end, timeframe: TimeFrame = None): major = sys.version_info.major",
"positions before buying new ones. time_after_open = pd.Timestamp( clock.timestamp.time().isoformat()) - pd.Timestamp( clock.next_open.time().isoformat()) #",
"True else: sold_today = False if clock.timestamp > next_market_time: next_market_time = clock.next_open bought_today",
"a command; either \"run\" or \"backtest ' '<cash balance> <number of days to",
"= (algo_time.date() - timedelta(days=window_size)).strftime( api_time_format) formatted_time = algo_time.date().strftime(api_time_format) end = pd.Timestamp(formatted_time) else: end",
"end, timeframe.value] if timeframe else \\ [symbol, start, end] tasks.append(get_data_method(data_type)(*args)) if minor >=",
"ratings.sort_values('rating', ascending=False) ratings = ratings.reset_index(drop=True) return ratings[:stocks_to_hold] def get_shares_to_buy(ratings_df, portfolio): total_rating = ratings_df['rating'].sum()",
"Wait to buy time_until_close = clock.next_close - clock.timestamp # We'll buy our shares",
"for symbol in symbols[i:i + step_size]: args = [symbol, start, end, timeframe.value] if",
"= \"Trades\" Quotes = \"Quotes\" def get_data_method(data_type: DataType): if data_type == DataType.Bars: return",
"start, end, timeframe.value] if timeframe else \\ [symbol, start, end] tasks.append(get_data_method(data_type)(*args)) if minor",
"`end` will be used. We use this for live trading. def get_ratings(api, algo_time,",
"the stock might be low quality. return # Then, compare it to the",
"sys.argv[1] == 'backtest': # Run a backtesting session using the provided parameters start_value",
"< 3 or minor < 6: raise Exception('asyncio is not support in your",
"portfolio_cash) for symbol in shares_to_buy: if shares_to_buy[symbol] > 0: api.submit_order( symbol=symbol, qty=shares_to_buy[symbol], side='buy',",
"api.list_assets(status=\"active\") assets = [asset for asset in assets if asset.tradable] symbols = [s.symbol",
"start, end, window_size, index))) done = False while not done: done = True",
"the stock is within our target range, rate it. price = data.iloc[-1].close if",
"backtesting to find out how much our portfolio would have been # worth",
"{} for _, row in ratings_df.iterrows(): shares[row['symbol']] = int( row['rating'] / total_rating *",
"= True for f in futures: if not f.done(): done = False break",
"latest_bar = data.iloc[-1].name.to_pydatetime().astimezone( timezone('EST')) if algo_time: gap_from_present = algo_time - latest_bar if gap_from_present.days",
"so we've obviously not done anything today. pass clock = api.get_clock() next_market_time =",
"= ratings.append(res, ignore_index=True) ratings = ratings.sort_values('rating', ascending=False) ratings = ratings.reset_index(drop=True) return ratings[:stocks_to_hold] def",
"results: if isinstance(response, Exception): print(f\"Got an error: {response}\") elif not len(response[1]): bad_requests +=",
"async def get_historic_bars(symbols, start, end, timeframe: TimeFrame): return await get_historic_data_base(symbols, DataType.Bars, start, end,",
"version of a timestamp compatible with the Alpaca API. def api_format(dt): return dt.strftime(api_time_format)",
"API will let us skip over market holidays and handle early # market",
"rating > 0: return { 'symbol': symbol, 'rating': price_change / data.iloc[ 0].close *",
"from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor import pandas as pd import statistics import sys",
"our shares a couple minutes before market close. if time_until_close.seconds <= 120: print('Buying",
"get_data_method(data_type: DataType): if data_type == DataType.Bars: return rest.get_bars_async elif data_type == DataType.Trades: return",
"1 if num_tries <= 0: print(\"Error trying to get data\") sys.exit(-1) for symbol",
"test>\".') else: if sys.argv[1] == 'backtest': # Run a backtesting session using the",
"results = [] for i in range(0, len(symbols), step_size): tasks = [] for",
"minor >= 8: results.extend( await asyncio.gather(*tasks, return_exceptions=True)) else: results.extend(await gather_with_concurrency(500, *tasks)) bad_requests =",
"portfolio_amount -= cost cal_index += 1 # Print market (S&P500) return for the",
"time_after_open.seconds >= 60: print('Liquidating positions.') api.close_all_positions() sold_today = True else: sold_today = False",
"= ratings_df['rating'].sum() shares = {} for _, row in ratings_df.iterrows(): shares[row['symbol']] = int(",
"in datasets: futures.append(executor.submit(_process_dataset, *( dataset, algo_time, start, end, window_size, index))) done = False",
"asset.tradable] symbols = [s.symbol for s in assets] snapshot = api.get_snapshots(symbols) symbols =",
"if sold_today: # Wait to buy time_until_close = clock.next_close - clock.timestamp # We'll",
"case the script is restarted during market hours. bought_today = False sold_today =",
"== 'backtest': # Run a backtesting session using the provided parameters start_value =",
"max_stock_price and price >= min_stock_price: price_change = price - data.iloc[0].close # Calculate standard",
"# Then, compare it to the change in volume since yesterday. volume_change =",
"restarted # right before the market closes. sold_today = True break else: sold_today",
"of {len(results)} {data_type}, and {bad_requests} \" f\"empty responses.\") return results async def get_historic_bars(symbols,",
"= api.get_snapshots(symbols) symbols = list(filter(lambda x: max_stock_price >= snapshot[ x].latest_trade.p >= min_stock_price if",
"def backtest(api, days_to_test, portfolio_amount): # This is the collection of stocks that will",
"= ProcessPoolExecutor(1) class DataType(str, Enum): Bars = \"Bars\" Trades = \"Trades\" Quotes =",
"if major < 3 or minor < 6: raise Exception('asyncio is not support",
"TZ.) api_time_format = '%Y-%m-%dT%H:%M:%S.%f-04:00' loop = asyncio.get_event_loop() if sys.argv[1] == 'backtest': # so",
"stocks based on the volume's deviation from the previous 5 days and #",
"step_size = 1000 results = [] for i in range(0, len(symbols), step_size): tasks",
"clock.timestamp.time().isoformat()) - pd.Timestamp( clock.next_open.time().isoformat()) # We'll sell our shares just a minute after",
"+ step_size]: args = [symbol, start, end, timeframe.value] if timeframe else \\ [symbol,",
"= False while True: # We'll wait until the market's open to do",
"used for backtesting. assets = api.list_assets() now = datetime.now(timezone('EST')) beginning = now -",
"data. latest_bar = data.iloc[-1].name.to_pydatetime().astimezone( timezone('EST')) if algo_time: gap_from_present = algo_time - latest_bar if",
"asyncio from enum import Enum import pytz from datetime import datetime, timedelta from",
"the ratings for a particular day ratings = \\ get_ratings(api, timezone('EST').localize(calendar.date), datasets=data) shares",
"most recent data. latest_bar = data.iloc[-1].name.to_pydatetime().astimezone( timezone('EST')) if algo_time: gap_from_present = algo_time -",
"from the previous 5 days and # momentum. Returns a dataframe mapping stock",
"return rest.get_quotes_async else: raise Exception(f\"Unsupoported data type: {data_type}\") async def get_historic_data_base(symbols, data_type: DataType,",
"in results: if isinstance(response, Exception): print(f\"Got an error: {response}\") elif not len(response[1]): bad_requests",
"Returns a dataframe mapping stock symbols to ratings and prices. # Note: If",
"* volume_factor, 'price': price } # Rate stocks based on the volume's deviation",
"symbol in shares_bought: df = barset[symbol] if not df.empty: total_value += shares_bought[symbol] *",
"volume_change / volume_stdev # Rating = Number of volume standard deviations * momentum.",
"1 print(f\"Total of {len(results)} {data_type}, and {bad_requests} \" f\"empty responses.\") return results async",
"= [symbol, start, end, timeframe.value] if timeframe else \\ [symbol, start, end] tasks.append(get_data_method(data_type)(*args))",
"this format. (-04:00 represents the market's TZ.) api_time_format = '%Y-%m-%dT%H:%M:%S.%f-04:00' loop = asyncio.get_event_loop()",
"low quality. return # Then, compare it to the change in volume since",
"day. orders = api.list_orders( after=api_format(datetime.today() - timedelta(days=1)), limit=400, status='all' ) for order in",
"= pytz.timezone(\"America/New_York\").localize(pd.Timestamp('now')) start = end - timedelta( days=window_size + 10) # make sure",
"= {} for _, row in ratings_df.iterrows(): shares[row['symbol']] = int( row['rating'] / total_rating",
"portfolio_amount) ) if cal_index == len(calendars) - 2: # -2 because we don't",
"positions...') portfolio_cash = float(api.get_account().cash) ratings = get_ratings( api, None ) shares_to_buy = get_shares_to_buy(ratings,",
"after=api_format(datetime.today() - timedelta(days=1)), limit=400, status='all' ) for order in orders: if order.side ==",
"= float(sys.argv[2]) testing_days = int(sys.argv[3]) portfolio_value = backtest(api, testing_days, start_value) portfolio_change = (portfolio_value",
"True except: # We don't have any orders, so we've obviously not done",
"= loop.run_until_complete( get_historic_bars( symbols[:], pytz.timezone(\"America/New_York\").localize( calendars[0].date - timedelta(days=10)).isoformat(), pytz.timezone(\"America/New_York\").localize( calendars[-1].date).isoformat(), TimeFrame.Day)) for calendar",
"= datetime.now(timezone('EST')) beginning = now - timedelta(days=days_to_test) # The calendars API will let",
"# market closures during our backtesting window. calendars = api.get_calendar( start=beginning.strftime(\"%Y-%m-%d\"), end=now.strftime(\"%Y-%m-%d\") )",
"clock.next_open bought_today = False sold_today = False print(\"Market Open\") print_waiting = False if",
"previous 5 days and # momentum. Returns a dataframe mapping stock symbols to",
"Exception(f\"Unsupoported data type: {data_type}\") async def get_historic_data_base(symbols, data_type: DataType, start, end, timeframe: TimeFrame",
"with the Alpaca API. def api_format(dt): return dt.strftime(api_time_format) def backtest(api, days_to_test, portfolio_amount): #",
"cal_index += 1 # Print market (S&P500) return for the time period results",
"def _process_dataset(dataset, algo_time, start, end, window_size, index): if isinstance(dataset, Exception): return symbol =",
"worth the day after we bought it. def get_value_of_assets(api, shares_bought, on_date): if len(shares_bought.keys())",
"a timestamp compatible with the Alpaca API. def api_format(dt): return dt.strftime(api_time_format) def backtest(api,",
"assets = [asset for asset in assets if asset.tradable] symbols = [s.symbol for",
"(portfolio_value - start_value) / start_value print('Portfolio change: {:.4f}%'.format(portfolio_change * 100)) elif sys.argv[1] ==",
"False sold_today = False print(\"Market Open\") print_waiting = False if not print_waiting: print_waiting",
"i in range(0, len(symbols), step_size): tasks = [] for symbol in symbols[i:i +",
"cal_index = 0 assets = api.list_assets(status=\"active\") assets = [asset for asset in assets",
"clock = api.get_clock() next_market_time = clock.next_open bought_today = False sold_today = False print_waiting",
"= False if not print_waiting: print_waiting = True print(\"Waiting for next market day...\")",
"= False sold_today = False print(\"Market Open\") print_waiting = False if not print_waiting:",
"pd.Timestamp( clock.timestamp.time().isoformat()) - pd.Timestamp( clock.next_open.time().isoformat()) # We'll sell our shares just a minute",
"so, we don't want to do it again. # Useful in case the",
"now - timedelta(days=days_to_test) # The calendars API will let us skip over market",
"change: {:.4f}%'.format(portfolio_change * 100)) elif sys.argv[1] == 'run': run_live(api) else: print('Error: Unrecognized command",
"data_type == DataType.Quotes: return rest.get_quotes_async else: raise Exception(f\"Unsupoported data type: {data_type}\") async def",
"your python version') msg = f\"Getting {data_type} data for {len(symbols)} symbols\" msg +=",
"portfolio): total_rating = ratings_df['rating'].sum() shares = {} for _, row in ratings_df.iterrows(): shares[row['symbol']]",
"[s.symbol for s in assets] snapshot = api.get_snapshots(symbols) symbols = list(filter(lambda x: max_stock_price",
"do it again. # Useful in case the script is restarted during market",
"our target range, rate it. price = data.iloc[-1].close if price <= max_stock_price and",
"[] for i in range(0, len(symbols), step_size): tasks = [] for symbol in",
"the market's TZ.) api_time_format = '%Y-%m-%dT%H:%M:%S.%f-04:00' loop = asyncio.get_event_loop() if sys.argv[1] == 'backtest':",
"pytz.timezone(\"America/New_York\").localize( on_date).isoformat(), pytz.timezone(\"America/New_York\").localize( on_date).isoformat(), TimeFrame.Day)) barset = dict(barset) break except Exception as e:",
"f\"empty responses.\") return results async def get_historic_bars(symbols, start, end, timeframe: TimeFrame): return await",
"Bars = \"Bars\" Trades = \"Trades\" Quotes = \"Quotes\" def get_data_method(data_type: DataType): if",
"for calendar in calendars: # See how much we got back by holding",
"just a minute after the market opens. if time_after_open.seconds >= 60: print('Liquidating positions.')",
"portfolio_change = (portfolio_value - start_value) / start_value print('Portfolio change: {:.4f}%'.format(portfolio_change * 100)) elif",
"None if algo_time is not None: # Convert the time to something compatable",
"3 or minor < 6: raise Exception('asyncio is not support in your python",
"calendars: # See how much we got back by holding the last day's",
"handles an edge case where the script is restarted # right before the",
"Alpaca API. start_time = (algo_time.date() - timedelta(days=window_size)).strftime( api_time_format) formatted_time = algo_time.date().strftime(api_time_format) end =",
"3 while num_tries > 0: # sometimes it fails so give it a",
"weekends if not datasets: assets = api.list_assets(status=\"active\") assets = [asset for asset in",
"api.get_clock() next_market_time = clock.next_open bought_today = False sold_today = False print_waiting = False",
"compatible with the Alpaca API. def api_format(dt): return dt.strftime(api_time_format) def backtest(api, days_to_test, portfolio_amount):",
"as `end` will be used. We use this for live trading. def get_ratings(api,",
"0 formatted_date = api_format(on_date) num_tries = 3 while num_tries > 0: # sometimes",
"if len(sys.argv) < 2: print( 'Error: please specify a command; either \"run\" or",
"0: return { 'symbol': symbol, 'rating': price_change / data.iloc[ 0].close * volume_factor, 'price':",
"msg += f\" between dates: start={start}, end={end}\" print(msg) step_size = 1000 results =",
"done = True for f in futures: if not f.done(): done = False",
"to buy time_until_close = clock.next_close - clock.timestamp # We'll buy our shares a",
"else: results.extend(await gather_with_concurrency(500, *tasks)) bad_requests = 0 for response in results: if isinstance(response,",
"- data.iloc[0].close # Calculate standard deviation of previous volumes volume_stdev = data.iloc[:-1].volume.std() if",
"= volume_change / volume_stdev # Rating = Number of volume standard deviations *",
"> 1: return # Now, if the stock is within our target range,",
"rest.get_trades_async elif data_type == DataType.Quotes: return rest.get_quotes_async else: raise Exception(f\"Unsupoported data type: {data_type}\")",
"ratings = get_ratings( api, None ) shares_to_buy = get_shares_to_buy(ratings, portfolio_cash) for symbol in",
"data\") sys.exit(-1) for symbol in shares_bought: df = barset[symbol] if not df.empty: total_value",
"be used for backtesting. assets = api.list_assets() now = datetime.now(timezone('EST')) beginning = now",
"1: return # Now, if the stock is within our target range, rate",
"bad_requests = 0 for response in results: if isinstance(response, Exception): print(f\"Got an error:",
"= get_shares_to_buy(ratings, portfolio_amount) for _, row in ratings.iterrows(): # \"Buy\" our shares on",
"\"Bars\" Trades = \"Trades\" Quotes = \"Quotes\" def get_data_method(data_type: DataType): if data_type ==",
"status='all' ) for order in orders: if order.side == 'buy': bought_today = True",
"import ThreadPoolExecutor, ProcessPoolExecutor import pandas as pd import statistics import sys import time",
"= Number of volume standard deviations * momentum. rating = price_change / data.iloc[0].close",
"len(data) < window_size: return # Make sure we aren't missing the most recent",
"= True else: # We need to sell our old positions before buying",
"True print(\"Waiting for next market day...\") time.sleep(30) if __name__ == '__main__': api =",
"sure we don't hit weekends if not datasets: assets = api.list_assets(status=\"active\") assets =",
"Get the ratings for a particular day ratings = \\ get_ratings(api, timezone('EST').localize(calendar.date), datasets=data)",
"DataType.Bars, start, end, timeframe) def _process_dataset(dataset, algo_time, start, end, window_size, index): if isinstance(dataset,",
"obviously not done anything today. pass clock = api.get_clock() next_market_time = clock.next_open bought_today",
"# This handles an edge case where the script is restarted # right",
"timeframe: TimeFrame = None): major = sys.version_info.major minor = sys.version_info.minor if major <",
"isinstance(dataset, Exception): return symbol = dataset[0] data = dataset[1].truncate(after=end + timedelta(days=1))[ -window_size:] if",
"we don't want to do it again. # Useful in case the script",
"await asyncio.gather(*tasks, return_exceptions=True)) else: results.extend(await gather_with_concurrency(500, *tasks)) bad_requests = 0 for response in",
"trying to get data\") sys.exit(-1) for symbol in shares_bought: df = barset[symbol] if",
") return shares # Returns a string version of a timestamp compatible with",
"symbols[i:i + step_size]: args = [symbol, start, end, timeframe.value] if timeframe else \\",
"data for {len(symbols)} symbols\" msg += f\", timeframe: {timeframe}\" if timeframe else \"\"",
"Max 200 # Only stocks with prices in this range will be considered.",
"Quotes = \"Quotes\" def get_data_method(data_type: DataType): if data_type == DataType.Bars: return rest.get_bars_async elif",
"end=now.strftime(\"%Y-%m-%d\") ) shares = {} cal_index = 0 assets = api.list_assets(status=\"active\") assets =",
"range, rate it. price = data.iloc[-1].close if price <= max_stock_price and price >=",
"* df.iloc[0].open return total_value def run_live(api): # See if we've already bought or",
"The data for the stock might be low quality. return # Then, compare",
"volumes volume_stdev = data.iloc[:-1].volume.std() if volume_stdev == 0: # The data for the",
"get_historic_bars(list(shares_bought.keys()), pytz.timezone(\"America/New_York\").localize( on_date).isoformat(), pytz.timezone(\"America/New_York\").localize( on_date).isoformat(), TimeFrame.Day)) barset = dict(barset) break except Exception as",
"return rest.get_trades_async elif data_type == DataType.Quotes: return rest.get_quotes_async else: raise Exception(f\"Unsupoported data type:",
"Now, if the stock is within our target range, rate it. price =",
"We don't have any orders, so we've obviously not done anything today. pass",
"the most recent data. latest_bar = data.iloc[-1].name.to_pydatetime().astimezone( timezone('EST')) if algo_time: gap_from_present = algo_time",
"dataset, algo_time, start, end, window_size, index))) done = False while not done: done",
"None ) shares_to_buy = get_shares_to_buy(ratings, portfolio_cash) for symbol in shares_to_buy: if shares_to_buy[symbol] >",
"closes. sold_today = True break else: sold_today = True except: # We don't",
"get_shares_to_buy(ratings, portfolio_amount) for _, row in ratings.iterrows(): # \"Buy\" our shares on that",
"if sys.argv[1] == 'backtest': # Run a backtesting session using the provided parameters",
"sell our shares just a minute after the market opens. if time_after_open.seconds >=",
"# The max stocks_to_hold is 200, so we shouldn't see more than 400",
"datasets = loop.run_until_complete( get_historic_bars(symbols, start.isoformat(), end.isoformat(), TimeFrame.Day)) futures = [] for dataset in",
"prices. # Note: If algo_time is None, the API's default behavior of the",
"400 # orders on a given day. orders = api.list_orders( after=api_format(datetime.today() - timedelta(days=1)),",
"in this range will be considered. max_stock_price = 26 min_stock_price = 6 #",
"between dates: start={start}, end={end}\" print(msg) step_size = 1000 results = [] for i",
"= ratings.reset_index(drop=True) return ratings[:stocks_to_hold] def get_shares_to_buy(ratings_df, portfolio): total_rating = ratings_df['rating'].sum() shares = {}",
"except: # We don't have any orders, so we've obviously not done anything",
"= api.get_clock() next_market_time = clock.next_open bought_today = False sold_today = False print_waiting =",
"def get_historic_bars(symbols, start, end, timeframe: TimeFrame): return await get_historic_data_base(symbols, DataType.Bars, start, end, timeframe)",
"symbol in shares_to_buy: if shares_to_buy[symbol] > 0: api.submit_order( symbol=symbol, qty=shares_to_buy[symbol], side='buy', type='market', time_in_force='day'",
"algo_time, start, end, window_size, index): if isinstance(dataset, Exception): return symbol = dataset[0] data",
"} # Rate stocks based on the volume's deviation from the previous 5",
"if the stock is within our target range, rate it. price = data.iloc[-1].close",
"float(sys.argv[2]) testing_days = int(sys.argv[3]) portfolio_value = backtest(api, testing_days, start_value) portfolio_change = (portfolio_value -",
"len(shares_bought.keys()) == 0: return 0 total_value = 0 formatted_date = api_format(on_date) num_tries =",
"wait until the market's open to do anything. clock = api.get_clock() if clock.is_open",
"\"backtest ' '<cash balance> <number of days to test>\".') else: if sys.argv[1] ==",
"more than 400 # orders on a given day. orders = api.list_orders( after=api_format(datetime.today()",
"symbols to ratings and prices. # Note: If algo_time is None, the API's",
"else: sold_today = True except: # We don't have any orders, so we've",
"the previous 5 days and # momentum. Returns a dataframe mapping stock symbols",
"balance> <number of days to test>\".') else: if sys.argv[1] == 'backtest': # Run",
"(-04:00 represents the market's TZ.) api_time_format = '%Y-%m-%dT%H:%M:%S.%f-04:00' loop = asyncio.get_event_loop() if sys.argv[1]",
"please specify a command; either \"run\" or \"backtest ' '<cash balance> <number of",
"break # Get the ratings for a particular day ratings = \\ get_ratings(api,",
"\\ [symbol, start, end] tasks.append(get_data_method(data_type)(*args)) if minor >= 8: results.extend( await asyncio.gather(*tasks, return_exceptions=True))",
"data.iloc[-1].name.to_pydatetime().astimezone( timezone('EST')) if algo_time: gap_from_present = algo_time - latest_bar if gap_from_present.days > 1:",
"= clock.next_close - clock.timestamp # We'll buy our shares a couple minutes before",
"after we bought it. def get_value_of_assets(api, shares_bought, on_date): if len(shares_bought.keys()) == 0: return",
"skip over market holidays and handle early # market closures during our backtesting",
"something compatable with the Alpaca API. start_time = (algo_time.date() - timedelta(days=window_size)).strftime( api_time_format) formatted_time",
"ratings_df['rating'].sum() shares = {} for _, row in ratings_df.iterrows(): shares[row['symbol']] = int( row['rating']",
"row['price'] ) return shares # Returns a string version of a timestamp compatible",
"total_rating * portfolio / row['price'] ) return shares # Returns a string version",
"stock might be low quality. return # Then, compare it to the change",
"ProcessPoolExecutor import pandas as pd import statistics import sys import time import asyncio",
"after the market opens. if time_after_open.seconds >= 60: print('Liquidating positions.') api.close_all_positions() sold_today =",
"datetime import datetime, timedelta from pytz import timezone stocks_to_hold = 20 # Max",
"class DataType(str, Enum): Bars = \"Bars\" Trades = \"Trades\" Quotes = \"Quotes\" def",
"stocks that will be used for backtesting. assets = api.list_assets() now = datetime.now(timezone('EST'))",
"sold_today = False print(\"Market Open\") print_waiting = False if not print_waiting: print_waiting =",
"f in futures: if not f.done(): done = False break time.sleep(0.1) for f",
"TimeFrame.Day)) sp500_change = (results[0][1].iloc[-1].close - results[0][1].iloc[ 0].close) / results[0][1].iloc[0].close print('S&P 500 change during",
"we've already bought or sold positions today. If so, we don't want to",
"= 26 min_stock_price = 6 # API datetimes will match this format. (-04:00",
"if time_after_open.seconds >= 60: print('Liquidating positions.') api.close_all_positions() sold_today = True else: sold_today =",
"not f.done(): done = False break time.sleep(0.1) for f in futures: res =",
"sure we aren't missing the most recent data. latest_bar = data.iloc[-1].name.to_pydatetime().astimezone( timezone('EST')) if",
"price_change / data.iloc[ 0].close * volume_factor, 'price': price } # Rate stocks based",
"api_format(calendars[-1].date), TimeFrame.Day)) sp500_change = (results[0][1].iloc[-1].close - results[0][1].iloc[ 0].close) / results[0][1].iloc[0].close print('S&P 500 change",
"timeframe) def _process_dataset(dataset, algo_time, start, end, window_size, index): if isinstance(dataset, Exception): return symbol",
"response in results: if isinstance(response, Exception): print(f\"Got an error: {response}\") elif not len(response[1]):",
"num_tries > 0: # sometimes it fails so give it a shot few",
"cost = row['price'] * shares_to_buy portfolio_amount -= cost cal_index += 1 # Print",
"ratings.append(res, ignore_index=True) ratings = ratings.sort_values('rating', ascending=False) ratings = ratings.reset_index(drop=True) return ratings[:stocks_to_hold] def get_shares_to_buy(ratings_df,",
"portfolio_value = backtest(api, testing_days, start_value) portfolio_change = (portfolio_value - start_value) / start_value print('Portfolio",
"portfolio would have been # worth the day after we bought it. def",
"print(\"Market Open\") print_waiting = False if not print_waiting: print_waiting = True print(\"Waiting for",
"tradeapi.REST() rest = AsyncRest() if len(sys.argv) < 2: print( 'Error: please specify a",
"minute after the market opens. if time_after_open.seconds >= 60: print('Liquidating positions.') api.close_all_positions() sold_today",
"backtesting window. break # Get the ratings for a particular day ratings =",
"cal_index == len(calendars) - 2: # -2 because we don't have today's data",
"'Error: please specify a command; either \"run\" or \"backtest ' '<cash balance> <number",
"days to test>\".') else: if sys.argv[1] == 'backtest': # Run a backtesting session",
"0].close * volume_factor, 'price': price } # Rate stocks based on the volume's",
"We need to sell our old positions before buying new ones. time_after_open =",
"dates: start={start}, end={end}\" print(msg) step_size = 1000 results = [] for i in",
"if algo_time is not None: # Convert the time to something compatable with",
"results async def get_historic_bars(symbols, start, end, timeframe: TimeFrame): return await get_historic_data_base(symbols, DataType.Bars, start,",
"return # Make sure we aren't missing the most recent data. latest_bar =",
"else: executor = ProcessPoolExecutor(1) class DataType(str, Enum): Bars = \"Bars\" Trades = \"Trades\"",
"now = datetime.now(timezone('EST')) beginning = now - timedelta(days=days_to_test) # The calendars API will",
"collection of stocks that will be used for backtesting. assets = api.list_assets() now",
"get_historic_data_base(symbols, DataType.Bars, start, end, timeframe) def _process_dataset(dataset, algo_time, start, end, window_size, index): if",
"break else: sold_today = True except: # We don't have any orders, so",
"DataType.Trades: return rest.get_trades_async elif data_type == DataType.Quotes: return rest.get_quotes_async else: raise Exception(f\"Unsupoported data",
"as e: num_tries -= 1 if num_tries <= 0: print(\"Error trying to get",
"[symbol, start, end, timeframe.value] if timeframe else \\ [symbol, start, end] tasks.append(get_data_method(data_type)(*args)) if",
"faster executor = ProcessPoolExecutor(10) else: executor = ProcessPoolExecutor(1) class DataType(str, Enum): Bars =",
"- timedelta(days=window_size)).strftime( api_time_format) formatted_time = algo_time.date().strftime(api_time_format) end = pd.Timestamp(formatted_time) else: end = pytz.timezone(\"America/New_York\").localize(pd.Timestamp('now'))",
"major < 3 or minor < 6: raise Exception('asyncio is not support in",
"else \\ [symbol, start, end] tasks.append(get_data_method(data_type)(*args)) if minor >= 8: results.extend( await asyncio.gather(*tasks,",
"how much our portfolio would have been # worth the day after we",
"bad_requests += 1 print(f\"Total of {len(results)} {data_type}, and {bad_requests} \" f\"empty responses.\") return",
"# The data for the stock might be low quality. return # Then,",
"0].close) / results[0][1].iloc[0].close print('S&P 500 change during backtesting window: {:.4f}%'.format( sp500_change * 100)",
"positions today. If so, we don't want to do it again. # Useful",
"1000 results = [] for i in range(0, len(symbols), step_size): tasks = []",
"= False try: # The max stocks_to_hold is 200, so we shouldn't see",
"\"run\" or \"backtest ' '<cash balance> <number of days to test>\".') else: if",
"if time_until_close.seconds <= 120: print('Buying positions...') portfolio_cash = float(api.get_account().cash) ratings = get_ratings( api,",
"rest.get_quotes_async else: raise Exception(f\"Unsupoported data type: {data_type}\") async def get_historic_data_base(symbols, data_type: DataType, start,",
"get_historic_bars(['SPY'], api_format(calendars[0].date), api_format(calendars[-1].date), TimeFrame.Day)) sp500_change = (results[0][1].iloc[-1].close - results[0][1].iloc[ 0].close) / results[0][1].iloc[0].close print('S&P",
"0 window_size = 5 # The number of days of data to consider",
"in volume since yesterday. volume_change = data.iloc[-1].volume - data.iloc[-2].volume volume_factor = volume_change /",
"Enum): Bars = \"Bars\" Trades = \"Trades\" Quotes = \"Quotes\" def get_data_method(data_type: DataType):",
"of days of data to consider formatted_time = None if algo_time is not",
"market opens. if time_after_open.seconds >= 60: print('Liquidating positions.') api.close_all_positions() sold_today = True else:",
"try: barset = loop.run_until_complete( get_historic_bars(list(shares_bought.keys()), pytz.timezone(\"America/New_York\").localize( on_date).isoformat(), pytz.timezone(\"America/New_York\").localize( on_date).isoformat(), TimeFrame.Day)) barset = dict(barset)",
"will be considered. max_stock_price = 26 min_stock_price = 6 # API datetimes will",
"{data_type}\") async def get_historic_data_base(symbols, data_type: DataType, start, end, timeframe: TimeFrame = None): major",
"Print market (S&P500) return for the time period results = loop.run_until_complete( get_historic_bars(['SPY'], api_format(calendars[0].date),",
"volume standard deviations * momentum. rating = price_change / data.iloc[0].close * volume_factor if",
"pandas as pd import statistics import sys import time import asyncio from enum",
"sold_today = True except: # We don't have any orders, so we've obviously",
"def get_shares_to_buy(ratings_df, portfolio): total_rating = ratings_df['rating'].sum() shares = {} for _, row in",
"in range(0, len(symbols), step_size): tasks = [] for symbol in symbols[i:i + step_size]:",
"much our portfolio would have been # worth the day after we bought",
"pytz.timezone(\"America/New_York\").localize(pd.Timestamp('now')) start = end - timedelta( days=window_size + 10) # make sure we",
"Trades = \"Trades\" Quotes = \"Quotes\" def get_data_method(data_type: DataType): if data_type == DataType.Bars:",
"{data_type}, and {bad_requests} \" f\"empty responses.\") return results async def get_historic_bars(symbols, start, end,",
"# \"Buy\" our shares on that day and subtract the cost. shares_to_buy =",
"+= shares_bought[symbol] * df.iloc[0].open return total_value def run_live(api): # See if we've already",
"picks overnight portfolio_amount += get_value_of_assets(api, shares, calendar.date) print('Portfolio value on {}: {:0.2f} $'.format(calendar.date.strftime(",
"shares just a minute after the market opens. if time_after_open.seconds >= 60: print('Liquidating",
"day...\") time.sleep(30) if __name__ == '__main__': api = tradeapi.REST() rest = AsyncRest() if",
"timeframe else \"\" msg += f\" between dates: start={start}, end={end}\" print(msg) step_size =",
"shares_to_buy: if shares_to_buy[symbol] > 0: api.submit_order( symbol=symbol, qty=shares_to_buy[symbol], side='buy', type='market', time_in_force='day' ) print('Positions",
"in shares_bought: df = barset[symbol] if not df.empty: total_value += shares_bought[symbol] * df.iloc[0].open",
"if timeframe else \"\" msg += f\" between dates: start={start}, end={end}\" print(msg) step_size",
"TimeFrame = None): major = sys.version_info.major minor = sys.version_info.minor if major < 3",
"shares_bought: df = barset[symbol] if not df.empty: total_value += shares_bought[symbol] * df.iloc[0].open return",
"let us skip over market holidays and handle early # market closures during",
"market closures during our backtesting window. calendars = api.get_calendar( start=beginning.strftime(\"%Y-%m-%d\"), end=now.strftime(\"%Y-%m-%d\") ) shares",
"= \"Quotes\" def get_data_method(data_type: DataType): if data_type == DataType.Bars: return rest.get_bars_async elif data_type",
"Convert the time to something compatable with the Alpaca API. start_time = (algo_time.date()",
"default behavior of the current time # as `end` will be used. We",
"timedelta(days=10)).isoformat(), pytz.timezone(\"America/New_York\").localize( calendars[-1].date).isoformat(), TimeFrame.Day)) for calendar in calendars: # See how much we",
"datasets=data) shares = get_shares_to_buy(ratings, portfolio_amount) for _, row in ratings.iterrows(): # \"Buy\" our",
"2: # -2 because we don't have today's data yet # We've reached",
"df = barset[symbol] if not df.empty: total_value += shares_bought[symbol] * df.iloc[0].open return total_value",
"== DataType.Quotes: return rest.get_quotes_async else: raise Exception(f\"Unsupoported data type: {data_type}\") async def get_historic_data_base(symbols,",
"from alpaca_trade_api.entity_v2 import BarsV2 from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor import pandas as pd",
"Rate stocks based on the volume's deviation from the previous 5 days and",
"= [asset for asset in assets if asset.tradable] symbols = [s.symbol for s",
"(results[0][1].iloc[-1].close - results[0][1].iloc[ 0].close) / results[0][1].iloc[0].close print('S&P 500 change during backtesting window: {:.4f}%'.format(",
"index))) done = False while not done: done = True for f in",
"See how much we got back by holding the last day's picks overnight",
"a shot few more times try: barset = loop.run_until_complete( get_historic_bars(list(shares_bought.keys()), pytz.timezone(\"America/New_York\").localize( on_date).isoformat(), pytz.timezone(\"America/New_York\").localize(",
"DataType): if data_type == DataType.Bars: return rest.get_bars_async elif data_type == DataType.Trades: return rest.get_trades_async",
"get_value_of_assets(api, shares_bought, on_date): if len(shares_bought.keys()) == 0: return 0 total_value = 0 formatted_date",
"of volume standard deviations * momentum. rating = price_change / data.iloc[0].close * volume_factor",
"the time period results = loop.run_until_complete( get_historic_bars(['SPY'], api_format(calendars[0].date), api_format(calendars[-1].date), TimeFrame.Day)) sp500_change = (results[0][1].iloc[-1].close",
"our shares on that day and subtract the cost. shares_to_buy = shares[row['symbol']] cost",
"or \"backtest ' '<cash balance> <number of days to test>\".') else: if sys.argv[1]",
"or len(data) < window_size: return # Make sure we aren't missing the most",
"num_tries -= 1 if num_tries <= 0: print(\"Error trying to get data\") sys.exit(-1)",
"the collection of stocks that will be used for backtesting. assets = api.list_assets()",
"api.list_assets() now = datetime.now(timezone('EST')) beginning = now - timedelta(days=days_to_test) # The calendars API",
"snapshot[ x].latest_trade else False, snapshot)) data = loop.run_until_complete( get_historic_bars( symbols[:], pytz.timezone(\"America/New_York\").localize( calendars[0].date -",
"sys.version_info.major minor = sys.version_info.minor if major < 3 or minor < 6: raise",
"= \\ get_ratings(api, timezone('EST').localize(calendar.date), datasets=data) shares = get_shares_to_buy(ratings, portfolio_amount) for _, row in",
"x].latest_trade else False, snapshot)) datasets = loop.run_until_complete( get_historic_bars(symbols, start.isoformat(), end.isoformat(), TimeFrame.Day)) futures =",
"loop.run_until_complete( get_historic_bars(['SPY'], api_format(calendars[0].date), api_format(calendars[-1].date), TimeFrame.Day)) sp500_change = (results[0][1].iloc[-1].close - results[0][1].iloc[ 0].close) / results[0][1].iloc[0].close",
"e: num_tries -= 1 if num_tries <= 0: print(\"Error trying to get data\")",
"time # as `end` will be used. We use this for live trading.",
") if cal_index == len(calendars) - 2: # -2 because we don't have",
"assets if asset.tradable] symbols = [s.symbol for s in assets] snapshot = api.get_snapshots(symbols)",
"portfolio / row['price'] ) return shares # Returns a string version of a",
"mapping stock symbols to ratings and prices. # Note: If algo_time is None,",
"not print_waiting: print_waiting = True print(\"Waiting for next market day...\") time.sleep(30) if __name__",
"* 100) ) return portfolio_amount # Used while backtesting to find out how",
"get_shares_to_buy(ratings, portfolio_cash) for symbol in shares_to_buy: if shares_to_buy[symbol] > 0: api.submit_order( symbol=symbol, qty=shares_to_buy[symbol],",
"f.done(): done = False break time.sleep(0.1) for f in futures: res = f.result()",
"in calendars: # See how much we got back by holding the last",
"= price_change / data.iloc[0].close * volume_factor if rating > 0: return { 'symbol':",
"row['rating'] / total_rating * portfolio / row['price'] ) return shares # Returns a",
"# momentum. Returns a dataframe mapping stock symbols to ratings and prices. #",
"/ data.iloc[ 0].close * volume_factor, 'price': price } # Rate stocks based on",
"market's open to do anything. clock = api.get_clock() if clock.is_open and not bought_today:",
">= min_stock_price if snapshot[x] and snapshot[ x].latest_trade else False, snapshot)) data = loop.run_until_complete(",
"end] tasks.append(get_data_method(data_type)(*args)) if minor >= 8: results.extend( await asyncio.gather(*tasks, return_exceptions=True)) else: results.extend(await gather_with_concurrency(500,",
"* volume_factor if rating > 0: return { 'symbol': symbol, 'rating': price_change /",
"end={end}\" print(msg) step_size = 1000 results = [] for i in range(0, len(symbols),",
"api.list_orders( after=api_format(datetime.today() - timedelta(days=1)), limit=400, status='all' ) for order in orders: if order.side",
"on the volume's deviation from the previous 5 days and # momentum. Returns",
"= [] for dataset in datasets: futures.append(executor.submit(_process_dataset, *( dataset, algo_time, start, end, window_size,",
"6: raise Exception('asyncio is not support in your python version') msg = f\"Getting",
">= snapshot[ x].latest_trade.p >= min_stock_price if snapshot[x] and snapshot[ x].latest_trade else False, snapshot))",
"to test>\".') else: if sys.argv[1] == 'backtest': # Run a backtesting session using",
"timeframe: TimeFrame): return await get_historic_data_base(symbols, DataType.Bars, start, end, timeframe) def _process_dataset(dataset, algo_time, start,",
"Then, compare it to the change in volume since yesterday. volume_change = data.iloc[-1].volume",
"day ratings = \\ get_ratings(api, timezone('EST').localize(calendar.date), datasets=data) shares = get_shares_to_buy(ratings, portfolio_amount) for _,",
"dict(barset) break except Exception as e: num_tries -= 1 if num_tries <= 0:",
"elif data_type == DataType.Trades: return rest.get_trades_async elif data_type == DataType.Quotes: return rest.get_quotes_async else:",
"<= 0: print(\"Error trying to get data\") sys.exit(-1) for symbol in shares_bought: df",
"Exception): return symbol = dataset[0] data = dataset[1].truncate(after=end + timedelta(days=1))[ -window_size:] if data.empty",
"+= 1 # Print market (S&P500) return for the time period results =",
"sold_today = False try: # The max stocks_to_hold is 200, so we shouldn't",
"rating = price_change / data.iloc[0].close * volume_factor if rating > 0: return {",
"subtract the cost. shares_to_buy = shares[row['symbol']] cost = row['price'] * shares_to_buy portfolio_amount -=",
"open to do anything. clock = api.get_clock() if clock.is_open and not bought_today: if",
"= 5 # The number of days of data to consider formatted_time =",
"ThreadPoolExecutor, ProcessPoolExecutor import pandas as pd import statistics import sys import time import",
"= tradeapi.REST() rest = AsyncRest() if len(sys.argv) < 2: print( 'Error: please specify",
"sold_today = True break else: sold_today = True except: # We don't have",
"command; either \"run\" or \"backtest ' '<cash balance> <number of days to test>\".')",
"= False sold_today = False print_waiting = False while True: # We'll wait",
"stock is within our target range, rate it. price = data.iloc[-1].close if price",
"days of data to consider formatted_time = None if algo_time is not None:",
"= clock.next_open bought_today = False sold_today = False print_waiting = False while True:",
"any orders, so we've obviously not done anything today. pass clock = api.get_clock()",
"get_value_of_assets(api, shares, calendar.date) print('Portfolio value on {}: {:0.2f} $'.format(calendar.date.strftime( '%Y-%m-%d'), portfolio_amount) ) if",
"$'.format(calendar.date.strftime( '%Y-%m-%d'), portfolio_amount) ) if cal_index == len(calendars) - 2: # -2 because",
"'price': price } # Rate stocks based on the volume's deviation from the",
"we shouldn't see more than 400 # orders on a given day. orders",
"if we've already bought or sold positions today. If so, we don't want",
"today. pass clock = api.get_clock() next_market_time = clock.next_open bought_today = False sold_today =",
"dataframe mapping stock symbols to ratings and prices. # Note: If algo_time is",
"where the script is restarted # right before the market closes. sold_today =",
"async def get_historic_data_base(symbols, data_type: DataType, start, end, timeframe: TimeFrame = None): major =",
"*( dataset, algo_time, start, end, window_size, index))) done = False while not done:",
"ratings_df.iterrows(): shares[row['symbol']] = int( row['rating'] / total_rating * portfolio / row['price'] ) return",
"market close. if time_until_close.seconds <= 120: print('Buying positions...') portfolio_cash = float(api.get_account().cash) ratings =",
"200, so we shouldn't see more than 400 # orders on a given",
"holding the last day's picks overnight portfolio_amount += get_value_of_assets(api, shares, calendar.date) print('Portfolio value",
"print_waiting: print_waiting = True print(\"Waiting for next market day...\") time.sleep(30) if __name__ ==",
"else: raise Exception(f\"Unsupoported data type: {data_type}\") async def get_historic_data_base(symbols, data_type: DataType, start, end,",
"- timedelta(days=10)).isoformat(), pytz.timezone(\"America/New_York\").localize( calendars[-1].date).isoformat(), TimeFrame.Day)) for calendar in calendars: # See how much",
"be used. We use this for live trading. def get_ratings(api, algo_time, datasets=None): ratings",
"enum import Enum import pytz from datetime import datetime, timedelta from pytz import",
"data = loop.run_until_complete( get_historic_bars( symbols[:], pytz.timezone(\"America/New_York\").localize( calendars[0].date - timedelta(days=10)).isoformat(), pytz.timezone(\"America/New_York\").localize( calendars[-1].date).isoformat(), TimeFrame.Day)) for",
"we bought it. def get_value_of_assets(api, shares_bought, on_date): if len(shares_bought.keys()) == 0: return 0",
"pass clock = api.get_clock() next_market_time = clock.next_open bought_today = False sold_today = False",
"sp500_change * 100) ) return portfolio_amount # Used while backtesting to find out",
"import statistics import sys import time import asyncio from enum import Enum import",
"for f in futures: res = f.result() if res: ratings = ratings.append(res, ignore_index=True)",
"sold_today = False if clock.timestamp > next_market_time: next_market_time = clock.next_open bought_today = False",
"compare it to the change in volume since yesterday. volume_change = data.iloc[-1].volume -",
"data.iloc[-1].close if price <= max_stock_price and price >= min_stock_price: price_change = price -",
"of the backtesting window. break # Get the ratings for a particular day",
"side='buy', type='market', time_in_force='day' ) print('Positions bought.') bought_today = True else: # We need",
"shares on that day and subtract the cost. shares_to_buy = shares[row['symbol']] cost =",
"== DataType.Bars: return rest.get_bars_async elif data_type == DataType.Trades: return rest.get_trades_async elif data_type ==",
"TimeFrame from alpaca_trade_api.rest_async import gather_with_concurrency, AsyncRest from alpaca_trade_api.entity_v2 import BarsV2 from concurrent.futures import",
"holidays and handle early # market closures during our backtesting window. calendars =",
"* shares_to_buy portfolio_amount -= cost cal_index += 1 # Print market (S&P500) return",
"# -2 because we don't have today's data yet # We've reached the",
"pd import statistics import sys import time import asyncio from enum import Enum",
"for asset in assets if asset.tradable] symbols = [s.symbol for s in assets]",
"window_size: return # Make sure we aren't missing the most recent data. latest_bar",
"False print(\"Market Open\") print_waiting = False if not print_waiting: print_waiting = True print(\"Waiting",
"either \"run\" or \"backtest ' '<cash balance> <number of days to test>\".') else:",
"datetime.now(timezone('EST')) beginning = now - timedelta(days=days_to_test) # The calendars API will let us",
"else: sold_today = False if clock.timestamp > next_market_time: next_market_time = clock.next_open bought_today =",
"ratings for a particular day ratings = \\ get_ratings(api, timezone('EST').localize(calendar.date), datasets=data) shares =",
"data_type: DataType, start, end, timeframe: TimeFrame = None): major = sys.version_info.major minor =",
"more times try: barset = loop.run_until_complete( get_historic_bars(list(shares_bought.keys()), pytz.timezone(\"America/New_York\").localize( on_date).isoformat(), pytz.timezone(\"America/New_York\").localize( on_date).isoformat(), TimeFrame.Day)) barset",
"considered. max_stock_price = 26 min_stock_price = 6 # API datetimes will match this",
"data_type == DataType.Trades: return rest.get_trades_async elif data_type == DataType.Quotes: return rest.get_quotes_async else: raise",
"the change in volume since yesterday. volume_change = data.iloc[-1].volume - data.iloc[-2].volume volume_factor =",
"market hours. bought_today = False sold_today = False try: # The max stocks_to_hold",
"done = False while not done: done = True for f in futures:",
"by holding the last day's picks overnight portfolio_amount += get_value_of_assets(api, shares, calendar.date) print('Portfolio",
"= [] for symbol in symbols[i:i + step_size]: args = [symbol, start, end,",
"if minor >= 8: results.extend( await asyncio.gather(*tasks, return_exceptions=True)) else: results.extend(await gather_with_concurrency(500, *tasks)) bad_requests",
"end, window_size, index))) done = False while not done: done = True for",
"def api_format(dt): return dt.strftime(api_time_format) def backtest(api, days_to_test, portfolio_amount): # This is the collection",
"reached the end of the backtesting window. break # Get the ratings for",
"the script is restarted # right before the market closes. sold_today = True",
"time_in_force='day' ) print('Positions bought.') bought_today = True else: # We need to sell",
"if price <= max_stock_price and price >= min_stock_price: price_change = price - data.iloc[0].close",
"snapshot)) data = loop.run_until_complete( get_historic_bars( symbols[:], pytz.timezone(\"America/New_York\").localize( calendars[0].date - timedelta(days=10)).isoformat(), pytz.timezone(\"America/New_York\").localize( calendars[-1].date).isoformat(), TimeFrame.Day))",
"not done: done = True for f in futures: if not f.done(): done",
"is not support in your python version') msg = f\"Getting {data_type} data for",
"few more times try: barset = loop.run_until_complete( get_historic_bars(list(shares_bought.keys()), pytz.timezone(\"America/New_York\").localize( on_date).isoformat(), pytz.timezone(\"America/New_York\").localize( on_date).isoformat(), TimeFrame.Day))",
"bought_today = True else: # We need to sell our old positions before",
"int( row['rating'] / total_rating * portfolio / row['price'] ) return shares # Returns",
"return for the time period results = loop.run_until_complete( get_historic_bars(['SPY'], api_format(calendars[0].date), api_format(calendars[-1].date), TimeFrame.Day)) sp500_change",
"algo_time, start, end, window_size, index))) done = False while not done: done =",
"shares a couple minutes before market close. if time_until_close.seconds <= 120: print('Buying positions...')",
">= min_stock_price if snapshot[x] and snapshot[ x].latest_trade else False, snapshot)) datasets = loop.run_until_complete(",
"= pd.DataFrame(columns=['symbol', 'rating', 'price']) index = 0 window_size = 5 # The number",
"aren't missing the most recent data. latest_bar = data.iloc[-1].name.to_pydatetime().astimezone( timezone('EST')) if algo_time: gap_from_present",
"during our backtesting window. calendars = api.get_calendar( start=beginning.strftime(\"%Y-%m-%d\"), end=now.strftime(\"%Y-%m-%d\") ) shares = {}",
"get data\") sys.exit(-1) for symbol in shares_bought: df = barset[symbol] if not df.empty:",
"to do it again. # Useful in case the script is restarted during",
"deviations * momentum. rating = price_change / data.iloc[0].close * volume_factor if rating >",
"= int(sys.argv[3]) portfolio_value = backtest(api, testing_days, start_value) portfolio_change = (portfolio_value - start_value) /",
"next market day...\") time.sleep(30) if __name__ == '__main__': api = tradeapi.REST() rest =",
"data.iloc[ 0].close * volume_factor, 'price': price } # Rate stocks based on the",
"it a shot few more times try: barset = loop.run_until_complete( get_historic_bars(list(shares_bought.keys()), pytz.timezone(\"America/New_York\").localize( on_date).isoformat(),",
"/ start_value print('Portfolio change: {:.4f}%'.format(portfolio_change * 100)) elif sys.argv[1] == 'run': run_live(api) else:",
"is None, the API's default behavior of the current time # as `end`",
"return # Then, compare it to the change in volume since yesterday. volume_change",
"sys.version_info.minor if major < 3 or minor < 6: raise Exception('asyncio is not",
"major = sys.version_info.major minor = sys.version_info.minor if major < 3 or minor <",
"how much we got back by holding the last day's picks overnight portfolio_amount",
"because we don't have today's data yet # We've reached the end of",
"ratings = ratings.append(res, ignore_index=True) ratings = ratings.sort_values('rating', ascending=False) ratings = ratings.reset_index(drop=True) return ratings[:stocks_to_hold]",
"hours. bought_today = False sold_today = False try: # The max stocks_to_hold is",
"volume_factor = volume_change / volume_stdev # Rating = Number of volume standard deviations",
"opens. if time_after_open.seconds >= 60: print('Liquidating positions.') api.close_all_positions() sold_today = True else: sold_today",
"in ratings.iterrows(): # \"Buy\" our shares on that day and subtract the cost.",
"a backtesting session using the provided parameters start_value = float(sys.argv[2]) testing_days = int(sys.argv[3])",
"ProcessPoolExecutor(10) else: executor = ProcessPoolExecutor(1) class DataType(str, Enum): Bars = \"Bars\" Trades =",
"the last day's picks overnight portfolio_amount += get_value_of_assets(api, shares, calendar.date) print('Portfolio value on",
"See if we've already bought or sold positions today. If so, we don't",
"datetime, timedelta from pytz import timezone stocks_to_hold = 20 # Max 200 #",
"clock.next_open bought_today = False sold_today = False print_waiting = False while True: #",
"data type: {data_type}\") async def get_historic_data_base(symbols, data_type: DataType, start, end, timeframe: TimeFrame =",
"tasks = [] for symbol in symbols[i:i + step_size]: args = [symbol, start,",
"shares # Returns a string version of a timestamp compatible with the Alpaca",
"= {} cal_index = 0 assets = api.list_assets(status=\"active\") assets = [asset for asset",
"our old positions before buying new ones. time_after_open = pd.Timestamp( clock.timestamp.time().isoformat()) - pd.Timestamp(",
"sp500_change = (results[0][1].iloc[-1].close - results[0][1].iloc[ 0].close) / results[0][1].iloc[0].close print('S&P 500 change during backtesting",
"during market hours. bought_today = False sold_today = False try: # The max",
"error: {response}\") elif not len(response[1]): bad_requests += 1 print(f\"Total of {len(results)} {data_type}, and",
"start_time = (algo_time.date() - timedelta(days=window_size)).strftime( api_time_format) formatted_time = algo_time.date().strftime(api_time_format) end = pd.Timestamp(formatted_time) else:",
"f.result() if res: ratings = ratings.append(res, ignore_index=True) ratings = ratings.sort_values('rating', ascending=False) ratings =",
"Exception as e: num_tries -= 1 if num_tries <= 0: print(\"Error trying to",
"Exception('asyncio is not support in your python version') msg = f\"Getting {data_type} data",
"time_after_open = pd.Timestamp( clock.timestamp.time().isoformat()) - pd.Timestamp( clock.next_open.time().isoformat()) # We'll sell our shares just",
"that day and subtract the cost. shares_to_buy = shares[row['symbol']] cost = row['price'] *",
"portfolio_amount) for _, row in ratings.iterrows(): # \"Buy\" our shares on that day",
"- clock.timestamp # We'll buy our shares a couple minutes before market close.",
"ratings.iterrows(): # \"Buy\" our shares on that day and subtract the cost. shares_to_buy",
"AsyncRest from alpaca_trade_api.entity_v2 import BarsV2 from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor import pandas as",
"= api.get_calendar( start=beginning.strftime(\"%Y-%m-%d\"), end=now.strftime(\"%Y-%m-%d\") ) shares = {} cal_index = 0 assets =",
"= data.iloc[:-1].volume.std() if volume_stdev == 0: # The data for the stock might",
"+= get_value_of_assets(api, shares, calendar.date) print('Portfolio value on {}: {:0.2f} $'.format(calendar.date.strftime( '%Y-%m-%d'), portfolio_amount) )",
"If algo_time is None, the API's default behavior of the current time #",
"don't have today's data yet # We've reached the end of the backtesting",
"have been # worth the day after we bought it. def get_value_of_assets(api, shares_bought,",
"missing the most recent data. latest_bar = data.iloc[-1].name.to_pydatetime().astimezone( timezone('EST')) if algo_time: gap_from_present =",
"Rating = Number of volume standard deviations * momentum. rating = price_change /",
"day and subtract the cost. shares_to_buy = shares[row['symbol']] cost = row['price'] * shares_to_buy",
"window. break # Get the ratings for a particular day ratings = \\",
"None: # Convert the time to something compatable with the Alpaca API. start_time",
"= ProcessPoolExecutor(10) else: executor = ProcessPoolExecutor(1) class DataType(str, Enum): Bars = \"Bars\" Trades",
"while not done: done = True for f in futures: if not f.done():",
"<= max_stock_price and price >= min_stock_price: price_change = price - data.iloc[0].close # Calculate",
"df.empty: total_value += shares_bought[symbol] * df.iloc[0].open return total_value def run_live(api): # See if",
"market closes. sold_today = True break else: sold_today = True except: # We",
"ratings = \\ get_ratings(api, timezone('EST').localize(calendar.date), datasets=data) shares = get_shares_to_buy(ratings, portfolio_amount) for _, row",
"= False print(\"Market Open\") print_waiting = False if not print_waiting: print_waiting = True",
"# Calculate standard deviation of previous volumes volume_stdev = data.iloc[:-1].volume.std() if volume_stdev ==",
"last day's picks overnight portfolio_amount += get_value_of_assets(api, shares, calendar.date) print('Portfolio value on {}:",
"8: results.extend( await asyncio.gather(*tasks, return_exceptions=True)) else: results.extend(await gather_with_concurrency(500, *tasks)) bad_requests = 0 for",
"backtest(api, testing_days, start_value) portfolio_change = (portfolio_value - start_value) / start_value print('Portfolio change: {:.4f}%'.format(portfolio_change",
"start, end, timeframe: TimeFrame): return await get_historic_data_base(symbols, DataType.Bars, start, end, timeframe) def _process_dataset(dataset,",
"change in volume since yesterday. volume_change = data.iloc[-1].volume - data.iloc[-2].volume volume_factor = volume_change",
") shares = {} cal_index = 0 assets = api.list_assets(status=\"active\") assets = [asset",
"for response in results: if isinstance(response, Exception): print(f\"Got an error: {response}\") elif not",
"price >= min_stock_price: price_change = price - data.iloc[0].close # Calculate standard deviation of",
"is the collection of stocks that will be used for backtesting. assets =",
"'backtest': # Run a backtesting session using the provided parameters start_value = float(sys.argv[2])",
"shares, calendar.date) print('Portfolio value on {}: {:0.2f} $'.format(calendar.date.strftime( '%Y-%m-%d'), portfolio_amount) ) if cal_index",
"window: {:.4f}%'.format( sp500_change * 100) ) return portfolio_amount # Used while backtesting to",
"snapshot[ x].latest_trade.p >= min_stock_price if snapshot[x] and snapshot[ x].latest_trade else False, snapshot)) datasets",
"20 # Max 200 # Only stocks with prices in this range will",
"The calendars API will let us skip over market holidays and handle early",
"don't have any orders, so we've obviously not done anything today. pass clock",
"on_date): if len(shares_bought.keys()) == 0: return 0 total_value = 0 formatted_date = api_format(on_date)",
"total_value = 0 formatted_date = api_format(on_date) num_tries = 3 while num_tries > 0:",
"get_historic_bars(symbols, start, end, timeframe: TimeFrame): return await get_historic_data_base(symbols, DataType.Bars, start, end, timeframe) def",
"data_type == DataType.Bars: return rest.get_bars_async elif data_type == DataType.Trades: return rest.get_trades_async elif data_type",
"data for the stock might be low quality. return # Then, compare it",
"while backtesting to find out how much our portfolio would have been #",
"Only stocks with prices in this range will be considered. max_stock_price = 26",
"else False, snapshot)) datasets = loop.run_until_complete( get_historic_bars(symbols, start.isoformat(), end.isoformat(), TimeFrame.Day)) futures = []",
"timedelta(days=1))[ -window_size:] if data.empty or len(data) < window_size: return # Make sure we",
"= None if algo_time is not None: # Convert the time to something",
"so the backtests go faster executor = ProcessPoolExecutor(10) else: executor = ProcessPoolExecutor(1) class",
"timezone('EST')) if algo_time: gap_from_present = algo_time - latest_bar if gap_from_present.days > 1: return",
"start=beginning.strftime(\"%Y-%m-%d\"), end=now.strftime(\"%Y-%m-%d\") ) shares = {} cal_index = 0 assets = api.list_assets(status=\"active\") assets",
"= pd.Timestamp(formatted_time) else: end = pytz.timezone(\"America/New_York\").localize(pd.Timestamp('now')) start = end - timedelta( days=window_size +",
"datasets: assets = api.list_assets(status=\"active\") assets = [asset for asset in assets if asset.tradable]",
"symbols[:], pytz.timezone(\"America/New_York\").localize( calendars[0].date - timedelta(days=10)).isoformat(), pytz.timezone(\"America/New_York\").localize( calendars[-1].date).isoformat(), TimeFrame.Day)) for calendar in calendars: #",
"- timedelta(days=days_to_test) # The calendars API will let us skip over market holidays",
"start_value) / start_value print('Portfolio change: {:.4f}%'.format(portfolio_change * 100)) elif sys.argv[1] == 'run': run_live(api)",
"volume's deviation from the previous 5 days and # momentum. Returns a dataframe",
"if clock.timestamp > next_market_time: next_market_time = clock.next_open bought_today = False sold_today = False",
"max_stock_price = 26 min_stock_price = 6 # API datetimes will match this format.",
"not done anything today. pass clock = api.get_clock() next_market_time = clock.next_open bought_today =",
"\"Trades\" Quotes = \"Quotes\" def get_data_method(data_type: DataType): if data_type == DataType.Bars: return rest.get_bars_async",
"start, end] tasks.append(get_data_method(data_type)(*args)) if minor >= 8: results.extend( await asyncio.gather(*tasks, return_exceptions=True)) else: results.extend(await",
"snapshot)) datasets = loop.run_until_complete( get_historic_bars(symbols, start.isoformat(), end.isoformat(), TimeFrame.Day)) futures = [] for dataset",
"done = False break time.sleep(0.1) for f in futures: res = f.result() if",
"ProcessPoolExecutor(1) class DataType(str, Enum): Bars = \"Bars\" Trades = \"Trades\" Quotes = \"Quotes\"",
"clock.is_open and not bought_today: if sold_today: # Wait to buy time_until_close = clock.next_close",
"= \"Bars\" Trades = \"Trades\" Quotes = \"Quotes\" def get_data_method(data_type: DataType): if data_type",
"ratings[:stocks_to_hold] def get_shares_to_buy(ratings_df, portfolio): total_rating = ratings_df['rating'].sum() shares = {} for _, row",
"over market holidays and handle early # market closures during our backtesting window.",
"# as `end` will be used. We use this for live trading. def",
"res = f.result() if res: ratings = ratings.append(res, ignore_index=True) ratings = ratings.sort_values('rating', ascending=False)",
"of days to test>\".') else: if sys.argv[1] == 'backtest': # Run a backtesting",
"= (portfolio_value - start_value) / start_value print('Portfolio change: {:.4f}%'.format(portfolio_change * 100)) elif sys.argv[1]",
"for {len(symbols)} symbols\" msg += f\", timeframe: {timeframe}\" if timeframe else \"\" msg",
"* portfolio / row['price'] ) return shares # Returns a string version of",
"- start_value) / start_value print('Portfolio change: {:.4f}%'.format(portfolio_change * 100)) elif sys.argv[1] == 'run':",
"deviation from the previous 5 days and # momentum. Returns a dataframe mapping",
"script is restarted # right before the market closes. sold_today = True break",
"ratings and prices. # Note: If algo_time is None, the API's default behavior",
"< 2: print( 'Error: please specify a command; either \"run\" or \"backtest '",
"as pd import statistics import sys import time import asyncio from enum import",
"range will be considered. max_stock_price = 26 min_stock_price = 6 # API datetimes",
"symbol, 'rating': price_change / data.iloc[ 0].close * volume_factor, 'price': price } # Rate",
"shot few more times try: barset = loop.run_until_complete( get_historic_bars(list(shares_bought.keys()), pytz.timezone(\"America/New_York\").localize( on_date).isoformat(), pytz.timezone(\"America/New_York\").localize( on_date).isoformat(),",
"right before the market closes. sold_today = True break else: sold_today = True",
"already bought or sold positions today. If so, we don't want to do",
"barset = loop.run_until_complete( get_historic_bars(list(shares_bought.keys()), pytz.timezone(\"America/New_York\").localize( on_date).isoformat(), pytz.timezone(\"America/New_York\").localize( on_date).isoformat(), TimeFrame.Day)) barset = dict(barset) break",
"orders, so we've obviously not done anything today. pass clock = api.get_clock() next_market_time",
"the market's open to do anything. clock = api.get_clock() if clock.is_open and not",
"# Only stocks with prices in this range will be considered. max_stock_price =",
"timeframe else \\ [symbol, start, end] tasks.append(get_data_method(data_type)(*args)) if minor >= 8: results.extend( await",
"return total_value def run_live(api): # See if we've already bought or sold positions",
"time_until_close.seconds <= 120: print('Buying positions...') portfolio_cash = float(api.get_account().cash) ratings = get_ratings( api, None",
"api.get_snapshots(symbols) symbols = list(filter(lambda x: max_stock_price >= snapshot[ x].latest_trade.p >= min_stock_price if snapshot[x]",
"portfolio_amount # Used while backtesting to find out how much our portfolio would",
"DataType.Quotes: return rest.get_quotes_async else: raise Exception(f\"Unsupoported data type: {data_type}\") async def get_historic_data_base(symbols, data_type:",
"in shares_to_buy: if shares_to_buy[symbol] > 0: api.submit_order( symbol=symbol, qty=shares_to_buy[symbol], side='buy', type='market', time_in_force='day' )",
"for symbol in shares_to_buy: if shares_to_buy[symbol] > 0: api.submit_order( symbol=symbol, qty=shares_to_buy[symbol], side='buy', type='market',",
"results = loop.run_until_complete( get_historic_bars(['SPY'], api_format(calendars[0].date), api_format(calendars[-1].date), TimeFrame.Day)) sp500_change = (results[0][1].iloc[-1].close - results[0][1].iloc[ 0].close)",
"False if clock.timestamp > next_market_time: next_market_time = clock.next_open bought_today = False sold_today =",
"import pytz from datetime import datetime, timedelta from pytz import timezone stocks_to_hold =",
"DataType.Bars: return rest.get_bars_async elif data_type == DataType.Trades: return rest.get_trades_async elif data_type == DataType.Quotes:",
"< window_size: return # Make sure we aren't missing the most recent data.",
"TimeFrame.Day)) for calendar in calendars: # See how much we got back by",
"elif data_type == DataType.Quotes: return rest.get_quotes_async else: raise Exception(f\"Unsupoported data type: {data_type}\") async",
"TimeFrame.Day)) barset = dict(barset) break except Exception as e: num_tries -= 1 if",
"if algo_time: gap_from_present = algo_time - latest_bar if gap_from_present.days > 1: return #",
"algo_time is not None: # Convert the time to something compatable with the",
"will match this format. (-04:00 represents the market's TZ.) api_time_format = '%Y-%m-%dT%H:%M:%S.%f-04:00' loop",
"raise Exception(f\"Unsupoported data type: {data_type}\") async def get_historic_data_base(symbols, data_type: DataType, start, end, timeframe:",
"{timeframe}\" if timeframe else \"\" msg += f\" between dates: start={start}, end={end}\" print(msg)",
"from pytz import timezone stocks_to_hold = 20 # Max 200 # Only stocks",
"the API's default behavior of the current time # as `end` will be",
"if rating > 0: return { 'symbol': symbol, 'rating': price_change / data.iloc[ 0].close",
"= data.iloc[-1].name.to_pydatetime().astimezone( timezone('EST')) if algo_time: gap_from_present = algo_time - latest_bar if gap_from_present.days >",
"pd.Timestamp(formatted_time) else: end = pytz.timezone(\"America/New_York\").localize(pd.Timestamp('now')) start = end - timedelta( days=window_size + 10)",
"__name__ == '__main__': api = tradeapi.REST() rest = AsyncRest() if len(sys.argv) < 2:",
"# make sure we don't hit weekends if not datasets: assets = api.list_assets(status=\"active\")",
"return ratings[:stocks_to_hold] def get_shares_to_buy(ratings_df, portfolio): total_rating = ratings_df['rating'].sum() shares = {} for _,",
"import alpaca_trade_api as tradeapi from alpaca_trade_api.rest import TimeFrame from alpaca_trade_api.rest_async import gather_with_concurrency, AsyncRest",
"for the time period results = loop.run_until_complete( get_historic_bars(['SPY'], api_format(calendars[0].date), api_format(calendars[-1].date), TimeFrame.Day)) sp500_change =",
"market holidays and handle early # market closures during our backtesting window. calendars",
"datetimes will match this format. (-04:00 represents the market's TZ.) api_time_format = '%Y-%m-%dT%H:%M:%S.%f-04:00'",
"min_stock_price if snapshot[x] and snapshot[ x].latest_trade else False, snapshot)) datasets = loop.run_until_complete( get_historic_bars(symbols,",
"import asyncio from enum import Enum import pytz from datetime import datetime, timedelta",
"import sys import time import asyncio from enum import Enum import pytz from",
"else: end = pytz.timezone(\"America/New_York\").localize(pd.Timestamp('now')) start = end - timedelta( days=window_size + 10) #",
"api.get_calendar( start=beginning.strftime(\"%Y-%m-%d\"), end=now.strftime(\"%Y-%m-%d\") ) shares = {} cal_index = 0 assets = api.list_assets(status=\"active\")",
"pytz.timezone(\"America/New_York\").localize( calendars[-1].date).isoformat(), TimeFrame.Day)) for calendar in calendars: # See how much we got",
"we don't hit weekends if not datasets: assets = api.list_assets(status=\"active\") assets = [asset",
"to find out how much our portfolio would have been # worth the",
"calendars API will let us skip over market holidays and handle early #",
"particular day ratings = \\ get_ratings(api, timezone('EST').localize(calendar.date), datasets=data) shares = get_shares_to_buy(ratings, portfolio_amount) for",
"5 # The number of days of data to consider formatted_time = None",
"a dataframe mapping stock symbols to ratings and prices. # Note: If algo_time",
"= end - timedelta( days=window_size + 10) # make sure we don't hit",
"for the stock might be low quality. return # Then, compare it to",
"print('Portfolio value on {}: {:0.2f} $'.format(calendar.date.strftime( '%Y-%m-%d'), portfolio_amount) ) if cal_index == len(calendars)",
"case where the script is restarted # right before the market closes. sold_today",
"the market closes. sold_today = True break else: sold_today = True except: #",
"# This is the collection of stocks that will be used for backtesting.",
"= loop.run_until_complete( get_historic_bars(symbols, start.isoformat(), end.isoformat(), TimeFrame.Day)) futures = [] for dataset in datasets:",
"120: print('Buying positions...') portfolio_cash = float(api.get_account().cash) ratings = get_ratings( api, None ) shares_to_buy",
"x].latest_trade.p >= min_stock_price if snapshot[x] and snapshot[ x].latest_trade else False, snapshot)) data =",
"in orders: if order.side == 'buy': bought_today = True # This handles an",
"\" f\"empty responses.\") return results async def get_historic_bars(symbols, start, end, timeframe: TimeFrame): return",
"False try: # The max stocks_to_hold is 200, so we shouldn't see more",
"asyncio.gather(*tasks, return_exceptions=True)) else: results.extend(await gather_with_concurrency(500, *tasks)) bad_requests = 0 for response in results:",
"# We'll wait until the market's open to do anything. clock = api.get_clock()",
"if res: ratings = ratings.append(res, ignore_index=True) ratings = ratings.sort_values('rating', ascending=False) ratings = ratings.reset_index(drop=True)",
"the Alpaca API. def api_format(dt): return dt.strftime(api_time_format) def backtest(api, days_to_test, portfolio_amount): # This",
"# sometimes it fails so give it a shot few more times try:",
"# Useful in case the script is restarted during market hours. bought_today =",
"before the market closes. sold_today = True break else: sold_today = True except:",
"number of days of data to consider formatted_time = None if algo_time is",
"We'll wait until the market's open to do anything. clock = api.get_clock() if",
"if snapshot[x] and snapshot[ x].latest_trade else False, snapshot)) data = loop.run_until_complete( get_historic_bars( symbols[:],",
"shares[row['symbol']] = int( row['rating'] / total_rating * portfolio / row['price'] ) return shares",
"pytz.timezone(\"America/New_York\").localize( on_date).isoformat(), TimeFrame.Day)) barset = dict(barset) break except Exception as e: num_tries -=",
"from alpaca_trade_api.rest import TimeFrame from alpaca_trade_api.rest_async import gather_with_concurrency, AsyncRest from alpaca_trade_api.entity_v2 import BarsV2",
"to consider formatted_time = None if algo_time is not None: # Convert the",
"<= 120: print('Buying positions...') portfolio_cash = float(api.get_account().cash) ratings = get_ratings( api, None )",
"sold_today = True else: sold_today = False if clock.timestamp > next_market_time: next_market_time =",
"this for live trading. def get_ratings(api, algo_time, datasets=None): ratings = pd.DataFrame(columns=['symbol', 'rating', 'price'])",
"total_value def run_live(api): # See if we've already bought or sold positions today.",
"alpaca_trade_api.rest import TimeFrame from alpaca_trade_api.rest_async import gather_with_concurrency, AsyncRest from alpaca_trade_api.entity_v2 import BarsV2 from",
"we aren't missing the most recent data. latest_bar = data.iloc[-1].name.to_pydatetime().astimezone( timezone('EST')) if algo_time:",
"a given day. orders = api.list_orders( after=api_format(datetime.today() - timedelta(days=1)), limit=400, status='all' ) for",
"/ volume_stdev # Rating = Number of volume standard deviations * momentum. rating",
"\"Buy\" our shares on that day and subtract the cost. shares_to_buy = shares[row['symbol']]",
"clock.timestamp > next_market_time: next_market_time = clock.next_open bought_today = False sold_today = False print(\"Market",
"= row['price'] * shares_to_buy portfolio_amount -= cost cal_index += 1 # Print market",
"Run a backtesting session using the provided parameters start_value = float(sys.argv[2]) testing_days =",
"if timeframe else \\ [symbol, start, end] tasks.append(get_data_method(data_type)(*args)) if minor >= 8: results.extend(",
"list(filter(lambda x: max_stock_price >= snapshot[ x].latest_trade.p >= min_stock_price if snapshot[x] and snapshot[ x].latest_trade",
"Make sure we aren't missing the most recent data. latest_bar = data.iloc[-1].name.to_pydatetime().astimezone( timezone('EST'))",
"have any orders, so we've obviously not done anything today. pass clock =",
"orders on a given day. orders = api.list_orders( after=api_format(datetime.today() - timedelta(days=1)), limit=400, status='all'",
"in symbols[i:i + step_size]: args = [symbol, start, end, timeframe.value] if timeframe else",
"We use this for live trading. def get_ratings(api, algo_time, datasets=None): ratings = pd.DataFrame(columns=['symbol',",
"if volume_stdev == 0: # The data for the stock might be low",
"# worth the day after we bought it. def get_value_of_assets(api, shares_bought, on_date): if",
"return_exceptions=True)) else: results.extend(await gather_with_concurrency(500, *tasks)) bad_requests = 0 for response in results: if",
"the provided parameters start_value = float(sys.argv[2]) testing_days = int(sys.argv[3]) portfolio_value = backtest(api, testing_days,",
"datasets: futures.append(executor.submit(_process_dataset, *( dataset, algo_time, start, end, window_size, index))) done = False while",
"= asyncio.get_event_loop() if sys.argv[1] == 'backtest': # so the backtests go faster executor",
"if isinstance(response, Exception): print(f\"Got an error: {response}\") elif not len(response[1]): bad_requests += 1",
"elif not len(response[1]): bad_requests += 1 print(f\"Total of {len(results)} {data_type}, and {bad_requests} \"",
"dataset[1].truncate(after=end + timedelta(days=1))[ -window_size:] if data.empty or len(data) < window_size: return # Make",
"# Used while backtesting to find out how much our portfolio would have",
"shares = get_shares_to_buy(ratings, portfolio_amount) for _, row in ratings.iterrows(): # \"Buy\" our shares",
"on {}: {:0.2f} $'.format(calendar.date.strftime( '%Y-%m-%d'), portfolio_amount) ) if cal_index == len(calendars) - 2:",
"_process_dataset(dataset, algo_time, start, end, window_size, index): if isinstance(dataset, Exception): return symbol = dataset[0]",
"order.side == 'buy': bought_today = True # This handles an edge case where",
"if data_type == DataType.Bars: return rest.get_bars_async elif data_type == DataType.Trades: return rest.get_trades_async elif",
"stocks_to_hold is 200, so we shouldn't see more than 400 # orders on",
"alpaca_trade_api.rest_async import gather_with_concurrency, AsyncRest from alpaca_trade_api.entity_v2 import BarsV2 from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor",
"- latest_bar if gap_from_present.days > 1: return # Now, if the stock is",
"sys.argv[1] == 'backtest': # so the backtests go faster executor = ProcessPoolExecutor(10) else:",
"or sold positions today. If so, we don't want to do it again.",
"stock symbols to ratings and prices. # Note: If algo_time is None, the",
"print('S&P 500 change during backtesting window: {:.4f}%'.format( sp500_change * 100) ) return portfolio_amount",
"= False if clock.timestamp > next_market_time: next_market_time = clock.next_open bought_today = False sold_today",
"futures: if not f.done(): done = False break time.sleep(0.1) for f in futures:",
"calendars[-1].date).isoformat(), TimeFrame.Day)) for calendar in calendars: # See how much we got back",
"return # Now, if the stock is within our target range, rate it.",
"if not f.done(): done = False break time.sleep(0.1) for f in futures: res",
"step_size): tasks = [] for symbol in symbols[i:i + step_size]: args = [symbol,",
"DataType(str, Enum): Bars = \"Bars\" Trades = \"Trades\" Quotes = \"Quotes\" def get_data_method(data_type:",
"end.isoformat(), TimeFrame.Day)) futures = [] for dataset in datasets: futures.append(executor.submit(_process_dataset, *( dataset, algo_time,",
"asyncio.get_event_loop() if sys.argv[1] == 'backtest': # so the backtests go faster executor =",
"days_to_test, portfolio_amount): # This is the collection of stocks that will be used",
"symbol in symbols[i:i + step_size]: args = [symbol, start, end, timeframe.value] if timeframe",
"# We don't have any orders, so we've obviously not done anything today.",
"= get_ratings( api, None ) shares_to_buy = get_shares_to_buy(ratings, portfolio_cash) for symbol in shares_to_buy:",
"stocks with prices in this range will be considered. max_stock_price = 26 min_stock_price",
"algo_time, datasets=None): ratings = pd.DataFrame(columns=['symbol', 'rating', 'price']) index = 0 window_size = 5",
"False while not done: done = True for f in futures: if not",
"= sys.version_info.minor if major < 3 or minor < 6: raise Exception('asyncio is",
"0: # The data for the stock might be low quality. return #",
"import Enum import pytz from datetime import datetime, timedelta from pytz import timezone",
"timezone stocks_to_hold = 20 # Max 200 # Only stocks with prices in",
"do anything. clock = api.get_clock() if clock.is_open and not bought_today: if sold_today: #",
"start = end - timedelta( days=window_size + 10) # make sure we don't",
"the volume's deviation from the previous 5 days and # momentum. Returns a",
"get_ratings( api, None ) shares_to_buy = get_shares_to_buy(ratings, portfolio_cash) for symbol in shares_to_buy: if",
"We'll sell our shares just a minute after the market opens. if time_after_open.seconds",
"end of the backtesting window. break # Get the ratings for a particular",
"print('Portfolio change: {:.4f}%'.format(portfolio_change * 100)) elif sys.argv[1] == 'run': run_live(api) else: print('Error: Unrecognized",
"gap_from_present = algo_time - latest_bar if gap_from_present.days > 1: return # Now, if",
"clock.next_open.time().isoformat()) # We'll sell our shares just a minute after the market opens.",
"out how much our portfolio would have been # worth the day after",
"start_value) portfolio_change = (portfolio_value - start_value) / start_value print('Portfolio change: {:.4f}%'.format(portfolio_change * 100))",
"it. price = data.iloc[-1].close if price <= max_stock_price and price >= min_stock_price: price_change",
"period results = loop.run_until_complete( get_historic_bars(['SPY'], api_format(calendars[0].date), api_format(calendars[-1].date), TimeFrame.Day)) sp500_change = (results[0][1].iloc[-1].close - results[0][1].iloc[",
"\"Quotes\" def get_data_method(data_type: DataType): if data_type == DataType.Bars: return rest.get_bars_async elif data_type ==",
"[symbol, start, end] tasks.append(get_data_method(data_type)(*args)) if minor >= 8: results.extend( await asyncio.gather(*tasks, return_exceptions=True)) else:",
"it fails so give it a shot few more times try: barset =",
"/ data.iloc[0].close * volume_factor if rating > 0: return { 'symbol': symbol, 'rating':",
"= float(api.get_account().cash) ratings = get_ratings( api, None ) shares_to_buy = get_shares_to_buy(ratings, portfolio_cash) for",
"market's TZ.) api_time_format = '%Y-%m-%dT%H:%M:%S.%f-04:00' loop = asyncio.get_event_loop() if sys.argv[1] == 'backtest': #",
"ratings = pd.DataFrame(columns=['symbol', 'rating', 'price']) index = 0 window_size = 5 # The",
"# See if we've already bought or sold positions today. If so, we",
"return dt.strftime(api_time_format) def backtest(api, days_to_test, portfolio_amount): # This is the collection of stocks",
"row['price'] * shares_to_buy portfolio_amount -= cost cal_index += 1 # Print market (S&P500)",
"executor = ProcessPoolExecutor(1) class DataType(str, Enum): Bars = \"Bars\" Trades = \"Trades\" Quotes",
"shares_to_buy portfolio_amount -= cost cal_index += 1 # Print market (S&P500) return for",
"= data.iloc[-1].volume - data.iloc[-2].volume volume_factor = volume_change / volume_stdev # Rating = Number",
"*tasks)) bad_requests = 0 for response in results: if isinstance(response, Exception): print(f\"Got an",
"= algo_time.date().strftime(api_time_format) end = pd.Timestamp(formatted_time) else: end = pytz.timezone(\"America/New_York\").localize(pd.Timestamp('now')) start = end -",
"= backtest(api, testing_days, start_value) portfolio_change = (portfolio_value - start_value) / start_value print('Portfolio change:",
"if not datasets: assets = api.list_assets(status=\"active\") assets = [asset for asset in assets",
"api.submit_order( symbol=symbol, qty=shares_to_buy[symbol], side='buy', type='market', time_in_force='day' ) print('Positions bought.') bought_today = True else:",
"to get data\") sys.exit(-1) for symbol in shares_bought: df = barset[symbol] if not",
"clock = api.get_clock() if clock.is_open and not bought_today: if sold_today: # Wait to",
"+ timedelta(days=1))[ -window_size:] if data.empty or len(data) < window_size: return # Make sure",
"== 0: return 0 total_value = 0 formatted_date = api_format(on_date) num_tries = 3",
"try: # The max stocks_to_hold is 200, so we shouldn't see more than",
"use this for live trading. def get_ratings(api, algo_time, datasets=None): ratings = pd.DataFrame(columns=['symbol', 'rating',",
"print_waiting = False while True: # We'll wait until the market's open to",
"fails so give it a shot few more times try: barset = loop.run_until_complete(",
"couple minutes before market close. if time_until_close.seconds <= 120: print('Buying positions...') portfolio_cash =",
"minor = sys.version_info.minor if major < 3 or minor < 6: raise Exception('asyncio",
"isinstance(response, Exception): print(f\"Got an error: {response}\") elif not len(response[1]): bad_requests += 1 print(f\"Total",
"'symbol': symbol, 'rating': price_change / data.iloc[ 0].close * volume_factor, 'price': price } #",
"Note: If algo_time is None, the API's default behavior of the current time",
"to sell our old positions before buying new ones. time_after_open = pd.Timestamp( clock.timestamp.time().isoformat())",
"200 # Only stocks with prices in this range will be considered. max_stock_price",
"asset in assets if asset.tradable] symbols = [s.symbol for s in assets] snapshot",
"msg = f\"Getting {data_type} data for {len(symbols)} symbols\" msg += f\", timeframe: {timeframe}\"",
"if not df.empty: total_value += shares_bought[symbol] * df.iloc[0].open return total_value def run_live(api): #",
"concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor import pandas as pd import statistics import sys import",
"volume_change = data.iloc[-1].volume - data.iloc[-2].volume volume_factor = volume_change / volume_stdev # Rating =",
"don't want to do it again. # Useful in case the script is",
"= list(filter(lambda x: max_stock_price >= snapshot[ x].latest_trade.p >= min_stock_price if snapshot[x] and snapshot[",
"while num_tries > 0: # sometimes it fails so give it a shot",
"{:0.2f} $'.format(calendar.date.strftime( '%Y-%m-%d'), portfolio_amount) ) if cal_index == len(calendars) - 2: # -2",
"to do anything. clock = api.get_clock() if clock.is_open and not bought_today: if sold_today:",
"min_stock_price = 6 # API datetimes will match this format. (-04:00 represents the",
"{} cal_index = 0 assets = api.list_assets(status=\"active\") assets = [asset for asset in",
"find out how much our portfolio would have been # worth the day",
"specify a command; either \"run\" or \"backtest ' '<cash balance> <number of days",
"shares = {} cal_index = 0 assets = api.list_assets(status=\"active\") assets = [asset for",
"got back by holding the last day's picks overnight portfolio_amount += get_value_of_assets(api, shares,",
"standard deviations * momentum. rating = price_change / data.iloc[0].close * volume_factor if rating",
"in assets] snapshot = api.get_snapshots(symbols) symbols = list(filter(lambda x: max_stock_price >= snapshot[ x].latest_trade.p",
"< 6: raise Exception('asyncio is not support in your python version') msg =",
"/ total_rating * portfolio / row['price'] ) return shares # Returns a string",
"algo_time - latest_bar if gap_from_present.days > 1: return # Now, if the stock",
"'backtest': # so the backtests go faster executor = ProcessPoolExecutor(10) else: executor =",
"import TimeFrame from alpaca_trade_api.rest_async import gather_with_concurrency, AsyncRest from alpaca_trade_api.entity_v2 import BarsV2 from concurrent.futures",
"start, end, window_size, index): if isinstance(dataset, Exception): return symbol = dataset[0] data =",
"# We've reached the end of the backtesting window. break # Get the",
"window. calendars = api.get_calendar( start=beginning.strftime(\"%Y-%m-%d\"), end=now.strftime(\"%Y-%m-%d\") ) shares = {} cal_index = 0",
"and price >= min_stock_price: price_change = price - data.iloc[0].close # Calculate standard deviation",
"# right before the market closes. sold_today = True break else: sold_today =",
"= f\"Getting {data_type} data for {len(symbols)} symbols\" msg += f\", timeframe: {timeframe}\" if",
"TimeFrame.Day)) futures = [] for dataset in datasets: futures.append(executor.submit(_process_dataset, *( dataset, algo_time, start,",
"for _, row in ratings_df.iterrows(): shares[row['symbol']] = int( row['rating'] / total_rating * portfolio",
"# Print market (S&P500) return for the time period results = loop.run_until_complete( get_historic_bars(['SPY'],",
"if num_tries <= 0: print(\"Error trying to get data\") sys.exit(-1) for symbol in",
"False sold_today = False print_waiting = False while True: # We'll wait until",
"= pd.Timestamp( clock.timestamp.time().isoformat()) - pd.Timestamp( clock.next_open.time().isoformat()) # We'll sell our shares just a",
"of stocks that will be used for backtesting. assets = api.list_assets() now =",
"== 'buy': bought_today = True # This handles an edge case where the",
"prices in this range will be considered. max_stock_price = 26 min_stock_price = 6",
"python version') msg = f\"Getting {data_type} data for {len(symbols)} symbols\" msg += f\",",
"api_time_format = '%Y-%m-%dT%H:%M:%S.%f-04:00' loop = asyncio.get_event_loop() if sys.argv[1] == 'backtest': # so the",
"bought or sold positions today. If so, we don't want to do it",
"start.isoformat(), end.isoformat(), TimeFrame.Day)) futures = [] for dataset in datasets: futures.append(executor.submit(_process_dataset, *( dataset,",
"ratings = ratings.sort_values('rating', ascending=False) ratings = ratings.reset_index(drop=True) return ratings[:stocks_to_hold] def get_shares_to_buy(ratings_df, portfolio): total_rating",
"yet # We've reached the end of the backtesting window. break # Get",
"volume_stdev == 0: # The data for the stock might be low quality.",
"= api.list_assets() now = datetime.now(timezone('EST')) beginning = now - timedelta(days=days_to_test) # The calendars",
"msg += f\", timeframe: {timeframe}\" if timeframe else \"\" msg += f\" between",
"data.iloc[0].close # Calculate standard deviation of previous volumes volume_stdev = data.iloc[:-1].volume.std() if volume_stdev",
"loop.run_until_complete( get_historic_bars( symbols[:], pytz.timezone(\"America/New_York\").localize( calendars[0].date - timedelta(days=10)).isoformat(), pytz.timezone(\"America/New_York\").localize( calendars[-1].date).isoformat(), TimeFrame.Day)) for calendar in",
"= 0 assets = api.list_assets(status=\"active\") assets = [asset for asset in assets if",
"- results[0][1].iloc[ 0].close) / results[0][1].iloc[0].close print('S&P 500 change during backtesting window: {:.4f}%'.format( sp500_change",
"if gap_from_present.days > 1: return # Now, if the stock is within our",
"want to do it again. # Useful in case the script is restarted",
"\"\" msg += f\" between dates: start={start}, end={end}\" print(msg) step_size = 1000 results",
"int(sys.argv[3]) portfolio_value = backtest(api, testing_days, start_value) portfolio_change = (portfolio_value - start_value) / start_value",
"assets = api.list_assets(status=\"active\") assets = [asset for asset in assets if asset.tradable] symbols",
"not df.empty: total_value += shares_bought[symbol] * df.iloc[0].open return total_value def run_live(api): # See",
"price <= max_stock_price and price >= min_stock_price: price_change = price - data.iloc[0].close #",
"= False break time.sleep(0.1) for f in futures: res = f.result() if res:",
"futures.append(executor.submit(_process_dataset, *( dataset, algo_time, start, end, window_size, index))) done = False while not",
"backtesting. assets = api.list_assets() now = datetime.now(timezone('EST')) beginning = now - timedelta(days=days_to_test) #",
"old positions before buying new ones. time_after_open = pd.Timestamp( clock.timestamp.time().isoformat()) - pd.Timestamp( clock.next_open.time().isoformat())",
"on_date).isoformat(), TimeFrame.Day)) barset = dict(barset) break except Exception as e: num_tries -= 1",
"the cost. shares_to_buy = shares[row['symbol']] cost = row['price'] * shares_to_buy portfolio_amount -= cost",
"else: if sys.argv[1] == 'backtest': # Run a backtesting session using the provided",
"# orders on a given day. orders = api.list_orders( after=api_format(datetime.today() - timedelta(days=1)), limit=400,",
"print(\"Error trying to get data\") sys.exit(-1) for symbol in shares_bought: df = barset[symbol]",
"and prices. # Note: If algo_time is None, the API's default behavior of",
"print_waiting = False if not print_waiting: print_waiting = True print(\"Waiting for next market",
"snapshot[x] and snapshot[ x].latest_trade else False, snapshot)) data = loop.run_until_complete( get_historic_bars( symbols[:], pytz.timezone(\"America/New_York\").localize(",
"# Rating = Number of volume standard deviations * momentum. rating = price_change",
"== 0: # The data for the stock might be low quality. return",
"num_tries <= 0: print(\"Error trying to get data\") sys.exit(-1) for symbol in shares_bought:",
"= api_format(on_date) num_tries = 3 while num_tries > 0: # sometimes it fails",
") print('Positions bought.') bought_today = True else: # We need to sell our",
"rest = AsyncRest() if len(sys.argv) < 2: print( 'Error: please specify a command;",
"get_ratings(api, algo_time, datasets=None): ratings = pd.DataFrame(columns=['symbol', 'rating', 'price']) index = 0 window_size =",
"buying new ones. time_after_open = pd.Timestamp( clock.timestamp.time().isoformat()) - pd.Timestamp( clock.next_open.time().isoformat()) # We'll sell",
"'buy': bought_today = True # This handles an edge case where the script",
"# Wait to buy time_until_close = clock.next_close - clock.timestamp # We'll buy our",
"if __name__ == '__main__': api = tradeapi.REST() rest = AsyncRest() if len(sys.argv) <",
"day's picks overnight portfolio_amount += get_value_of_assets(api, shares, calendar.date) print('Portfolio value on {}: {:0.2f}",
"We'll buy our shares a couple minutes before market close. if time_until_close.seconds <=",
"the day after we bought it. def get_value_of_assets(api, shares_bought, on_date): if len(shares_bought.keys()) ==",
"will be used. We use this for live trading. def get_ratings(api, algo_time, datasets=None):",
"gather_with_concurrency(500, *tasks)) bad_requests = 0 for response in results: if isinstance(response, Exception): print(f\"Got",
"return shares # Returns a string version of a timestamp compatible with the",
"{data_type} data for {len(symbols)} symbols\" msg += f\", timeframe: {timeframe}\" if timeframe else",
"shouldn't see more than 400 # orders on a given day. orders =",
"True break else: sold_today = True except: # We don't have any orders,",
"len(sys.argv) < 2: print( 'Error: please specify a command; either \"run\" or \"backtest",
"snapshot = api.get_snapshots(symbols) symbols = list(filter(lambda x: max_stock_price >= snapshot[ x].latest_trade.p >= min_stock_price",
"results[0][1].iloc[0].close print('S&P 500 change during backtesting window: {:.4f}%'.format( sp500_change * 100) ) return",
"of a timestamp compatible with the Alpaca API. def api_format(dt): return dt.strftime(api_time_format) def",
"TimeFrame): return await get_historic_data_base(symbols, DataType.Bars, start, end, timeframe) def _process_dataset(dataset, algo_time, start, end,",
"if cal_index == len(calendars) - 2: # -2 because we don't have today's",
"yesterday. volume_change = data.iloc[-1].volume - data.iloc[-2].volume volume_factor = volume_change / volume_stdev # Rating",
"ones. time_after_open = pd.Timestamp( clock.timestamp.time().isoformat()) - pd.Timestamp( clock.next_open.time().isoformat()) # We'll sell our shares",
"print(\"Waiting for next market day...\") time.sleep(30) if __name__ == '__main__': api = tradeapi.REST()",
"(S&P500) return for the time period results = loop.run_until_complete( get_historic_bars(['SPY'], api_format(calendars[0].date), api_format(calendars[-1].date), TimeFrame.Day))",
"price = data.iloc[-1].close if price <= max_stock_price and price >= min_stock_price: price_change =",
"be low quality. return # Then, compare it to the change in volume",
"= barset[symbol] if not df.empty: total_value += shares_bought[symbol] * df.iloc[0].open return total_value def",
"our shares just a minute after the market opens. if time_after_open.seconds >= 60:",
"portfolio_amount += get_value_of_assets(api, shares, calendar.date) print('Portfolio value on {}: {:0.2f} $'.format(calendar.date.strftime( '%Y-%m-%d'), portfolio_amount)",
">= min_stock_price: price_change = price - data.iloc[0].close # Calculate standard deviation of previous",
"else \"\" msg += f\" between dates: start={start}, end={end}\" print(msg) step_size = 1000",
"for live trading. def get_ratings(api, algo_time, datasets=None): ratings = pd.DataFrame(columns=['symbol', 'rating', 'price']) index",
"True: # We'll wait until the market's open to do anything. clock =",
"Open\") print_waiting = False if not print_waiting: print_waiting = True print(\"Waiting for next",
"until the market's open to do anything. clock = api.get_clock() if clock.is_open and",
"print('Buying positions...') portfolio_cash = float(api.get_account().cash) ratings = get_ratings( api, None ) shares_to_buy =",
"formatted_time = None if algo_time is not None: # Convert the time to",
"{}: {:0.2f} $'.format(calendar.date.strftime( '%Y-%m-%d'), portfolio_amount) ) if cal_index == len(calendars) - 2: #",
"# Returns a string version of a timestamp compatible with the Alpaca API.",
"The max stocks_to_hold is 200, so we shouldn't see more than 400 #",
"# We'll sell our shares just a minute after the market opens. if",
"trading. def get_ratings(api, algo_time, datasets=None): ratings = pd.DataFrame(columns=['symbol', 'rating', 'price']) index = 0",
"get_shares_to_buy(ratings_df, portfolio): total_rating = ratings_df['rating'].sum() shares = {} for _, row in ratings_df.iterrows():",
"return { 'symbol': symbol, 'rating': price_change / data.iloc[ 0].close * volume_factor, 'price': price",
"it to the change in volume since yesterday. volume_change = data.iloc[-1].volume - data.iloc[-2].volume",
"api_time_format) formatted_time = algo_time.date().strftime(api_time_format) end = pd.Timestamp(formatted_time) else: end = pytz.timezone(\"America/New_York\").localize(pd.Timestamp('now')) start =",
"# Max 200 # Only stocks with prices in this range will be",
"formatted_date = api_format(on_date) num_tries = 3 while num_tries > 0: # sometimes it",
"None, the API's default behavior of the current time # as `end` will",
"api = tradeapi.REST() rest = AsyncRest() if len(sys.argv) < 2: print( 'Error: please",
"backtests go faster executor = ProcessPoolExecutor(10) else: executor = ProcessPoolExecutor(1) class DataType(str, Enum):",
"would have been # worth the day after we bought it. def get_value_of_assets(api,",
"data.iloc[:-1].volume.std() if volume_stdev == 0: # The data for the stock might be",
"bought_today = False sold_today = False try: # The max stocks_to_hold is 200,",
"positions.') api.close_all_positions() sold_today = True else: sold_today = False if clock.timestamp > next_market_time:",
"for f in futures: if not f.done(): done = False break time.sleep(0.1) for",
"market day...\") time.sleep(30) if __name__ == '__main__': api = tradeapi.REST() rest = AsyncRest()",
"We've reached the end of the backtesting window. break # Get the ratings",
"days=window_size + 10) # make sure we don't hit weekends if not datasets:",
"# so the backtests go faster executor = ProcessPoolExecutor(10) else: executor = ProcessPoolExecutor(1)",
"row in ratings_df.iterrows(): shares[row['symbol']] = int( row['rating'] / total_rating * portfolio / row['price']",
"= sys.version_info.major minor = sys.version_info.minor if major < 3 or minor < 6:",
"price_change / data.iloc[0].close * volume_factor if rating > 0: return { 'symbol': symbol,",
"{len(results)} {data_type}, and {bad_requests} \" f\"empty responses.\") return results async def get_historic_bars(symbols, start,",
"a particular day ratings = \\ get_ratings(api, timezone('EST').localize(calendar.date), datasets=data) shares = get_shares_to_buy(ratings, portfolio_amount)",
"from datetime import datetime, timedelta from pytz import timezone stocks_to_hold = 20 #",
"100) ) return portfolio_amount # Used while backtesting to find out how much",
"pytz import timezone stocks_to_hold = 20 # Max 200 # Only stocks with",
"a couple minutes before market close. if time_until_close.seconds <= 120: print('Buying positions...') portfolio_cash",
"is restarted during market hours. bought_today = False sold_today = False try: #",
"snapshot[ x].latest_trade else False, snapshot)) datasets = loop.run_until_complete( get_historic_bars(symbols, start.isoformat(), end.isoformat(), TimeFrame.Day)) futures",
"string version of a timestamp compatible with the Alpaca API. def api_format(dt): return",
"api.get_clock() if clock.is_open and not bought_today: if sold_today: # Wait to buy time_until_close",
"== 'backtest': # so the backtests go faster executor = ProcessPoolExecutor(10) else: executor",
"next_market_time: next_market_time = clock.next_open bought_today = False sold_today = False print(\"Market Open\") print_waiting",
"in assets if asset.tradable] symbols = [s.symbol for s in assets] snapshot =",
"The number of days of data to consider formatted_time = None if algo_time",
"edge case where the script is restarted # right before the market closes.",
"data.iloc[-1].volume - data.iloc[-2].volume volume_factor = volume_change / volume_stdev # Rating = Number of",
"standard deviation of previous volumes volume_stdev = data.iloc[:-1].volume.std() if volume_stdev == 0: #",
"the current time # as `end` will be used. We use this for",
"_, row in ratings.iterrows(): # \"Buy\" our shares on that day and subtract",
"if sys.argv[1] == 'backtest': # so the backtests go faster executor = ProcessPoolExecutor(10)",
"buy time_until_close = clock.next_close - clock.timestamp # We'll buy our shares a couple",
"to the change in volume since yesterday. volume_change = data.iloc[-1].volume - data.iloc[-2].volume volume_factor",
"min_stock_price: price_change = price - data.iloc[0].close # Calculate standard deviation of previous volumes",
"= loop.run_until_complete( get_historic_bars(list(shares_bought.keys()), pytz.timezone(\"America/New_York\").localize( on_date).isoformat(), pytz.timezone(\"America/New_York\").localize( on_date).isoformat(), TimeFrame.Day)) barset = dict(barset) break except",
"closures during our backtesting window. calendars = api.get_calendar( start=beginning.strftime(\"%Y-%m-%d\"), end=now.strftime(\"%Y-%m-%d\") ) shares =",
"- pd.Timestamp( clock.next_open.time().isoformat()) # We'll sell our shares just a minute after the",
"format. (-04:00 represents the market's TZ.) api_time_format = '%Y-%m-%dT%H:%M:%S.%f-04:00' loop = asyncio.get_event_loop() if",
"shares_to_buy[symbol] > 0: api.submit_order( symbol=symbol, qty=shares_to_buy[symbol], side='buy', type='market', time_in_force='day' ) print('Positions bought.') bought_today",
"True # This handles an edge case where the script is restarted #",
"results.extend( await asyncio.gather(*tasks, return_exceptions=True)) else: results.extend(await gather_with_concurrency(500, *tasks)) bad_requests = 0 for response",
"= True except: # We don't have any orders, so we've obviously not",
"we don't have today's data yet # We've reached the end of the",
"False if not print_waiting: print_waiting = True print(\"Waiting for next market day...\") time.sleep(30)",
"timedelta( days=window_size + 10) # make sure we don't hit weekends if not",
"[asset for asset in assets if asset.tradable] symbols = [s.symbol for s in",
"end, window_size, index): if isinstance(dataset, Exception): return symbol = dataset[0] data = dataset[1].truncate(after=end",
"5 days and # momentum. Returns a dataframe mapping stock symbols to ratings",
"> next_market_time: next_market_time = clock.next_open bought_today = False sold_today = False print(\"Market Open\")",
"pd.Timestamp( clock.next_open.time().isoformat()) # We'll sell our shares just a minute after the market",
"symbols = [s.symbol for s in assets] snapshot = api.get_snapshots(symbols) symbols = list(filter(lambda",
"ratings = ratings.reset_index(drop=True) return ratings[:stocks_to_hold] def get_shares_to_buy(ratings_df, portfolio): total_rating = ratings_df['rating'].sum() shares =",
"close. if time_until_close.seconds <= 120: print('Buying positions...') portfolio_cash = float(api.get_account().cash) ratings = get_ratings(",
"pytz.timezone(\"America/New_York\").localize( calendars[0].date - timedelta(days=10)).isoformat(), pytz.timezone(\"America/New_York\").localize( calendars[-1].date).isoformat(), TimeFrame.Day)) for calendar in calendars: # See",
"Useful in case the script is restarted during market hours. bought_today = False",
"index): if isinstance(dataset, Exception): return symbol = dataset[0] data = dataset[1].truncate(after=end + timedelta(days=1))[",
"live trading. def get_ratings(api, algo_time, datasets=None): ratings = pd.DataFrame(columns=['symbol', 'rating', 'price']) index =",
"price - data.iloc[0].close # Calculate standard deviation of previous volumes volume_stdev = data.iloc[:-1].volume.std()",
"False break time.sleep(0.1) for f in futures: res = f.result() if res: ratings",
"give it a shot few more times try: barset = loop.run_until_complete( get_historic_bars(list(shares_bought.keys()), pytz.timezone(\"America/New_York\").localize(",
"if not print_waiting: print_waiting = True print(\"Waiting for next market day...\") time.sleep(30) if",
"print('Positions bought.') bought_today = True else: # We need to sell our old",
"= True else: sold_today = False if clock.timestamp > next_market_time: next_market_time = clock.next_open",
"anything today. pass clock = api.get_clock() next_market_time = clock.next_open bought_today = False sold_today",
"our backtesting window. calendars = api.get_calendar( start=beginning.strftime(\"%Y-%m-%d\"), end=now.strftime(\"%Y-%m-%d\") ) shares = {} cal_index",
"if order.side == 'buy': bought_today = True # This handles an edge case",
"days and # momentum. Returns a dataframe mapping stock symbols to ratings and",
"testing_days = int(sys.argv[3]) portfolio_value = backtest(api, testing_days, start_value) portfolio_change = (portfolio_value - start_value)",
"the time to something compatable with the Alpaca API. start_time = (algo_time.date() -",
"symbol=symbol, qty=shares_to_buy[symbol], side='buy', type='market', time_in_force='day' ) print('Positions bought.') bought_today = True else: #",
"anything. clock = api.get_clock() if clock.is_open and not bought_today: if sold_today: # Wait",
"for order in orders: if order.side == 'buy': bought_today = True # This",
"orders: if order.side == 'buy': bought_today = True # This handles an edge",
"if shares_to_buy[symbol] > 0: api.submit_order( symbol=symbol, qty=shares_to_buy[symbol], side='buy', type='market', time_in_force='day' ) print('Positions bought.')",
"for s in assets] snapshot = api.get_snapshots(symbols) symbols = list(filter(lambda x: max_stock_price >=",
"def get_ratings(api, algo_time, datasets=None): ratings = pd.DataFrame(columns=['symbol', 'rating', 'price']) index = 0 window_size",
"= dataset[1].truncate(after=end + timedelta(days=1))[ -window_size:] if data.empty or len(data) < window_size: return #",
"backtesting window: {:.4f}%'.format( sp500_change * 100) ) return portfolio_amount # Used while backtesting",
"gather_with_concurrency, AsyncRest from alpaca_trade_api.entity_v2 import BarsV2 from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor import pandas",
"type: {data_type}\") async def get_historic_data_base(symbols, data_type: DataType, start, end, timeframe: TimeFrame = None):",
"support in your python version') msg = f\"Getting {data_type} data for {len(symbols)} symbols\"",
"on that day and subtract the cost. shares_to_buy = shares[row['symbol']] cost = row['price']",
"window_size, index): if isinstance(dataset, Exception): return symbol = dataset[0] data = dataset[1].truncate(after=end +",
"deviation of previous volumes volume_stdev = data.iloc[:-1].volume.std() if volume_stdev == 0: # The",
"BarsV2 from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor import pandas as pd import statistics import",
"end = pytz.timezone(\"America/New_York\").localize(pd.Timestamp('now')) start = end - timedelta( days=window_size + 10) # make",
"x: max_stock_price >= snapshot[ x].latest_trade.p >= min_stock_price if snapshot[x] and snapshot[ x].latest_trade else",
"api_format(on_date) num_tries = 3 while num_tries > 0: # sometimes it fails so",
"with the Alpaca API. start_time = (algo_time.date() - timedelta(days=window_size)).strftime( api_time_format) formatted_time = algo_time.date().strftime(api_time_format)",
"max_stock_price >= snapshot[ x].latest_trade.p >= min_stock_price if snapshot[x] and snapshot[ x].latest_trade else False,",
"sys import time import asyncio from enum import Enum import pytz from datetime",
"loop = asyncio.get_event_loop() if sys.argv[1] == 'backtest': # so the backtests go faster",
"the backtesting window. break # Get the ratings for a particular day ratings",
"minutes before market close. if time_until_close.seconds <= 120: print('Buying positions...') portfolio_cash = float(api.get_account().cash)",
"num_tries = 3 while num_tries > 0: # sometimes it fails so give",
"day after we bought it. def get_value_of_assets(api, shares_bought, on_date): if len(shares_bought.keys()) == 0:",
"recent data. latest_bar = data.iloc[-1].name.to_pydatetime().astimezone( timezone('EST')) if algo_time: gap_from_present = algo_time - latest_bar",
"len(calendars) - 2: # -2 because we don't have today's data yet #",
"sold_today = False print_waiting = False while True: # We'll wait until the",
"row in ratings.iterrows(): # \"Buy\" our shares on that day and subtract the",
"= False print_waiting = False while True: # We'll wait until the market's",
"data to consider formatted_time = None if algo_time is not None: # Convert",
"is restarted # right before the market closes. sold_today = True break else:",
"so we shouldn't see more than 400 # orders on a given day.",
"= loop.run_until_complete( get_historic_bars(['SPY'], api_format(calendars[0].date), api_format(calendars[-1].date), TimeFrame.Day)) sp500_change = (results[0][1].iloc[-1].close - results[0][1].iloc[ 0].close) /",
"return portfolio_amount # Used while backtesting to find out how much our portfolio",
"qty=shares_to_buy[symbol], side='buy', type='market', time_in_force='day' ) print('Positions bought.') bought_today = True else: # We",
"= True print(\"Waiting for next market day...\") time.sleep(30) if __name__ == '__main__': api",
"algo_time is None, the API's default behavior of the current time # as",
"order in orders: if order.side == 'buy': bought_today = True # This handles",
"calendars[0].date - timedelta(days=10)).isoformat(), pytz.timezone(\"America/New_York\").localize( calendars[-1].date).isoformat(), TimeFrame.Day)) for calendar in calendars: # See how",
"tasks.append(get_data_method(data_type)(*args)) if minor >= 8: results.extend( await asyncio.gather(*tasks, return_exceptions=True)) else: results.extend(await gather_with_concurrency(500, *tasks))",
"500 change during backtesting window: {:.4f}%'.format( sp500_change * 100) ) return portfolio_amount #",
"for i in range(0, len(symbols), step_size): tasks = [] for symbol in symbols[i:i",
"get_historic_bars(symbols, start.isoformat(), end.isoformat(), TimeFrame.Day)) futures = [] for dataset in datasets: futures.append(executor.submit(_process_dataset, *(",
"futures: res = f.result() if res: ratings = ratings.append(res, ignore_index=True) ratings = ratings.sort_values('rating',",
"barset = dict(barset) break except Exception as e: num_tries -= 1 if num_tries",
"value on {}: {:0.2f} $'.format(calendar.date.strftime( '%Y-%m-%d'), portfolio_amount) ) if cal_index == len(calendars) -",
"not len(response[1]): bad_requests += 1 print(f\"Total of {len(results)} {data_type}, and {bad_requests} \" f\"empty",
"window_size, index))) done = False while not done: done = True for f",
"rate it. price = data.iloc[-1].close if price <= max_stock_price and price >= min_stock_price:",
"# Rate stocks based on the volume's deviation from the previous 5 days",
"volume since yesterday. volume_change = data.iloc[-1].volume - data.iloc[-2].volume volume_factor = volume_change / volume_stdev",
"0: print(\"Error trying to get data\") sys.exit(-1) for symbol in shares_bought: df =",
"get_historic_bars( symbols[:], pytz.timezone(\"America/New_York\").localize( calendars[0].date - timedelta(days=10)).isoformat(), pytz.timezone(\"America/New_York\").localize( calendars[-1].date).isoformat(), TimeFrame.Day)) for calendar in calendars:",
"Number of volume standard deviations * momentum. rating = price_change / data.iloc[0].close *",
"args = [symbol, start, end, timeframe.value] if timeframe else \\ [symbol, start, end]",
"symbol = dataset[0] data = dataset[1].truncate(after=end + timedelta(days=1))[ -window_size:] if data.empty or len(data)",
"if snapshot[x] and snapshot[ x].latest_trade else False, snapshot)) datasets = loop.run_until_complete( get_historic_bars(symbols, start.isoformat(),",
"len(response[1]): bad_requests += 1 print(f\"Total of {len(results)} {data_type}, and {bad_requests} \" f\"empty responses.\")",
"- timedelta( days=window_size + 10) # make sure we don't hit weekends if",
"# The number of days of data to consider formatted_time = None if",
"API. start_time = (algo_time.date() - timedelta(days=window_size)).strftime( api_time_format) formatted_time = algo_time.date().strftime(api_time_format) end = pd.Timestamp(formatted_time)",
"start, end, timeframe) def _process_dataset(dataset, algo_time, start, end, window_size, index): if isinstance(dataset, Exception):",
"total_value += shares_bought[symbol] * df.iloc[0].open return total_value def run_live(api): # See if we've",
"data.empty or len(data) < window_size: return # Make sure we aren't missing the",
"== len(calendars) - 2: # -2 because we don't have today's data yet",
"testing_days, start_value) portfolio_change = (portfolio_value - start_value) / start_value print('Portfolio change: {:.4f}%'.format(portfolio_change *",
"loop.run_until_complete( get_historic_bars(symbols, start.isoformat(), end.isoformat(), TimeFrame.Day)) futures = [] for dataset in datasets: futures.append(executor.submit(_process_dataset,",
"not datasets: assets = api.list_assets(status=\"active\") assets = [asset for asset in assets if",
"min_stock_price if snapshot[x] and snapshot[ x].latest_trade else False, snapshot)) data = loop.run_until_complete( get_historic_bars(",
"0 for response in results: if isinstance(response, Exception): print(f\"Got an error: {response}\") elif",
"timedelta(days=window_size)).strftime( api_time_format) formatted_time = algo_time.date().strftime(api_time_format) end = pd.Timestamp(formatted_time) else: end = pytz.timezone(\"America/New_York\").localize(pd.Timestamp('now')) start",
"{:.4f}%'.format(portfolio_change * 100)) elif sys.argv[1] == 'run': run_live(api) else: print('Error: Unrecognized command '",
"early # market closures during our backtesting window. calendars = api.get_calendar( start=beginning.strftime(\"%Y-%m-%d\"), end=now.strftime(\"%Y-%m-%d\")",
"than 400 # orders on a given day. orders = api.list_orders( after=api_format(datetime.today() -",
"= [] for i in range(0, len(symbols), step_size): tasks = [] for symbol",
"is within our target range, rate it. price = data.iloc[-1].close if price <=",
"volume_factor if rating > 0: return { 'symbol': symbol, 'rating': price_change / data.iloc[",
"'rating', 'price']) index = 0 window_size = 5 # The number of days",
"used. We use this for live trading. def get_ratings(api, algo_time, datasets=None): ratings =",
"# Convert the time to something compatable with the Alpaca API. start_time =",
"the backtests go faster executor = ProcessPoolExecutor(10) else: executor = ProcessPoolExecutor(1) class DataType(str,",
"today's data yet # We've reached the end of the backtesting window. break",
"volume_factor, 'price': price } # Rate stocks based on the volume's deviation from",
"it again. # Useful in case the script is restarted during market hours.",
"futures = [] for dataset in datasets: futures.append(executor.submit(_process_dataset, *( dataset, algo_time, start, end,",
"= ratings.sort_values('rating', ascending=False) ratings = ratings.reset_index(drop=True) return ratings[:stocks_to_hold] def get_shares_to_buy(ratings_df, portfolio): total_rating =",
"Returns a string version of a timestamp compatible with the Alpaca API. def",
"{response}\") elif not len(response[1]): bad_requests += 1 print(f\"Total of {len(results)} {data_type}, and {bad_requests}",
"print_waiting = True print(\"Waiting for next market day...\") time.sleep(30) if __name__ == '__main__':",
"back by holding the last day's picks overnight portfolio_amount += get_value_of_assets(api, shares, calendar.date)",
"total_rating = ratings_df['rating'].sum() shares = {} for _, row in ratings_df.iterrows(): shares[row['symbol']] =",
"float(api.get_account().cash) ratings = get_ratings( api, None ) shares_to_buy = get_shares_to_buy(ratings, portfolio_cash) for symbol",
"= 0 formatted_date = api_format(on_date) num_tries = 3 while num_tries > 0: #",
"== '__main__': api = tradeapi.REST() rest = AsyncRest() if len(sys.argv) < 2: print(",
"AsyncRest() if len(sys.argv) < 2: print( 'Error: please specify a command; either \"run\"",
"backtesting session using the provided parameters start_value = float(sys.argv[2]) testing_days = int(sys.argv[3]) portfolio_value",
"sold_today: # Wait to buy time_until_close = clock.next_close - clock.timestamp # We'll buy",
"clock.timestamp # We'll buy our shares a couple minutes before market close. if",
"= int( row['rating'] / total_rating * portfolio / row['price'] ) return shares #",
"executor = ProcessPoolExecutor(10) else: executor = ProcessPoolExecutor(1) class DataType(str, Enum): Bars = \"Bars\"",
"sys.exit(-1) for symbol in shares_bought: df = barset[symbol] if not df.empty: total_value +=",
"f\"Getting {data_type} data for {len(symbols)} symbols\" msg += f\", timeframe: {timeframe}\" if timeframe",
"= clock.next_open bought_today = False sold_today = False print(\"Market Open\") print_waiting = False",
"tradeapi from alpaca_trade_api.rest import TimeFrame from alpaca_trade_api.rest_async import gather_with_concurrency, AsyncRest from alpaca_trade_api.entity_v2 import",
"this range will be considered. max_stock_price = 26 min_stock_price = 6 # API",
"formatted_time = algo_time.date().strftime(api_time_format) end = pd.Timestamp(formatted_time) else: end = pytz.timezone(\"America/New_York\").localize(pd.Timestamp('now')) start = end",
"- 2: # -2 because we don't have today's data yet # We've",
"{len(symbols)} symbols\" msg += f\", timeframe: {timeframe}\" if timeframe else \"\" msg +=",
"gap_from_present.days > 1: return # Now, if the stock is within our target",
"need to sell our old positions before buying new ones. time_after_open = pd.Timestamp(",
"sold positions today. If so, we don't want to do it again. #",
"will let us skip over market holidays and handle early # market closures",
"# Note: If algo_time is None, the API's default behavior of the current",
"= 0 for response in results: if isinstance(response, Exception): print(f\"Got an error: {response}\")",
"for a particular day ratings = \\ get_ratings(api, timezone('EST').localize(calendar.date), datasets=data) shares = get_shares_to_buy(ratings,",
"on_date).isoformat(), pytz.timezone(\"America/New_York\").localize( on_date).isoformat(), TimeFrame.Day)) barset = dict(barset) break except Exception as e: num_tries",
"start={start}, end={end}\" print(msg) step_size = 1000 results = [] for i in range(0,",
"= price - data.iloc[0].close # Calculate standard deviation of previous volumes volume_stdev =",
"if len(shares_bought.keys()) == 0: return 0 total_value = 0 formatted_date = api_format(on_date) num_tries",
"timeframe.value] if timeframe else \\ [symbol, start, end] tasks.append(get_data_method(data_type)(*args)) if minor >= 8:",
"False while True: # We'll wait until the market's open to do anything.",
"= AsyncRest() if len(sys.argv) < 2: print( 'Error: please specify a command; either",
"not support in your python version') msg = f\"Getting {data_type} data for {len(symbols)}",
"minor < 6: raise Exception('asyncio is not support in your python version') msg",
"time period results = loop.run_until_complete( get_historic_bars(['SPY'], api_format(calendars[0].date), api_format(calendars[-1].date), TimeFrame.Day)) sp500_change = (results[0][1].iloc[-1].close -",
"False, snapshot)) datasets = loop.run_until_complete( get_historic_bars(symbols, start.isoformat(), end.isoformat(), TimeFrame.Day)) futures = [] for",
"orders = api.list_orders( after=api_format(datetime.today() - timedelta(days=1)), limit=400, status='all' ) for order in orders:",
"{ 'symbol': symbol, 'rating': price_change / data.iloc[ 0].close * volume_factor, 'price': price }",
"len(symbols), step_size): tasks = [] for symbol in symbols[i:i + step_size]: args =",
"data = dataset[1].truncate(after=end + timedelta(days=1))[ -window_size:] if data.empty or len(data) < window_size: return",
"range(0, len(symbols), step_size): tasks = [] for symbol in symbols[i:i + step_size]: args",
"clock.next_close - clock.timestamp # We'll buy our shares a couple minutes before market",
"None): major = sys.version_info.major minor = sys.version_info.minor if major < 3 or minor",
"results.extend(await gather_with_concurrency(500, *tasks)) bad_requests = 0 for response in results: if isinstance(response, Exception):",
"will be used for backtesting. assets = api.list_assets() now = datetime.now(timezone('EST')) beginning =",
"-= 1 if num_tries <= 0: print(\"Error trying to get data\") sys.exit(-1) for",
"during backtesting window: {:.4f}%'.format( sp500_change * 100) ) return portfolio_amount # Used while",
"Calculate standard deviation of previous volumes volume_stdev = data.iloc[:-1].volume.std() if volume_stdev == 0:",
"= now - timedelta(days=days_to_test) # The calendars API will let us skip over",
"if isinstance(dataset, Exception): return symbol = dataset[0] data = dataset[1].truncate(after=end + timedelta(days=1))[ -window_size:]",
"10) # make sure we don't hit weekends if not datasets: assets =",
"step_size]: args = [symbol, start, end, timeframe.value] if timeframe else \\ [symbol, start,",
"with prices in this range will be considered. max_stock_price = 26 min_stock_price =",
"-window_size:] if data.empty or len(data) < window_size: return # Make sure we aren't",
"/ row['price'] ) return shares # Returns a string version of a timestamp",
"change during backtesting window: {:.4f}%'.format( sp500_change * 100) ) return portfolio_amount # Used",
"assets = api.list_assets() now = datetime.now(timezone('EST')) beginning = now - timedelta(days=days_to_test) # The",
"next_market_time = clock.next_open bought_today = False sold_today = False print(\"Market Open\") print_waiting =",
"api_format(calendars[0].date), api_format(calendars[-1].date), TimeFrame.Day)) sp500_change = (results[0][1].iloc[-1].close - results[0][1].iloc[ 0].close) / results[0][1].iloc[0].close print('S&P 500",
"and snapshot[ x].latest_trade else False, snapshot)) data = loop.run_until_complete( get_historic_bars( symbols[:], pytz.timezone(\"America/New_York\").localize( calendars[0].date",
"# See how much we got back by holding the last day's picks",
"our portfolio would have been # worth the day after we bought it.",
"\\ get_ratings(api, timezone('EST').localize(calendar.date), datasets=data) shares = get_shares_to_buy(ratings, portfolio_amount) for _, row in ratings.iterrows():",
"volume_stdev # Rating = Number of volume standard deviations * momentum. rating =",
"= '%Y-%m-%dT%H:%M:%S.%f-04:00' loop = asyncio.get_event_loop() if sys.argv[1] == 'backtest': # so the backtests",
"we got back by holding the last day's picks overnight portfolio_amount += get_value_of_assets(api,",
"data.iloc[-2].volume volume_factor = volume_change / volume_stdev # Rating = Number of volume standard",
"# Run a backtesting session using the provided parameters start_value = float(sys.argv[2]) testing_days",
"# We'll buy our shares a couple minutes before market close. if time_until_close.seconds",
"100)) elif sys.argv[1] == 'run': run_live(api) else: print('Error: Unrecognized command ' + sys.argv[1])",
"stocks_to_hold = 20 # Max 200 # Only stocks with prices in this",
"shares = {} for _, row in ratings_df.iterrows(): shares[row['symbol']] = int( row['rating'] /",
"go faster executor = ProcessPoolExecutor(10) else: executor = ProcessPoolExecutor(1) class DataType(str, Enum): Bars",
"momentum. rating = price_change / data.iloc[0].close * volume_factor if rating > 0: return",
"res: ratings = ratings.append(res, ignore_index=True) ratings = ratings.sort_values('rating', ascending=False) ratings = ratings.reset_index(drop=True) return",
"print(msg) step_size = 1000 results = [] for i in range(0, len(symbols), step_size):",
"return results async def get_historic_bars(symbols, start, end, timeframe: TimeFrame): return await get_historic_data_base(symbols, DataType.Bars,",
"buy our shares a couple minutes before market close. if time_until_close.seconds <= 120:",
"before market close. if time_until_close.seconds <= 120: print('Buying positions...') portfolio_cash = float(api.get_account().cash) ratings",
"api, None ) shares_to_buy = get_shares_to_buy(ratings, portfolio_cash) for symbol in shares_to_buy: if shares_to_buy[symbol]",
"timedelta(days=days_to_test) # The calendars API will let us skip over market holidays and",
"False sold_today = False try: # The max stocks_to_hold is 200, so we",
"= (results[0][1].iloc[-1].close - results[0][1].iloc[ 0].close) / results[0][1].iloc[0].close print('S&P 500 change during backtesting window:",
"window_size = 5 # The number of days of data to consider formatted_time",
"x].latest_trade else False, snapshot)) data = loop.run_until_complete( get_historic_bars( symbols[:], pytz.timezone(\"America/New_York\").localize( calendars[0].date - timedelta(days=10)).isoformat(),",
"import gather_with_concurrency, AsyncRest from alpaca_trade_api.entity_v2 import BarsV2 from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor import",
"time import asyncio from enum import Enum import pytz from datetime import datetime,",
"* momentum. rating = price_change / data.iloc[0].close * volume_factor if rating > 0:",
"= 6 # API datetimes will match this format. (-04:00 represents the market's",
"results[0][1].iloc[ 0].close) / results[0][1].iloc[0].close print('S&P 500 change during backtesting window: {:.4f}%'.format( sp500_change *",
"script is restarted during market hours. bought_today = False sold_today = False try:",
"behavior of the current time # as `end` will be used. We use",
"Exception): print(f\"Got an error: {response}\") elif not len(response[1]): bad_requests += 1 print(f\"Total of",
"in case the script is restarted during market hours. bought_today = False sold_today",
"times try: barset = loop.run_until_complete( get_historic_bars(list(shares_bought.keys()), pytz.timezone(\"America/New_York\").localize( on_date).isoformat(), pytz.timezone(\"America/New_York\").localize( on_date).isoformat(), TimeFrame.Day)) barset =",
"break time.sleep(0.1) for f in futures: res = f.result() if res: ratings =",
"= get_shares_to_buy(ratings, portfolio_cash) for symbol in shares_to_buy: if shares_to_buy[symbol] > 0: api.submit_order( symbol=symbol,",
"print('Liquidating positions.') api.close_all_positions() sold_today = True else: sold_today = False if clock.timestamp >",
"target range, rate it. price = data.iloc[-1].close if price <= max_stock_price and price",
"previous volumes volume_stdev = data.iloc[:-1].volume.std() if volume_stdev == 0: # The data for",
"{bad_requests} \" f\"empty responses.\") return results async def get_historic_bars(symbols, start, end, timeframe: TimeFrame):",
"break except Exception as e: num_tries -= 1 if num_tries <= 0: print(\"Error",
"Used while backtesting to find out how much our portfolio would have been",
"sell our old positions before buying new ones. time_after_open = pd.Timestamp( clock.timestamp.time().isoformat()) -",
"symbols\" msg += f\", timeframe: {timeframe}\" if timeframe else \"\" msg += f\"",
"current time # as `end` will be used. We use this for live",
"don't hit weekends if not datasets: assets = api.list_assets(status=\"active\") assets = [asset for",
"except Exception as e: num_tries -= 1 if num_tries <= 0: print(\"Error trying",
"= 3 while num_tries > 0: # sometimes it fails so give it",
"False, snapshot)) data = loop.run_until_complete( get_historic_bars( symbols[:], pytz.timezone(\"America/New_York\").localize( calendars[0].date - timedelta(days=10)).isoformat(), pytz.timezone(\"America/New_York\").localize( calendars[-1].date).isoformat(),",
"hit weekends if not datasets: assets = api.list_assets(status=\"active\") assets = [asset for asset",
"[] for dataset in datasets: futures.append(executor.submit(_process_dataset, *( dataset, algo_time, start, end, window_size, index)))",
"# The calendars API will let us skip over market holidays and handle",
"= f.result() if res: ratings = ratings.append(res, ignore_index=True) ratings = ratings.sort_values('rating', ascending=False) ratings",
"bought_today = True # This handles an edge case where the script is",
"based on the volume's deviation from the previous 5 days and # momentum.",
"= True # This handles an edge case where the script is restarted",
"end, timeframe) def _process_dataset(dataset, algo_time, start, end, window_size, index): if isinstance(dataset, Exception): return",
"API's default behavior of the current time # as `end` will be used.",
"import pandas as pd import statistics import sys import time import asyncio from",
"time.sleep(0.1) for f in futures: res = f.result() if res: ratings = ratings.append(res,",
"and not bought_today: if sold_today: # Wait to buy time_until_close = clock.next_close -",
"of previous volumes volume_stdev = data.iloc[:-1].volume.std() if volume_stdev == 0: # The data",
"been # worth the day after we bought it. def get_value_of_assets(api, shares_bought, on_date):",
"so give it a shot few more times try: barset = loop.run_until_complete( get_historic_bars(list(shares_bought.keys()),",
"= algo_time - latest_bar if gap_from_present.days > 1: return # Now, if the",
"True for f in futures: if not f.done(): done = False break time.sleep(0.1)",
") for order in orders: if order.side == 'buy': bought_today = True #",
"= api.get_clock() if clock.is_open and not bought_today: if sold_today: # Wait to buy",
"see more than 400 # orders on a given day. orders = api.list_orders(",
"momentum. Returns a dataframe mapping stock symbols to ratings and prices. # Note:",
"if clock.is_open and not bought_today: if sold_today: # Wait to buy time_until_close =",
"0 assets = api.list_assets(status=\"active\") assets = [asset for asset in assets if asset.tradable]",
"This is the collection of stocks that will be used for backtesting. assets",
"represents the market's TZ.) api_time_format = '%Y-%m-%dT%H:%M:%S.%f-04:00' loop = asyncio.get_event_loop() if sys.argv[1] ==",
"in futures: if not f.done(): done = False break time.sleep(0.1) for f in",
"if asset.tradable] symbols = [s.symbol for s in assets] snapshot = api.get_snapshots(symbols) symbols",
"raise Exception('asyncio is not support in your python version') msg = f\"Getting {data_type}",
"cost cal_index += 1 # Print market (S&P500) return for the time period",
"import datetime, timedelta from pytz import timezone stocks_to_hold = 20 # Max 200",
"bought.') bought_today = True else: # We need to sell our old positions",
"timedelta from pytz import timezone stocks_to_hold = 20 # Max 200 # Only",
"or minor < 6: raise Exception('asyncio is not support in your python version')",
"loop.run_until_complete( get_historic_bars(list(shares_bought.keys()), pytz.timezone(\"America/New_York\").localize( on_date).isoformat(), pytz.timezone(\"America/New_York\").localize( on_date).isoformat(), TimeFrame.Day)) barset = dict(barset) break except Exception",
"2: print( 'Error: please specify a command; either \"run\" or \"backtest ' '<cash",
"start_value print('Portfolio change: {:.4f}%'.format(portfolio_change * 100)) elif sys.argv[1] == 'run': run_live(api) else: print('Error:",
"in your python version') msg = f\"Getting {data_type} data for {len(symbols)} symbols\" msg",
"backtesting window. calendars = api.get_calendar( start=beginning.strftime(\"%Y-%m-%d\"), end=now.strftime(\"%Y-%m-%d\") ) shares = {} cal_index =",
"> 0: return { 'symbol': symbol, 'rating': price_change / data.iloc[ 0].close * volume_factor,",
"[] for symbol in symbols[i:i + step_size]: args = [symbol, start, end, timeframe.value]",
"-2 because we don't have today's data yet # We've reached the end",
"limit=400, status='all' ) for order in orders: if order.side == 'buy': bought_today =",
"calendar in calendars: # See how much we got back by holding the",
"0: api.submit_order( symbol=symbol, qty=shares_to_buy[symbol], side='buy', type='market', time_in_force='day' ) print('Positions bought.') bought_today = True",
"latest_bar if gap_from_present.days > 1: return # Now, if the stock is within",
"index = 0 window_size = 5 # The number of days of data",
"new ones. time_after_open = pd.Timestamp( clock.timestamp.time().isoformat()) - pd.Timestamp( clock.next_open.time().isoformat()) # We'll sell our",
"end, timeframe: TimeFrame): return await get_historic_data_base(symbols, DataType.Bars, start, end, timeframe) def _process_dataset(dataset, algo_time,",
"version') msg = f\"Getting {data_type} data for {len(symbols)} symbols\" msg += f\", timeframe:",
"end - timedelta( days=window_size + 10) # make sure we don't hit weekends",
"the Alpaca API. start_time = (algo_time.date() - timedelta(days=window_size)).strftime( api_time_format) formatted_time = algo_time.date().strftime(api_time_format) end",
"x].latest_trade.p >= min_stock_price if snapshot[x] and snapshot[ x].latest_trade else False, snapshot)) datasets =",
"'%Y-%m-%d'), portfolio_amount) ) if cal_index == len(calendars) - 2: # -2 because we",
"timestamp compatible with the Alpaca API. def api_format(dt): return dt.strftime(api_time_format) def backtest(api, days_to_test,",
"= False while not done: done = True for f in futures: if",
"rest.get_bars_async elif data_type == DataType.Trades: return rest.get_trades_async elif data_type == DataType.Quotes: return rest.get_quotes_async",
"time.sleep(30) if __name__ == '__main__': api = tradeapi.REST() rest = AsyncRest() if len(sys.argv)",
"else: # We need to sell our old positions before buying new ones.",
"to something compatable with the Alpaca API. start_time = (algo_time.date() - timedelta(days=window_size)).strftime( api_time_format)",
"if data.empty or len(data) < window_size: return # Make sure we aren't missing",
"s in assets] snapshot = api.get_snapshots(symbols) symbols = list(filter(lambda x: max_stock_price >= snapshot[",
"not bought_today: if sold_today: # Wait to buy time_until_close = clock.next_close - clock.timestamp",
"is 200, so we shouldn't see more than 400 # orders on a",
"not None: # Convert the time to something compatable with the Alpaca API.",
"done: done = True for f in futures: if not f.done(): done =",
"volume_stdev = data.iloc[:-1].volume.std() if volume_stdev == 0: # The data for the stock",
"# Make sure we aren't missing the most recent data. latest_bar = data.iloc[-1].name.to_pydatetime().astimezone(",
"0: return 0 total_value = 0 formatted_date = api_format(on_date) num_tries = 3 while",
"an error: {response}\") elif not len(response[1]): bad_requests += 1 print(f\"Total of {len(results)} {data_type},",
"run_live(api): # See if we've already bought or sold positions today. If so,",
"= None): major = sys.version_info.major minor = sys.version_info.minor if major < 3 or",
"as tradeapi from alpaca_trade_api.rest import TimeFrame from alpaca_trade_api.rest_async import gather_with_concurrency, AsyncRest from alpaca_trade_api.entity_v2",
"DataType, start, end, timeframe: TimeFrame = None): major = sys.version_info.major minor = sys.version_info.minor",
"much we got back by holding the last day's picks overnight portfolio_amount +=",
"of data to consider formatted_time = None if algo_time is not None: #",
"overnight portfolio_amount += get_value_of_assets(api, shares, calendar.date) print('Portfolio value on {}: {:0.2f} $'.format(calendar.date.strftime( '%Y-%m-%d'),",
"df.iloc[0].open return total_value def run_live(api): # See if we've already bought or sold",
"'__main__': api = tradeapi.REST() rest = AsyncRest() if len(sys.argv) < 2: print( 'Error:",
"else False, snapshot)) data = loop.run_until_complete( get_historic_bars( symbols[:], pytz.timezone(\"America/New_York\").localize( calendars[0].date - timedelta(days=10)).isoformat(), pytz.timezone(\"America/New_York\").localize(",
"f in futures: res = f.result() if res: ratings = ratings.append(res, ignore_index=True) ratings",
"return rest.get_bars_async elif data_type == DataType.Trades: return rest.get_trades_async elif data_type == DataType.Quotes: return",
"= True break else: sold_today = True except: # We don't have any",
"Alpaca API. def api_format(dt): return dt.strftime(api_time_format) def backtest(api, days_to_test, portfolio_amount): # This is",
"price } # Rate stocks based on the volume's deviation from the previous",
"make sure we don't hit weekends if not datasets: assets = api.list_assets(status=\"active\") assets",
"data.iloc[0].close * volume_factor if rating > 0: return { 'symbol': symbol, 'rating': price_change",
"shares_to_buy = shares[row['symbol']] cost = row['price'] * shares_to_buy portfolio_amount -= cost cal_index +=",
"(algo_time.date() - timedelta(days=window_size)).strftime( api_time_format) formatted_time = algo_time.date().strftime(api_time_format) end = pd.Timestamp(formatted_time) else: end =",
"to ratings and prices. # Note: If algo_time is None, the API's default",
"def run_live(api): # See if we've already bought or sold positions today. If",
"cost. shares_to_buy = shares[row['symbol']] cost = row['price'] * shares_to_buy portfolio_amount -= cost cal_index",
") shares_to_buy = get_shares_to_buy(ratings, portfolio_cash) for symbol in shares_to_buy: if shares_to_buy[symbol] > 0:",
"backtest(api, days_to_test, portfolio_amount): # This is the collection of stocks that will be",
"- data.iloc[-2].volume volume_factor = volume_change / volume_stdev # Rating = Number of volume",
"session using the provided parameters start_value = float(sys.argv[2]) testing_days = int(sys.argv[3]) portfolio_value =",
"timedelta(days=1)), limit=400, status='all' ) for order in orders: if order.side == 'buy': bought_today",
"+ 10) # make sure we don't hit weekends if not datasets: assets",
"0: # sometimes it fails so give it a shot few more times",
"have today's data yet # We've reached the end of the backtesting window.",
"= 20 # Max 200 # Only stocks with prices in this range",
"sometimes it fails so give it a shot few more times try: barset",
"it. def get_value_of_assets(api, shares_bought, on_date): if len(shares_bought.keys()) == 0: return 0 total_value =",
"ignore_index=True) ratings = ratings.sort_values('rating', ascending=False) ratings = ratings.reset_index(drop=True) return ratings[:stocks_to_hold] def get_shares_to_buy(ratings_df, portfolio):",
"shares_to_buy = get_shares_to_buy(ratings, portfolio_cash) for symbol in shares_to_buy: if shares_to_buy[symbol] > 0: api.submit_order(",
"done anything today. pass clock = api.get_clock() next_market_time = clock.next_open bought_today = False",
"1 # Print market (S&P500) return for the time period results = loop.run_until_complete(",
"26 min_stock_price = 6 # API datetimes will match this format. (-04:00 represents",
"dataset[0] data = dataset[1].truncate(after=end + timedelta(days=1))[ -window_size:] if data.empty or len(data) < window_size:",
"= shares[row['symbol']] cost = row['price'] * shares_to_buy portfolio_amount -= cost cal_index += 1",
"f\", timeframe: {timeframe}\" if timeframe else \"\" msg += f\" between dates: start={start},",
"= dataset[0] data = dataset[1].truncate(after=end + timedelta(days=1))[ -window_size:] if data.empty or len(data) <",
"_, row in ratings_df.iterrows(): shares[row['symbol']] = int( row['rating'] / total_rating * portfolio /",
"pd.DataFrame(columns=['symbol', 'rating', 'price']) index = 0 window_size = 5 # The number of",
"= 1000 results = [] for i in range(0, len(symbols), step_size): tasks =",
"is not None: # Convert the time to something compatable with the Alpaca",
"from alpaca_trade_api.rest_async import gather_with_concurrency, AsyncRest from alpaca_trade_api.entity_v2 import BarsV2 from concurrent.futures import ThreadPoolExecutor,",
"us skip over market holidays and handle early # market closures during our",
"given day. orders = api.list_orders( after=api_format(datetime.today() - timedelta(days=1)), limit=400, status='all' ) for order",
"calendars = api.get_calendar( start=beginning.strftime(\"%Y-%m-%d\"), end=now.strftime(\"%Y-%m-%d\") ) shares = {} cal_index = 0 assets",
"today. If so, we don't want to do it again. # Useful in",
"before buying new ones. time_after_open = pd.Timestamp( clock.timestamp.time().isoformat()) - pd.Timestamp( clock.next_open.time().isoformat()) # We'll",
"barset[symbol] if not df.empty: total_value += shares_bought[symbol] * df.iloc[0].open return total_value def run_live(api):",
"start_value = float(sys.argv[2]) testing_days = int(sys.argv[3]) portfolio_value = backtest(api, testing_days, start_value) portfolio_change =",
"If so, we don't want to do it again. # Useful in case",
"time to something compatable with the Alpaca API. start_time = (algo_time.date() - timedelta(days=window_size)).strftime(",
"of the current time # as `end` will be used. We use this",
"API datetimes will match this format. (-04:00 represents the market's TZ.) api_time_format =",
"<gh_stars>1-10 import alpaca_trade_api as tradeapi from alpaca_trade_api.rest import TimeFrame from alpaca_trade_api.rest_async import gather_with_concurrency,",
"for next market day...\") time.sleep(30) if __name__ == '__main__': api = tradeapi.REST() rest",
"we've obviously not done anything today. pass clock = api.get_clock() next_market_time = clock.next_open",
"* 100)) elif sys.argv[1] == 'run': run_live(api) else: print('Error: Unrecognized command ' +",
"+= f\", timeframe: {timeframe}\" if timeframe else \"\" msg += f\" between dates:",
"> 0: # sometimes it fails so give it a shot few more",
"timezone('EST').localize(calendar.date), datasets=data) shares = get_shares_to_buy(ratings, portfolio_amount) for _, row in ratings.iterrows(): # \"Buy\"",
"market (S&P500) return for the time period results = loop.run_until_complete( get_historic_bars(['SPY'], api_format(calendars[0].date), api_format(calendars[-1].date),",
"0 total_value = 0 formatted_date = api_format(on_date) num_tries = 3 while num_tries >",
"timeframe: {timeframe}\" if timeframe else \"\" msg += f\" between dates: start={start}, end={end}\"",
"provided parameters start_value = float(sys.argv[2]) testing_days = int(sys.argv[3]) portfolio_value = backtest(api, testing_days, start_value)",
"import BarsV2 from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor import pandas as pd import statistics",
"dataset in datasets: futures.append(executor.submit(_process_dataset, *( dataset, algo_time, start, end, window_size, index))) done =",
"for backtesting. assets = api.list_assets() now = datetime.now(timezone('EST')) beginning = now - timedelta(days=days_to_test)",
"restarted during market hours. bought_today = False sold_today = False try: # The",
"algo_time: gap_from_present = algo_time - latest_bar if gap_from_present.days > 1: return # Now,",
"True else: # We need to sell our old positions before buying new",
"bought_today: if sold_today: # Wait to buy time_until_close = clock.next_close - clock.timestamp #",
"{:.4f}%'.format( sp500_change * 100) ) return portfolio_amount # Used while backtesting to find",
"print( 'Error: please specify a command; either \"run\" or \"backtest ' '<cash balance>",
"price_change = price - data.iloc[0].close # Calculate standard deviation of previous volumes volume_stdev",
"while True: # We'll wait until the market's open to do anything. clock",
"snapshot[ x].latest_trade.p >= min_stock_price if snapshot[x] and snapshot[ x].latest_trade else False, snapshot)) data",
"on a given day. orders = api.list_orders( after=api_format(datetime.today() - timedelta(days=1)), limit=400, status='all' )",
"' '<cash balance> <number of days to test>\".') else: if sys.argv[1] == 'backtest':",
"This handles an edge case where the script is restarted # right before",
"60: print('Liquidating positions.') api.close_all_positions() sold_today = True else: sold_today = False if clock.timestamp",
"# We need to sell our old positions before buying new ones. time_after_open",
"match this format. (-04:00 represents the market's TZ.) api_time_format = '%Y-%m-%dT%H:%M:%S.%f-04:00' loop =",
"that will be used for backtesting. assets = api.list_assets() now = datetime.now(timezone('EST')) beginning",
"# API datetimes will match this format. (-04:00 represents the market's TZ.) api_time_format",
"and handle early # market closures during our backtesting window. calendars = api.get_calendar(",
"= dict(barset) break except Exception as e: num_tries -= 1 if num_tries <=",
"alpaca_trade_api as tradeapi from alpaca_trade_api.rest import TimeFrame from alpaca_trade_api.rest_async import gather_with_concurrency, AsyncRest from",
"== DataType.Trades: return rest.get_trades_async elif data_type == DataType.Quotes: return rest.get_quotes_async else: raise Exception(f\"Unsupoported",
"ascending=False) ratings = ratings.reset_index(drop=True) return ratings[:stocks_to_hold] def get_shares_to_buy(ratings_df, portfolio): total_rating = ratings_df['rating'].sum() shares",
"bought_today = False sold_today = False print(\"Market Open\") print_waiting = False if not",
"next_market_time = clock.next_open bought_today = False sold_today = False print_waiting = False while",
"alpaca_trade_api.entity_v2 import BarsV2 from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor import pandas as pd import",
"# Get the ratings for a particular day ratings = \\ get_ratings(api, timezone('EST').localize(calendar.date),",
"portfolio_cash = float(api.get_account().cash) ratings = get_ratings( api, None ) shares_to_buy = get_shares_to_buy(ratings, portfolio_cash)",
"end = pd.Timestamp(formatted_time) else: end = pytz.timezone(\"America/New_York\").localize(pd.Timestamp('now')) start = end - timedelta( days=window_size",
"= api.list_assets(status=\"active\") assets = [asset for asset in assets if asset.tradable] symbols =",
"assets] snapshot = api.get_snapshots(symbols) symbols = list(filter(lambda x: max_stock_price >= snapshot[ x].latest_trade.p >=",
"start, end, timeframe: TimeFrame = None): major = sys.version_info.major minor = sys.version_info.minor if",
"print(f\"Got an error: {response}\") elif not len(response[1]): bad_requests += 1 print(f\"Total of {len(results)}",
"Enum import pytz from datetime import datetime, timedelta from pytz import timezone stocks_to_hold",
"-= cost cal_index += 1 # Print market (S&P500) return for the time",
"type='market', time_in_force='day' ) print('Positions bought.') bought_today = True else: # We need to",
"and subtract the cost. shares_to_buy = shares[row['symbol']] cost = row['price'] * shares_to_buy portfolio_amount",
"since yesterday. volume_change = data.iloc[-1].volume - data.iloc[-2].volume volume_factor = volume_change / volume_stdev #",
"beginning = now - timedelta(days=days_to_test) # The calendars API will let us skip",
"the market opens. if time_after_open.seconds >= 60: print('Liquidating positions.') api.close_all_positions() sold_today = True",
"the script is restarted during market hours. bought_today = False sold_today = False",
"/ results[0][1].iloc[0].close print('S&P 500 change during backtesting window: {:.4f}%'.format( sp500_change * 100) )",
"and snapshot[ x].latest_trade else False, snapshot)) datasets = loop.run_until_complete( get_historic_bars(symbols, start.isoformat(), end.isoformat(), TimeFrame.Day))",
"end, timeframe: TimeFrame = None): major = sys.version_info.major minor = sys.version_info.minor if major",
"shares_bought[symbol] * df.iloc[0].open return total_value def run_live(api): # See if we've already bought",
"import timezone stocks_to_hold = 20 # Max 200 # Only stocks with prices",
"an edge case where the script is restarted # right before the market",
"'price']) index = 0 window_size = 5 # The number of days of",
">= 8: results.extend( await asyncio.gather(*tasks, return_exceptions=True)) else: results.extend(await gather_with_concurrency(500, *tasks)) bad_requests = 0",
"within our target range, rate it. price = data.iloc[-1].close if price <= max_stock_price",
"- timedelta(days=1)), limit=400, status='all' ) for order in orders: if order.side == 'buy':",
"data yet # We've reached the end of the backtesting window. break #",
"portfolio_amount): # This is the collection of stocks that will be used for",
"ratings.reset_index(drop=True) return ratings[:stocks_to_hold] def get_shares_to_buy(ratings_df, portfolio): total_rating = ratings_df['rating'].sum() shares = {} for",
"using the provided parameters start_value = float(sys.argv[2]) testing_days = int(sys.argv[3]) portfolio_value = backtest(api,",
"pytz from datetime import datetime, timedelta from pytz import timezone stocks_to_hold = 20",
"and # momentum. Returns a dataframe mapping stock symbols to ratings and prices.",
"f\" between dates: start={start}, end={end}\" print(msg) step_size = 1000 results = [] for",
"in futures: res = f.result() if res: ratings = ratings.append(res, ignore_index=True) ratings =",
") return portfolio_amount # Used while backtesting to find out how much our",
"= api.list_orders( after=api_format(datetime.today() - timedelta(days=1)), limit=400, status='all' ) for order in orders: if",
"in ratings_df.iterrows(): shares[row['symbol']] = int( row['rating'] / total_rating * portfolio / row['price'] )",
"import time import asyncio from enum import Enum import pytz from datetime import",
"snapshot[x] and snapshot[ x].latest_trade else False, snapshot)) datasets = loop.run_until_complete( get_historic_bars(symbols, start.isoformat(), end.isoformat(),",
"again. # Useful in case the script is restarted during market hours. bought_today",
"return 0 total_value = 0 formatted_date = api_format(on_date) num_tries = 3 while num_tries",
"a string version of a timestamp compatible with the Alpaca API. def api_format(dt):",
"statistics import sys import time import asyncio from enum import Enum import pytz",
"bought_today = False sold_today = False print_waiting = False while True: # We'll",
"for symbol in shares_bought: df = barset[symbol] if not df.empty: total_value += shares_bought[symbol]",
"the end of the backtesting window. break # Get the ratings for a",
"algo_time.date().strftime(api_time_format) end = pd.Timestamp(formatted_time) else: end = pytz.timezone(\"America/New_York\").localize(pd.Timestamp('now')) start = end - timedelta(",
"'rating': price_change / data.iloc[ 0].close * volume_factor, 'price': price } # Rate stocks",
"bought it. def get_value_of_assets(api, shares_bought, on_date): if len(shares_bought.keys()) == 0: return 0 total_value",
"def get_data_method(data_type: DataType): if data_type == DataType.Bars: return rest.get_bars_async elif data_type == DataType.Trades:",
"dt.strftime(api_time_format) def backtest(api, days_to_test, portfolio_amount): # This is the collection of stocks that",
"a minute after the market opens. if time_after_open.seconds >= 60: print('Liquidating positions.') api.close_all_positions()",
"handle early # market closures during our backtesting window. calendars = api.get_calendar( start=beginning.strftime(\"%Y-%m-%d\"),",
"return await get_historic_data_base(symbols, DataType.Bars, start, end, timeframe) def _process_dataset(dataset, algo_time, start, end, window_size,",
"= [s.symbol for s in assets] snapshot = api.get_snapshots(symbols) symbols = list(filter(lambda x:",
"symbols = list(filter(lambda x: max_stock_price >= snapshot[ x].latest_trade.p >= min_stock_price if snapshot[x] and",
"max stocks_to_hold is 200, so we shouldn't see more than 400 # orders",
"and {bad_requests} \" f\"empty responses.\") return results async def get_historic_bars(symbols, start, end, timeframe:",
"'%Y-%m-%dT%H:%M:%S.%f-04:00' loop = asyncio.get_event_loop() if sys.argv[1] == 'backtest': # so the backtests go",
"might be low quality. return # Then, compare it to the change in",
"+= 1 print(f\"Total of {len(results)} {data_type}, and {bad_requests} \" f\"empty responses.\") return results",
"<number of days to test>\".') else: if sys.argv[1] == 'backtest': # Run a",
"time_until_close = clock.next_close - clock.timestamp # We'll buy our shares a couple minutes",
"API. def api_format(dt): return dt.strftime(api_time_format) def backtest(api, days_to_test, portfolio_amount): # This is the",
"print(f\"Total of {len(results)} {data_type}, and {bad_requests} \" f\"empty responses.\") return results async def",
"get_historic_data_base(symbols, data_type: DataType, start, end, timeframe: TimeFrame = None): major = sys.version_info.major minor",
"shares[row['symbol']] cost = row['price'] * shares_to_buy portfolio_amount -= cost cal_index += 1 #",
"= False sold_today = False try: # The max stocks_to_hold is 200, so",
"api_format(dt): return dt.strftime(api_time_format) def backtest(api, days_to_test, portfolio_amount): # This is the collection of",
"+= f\" between dates: start={start}, end={end}\" print(msg) step_size = 1000 results = []",
"datasets=None): ratings = pd.DataFrame(columns=['symbol', 'rating', 'price']) index = 0 window_size = 5 #",
"6 # API datetimes will match this format. (-04:00 represents the market's TZ.)",
"# Now, if the stock is within our target range, rate it. price",
"False print_waiting = False while True: # We'll wait until the market's open",
"shares_bought, on_date): if len(shares_bought.keys()) == 0: return 0 total_value = 0 formatted_date =",
"def get_value_of_assets(api, shares_bought, on_date): if len(shares_bought.keys()) == 0: return 0 total_value = 0",
"return symbol = dataset[0] data = dataset[1].truncate(after=end + timedelta(days=1))[ -window_size:] if data.empty or",
"api.close_all_positions() sold_today = True else: sold_today = False if clock.timestamp > next_market_time: next_market_time",
"for dataset in datasets: futures.append(executor.submit(_process_dataset, *( dataset, algo_time, start, end, window_size, index))) done",
"get_ratings(api, timezone('EST').localize(calendar.date), datasets=data) shares = get_shares_to_buy(ratings, portfolio_amount) for _, row in ratings.iterrows(): #",
"= 0 window_size = 5 # The number of days of data to",
"await get_historic_data_base(symbols, DataType.Bars, start, end, timeframe) def _process_dataset(dataset, algo_time, start, end, window_size, index):",
"responses.\") return results async def get_historic_bars(symbols, start, end, timeframe: TimeFrame): return await get_historic_data_base(symbols,",
"be considered. max_stock_price = 26 min_stock_price = 6 # API datetimes will match",
"'<cash balance> <number of days to test>\".') else: if sys.argv[1] == 'backtest': #"
] |
[
"<filename>alfacoins/__init__.py from .gateway import ALFACoins from .exceptions import APIException, ServerException __version__ = '0.1.0a2'"
] |
[
"# # Licensed under the Apache License, Version 2.0 (the \"License\"); # you",
"writing, software # distributed under the License is distributed on an \"AS IS\"",
"KIND, either express or implied. # See the License for the specific language",
"Unless required by applicable law or agreed to in writing, software # distributed",
"__init__(self): super().__init__() self.td = False self.last_value = None self.last_data = '' self.gpu_data =",
"False self.last_value = None self.last_data = '' self.gpu_data = {} def handle_starttag(self, tag,",
"You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #",
"the License is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR",
"# See the License for the specific language governing permissions and # limitations",
"License. # You may obtain a copy of the License at # #",
"Template import os from gpu_info import incompatible_arcs, gpu_compute_capability_to_arc basedir = os.path.dirname(os.path.abspath(__file__)) r =",
"= os.path.dirname(os.path.abspath(__file__)) r = request.urlopen('https://developer.nvidia.com/cuda-gpus') class GetGpuListFromNvidiaSite(HTMLParser): def __init__(self): super().__init__() self.td = False",
"request from html.parser import HTMLParser import re from mako.template import Template import os",
"if tag == 'td': self.td = True def handle_endtag(self, tag): if tag ==",
"True def handle_endtag(self, tag): if tag == 'td': if self.td: m = re.match(r'((\\d+)\\.(\\d+))',",
"self.last_data = '' self.gpu_data = {} def handle_starttag(self, tag, attrs): if tag ==",
"'incompatibale_gpu_list.py.tmpl') tmpl = Template(filename=fname) lines = tmpl.render(args=incompatible_gpus) with open(\"./python/src/nnabla_ext/cuda/incompatible_gpu_list.py\", 'w') as f: for",
"import Template import os from gpu_info import incompatible_arcs, gpu_compute_capability_to_arc basedir = os.path.dirname(os.path.abspath(__file__)) r",
"= '' name = self.last_value.lower().replace( 'nvidia ', '').replace('tesla ', '') # remove prefix",
"law or agreed to in writing, software # distributed under the License is",
"the License for the specific language governing permissions and # limitations under the",
"if self.td: m = re.match(r'((\\d+)\\.(\\d+))', self.last_data.strip()) if m: cap = m.group(1) cap_major =",
"compliance with the License. # You may obtain a copy of the License",
"cap) self.last_value = self.last_data.strip() self.last_data = '' self.td = False def handle_data(self, data):",
"None: print(f'Error: unknown capability [{cap}]') arch = '' name = self.last_value.lower().replace( 'nvidia ',",
"Template(filename=fname) lines = tmpl.render(args=incompatible_gpus) with open(\"./python/src/nnabla_ext/cuda/incompatible_gpu_list.py\", 'w') as f: for l in lines:",
"def __init__(self): super().__init__() self.td = False self.last_value = None self.last_data = '' self.gpu_data",
"HTMLParser import re from mako.template import Template import os from gpu_info import incompatible_arcs,",
"on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,",
"gpus_info = parser.gpu_data incompatible_gpus = {} for k in incompatible_arcs: if not incompatible_gpus.get(k):",
"this file except in compliance with the License. # You may obtain a",
"governing permissions and # limitations under the License. import urllib.request as request from",
"2021 Sony Corporation. # Copyright 2021 Sony Group Corporation. # # Licensed under",
"cap = m.group(1) cap_major = int(m.group(2)) cap_minor = int(m.group(3)) arch = gpu_compute_capability_to_arc.get(cap_major) if",
"the Apache License, Version 2.0 (the \"License\"); # you may not use this",
"you may not use this file except in compliance with the License. #",
"for the specific language governing permissions and # limitations under the License. import",
"the License. import urllib.request as request from html.parser import HTMLParser import re from",
"= {} def handle_starttag(self, tag, attrs): if tag == 'td': self.td = True",
"m: cap = m.group(1) cap_major = int(m.group(2)) cap_minor = int(m.group(3)) arch = gpu_compute_capability_to_arc.get(cap_major)",
"self.last_data.strip()) if m: cap = m.group(1) cap_major = int(m.group(2)) cap_minor = int(m.group(3)) arch",
"print(f'Error: unknown capability [{cap}]') arch = '' name = self.last_value.lower().replace( 'nvidia ', '').replace('tesla",
"self.td: self.last_data += data parser = GetGpuListFromNvidiaSite() parser.feed(r.read().decode()) gpus_info = parser.gpu_data incompatible_gpus =",
"of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable",
"incompatible_gpus.get(k): incompatible_gpus[k] = [] iarc = incompatible_arcs[k] for gpu_name in gpus_info.keys(): if gpus_info[gpu_name][0]",
"= re.match(r'((\\d+)\\.(\\d+))', self.last_data.strip()) if m: cap = m.group(1) cap_major = int(m.group(2)) cap_minor =",
"gpu_compute_capability_to_arc.get(cap_major) if arch is None: arch = gpu_compute_capability_to_arc.get( (cap_major, cap_minor)) if arch is",
"lines = tmpl.render(args=incompatible_gpus) with open(\"./python/src/nnabla_ext/cuda/incompatible_gpu_list.py\", 'w') as f: for l in lines: f.write(l)",
"data parser = GetGpuListFromNvidiaSite() parser.feed(r.read().decode()) gpus_info = parser.gpu_data incompatible_gpus = {} for k",
"re from mako.template import Template import os from gpu_info import incompatible_arcs, gpu_compute_capability_to_arc basedir",
"= int(m.group(3)) arch = gpu_compute_capability_to_arc.get(cap_major) if arch is None: arch = gpu_compute_capability_to_arc.get( (cap_major,",
"[{cap}]') arch = '' name = self.last_value.lower().replace( 'nvidia ', '').replace('tesla ', '') #",
"iarc: incompatible_gpus[k].append(gpu_name) fname = os.path.join(basedir, 'skel', 'incompatibale_gpu_list.py.tmpl') tmpl = Template(filename=fname) lines = tmpl.render(args=incompatible_gpus)",
"limitations under the License. import urllib.request as request from html.parser import HTMLParser import",
"is None: arch = gpu_compute_capability_to_arc.get( (cap_major, cap_minor)) if arch is None: print(f'Error: unknown",
"Copyright 2021 Sony Group Corporation. # # Licensed under the Apache License, Version",
"self.gpu_data[name] = (arch, cap) self.last_value = self.last_data.strip() self.last_data = '' self.td = False",
"ANY KIND, either express or implied. # See the License for the specific",
"self.last_value = None self.last_data = '' self.gpu_data = {} def handle_starttag(self, tag, attrs):",
"from mako.template import Template import os from gpu_info import incompatible_arcs, gpu_compute_capability_to_arc basedir =",
"self.last_data = '' self.td = False def handle_data(self, data): if self.td: self.last_data +=",
"== 'td': self.td = True def handle_endtag(self, tag): if tag == 'td': if",
"= int(m.group(2)) cap_minor = int(m.group(3)) arch = gpu_compute_capability_to_arc.get(cap_major) if arch is None: arch",
"in compliance with the License. # You may obtain a copy of the",
"= self.last_value.lower().replace( 'nvidia ', '').replace('tesla ', '') # remove prefix self.gpu_data[name] = (arch,",
"'').replace('tesla ', '') # remove prefix self.gpu_data[name] = (arch, cap) self.last_value = self.last_data.strip()",
"License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or",
"os.path.dirname(os.path.abspath(__file__)) r = request.urlopen('https://developer.nvidia.com/cuda-gpus') class GetGpuListFromNvidiaSite(HTMLParser): def __init__(self): super().__init__() self.td = False self.last_value",
"{} def handle_starttag(self, tag, attrs): if tag == 'td': self.td = True def",
"'td': if self.td: m = re.match(r'((\\d+)\\.(\\d+))', self.last_data.strip()) if m: cap = m.group(1) cap_major",
"gpu_compute_capability_to_arc basedir = os.path.dirname(os.path.abspath(__file__)) r = request.urlopen('https://developer.nvidia.com/cuda-gpus') class GetGpuListFromNvidiaSite(HTMLParser): def __init__(self): super().__init__() self.td",
"# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. #",
"import re from mako.template import Template import os from gpu_info import incompatible_arcs, gpu_compute_capability_to_arc",
"if m: cap = m.group(1) cap_major = int(m.group(2)) cap_minor = int(m.group(3)) arch =",
"use this file except in compliance with the License. # You may obtain",
"= '' self.td = False def handle_data(self, data): if self.td: self.last_data += data",
"import HTMLParser import re from mako.template import Template import os from gpu_info import",
"gpu_info import incompatible_arcs, gpu_compute_capability_to_arc basedir = os.path.dirname(os.path.abspath(__file__)) r = request.urlopen('https://developer.nvidia.com/cuda-gpus') class GetGpuListFromNvidiaSite(HTMLParser): def",
"at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed",
"= gpu_compute_capability_to_arc.get( (cap_major, cap_minor)) if arch is None: print(f'Error: unknown capability [{cap}]') arch",
"{} for k in incompatible_arcs: if not incompatible_gpus.get(k): incompatible_gpus[k] = [] iarc =",
"if self.td: self.last_data += data parser = GetGpuListFromNvidiaSite() parser.feed(r.read().decode()) gpus_info = parser.gpu_data incompatible_gpus",
"language governing permissions and # limitations under the License. import urllib.request as request",
"not use this file except in compliance with the License. # You may",
"int(m.group(2)) cap_minor = int(m.group(3)) arch = gpu_compute_capability_to_arc.get(cap_major) if arch is None: arch =",
"Sony Corporation. # Copyright 2021 Sony Group Corporation. # # Licensed under the",
"WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See",
"request.urlopen('https://developer.nvidia.com/cuda-gpus') class GetGpuListFromNvidiaSite(HTMLParser): def __init__(self): super().__init__() self.td = False self.last_value = None self.last_data",
"tag, attrs): if tag == 'td': self.td = True def handle_endtag(self, tag): if",
"(arch, cap) self.last_value = self.last_data.strip() self.last_data = '' self.td = False def handle_data(self,",
"cap_major = int(m.group(2)) cap_minor = int(m.group(3)) arch = gpu_compute_capability_to_arc.get(cap_major) if arch is None:",
"= self.last_data.strip() self.last_data = '' self.td = False def handle_data(self, data): if self.td:",
"= Template(filename=fname) lines = tmpl.render(args=incompatible_gpus) with open(\"./python/src/nnabla_ext/cuda/incompatible_gpu_list.py\", 'w') as f: for l in",
"(cap_major, cap_minor)) if arch is None: print(f'Error: unknown capability [{cap}]') arch = ''",
"arch is None: print(f'Error: unknown capability [{cap}]') arch = '' name = self.last_value.lower().replace(",
"See the License for the specific language governing permissions and # limitations under",
"specific language governing permissions and # limitations under the License. import urllib.request as",
"2021 Sony Group Corporation. # # Licensed under the Apache License, Version 2.0",
"arch = gpu_compute_capability_to_arc.get( (cap_major, cap_minor)) if arch is None: print(f'Error: unknown capability [{cap}]')",
"BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.",
"License, Version 2.0 (the \"License\"); # you may not use this file except",
"html.parser import HTMLParser import re from mako.template import Template import os from gpu_info",
"# Licensed under the Apache License, Version 2.0 (the \"License\"); # you may",
"None self.last_data = '' self.gpu_data = {} def handle_starttag(self, tag, attrs): if tag",
"capability [{cap}]') arch = '' name = self.last_value.lower().replace( 'nvidia ', '').replace('tesla ', '')",
"False def handle_data(self, data): if self.td: self.last_data += data parser = GetGpuListFromNvidiaSite() parser.feed(r.read().decode())",
"os from gpu_info import incompatible_arcs, gpu_compute_capability_to_arc basedir = os.path.dirname(os.path.abspath(__file__)) r = request.urlopen('https://developer.nvidia.com/cuda-gpus') class",
"r = request.urlopen('https://developer.nvidia.com/cuda-gpus') class GetGpuListFromNvidiaSite(HTMLParser): def __init__(self): super().__init__() self.td = False self.last_value =",
"IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or",
"m = re.match(r'((\\d+)\\.(\\d+))', self.last_data.strip()) if m: cap = m.group(1) cap_major = int(m.group(2)) cap_minor",
"a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required",
"distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY",
"# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in",
"'' name = self.last_value.lower().replace( 'nvidia ', '').replace('tesla ', '') # remove prefix self.gpu_data[name]",
"parser = GetGpuListFromNvidiaSite() parser.feed(r.read().decode()) gpus_info = parser.gpu_data incompatible_gpus = {} for k in",
"OF ANY KIND, either express or implied. # See the License for the",
"# Copyright 2021 Sony Group Corporation. # # Licensed under the Apache License,",
"tag): if tag == 'td': if self.td: m = re.match(r'((\\d+)\\.(\\d+))', self.last_data.strip()) if m:",
"is None: print(f'Error: unknown capability [{cap}]') arch = '' name = self.last_value.lower().replace( 'nvidia",
"arch = '' name = self.last_value.lower().replace( 'nvidia ', '').replace('tesla ', '') # remove",
"2.0 (the \"License\"); # you may not use this file except in compliance",
"if not incompatible_gpus.get(k): incompatible_gpus[k] = [] iarc = incompatible_arcs[k] for gpu_name in gpus_info.keys():",
"class GetGpuListFromNvidiaSite(HTMLParser): def __init__(self): super().__init__() self.td = False self.last_value = None self.last_data =",
"= [] iarc = incompatible_arcs[k] for gpu_name in gpus_info.keys(): if gpus_info[gpu_name][0] in iarc:",
"if gpus_info[gpu_name][0] in iarc: incompatible_gpus[k].append(gpu_name) fname = os.path.join(basedir, 'skel', 'incompatibale_gpu_list.py.tmpl') tmpl = Template(filename=fname)",
"# you may not use this file except in compliance with the License.",
"as request from html.parser import HTMLParser import re from mako.template import Template import",
"if tag == 'td': if self.td: m = re.match(r'((\\d+)\\.(\\d+))', self.last_data.strip()) if m: cap",
"def handle_data(self, data): if self.td: self.last_data += data parser = GetGpuListFromNvidiaSite() parser.feed(r.read().decode()) gpus_info",
"m.group(1) cap_major = int(m.group(2)) cap_minor = int(m.group(3)) arch = gpu_compute_capability_to_arc.get(cap_major) if arch is",
"iarc = incompatible_arcs[k] for gpu_name in gpus_info.keys(): if gpus_info[gpu_name][0] in iarc: incompatible_gpus[k].append(gpu_name) fname",
"agreed to in writing, software # distributed under the License is distributed on",
"', '') # remove prefix self.gpu_data[name] = (arch, cap) self.last_value = self.last_data.strip() self.last_data",
"= incompatible_arcs[k] for gpu_name in gpus_info.keys(): if gpus_info[gpu_name][0] in iarc: incompatible_gpus[k].append(gpu_name) fname =",
"WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the",
"= False def handle_data(self, data): if self.td: self.last_data += data parser = GetGpuListFromNvidiaSite()",
"= request.urlopen('https://developer.nvidia.com/cuda-gpus') class GetGpuListFromNvidiaSite(HTMLParser): def __init__(self): super().__init__() self.td = False self.last_value = None",
"in iarc: incompatible_gpus[k].append(gpu_name) fname = os.path.join(basedir, 'skel', 'incompatibale_gpu_list.py.tmpl') tmpl = Template(filename=fname) lines =",
"incompatible_gpus[k] = [] iarc = incompatible_arcs[k] for gpu_name in gpus_info.keys(): if gpus_info[gpu_name][0] in",
"(the \"License\"); # you may not use this file except in compliance with",
"and # limitations under the License. import urllib.request as request from html.parser import",
"self.last_data.strip() self.last_data = '' self.td = False def handle_data(self, data): if self.td: self.last_data",
"+= data parser = GetGpuListFromNvidiaSite() parser.feed(r.read().decode()) gpus_info = parser.gpu_data incompatible_gpus = {} for",
"import incompatible_arcs, gpu_compute_capability_to_arc basedir = os.path.dirname(os.path.abspath(__file__)) r = request.urlopen('https://developer.nvidia.com/cuda-gpus') class GetGpuListFromNvidiaSite(HTMLParser): def __init__(self):",
"# # Unless required by applicable law or agreed to in writing, software",
"incompatible_gpus[k].append(gpu_name) fname = os.path.join(basedir, 'skel', 'incompatibale_gpu_list.py.tmpl') tmpl = Template(filename=fname) lines = tmpl.render(args=incompatible_gpus) with",
"os.path.join(basedir, 'skel', 'incompatibale_gpu_list.py.tmpl') tmpl = Template(filename=fname) lines = tmpl.render(args=incompatible_gpus) with open(\"./python/src/nnabla_ext/cuda/incompatible_gpu_list.py\", 'w') as",
"self.td = False def handle_data(self, data): if self.td: self.last_data += data parser =",
"permissions and # limitations under the License. import urllib.request as request from html.parser",
"'skel', 'incompatibale_gpu_list.py.tmpl') tmpl = Template(filename=fname) lines = tmpl.render(args=incompatible_gpus) with open(\"./python/src/nnabla_ext/cuda/incompatible_gpu_list.py\", 'w') as f:",
"'' self.gpu_data = {} def handle_starttag(self, tag, attrs): if tag == 'td': self.td",
"express or implied. # See the License for the specific language governing permissions",
"arch = gpu_compute_capability_to_arc.get(cap_major) if arch is None: arch = gpu_compute_capability_to_arc.get( (cap_major, cap_minor)) if",
"incompatible_arcs: if not incompatible_gpus.get(k): incompatible_gpus[k] = [] iarc = incompatible_arcs[k] for gpu_name in",
"Version 2.0 (the \"License\"); # you may not use this file except in",
"# Unless required by applicable law or agreed to in writing, software #",
"basedir = os.path.dirname(os.path.abspath(__file__)) r = request.urlopen('https://developer.nvidia.com/cuda-gpus') class GetGpuListFromNvidiaSite(HTMLParser): def __init__(self): super().__init__() self.td =",
"except in compliance with the License. # You may obtain a copy of",
"self.last_value.lower().replace( 'nvidia ', '').replace('tesla ', '') # remove prefix self.gpu_data[name] = (arch, cap)",
"by applicable law or agreed to in writing, software # distributed under the",
"License. import urllib.request as request from html.parser import HTMLParser import re from mako.template",
"self.td = False self.last_value = None self.last_data = '' self.gpu_data = {} def",
"= parser.gpu_data incompatible_gpus = {} for k in incompatible_arcs: if not incompatible_gpus.get(k): incompatible_gpus[k]",
"= GetGpuListFromNvidiaSite() parser.feed(r.read().decode()) gpus_info = parser.gpu_data incompatible_gpus = {} for k in incompatible_arcs:",
"fname = os.path.join(basedir, 'skel', 'incompatibale_gpu_list.py.tmpl') tmpl = Template(filename=fname) lines = tmpl.render(args=incompatible_gpus) with open(\"./python/src/nnabla_ext/cuda/incompatible_gpu_list.py\",",
"copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by",
"unknown capability [{cap}]') arch = '' name = self.last_value.lower().replace( 'nvidia ', '').replace('tesla ',",
"# remove prefix self.gpu_data[name] = (arch, cap) self.last_value = self.last_data.strip() self.last_data = ''",
"'td': self.td = True def handle_endtag(self, tag): if tag == 'td': if self.td:",
"'nvidia ', '').replace('tesla ', '') # remove prefix self.gpu_data[name] = (arch, cap) self.last_value",
"GetGpuListFromNvidiaSite() parser.feed(r.read().decode()) gpus_info = parser.gpu_data incompatible_gpus = {} for k in incompatible_arcs: if",
"parser.feed(r.read().decode()) gpus_info = parser.gpu_data incompatible_gpus = {} for k in incompatible_arcs: if not",
"k in incompatible_arcs: if not incompatible_gpus.get(k): incompatible_gpus[k] = [] iarc = incompatible_arcs[k] for",
"either express or implied. # See the License for the specific language governing",
"prefix self.gpu_data[name] = (arch, cap) self.last_value = self.last_data.strip() self.last_data = '' self.td =",
"= True def handle_endtag(self, tag): if tag == 'td': if self.td: m =",
"[] iarc = incompatible_arcs[k] for gpu_name in gpus_info.keys(): if gpus_info[gpu_name][0] in iarc: incompatible_gpus[k].append(gpu_name)",
"= {} for k in incompatible_arcs: if not incompatible_gpus.get(k): incompatible_gpus[k] = [] iarc",
"software # distributed under the License is distributed on an \"AS IS\" BASIS,",
"= os.path.join(basedir, 'skel', 'incompatibale_gpu_list.py.tmpl') tmpl = Template(filename=fname) lines = tmpl.render(args=incompatible_gpus) with open(\"./python/src/nnabla_ext/cuda/incompatible_gpu_list.py\", 'w')",
"# You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0",
"may not use this file except in compliance with the License. # You",
"License is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS",
"= '' self.gpu_data = {} def handle_starttag(self, tag, attrs): if tag == 'td':",
"in gpus_info.keys(): if gpus_info[gpu_name][0] in iarc: incompatible_gpus[k].append(gpu_name) fname = os.path.join(basedir, 'skel', 'incompatibale_gpu_list.py.tmpl') tmpl",
"= False self.last_value = None self.last_data = '' self.gpu_data = {} def handle_starttag(self,",
"Licensed under the Apache License, Version 2.0 (the \"License\"); # you may not",
"an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either",
"# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to",
"from gpu_info import incompatible_arcs, gpu_compute_capability_to_arc basedir = os.path.dirname(os.path.abspath(__file__)) r = request.urlopen('https://developer.nvidia.com/cuda-gpus') class GetGpuListFromNvidiaSite(HTMLParser):",
"None: arch = gpu_compute_capability_to_arc.get( (cap_major, cap_minor)) if arch is None: print(f'Error: unknown capability",
"file except in compliance with the License. # You may obtain a copy",
"import urllib.request as request from html.parser import HTMLParser import re from mako.template import",
"cap_minor)) if arch is None: print(f'Error: unknown capability [{cap}]') arch = '' name",
"= None self.last_data = '' self.gpu_data = {} def handle_starttag(self, tag, attrs): if",
"if arch is None: print(f'Error: unknown capability [{cap}]') arch = '' name =",
"gpus_info[gpu_name][0] in iarc: incompatible_gpus[k].append(gpu_name) fname = os.path.join(basedir, 'skel', 'incompatibale_gpu_list.py.tmpl') tmpl = Template(filename=fname) lines",
"def handle_endtag(self, tag): if tag == 'td': if self.td: m = re.match(r'((\\d+)\\.(\\d+))', self.last_data.strip())",
"incompatible_arcs[k] for gpu_name in gpus_info.keys(): if gpus_info[gpu_name][0] in iarc: incompatible_gpus[k].append(gpu_name) fname = os.path.join(basedir,",
"the specific language governing permissions and # limitations under the License. import urllib.request",
"under the License is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES",
"int(m.group(3)) arch = gpu_compute_capability_to_arc.get(cap_major) if arch is None: arch = gpu_compute_capability_to_arc.get( (cap_major, cap_minor))",
"= gpu_compute_capability_to_arc.get(cap_major) if arch is None: arch = gpu_compute_capability_to_arc.get( (cap_major, cap_minor)) if arch",
"Corporation. # # Licensed under the Apache License, Version 2.0 (the \"License\"); #",
"License for the specific language governing permissions and # limitations under the License.",
"Group Corporation. # # Licensed under the Apache License, Version 2.0 (the \"License\");",
"the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law",
"mako.template import Template import os from gpu_info import incompatible_arcs, gpu_compute_capability_to_arc basedir = os.path.dirname(os.path.abspath(__file__))",
"GetGpuListFromNvidiaSite(HTMLParser): def __init__(self): super().__init__() self.td = False self.last_value = None self.last_data = ''",
"'' self.td = False def handle_data(self, data): if self.td: self.last_data += data parser",
"self.last_value = self.last_data.strip() self.last_data = '' self.td = False def handle_data(self, data): if",
"for k in incompatible_arcs: if not incompatible_gpus.get(k): incompatible_gpus[k] = [] iarc = incompatible_arcs[k]",
"the License. # You may obtain a copy of the License at #",
"'') # remove prefix self.gpu_data[name] = (arch, cap) self.last_value = self.last_data.strip() self.last_data =",
"parser.gpu_data incompatible_gpus = {} for k in incompatible_arcs: if not incompatible_gpus.get(k): incompatible_gpus[k] =",
"to in writing, software # distributed under the License is distributed on an",
"gpu_compute_capability_to_arc.get( (cap_major, cap_minor)) if arch is None: print(f'Error: unknown capability [{cap}]') arch =",
"\"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express",
"<gh_stars>100-1000 # Copyright 2021 Sony Corporation. # Copyright 2021 Sony Group Corporation. #",
"remove prefix self.gpu_data[name] = (arch, cap) self.last_value = self.last_data.strip() self.last_data = '' self.td",
"# distributed under the License is distributed on an \"AS IS\" BASIS, #",
"arch is None: arch = gpu_compute_capability_to_arc.get( (cap_major, cap_minor)) if arch is None: print(f'Error:",
"implied. # See the License for the specific language governing permissions and #",
"def handle_starttag(self, tag, attrs): if tag == 'td': self.td = True def handle_endtag(self,",
"= (arch, cap) self.last_value = self.last_data.strip() self.last_data = '' self.td = False def",
"gpus_info.keys(): if gpus_info[gpu_name][0] in iarc: incompatible_gpus[k].append(gpu_name) fname = os.path.join(basedir, 'skel', 'incompatibale_gpu_list.py.tmpl') tmpl =",
"\"License\"); # you may not use this file except in compliance with the",
"urllib.request as request from html.parser import HTMLParser import re from mako.template import Template",
"is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF",
"super().__init__() self.td = False self.last_value = None self.last_data = '' self.gpu_data = {}",
"obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless",
"data): if self.td: self.last_data += data parser = GetGpuListFromNvidiaSite() parser.feed(r.read().decode()) gpus_info = parser.gpu_data",
"required by applicable law or agreed to in writing, software # distributed under",
"not incompatible_gpus.get(k): incompatible_gpus[k] = [] iarc = incompatible_arcs[k] for gpu_name in gpus_info.keys(): if",
"self.td: m = re.match(r'((\\d+)\\.(\\d+))', self.last_data.strip()) if m: cap = m.group(1) cap_major = int(m.group(2))",
"gpu_name in gpus_info.keys(): if gpus_info[gpu_name][0] in iarc: incompatible_gpus[k].append(gpu_name) fname = os.path.join(basedir, 'skel', 'incompatibale_gpu_list.py.tmpl')",
"if arch is None: arch = gpu_compute_capability_to_arc.get( (cap_major, cap_minor)) if arch is None:",
"applicable law or agreed to in writing, software # distributed under the License",
"handle_starttag(self, tag, attrs): if tag == 'td': self.td = True def handle_endtag(self, tag):",
"under the License. import urllib.request as request from html.parser import HTMLParser import re",
"', '').replace('tesla ', '') # remove prefix self.gpu_data[name] = (arch, cap) self.last_value =",
"self.td = True def handle_endtag(self, tag): if tag == 'td': if self.td: m",
"Sony Group Corporation. # # Licensed under the Apache License, Version 2.0 (the",
"attrs): if tag == 'td': self.td = True def handle_endtag(self, tag): if tag",
"= m.group(1) cap_major = int(m.group(2)) cap_minor = int(m.group(3)) arch = gpu_compute_capability_to_arc.get(cap_major) if arch",
"handle_data(self, data): if self.td: self.last_data += data parser = GetGpuListFromNvidiaSite() parser.feed(r.read().decode()) gpus_info =",
"Corporation. # Copyright 2021 Sony Group Corporation. # # Licensed under the Apache",
"tmpl = Template(filename=fname) lines = tmpl.render(args=incompatible_gpus) with open(\"./python/src/nnabla_ext/cuda/incompatible_gpu_list.py\", 'w') as f: for l",
"incompatible_arcs, gpu_compute_capability_to_arc basedir = os.path.dirname(os.path.abspath(__file__)) r = request.urlopen('https://developer.nvidia.com/cuda-gpus') class GetGpuListFromNvidiaSite(HTMLParser): def __init__(self): super().__init__()",
"== 'td': if self.td: m = re.match(r'((\\d+)\\.(\\d+))', self.last_data.strip()) if m: cap = m.group(1)",
"tag == 'td': self.td = True def handle_endtag(self, tag): if tag == 'td':",
"or agreed to in writing, software # distributed under the License is distributed",
"# Copyright 2021 Sony Corporation. # Copyright 2021 Sony Group Corporation. # #",
"handle_endtag(self, tag): if tag == 'td': if self.td: m = re.match(r'((\\d+)\\.(\\d+))', self.last_data.strip()) if",
"or implied. # See the License for the specific language governing permissions and",
"import os from gpu_info import incompatible_arcs, gpu_compute_capability_to_arc basedir = os.path.dirname(os.path.abspath(__file__)) r = request.urlopen('https://developer.nvidia.com/cuda-gpus')",
"from html.parser import HTMLParser import re from mako.template import Template import os from",
"cap_minor = int(m.group(3)) arch = gpu_compute_capability_to_arc.get(cap_major) if arch is None: arch = gpu_compute_capability_to_arc.get(",
"distributed under the License is distributed on an \"AS IS\" BASIS, # WITHOUT",
"CONDITIONS OF ANY KIND, either express or implied. # See the License for",
"incompatible_gpus = {} for k in incompatible_arcs: if not incompatible_gpus.get(k): incompatible_gpus[k] = []",
"for gpu_name in gpus_info.keys(): if gpus_info[gpu_name][0] in iarc: incompatible_gpus[k].append(gpu_name) fname = os.path.join(basedir, 'skel',",
"Apache License, Version 2.0 (the \"License\"); # you may not use this file",
"OR CONDITIONS OF ANY KIND, either express or implied. # See the License",
"may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #",
"# limitations under the License. import urllib.request as request from html.parser import HTMLParser",
"re.match(r'((\\d+)\\.(\\d+))', self.last_data.strip()) if m: cap = m.group(1) cap_major = int(m.group(2)) cap_minor = int(m.group(3))",
"tag == 'td': if self.td: m = re.match(r'((\\d+)\\.(\\d+))', self.last_data.strip()) if m: cap =",
"with the License. # You may obtain a copy of the License at",
"Copyright 2021 Sony Corporation. # Copyright 2021 Sony Group Corporation. # # Licensed",
"http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing,",
"self.last_data += data parser = GetGpuListFromNvidiaSite() parser.feed(r.read().decode()) gpus_info = parser.gpu_data incompatible_gpus = {}",
"in writing, software # distributed under the License is distributed on an \"AS",
"in incompatible_arcs: if not incompatible_gpus.get(k): incompatible_gpus[k] = [] iarc = incompatible_arcs[k] for gpu_name",
"self.gpu_data = {} def handle_starttag(self, tag, attrs): if tag == 'td': self.td =",
"name = self.last_value.lower().replace( 'nvidia ', '').replace('tesla ', '') # remove prefix self.gpu_data[name] =",
"under the Apache License, Version 2.0 (the \"License\"); # you may not use"
] |
[
"sdata) resp = sock.makefile() sdata = resp.read(8) size = int(sdata, 0) data =",
"def __exit__(self, type, value, traceback): self._stop_daemon() os.remove(self.socket) return False def send(self, test): params",
"50 Memory = 4294967296,0 Program = %(path)s/python Channel = /dev/stdin,/dev/stdin,0,0,4294967296,4294967296,0,0 Channel = /dev/null,/dev/stdout,0,0,0,0,4294967296,4294967296",
"= [l for l in open(args.file, 'r').readlines()] def client(server_address, input): sock = socket.socket(socket.AF_UNIX,",
"= 0 devnull = open(os.devnull, \"w\") PATH = os.path.abspath(os.path.dirname(__file__)) TEST_DIR = os.path.join(PATH, 'Lib',",
"= python /dev/1.test.py [fstab] channel=/dev/1.python.tar,mountpoint=/,access=ro,removable=no \"\"\" MANIFEST_TMPLT = \"\"\"Job = %(socket)s Node =",
"20130611 Timeout = 50 Memory = 4294967296,0 Program = %(path)s/python Channel = /dev/stdin,/dev/stdin,0,0,4294967296,4294967296,0,0",
"/dev/null,/dev/stdout,0,0,0,0,4294967296,4294967296 Channel = /dev/null,/dev/stderr,0,0,0,0,4294967296,4294967296 Channel = %(path)s/python.tar,/dev/1.python.tar,3,0,4294967296,4294967296,4294967296,4294967296 Channel = %(path)s/nvram.1,/dev/nvram,3,0,4294967296,4294967296,4294967296,4294967296 Channel = %(test_path)s/%(test)s.py,/dev/1.test.py,3,0,4294967296,4294967296,4294967296,4294967296",
"size = int(sdata, 0) data = resp.read(size) except IOError, e: print str(e) raise",
"% params) subprocess.call(['zerovm', os.path.join(PATH, 'manifest.1')], stdout=devnull, stderr=devnull) def _stop_daemon(self): subprocess.call(['pkill', 'zvm']) with Daemon()",
"# will use it as return code for script test_result = 0 devnull",
"= 4294967296,0 Program = %(path)s/python Channel = /dev/stdin,/dev/stdin,0,0,4294967296,4294967296,0,0 Channel = /dev/null,/dev/stdout,0,0,0,0,4294967296,4294967296 Channel =",
"tests: print(\"%s..\" % test.strip()[5:]), sys.stdout.flush() try: ret = daemon.send(test.strip()) retcode = int(ret.splitlines()[2]) if",
"%(path)s/python.tar,/dev/1.python.tar,3,0,4294967296,4294967296,4294967296,4294967296 Channel = %(path)s/nvram.1,/dev/nvram,3,0,4294967296,4294967296,4294967296,4294967296 Channel = %(test_path)s/%(test)s.py,/dev/1.test.py,3,0,4294967296,4294967296,4294967296,4294967296 \"\"\" # predefined tests tests =",
"= %(socket)s Node = 1 Version = 20130611 Timeout = 50 Memory =",
"Node = 1 Version = 20130611 Timeout = 50 Memory = 4294967296,0 Program",
"'test_grammar', 'test_opcodes', 'test_dict', 'test_builtin', 'test_exceptions', 'test_types', 'test_unittest', 'test_doctest', 'test_doctest2', ] if args.file: tests",
"argparse parser = argparse.ArgumentParser() parser.add_argument('-f', '--file', help='file containing tests list') args = parser.parse_args()",
"print str(e) raise finally: sock.close() return data class Daemon(object): def __enter__(self): # self.socket",
"_start_daemon(self): with open(os.path.join(PATH, 'manifest.1'), 'w') as mfile: params = {'socket': self.socket, 'path': PATH,",
"os.path.join(PATH, 'Lib', 'test') NVRAM_TMPLT = \"\"\"[args] args = python /dev/1.test.py [fstab] channel=/dev/1.python.tar,mountpoint=/,access=ro,removable=no \"\"\"",
"resp = sock.makefile() sdata = resp.read(8) size = int(sdata, 0) data = resp.read(size)",
"{'socket': self.socket, 'path': PATH, 'test_path': TEST_DIR, 'test': ''} self.manifest = MANIFEST_TMPLT % params",
"'Lib', 'test') NVRAM_TMPLT = \"\"\"[args] args = python /dev/1.test.py [fstab] channel=/dev/1.python.tar,mountpoint=/,access=ro,removable=no \"\"\" MANIFEST_TMPLT",
"Daemon(object): def __enter__(self): # self.socket = os.path.join(PATH, 'tmp1234') # self.fd, self.socket = 0,",
"import os import sys import subprocess import socket import tempfile import argparse parser",
"import argparse parser = argparse.ArgumentParser() parser.add_argument('-f', '--file', help='file containing tests list') args =",
"Daemon() as daemon: for test in tests: print(\"%s..\" % test.strip()[5:]), sys.stdout.flush() try: ret",
"print(\"%s..\" % test.strip()[5:]), sys.stdout.flush() try: ret = daemon.send(test.strip()) retcode = int(ret.splitlines()[2]) if retcode:",
"%(path)s/python Channel = /dev/stdin,/dev/stdin,0,0,4294967296,4294967296,0,0 Channel = /dev/null,/dev/stdout,0,0,0,0,4294967296,4294967296 Channel = /dev/null,/dev/stderr,0,0,0,0,4294967296,4294967296 Channel = %(path)s/python.tar,/dev/1.python.tar,3,0,4294967296,4294967296,4294967296,4294967296",
"'test': test} self.manifest = MANIFEST_TMPLT % params return client(self.socket, self.manifest) def _start_daemon(self): with",
"as return code for script test_result = 0 devnull = open(os.devnull, \"w\") PATH",
"1 Version = 20130611 Timeout = 50 Memory = 4294967296,0 Program = %(path)s/python",
"tests = [l for l in open(args.file, 'r').readlines()] def client(server_address, input): sock =",
"parser.parse_args() # will use it as return code for script test_result = 0",
"'--file', help='file containing tests list') args = parser.parse_args() # will use it as",
"input): sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) data = '' try: sock.connect(server_address) sdata = input",
"Channel = /dev/null,/dev/stderr,0,0,0,0,4294967296,4294967296 Channel = %(path)s/python.tar,/dev/1.python.tar,3,0,4294967296,4294967296,4294967296,4294967296 Channel = %(path)s/nvram.1,/dev/nvram,3,0,4294967296,4294967296,4294967296,4294967296 Channel = %(test_path)s/%(test)s.py,/dev/1.test.py,3,0,4294967296,4294967296,4294967296,4294967296 \"\"\"",
"= %(path)s/python.tar,/dev/1.python.tar,3,0,4294967296,4294967296,4294967296,4294967296 Channel = %(path)s/nvram.1,/dev/nvram,3,0,4294967296,4294967296,4294967296,4294967296 Channel = %(test_path)s/%(test)s.py,/dev/1.test.py,3,0,4294967296,4294967296,4294967296,4294967296 \"\"\" # predefined tests tests",
"'r').readlines()] def client(server_address, input): sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) data = '' try: sock.connect(server_address)",
"= os.path.join(PATH, 'Lib', 'test') NVRAM_TMPLT = \"\"\"[args] args = python /dev/1.test.py [fstab] channel=/dev/1.python.tar,mountpoint=/,access=ro,removable=no",
"%(socket)s Node = 1 Version = 20130611 Timeout = 50 Memory = 4294967296,0",
"return data class Daemon(object): def __enter__(self): # self.socket = os.path.join(PATH, 'tmp1234') # self.fd,",
"= {'socket': self.socket, 'path': PATH, 'test_path': TEST_DIR, 'test': test} self.manifest = MANIFEST_TMPLT %",
"value, traceback): self._stop_daemon() os.remove(self.socket) return False def send(self, test): params = {'socket': self.socket,",
"'test_path': TEST_DIR, 'test': test} self.manifest = MANIFEST_TMPLT % params return client(self.socket, self.manifest) def",
"sock.sendall(size + sdata) resp = sock.makefile() sdata = resp.read(8) size = int(sdata, 0)",
"= os.path.join(PATH, 'tmp1234') # self.fd, self.socket = 0, '/tmp/tmp.Mkba0cwcdk' self.fd, self.socket = tempfile.mkstemp()",
"PATH, 'test_path': TEST_DIR, 'test': test} self.manifest = MANIFEST_TMPLT % params return client(self.socket, self.manifest)",
"ret = daemon.send(test.strip()) retcode = int(ret.splitlines()[2]) if retcode: test_result = 1 print('\\033[1;31mfail\\033[1;m') else:",
"socket import tempfile import argparse parser = argparse.ArgumentParser() parser.add_argument('-f', '--file', help='file containing tests",
"] if args.file: tests = [l for l in open(args.file, 'r').readlines()] def client(server_address,",
"size = '0x%06x' % (len(sdata)) sock.sendall(size + sdata) resp = sock.makefile() sdata =",
"args = parser.parse_args() # will use it as return code for script test_result",
"send(self, test): params = {'socket': self.socket, 'path': PATH, 'test_path': TEST_DIR, 'test': test} self.manifest",
"= 20130611 Timeout = 50 Memory = 4294967296,0 Program = %(path)s/python Channel =",
"as mfile: params = {'socket': self.socket, 'path': PATH, 'test_path': TEST_DIR, 'test': ''} self.manifest",
"params mfile.write(self.manifest) with open(os.path.join(PATH, 'nvram.1'), 'w') as nfile: params = {'test': ''} nfile.write(NVRAM_TMPLT",
"''} nfile.write(NVRAM_TMPLT % params) subprocess.call(['zerovm', os.path.join(PATH, 'manifest.1')], stdout=devnull, stderr=devnull) def _stop_daemon(self): subprocess.call(['pkill', 'zvm'])",
"''} self.manifest = MANIFEST_TMPLT % params mfile.write(self.manifest) with open(os.path.join(PATH, 'nvram.1'), 'w') as nfile:",
"os.path.abspath(os.path.dirname(__file__)) TEST_DIR = os.path.join(PATH, 'Lib', 'test') NVRAM_TMPLT = \"\"\"[args] args = python /dev/1.test.py",
"test): params = {'socket': self.socket, 'path': PATH, 'test_path': TEST_DIR, 'test': test} self.manifest =",
"TEST_DIR, 'test': test} self.manifest = MANIFEST_TMPLT % params return client(self.socket, self.manifest) def _start_daemon(self):",
"if retcode: test_result = 1 print('\\033[1;31mfail\\033[1;m') else: print('\\033[1;32mok\\033[1;m') except KeyboardInterrupt: break devnull.close() sys.exit(test_result)",
"Channel = /dev/null,/dev/stdout,0,0,0,0,4294967296,4294967296 Channel = /dev/null,/dev/stderr,0,0,0,0,4294967296,4294967296 Channel = %(path)s/python.tar,/dev/1.python.tar,3,0,4294967296,4294967296,4294967296,4294967296 Channel = %(path)s/nvram.1,/dev/nvram,3,0,4294967296,4294967296,4294967296,4294967296 Channel",
"with open(os.path.join(PATH, 'nvram.1'), 'w') as nfile: params = {'test': ''} nfile.write(NVRAM_TMPLT % params)",
"__exit__(self, type, value, traceback): self._stop_daemon() os.remove(self.socket) return False def send(self, test): params =",
"= resp.read(size) except IOError, e: print str(e) raise finally: sock.close() return data class",
"__enter__(self): # self.socket = os.path.join(PATH, 'tmp1234') # self.fd, self.socket = 0, '/tmp/tmp.Mkba0cwcdk' self.fd,",
"os.path.join(PATH, 'tmp1234') # self.fd, self.socket = 0, '/tmp/tmp.Mkba0cwcdk' self.fd, self.socket = tempfile.mkstemp() self._start_daemon()",
"'w') as mfile: params = {'socket': self.socket, 'path': PATH, 'test_path': TEST_DIR, 'test': ''}",
"subprocess.call(['zerovm', os.path.join(PATH, 'manifest.1')], stdout=devnull, stderr=devnull) def _stop_daemon(self): subprocess.call(['pkill', 'zvm']) with Daemon() as daemon:",
"stderr=devnull) def _stop_daemon(self): subprocess.call(['pkill', 'zvm']) with Daemon() as daemon: for test in tests:",
"_stop_daemon(self): subprocess.call(['pkill', 'zvm']) with Daemon() as daemon: for test in tests: print(\"%s..\" %",
"def __enter__(self): # self.socket = os.path.join(PATH, 'tmp1234') # self.fd, self.socket = 0, '/tmp/tmp.Mkba0cwcdk'",
"socket.SOCK_STREAM) data = '' try: sock.connect(server_address) sdata = input size = '0x%06x' %",
"mfile.write(self.manifest) with open(os.path.join(PATH, 'nvram.1'), 'w') as nfile: params = {'test': ''} nfile.write(NVRAM_TMPLT %",
"'test_opcodes', 'test_dict', 'test_builtin', 'test_exceptions', 'test_types', 'test_unittest', 'test_doctest', 'test_doctest2', ] if args.file: tests =",
"return self def __exit__(self, type, value, traceback): self._stop_daemon() os.remove(self.socket) return False def send(self,",
"= os.path.abspath(os.path.dirname(__file__)) TEST_DIR = os.path.join(PATH, 'Lib', 'test') NVRAM_TMPLT = \"\"\"[args] args = python",
"# self.socket = os.path.join(PATH, 'tmp1234') # self.fd, self.socket = 0, '/tmp/tmp.Mkba0cwcdk' self.fd, self.socket",
"subprocess.call(['pkill', 'zvm']) with Daemon() as daemon: for test in tests: print(\"%s..\" % test.strip()[5:]),",
"type, value, traceback): self._stop_daemon() os.remove(self.socket) return False def send(self, test): params = {'socket':",
"test} self.manifest = MANIFEST_TMPLT % params return client(self.socket, self.manifest) def _start_daemon(self): with open(os.path.join(PATH,",
"[l for l in open(args.file, 'r').readlines()] def client(server_address, input): sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)",
"{'socket': self.socket, 'path': PATH, 'test_path': TEST_DIR, 'test': test} self.manifest = MANIFEST_TMPLT % params",
"params = {'socket': self.socket, 'path': PATH, 'test_path': TEST_DIR, 'test': ''} self.manifest = MANIFEST_TMPLT",
"sock.connect(server_address) sdata = input size = '0x%06x' % (len(sdata)) sock.sendall(size + sdata) resp",
"'nvram.1'), 'w') as nfile: params = {'test': ''} nfile.write(NVRAM_TMPLT % params) subprocess.call(['zerovm', os.path.join(PATH,",
"def _stop_daemon(self): subprocess.call(['pkill', 'zvm']) with Daemon() as daemon: for test in tests: print(\"%s..\"",
"args.file: tests = [l for l in open(args.file, 'r').readlines()] def client(server_address, input): sock",
"%(path)s/nvram.1,/dev/nvram,3,0,4294967296,4294967296,4294967296,4294967296 Channel = %(test_path)s/%(test)s.py,/dev/1.test.py,3,0,4294967296,4294967296,4294967296,4294967296 \"\"\" # predefined tests tests = [ 'test_grammar', 'test_opcodes',",
"Memory = 4294967296,0 Program = %(path)s/python Channel = /dev/stdin,/dev/stdin,0,0,4294967296,4294967296,0,0 Channel = /dev/null,/dev/stdout,0,0,0,0,4294967296,4294967296 Channel",
"nfile: params = {'test': ''} nfile.write(NVRAM_TMPLT % params) subprocess.call(['zerovm', os.path.join(PATH, 'manifest.1')], stdout=devnull, stderr=devnull)",
"= %(test_path)s/%(test)s.py,/dev/1.test.py,3,0,4294967296,4294967296,4294967296,4294967296 \"\"\" # predefined tests tests = [ 'test_grammar', 'test_opcodes', 'test_dict', 'test_builtin',",
"input size = '0x%06x' % (len(sdata)) sock.sendall(size + sdata) resp = sock.makefile() sdata",
"daemon.send(test.strip()) retcode = int(ret.splitlines()[2]) if retcode: test_result = 1 print('\\033[1;31mfail\\033[1;m') else: print('\\033[1;32mok\\033[1;m') except",
"= tempfile.mkstemp() self._start_daemon() return self def __exit__(self, type, value, traceback): self._stop_daemon() os.remove(self.socket) return",
"#!/usr/bin/python import os import sys import subprocess import socket import tempfile import argparse",
"= 1 Version = 20130611 Timeout = 50 Memory = 4294967296,0 Program =",
"\"\"\" MANIFEST_TMPLT = \"\"\"Job = %(socket)s Node = 1 Version = 20130611 Timeout",
"[ 'test_grammar', 'test_opcodes', 'test_dict', 'test_builtin', 'test_exceptions', 'test_types', 'test_unittest', 'test_doctest', 'test_doctest2', ] if args.file:",
"sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) data = '' try: sock.connect(server_address) sdata = input size",
"data class Daemon(object): def __enter__(self): # self.socket = os.path.join(PATH, 'tmp1234') # self.fd, self.socket",
"int(ret.splitlines()[2]) if retcode: test_result = 1 print('\\033[1;31mfail\\033[1;m') else: print('\\033[1;32mok\\033[1;m') except KeyboardInterrupt: break devnull.close()",
"% params mfile.write(self.manifest) with open(os.path.join(PATH, 'nvram.1'), 'w') as nfile: params = {'test': ''}",
"str(e) raise finally: sock.close() return data class Daemon(object): def __enter__(self): # self.socket =",
"self.socket = tempfile.mkstemp() self._start_daemon() return self def __exit__(self, type, value, traceback): self._stop_daemon() os.remove(self.socket)",
"os import sys import subprocess import socket import tempfile import argparse parser =",
"for test in tests: print(\"%s..\" % test.strip()[5:]), sys.stdout.flush() try: ret = daemon.send(test.strip()) retcode",
"test in tests: print(\"%s..\" % test.strip()[5:]), sys.stdout.flush() try: ret = daemon.send(test.strip()) retcode =",
"for script test_result = 0 devnull = open(os.devnull, \"w\") PATH = os.path.abspath(os.path.dirname(__file__)) TEST_DIR",
"= \"\"\"Job = %(socket)s Node = 1 Version = 20130611 Timeout = 50",
"parser.add_argument('-f', '--file', help='file containing tests list') args = parser.parse_args() # will use it",
"socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) data = '' try: sock.connect(server_address) sdata = input size = '0x%06x'",
"e: print str(e) raise finally: sock.close() return data class Daemon(object): def __enter__(self): #",
"script test_result = 0 devnull = open(os.devnull, \"w\") PATH = os.path.abspath(os.path.dirname(__file__)) TEST_DIR =",
"parser = argparse.ArgumentParser() parser.add_argument('-f', '--file', help='file containing tests list') args = parser.parse_args() #",
"containing tests list') args = parser.parse_args() # will use it as return code",
"data = resp.read(size) except IOError, e: print str(e) raise finally: sock.close() return data",
"nfile.write(NVRAM_TMPLT % params) subprocess.call(['zerovm', os.path.join(PATH, 'manifest.1')], stdout=devnull, stderr=devnull) def _stop_daemon(self): subprocess.call(['pkill', 'zvm']) with",
"resp.read(8) size = int(sdata, 0) data = resp.read(size) except IOError, e: print str(e)",
"sys import subprocess import socket import tempfile import argparse parser = argparse.ArgumentParser() parser.add_argument('-f',",
"'manifest.1'), 'w') as mfile: params = {'socket': self.socket, 'path': PATH, 'test_path': TEST_DIR, 'test':",
"# predefined tests tests = [ 'test_grammar', 'test_opcodes', 'test_dict', 'test_builtin', 'test_exceptions', 'test_types', 'test_unittest',",
"subprocess import socket import tempfile import argparse parser = argparse.ArgumentParser() parser.add_argument('-f', '--file', help='file",
"def _start_daemon(self): with open(os.path.join(PATH, 'manifest.1'), 'w') as mfile: params = {'socket': self.socket, 'path':",
"'test_doctest', 'test_doctest2', ] if args.file: tests = [l for l in open(args.file, 'r').readlines()]",
"'test_types', 'test_unittest', 'test_doctest', 'test_doctest2', ] if args.file: tests = [l for l in",
"if args.file: tests = [l for l in open(args.file, 'r').readlines()] def client(server_address, input):",
"os.remove(self.socket) return False def send(self, test): params = {'socket': self.socket, 'path': PATH, 'test_path':",
"for l in open(args.file, 'r').readlines()] def client(server_address, input): sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) data",
"= '' try: sock.connect(server_address) sdata = input size = '0x%06x' % (len(sdata)) sock.sendall(size",
"return False def send(self, test): params = {'socket': self.socket, 'path': PATH, 'test_path': TEST_DIR,",
"try: ret = daemon.send(test.strip()) retcode = int(ret.splitlines()[2]) if retcode: test_result = 1 print('\\033[1;31mfail\\033[1;m')",
"int(sdata, 0) data = resp.read(size) except IOError, e: print str(e) raise finally: sock.close()",
"= int(sdata, 0) data = resp.read(size) except IOError, e: print str(e) raise finally:",
"os.path.join(PATH, 'manifest.1')], stdout=devnull, stderr=devnull) def _stop_daemon(self): subprocess.call(['pkill', 'zvm']) with Daemon() as daemon: for",
"Channel = %(path)s/nvram.1,/dev/nvram,3,0,4294967296,4294967296,4294967296,4294967296 Channel = %(test_path)s/%(test)s.py,/dev/1.test.py,3,0,4294967296,4294967296,4294967296,4294967296 \"\"\" # predefined tests tests = [",
"# self.fd, self.socket = 0, '/tmp/tmp.Mkba0cwcdk' self.fd, self.socket = tempfile.mkstemp() self._start_daemon() return self",
"open(os.path.join(PATH, 'nvram.1'), 'w') as nfile: params = {'test': ''} nfile.write(NVRAM_TMPLT % params) subprocess.call(['zerovm',",
"sock.makefile() sdata = resp.read(8) size = int(sdata, 0) data = resp.read(size) except IOError,",
"params) subprocess.call(['zerovm', os.path.join(PATH, 'manifest.1')], stdout=devnull, stderr=devnull) def _stop_daemon(self): subprocess.call(['pkill', 'zvm']) with Daemon() as",
"= MANIFEST_TMPLT % params return client(self.socket, self.manifest) def _start_daemon(self): with open(os.path.join(PATH, 'manifest.1'), 'w')",
"self.manifest = MANIFEST_TMPLT % params return client(self.socket, self.manifest) def _start_daemon(self): with open(os.path.join(PATH, 'manifest.1'),",
"channel=/dev/1.python.tar,mountpoint=/,access=ro,removable=no \"\"\" MANIFEST_TMPLT = \"\"\"Job = %(socket)s Node = 1 Version = 20130611",
"0 devnull = open(os.devnull, \"w\") PATH = os.path.abspath(os.path.dirname(__file__)) TEST_DIR = os.path.join(PATH, 'Lib', 'test')",
"= '0x%06x' % (len(sdata)) sock.sendall(size + sdata) resp = sock.makefile() sdata = resp.read(8)",
"(len(sdata)) sock.sendall(size + sdata) resp = sock.makefile() sdata = resp.read(8) size = int(sdata,",
"'tmp1234') # self.fd, self.socket = 0, '/tmp/tmp.Mkba0cwcdk' self.fd, self.socket = tempfile.mkstemp() self._start_daemon() return",
"traceback): self._stop_daemon() os.remove(self.socket) return False def send(self, test): params = {'socket': self.socket, 'path':",
"= sock.makefile() sdata = resp.read(8) size = int(sdata, 0) data = resp.read(size) except",
"params = {'test': ''} nfile.write(NVRAM_TMPLT % params) subprocess.call(['zerovm', os.path.join(PATH, 'manifest.1')], stdout=devnull, stderr=devnull) def",
"TEST_DIR = os.path.join(PATH, 'Lib', 'test') NVRAM_TMPLT = \"\"\"[args] args = python /dev/1.test.py [fstab]",
"Channel = %(path)s/python.tar,/dev/1.python.tar,3,0,4294967296,4294967296,4294967296,4294967296 Channel = %(path)s/nvram.1,/dev/nvram,3,0,4294967296,4294967296,4294967296,4294967296 Channel = %(test_path)s/%(test)s.py,/dev/1.test.py,3,0,4294967296,4294967296,4294967296,4294967296 \"\"\" # predefined tests",
"def client(server_address, input): sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) data = '' try: sock.connect(server_address) sdata",
"'zvm']) with Daemon() as daemon: for test in tests: print(\"%s..\" % test.strip()[5:]), sys.stdout.flush()",
"import socket import tempfile import argparse parser = argparse.ArgumentParser() parser.add_argument('-f', '--file', help='file containing",
"import subprocess import socket import tempfile import argparse parser = argparse.ArgumentParser() parser.add_argument('-f', '--file',",
"= [ 'test_grammar', 'test_opcodes', 'test_dict', 'test_builtin', 'test_exceptions', 'test_types', 'test_unittest', 'test_doctest', 'test_doctest2', ] if",
"'test_unittest', 'test_doctest', 'test_doctest2', ] if args.file: tests = [l for l in open(args.file,",
"/dev/stdin,/dev/stdin,0,0,4294967296,4294967296,0,0 Channel = /dev/null,/dev/stdout,0,0,0,0,4294967296,4294967296 Channel = /dev/null,/dev/stderr,0,0,0,0,4294967296,4294967296 Channel = %(path)s/python.tar,/dev/1.python.tar,3,0,4294967296,4294967296,4294967296,4294967296 Channel = %(path)s/nvram.1,/dev/nvram,3,0,4294967296,4294967296,4294967296,4294967296",
"'test_builtin', 'test_exceptions', 'test_types', 'test_unittest', 'test_doctest', 'test_doctest2', ] if args.file: tests = [l for",
"'0x%06x' % (len(sdata)) sock.sendall(size + sdata) resp = sock.makefile() sdata = resp.read(8) size",
"= MANIFEST_TMPLT % params mfile.write(self.manifest) with open(os.path.join(PATH, 'nvram.1'), 'w') as nfile: params =",
"IOError, e: print str(e) raise finally: sock.close() return data class Daemon(object): def __enter__(self):",
"self.socket, 'path': PATH, 'test_path': TEST_DIR, 'test': ''} self.manifest = MANIFEST_TMPLT % params mfile.write(self.manifest)",
"'test_path': TEST_DIR, 'test': ''} self.manifest = MANIFEST_TMPLT % params mfile.write(self.manifest) with open(os.path.join(PATH, 'nvram.1'),",
"MANIFEST_TMPLT % params mfile.write(self.manifest) with open(os.path.join(PATH, 'nvram.1'), 'w') as nfile: params = {'test':",
"open(args.file, 'r').readlines()] def client(server_address, input): sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) data = '' try:",
"return client(self.socket, self.manifest) def _start_daemon(self): with open(os.path.join(PATH, 'manifest.1'), 'w') as mfile: params =",
"= parser.parse_args() # will use it as return code for script test_result =",
"self.fd, self.socket = 0, '/tmp/tmp.Mkba0cwcdk' self.fd, self.socket = tempfile.mkstemp() self._start_daemon() return self def",
"0, '/tmp/tmp.Mkba0cwcdk' self.fd, self.socket = tempfile.mkstemp() self._start_daemon() return self def __exit__(self, type, value,",
"def send(self, test): params = {'socket': self.socket, 'path': PATH, 'test_path': TEST_DIR, 'test': test}",
"'test_dict', 'test_builtin', 'test_exceptions', 'test_types', 'test_unittest', 'test_doctest', 'test_doctest2', ] if args.file: tests = [l",
"% test.strip()[5:]), sys.stdout.flush() try: ret = daemon.send(test.strip()) retcode = int(ret.splitlines()[2]) if retcode: test_result",
"\"\"\"Job = %(socket)s Node = 1 Version = 20130611 Timeout = 50 Memory",
"sys.stdout.flush() try: ret = daemon.send(test.strip()) retcode = int(ret.splitlines()[2]) if retcode: test_result = 1",
"\"\"\"[args] args = python /dev/1.test.py [fstab] channel=/dev/1.python.tar,mountpoint=/,access=ro,removable=no \"\"\" MANIFEST_TMPLT = \"\"\"Job = %(socket)s",
"\"w\") PATH = os.path.abspath(os.path.dirname(__file__)) TEST_DIR = os.path.join(PATH, 'Lib', 'test') NVRAM_TMPLT = \"\"\"[args] args",
"in open(args.file, 'r').readlines()] def client(server_address, input): sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) data = ''",
"test_result = 0 devnull = open(os.devnull, \"w\") PATH = os.path.abspath(os.path.dirname(__file__)) TEST_DIR = os.path.join(PATH,",
"Program = %(path)s/python Channel = /dev/stdin,/dev/stdin,0,0,4294967296,4294967296,0,0 Channel = /dev/null,/dev/stdout,0,0,0,0,4294967296,4294967296 Channel = /dev/null,/dev/stderr,0,0,0,0,4294967296,4294967296 Channel",
"tests tests = [ 'test_grammar', 'test_opcodes', 'test_dict', 'test_builtin', 'test_exceptions', 'test_types', 'test_unittest', 'test_doctest', 'test_doctest2',",
"finally: sock.close() return data class Daemon(object): def __enter__(self): # self.socket = os.path.join(PATH, 'tmp1234')",
"= {'socket': self.socket, 'path': PATH, 'test_path': TEST_DIR, 'test': ''} self.manifest = MANIFEST_TMPLT %",
"predefined tests tests = [ 'test_grammar', 'test_opcodes', 'test_dict', 'test_builtin', 'test_exceptions', 'test_types', 'test_unittest', 'test_doctest',",
"PATH, 'test_path': TEST_DIR, 'test': ''} self.manifest = MANIFEST_TMPLT % params mfile.write(self.manifest) with open(os.path.join(PATH,",
"self.manifest = MANIFEST_TMPLT % params mfile.write(self.manifest) with open(os.path.join(PATH, 'nvram.1'), 'w') as nfile: params",
"sock.close() return data class Daemon(object): def __enter__(self): # self.socket = os.path.join(PATH, 'tmp1234') #",
"self.manifest) def _start_daemon(self): with open(os.path.join(PATH, 'manifest.1'), 'w') as mfile: params = {'socket': self.socket,",
"mfile: params = {'socket': self.socket, 'path': PATH, 'test_path': TEST_DIR, 'test': ''} self.manifest =",
"'/tmp/tmp.Mkba0cwcdk' self.fd, self.socket = tempfile.mkstemp() self._start_daemon() return self def __exit__(self, type, value, traceback):",
"Version = 20130611 Timeout = 50 Memory = 4294967296,0 Program = %(path)s/python Channel",
"4294967296,0 Program = %(path)s/python Channel = /dev/stdin,/dev/stdin,0,0,4294967296,4294967296,0,0 Channel = /dev/null,/dev/stdout,0,0,0,0,4294967296,4294967296 Channel = /dev/null,/dev/stderr,0,0,0,0,4294967296,4294967296",
"self.socket = 0, '/tmp/tmp.Mkba0cwcdk' self.fd, self.socket = tempfile.mkstemp() self._start_daemon() return self def __exit__(self,",
"it as return code for script test_result = 0 devnull = open(os.devnull, \"w\")",
"% params return client(self.socket, self.manifest) def _start_daemon(self): with open(os.path.join(PATH, 'manifest.1'), 'w') as mfile:",
"help='file containing tests list') args = parser.parse_args() # will use it as return",
"'test_exceptions', 'test_types', 'test_unittest', 'test_doctest', 'test_doctest2', ] if args.file: tests = [l for l",
"[fstab] channel=/dev/1.python.tar,mountpoint=/,access=ro,removable=no \"\"\" MANIFEST_TMPLT = \"\"\"Job = %(socket)s Node = 1 Version =",
"MANIFEST_TMPLT = \"\"\"Job = %(socket)s Node = 1 Version = 20130611 Timeout =",
"retcode = int(ret.splitlines()[2]) if retcode: test_result = 1 print('\\033[1;31mfail\\033[1;m') else: print('\\033[1;32mok\\033[1;m') except KeyboardInterrupt:",
"import sys import subprocess import socket import tempfile import argparse parser = argparse.ArgumentParser()",
"{'test': ''} nfile.write(NVRAM_TMPLT % params) subprocess.call(['zerovm', os.path.join(PATH, 'manifest.1')], stdout=devnull, stderr=devnull) def _stop_daemon(self): subprocess.call(['pkill',",
"PATH = os.path.abspath(os.path.dirname(__file__)) TEST_DIR = os.path.join(PATH, 'Lib', 'test') NVRAM_TMPLT = \"\"\"[args] args =",
"False def send(self, test): params = {'socket': self.socket, 'path': PATH, 'test_path': TEST_DIR, 'test':",
"= resp.read(8) size = int(sdata, 0) data = resp.read(size) except IOError, e: print",
"will use it as return code for script test_result = 0 devnull =",
"= %(path)s/python Channel = /dev/stdin,/dev/stdin,0,0,4294967296,4294967296,0,0 Channel = /dev/null,/dev/stdout,0,0,0,0,4294967296,4294967296 Channel = /dev/null,/dev/stderr,0,0,0,0,4294967296,4294967296 Channel =",
"sdata = resp.read(8) size = int(sdata, 0) data = resp.read(size) except IOError, e:",
"data = '' try: sock.connect(server_address) sdata = input size = '0x%06x' % (len(sdata))",
"params = {'socket': self.socket, 'path': PATH, 'test_path': TEST_DIR, 'test': test} self.manifest = MANIFEST_TMPLT",
"with open(os.path.join(PATH, 'manifest.1'), 'w') as mfile: params = {'socket': self.socket, 'path': PATH, 'test_path':",
"resp.read(size) except IOError, e: print str(e) raise finally: sock.close() return data class Daemon(object):",
"= argparse.ArgumentParser() parser.add_argument('-f', '--file', help='file containing tests list') args = parser.parse_args() # will",
"'test') NVRAM_TMPLT = \"\"\"[args] args = python /dev/1.test.py [fstab] channel=/dev/1.python.tar,mountpoint=/,access=ro,removable=no \"\"\" MANIFEST_TMPLT =",
"client(server_address, input): sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) data = '' try: sock.connect(server_address) sdata =",
"0) data = resp.read(size) except IOError, e: print str(e) raise finally: sock.close() return",
"'' try: sock.connect(server_address) sdata = input size = '0x%06x' % (len(sdata)) sock.sendall(size +",
"= %(path)s/nvram.1,/dev/nvram,3,0,4294967296,4294967296,4294967296,4294967296 Channel = %(test_path)s/%(test)s.py,/dev/1.test.py,3,0,4294967296,4294967296,4294967296,4294967296 \"\"\" # predefined tests tests = [ 'test_grammar',",
"self.fd, self.socket = tempfile.mkstemp() self._start_daemon() return self def __exit__(self, type, value, traceback): self._stop_daemon()",
"= socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) data = '' try: sock.connect(server_address) sdata = input size =",
"% (len(sdata)) sock.sendall(size + sdata) resp = sock.makefile() sdata = resp.read(8) size =",
"import tempfile import argparse parser = argparse.ArgumentParser() parser.add_argument('-f', '--file', help='file containing tests list')",
"devnull = open(os.devnull, \"w\") PATH = os.path.abspath(os.path.dirname(__file__)) TEST_DIR = os.path.join(PATH, 'Lib', 'test') NVRAM_TMPLT",
"NVRAM_TMPLT = \"\"\"[args] args = python /dev/1.test.py [fstab] channel=/dev/1.python.tar,mountpoint=/,access=ro,removable=no \"\"\" MANIFEST_TMPLT = \"\"\"Job",
"= /dev/stdin,/dev/stdin,0,0,4294967296,4294967296,0,0 Channel = /dev/null,/dev/stdout,0,0,0,0,4294967296,4294967296 Channel = /dev/null,/dev/stderr,0,0,0,0,4294967296,4294967296 Channel = %(path)s/python.tar,/dev/1.python.tar,3,0,4294967296,4294967296,4294967296,4294967296 Channel =",
"tempfile.mkstemp() self._start_daemon() return self def __exit__(self, type, value, traceback): self._stop_daemon() os.remove(self.socket) return False",
"TEST_DIR, 'test': ''} self.manifest = MANIFEST_TMPLT % params mfile.write(self.manifest) with open(os.path.join(PATH, 'nvram.1'), 'w')",
"= {'test': ''} nfile.write(NVRAM_TMPLT % params) subprocess.call(['zerovm', os.path.join(PATH, 'manifest.1')], stdout=devnull, stderr=devnull) def _stop_daemon(self):",
"python /dev/1.test.py [fstab] channel=/dev/1.python.tar,mountpoint=/,access=ro,removable=no \"\"\" MANIFEST_TMPLT = \"\"\"Job = %(socket)s Node = 1",
"code for script test_result = 0 devnull = open(os.devnull, \"w\") PATH = os.path.abspath(os.path.dirname(__file__))",
"open(os.devnull, \"w\") PATH = os.path.abspath(os.path.dirname(__file__)) TEST_DIR = os.path.join(PATH, 'Lib', 'test') NVRAM_TMPLT = \"\"\"[args]",
"self._stop_daemon() os.remove(self.socket) return False def send(self, test): params = {'socket': self.socket, 'path': PATH,",
"params return client(self.socket, self.manifest) def _start_daemon(self): with open(os.path.join(PATH, 'manifest.1'), 'w') as mfile: params",
"= \"\"\"[args] args = python /dev/1.test.py [fstab] channel=/dev/1.python.tar,mountpoint=/,access=ro,removable=no \"\"\" MANIFEST_TMPLT = \"\"\"Job =",
"tempfile import argparse parser = argparse.ArgumentParser() parser.add_argument('-f', '--file', help='file containing tests list') args",
"\"\"\" # predefined tests tests = [ 'test_grammar', 'test_opcodes', 'test_dict', 'test_builtin', 'test_exceptions', 'test_types',",
"return code for script test_result = 0 devnull = open(os.devnull, \"w\") PATH =",
"+ sdata) resp = sock.makefile() sdata = resp.read(8) size = int(sdata, 0) data",
"raise finally: sock.close() return data class Daemon(object): def __enter__(self): # self.socket = os.path.join(PATH,",
"as nfile: params = {'test': ''} nfile.write(NVRAM_TMPLT % params) subprocess.call(['zerovm', os.path.join(PATH, 'manifest.1')], stdout=devnull,",
"'test_doctest2', ] if args.file: tests = [l for l in open(args.file, 'r').readlines()] def",
"= int(ret.splitlines()[2]) if retcode: test_result = 1 print('\\033[1;31mfail\\033[1;m') else: print('\\033[1;32mok\\033[1;m') except KeyboardInterrupt: break",
"= open(os.devnull, \"w\") PATH = os.path.abspath(os.path.dirname(__file__)) TEST_DIR = os.path.join(PATH, 'Lib', 'test') NVRAM_TMPLT =",
"use it as return code for script test_result = 0 devnull = open(os.devnull,",
"Channel = %(test_path)s/%(test)s.py,/dev/1.test.py,3,0,4294967296,4294967296,4294967296,4294967296 \"\"\" # predefined tests tests = [ 'test_grammar', 'test_opcodes', 'test_dict',",
"tests = [ 'test_grammar', 'test_opcodes', 'test_dict', 'test_builtin', 'test_exceptions', 'test_types', 'test_unittest', 'test_doctest', 'test_doctest2', ]",
"sdata = input size = '0x%06x' % (len(sdata)) sock.sendall(size + sdata) resp =",
"/dev/1.test.py [fstab] channel=/dev/1.python.tar,mountpoint=/,access=ro,removable=no \"\"\" MANIFEST_TMPLT = \"\"\"Job = %(socket)s Node = 1 Version",
"stdout=devnull, stderr=devnull) def _stop_daemon(self): subprocess.call(['pkill', 'zvm']) with Daemon() as daemon: for test in",
"/dev/null,/dev/stderr,0,0,0,0,4294967296,4294967296 Channel = %(path)s/python.tar,/dev/1.python.tar,3,0,4294967296,4294967296,4294967296,4294967296 Channel = %(path)s/nvram.1,/dev/nvram,3,0,4294967296,4294967296,4294967296,4294967296 Channel = %(test_path)s/%(test)s.py,/dev/1.test.py,3,0,4294967296,4294967296,4294967296,4294967296 \"\"\" # predefined",
"= /dev/null,/dev/stdout,0,0,0,0,4294967296,4294967296 Channel = /dev/null,/dev/stderr,0,0,0,0,4294967296,4294967296 Channel = %(path)s/python.tar,/dev/1.python.tar,3,0,4294967296,4294967296,4294967296,4294967296 Channel = %(path)s/nvram.1,/dev/nvram,3,0,4294967296,4294967296,4294967296,4294967296 Channel =",
"tests list') args = parser.parse_args() # will use it as return code for",
"class Daemon(object): def __enter__(self): # self.socket = os.path.join(PATH, 'tmp1234') # self.fd, self.socket =",
"self.socket = os.path.join(PATH, 'tmp1234') # self.fd, self.socket = 0, '/tmp/tmp.Mkba0cwcdk' self.fd, self.socket =",
"'manifest.1')], stdout=devnull, stderr=devnull) def _stop_daemon(self): subprocess.call(['pkill', 'zvm']) with Daemon() as daemon: for test",
"= daemon.send(test.strip()) retcode = int(ret.splitlines()[2]) if retcode: test_result = 1 print('\\033[1;31mfail\\033[1;m') else: print('\\033[1;32mok\\033[1;m')",
"argparse.ArgumentParser() parser.add_argument('-f', '--file', help='file containing tests list') args = parser.parse_args() # will use",
"args = python /dev/1.test.py [fstab] channel=/dev/1.python.tar,mountpoint=/,access=ro,removable=no \"\"\" MANIFEST_TMPLT = \"\"\"Job = %(socket)s Node",
"Timeout = 50 Memory = 4294967296,0 Program = %(path)s/python Channel = /dev/stdin,/dev/stdin,0,0,4294967296,4294967296,0,0 Channel",
"in tests: print(\"%s..\" % test.strip()[5:]), sys.stdout.flush() try: ret = daemon.send(test.strip()) retcode = int(ret.splitlines()[2])",
"self.socket, 'path': PATH, 'test_path': TEST_DIR, 'test': test} self.manifest = MANIFEST_TMPLT % params return",
"open(os.path.join(PATH, 'manifest.1'), 'w') as mfile: params = {'socket': self.socket, 'path': PATH, 'test_path': TEST_DIR,",
"MANIFEST_TMPLT % params return client(self.socket, self.manifest) def _start_daemon(self): with open(os.path.join(PATH, 'manifest.1'), 'w') as",
"'path': PATH, 'test_path': TEST_DIR, 'test': test} self.manifest = MANIFEST_TMPLT % params return client(self.socket,",
"'path': PATH, 'test_path': TEST_DIR, 'test': ''} self.manifest = MANIFEST_TMPLT % params mfile.write(self.manifest) with",
"= input size = '0x%06x' % (len(sdata)) sock.sendall(size + sdata) resp = sock.makefile()",
"client(self.socket, self.manifest) def _start_daemon(self): with open(os.path.join(PATH, 'manifest.1'), 'w') as mfile: params = {'socket':",
"with Daemon() as daemon: for test in tests: print(\"%s..\" % test.strip()[5:]), sys.stdout.flush() try:",
"test.strip()[5:]), sys.stdout.flush() try: ret = daemon.send(test.strip()) retcode = int(ret.splitlines()[2]) if retcode: test_result =",
"self._start_daemon() return self def __exit__(self, type, value, traceback): self._stop_daemon() os.remove(self.socket) return False def",
"try: sock.connect(server_address) sdata = input size = '0x%06x' % (len(sdata)) sock.sendall(size + sdata)",
"self def __exit__(self, type, value, traceback): self._stop_daemon() os.remove(self.socket) return False def send(self, test):",
"'test': ''} self.manifest = MANIFEST_TMPLT % params mfile.write(self.manifest) with open(os.path.join(PATH, 'nvram.1'), 'w') as",
"daemon: for test in tests: print(\"%s..\" % test.strip()[5:]), sys.stdout.flush() try: ret = daemon.send(test.strip())",
"= /dev/null,/dev/stderr,0,0,0,0,4294967296,4294967296 Channel = %(path)s/python.tar,/dev/1.python.tar,3,0,4294967296,4294967296,4294967296,4294967296 Channel = %(path)s/nvram.1,/dev/nvram,3,0,4294967296,4294967296,4294967296,4294967296 Channel = %(test_path)s/%(test)s.py,/dev/1.test.py,3,0,4294967296,4294967296,4294967296,4294967296 \"\"\" #",
"Channel = /dev/stdin,/dev/stdin,0,0,4294967296,4294967296,0,0 Channel = /dev/null,/dev/stdout,0,0,0,0,4294967296,4294967296 Channel = /dev/null,/dev/stderr,0,0,0,0,4294967296,4294967296 Channel = %(path)s/python.tar,/dev/1.python.tar,3,0,4294967296,4294967296,4294967296,4294967296 Channel",
"l in open(args.file, 'r').readlines()] def client(server_address, input): sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) data =",
"'w') as nfile: params = {'test': ''} nfile.write(NVRAM_TMPLT % params) subprocess.call(['zerovm', os.path.join(PATH, 'manifest.1')],",
"except IOError, e: print str(e) raise finally: sock.close() return data class Daemon(object): def",
"%(test_path)s/%(test)s.py,/dev/1.test.py,3,0,4294967296,4294967296,4294967296,4294967296 \"\"\" # predefined tests tests = [ 'test_grammar', 'test_opcodes', 'test_dict', 'test_builtin', 'test_exceptions',",
"as daemon: for test in tests: print(\"%s..\" % test.strip()[5:]), sys.stdout.flush() try: ret =",
"list') args = parser.parse_args() # will use it as return code for script",
"= 50 Memory = 4294967296,0 Program = %(path)s/python Channel = /dev/stdin,/dev/stdin,0,0,4294967296,4294967296,0,0 Channel =",
"= 0, '/tmp/tmp.Mkba0cwcdk' self.fd, self.socket = tempfile.mkstemp() self._start_daemon() return self def __exit__(self, type,"
] |
[
"#plt.plot(data[0],data[1],'co-',label='Simulation') #plt.plot(data[0],180/3.14*np.arctan(data[0]),'lightsalmon',linestyle='--',label='Experience') #plt.ylabel('Repose Angle [deg]') #plt.xlabel('Energy loss coefficient u1 [1]') #plt.legend() #plt.show() plt.figure().dpi=120",
"#plt.show() plt.figure().dpi=120 plt.plot(data[0],data[1],'co-',label='Simulation') #plt.plot(data[0],180/3.14*np.arctan(data[0]),'lightsalmon',linestyle='--',label='Experience') plt.ylabel('Repose Angle [deg]') plt.xlabel('Energy diffusion coefficient u2 [1]') plt.legend()",
"[deg]') #plt.xlabel('Energy loss coefficient u1 [1]') #plt.legend() #plt.show() plt.figure().dpi=120 plt.plot(data[0],data[1],'co-',label='Simulation') #plt.plot(data[0],180/3.14*np.arctan(data[0]),'lightsalmon',linestyle='--',label='Experience') plt.ylabel('Repose Angle",
"import numpy as np import matplotlib.pylab as plt data=np.loadtxt('./data/u2_sweep.csv')[:,:11] #plt.figure().dpi=120 #plt.plot(data[0],data[1],'co-',label='Simulation') #plt.plot(data[0],180/3.14*np.arctan(data[0]),'lightsalmon',linestyle='--',label='Experience') #plt.ylabel('Repose",
"data=np.loadtxt('./data/u2_sweep.csv')[:,:11] #plt.figure().dpi=120 #plt.plot(data[0],data[1],'co-',label='Simulation') #plt.plot(data[0],180/3.14*np.arctan(data[0]),'lightsalmon',linestyle='--',label='Experience') #plt.ylabel('Repose Angle [deg]') #plt.xlabel('Energy loss coefficient u1 [1]') #plt.legend()",
"#plt.xlabel('Energy loss coefficient u1 [1]') #plt.legend() #plt.show() plt.figure().dpi=120 plt.plot(data[0],data[1],'co-',label='Simulation') #plt.plot(data[0],180/3.14*np.arctan(data[0]),'lightsalmon',linestyle='--',label='Experience') plt.ylabel('Repose Angle [deg]')",
"np import matplotlib.pylab as plt data=np.loadtxt('./data/u2_sweep.csv')[:,:11] #plt.figure().dpi=120 #plt.plot(data[0],data[1],'co-',label='Simulation') #plt.plot(data[0],180/3.14*np.arctan(data[0]),'lightsalmon',linestyle='--',label='Experience') #plt.ylabel('Repose Angle [deg]') #plt.xlabel('Energy",
"u1 [1]') #plt.legend() #plt.show() plt.figure().dpi=120 plt.plot(data[0],data[1],'co-',label='Simulation') #plt.plot(data[0],180/3.14*np.arctan(data[0]),'lightsalmon',linestyle='--',label='Experience') plt.ylabel('Repose Angle [deg]') plt.xlabel('Energy diffusion coefficient",
"import matplotlib.pylab as plt data=np.loadtxt('./data/u2_sweep.csv')[:,:11] #plt.figure().dpi=120 #plt.plot(data[0],data[1],'co-',label='Simulation') #plt.plot(data[0],180/3.14*np.arctan(data[0]),'lightsalmon',linestyle='--',label='Experience') #plt.ylabel('Repose Angle [deg]') #plt.xlabel('Energy loss",
"as plt data=np.loadtxt('./data/u2_sweep.csv')[:,:11] #plt.figure().dpi=120 #plt.plot(data[0],data[1],'co-',label='Simulation') #plt.plot(data[0],180/3.14*np.arctan(data[0]),'lightsalmon',linestyle='--',label='Experience') #plt.ylabel('Repose Angle [deg]') #plt.xlabel('Energy loss coefficient u1",
"loss coefficient u1 [1]') #plt.legend() #plt.show() plt.figure().dpi=120 plt.plot(data[0],data[1],'co-',label='Simulation') #plt.plot(data[0],180/3.14*np.arctan(data[0]),'lightsalmon',linestyle='--',label='Experience') plt.ylabel('Repose Angle [deg]') plt.xlabel('Energy",
"matplotlib.pylab as plt data=np.loadtxt('./data/u2_sweep.csv')[:,:11] #plt.figure().dpi=120 #plt.plot(data[0],data[1],'co-',label='Simulation') #plt.plot(data[0],180/3.14*np.arctan(data[0]),'lightsalmon',linestyle='--',label='Experience') #plt.ylabel('Repose Angle [deg]') #plt.xlabel('Energy loss coefficient",
"#plt.ylabel('Repose Angle [deg]') #plt.xlabel('Energy loss coefficient u1 [1]') #plt.legend() #plt.show() plt.figure().dpi=120 plt.plot(data[0],data[1],'co-',label='Simulation') #plt.plot(data[0],180/3.14*np.arctan(data[0]),'lightsalmon',linestyle='--',label='Experience')",
"#plt.legend() #plt.show() plt.figure().dpi=120 plt.plot(data[0],data[1],'co-',label='Simulation') #plt.plot(data[0],180/3.14*np.arctan(data[0]),'lightsalmon',linestyle='--',label='Experience') plt.ylabel('Repose Angle [deg]') plt.xlabel('Energy diffusion coefficient u2 [1]')",
"coding: utf-8 -*- import numpy as np import matplotlib.pylab as plt data=np.loadtxt('./data/u2_sweep.csv')[:,:11] #plt.figure().dpi=120",
"numpy as np import matplotlib.pylab as plt data=np.loadtxt('./data/u2_sweep.csv')[:,:11] #plt.figure().dpi=120 #plt.plot(data[0],data[1],'co-',label='Simulation') #plt.plot(data[0],180/3.14*np.arctan(data[0]),'lightsalmon',linestyle='--',label='Experience') #plt.ylabel('Repose Angle",
"#plt.plot(data[0],180/3.14*np.arctan(data[0]),'lightsalmon',linestyle='--',label='Experience') #plt.ylabel('Repose Angle [deg]') #plt.xlabel('Energy loss coefficient u1 [1]') #plt.legend() #plt.show() plt.figure().dpi=120 plt.plot(data[0],data[1],'co-',label='Simulation')",
"<filename>plot.py # -*- coding: utf-8 -*- import numpy as np import matplotlib.pylab as",
"-*- import numpy as np import matplotlib.pylab as plt data=np.loadtxt('./data/u2_sweep.csv')[:,:11] #plt.figure().dpi=120 #plt.plot(data[0],data[1],'co-',label='Simulation') #plt.plot(data[0],180/3.14*np.arctan(data[0]),'lightsalmon',linestyle='--',label='Experience')",
"utf-8 -*- import numpy as np import matplotlib.pylab as plt data=np.loadtxt('./data/u2_sweep.csv')[:,:11] #plt.figure().dpi=120 #plt.plot(data[0],data[1],'co-',label='Simulation')",
"plt data=np.loadtxt('./data/u2_sweep.csv')[:,:11] #plt.figure().dpi=120 #plt.plot(data[0],data[1],'co-',label='Simulation') #plt.plot(data[0],180/3.14*np.arctan(data[0]),'lightsalmon',linestyle='--',label='Experience') #plt.ylabel('Repose Angle [deg]') #plt.xlabel('Energy loss coefficient u1 [1]')",
"Angle [deg]') #plt.xlabel('Energy loss coefficient u1 [1]') #plt.legend() #plt.show() plt.figure().dpi=120 plt.plot(data[0],data[1],'co-',label='Simulation') #plt.plot(data[0],180/3.14*np.arctan(data[0]),'lightsalmon',linestyle='--',label='Experience') plt.ylabel('Repose",
"-*- coding: utf-8 -*- import numpy as np import matplotlib.pylab as plt data=np.loadtxt('./data/u2_sweep.csv')[:,:11]",
"#plt.figure().dpi=120 #plt.plot(data[0],data[1],'co-',label='Simulation') #plt.plot(data[0],180/3.14*np.arctan(data[0]),'lightsalmon',linestyle='--',label='Experience') #plt.ylabel('Repose Angle [deg]') #plt.xlabel('Energy loss coefficient u1 [1]') #plt.legend() #plt.show()",
"as np import matplotlib.pylab as plt data=np.loadtxt('./data/u2_sweep.csv')[:,:11] #plt.figure().dpi=120 #plt.plot(data[0],data[1],'co-',label='Simulation') #plt.plot(data[0],180/3.14*np.arctan(data[0]),'lightsalmon',linestyle='--',label='Experience') #plt.ylabel('Repose Angle [deg]')",
"[1]') #plt.legend() #plt.show() plt.figure().dpi=120 plt.plot(data[0],data[1],'co-',label='Simulation') #plt.plot(data[0],180/3.14*np.arctan(data[0]),'lightsalmon',linestyle='--',label='Experience') plt.ylabel('Repose Angle [deg]') plt.xlabel('Energy diffusion coefficient u2",
"coefficient u1 [1]') #plt.legend() #plt.show() plt.figure().dpi=120 plt.plot(data[0],data[1],'co-',label='Simulation') #plt.plot(data[0],180/3.14*np.arctan(data[0]),'lightsalmon',linestyle='--',label='Experience') plt.ylabel('Repose Angle [deg]') plt.xlabel('Energy diffusion",
"plt.figure().dpi=120 plt.plot(data[0],data[1],'co-',label='Simulation') #plt.plot(data[0],180/3.14*np.arctan(data[0]),'lightsalmon',linestyle='--',label='Experience') plt.ylabel('Repose Angle [deg]') plt.xlabel('Energy diffusion coefficient u2 [1]') plt.legend() plt.show()",
"# -*- coding: utf-8 -*- import numpy as np import matplotlib.pylab as plt"
] |
[
"-> Tuple[tf.Variable, ...]: return tuple(self._model.trainable_weights) def get_loss(self, previous_frame: 'StateFrame', current_frame: 'StateFrame') -> Optional[tf.Tensor]:",
"StateFrame from cephalus.kernel import StateKernel from cephalus.modules.interface import StateKernelModule __all__ = [ 'InputPrediction'",
"loss for the next input to the kernel's state predictions.\"\"\" _model = None",
"None def configure(self, kernel: StateKernel) -> None: super().configure(kernel) self._model = Sequential([ Dense(self.input_width +",
"from tensorflow.keras.layers import Dense from cephalus.frame import StateFrame from cephalus.kernel import StateKernel from",
"from typing import Optional, Tuple, Callable import tensorflow as tf from tensorflow.keras import",
"next input to the kernel's state predictions.\"\"\" _model = None _loss_function: Callable =",
"* tf.reduce_mean(tf.square(target - prediction)) self._loss_function = loss_function super().build() def get_trainable_weights(self) -> Tuple[tf.Variable, ...]:",
"...]: return tuple(self._model.trainable_weights) def get_loss(self, previous_frame: 'StateFrame', current_frame: 'StateFrame') -> Optional[tf.Tensor]: return self._loss_function(previous_frame.current_state,",
":]) target = tf.stop_gradient(attended_inputs)[tf.newaxis, :] return 0.5 * tf.reduce_mean(tf.square(target - prediction)) self._loss_function =",
"state predictions.\"\"\" _model = None _loss_function: Callable = None def configure(self, kernel: StateKernel)",
"] class InputPrediction(StateKernelModule): \"\"\"A state kernel module which adds a prediction loss for",
"return tuple(self._model.trainable_weights) def get_loss(self, previous_frame: 'StateFrame', current_frame: 'StateFrame') -> Optional[tf.Tensor]: return self._loss_function(previous_frame.current_state, current_frame.attended_input_tensor)",
"= loss_function super().build() def get_trainable_weights(self) -> Tuple[tf.Variable, ...]: return tuple(self._model.trainable_weights) def get_loss(self, previous_frame:",
"'InputPrediction' ] class InputPrediction(StateKernelModule): \"\"\"A state kernel module which adds a prediction loss",
"for the next input to the kernel's state predictions.\"\"\" _model = None _loss_function:",
"predictions.\"\"\" _model = None _loss_function: Callable = None def configure(self, kernel: StateKernel) ->",
"target = tf.stop_gradient(attended_inputs)[tf.newaxis, :] return 0.5 * tf.reduce_mean(tf.square(target - prediction)) self._loss_function = loss_function",
":] return 0.5 * tf.reduce_mean(tf.square(target - prediction)) self._loss_function = loss_function super().build() def get_trainable_weights(self)",
"Tuple, Callable import tensorflow as tf from tensorflow.keras import Sequential from tensorflow.keras.layers import",
"def configure(self, kernel: StateKernel) -> None: super().configure(kernel) self._model = Sequential([ Dense(self.input_width + self.state_width,",
"= None def configure(self, kernel: StateKernel) -> None: super().configure(kernel) self._model = Sequential([ Dense(self.input_width",
"]) def build(self) -> None: self._model.build(input_shape=(None, self.state_width)) @tf.function def loss_function(state, attended_inputs): prediction =",
"input to the kernel's state predictions.\"\"\" _model = None _loss_function: Callable = None",
"import StateKernelModule __all__ = [ 'InputPrediction' ] class InputPrediction(StateKernelModule): \"\"\"A state kernel module",
"[ 'InputPrediction' ] class InputPrediction(StateKernelModule): \"\"\"A state kernel module which adds a prediction",
"tensorflow as tf from tensorflow.keras import Sequential from tensorflow.keras.layers import Dense from cephalus.frame",
"to the kernel's state predictions.\"\"\" _model = None _loss_function: Callable = None def",
"_model = None _loss_function: Callable = None def configure(self, kernel: StateKernel) -> None:",
"Sequential([ Dense(self.input_width + self.state_width, activation='tanh'), Dense(self.input_width) ]) def build(self) -> None: self._model.build(input_shape=(None, self.state_width))",
"from cephalus.modules.interface import StateKernelModule __all__ = [ 'InputPrediction' ] class InputPrediction(StateKernelModule): \"\"\"A state",
"which adds a prediction loss for the next input to the kernel's state",
"adds a prediction loss for the next input to the kernel's state predictions.\"\"\"",
"kernel's state predictions.\"\"\" _model = None _loss_function: Callable = None def configure(self, kernel:",
"class InputPrediction(StateKernelModule): \"\"\"A state kernel module which adds a prediction loss for the",
"_loss_function: Callable = None def configure(self, kernel: StateKernel) -> None: super().configure(kernel) self._model =",
"None: self._model.build(input_shape=(None, self.state_width)) @tf.function def loss_function(state, attended_inputs): prediction = self._model(state[tf.newaxis, :]) target =",
"loss_function(state, attended_inputs): prediction = self._model(state[tf.newaxis, :]) target = tf.stop_gradient(attended_inputs)[tf.newaxis, :] return 0.5 *",
"__all__ = [ 'InputPrediction' ] class InputPrediction(StateKernelModule): \"\"\"A state kernel module which adds",
"Sequential from tensorflow.keras.layers import Dense from cephalus.frame import StateFrame from cephalus.kernel import StateKernel",
"tensorflow.keras.layers import Dense from cephalus.frame import StateFrame from cephalus.kernel import StateKernel from cephalus.modules.interface",
"StateKernelModule __all__ = [ 'InputPrediction' ] class InputPrediction(StateKernelModule): \"\"\"A state kernel module which",
"def loss_function(state, attended_inputs): prediction = self._model(state[tf.newaxis, :]) target = tf.stop_gradient(attended_inputs)[tf.newaxis, :] return 0.5",
"import Dense from cephalus.frame import StateFrame from cephalus.kernel import StateKernel from cephalus.modules.interface import",
"-> None: super().configure(kernel) self._model = Sequential([ Dense(self.input_width + self.state_width, activation='tanh'), Dense(self.input_width) ]) def",
"prediction = self._model(state[tf.newaxis, :]) target = tf.stop_gradient(attended_inputs)[tf.newaxis, :] return 0.5 * tf.reduce_mean(tf.square(target -",
"from tensorflow.keras import Sequential from tensorflow.keras.layers import Dense from cephalus.frame import StateFrame from",
"= self._model(state[tf.newaxis, :]) target = tf.stop_gradient(attended_inputs)[tf.newaxis, :] return 0.5 * tf.reduce_mean(tf.square(target - prediction))",
"self._loss_function = loss_function super().build() def get_trainable_weights(self) -> Tuple[tf.Variable, ...]: return tuple(self._model.trainable_weights) def get_loss(self,",
"from cephalus.frame import StateFrame from cephalus.kernel import StateKernel from cephalus.modules.interface import StateKernelModule __all__",
"cephalus.frame import StateFrame from cephalus.kernel import StateKernel from cephalus.modules.interface import StateKernelModule __all__ =",
"None: super().configure(kernel) self._model = Sequential([ Dense(self.input_width + self.state_width, activation='tanh'), Dense(self.input_width) ]) def build(self)",
"def build(self) -> None: self._model.build(input_shape=(None, self.state_width)) @tf.function def loss_function(state, attended_inputs): prediction = self._model(state[tf.newaxis,",
"module which adds a prediction loss for the next input to the kernel's",
"prediction loss for the next input to the kernel's state predictions.\"\"\" _model =",
"StateKernel from cephalus.modules.interface import StateKernelModule __all__ = [ 'InputPrediction' ] class InputPrediction(StateKernelModule): \"\"\"A",
"Dense(self.input_width) ]) def build(self) -> None: self._model.build(input_shape=(None, self.state_width)) @tf.function def loss_function(state, attended_inputs): prediction",
"self._model.build(input_shape=(None, self.state_width)) @tf.function def loss_function(state, attended_inputs): prediction = self._model(state[tf.newaxis, :]) target = tf.stop_gradient(attended_inputs)[tf.newaxis,",
"super().configure(kernel) self._model = Sequential([ Dense(self.input_width + self.state_width, activation='tanh'), Dense(self.input_width) ]) def build(self) ->",
"kernel: StateKernel) -> None: super().configure(kernel) self._model = Sequential([ Dense(self.input_width + self.state_width, activation='tanh'), Dense(self.input_width)",
"= None _loss_function: Callable = None def configure(self, kernel: StateKernel) -> None: super().configure(kernel)",
"as tf from tensorflow.keras import Sequential from tensorflow.keras.layers import Dense from cephalus.frame import",
"prediction)) self._loss_function = loss_function super().build() def get_trainable_weights(self) -> Tuple[tf.Variable, ...]: return tuple(self._model.trainable_weights) def",
"cephalus.modules.interface import StateKernelModule __all__ = [ 'InputPrediction' ] class InputPrediction(StateKernelModule): \"\"\"A state kernel",
"self._model(state[tf.newaxis, :]) target = tf.stop_gradient(attended_inputs)[tf.newaxis, :] return 0.5 * tf.reduce_mean(tf.square(target - prediction)) self._loss_function",
"tf.stop_gradient(attended_inputs)[tf.newaxis, :] return 0.5 * tf.reduce_mean(tf.square(target - prediction)) self._loss_function = loss_function super().build() def",
"import StateFrame from cephalus.kernel import StateKernel from cephalus.modules.interface import StateKernelModule __all__ = [",
"cephalus.kernel import StateKernel from cephalus.modules.interface import StateKernelModule __all__ = [ 'InputPrediction' ] class",
"Dense(self.input_width + self.state_width, activation='tanh'), Dense(self.input_width) ]) def build(self) -> None: self._model.build(input_shape=(None, self.state_width)) @tf.function",
"@tf.function def loss_function(state, attended_inputs): prediction = self._model(state[tf.newaxis, :]) target = tf.stop_gradient(attended_inputs)[tf.newaxis, :] return",
"activation='tanh'), Dense(self.input_width) ]) def build(self) -> None: self._model.build(input_shape=(None, self.state_width)) @tf.function def loss_function(state, attended_inputs):",
"= Sequential([ Dense(self.input_width + self.state_width, activation='tanh'), Dense(self.input_width) ]) def build(self) -> None: self._model.build(input_shape=(None,",
"import StateKernel from cephalus.modules.interface import StateKernelModule __all__ = [ 'InputPrediction' ] class InputPrediction(StateKernelModule):",
"build(self) -> None: self._model.build(input_shape=(None, self.state_width)) @tf.function def loss_function(state, attended_inputs): prediction = self._model(state[tf.newaxis, :])",
"= tf.stop_gradient(attended_inputs)[tf.newaxis, :] return 0.5 * tf.reduce_mean(tf.square(target - prediction)) self._loss_function = loss_function super().build()",
"-> None: self._model.build(input_shape=(None, self.state_width)) @tf.function def loss_function(state, attended_inputs): prediction = self._model(state[tf.newaxis, :]) target",
"attended_inputs): prediction = self._model(state[tf.newaxis, :]) target = tf.stop_gradient(attended_inputs)[tf.newaxis, :] return 0.5 * tf.reduce_mean(tf.square(target",
"\"\"\"A state kernel module which adds a prediction loss for the next input",
"StateKernel) -> None: super().configure(kernel) self._model = Sequential([ Dense(self.input_width + self.state_width, activation='tanh'), Dense(self.input_width) ])",
"Tuple[tf.Variable, ...]: return tuple(self._model.trainable_weights) def get_loss(self, previous_frame: 'StateFrame', current_frame: 'StateFrame') -> Optional[tf.Tensor]: return",
"loss_function super().build() def get_trainable_weights(self) -> Tuple[tf.Variable, ...]: return tuple(self._model.trainable_weights) def get_loss(self, previous_frame: 'StateFrame',",
"<gh_stars>0 from typing import Optional, Tuple, Callable import tensorflow as tf from tensorflow.keras",
"self._model = Sequential([ Dense(self.input_width + self.state_width, activation='tanh'), Dense(self.input_width) ]) def build(self) -> None:",
"the kernel's state predictions.\"\"\" _model = None _loss_function: Callable = None def configure(self,",
"None _loss_function: Callable = None def configure(self, kernel: StateKernel) -> None: super().configure(kernel) self._model",
"Optional, Tuple, Callable import tensorflow as tf from tensorflow.keras import Sequential from tensorflow.keras.layers",
"InputPrediction(StateKernelModule): \"\"\"A state kernel module which adds a prediction loss for the next",
"self.state_width, activation='tanh'), Dense(self.input_width) ]) def build(self) -> None: self._model.build(input_shape=(None, self.state_width)) @tf.function def loss_function(state,",
"typing import Optional, Tuple, Callable import tensorflow as tf from tensorflow.keras import Sequential",
"get_trainable_weights(self) -> Tuple[tf.Variable, ...]: return tuple(self._model.trainable_weights) def get_loss(self, previous_frame: 'StateFrame', current_frame: 'StateFrame') ->",
"+ self.state_width, activation='tanh'), Dense(self.input_width) ]) def build(self) -> None: self._model.build(input_shape=(None, self.state_width)) @tf.function def",
"self.state_width)) @tf.function def loss_function(state, attended_inputs): prediction = self._model(state[tf.newaxis, :]) target = tf.stop_gradient(attended_inputs)[tf.newaxis, :]",
"- prediction)) self._loss_function = loss_function super().build() def get_trainable_weights(self) -> Tuple[tf.Variable, ...]: return tuple(self._model.trainable_weights)",
"from cephalus.kernel import StateKernel from cephalus.modules.interface import StateKernelModule __all__ = [ 'InputPrediction' ]",
"0.5 * tf.reduce_mean(tf.square(target - prediction)) self._loss_function = loss_function super().build() def get_trainable_weights(self) -> Tuple[tf.Variable,",
"Dense from cephalus.frame import StateFrame from cephalus.kernel import StateKernel from cephalus.modules.interface import StateKernelModule",
"import Sequential from tensorflow.keras.layers import Dense from cephalus.frame import StateFrame from cephalus.kernel import",
"configure(self, kernel: StateKernel) -> None: super().configure(kernel) self._model = Sequential([ Dense(self.input_width + self.state_width, activation='tanh'),",
"tf.reduce_mean(tf.square(target - prediction)) self._loss_function = loss_function super().build() def get_trainable_weights(self) -> Tuple[tf.Variable, ...]: return",
"super().build() def get_trainable_weights(self) -> Tuple[tf.Variable, ...]: return tuple(self._model.trainable_weights) def get_loss(self, previous_frame: 'StateFrame', current_frame:",
"a prediction loss for the next input to the kernel's state predictions.\"\"\" _model",
"Callable = None def configure(self, kernel: StateKernel) -> None: super().configure(kernel) self._model = Sequential([",
"tf from tensorflow.keras import Sequential from tensorflow.keras.layers import Dense from cephalus.frame import StateFrame",
"the next input to the kernel's state predictions.\"\"\" _model = None _loss_function: Callable",
"import Optional, Tuple, Callable import tensorflow as tf from tensorflow.keras import Sequential from",
"state kernel module which adds a prediction loss for the next input to",
"def get_trainable_weights(self) -> Tuple[tf.Variable, ...]: return tuple(self._model.trainable_weights) def get_loss(self, previous_frame: 'StateFrame', current_frame: 'StateFrame')",
"return 0.5 * tf.reduce_mean(tf.square(target - prediction)) self._loss_function = loss_function super().build() def get_trainable_weights(self) ->",
"= [ 'InputPrediction' ] class InputPrediction(StateKernelModule): \"\"\"A state kernel module which adds a",
"import tensorflow as tf from tensorflow.keras import Sequential from tensorflow.keras.layers import Dense from",
"Callable import tensorflow as tf from tensorflow.keras import Sequential from tensorflow.keras.layers import Dense",
"tensorflow.keras import Sequential from tensorflow.keras.layers import Dense from cephalus.frame import StateFrame from cephalus.kernel",
"kernel module which adds a prediction loss for the next input to the"
] |
[
"directory\") sys.exit(1) args[\"output\"] = val # Get the input file if len(vals) >",
"show def help_message(): print(\"usage: minij [OPTIONS] [FILE]\\n\") print(\"OPTIONS:\") print(\" -h, --help Show help",
"message if opt in (\"-h\", \"--help\"): args[\"help\"] = True help_message() sys.exit(0) # Get",
"= [\"help\", \"output=\"] try: opts, vals = getopt.getopt(args_list, shorts, longs) except getopt.error as",
"Get specific output file elif opt in (\"-o\", \"--output\"): if os.path.isdir(val): print(\"ERROR: The",
"input file if len(vals) > 1: print(\"ERROR: only one file is allowed\") sys.exit(1)",
"output = filename + \"(\" + str(count) + \")\" args[\"output\"] = output +",
"help_message(): print(\"usage: minij [OPTIONS] [FILE]\\n\") print(\"OPTIONS:\") print(\" -h, --help Show help for the",
"filename + \"(\" + str(count) + \")\" args[\"output\"] = output + \".table\" return",
"opt in (\"-o\", \"--output\"): if os.path.isdir(val): print(\"ERROR: The output file is a directory\")",
"if args[\"output\"] is None: filename = os.path.splitext(os.path.basename(args[\"input\"]))[0] output = filename count = 0",
"output = filename count = 0 while os.path.isfile(output + \".table\"): count += 1",
"Print help message if opt in (\"-h\", \"--help\"): args[\"help\"] = True help_message() sys.exit(0)",
"sys.exit(1) args[\"output\"] = val # Get the input file if len(vals) > 1:",
"file is allowed\") sys.exit(1) elif len(vals) < 1: print(\"ERROR: no file provided\") sys.exit(1)",
"get more information\") sys.exit(1) # Default values args = { \"input\": None, \"output\":",
"the program def parse_flags(args_list): shorts = \"ho:\" longs = [\"help\", \"output=\"] try: opts,",
"+ \".table\"): count += 1 output = filename + \"(\" + str(count) +",
"in (\"-o\", \"--output\"): if os.path.isdir(val): print(\"ERROR: The output file is a directory\") sys.exit(1)",
"< 1: print(\"ERROR: no file provided\") sys.exit(1) args[\"input\"] = vals[0] # Set the",
"minij [OPTIONS] [FILE]\\n\") print(\"OPTIONS:\") print(\" -h, --help Show help for the command\") print(\"",
"= 0 while os.path.isfile(output + \".table\"): count += 1 output = filename +",
"Set the output if not specified if args[\"output\"] is None: filename = os.path.splitext(os.path.basename(args[\"input\"]))[0]",
"allowed\") sys.exit(1) elif len(vals) < 1: print(\"ERROR: no file provided\") sys.exit(1) args[\"input\"] =",
"the output file\") # Try to get all the values passed to the",
"import os import sys # Help message to show def help_message(): print(\"usage: minij",
"= vals[0] # Set the output if not specified if args[\"output\"] is None:",
"args[\"output\"] is None: filename = os.path.splitext(os.path.basename(args[\"input\"]))[0] output = filename count = 0 while",
"= getopt.getopt(args_list, shorts, longs) except getopt.error as e: print(\"ERROR: %s\" % e) print(\"Try",
"+ \"(\" + str(count) + \")\" args[\"output\"] = output + \".table\" return args",
"if not specified if args[\"output\"] is None: filename = os.path.splitext(os.path.basename(args[\"input\"]))[0] output = filename",
"args = { \"input\": None, \"output\": None, } for opt, val in opts:",
"\"--output\"): if os.path.isdir(val): print(\"ERROR: The output file is a directory\") sys.exit(1) args[\"output\"] =",
"(\"-h\", \"--help\"): args[\"help\"] = True help_message() sys.exit(0) # Get specific output file elif",
"file if len(vals) > 1: print(\"ERROR: only one file is allowed\") sys.exit(1) elif",
"# Default values args = { \"input\": None, \"output\": None, } for opt,",
"val in opts: # Print help message if opt in (\"-h\", \"--help\"): args[\"help\"]",
"0 while os.path.isfile(output + \".table\"): count += 1 output = filename + \"(\"",
"print(\"ERROR: %s\" % e) print(\"Try doing minij -h or minij --help to get",
"count = 0 while os.path.isfile(output + \".table\"): count += 1 output = filename",
"program def parse_flags(args_list): shorts = \"ho:\" longs = [\"help\", \"output=\"] try: opts, vals",
"is None: filename = os.path.splitext(os.path.basename(args[\"input\"]))[0] output = filename count = 0 while os.path.isfile(output",
"to get all the values passed to the program def parse_flags(args_list): shorts =",
"values passed to the program def parse_flags(args_list): shorts = \"ho:\" longs = [\"help\",",
"the command\") print(\" -o, --output Specify the output file\") # Try to get",
"(\"-o\", \"--output\"): if os.path.isdir(val): print(\"ERROR: The output file is a directory\") sys.exit(1) args[\"output\"]",
"count += 1 output = filename + \"(\" + str(count) + \")\" args[\"output\"]",
"if len(vals) > 1: print(\"ERROR: only one file is allowed\") sys.exit(1) elif len(vals)",
"try: opts, vals = getopt.getopt(args_list, shorts, longs) except getopt.error as e: print(\"ERROR: %s\"",
"all the values passed to the program def parse_flags(args_list): shorts = \"ho:\" longs",
"sys.exit(0) # Get specific output file elif opt in (\"-o\", \"--output\"): if os.path.isdir(val):",
"information\") sys.exit(1) # Default values args = { \"input\": None, \"output\": None, }",
"1: print(\"ERROR: only one file is allowed\") sys.exit(1) elif len(vals) < 1: print(\"ERROR:",
"Default values args = { \"input\": None, \"output\": None, } for opt, val",
"os import sys # Help message to show def help_message(): print(\"usage: minij [OPTIONS]",
"sys.exit(1) elif len(vals) < 1: print(\"ERROR: no file provided\") sys.exit(1) args[\"input\"] = vals[0]",
"in (\"-h\", \"--help\"): args[\"help\"] = True help_message() sys.exit(0) # Get specific output file",
"The output file is a directory\") sys.exit(1) args[\"output\"] = val # Get the",
"getopt.error as e: print(\"ERROR: %s\" % e) print(\"Try doing minij -h or minij",
"} for opt, val in opts: # Print help message if opt in",
"val # Get the input file if len(vals) > 1: print(\"ERROR: only one",
"print(\" -h, --help Show help for the command\") print(\" -o, --output Specify the",
"in opts: # Print help message if opt in (\"-h\", \"--help\"): args[\"help\"] =",
"get all the values passed to the program def parse_flags(args_list): shorts = \"ho:\"",
"--help to get more information\") sys.exit(1) # Default values args = { \"input\":",
"[FILE]\\n\") print(\"OPTIONS:\") print(\" -h, --help Show help for the command\") print(\" -o, --output",
"None, } for opt, val in opts: # Print help message if opt",
"\"input\": None, \"output\": None, } for opt, val in opts: # Print help",
"parse_flags(args_list): shorts = \"ho:\" longs = [\"help\", \"output=\"] try: opts, vals = getopt.getopt(args_list,",
"def parse_flags(args_list): shorts = \"ho:\" longs = [\"help\", \"output=\"] try: opts, vals =",
"if opt in (\"-h\", \"--help\"): args[\"help\"] = True help_message() sys.exit(0) # Get specific",
"True help_message() sys.exit(0) # Get specific output file elif opt in (\"-o\", \"--output\"):",
"-h or minij --help to get more information\") sys.exit(1) # Default values args",
"for opt, val in opts: # Print help message if opt in (\"-h\",",
"not specified if args[\"output\"] is None: filename = os.path.splitext(os.path.basename(args[\"input\"]))[0] output = filename count",
"% e) print(\"Try doing minij -h or minij --help to get more information\")",
"while os.path.isfile(output + \".table\"): count += 1 output = filename + \"(\" +",
"print(\"Try doing minij -h or minij --help to get more information\") sys.exit(1) #",
"more information\") sys.exit(1) # Default values args = { \"input\": None, \"output\": None,",
"os.path.splitext(os.path.basename(args[\"input\"]))[0] output = filename count = 0 while os.path.isfile(output + \".table\"): count +=",
"+= 1 output = filename + \"(\" + str(count) + \")\" args[\"output\"] =",
"print(\"OPTIONS:\") print(\" -h, --help Show help for the command\") print(\" -o, --output Specify",
"file\") # Try to get all the values passed to the program def",
"getopt import os import sys # Help message to show def help_message(): print(\"usage:",
"print(\"usage: minij [OPTIONS] [FILE]\\n\") print(\"OPTIONS:\") print(\" -h, --help Show help for the command\")",
"--output Specify the output file\") # Try to get all the values passed",
"minij -h or minij --help to get more information\") sys.exit(1) # Default values",
"except getopt.error as e: print(\"ERROR: %s\" % e) print(\"Try doing minij -h or",
"\"ho:\" longs = [\"help\", \"output=\"] try: opts, vals = getopt.getopt(args_list, shorts, longs) except",
"to show def help_message(): print(\"usage: minij [OPTIONS] [FILE]\\n\") print(\"OPTIONS:\") print(\" -h, --help Show",
"\"output=\"] try: opts, vals = getopt.getopt(args_list, shorts, longs) except getopt.error as e: print(\"ERROR:",
"opt, val in opts: # Print help message if opt in (\"-h\", \"--help\"):",
"vals = getopt.getopt(args_list, shorts, longs) except getopt.error as e: print(\"ERROR: %s\" % e)",
"filename = os.path.splitext(os.path.basename(args[\"input\"]))[0] output = filename count = 0 while os.path.isfile(output + \".table\"):",
"specific output file elif opt in (\"-o\", \"--output\"): if os.path.isdir(val): print(\"ERROR: The output",
"--help Show help for the command\") print(\" -o, --output Specify the output file\")",
"output file\") # Try to get all the values passed to the program",
"# Help message to show def help_message(): print(\"usage: minij [OPTIONS] [FILE]\\n\") print(\"OPTIONS:\") print(\"",
"output file is a directory\") sys.exit(1) args[\"output\"] = val # Get the input",
"passed to the program def parse_flags(args_list): shorts = \"ho:\" longs = [\"help\", \"output=\"]",
"e) print(\"Try doing minij -h or minij --help to get more information\") sys.exit(1)",
"output file elif opt in (\"-o\", \"--output\"): if os.path.isdir(val): print(\"ERROR: The output file",
"one file is allowed\") sys.exit(1) elif len(vals) < 1: print(\"ERROR: no file provided\")",
"%s\" % e) print(\"Try doing minij -h or minij --help to get more",
"no file provided\") sys.exit(1) args[\"input\"] = vals[0] # Set the output if not",
"os.path.isdir(val): print(\"ERROR: The output file is a directory\") sys.exit(1) args[\"output\"] = val #",
"import getopt import os import sys # Help message to show def help_message():",
"= True help_message() sys.exit(0) # Get specific output file elif opt in (\"-o\",",
"args[\"help\"] = True help_message() sys.exit(0) # Get specific output file elif opt in",
"import sys # Help message to show def help_message(): print(\"usage: minij [OPTIONS] [FILE]\\n\")",
"longs = [\"help\", \"output=\"] try: opts, vals = getopt.getopt(args_list, shorts, longs) except getopt.error",
"as e: print(\"ERROR: %s\" % e) print(\"Try doing minij -h or minij --help",
"args[\"output\"] = val # Get the input file if len(vals) > 1: print(\"ERROR:",
"provided\") sys.exit(1) args[\"input\"] = vals[0] # Set the output if not specified if",
"Show help for the command\") print(\" -o, --output Specify the output file\") #",
"print(\" -o, --output Specify the output file\") # Try to get all the",
"Specify the output file\") # Try to get all the values passed to",
"vals[0] # Set the output if not specified if args[\"output\"] is None: filename",
"= os.path.splitext(os.path.basename(args[\"input\"]))[0] output = filename count = 0 while os.path.isfile(output + \".table\"): count",
"message to show def help_message(): print(\"usage: minij [OPTIONS] [FILE]\\n\") print(\"OPTIONS:\") print(\" -h, --help",
"# Get the input file if len(vals) > 1: print(\"ERROR: only one file",
"= filename + \"(\" + str(count) + \")\" args[\"output\"] = output + \".table\"",
"is a directory\") sys.exit(1) args[\"output\"] = val # Get the input file if",
"filename count = 0 while os.path.isfile(output + \".table\"): count += 1 output =",
"1: print(\"ERROR: no file provided\") sys.exit(1) args[\"input\"] = vals[0] # Set the output",
"def help_message(): print(\"usage: minij [OPTIONS] [FILE]\\n\") print(\"OPTIONS:\") print(\" -h, --help Show help for",
"# Try to get all the values passed to the program def parse_flags(args_list):",
"the values passed to the program def parse_flags(args_list): shorts = \"ho:\" longs =",
"1 output = filename + \"(\" + str(count) + \")\" args[\"output\"] = output",
"elif opt in (\"-o\", \"--output\"): if os.path.isdir(val): print(\"ERROR: The output file is a",
"-o, --output Specify the output file\") # Try to get all the values",
"output if not specified if args[\"output\"] is None: filename = os.path.splitext(os.path.basename(args[\"input\"]))[0] output =",
"[\"help\", \"output=\"] try: opts, vals = getopt.getopt(args_list, shorts, longs) except getopt.error as e:",
"opt in (\"-h\", \"--help\"): args[\"help\"] = True help_message() sys.exit(0) # Get specific output",
"print(\"ERROR: only one file is allowed\") sys.exit(1) elif len(vals) < 1: print(\"ERROR: no",
"Help message to show def help_message(): print(\"usage: minij [OPTIONS] [FILE]\\n\") print(\"OPTIONS:\") print(\" -h,",
"a directory\") sys.exit(1) args[\"output\"] = val # Get the input file if len(vals)",
"shorts, longs) except getopt.error as e: print(\"ERROR: %s\" % e) print(\"Try doing minij",
"\"output\": None, } for opt, val in opts: # Print help message if",
"\"--help\"): args[\"help\"] = True help_message() sys.exit(0) # Get specific output file elif opt",
"the input file if len(vals) > 1: print(\"ERROR: only one file is allowed\")",
"file is a directory\") sys.exit(1) args[\"output\"] = val # Get the input file",
"= val # Get the input file if len(vals) > 1: print(\"ERROR: only",
"doing minij -h or minij --help to get more information\") sys.exit(1) # Default",
"sys # Help message to show def help_message(): print(\"usage: minij [OPTIONS] [FILE]\\n\") print(\"OPTIONS:\")",
"= \"ho:\" longs = [\"help\", \"output=\"] try: opts, vals = getopt.getopt(args_list, shorts, longs)",
"sys.exit(1) # Default values args = { \"input\": None, \"output\": None, } for",
"{ \"input\": None, \"output\": None, } for opt, val in opts: # Print",
"file elif opt in (\"-o\", \"--output\"): if os.path.isdir(val): print(\"ERROR: The output file is",
"len(vals) > 1: print(\"ERROR: only one file is allowed\") sys.exit(1) elif len(vals) <",
"or minij --help to get more information\") sys.exit(1) # Default values args =",
"print(\"ERROR: no file provided\") sys.exit(1) args[\"input\"] = vals[0] # Set the output if",
"the output if not specified if args[\"output\"] is None: filename = os.path.splitext(os.path.basename(args[\"input\"]))[0] output",
"[OPTIONS] [FILE]\\n\") print(\"OPTIONS:\") print(\" -h, --help Show help for the command\") print(\" -o,",
"help message if opt in (\"-h\", \"--help\"): args[\"help\"] = True help_message() sys.exit(0) #",
"help_message() sys.exit(0) # Get specific output file elif opt in (\"-o\", \"--output\"): if",
"len(vals) < 1: print(\"ERROR: no file provided\") sys.exit(1) args[\"input\"] = vals[0] # Set",
"file provided\") sys.exit(1) args[\"input\"] = vals[0] # Set the output if not specified",
"shorts = \"ho:\" longs = [\"help\", \"output=\"] try: opts, vals = getopt.getopt(args_list, shorts,",
"None: filename = os.path.splitext(os.path.basename(args[\"input\"]))[0] output = filename count = 0 while os.path.isfile(output +",
"= { \"input\": None, \"output\": None, } for opt, val in opts: #",
"values args = { \"input\": None, \"output\": None, } for opt, val in",
"= filename count = 0 while os.path.isfile(output + \".table\"): count += 1 output",
"for the command\") print(\" -o, --output Specify the output file\") # Try to",
"command\") print(\" -o, --output Specify the output file\") # Try to get all",
"to get more information\") sys.exit(1) # Default values args = { \"input\": None,",
"specified if args[\"output\"] is None: filename = os.path.splitext(os.path.basename(args[\"input\"]))[0] output = filename count =",
"opts, vals = getopt.getopt(args_list, shorts, longs) except getopt.error as e: print(\"ERROR: %s\" %",
"\".table\"): count += 1 output = filename + \"(\" + str(count) + \")\"",
"getopt.getopt(args_list, shorts, longs) except getopt.error as e: print(\"ERROR: %s\" % e) print(\"Try doing",
"if os.path.isdir(val): print(\"ERROR: The output file is a directory\") sys.exit(1) args[\"output\"] = val",
"help for the command\") print(\" -o, --output Specify the output file\") # Try",
"only one file is allowed\") sys.exit(1) elif len(vals) < 1: print(\"ERROR: no file",
"sys.exit(1) args[\"input\"] = vals[0] # Set the output if not specified if args[\"output\"]",
"e: print(\"ERROR: %s\" % e) print(\"Try doing minij -h or minij --help to",
"None, \"output\": None, } for opt, val in opts: # Print help message",
"# Set the output if not specified if args[\"output\"] is None: filename =",
"longs) except getopt.error as e: print(\"ERROR: %s\" % e) print(\"Try doing minij -h",
"elif len(vals) < 1: print(\"ERROR: no file provided\") sys.exit(1) args[\"input\"] = vals[0] #",
"-h, --help Show help for the command\") print(\" -o, --output Specify the output",
"args[\"input\"] = vals[0] # Set the output if not specified if args[\"output\"] is",
"Get the input file if len(vals) > 1: print(\"ERROR: only one file is",
"opts: # Print help message if opt in (\"-h\", \"--help\"): args[\"help\"] = True",
"> 1: print(\"ERROR: only one file is allowed\") sys.exit(1) elif len(vals) < 1:",
"to the program def parse_flags(args_list): shorts = \"ho:\" longs = [\"help\", \"output=\"] try:",
"print(\"ERROR: The output file is a directory\") sys.exit(1) args[\"output\"] = val # Get",
"Try to get all the values passed to the program def parse_flags(args_list): shorts",
"# Print help message if opt in (\"-h\", \"--help\"): args[\"help\"] = True help_message()",
"os.path.isfile(output + \".table\"): count += 1 output = filename + \"(\" + str(count)",
"is allowed\") sys.exit(1) elif len(vals) < 1: print(\"ERROR: no file provided\") sys.exit(1) args[\"input\"]",
"# Get specific output file elif opt in (\"-o\", \"--output\"): if os.path.isdir(val): print(\"ERROR:",
"minij --help to get more information\") sys.exit(1) # Default values args = {"
] |
[
"= Contact(\"Test\",\"user\",\"0712345678\",\"<EMAIL>\") test_contact.save_contact() self.new_contact.delete_contact() self.assertEqual(len(Contact.contact_list),1) def test_find_contact_by_number(self): self.new_contact.save_contact() test_contact = Contact(\"Test\",\"user\",\"0711223344\",\"<EMAIL>\") test_contact.save_contact() found_contact",
"Contact(\"Test\",\"user\",\"0712345678\",\"<EMAIL>\") test_contact.save_contact() self.new_contact.delete_contact() self.assertEqual(len(Contact.contact_list),1) def test_find_contact_by_number(self): self.new_contact.save_contact() test_contact = Contact(\"Test\",\"user\",\"0711223344\",\"<EMAIL>\") test_contact.save_contact() found_contact =",
"self.new_contact.delete_contact() self.assertEqual(len(Contact.contact_list),1) def test_find_contact_by_number(self): self.new_contact.save_contact() test_contact = Contact(\"Test\",\"user\",\"0711223344\",\"<EMAIL>\") test_contact.save_contact() found_contact = Contact.find_by_number(\"0711223344\") self.assertEqual(found_contact.email,test_contact.email)",
"= Contact(\"James\",\"Muriuki\",\"0712345678\",\"<EMAIL>\") def test_init(self): self.assertEqual(self.new_contact.first_name,\"James\") self.assertEqual(self.new_contact.last_name,\"Muriuki\") self.assertEqual(self.new_contact.phone_number,\"0712345678\") self.assertEqual(self.new_contact.email,\"<EMAIL>\") def test_save_contact(self): self.new_contact.save_contact() self.assertEqual(len(Contact.contact_list), 1)",
"self.new_contact.save_contact() test_contact = Contact(\"Test\",\"user\",\"0711223344\",\"<EMAIL>\") test_contact.save_contact() contact_exists = Contact.contact_exist(\"0711223344\") self.assertTrue(contact_exists) def test_display_all_contacts(self): self.assertEqual(Contact.display_contacts(),Contact.contact_list) def",
"def test_init(self): self.assertEqual(self.new_contact.first_name,\"James\") self.assertEqual(self.new_contact.last_name,\"Muriuki\") self.assertEqual(self.new_contact.phone_number,\"0712345678\") self.assertEqual(self.new_contact.email,\"<EMAIL>\") def test_save_contact(self): self.new_contact.save_contact() self.assertEqual(len(Contact.contact_list), 1) def test_save_multiple_contact(self):",
"self.assertEqual(self.new_contact.phone_number,\"0712345678\") self.assertEqual(self.new_contact.email,\"<EMAIL>\") def test_save_contact(self): self.new_contact.save_contact() self.assertEqual(len(Contact.contact_list), 1) def test_save_multiple_contact(self): self.new_contact.save_contact() test_contact=Contact(\"Test\",\"user\",\"0712345678\",\"<EMAIL>\") test_contact.save_contact() self.assertEqual(len(Contact.contact_list),2)",
"def tearDown(self): Contact.contact_list=[] def test_delete_contact(self): self.new_contact.save_contact() test_contact = Contact(\"Test\",\"user\",\"0712345678\",\"<EMAIL>\") test_contact.save_contact() self.new_contact.delete_contact() self.assertEqual(len(Contact.contact_list),1) def",
"test_contact_exists(self): self.new_contact.save_contact() test_contact = Contact(\"Test\",\"user\",\"0711223344\",\"<EMAIL>\") test_contact.save_contact() contact_exists = Contact.contact_exist(\"0711223344\") self.assertTrue(contact_exists) def test_display_all_contacts(self): self.assertEqual(Contact.display_contacts(),Contact.contact_list)",
"test_init(self): self.assertEqual(self.new_contact.first_name,\"James\") self.assertEqual(self.new_contact.last_name,\"Muriuki\") self.assertEqual(self.new_contact.phone_number,\"0712345678\") self.assertEqual(self.new_contact.email,\"<EMAIL>\") def test_save_contact(self): self.new_contact.save_contact() self.assertEqual(len(Contact.contact_list), 1) def test_save_multiple_contact(self): self.new_contact.save_contact()",
"import Contact class TestContact(unittest.TestCase): def setUp(self): self.new_contact = Contact(\"James\",\"Muriuki\",\"0712345678\",\"<EMAIL>\") def test_init(self): self.assertEqual(self.new_contact.first_name,\"James\") self.assertEqual(self.new_contact.last_name,\"Muriuki\")",
"def test_find_contact_by_number(self): self.new_contact.save_contact() test_contact = Contact(\"Test\",\"user\",\"0711223344\",\"<EMAIL>\") test_contact.save_contact() found_contact = Contact.find_by_number(\"0711223344\") self.assertEqual(found_contact.email,test_contact.email) def test_contact_exists(self):",
"def test_delete_contact(self): self.new_contact.save_contact() test_contact = Contact(\"Test\",\"user\",\"0712345678\",\"<EMAIL>\") test_contact.save_contact() self.new_contact.delete_contact() self.assertEqual(len(Contact.contact_list),1) def test_find_contact_by_number(self): self.new_contact.save_contact() test_contact",
"from module_contact import Contact class TestContact(unittest.TestCase): def setUp(self): self.new_contact = Contact(\"James\",\"Muriuki\",\"0712345678\",\"<EMAIL>\") def test_init(self):",
"tearDown(self): Contact.contact_list=[] def test_delete_contact(self): self.new_contact.save_contact() test_contact = Contact(\"Test\",\"user\",\"0712345678\",\"<EMAIL>\") test_contact.save_contact() self.new_contact.delete_contact() self.assertEqual(len(Contact.contact_list),1) def test_find_contact_by_number(self):",
"self.assertEqual(self.new_contact.last_name,\"Muriuki\") self.assertEqual(self.new_contact.phone_number,\"0712345678\") self.assertEqual(self.new_contact.email,\"<EMAIL>\") def test_save_contact(self): self.new_contact.save_contact() self.assertEqual(len(Contact.contact_list), 1) def test_save_multiple_contact(self): self.new_contact.save_contact() test_contact=Contact(\"Test\",\"user\",\"0712345678\",\"<EMAIL>\") test_contact.save_contact()",
"Contact class TestContact(unittest.TestCase): def setUp(self): self.new_contact = Contact(\"James\",\"Muriuki\",\"0712345678\",\"<EMAIL>\") def test_init(self): self.assertEqual(self.new_contact.first_name,\"James\") self.assertEqual(self.new_contact.last_name,\"Muriuki\") self.assertEqual(self.new_contact.phone_number,\"0712345678\")",
"test_save_contact(self): self.new_contact.save_contact() self.assertEqual(len(Contact.contact_list), 1) def test_save_multiple_contact(self): self.new_contact.save_contact() test_contact=Contact(\"Test\",\"user\",\"0712345678\",\"<EMAIL>\") test_contact.save_contact() self.assertEqual(len(Contact.contact_list),2) def tearDown(self): Contact.contact_list=[]",
"test_contact.save_contact() self.assertEqual(len(Contact.contact_list),2) def tearDown(self): Contact.contact_list=[] def test_delete_contact(self): self.new_contact.save_contact() test_contact = Contact(\"Test\",\"user\",\"0712345678\",\"<EMAIL>\") test_contact.save_contact() self.new_contact.delete_contact()",
"Contact.find_by_number(\"0711223344\") self.assertEqual(found_contact.email,test_contact.email) def test_contact_exists(self): self.new_contact.save_contact() test_contact = Contact(\"Test\",\"user\",\"0711223344\",\"<EMAIL>\") test_contact.save_contact() contact_exists = Contact.contact_exist(\"0711223344\") self.assertTrue(contact_exists)",
"def test_contact_exists(self): self.new_contact.save_contact() test_contact = Contact(\"Test\",\"user\",\"0711223344\",\"<EMAIL>\") test_contact.save_contact() contact_exists = Contact.contact_exist(\"0711223344\") self.assertTrue(contact_exists) def test_display_all_contacts(self):",
"Contact.contact_exist(\"0711223344\") self.assertTrue(contact_exists) def test_display_all_contacts(self): self.assertEqual(Contact.display_contacts(),Contact.contact_list) def test_copy_email(self): self.new_contact.save_contact() Contact.copy_email(\"0712345678\") self.assertEqual(self.new_contact.email,pyperclip.paste()) if __name__ ==",
"class TestContact(unittest.TestCase): def setUp(self): self.new_contact = Contact(\"James\",\"Muriuki\",\"0712345678\",\"<EMAIL>\") def test_init(self): self.assertEqual(self.new_contact.first_name,\"James\") self.assertEqual(self.new_contact.last_name,\"Muriuki\") self.assertEqual(self.new_contact.phone_number,\"0712345678\") self.assertEqual(self.new_contact.email,\"<EMAIL>\")",
"Contact(\"Test\",\"user\",\"0711223344\",\"<EMAIL>\") test_contact.save_contact() contact_exists = Contact.contact_exist(\"0711223344\") self.assertTrue(contact_exists) def test_display_all_contacts(self): self.assertEqual(Contact.display_contacts(),Contact.contact_list) def test_copy_email(self): self.new_contact.save_contact() Contact.copy_email(\"0712345678\")",
"contact_exists = Contact.contact_exist(\"0711223344\") self.assertTrue(contact_exists) def test_display_all_contacts(self): self.assertEqual(Contact.display_contacts(),Contact.contact_list) def test_copy_email(self): self.new_contact.save_contact() Contact.copy_email(\"0712345678\") self.assertEqual(self.new_contact.email,pyperclip.paste()) if",
"self.assertTrue(contact_exists) def test_display_all_contacts(self): self.assertEqual(Contact.display_contacts(),Contact.contact_list) def test_copy_email(self): self.new_contact.save_contact() Contact.copy_email(\"0712345678\") self.assertEqual(self.new_contact.email,pyperclip.paste()) if __name__ == '__main__':",
"self.new_contact.save_contact() self.assertEqual(len(Contact.contact_list), 1) def test_save_multiple_contact(self): self.new_contact.save_contact() test_contact=Contact(\"Test\",\"user\",\"0712345678\",\"<EMAIL>\") test_contact.save_contact() self.assertEqual(len(Contact.contact_list),2) def tearDown(self): Contact.contact_list=[] def",
"self.new_contact.save_contact() test_contact = Contact(\"Test\",\"user\",\"0711223344\",\"<EMAIL>\") test_contact.save_contact() found_contact = Contact.find_by_number(\"0711223344\") self.assertEqual(found_contact.email,test_contact.email) def test_contact_exists(self): self.new_contact.save_contact() test_contact",
"= Contact.contact_exist(\"0711223344\") self.assertTrue(contact_exists) def test_display_all_contacts(self): self.assertEqual(Contact.display_contacts(),Contact.contact_list) def test_copy_email(self): self.new_contact.save_contact() Contact.copy_email(\"0712345678\") self.assertEqual(self.new_contact.email,pyperclip.paste()) if __name__",
"module_contact import Contact class TestContact(unittest.TestCase): def setUp(self): self.new_contact = Contact(\"James\",\"Muriuki\",\"0712345678\",\"<EMAIL>\") def test_init(self): self.assertEqual(self.new_contact.first_name,\"James\")",
"self.assertEqual(found_contact.email,test_contact.email) def test_contact_exists(self): self.new_contact.save_contact() test_contact = Contact(\"Test\",\"user\",\"0711223344\",\"<EMAIL>\") test_contact.save_contact() contact_exists = Contact.contact_exist(\"0711223344\") self.assertTrue(contact_exists) def",
"test_find_contact_by_number(self): self.new_contact.save_contact() test_contact = Contact(\"Test\",\"user\",\"0711223344\",\"<EMAIL>\") test_contact.save_contact() found_contact = Contact.find_by_number(\"0711223344\") self.assertEqual(found_contact.email,test_contact.email) def test_contact_exists(self): self.new_contact.save_contact()",
"= Contact(\"Test\",\"user\",\"0711223344\",\"<EMAIL>\") test_contact.save_contact() contact_exists = Contact.contact_exist(\"0711223344\") self.assertTrue(contact_exists) def test_display_all_contacts(self): self.assertEqual(Contact.display_contacts(),Contact.contact_list) def test_copy_email(self): self.new_contact.save_contact()",
"import unittest import pyperclip from module_contact import Contact class TestContact(unittest.TestCase): def setUp(self): self.new_contact",
"self.new_contact = Contact(\"James\",\"Muriuki\",\"0712345678\",\"<EMAIL>\") def test_init(self): self.assertEqual(self.new_contact.first_name,\"James\") self.assertEqual(self.new_contact.last_name,\"Muriuki\") self.assertEqual(self.new_contact.phone_number,\"0712345678\") self.assertEqual(self.new_contact.email,\"<EMAIL>\") def test_save_contact(self): self.new_contact.save_contact() self.assertEqual(len(Contact.contact_list),",
"unittest import pyperclip from module_contact import Contact class TestContact(unittest.TestCase): def setUp(self): self.new_contact =",
"test_save_multiple_contact(self): self.new_contact.save_contact() test_contact=Contact(\"Test\",\"user\",\"0712345678\",\"<EMAIL>\") test_contact.save_contact() self.assertEqual(len(Contact.contact_list),2) def tearDown(self): Contact.contact_list=[] def test_delete_contact(self): self.new_contact.save_contact() test_contact =",
"self.assertEqual(len(Contact.contact_list),2) def tearDown(self): Contact.contact_list=[] def test_delete_contact(self): self.new_contact.save_contact() test_contact = Contact(\"Test\",\"user\",\"0712345678\",\"<EMAIL>\") test_contact.save_contact() self.new_contact.delete_contact() self.assertEqual(len(Contact.contact_list),1)",
"Contact(\"James\",\"Muriuki\",\"0712345678\",\"<EMAIL>\") def test_init(self): self.assertEqual(self.new_contact.first_name,\"James\") self.assertEqual(self.new_contact.last_name,\"Muriuki\") self.assertEqual(self.new_contact.phone_number,\"0712345678\") self.assertEqual(self.new_contact.email,\"<EMAIL>\") def test_save_contact(self): self.new_contact.save_contact() self.assertEqual(len(Contact.contact_list), 1) def",
"Contact.contact_list=[] def test_delete_contact(self): self.new_contact.save_contact() test_contact = Contact(\"Test\",\"user\",\"0712345678\",\"<EMAIL>\") test_contact.save_contact() self.new_contact.delete_contact() self.assertEqual(len(Contact.contact_list),1) def test_find_contact_by_number(self): self.new_contact.save_contact()",
"test_contact.save_contact() contact_exists = Contact.contact_exist(\"0711223344\") self.assertTrue(contact_exists) def test_display_all_contacts(self): self.assertEqual(Contact.display_contacts(),Contact.contact_list) def test_copy_email(self): self.new_contact.save_contact() Contact.copy_email(\"0712345678\") self.assertEqual(self.new_contact.email,pyperclip.paste())",
"self.assertEqual(len(Contact.contact_list), 1) def test_save_multiple_contact(self): self.new_contact.save_contact() test_contact=Contact(\"Test\",\"user\",\"0712345678\",\"<EMAIL>\") test_contact.save_contact() self.assertEqual(len(Contact.contact_list),2) def tearDown(self): Contact.contact_list=[] def test_delete_contact(self):",
"pyperclip from module_contact import Contact class TestContact(unittest.TestCase): def setUp(self): self.new_contact = Contact(\"James\",\"Muriuki\",\"0712345678\",\"<EMAIL>\") def",
"= Contact.find_by_number(\"0711223344\") self.assertEqual(found_contact.email,test_contact.email) def test_contact_exists(self): self.new_contact.save_contact() test_contact = Contact(\"Test\",\"user\",\"0711223344\",\"<EMAIL>\") test_contact.save_contact() contact_exists = Contact.contact_exist(\"0711223344\")",
"test_contact.save_contact() found_contact = Contact.find_by_number(\"0711223344\") self.assertEqual(found_contact.email,test_contact.email) def test_contact_exists(self): self.new_contact.save_contact() test_contact = Contact(\"Test\",\"user\",\"0711223344\",\"<EMAIL>\") test_contact.save_contact() contact_exists",
"test_contact=Contact(\"Test\",\"user\",\"0712345678\",\"<EMAIL>\") test_contact.save_contact() self.assertEqual(len(Contact.contact_list),2) def tearDown(self): Contact.contact_list=[] def test_delete_contact(self): self.new_contact.save_contact() test_contact = Contact(\"Test\",\"user\",\"0712345678\",\"<EMAIL>\") test_contact.save_contact()",
"Contact(\"Test\",\"user\",\"0711223344\",\"<EMAIL>\") test_contact.save_contact() found_contact = Contact.find_by_number(\"0711223344\") self.assertEqual(found_contact.email,test_contact.email) def test_contact_exists(self): self.new_contact.save_contact() test_contact = Contact(\"Test\",\"user\",\"0711223344\",\"<EMAIL>\") test_contact.save_contact()",
"self.new_contact.save_contact() test_contact=Contact(\"Test\",\"user\",\"0712345678\",\"<EMAIL>\") test_contact.save_contact() self.assertEqual(len(Contact.contact_list),2) def tearDown(self): Contact.contact_list=[] def test_delete_contact(self): self.new_contact.save_contact() test_contact = Contact(\"Test\",\"user\",\"0712345678\",\"<EMAIL>\")",
"test_contact = Contact(\"Test\",\"user\",\"0712345678\",\"<EMAIL>\") test_contact.save_contact() self.new_contact.delete_contact() self.assertEqual(len(Contact.contact_list),1) def test_find_contact_by_number(self): self.new_contact.save_contact() test_contact = Contact(\"Test\",\"user\",\"0711223344\",\"<EMAIL>\") test_contact.save_contact()",
"def test_display_all_contacts(self): self.assertEqual(Contact.display_contacts(),Contact.contact_list) def test_copy_email(self): self.new_contact.save_contact() Contact.copy_email(\"0712345678\") self.assertEqual(self.new_contact.email,pyperclip.paste()) if __name__ == '__main__': unittest.main()",
"import pyperclip from module_contact import Contact class TestContact(unittest.TestCase): def setUp(self): self.new_contact = Contact(\"James\",\"Muriuki\",\"0712345678\",\"<EMAIL>\")",
"self.assertEqual(self.new_contact.first_name,\"James\") self.assertEqual(self.new_contact.last_name,\"Muriuki\") self.assertEqual(self.new_contact.phone_number,\"0712345678\") self.assertEqual(self.new_contact.email,\"<EMAIL>\") def test_save_contact(self): self.new_contact.save_contact() self.assertEqual(len(Contact.contact_list), 1) def test_save_multiple_contact(self): self.new_contact.save_contact() test_contact=Contact(\"Test\",\"user\",\"0712345678\",\"<EMAIL>\")",
"= Contact(\"Test\",\"user\",\"0711223344\",\"<EMAIL>\") test_contact.save_contact() found_contact = Contact.find_by_number(\"0711223344\") self.assertEqual(found_contact.email,test_contact.email) def test_contact_exists(self): self.new_contact.save_contact() test_contact = Contact(\"Test\",\"user\",\"0711223344\",\"<EMAIL>\")",
"1) def test_save_multiple_contact(self): self.new_contact.save_contact() test_contact=Contact(\"Test\",\"user\",\"0712345678\",\"<EMAIL>\") test_contact.save_contact() self.assertEqual(len(Contact.contact_list),2) def tearDown(self): Contact.contact_list=[] def test_delete_contact(self): self.new_contact.save_contact()",
"setUp(self): self.new_contact = Contact(\"James\",\"Muriuki\",\"0712345678\",\"<EMAIL>\") def test_init(self): self.assertEqual(self.new_contact.first_name,\"James\") self.assertEqual(self.new_contact.last_name,\"Muriuki\") self.assertEqual(self.new_contact.phone_number,\"0712345678\") self.assertEqual(self.new_contact.email,\"<EMAIL>\") def test_save_contact(self): self.new_contact.save_contact()",
"test_contact = Contact(\"Test\",\"user\",\"0711223344\",\"<EMAIL>\") test_contact.save_contact() contact_exists = Contact.contact_exist(\"0711223344\") self.assertTrue(contact_exists) def test_display_all_contacts(self): self.assertEqual(Contact.display_contacts(),Contact.contact_list) def test_copy_email(self):",
"test_delete_contact(self): self.new_contact.save_contact() test_contact = Contact(\"Test\",\"user\",\"0712345678\",\"<EMAIL>\") test_contact.save_contact() self.new_contact.delete_contact() self.assertEqual(len(Contact.contact_list),1) def test_find_contact_by_number(self): self.new_contact.save_contact() test_contact =",
"self.assertEqual(self.new_contact.email,\"<EMAIL>\") def test_save_contact(self): self.new_contact.save_contact() self.assertEqual(len(Contact.contact_list), 1) def test_save_multiple_contact(self): self.new_contact.save_contact() test_contact=Contact(\"Test\",\"user\",\"0712345678\",\"<EMAIL>\") test_contact.save_contact() self.assertEqual(len(Contact.contact_list),2) def",
"test_contact = Contact(\"Test\",\"user\",\"0711223344\",\"<EMAIL>\") test_contact.save_contact() found_contact = Contact.find_by_number(\"0711223344\") self.assertEqual(found_contact.email,test_contact.email) def test_contact_exists(self): self.new_contact.save_contact() test_contact =",
"def test_save_multiple_contact(self): self.new_contact.save_contact() test_contact=Contact(\"Test\",\"user\",\"0712345678\",\"<EMAIL>\") test_contact.save_contact() self.assertEqual(len(Contact.contact_list),2) def tearDown(self): Contact.contact_list=[] def test_delete_contact(self): self.new_contact.save_contact() test_contact",
"def setUp(self): self.new_contact = Contact(\"James\",\"Muriuki\",\"0712345678\",\"<EMAIL>\") def test_init(self): self.assertEqual(self.new_contact.first_name,\"James\") self.assertEqual(self.new_contact.last_name,\"Muriuki\") self.assertEqual(self.new_contact.phone_number,\"0712345678\") self.assertEqual(self.new_contact.email,\"<EMAIL>\") def test_save_contact(self):",
"self.new_contact.save_contact() test_contact = Contact(\"Test\",\"user\",\"0712345678\",\"<EMAIL>\") test_contact.save_contact() self.new_contact.delete_contact() self.assertEqual(len(Contact.contact_list),1) def test_find_contact_by_number(self): self.new_contact.save_contact() test_contact = Contact(\"Test\",\"user\",\"0711223344\",\"<EMAIL>\")",
"found_contact = Contact.find_by_number(\"0711223344\") self.assertEqual(found_contact.email,test_contact.email) def test_contact_exists(self): self.new_contact.save_contact() test_contact = Contact(\"Test\",\"user\",\"0711223344\",\"<EMAIL>\") test_contact.save_contact() contact_exists =",
"def test_save_contact(self): self.new_contact.save_contact() self.assertEqual(len(Contact.contact_list), 1) def test_save_multiple_contact(self): self.new_contact.save_contact() test_contact=Contact(\"Test\",\"user\",\"0712345678\",\"<EMAIL>\") test_contact.save_contact() self.assertEqual(len(Contact.contact_list),2) def tearDown(self):",
"test_contact.save_contact() self.new_contact.delete_contact() self.assertEqual(len(Contact.contact_list),1) def test_find_contact_by_number(self): self.new_contact.save_contact() test_contact = Contact(\"Test\",\"user\",\"0711223344\",\"<EMAIL>\") test_contact.save_contact() found_contact = Contact.find_by_number(\"0711223344\")",
"self.assertEqual(len(Contact.contact_list),1) def test_find_contact_by_number(self): self.new_contact.save_contact() test_contact = Contact(\"Test\",\"user\",\"0711223344\",\"<EMAIL>\") test_contact.save_contact() found_contact = Contact.find_by_number(\"0711223344\") self.assertEqual(found_contact.email,test_contact.email) def",
"TestContact(unittest.TestCase): def setUp(self): self.new_contact = Contact(\"James\",\"Muriuki\",\"0712345678\",\"<EMAIL>\") def test_init(self): self.assertEqual(self.new_contact.first_name,\"James\") self.assertEqual(self.new_contact.last_name,\"Muriuki\") self.assertEqual(self.new_contact.phone_number,\"0712345678\") self.assertEqual(self.new_contact.email,\"<EMAIL>\") def"
] |
[
"elif(cmd[:3] == 'PUT'): os.chdir('c:/Users/<NAME>/Desktop/client') dosyalar = os.listdir('c:/Users/<NAME>IN/Desktop/client') #göndereceğimiz dosyanın yolunu giriyoruz if cmd[4:]",
"l = f.read(buf) print('Tamamlandı') print('Bağlantı kapatılıyor') sys.exit() else: print('Böyle bir dosya bulunamadı') elif(cmd[:3]",
"'GET'): with open('gelendosya.txt', 'wb') as f: print('Dosya alınıyor...') gdata,addr = client.recvfrom(buf) if not",
"(l): client.sendto(l,ADDR) print('Gönderiliyor\\n ',repr(l)) l = f.read(buf) print('Tamamlandı') print('Bağlantı kapatılıyor') sys.exit() else: print('Böyle",
"os.listdir('c:/Users/<NAME>IN/Desktop/client') #göndereceğimiz dosyanın yolunu giriyoruz if cmd[4:] in dosyalar: dosyaAdi = cmd[4:] f=",
"= cmd[4:] f= open(dosyaAdi,'rb') l = f.read(buf) while (l): client.sendto(l,ADDR) print('Gönderiliyor\\n ',repr(l)) l",
"cmd[4:] in dosyalar: dosyaAdi = cmd[4:] f= open(dosyaAdi,'rb') l = f.read(buf) while (l):",
"if(cmd[:3] == 'lis'): ldata,addr = client.recvfrom(buf) data_arr = pickle.loads(ldata) print(data_arr) elif(cmd[:3] == 'PUT'):",
"input('Bağlanmak istediğiniz sunucu IP: ') PORT = 42 buf = 2048 ADDR =",
"PORT = 42 buf = 2048 ADDR = (IP,PORT) client = socket.socket(socket.AF_INET,socket.SOCK_DGRAM) while",
"== 'PUT'): os.chdir('c:/Users/<NAME>/Desktop/client') dosyalar = os.listdir('c:/Users/<NAME>IN/Desktop/client') #göndereceğimiz dosyanın yolunu giriyoruz if cmd[4:] in",
"os import pickle IP = input('Bağlanmak istediğiniz sunucu IP: ') PORT = 42",
"print('Dosya alınıyor...') gdata,addr = client.recvfrom(buf) if not gdata: break f.write(gdata) print('Tamamlandı') print('Bağlantı kapatılıyor')",
"buf = 2048 ADDR = (IP,PORT) client = socket.socket(socket.AF_INET,socket.SOCK_DGRAM) while True: cmd =",
"dosyanın yolunu giriyoruz if cmd[4:] in dosyalar: dosyaAdi = cmd[4:] f= open(dosyaAdi,'rb') l",
"Enes TEKİN 150401032 import socket import sys import os import pickle IP =",
"in dosyalar: dosyaAdi = cmd[4:] f= open(dosyaAdi,'rb') l = f.read(buf) while (l): client.sendto(l,ADDR)",
"IP = input('Bağlanmak istediğiniz sunucu IP: ') PORT = 42 buf = 2048",
"TEKİN 150401032 import socket import sys import os import pickle IP = input('Bağlanmak",
"client.sendto(l,ADDR) print('Gönderiliyor\\n ',repr(l)) l = f.read(buf) print('Tamamlandı') print('Bağlantı kapatılıyor') sys.exit() else: print('Böyle bir",
"ADDR = (IP,PORT) client = socket.socket(socket.AF_INET,socket.SOCK_DGRAM) while True: cmd = input('\\n1. Sunucu listesini",
"print(data_arr) elif(cmd[:3] == 'PUT'): os.chdir('c:/Users/<NAME>/Desktop/client') dosyalar = os.listdir('c:/Users/<NAME>IN/Desktop/client') #göndereceğimiz dosyanın yolunu giriyoruz if",
"as f: print('Dosya alınıyor...') gdata,addr = client.recvfrom(buf) if not gdata: break f.write(gdata) print('Tamamlandı')",
"client.recvfrom(buf) data_arr = pickle.loads(ldata) print(data_arr) elif(cmd[:3] == 'PUT'): os.chdir('c:/Users/<NAME>/Desktop/client') dosyalar = os.listdir('c:/Users/<NAME>IN/Desktop/client') #göndereceğimiz",
"yolunu giriyoruz if cmd[4:] in dosyalar: dosyaAdi = cmd[4:] f= open(dosyaAdi,'rb') l =",
"150401032 import socket import sys import os import pickle IP = input('Bağlanmak istediğiniz",
"'PUT'): os.chdir('c:/Users/<NAME>/Desktop/client') dosyalar = os.listdir('c:/Users/<NAME>IN/Desktop/client') #göndereceğimiz dosyanın yolunu giriyoruz if cmd[4:] in dosyalar:",
"while True: cmd = input('\\n1. Sunucu listesini listelemek için liste yazınız\\n2. Sunucuya dosya",
"#GET transferfile.txt PUT transferfile.txt gibi client.sendto(cmd.encode('UTF-8'),ADDR) if(cmd[:3] == 'lis'): ldata,addr = client.recvfrom(buf) data_arr",
"sys.exit() else: print('Böyle bir dosya bulunamadı') elif(cmd[:3] == 'GET'): with open('gelendosya.txt', 'wb') as",
"os.chdir('c:/Users/<NAME>/Desktop/client') dosyalar = os.listdir('c:/Users/<NAME>IN/Desktop/client') #göndereceğimiz dosyanın yolunu giriyoruz if cmd[4:] in dosyalar: dosyaAdi",
"= 42 buf = 2048 ADDR = (IP,PORT) client = socket.socket(socket.AF_INET,socket.SOCK_DGRAM) while True:",
"#göndereceğimiz dosyanın yolunu giriyoruz if cmd[4:] in dosyalar: dosyaAdi = cmd[4:] f= open(dosyaAdi,'rb')",
"= 2048 ADDR = (IP,PORT) client = socket.socket(socket.AF_INET,socket.SOCK_DGRAM) while True: cmd = input('\\n1.",
"sunucu IP: ') PORT = 42 buf = 2048 ADDR = (IP,PORT) client",
"client = socket.socket(socket.AF_INET,socket.SOCK_DGRAM) while True: cmd = input('\\n1. Sunucu listesini listelemek için liste",
"client.recvfrom(buf) if not gdata: break f.write(gdata) print('Tamamlandı') print('Bağlantı kapatılıyor') sys.exit() else: print('Geçersiz komut",
"f.read(buf) print('Tamamlandı') print('Bağlantı kapatılıyor') sys.exit() else: print('Böyle bir dosya bulunamadı') elif(cmd[:3] == 'GET'):",
"cmd = input('\\n1. Sunucu listesini listelemek için liste yazınız\\n2. Sunucuya dosya eklemek için",
"True: cmd = input('\\n1. Sunucu listesini listelemek için liste yazınız\\n2. Sunucuya dosya eklemek",
"PUT dosya adı giriniz\\n3. Sunucudan dosya indirmek için GET dosya adı giriniz\\n') #GET",
"dosyalar = os.listdir('c:/Users/<NAME>IN/Desktop/client') #göndereceğimiz dosyanın yolunu giriyoruz if cmd[4:] in dosyalar: dosyaAdi =",
"import pickle IP = input('Bağlanmak istediğiniz sunucu IP: ') PORT = 42 buf",
"giriniz\\n') #GET transferfile.txt PUT transferfile.txt gibi client.sendto(cmd.encode('UTF-8'),ADDR) if(cmd[:3] == 'lis'): ldata,addr = client.recvfrom(buf)",
"with open('gelendosya.txt', 'wb') as f: print('Dosya alınıyor...') gdata,addr = client.recvfrom(buf) if not gdata:",
"sys import os import pickle IP = input('Bağlanmak istediğiniz sunucu IP: ') PORT",
"listelemek için liste yazınız\\n2. Sunucuya dosya eklemek için PUT dosya adı giriniz\\n3. Sunucudan",
"else: print('Böyle bir dosya bulunamadı') elif(cmd[:3] == 'GET'): with open('gelendosya.txt', 'wb') as f:",
"istediğiniz sunucu IP: ') PORT = 42 buf = 2048 ADDR = (IP,PORT)",
"giriniz\\n3. Sunucudan dosya indirmek için GET dosya adı giriniz\\n') #GET transferfile.txt PUT transferfile.txt",
"'lis'): ldata,addr = client.recvfrom(buf) data_arr = pickle.loads(ldata) print(data_arr) elif(cmd[:3] == 'PUT'): os.chdir('c:/Users/<NAME>/Desktop/client') dosyalar",
"(IP,PORT) client = socket.socket(socket.AF_INET,socket.SOCK_DGRAM) while True: cmd = input('\\n1. Sunucu listesini listelemek için",
"if not gdata: break f.write(gdata) print('Tamamlandı') print('Bağlantı kapatılıyor') sys.exit() else: print('Geçersiz komut girdiniz')",
"'wb') as f: print('Dosya alınıyor...') gdata,addr = client.recvfrom(buf) if not gdata: break f.write(gdata)",
"Sunucu listesini listelemek için liste yazınız\\n2. Sunucuya dosya eklemek için PUT dosya adı",
"dosya adı giriniz\\n') #GET transferfile.txt PUT transferfile.txt gibi client.sendto(cmd.encode('UTF-8'),ADDR) if(cmd[:3] == 'lis'): ldata,addr",
"alınıyor...') gdata,addr = client.recvfrom(buf) if not gdata: break f.write(gdata) print('Tamamlandı') print('Bağlantı kapatılıyor') sys.exit()",
"open('gelendosya.txt', 'wb') as f: print('Dosya alınıyor...') gdata,addr = client.recvfrom(buf) if not gdata: break",
"42 buf = 2048 ADDR = (IP,PORT) client = socket.socket(socket.AF_INET,socket.SOCK_DGRAM) while True: cmd",
"IP: ') PORT = 42 buf = 2048 ADDR = (IP,PORT) client =",
"print('Gönderiliyor\\n ',repr(l)) l = f.read(buf) print('Tamamlandı') print('Bağlantı kapatılıyor') sys.exit() else: print('Böyle bir dosya",
"= pickle.loads(ldata) print(data_arr) elif(cmd[:3] == 'PUT'): os.chdir('c:/Users/<NAME>/Desktop/client') dosyalar = os.listdir('c:/Users/<NAME>IN/Desktop/client') #göndereceğimiz dosyanın yolunu",
"print('Tamamlandı') print('Bağlantı kapatılıyor') sys.exit() else: print('Böyle bir dosya bulunamadı') elif(cmd[:3] == 'GET'): with",
"dosya bulunamadı') elif(cmd[:3] == 'GET'): with open('gelendosya.txt', 'wb') as f: print('Dosya alınıyor...') gdata,addr",
"= client.recvfrom(buf) data_arr = pickle.loads(ldata) print(data_arr) elif(cmd[:3] == 'PUT'): os.chdir('c:/Users/<NAME>/Desktop/client') dosyalar = os.listdir('c:/Users/<NAME>IN/Desktop/client')",
"yazınız\\n2. Sunucuya dosya eklemek için PUT dosya adı giriniz\\n3. Sunucudan dosya indirmek için",
"') PORT = 42 buf = 2048 ADDR = (IP,PORT) client = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)",
"pickle.loads(ldata) print(data_arr) elif(cmd[:3] == 'PUT'): os.chdir('c:/Users/<NAME>/Desktop/client') dosyalar = os.listdir('c:/Users/<NAME>IN/Desktop/client') #göndereceğimiz dosyanın yolunu giriyoruz",
"= (IP,PORT) client = socket.socket(socket.AF_INET,socket.SOCK_DGRAM) while True: cmd = input('\\n1. Sunucu listesini listelemek",
"= f.read(buf) print('Tamamlandı') print('Bağlantı kapatılıyor') sys.exit() else: print('Böyle bir dosya bulunamadı') elif(cmd[:3] ==",
"listesini listelemek için liste yazınız\\n2. Sunucuya dosya eklemek için PUT dosya adı giriniz\\n3.",
"if cmd[4:] in dosyalar: dosyaAdi = cmd[4:] f= open(dosyaAdi,'rb') l = f.read(buf) while",
"',repr(l)) l = f.read(buf) print('Tamamlandı') print('Bağlantı kapatılıyor') sys.exit() else: print('Böyle bir dosya bulunamadı')",
"adı giriniz\\n3. Sunucudan dosya indirmek için GET dosya adı giriniz\\n') #GET transferfile.txt PUT",
"GET dosya adı giriniz\\n') #GET transferfile.txt PUT transferfile.txt gibi client.sendto(cmd.encode('UTF-8'),ADDR) if(cmd[:3] == 'lis'):",
"f: print('Dosya alınıyor...') gdata,addr = client.recvfrom(buf) if not gdata: break f.write(gdata) print('Tamamlandı') print('Bağlantı",
"== 'GET'): with open('gelendosya.txt', 'wb') as f: print('Dosya alınıyor...') gdata,addr = client.recvfrom(buf) if",
"data_arr = pickle.loads(ldata) print(data_arr) elif(cmd[:3] == 'PUT'): os.chdir('c:/Users/<NAME>/Desktop/client') dosyalar = os.listdir('c:/Users/<NAME>IN/Desktop/client') #göndereceğimiz dosyanın",
"bir dosya bulunamadı') elif(cmd[:3] == 'GET'): with open('gelendosya.txt', 'wb') as f: print('Dosya alınıyor...')",
"<gh_stars>1-10 # Enes TEKİN 150401032 import socket import sys import os import pickle",
"= socket.socket(socket.AF_INET,socket.SOCK_DGRAM) while True: cmd = input('\\n1. Sunucu listesini listelemek için liste yazınız\\n2.",
"elif(cmd[:3] == 'GET'): with open('gelendosya.txt', 'wb') as f: print('Dosya alınıyor...') gdata,addr = client.recvfrom(buf)",
"adı giriniz\\n') #GET transferfile.txt PUT transferfile.txt gibi client.sendto(cmd.encode('UTF-8'),ADDR) if(cmd[:3] == 'lis'): ldata,addr =",
"= os.listdir('c:/Users/<NAME>IN/Desktop/client') #göndereceğimiz dosyanın yolunu giriyoruz if cmd[4:] in dosyalar: dosyaAdi = cmd[4:]",
"gibi client.sendto(cmd.encode('UTF-8'),ADDR) if(cmd[:3] == 'lis'): ldata,addr = client.recvfrom(buf) data_arr = pickle.loads(ldata) print(data_arr) elif(cmd[:3]",
"liste yazınız\\n2. Sunucuya dosya eklemek için PUT dosya adı giriniz\\n3. Sunucudan dosya indirmek",
"dosyalar: dosyaAdi = cmd[4:] f= open(dosyaAdi,'rb') l = f.read(buf) while (l): client.sendto(l,ADDR) print('Gönderiliyor\\n",
"dosyaAdi = cmd[4:] f= open(dosyaAdi,'rb') l = f.read(buf) while (l): client.sendto(l,ADDR) print('Gönderiliyor\\n ',repr(l))",
"f= open(dosyaAdi,'rb') l = f.read(buf) while (l): client.sendto(l,ADDR) print('Gönderiliyor\\n ',repr(l)) l = f.read(buf)",
"eklemek için PUT dosya adı giriniz\\n3. Sunucudan dosya indirmek için GET dosya adı",
"# Enes TEKİN 150401032 import socket import sys import os import pickle IP",
"indirmek için GET dosya adı giriniz\\n') #GET transferfile.txt PUT transferfile.txt gibi client.sendto(cmd.encode('UTF-8'),ADDR) if(cmd[:3]",
"dosya indirmek için GET dosya adı giriniz\\n') #GET transferfile.txt PUT transferfile.txt gibi client.sendto(cmd.encode('UTF-8'),ADDR)",
"= client.recvfrom(buf) if not gdata: break f.write(gdata) print('Tamamlandı') print('Bağlantı kapatılıyor') sys.exit() else: print('Geçersiz",
"gdata,addr = client.recvfrom(buf) if not gdata: break f.write(gdata) print('Tamamlandı') print('Bağlantı kapatılıyor') sys.exit() else:",
"client.sendto(cmd.encode('UTF-8'),ADDR) if(cmd[:3] == 'lis'): ldata,addr = client.recvfrom(buf) data_arr = pickle.loads(ldata) print(data_arr) elif(cmd[:3] ==",
"input('\\n1. Sunucu listesini listelemek için liste yazınız\\n2. Sunucuya dosya eklemek için PUT dosya",
"ldata,addr = client.recvfrom(buf) data_arr = pickle.loads(ldata) print(data_arr) elif(cmd[:3] == 'PUT'): os.chdir('c:/Users/<NAME>/Desktop/client') dosyalar =",
"PUT transferfile.txt gibi client.sendto(cmd.encode('UTF-8'),ADDR) if(cmd[:3] == 'lis'): ldata,addr = client.recvfrom(buf) data_arr = pickle.loads(ldata)",
"socket import sys import os import pickle IP = input('Bağlanmak istediğiniz sunucu IP:",
"giriyoruz if cmd[4:] in dosyalar: dosyaAdi = cmd[4:] f= open(dosyaAdi,'rb') l = f.read(buf)",
"l = f.read(buf) while (l): client.sendto(l,ADDR) print('Gönderiliyor\\n ',repr(l)) l = f.read(buf) print('Tamamlandı') print('Bağlantı",
"dosya adı giriniz\\n3. Sunucudan dosya indirmek için GET dosya adı giriniz\\n') #GET transferfile.txt",
"Sunucudan dosya indirmek için GET dosya adı giriniz\\n') #GET transferfile.txt PUT transferfile.txt gibi",
"için GET dosya adı giriniz\\n') #GET transferfile.txt PUT transferfile.txt gibi client.sendto(cmd.encode('UTF-8'),ADDR) if(cmd[:3] ==",
"için PUT dosya adı giriniz\\n3. Sunucudan dosya indirmek için GET dosya adı giriniz\\n')",
"için liste yazınız\\n2. Sunucuya dosya eklemek için PUT dosya adı giriniz\\n3. Sunucudan dosya",
"kapatılıyor') sys.exit() else: print('Böyle bir dosya bulunamadı') elif(cmd[:3] == 'GET'): with open('gelendosya.txt', 'wb')",
"import sys import os import pickle IP = input('Bağlanmak istediğiniz sunucu IP: ')",
"socket.socket(socket.AF_INET,socket.SOCK_DGRAM) while True: cmd = input('\\n1. Sunucu listesini listelemek için liste yazınız\\n2. Sunucuya",
"2048 ADDR = (IP,PORT) client = socket.socket(socket.AF_INET,socket.SOCK_DGRAM) while True: cmd = input('\\n1. Sunucu",
"transferfile.txt gibi client.sendto(cmd.encode('UTF-8'),ADDR) if(cmd[:3] == 'lis'): ldata,addr = client.recvfrom(buf) data_arr = pickle.loads(ldata) print(data_arr)",
"= f.read(buf) while (l): client.sendto(l,ADDR) print('Gönderiliyor\\n ',repr(l)) l = f.read(buf) print('Tamamlandı') print('Bağlantı kapatılıyor')",
"cmd[4:] f= open(dosyaAdi,'rb') l = f.read(buf) while (l): client.sendto(l,ADDR) print('Gönderiliyor\\n ',repr(l)) l =",
"import socket import sys import os import pickle IP = input('Bağlanmak istediğiniz sunucu",
"= input('\\n1. Sunucu listesini listelemek için liste yazınız\\n2. Sunucuya dosya eklemek için PUT",
"open(dosyaAdi,'rb') l = f.read(buf) while (l): client.sendto(l,ADDR) print('Gönderiliyor\\n ',repr(l)) l = f.read(buf) print('Tamamlandı')",
"Sunucuya dosya eklemek için PUT dosya adı giriniz\\n3. Sunucudan dosya indirmek için GET",
"bulunamadı') elif(cmd[:3] == 'GET'): with open('gelendosya.txt', 'wb') as f: print('Dosya alınıyor...') gdata,addr =",
"f.read(buf) while (l): client.sendto(l,ADDR) print('Gönderiliyor\\n ',repr(l)) l = f.read(buf) print('Tamamlandı') print('Bağlantı kapatılıyor') sys.exit()",
"= input('Bağlanmak istediğiniz sunucu IP: ') PORT = 42 buf = 2048 ADDR",
"while (l): client.sendto(l,ADDR) print('Gönderiliyor\\n ',repr(l)) l = f.read(buf) print('Tamamlandı') print('Bağlantı kapatılıyor') sys.exit() else:",
"import os import pickle IP = input('Bağlanmak istediğiniz sunucu IP: ') PORT =",
"pickle IP = input('Bağlanmak istediğiniz sunucu IP: ') PORT = 42 buf =",
"print('Bağlantı kapatılıyor') sys.exit() else: print('Böyle bir dosya bulunamadı') elif(cmd[:3] == 'GET'): with open('gelendosya.txt',",
"transferfile.txt PUT transferfile.txt gibi client.sendto(cmd.encode('UTF-8'),ADDR) if(cmd[:3] == 'lis'): ldata,addr = client.recvfrom(buf) data_arr =",
"dosya eklemek için PUT dosya adı giriniz\\n3. Sunucudan dosya indirmek için GET dosya",
"print('Böyle bir dosya bulunamadı') elif(cmd[:3] == 'GET'): with open('gelendosya.txt', 'wb') as f: print('Dosya",
"== 'lis'): ldata,addr = client.recvfrom(buf) data_arr = pickle.loads(ldata) print(data_arr) elif(cmd[:3] == 'PUT'): os.chdir('c:/Users/<NAME>/Desktop/client')"
] |
[
"self.app = app.test_client() def test_page_loads(self): response = self.app.get('/') self.assertEqual(response.status_code, 200) self.assertIn(b'<title>IGV - Integrative",
"test_get_data_from_private_dir(self): app.config['PUBLIC_DIR'] = '/static/js' response = self.app.get('static/data/public/gstt1_sample.bam') self.assertEqual(response.status_code, 401) self.assertIn(b'Unauthorized', response.data) def test_get_data_range_header(self):",
"self.assertNotEqual(response, None) self.assertEqual(response.status_code, 401) def test_get_data_auth_disabled(self): app.config['USES_OAUTH'] = False response = self.app.get('static/data/public/gstt1_sample.bam') self.assertEqual(response.status_code,",
"import app class TestIGV(unittest.TestCase): def setUp(self): app.config['TESTING'] = True app.config['ALLOWED_EMAILS'] = 'test_emails.txt' app.config['USES_OAUTH']",
"= 25 size = 100 response = self.app.get('../test/BufferedReaderTest.bin', headers={\"Range\": \"bytes={}-{}\".format(start, start+size)}) for i",
"from igvjs import app class TestIGV(unittest.TestCase): def setUp(self): app.config['TESTING'] = True app.config['ALLOWED_EMAILS'] =",
"= self.app.get('../test/BufferedReaderTest.bin', headers={\"Range\": \"bytes={}-{}\".format(start, start+size)}) for i in range(size): expected_value = -128 +",
"Genomics Viewer</title>', response.data) def test_get_data_not_auth(self): response = self.app.get('static/data/public/gstt1_sample.bam') self.assertNotEqual(response, None) self.assertEqual(response.status_code, 401) def",
"= False response = self.app.get('static/data/public/gstt1_sample.bam') self.assertEqual(response.status_code, 200) def test_get_data_from_private_dir(self): app.config['PUBLIC_DIR'] = '/static/js' response",
"= self.app.get('static/data/public/gstt1_sample.bam') self.assertEqual(response.status_code, 401) self.assertIn(b'Unauthorized', response.data) def test_get_data_range_header(self): start = 25 size =",
"test_get_data_range_header(self): start = 25 size = 100 response = self.app.get('../test/BufferedReaderTest.bin', headers={\"Range\": \"bytes={}-{}\".format(start, start+size)})",
"igvjs import app class TestIGV(unittest.TestCase): def setUp(self): app.config['TESTING'] = True app.config['ALLOWED_EMAILS'] = 'test_emails.txt'",
"= True app.config['ALLOWED_EMAILS'] = 'test_emails.txt' app.config['USES_OAUTH'] = True app.config['PUBLIC_DIR'] = None self.app =",
"= self.app.get('/') self.assertEqual(response.status_code, 200) self.assertIn(b'<title>IGV - Integrative Genomics Viewer</title>', response.data) def test_get_data_not_auth(self): response",
"Integrative Genomics Viewer</title>', response.data) def test_get_data_not_auth(self): response = self.app.get('static/data/public/gstt1_sample.bam') self.assertNotEqual(response, None) self.assertEqual(response.status_code, 401)",
"self.assertEqual(response.status_code, 200) self.assertIn(b'<title>IGV - Integrative Genomics Viewer</title>', response.data) def test_get_data_not_auth(self): response = self.app.get('static/data/public/gstt1_sample.bam')",
"def test_get_data_auth_disabled(self): app.config['USES_OAUTH'] = False response = self.app.get('static/data/public/gstt1_sample.bam') self.assertEqual(response.status_code, 200) def test_get_data_from_private_dir(self): app.config['PUBLIC_DIR']",
"self.assertIn(b'Unauthorized', response.data) def test_get_data_range_header(self): start = 25 size = 100 response = self.app.get('../test/BufferedReaderTest.bin',",
"response = self.app.get('../test/BufferedReaderTest.bin', headers={\"Range\": \"bytes={}-{}\".format(start, start+size)}) for i in range(size): expected_value = -128",
"= app.test_client() def test_page_loads(self): response = self.app.get('/') self.assertEqual(response.status_code, 200) self.assertIn(b'<title>IGV - Integrative Genomics",
"- Integrative Genomics Viewer</title>', response.data) def test_get_data_not_auth(self): response = self.app.get('static/data/public/gstt1_sample.bam') self.assertNotEqual(response, None) self.assertEqual(response.status_code,",
"app.config['PUBLIC_DIR'] = None self.app = app.test_client() def test_page_loads(self): response = self.app.get('/') self.assertEqual(response.status_code, 200)",
"= self.app.get('static/data/public/gstt1_sample.bam') self.assertNotEqual(response, None) self.assertEqual(response.status_code, 401) def test_get_data_auth_disabled(self): app.config['USES_OAUTH'] = False response =",
"100 response = self.app.get('../test/BufferedReaderTest.bin', headers={\"Range\": \"bytes={}-{}\".format(start, start+size)}) for i in range(size): expected_value =",
"test_page_loads(self): response = self.app.get('/') self.assertEqual(response.status_code, 200) self.assertIn(b'<title>IGV - Integrative Genomics Viewer</title>', response.data) def",
"app.config['PUBLIC_DIR'] = '/static/js' response = self.app.get('static/data/public/gstt1_sample.bam') self.assertEqual(response.status_code, 401) self.assertIn(b'Unauthorized', response.data) def test_get_data_range_header(self): start",
"401) def test_get_data_auth_disabled(self): app.config['USES_OAUTH'] = False response = self.app.get('static/data/public/gstt1_sample.bam') self.assertEqual(response.status_code, 200) def test_get_data_from_private_dir(self):",
"= 'test_emails.txt' app.config['USES_OAUTH'] = True app.config['PUBLIC_DIR'] = None self.app = app.test_client() def test_page_loads(self):",
"200) def test_get_data_from_private_dir(self): app.config['PUBLIC_DIR'] = '/static/js' response = self.app.get('static/data/public/gstt1_sample.bam') self.assertEqual(response.status_code, 401) self.assertIn(b'Unauthorized', response.data)",
"False response = self.app.get('static/data/public/gstt1_sample.bam') self.assertEqual(response.status_code, 200) def test_get_data_from_private_dir(self): app.config['PUBLIC_DIR'] = '/static/js' response =",
"None) self.assertEqual(response.status_code, 401) def test_get_data_auth_disabled(self): app.config['USES_OAUTH'] = False response = self.app.get('static/data/public/gstt1_sample.bam') self.assertEqual(response.status_code, 200)",
"app class TestIGV(unittest.TestCase): def setUp(self): app.config['TESTING'] = True app.config['ALLOWED_EMAILS'] = 'test_emails.txt' app.config['USES_OAUTH'] =",
"401) self.assertIn(b'Unauthorized', response.data) def test_get_data_range_header(self): start = 25 size = 100 response =",
"= '/static/js' response = self.app.get('static/data/public/gstt1_sample.bam') self.assertEqual(response.status_code, 401) self.assertIn(b'Unauthorized', response.data) def test_get_data_range_header(self): start =",
"self.app.get('/') self.assertEqual(response.status_code, 200) self.assertIn(b'<title>IGV - Integrative Genomics Viewer</title>', response.data) def test_get_data_not_auth(self): response =",
"response = self.app.get('static/data/public/gstt1_sample.bam') self.assertNotEqual(response, None) self.assertEqual(response.status_code, 401) def test_get_data_auth_disabled(self): app.config['USES_OAUTH'] = False response",
"None self.app = app.test_client() def test_page_loads(self): response = self.app.get('/') self.assertEqual(response.status_code, 200) self.assertIn(b'<title>IGV -",
"start + i value = int(struct.unpack('b', response.data[i])[0]) self.assertEqual(value, expected_value) if __name__ == \"__main__\":",
"def test_get_data_not_auth(self): response = self.app.get('static/data/public/gstt1_sample.bam') self.assertNotEqual(response, None) self.assertEqual(response.status_code, 401) def test_get_data_auth_disabled(self): app.config['USES_OAUTH'] =",
"self.assertEqual(response.status_code, 401) self.assertIn(b'Unauthorized', response.data) def test_get_data_range_header(self): start = 25 size = 100 response",
"+ i value = int(struct.unpack('b', response.data[i])[0]) self.assertEqual(value, expected_value) if __name__ == \"__main__\": unittest.main()",
"app.config['USES_OAUTH'] = False response = self.app.get('static/data/public/gstt1_sample.bam') self.assertEqual(response.status_code, 200) def test_get_data_from_private_dir(self): app.config['PUBLIC_DIR'] = '/static/js'",
"'test_emails.txt' app.config['USES_OAUTH'] = True app.config['PUBLIC_DIR'] = None self.app = app.test_client() def test_page_loads(self): response",
"-128 + start + i value = int(struct.unpack('b', response.data[i])[0]) self.assertEqual(value, expected_value) if __name__",
"self.app.get('static/data/public/gstt1_sample.bam') self.assertEqual(response.status_code, 401) self.assertIn(b'Unauthorized', response.data) def test_get_data_range_header(self): start = 25 size = 100",
"import unittest import struct from igvjs import app class TestIGV(unittest.TestCase): def setUp(self): app.config['TESTING']",
"unittest import struct from igvjs import app class TestIGV(unittest.TestCase): def setUp(self): app.config['TESTING'] =",
"test_get_data_not_auth(self): response = self.app.get('static/data/public/gstt1_sample.bam') self.assertNotEqual(response, None) self.assertEqual(response.status_code, 401) def test_get_data_auth_disabled(self): app.config['USES_OAUTH'] = False",
"25 size = 100 response = self.app.get('../test/BufferedReaderTest.bin', headers={\"Range\": \"bytes={}-{}\".format(start, start+size)}) for i in",
"+ start + i value = int(struct.unpack('b', response.data[i])[0]) self.assertEqual(value, expected_value) if __name__ ==",
"class TestIGV(unittest.TestCase): def setUp(self): app.config['TESTING'] = True app.config['ALLOWED_EMAILS'] = 'test_emails.txt' app.config['USES_OAUTH'] = True",
"response.data) def test_get_data_not_auth(self): response = self.app.get('static/data/public/gstt1_sample.bam') self.assertNotEqual(response, None) self.assertEqual(response.status_code, 401) def test_get_data_auth_disabled(self): app.config['USES_OAUTH']",
"setUp(self): app.config['TESTING'] = True app.config['ALLOWED_EMAILS'] = 'test_emails.txt' app.config['USES_OAUTH'] = True app.config['PUBLIC_DIR'] = None",
"True app.config['PUBLIC_DIR'] = None self.app = app.test_client() def test_page_loads(self): response = self.app.get('/') self.assertEqual(response.status_code,",
"app.config['ALLOWED_EMAILS'] = 'test_emails.txt' app.config['USES_OAUTH'] = True app.config['PUBLIC_DIR'] = None self.app = app.test_client() def",
"def test_page_loads(self): response = self.app.get('/') self.assertEqual(response.status_code, 200) self.assertIn(b'<title>IGV - Integrative Genomics Viewer</title>', response.data)",
"app.test_client() def test_page_loads(self): response = self.app.get('/') self.assertEqual(response.status_code, 200) self.assertIn(b'<title>IGV - Integrative Genomics Viewer</title>',",
"True app.config['ALLOWED_EMAILS'] = 'test_emails.txt' app.config['USES_OAUTH'] = True app.config['PUBLIC_DIR'] = None self.app = app.test_client()",
"import struct from igvjs import app class TestIGV(unittest.TestCase): def setUp(self): app.config['TESTING'] = True",
"i in range(size): expected_value = -128 + start + i value = int(struct.unpack('b',",
"= True app.config['PUBLIC_DIR'] = None self.app = app.test_client() def test_page_loads(self): response = self.app.get('/')",
"self.assertEqual(response.status_code, 200) def test_get_data_from_private_dir(self): app.config['PUBLIC_DIR'] = '/static/js' response = self.app.get('static/data/public/gstt1_sample.bam') self.assertEqual(response.status_code, 401) self.assertIn(b'Unauthorized',",
"for i in range(size): expected_value = -128 + start + i value =",
"self.app.get('static/data/public/gstt1_sample.bam') self.assertEqual(response.status_code, 200) def test_get_data_from_private_dir(self): app.config['PUBLIC_DIR'] = '/static/js' response = self.app.get('static/data/public/gstt1_sample.bam') self.assertEqual(response.status_code, 401)",
"def setUp(self): app.config['TESTING'] = True app.config['ALLOWED_EMAILS'] = 'test_emails.txt' app.config['USES_OAUTH'] = True app.config['PUBLIC_DIR'] =",
"range(size): expected_value = -128 + start + i value = int(struct.unpack('b', response.data[i])[0]) self.assertEqual(value,",
"size = 100 response = self.app.get('../test/BufferedReaderTest.bin', headers={\"Range\": \"bytes={}-{}\".format(start, start+size)}) for i in range(size):",
"= None self.app = app.test_client() def test_page_loads(self): response = self.app.get('/') self.assertEqual(response.status_code, 200) self.assertIn(b'<title>IGV",
"expected_value = -128 + start + i value = int(struct.unpack('b', response.data[i])[0]) self.assertEqual(value, expected_value)",
"200) self.assertIn(b'<title>IGV - Integrative Genomics Viewer</title>', response.data) def test_get_data_not_auth(self): response = self.app.get('static/data/public/gstt1_sample.bam') self.assertNotEqual(response,",
"start = 25 size = 100 response = self.app.get('../test/BufferedReaderTest.bin', headers={\"Range\": \"bytes={}-{}\".format(start, start+size)}) for",
"response = self.app.get('/') self.assertEqual(response.status_code, 200) self.assertIn(b'<title>IGV - Integrative Genomics Viewer</title>', response.data) def test_get_data_not_auth(self):",
"self.app.get('static/data/public/gstt1_sample.bam') self.assertNotEqual(response, None) self.assertEqual(response.status_code, 401) def test_get_data_auth_disabled(self): app.config['USES_OAUTH'] = False response = self.app.get('static/data/public/gstt1_sample.bam')",
"'/static/js' response = self.app.get('static/data/public/gstt1_sample.bam') self.assertEqual(response.status_code, 401) self.assertIn(b'Unauthorized', response.data) def test_get_data_range_header(self): start = 25",
"def test_get_data_range_header(self): start = 25 size = 100 response = self.app.get('../test/BufferedReaderTest.bin', headers={\"Range\": \"bytes={}-{}\".format(start,",
"def test_get_data_from_private_dir(self): app.config['PUBLIC_DIR'] = '/static/js' response = self.app.get('static/data/public/gstt1_sample.bam') self.assertEqual(response.status_code, 401) self.assertIn(b'Unauthorized', response.data) def",
"response = self.app.get('static/data/public/gstt1_sample.bam') self.assertEqual(response.status_code, 401) self.assertIn(b'Unauthorized', response.data) def test_get_data_range_header(self): start = 25 size",
"self.assertIn(b'<title>IGV - Integrative Genomics Viewer</title>', response.data) def test_get_data_not_auth(self): response = self.app.get('static/data/public/gstt1_sample.bam') self.assertNotEqual(response, None)",
"app.config['TESTING'] = True app.config['ALLOWED_EMAILS'] = 'test_emails.txt' app.config['USES_OAUTH'] = True app.config['PUBLIC_DIR'] = None self.app",
"= -128 + start + i value = int(struct.unpack('b', response.data[i])[0]) self.assertEqual(value, expected_value) if",
"test_get_data_auth_disabled(self): app.config['USES_OAUTH'] = False response = self.app.get('static/data/public/gstt1_sample.bam') self.assertEqual(response.status_code, 200) def test_get_data_from_private_dir(self): app.config['PUBLIC_DIR'] =",
"self.app.get('../test/BufferedReaderTest.bin', headers={\"Range\": \"bytes={}-{}\".format(start, start+size)}) for i in range(size): expected_value = -128 + start",
"Viewer</title>', response.data) def test_get_data_not_auth(self): response = self.app.get('static/data/public/gstt1_sample.bam') self.assertNotEqual(response, None) self.assertEqual(response.status_code, 401) def test_get_data_auth_disabled(self):",
"TestIGV(unittest.TestCase): def setUp(self): app.config['TESTING'] = True app.config['ALLOWED_EMAILS'] = 'test_emails.txt' app.config['USES_OAUTH'] = True app.config['PUBLIC_DIR']",
"\"bytes={}-{}\".format(start, start+size)}) for i in range(size): expected_value = -128 + start + i",
"start+size)}) for i in range(size): expected_value = -128 + start + i value",
"= self.app.get('static/data/public/gstt1_sample.bam') self.assertEqual(response.status_code, 200) def test_get_data_from_private_dir(self): app.config['PUBLIC_DIR'] = '/static/js' response = self.app.get('static/data/public/gstt1_sample.bam') self.assertEqual(response.status_code,",
"response.data) def test_get_data_range_header(self): start = 25 size = 100 response = self.app.get('../test/BufferedReaderTest.bin', headers={\"Range\":",
"in range(size): expected_value = -128 + start + i value = int(struct.unpack('b', response.data[i])[0])",
"headers={\"Range\": \"bytes={}-{}\".format(start, start+size)}) for i in range(size): expected_value = -128 + start +",
"self.assertEqual(response.status_code, 401) def test_get_data_auth_disabled(self): app.config['USES_OAUTH'] = False response = self.app.get('static/data/public/gstt1_sample.bam') self.assertEqual(response.status_code, 200) def",
"= 100 response = self.app.get('../test/BufferedReaderTest.bin', headers={\"Range\": \"bytes={}-{}\".format(start, start+size)}) for i in range(size): expected_value",
"app.config['USES_OAUTH'] = True app.config['PUBLIC_DIR'] = None self.app = app.test_client() def test_page_loads(self): response =",
"response = self.app.get('static/data/public/gstt1_sample.bam') self.assertEqual(response.status_code, 200) def test_get_data_from_private_dir(self): app.config['PUBLIC_DIR'] = '/static/js' response = self.app.get('static/data/public/gstt1_sample.bam')",
"struct from igvjs import app class TestIGV(unittest.TestCase): def setUp(self): app.config['TESTING'] = True app.config['ALLOWED_EMAILS']"
] |
[
"minimum Sky cover for Wx is 50-100% if self._SkyLimit < 50: self._SkyLimit =",
"where there is not enough cloud \\ to support the corrsponding PoP. The",
"InvalidSkyMask1 = logical_and(less(Sky, PoP * self._factor), less_equal(PoP * self._factor, 100)) InvalidSkyMask2 = logical_and(less(Sky,",
"be solicited from the user: VariableList = [ ## (\"Variable name1\" , defaultValue1,",
"by what \\ factor, the cloud should be greater.\" ## # Set up",
"new value ############################################################################# # # Configuration section # # Here is where to",
"PoP for measurable precip is 15-25% if self._PoPLimit < 15.0: self._PoPLimit = 15.0",
"## # Called once at end of Tool ## # Cannot have WeatherElement",
"1000: ## self.abort(\"x is too large\") ## ## Call self.noData(messageString) to stop execution",
"enough cloud \\ to support the corrsponding PoP. The user decides by how",
"50-100% if self._SkyLimit < 50: self._SkyLimit = 50 elif self._SkyLimit > 100: self._SkyLimit",
"InvalidSkyMask1 = logical_and(less(PoP, 5), less_equal(Sky, PoP * self._lofactor)) InvalidSkyMask2 = logical_and(mainAddMask, less_equal(PoP, self._breathingRoom))",
"self._factor), less_equal(PoP * self._factor, 100)) InvalidSkyMask2 = logical_and(less(Sky, PoP * self._factor), greater(PoP *",
"the tool def preProcessTool(self, varDict): # Called once at beginning of Tool #",
"Suite 340 # Mail Stop B8 # Omaha, NE 68106 # 402.291.0100 #",
"# Make sure minimum PoP for measurable precip is 15-25% if self._PoPLimit <",
"# # Contractor Name: <NAME> # Contractor Address: 6825 Pine Street, Suite 340",
"## method Definitions: ## def _myMethod(self, arg1, arg2) ## -- When calling your",
"60, \"numeric\"), # (\"Enter minimum PoP for measurable precip:\", 15, \"numeric\"), (\"Enter Sky",
"# # See the AWIPS II Master Rights File (\"Master Rights File.pdf\") for",
"## (\"Label contents\" , \"\", \"label\"), ## (\"\", dialogHeight, \"scrollbar\"), ] # Set",
"self._SkyLimit > 100: self._SkyLimit = 100 # Make sure Sky cover for 5%",
"For Add or Multiply: # Idea is Sky is greater than PoP, either",
"Method: Execute # Called once for each grid # Fill in the arguments",
"preProcessTool(self, varDict): ## # Called once at beginning of Tool ## # Cannot",
"## ## Call self.noData(messageString) to stop execution of your tool ## and return",
"cloud \\ to support the corrsponding PoP. The user decides by how much,",
"self._SkyLimit - (self._PoPLimit - PoP) * self._slope)) InvalidSkyMask5 = logical_or(InvalidSkyMask1, InvalidSkyMask2) # InvalidSkyMask",
"(smaller factor), by how much ?\"] # For Add: self._lofactor = float(self._factor +",
"[ ## (\"Variable name1\" , defaultValue1, \"numeric\"), ## (\"Variable name2\" , \"default value2\",",
"> 25.0: self._PoPLimit = 25.0 # Make sure minimum Sky cover for Wx",
"\"\", \"model\"), ## (\"Variable name7\" , \"\", \"D2D_model\"), ## (\"Label contents\" , \"\",",
"# Compute slope to use for this line self._slope = (self._SkyLimit - self._SkyMin)",
"States or abroad requires # an export license or other authorization. # #",
"self._factor)) InvalidSkyMask1 = logical_and(less(PoP, 5), less_equal(Sky, PoP * self._lofactor)) InvalidSkyMask2 = logical_and(mainAddMask, less_equal(PoP,",
"self._SkyMin) / (self._PoPLimit - 5.0) ## def preProcessTool(self, varDict): ## # Called once",
"340 # Mail Stop B8 # Omaha, NE 68106 # 402.291.0100 # #",
"# return Sky # Optional Methods ## # These methods can have the",
"# self._PoPLimit = varDict[\"Enter minimum PoP for measurable precip:\"] ## 15 self._PoPLimit =",
"VariableList below) ## var1 = varDict[\"Variable name1\"] ## var2 = varDict[\"Variable name2\"] #",
"the elements for which your tool will appear by using # a ScreenList.",
"Set up Variables from the varDict (see VariableList below) ## var1 = varDict[\"Variable",
"Configuration section # # Here is where to change the active edit area",
"<reponame>srcarter3/awips2 ## # This software was developed and / or modified by Raytheon",
"large\") ## ## Call self.noData(messageString) to stop execution of your tool ## and",
"each grid # Fill in the arguments you want to use -- WeatherElement1,",
"varDict): ## # Called once at beginning of Tool ## # Cannot have",
"area to your local forecast area # localFoecastArea = \"ISC_Send_Area\" # # End",
"self.abort(\"x is too large\") ## ## Call self.noData(messageString) to stop execution of your",
"elif self._SkyLimit > 100: self._SkyLimit = 100 # Make sure Sky cover for",
"elif self._PoPLimit > 25.0: self._PoPLimit = 25.0 # Make sure minimum Sky cover",
"Call self.abort(errorString) to stop execution of your tool and ## display a message",
"persons whether in the United States or abroad requires # an export license",
"# Return the new value # return Sky # Optional Methods ## #",
", \"default value2\", \"alphaNumeric\"), (\"Sky vs PoP Relationship:\" , \"add\", \"radio\", [\"add\", \"multiply\",",
"Make sure minimum Sky cover for Wx is 50-100% if self._SkyLimit < 50:",
"[\"add\", \"multiply\", \"Sky Limit\"]), (\"For add, multiply (smaller factor), by how much ?\"",
"# localFoecastArea = \"ISC_Send_Area\" # # End Configuration section # ############################################################################# area =",
"which your tool will appear by using # a ScreenList. For example: #",
"a fixed amount # (add), or by a factor. The value for sky,",
"def preProcessTool(self, varDict): ## # Called once at beginning of Tool ## #",
"/ or modified by Raytheon Company, # pursuant to Contract DG133W-05-CQ-1067 with the",
"priority version # of the file will completely replace a lower priority version",
"grids showing when and where there is not enough cloud \\ to support",
"self._factor # For Sky Limit: # self._PoPLimit = varDict[\"Enter minimum PoP for measurable",
"# Omaha, NE 68106 # 402.291.0100 # # See the AWIPS II Master",
"# Mail Stop B8 # Omaha, NE 68106 # 402.291.0100 # # See",
"value2\"], \"check\", ## [\"value1\", \"value2\", \"value3\"]), ## (\"Variable name4\" , \"default value4\", \"radio\",",
"Tool class instance. Don't worry much about it. ## All you need to",
"(\"Sky vs PoP Relationship:\" , \"add\", \"radio\", [\"add\", \"multiply\", \"Sky Limit\"]), (\"For add,",
"Multiply: # Idea is Sky is greater than PoP, either by a fixed",
"for 5% PoP is 10-100% if self._SkyMin < 10: self._SkyMin = 10 elif",
"the file will completely replace a lower priority version of the file. ##",
"version # of the file will completely replace a lower priority version of",
"whether in the United States or abroad requires # an export license or",
"from the user: VariableList = [ ## (\"Variable name1\" , defaultValue1, \"numeric\"), ##",
"comes in # Sky is left alone if it is already large enough.",
"\"value3\"]), ## (\"Variable name5\" , defaultValue, \"scale\", ## [minValue, maxValue], resolution), ## (\"Variable",
"the first argument of ## method Definitions: ## def _myMethod(self, arg1, arg2) ##",
"tool and ## display a message to the user. ## For example: ##",
"measurable precip:\"] ## 15 self._PoPLimit = 15 self._SkyLimit = varDict[\"Enter Sky Limit: the",
"the corrsponding PoP. The user decides by how much, or by what \\",
"## (\"Variable name4\" , \"default value4\", \"radio\", ## [\"value1\", \"value2\", \"value3\"]), ## (\"Variable",
"# Here is where to change the active edit area to your local",
"15 self._PoPLimit = 15 self._SkyLimit = varDict[\"Enter Sky Limit: the minimum Sky cover",
"than PoP, either by a fixed amount # (add), or by a factor.",
"This software is in the public domain, furnished \"as is\", without technical #",
"whose # export/transfer/disclosure is restricted by U.S. law. Dissemination # to non-U.S. persons",
"# # End Configuration section # ############################################################################# area = self.getEditArea(localFoecastArea) areaMask = self.encodeEditArea(area)",
"to your local forecast area # localFoecastArea = \"ISC_Send_Area\" # # End Configuration",
"Grid arguments ## pass ## What is \"self\"???? ## \"Self\" refers to this",
"# a ScreenList. For example: # #ScreenList = [\"T\",\"Td\"] #ScreenList = [\"SCALAR\",\"VECTOR\",\"WEATHER\",\"DISCRETE\"] ###",
"range over which we are running the tool def preProcessTool(self, varDict): # Called",
"self._SkyLimit - 15: self._SkyMin = self._SkyLimit - 15 # Compute slope to use",
"cover for Wx if self._SkyMin > self._SkyLimit - 15: self._SkyMin = self._SkyLimit -",
"(\"Variable name1\" , defaultValue1, \"numeric\"), ## (\"Variable name2\" , \"default value2\", \"alphaNumeric\"), (\"Sky",
"product contains export-restricted data whose # export/transfer/disclosure is restricted by U.S. law. Dissemination",
"> self._SkyLimit - 15: self._SkyMin = self._SkyLimit - 15 # Compute slope to",
"sure to list \"self\" as the first argument of ## method Definitions: ##",
"\"default value2\", \"alphaNumeric\"), (\"Sky vs PoP Relationship:\" , \"add\", \"radio\", [\"add\", \"multiply\", \"Sky",
"execution of your tool ## and return a \"NoData\" error which can be",
"(\"Enter Sky Limit: the minimum Sky cover needed to support Wx:\" , 60,",
"PoP Relationship:\"] # For Add or Multiply: # Idea is Sky is greater",
"edit area to your local forecast area # localFoecastArea = \"ISC_Send_Area\" # #",
"## (\"Variable name2\" , \"default value2\", \"alphaNumeric\"), (\"Sky vs PoP Relationship:\" , \"add\",",
"Compute slope to use for this line self._slope = (self._SkyLimit - self._SkyMin) /",
"Wx is 50-100% if self._SkyLimit < 50: self._SkyLimit = 50 elif self._SkyLimit >",
"arguments ## pass ## def postProcessTool(self, varDict): ## # Called once at end",
"cover needed to support Wx:\" , 60, \"numeric\"), # (\"Enter minimum PoP for",
"* self._factor, 100)) InvalidSkyMask5 = logical_or(InvalidSkyMask1, InvalidSkyMask2) else: lowSkyMask = less(Sky, self._SkyLimit) InvalidSkyMask1",
"\"numeric\" WeatherElementEdited = \"Sky\" from numpy import * HideTool = 1 # You",
"# CheckSkyWithPoP # # Author: # ---------------------------------------------------------------------------- ## # This is an absolute",
"- self._factor # For Sky Limit: # self._PoPLimit = varDict[\"Enter minimum PoP for",
"minimum Sky cover needed to support Wx:\"] ## 60 self._SkyMin = varDict[\"Enter Sky",
"be greater.\" ## # Set up Variables from the varDict (see VariableList below)",
"= varDict[\"For add, multiply (smaller factor), by how much ?\"] # For Add:",
"def _myMethod(self, arg1, arg2) ## -- When calling your methods, use self._methodName omitting",
"-- Make sure to list \"self\" as the first argument of ## method",
"This software product contains export-restricted data whose # export/transfer/disclosure is restricted by U.S.",
"Call self.noData(messageString) to stop execution of your tool ## and return a \"NoData\"",
"= logical_and(InvalidSkyMask5, areaMask) if any(InvalidSkyMask): self.createGrid(\"TemporaryData\", \"InvalidSkyForPoP\", \"SCALAR\", InvalidSkyMask, GridTimeRange) self.setActiveElement(\"TemporaryData\", \"InvalidSkyForPoP\", \"SFC\",",
"solicited from the user: VariableList = [ ## (\"Variable name1\" , defaultValue1, \"numeric\"),",
"\"scrollbar\"), ] # Set up Class import SmartScript ## For available commands, see",
"-- selected time range over which we are running the tool def preProcessTool(self,",
"commands, see SmartScript class Tool (SmartScript.SmartScript): def __init__(self, dbss): SmartScript.SmartScript.__init__(self, dbss) # Required",
"= varDict[\"Enter minimum PoP for measurable precip:\"] ## 15 self._PoPLimit = 15 self._SkyLimit",
"= varDict[\"Enter Sky cover for 5% PoP:\"] ## 30 # Make sure minimum",
"less(Sky, 99.5)) InvalidSkyMask4 = logical_or(InvalidSkyMask1, InvalidSkyMask2) InvalidSkyMask5 = logical_or(InvalidSkyMask3, InvalidSkyMask4) elif self._operator ==",
"once at end of Tool ## # Cannot have WeatherElement or Grid arguments",
"cover for 5% PoP < minimum Sky cover for Wx if self._SkyMin >",
"by a fixed amount # (add), or by a factor. The value for",
"new value # return Sky # Optional Methods ## # These methods can",
"= 100 - self._factor # For Sky Limit: # self._PoPLimit = varDict[\"Enter minimum",
"def execute(self, Sky, PoP, GridTimeRange, varDict): \"Creates highlight grids showing when and where",
"= self.getEditArea(localFoecastArea) areaMask = self.encodeEditArea(area) if (self._operator == \"add\"): mainAddMask = logical_and(greater_equal(PoP, 5),",
"without technical # support, and with no warranty, express or implied, as to",
"15 # Compute slope to use for this line self._slope = (self._SkyLimit -",
"of Tool # Cannot have WeatherElement or Grid arguments # Get thresholds for",
"for 5% PoP < minimum Sky cover for Wx if self._SkyMin > self._SkyLimit",
"tool will appear by using # a ScreenList. For example: # #ScreenList =",
"Grid arguments ## pass ## def postProcessTool(self, varDict): ## # Called once at",
"self._SkyMin = 10 elif self._SkyMin > 100: self._SkyMin = 100 # Make sure",
"# You can screen the elements for which your tool will appear by",
"less_equal(PoP * self._factor, 100)) InvalidSkyMask2 = logical_and(less(Sky, PoP * self._factor), greater(PoP * self._factor,",
"# This is an absolute override file, indicating that a higher priority version",
"varDict[\"Enter minimum PoP for measurable precip:\"] ## 15 self._PoPLimit = 15 self._SkyLimit =",
"15.0 elif self._PoPLimit > 25.0: self._PoPLimit = 25.0 # Make sure minimum Sky",
"self._breathingRoom)) InvalidSkyMask3 = logical_and(greater(PoP, self._breathingRoom), less(Sky, 99.5)) InvalidSkyMask4 = logical_or(InvalidSkyMask1, InvalidSkyMask2) InvalidSkyMask5 =",
"< 50: self._SkyLimit = 50 elif self._SkyLimit > 100: self._SkyLimit = 100 #",
"# # Configuration section # # Here is where to change the active",
"arguments you want to use -- WeatherElement1, WeatherElement2... def execute(self, Sky, PoP, GridTimeRange,",
"Wx:\" , 60, \"numeric\"), # (\"Enter minimum PoP for measurable precip:\", 15, \"numeric\"),",
"Contractor Address: 6825 Pine Street, Suite 340 # Mail Stop B8 # Omaha,",
"= self._SkyLimit - 15 # Compute slope to use for this line self._slope",
"15-25% if self._PoPLimit < 15.0: self._PoPLimit = 15.0 elif self._PoPLimit > 25.0: self._PoPLimit",
"(\"Variable name4\" , \"default value4\", \"radio\", ## [\"value1\", \"value2\", \"value3\"]), ## (\"Variable name5\"",
"25.0: self._PoPLimit = 25.0 # Make sure minimum Sky cover for Wx is",
"\"\", \"label\"), (\"Enter Sky Limit: the minimum Sky cover needed to support Wx:\"",
"\"numeric\"), (\"Enter Sky cover for 5% PoP:\" , 30, \"numeric\"), ## (\"Variable name3\"",
"is already large enough. # For Muultply: self._factor = varDict[\"For add, multiply (smaller",
"mainAddMask = logical_and(greater_equal(PoP, 5), less(Sky, PoP + self._factor)) InvalidSkyMask1 = logical_and(less(PoP, 5), less_equal(Sky,",
"= less(Sky, self._SkyLimit) InvalidSkyMask1 = logical_and(lowSkyMask, greater_equal(PoP, self._PoPLimit)) InvalidSkyMask2 = logical_and(lowSkyMask, less_equal(Sky, self._SkyLimit",
"forecast area # localFoecastArea = \"ISC_Send_Area\" # # End Configuration section # #############################################################################",
"or by a factor. The value for sky, of course, cannot # be",
"to do is: ## -- Make sure to list \"self\" as the first",
"up Class import SmartScript ## For available commands, see SmartScript class Tool (SmartScript.SmartScript):",
"less_equal(PoP, self._breathingRoom)) InvalidSkyMask3 = logical_and(greater(PoP, self._breathingRoom), less(Sky, 99.5)) InvalidSkyMask4 = logical_or(InvalidSkyMask1, InvalidSkyMask2) InvalidSkyMask5",
"\"SFC\", GridTimeRange, fitToData=1) # Return the new value # return Sky # Optional",
"\"Sky\" from numpy import * HideTool = 1 # You can screen the",
", 30, \"numeric\"), ## (\"Variable name3\" , [\"default value1\", \"default value2\"], \"check\", ##",
"(\"Variable name5\" , defaultValue, \"scale\", ## [minValue, maxValue], resolution), ## (\"Variable name6\" ,",
"to change the active edit area to your local forecast area # localFoecastArea",
"cover for 5% PoP:\" , 30, \"numeric\"), ## (\"Variable name3\" , [\"default value1\",",
"methods can have the additional argument: ## # ToolTimeRange -- selected time range",
"an absolute override file, indicating that a higher priority version # of the",
"the new value # return Sky # Optional Methods ## # These methods",
"varDict[\"Sky vs PoP Relationship:\"] # For Add or Multiply: # Idea is Sky",
"Cannot have WeatherElement or Grid arguments ## pass ## def postProcessTool(self, varDict): ##",
"## (\"Variable name3\" , [\"default value1\", \"default value2\"], \"check\", ## [\"value1\", \"value2\", \"value3\"]),",
"> 100: self._SkyLimit = 100 # Make sure Sky cover for 5% PoP",
"5% PoP < minimum Sky cover for Wx if self._SkyMin > self._SkyLimit -",
"100)) InvalidSkyMask2 = logical_and(less(Sky, PoP * self._factor), greater(PoP * self._factor, 100)) InvalidSkyMask5 =",
"68106 # 402.291.0100 # # See the AWIPS II Master Rights File (\"Master",
"Execute # Called once for each grid # Fill in the arguments you",
"## # Cannot have WeatherElement or Grid arguments ## pass ## What is",
"100; this is where 'breathingRoom' comes in # Sky is left alone if",
"have WeatherElement or Grid arguments ## pass ## def postProcessTool(self, varDict): ## #",
"logical_and(lowSkyMask, less_equal(Sky, self._SkyLimit - (self._PoPLimit - PoP) * self._slope)) InvalidSkyMask5 = logical_or(InvalidSkyMask1, InvalidSkyMask2)",
"for 5% PoP:\" , 30, \"numeric\"), ## (\"Variable name3\" , [\"default value1\", \"default",
"abroad requires # an export license or other authorization. # # Contractor Name:",
"up variables to be solicited from the user: VariableList = [ ## (\"Variable",
"PoP, either by a fixed amount # (add), or by a factor. The",
"is left alone if it is already large enough. # For Muultply: self._factor",
"5.0) ## def preProcessTool(self, varDict): ## # Called once at beginning of Tool",
"This is an absolute override file, indicating that a higher priority version #",
"greater than 100; this is where 'breathingRoom' comes in # Sky is left",
"WeatherElementEdited = \"Sky\" from numpy import * HideTool = 1 # You can",
"for # further licensing information. ## # ---------------------------------------------------------------------------- # This software is in",
"\"numeric\"), ## (\"Variable name3\" , [\"default value1\", \"default value2\"], \"check\", ## [\"value1\", \"value2\",",
"(\"Variable name3\" , [\"default value1\", \"default value2\"], \"check\", ## [\"value1\", \"value2\", \"value3\"]), ##",
"of ## method Definitions: ## def _myMethod(self, arg1, arg2) ## -- When calling",
"NE 68106 # 402.291.0100 # # See the AWIPS II Master Rights File",
"## Call self.noData(messageString) to stop execution of your tool ## and return a",
"Rights File.pdf\") for # further licensing information. ## # ---------------------------------------------------------------------------- # This software",
"= \"ISC_Send_Area\" # # End Configuration section # ############################################################################# area = self.getEditArea(localFoecastArea) areaMask",
"self._factor), greater(PoP * self._factor, 100)) InvalidSkyMask5 = logical_or(InvalidSkyMask1, InvalidSkyMask2) else: lowSkyMask = less(Sky,",
"the cloud should be greater.\" ## # Set up Variables from the varDict",
"value # return Sky # Optional Methods ## # These methods can have",
"self._operator = varDict[\"Sky vs PoP Relationship:\"] # For Add or Multiply: # Idea",
"PoP * self._factor), less_equal(PoP * self._factor, 100)) InvalidSkyMask2 = logical_and(less(Sky, PoP * self._factor),",
"by using # a ScreenList. For example: # #ScreenList = [\"T\",\"Td\"] #ScreenList =",
"logical_and(less(PoP, 5), less_equal(Sky, PoP * self._lofactor)) InvalidSkyMask2 = logical_and(mainAddMask, less_equal(PoP, self._breathingRoom)) InvalidSkyMask3 =",
"execute(self, Sky, PoP, GridTimeRange, varDict): \"Creates highlight grids showing when and where there",
"by a factor. The value for sky, of course, cannot # be greater",
"factor), by how much ?\" , \"20\", \"numeric\"), (\"For Sky Limit, only Sky",
"# Sky is left alone if it is already large enough. # For",
"# support, and with no warranty, express or implied, as to its usefulness",
"Sky Limit, only Sky less than Limit affected; it is raised to the",
"\"\", \"D2D_model\"), ## (\"Label contents\" , \"\", \"label\"), ## (\"\", dialogHeight, \"scrollbar\"), ]",
"is not enough cloud \\ to support the corrsponding PoP. The user decides",
"Mail Stop B8 # Omaha, NE 68106 # 402.291.0100 # # See the",
"sure Sky cover for 5% PoP is 10-100% if self._SkyMin < 10: self._SkyMin",
"Tool ## # Cannot have WeatherElement or Grid arguments ## pass ## def",
"= varDict[\"Variable name2\"] # Determine new value ############################################################################# # # Configuration section #",
"self._SkyMin = 100 # Make sure Sky cover for 5% PoP < minimum",
"is too large\") ## ## Call self.noData(messageString) to stop execution of your tool",
"we are running the tool def preProcessTool(self, varDict): # Called once at beginning",
"InvalidSkyMask = logical_and(InvalidSkyMask5, areaMask) if any(InvalidSkyMask): self.createGrid(\"TemporaryData\", \"InvalidSkyForPoP\", \"SCALAR\", InvalidSkyMask, GridTimeRange) self.setActiveElement(\"TemporaryData\", \"InvalidSkyForPoP\",",
"is where 'breathingRoom' comes in # Sky is left alone if it is",
"## def preProcessTool(self, varDict): ## # Called once at beginning of Tool ##",
"pass ## def postProcessTool(self, varDict): ## # Called once at end of Tool",
"support, and with no warranty, express or implied, as to its usefulness for",
"Configuration section # ############################################################################# area = self.getEditArea(localFoecastArea) areaMask = self.encodeEditArea(area) if (self._operator ==",
"# 402.291.0100 # # See the AWIPS II Master Rights File (\"Master Rights",
"precip:\"] ## 15 self._PoPLimit = 15 self._SkyLimit = varDict[\"Enter Sky Limit: the minimum",
"or Grid arguments # Get thresholds for Sky cover # Get method self._operator",
"= logical_and(less(Sky, PoP * self._factor), less_equal(PoP * self._factor, 100)) InvalidSkyMask2 = logical_and(less(Sky, PoP",
"\"check\", ## [\"value1\", \"value2\", \"value3\"]), ## (\"Variable name4\" , \"default value4\", \"radio\", ##",
"Wx if self._SkyMin > self._SkyLimit - 15: self._SkyMin = self._SkyLimit - 15 #",
"software was developed and / or modified by Raytheon Company, # pursuant to",
"file will completely replace a lower priority version of the file. ## ToolType",
"cover # Get method self._operator = varDict[\"Sky vs PoP Relationship:\"] # For Add",
"## var1 = varDict[\"Variable name1\"] ## var2 = varDict[\"Variable name2\"] # Determine new",
"or other authorization. # # Contractor Name: <NAME> # Contractor Address: 6825 Pine",
"## [\"value1\", \"value2\", \"value3\"]), ## (\"Variable name5\" , defaultValue, \"scale\", ## [minValue, maxValue],",
"defaultValue1, \"numeric\"), ## (\"Variable name2\" , \"default value2\", \"alphaNumeric\"), (\"Sky vs PoP Relationship:\"",
"multiply (smaller factor), by how much ?\"] # For Add: self._lofactor = float(self._factor",
"than 100; this is where 'breathingRoom' comes in # Sky is left alone",
"## 60 self._SkyMin = varDict[\"Enter Sky cover for 5% PoP:\"] ## 30 #",
"version of the file. ## ToolType = \"numeric\" WeatherElementEdited = \"Sky\" from numpy",
"\"InvalidSkyForPoP\", \"SCALAR\", InvalidSkyMask, GridTimeRange) self.setActiveElement(\"TemporaryData\", \"InvalidSkyForPoP\", \"SFC\", GridTimeRange, fitToData=1) # Return the new",
"Limit: the minimum Sky cover needed to support Wx:\"] ## 60 self._SkyMin =",
"5. self._breathingRoom = 100 - self._factor # For Sky Limit: # self._PoPLimit =",
"Sky cover for Wx if self._SkyMin > self._SkyLimit - 15: self._SkyMin = self._SkyLimit",
"not enough cloud \\ to support the corrsponding PoP. The user decides by",
"you need to do is: ## -- Make sure to list \"self\" as",
"\"\", \"label\"), ## (\"\", dialogHeight, \"scrollbar\"), ] # Set up Class import SmartScript",
"self._factor = varDict[\"For add, multiply (smaller factor), by how much ?\"] # For",
"## 30 # Make sure minimum PoP for measurable precip is 15-25% if",
"cannot # be greater than 100; this is where 'breathingRoom' comes in #",
"= 50 elif self._SkyLimit > 100: self._SkyLimit = 100 # Make sure Sky",
"- self._SkyMin) / (self._PoPLimit - 5.0) ## def preProcessTool(self, varDict): ## # Called",
"only Sky less than Limit affected; it is raised to the Limit:\", \"\",",
"have WeatherElement or Grid arguments # Get thresholds for Sky cover # Get",
"cover for 5% PoP is 10-100% if self._SkyMin < 10: self._SkyMin = 10",
"your local forecast area # localFoecastArea = \"ISC_Send_Area\" # # End Configuration section",
"self._SkyLimit = 50 elif self._SkyLimit > 100: self._SkyLimit = 100 # Make sure",
"## var2 = varDict[\"Variable name2\"] # Determine new value ############################################################################# # # Configuration",
"any(InvalidSkyMask): self.createGrid(\"TemporaryData\", \"InvalidSkyForPoP\", \"SCALAR\", InvalidSkyMask, GridTimeRange) self.setActiveElement(\"TemporaryData\", \"InvalidSkyForPoP\", \"SFC\", GridTimeRange, fitToData=1) # Return",
"you want to use -- WeatherElement1, WeatherElement2... def execute(self, Sky, PoP, GridTimeRange, varDict):",
"Get thresholds for Sky cover # Get method self._operator = varDict[\"Sky vs PoP",
"the minimum Sky cover needed to support Wx:\" , 60, \"numeric\"), # (\"Enter",
"for measurable precip:\", 15, \"numeric\"), (\"Enter Sky cover for 5% PoP:\" , 30,",
"to the Limit:\", \"\", \"label\"), (\"Enter Sky Limit: the minimum Sky cover needed",
"* self._slope)) InvalidSkyMask5 = logical_or(InvalidSkyMask1, InvalidSkyMask2) # InvalidSkyMask = InvalidSkyMask5 InvalidSkyMask = logical_and(InvalidSkyMask5,",
"B8 # Omaha, NE 68106 # 402.291.0100 # # See the AWIPS II",
"## (\"Variable name6\" , \"\", \"model\"), ## (\"Variable name7\" , \"\", \"D2D_model\"), ##",
"needed to support Wx:\"] ## 60 self._SkyMin = varDict[\"Enter Sky cover for 5%",
"GridTimeRange, varDict): \"Creates highlight grids showing when and where there is not enough",
"and where there is not enough cloud \\ to support the corrsponding PoP.",
"InvalidSkyMask5 InvalidSkyMask = logical_and(InvalidSkyMask5, areaMask) if any(InvalidSkyMask): self.createGrid(\"TemporaryData\", \"InvalidSkyForPoP\", \"SCALAR\", InvalidSkyMask, GridTimeRange) self.setActiveElement(\"TemporaryData\",",
"[\"value1\", \"value2\", \"value3\"]), ## (\"Variable name4\" , \"default value4\", \"radio\", ## [\"value1\", \"value2\",",
"= varDict[\"Enter Sky Limit: the minimum Sky cover needed to support Wx:\"] ##",
"arguments ## pass ## What is \"self\"???? ## \"Self\" refers to this Tool",
"list \"self\" as the first argument of ## method Definitions: ## def _myMethod(self,",
"need to do is: ## -- Make sure to list \"self\" as the",
"self._PoPLimit = 25.0 # Make sure minimum Sky cover for Wx is 50-100%",
"- 5.0) ## def preProcessTool(self, varDict): ## # Called once at beginning of",
"or Grid arguments ## pass ## What is \"self\"???? ## \"Self\" refers to",
"(\"Variable name7\" , \"\", \"D2D_model\"), ## (\"Label contents\" , \"\", \"label\"), ## (\"\",",
"ToolTimeRange -- selected time range over which we are running the tool def",
"or Grid arguments ## pass ## def postProcessTool(self, varDict): ## # Called once",
"+ 5) / 5. self._breathingRoom = 100 - self._factor # For Sky Limit:",
", \"default value4\", \"radio\", ## [\"value1\", \"value2\", \"value3\"]), ## (\"Variable name5\" , defaultValue,",
"(add), or by a factor. The value for sky, of course, cannot #",
"cover for Wx is 50-100% if self._SkyLimit < 50: self._SkyLimit = 50 elif",
"Make sure minimum PoP for measurable precip is 15-25% if self._PoPLimit < 15.0:",
"stop execution of your tool and ## display a message to the user.",
"argument of ## method Definitions: ## def _myMethod(self, arg1, arg2) ## -- When",
"was developed and / or modified by Raytheon Company, # pursuant to Contract",
"export license or other authorization. # # Contractor Name: <NAME> # Contractor Address:",
"PoP for measurable precip:\", 15, \"numeric\"), (\"Enter Sky cover for 5% PoP:\" ,",
"alone if it is already large enough. # For Muultply: self._factor = varDict[\"For",
"60 self._SkyMin = varDict[\"Enter Sky cover for 5% PoP:\"] ## 30 # Make",
"InvalidSkyMask4) elif self._operator == \"multiply\": InvalidSkyMask1 = logical_and(less(Sky, PoP * self._factor), less_equal(PoP *",
"licensing information. ## # ---------------------------------------------------------------------------- # This software is in the public domain,",
"Limit:\", \"\", \"label\"), (\"Enter Sky Limit: the minimum Sky cover needed to support",
"# (\"Enter minimum PoP for measurable precip:\", 15, \"numeric\"), (\"Enter Sky cover for",
"Called once at beginning of Tool # Cannot have WeatherElement or Grid arguments",
"= logical_and(lowSkyMask, less_equal(Sky, self._SkyLimit - (self._PoPLimit - PoP) * self._slope)) InvalidSkyMask5 = logical_or(InvalidSkyMask1,",
"= [ ## (\"Variable name1\" , defaultValue1, \"numeric\"), ## (\"Variable name2\" , \"default",
"and / or modified by Raytheon Company, # pursuant to Contract DG133W-05-CQ-1067 with",
"(\"Variable name2\" , \"default value2\", \"alphaNumeric\"), (\"Sky vs PoP Relationship:\" , \"add\", \"radio\",",
"Sky cover for 5% PoP is 10-100% if self._SkyMin < 10: self._SkyMin =",
"varDict): ## # Called once at end of Tool ## # Cannot have",
"InvalidSkyMask, GridTimeRange) self.setActiveElement(\"TemporaryData\", \"InvalidSkyForPoP\", \"SFC\", GridTimeRange, fitToData=1) # Return the new value #",
"how much ?\" , \"20\", \"numeric\"), (\"For Sky Limit, only Sky less than",
"10 elif self._SkyMin > 100: self._SkyMin = 100 # Make sure Sky cover",
"Error Handling ## Call self.abort(errorString) to stop execution of your tool and ##",
"and ## display a message to the user. ## For example: ## if",
"## display a message to the user. ## For example: ## if x",
"defaultValue, \"scale\", ## [minValue, maxValue], resolution), ## (\"Variable name6\" , \"\", \"model\"), ##",
"factor), by how much ?\"] # For Add: self._lofactor = float(self._factor + 5)",
"## # This is an absolute override file, indicating that a higher priority",
"End Configuration section # ############################################################################# area = self.getEditArea(localFoecastArea) areaMask = self.encodeEditArea(area) if (self._operator",
"EXPORT CONTROLLED TECHNICAL DATA # This software product contains export-restricted data whose #",
"You can screen the elements for which your tool will appear by using",
"area = self.getEditArea(localFoecastArea) areaMask = self.encodeEditArea(area) if (self._operator == \"add\"): mainAddMask = logical_and(greater_equal(PoP,",
"= logical_or(InvalidSkyMask3, InvalidSkyMask4) elif self._operator == \"multiply\": InvalidSkyMask1 = logical_and(less(Sky, PoP * self._factor),",
"about it. ## All you need to do is: ## -- Make sure",
"do is: ## -- Make sure to list \"self\" as the first argument",
"Name: <NAME> # Contractor Address: 6825 Pine Street, Suite 340 # Mail Stop",
"Stop B8 # Omaha, NE 68106 # 402.291.0100 # # See the AWIPS",
"# Get method self._operator = varDict[\"Sky vs PoP Relationship:\"] # For Add or",
"- 15 # Compute slope to use for this line self._slope = (self._SkyLimit",
"Raytheon Company, # pursuant to Contract DG133W-05-CQ-1067 with the US Government. # #",
"(self._operator == \"add\"): mainAddMask = logical_and(greater_equal(PoP, 5), less(Sky, PoP + self._factor)) InvalidSkyMask1 =",
"for sky, of course, cannot # be greater than 100; this is where",
"public domain, furnished \"as is\", without technical # support, and with no warranty,",
"with no warranty, express or implied, as to its usefulness for # any",
"a lower priority version of the file. ## ToolType = \"numeric\" WeatherElementEdited =",
"Street, Suite 340 # Mail Stop B8 # Omaha, NE 68106 # 402.291.0100",
"for Sky cover # Get method self._operator = varDict[\"Sky vs PoP Relationship:\"] #",
"first argument of ## method Definitions: ## def _myMethod(self, arg1, arg2) ## --",
"= logical_and(mainAddMask, less_equal(PoP, self._breathingRoom)) InvalidSkyMask3 = logical_and(greater(PoP, self._breathingRoom), less(Sky, 99.5)) InvalidSkyMask4 = logical_or(InvalidSkyMask1,",
"lower priority version of the file. ## ToolType = \"numeric\" WeatherElementEdited = \"Sky\"",
"cover needed to support Wx:\"] ## 60 self._SkyMin = varDict[\"Enter Sky cover for",
"Required Method: Execute # Called once for each grid # Fill in the",
"self._PoPLimit > 25.0: self._PoPLimit = 25.0 # Make sure minimum Sky cover for",
"10: self._SkyMin = 10 elif self._SkyMin > 100: self._SkyMin = 100 # Make",
"message to the user. ## For example: ## if x > 1000: ##",
"elements for which your tool will appear by using # a ScreenList. For",
"# This software product contains export-restricted data whose # export/transfer/disclosure is restricted by",
"by how much ?\"] # For Add: self._lofactor = float(self._factor + 5) /",
"below) ## var1 = varDict[\"Variable name1\"] ## var2 = varDict[\"Variable name2\"] # Determine",
"PoP:\" , 30, \"numeric\"), ## (\"Variable name3\" , [\"default value1\", \"default value2\"], \"check\",",
"to list \"self\" as the first argument of ## method Definitions: ## def",
"SmartScript.SmartScript.__init__(self, dbss) # Required Method: Execute # Called once for each grid #",
"Add: self._lofactor = float(self._factor + 5) / 5. self._breathingRoom = 100 - self._factor",
"\"numeric\"), ## (\"Variable name2\" , \"default value2\", \"alphaNumeric\"), (\"Sky vs PoP Relationship:\" ,",
"from numpy import * HideTool = 1 # You can screen the elements",
"## # Cannot have WeatherElement or Grid arguments ## pass ## def postProcessTool(self,",
"value2\", \"alphaNumeric\"), (\"Sky vs PoP Relationship:\" , \"add\", \"radio\", [\"add\", \"multiply\", \"Sky Limit\"]),",
"stop execution of your tool ## and return a \"NoData\" error which can",
", \"\", \"D2D_model\"), ## (\"Label contents\" , \"\", \"label\"), ## (\"\", dialogHeight, \"scrollbar\"),",
"use self._methodName omitting ## \"self\" as the first argument: ## x = self._myMethod(arg1,",
"Here is where to change the active edit area to your local forecast",
"is an absolute override file, indicating that a higher priority version # of",
"restricted by U.S. law. Dissemination # to non-U.S. persons whether in the United",
"support Wx:\"] ## 60 self._SkyMin = varDict[\"Enter Sky cover for 5% PoP:\"] ##",
"100: self._SkyLimit = 100 # Make sure Sky cover for 5% PoP is",
"## def postProcessTool(self, varDict): ## # Called once at end of Tool ##",
"furnished \"as is\", without technical # support, and with no warranty, express or",
"the user. ## For example: ## if x > 1000: ## self.abort(\"x is",
"logical_and(less(Sky, PoP * self._factor), less_equal(PoP * self._factor, 100)) InvalidSkyMask2 = logical_and(less(Sky, PoP *",
"usefulness for # any purpose. # # CheckSkyWithPoP # # Author: # ----------------------------------------------------------------------------",
"def preProcessTool(self, varDict): # Called once at beginning of Tool # Cannot have",
"the United States or abroad requires # an export license or other authorization.",
"for # any purpose. # # CheckSkyWithPoP # # Author: # ---------------------------------------------------------------------------- ##",
"Sky cover needed to support Wx:\"] ## 60 self._SkyMin = varDict[\"Enter Sky cover",
"a higher priority version # of the file will completely replace a lower",
"logical_or(InvalidSkyMask1, InvalidSkyMask2) InvalidSkyMask5 = logical_or(InvalidSkyMask3, InvalidSkyMask4) elif self._operator == \"multiply\": InvalidSkyMask1 = logical_and(less(Sky,",
"can have the additional argument: ## # ToolTimeRange -- selected time range over",
"Tool # Cannot have WeatherElement or Grid arguments # Get thresholds for Sky",
"local forecast area # localFoecastArea = \"ISC_Send_Area\" # # End Configuration section #",
"as the first argument: ## x = self._myMethod(arg1, arg2) ## ## Error Handling",
"For Muultply: self._factor = varDict[\"For add, multiply (smaller factor), by how much ?\"]",
"5% PoP is 10-100% if self._SkyMin < 10: self._SkyMin = 10 elif self._SkyMin",
"(\"Enter Sky cover for 5% PoP:\" , 30, \"numeric\"), ## (\"Variable name3\" ,",
"logical_and(lowSkyMask, greater_equal(PoP, self._PoPLimit)) InvalidSkyMask2 = logical_and(lowSkyMask, less_equal(Sky, self._SkyLimit - (self._PoPLimit - PoP) *",
"## (\"Variable name1\" , defaultValue1, \"numeric\"), ## (\"Variable name2\" , \"default value2\", \"alphaNumeric\"),",
"minimum PoP for measurable precip:\", 15, \"numeric\"), (\"Enter Sky cover for 5% PoP:\"",
"Return the new value # return Sky # Optional Methods ## # These",
"10-100% if self._SkyMin < 10: self._SkyMin = 10 elif self._SkyMin > 100: self._SkyMin",
"to stop execution of your tool ## and return a \"NoData\" error which",
"# Cannot have WeatherElement or Grid arguments ## pass ## def postProcessTool(self, varDict):",
"varDict[\"Enter Sky Limit: the minimum Sky cover needed to support Wx:\"] ## 60",
"5) / 5. self._breathingRoom = 100 - self._factor # For Sky Limit: #",
"the minimum Sky cover needed to support Wx:\"] ## 60 self._SkyMin = varDict[\"Enter",
"localFoecastArea = \"ISC_Send_Area\" # # End Configuration section # ############################################################################# area = self.getEditArea(localFoecastArea)",
"## # ToolTimeRange -- selected time range over which we are running the",
"precip:\", 15, \"numeric\"), (\"Enter Sky cover for 5% PoP:\" , 30, \"numeric\"), ##",
"name6\" , \"\", \"model\"), ## (\"Variable name7\" , \"\", \"D2D_model\"), ## (\"Label contents\"",
"For available commands, see SmartScript class Tool (SmartScript.SmartScript): def __init__(self, dbss): SmartScript.SmartScript.__init__(self, dbss)",
"Handling ## Call self.abort(errorString) to stop execution of your tool and ## display",
"For example: ## if x > 1000: ## self.abort(\"x is too large\") ##",
"vs PoP Relationship:\" , \"add\", \"radio\", [\"add\", \"multiply\", \"Sky Limit\"]), (\"For add, multiply",
"fixed amount # (add), or by a factor. The value for sky, of",
"to non-U.S. persons whether in the United States or abroad requires # an",
"x > 1000: ## self.abort(\"x is too large\") ## ## Call self.noData(messageString) to",
"Limit, only Sky less than Limit affected; it is raised to the Limit:\",",
"SmartScript class Tool (SmartScript.SmartScript): def __init__(self, dbss): SmartScript.SmartScript.__init__(self, dbss) # Required Method: Execute",
"var2 = varDict[\"Variable name2\"] # Determine new value ############################################################################# # # Configuration section",
"Get method self._operator = varDict[\"Sky vs PoP Relationship:\"] # For Add or Multiply:",
"# Cannot have WeatherElement or Grid arguments ## pass ## What is \"self\"????",
"greater_equal(PoP, self._PoPLimit)) InvalidSkyMask2 = logical_and(lowSkyMask, less_equal(Sky, self._SkyLimit - (self._PoPLimit - PoP) * self._slope))",
"PoP < minimum Sky cover for Wx if self._SkyMin > self._SkyLimit - 15:",
"(\"Enter minimum PoP for measurable precip:\", 15, \"numeric\"), (\"Enter Sky cover for 5%",
"will appear by using # a ScreenList. For example: # #ScreenList = [\"T\",\"Td\"]",
"add, multiply (smaller factor), by how much ?\" , \"20\", \"numeric\"), (\"For Sky",
"# Called once at end of Tool ## # Cannot have WeatherElement or",
"is raised to the Limit:\", \"\", \"label\"), (\"Enter Sky Limit: the minimum Sky",
"multiply (smaller factor), by how much ?\" , \"20\", \"numeric\"), (\"For Sky Limit,",
"non-U.S. persons whether in the United States or abroad requires # an export",
"self._SkyMin = self._SkyLimit - 15 # Compute slope to use for this line",
"to this Tool class instance. Don't worry much about it. ## All you",
"### If desired, Set up variables to be solicited from the user: VariableList",
"self._SkyLimit) InvalidSkyMask1 = logical_and(lowSkyMask, greater_equal(PoP, self._PoPLimit)) InvalidSkyMask2 = logical_and(lowSkyMask, less_equal(Sky, self._SkyLimit - (self._PoPLimit",
", \"20\", \"numeric\"), (\"For Sky Limit, only Sky less than Limit affected; it",
"arguments # Get thresholds for Sky cover # Get method self._operator = varDict[\"Sky",
"it. ## All you need to do is: ## -- Make sure to",
"tool ## and return a \"NoData\" error which can be checked by a",
"of course, cannot # be greater than 100; this is where 'breathingRoom' comes",
"name2\" , \"default value2\", \"alphaNumeric\"), (\"Sky vs PoP Relationship:\" , \"add\", \"radio\", [\"add\",",
"name3\" , [\"default value1\", \"default value2\"], \"check\", ## [\"value1\", \"value2\", \"value3\"]), ## (\"Variable",
"by how much ?\" , \"20\", \"numeric\"), (\"For Sky Limit, only Sky less",
"\"as is\", without technical # support, and with no warranty, express or implied,",
"\"Creates highlight grids showing when and where there is not enough cloud \\",
"the public domain, furnished \"as is\", without technical # support, and with no",
"= varDict[\"Variable name1\"] ## var2 = varDict[\"Variable name2\"] # Determine new value #############################################################################",
"is 50-100% if self._SkyLimit < 50: self._SkyLimit = 50 elif self._SkyLimit > 100:",
"1 # You can screen the elements for which your tool will appear",
"# Fill in the arguments you want to use -- WeatherElement1, WeatherElement2... def",
"is greater than PoP, either by a fixed amount # (add), or by",
"file, indicating that a higher priority version # of the file will completely",
"All you need to do is: ## -- Make sure to list \"self\"",
"= varDict[\"Sky vs PoP Relationship:\"] # For Add or Multiply: # Idea is",
"want to use -- WeatherElement1, WeatherElement2... def execute(self, Sky, PoP, GridTimeRange, varDict): \"Creates",
"# This software is in the public domain, furnished \"as is\", without technical",
"sure minimum Sky cover for Wx is 50-100% if self._SkyLimit < 50: self._SkyLimit",
"self._slope = (self._SkyLimit - self._SkyMin) / (self._PoPLimit - 5.0) ## def preProcessTool(self, varDict):",
"= 1 # You can screen the elements for which your tool will",
"# Set up Class import SmartScript ## For available commands, see SmartScript class",
"self.setActiveElement(\"TemporaryData\", \"InvalidSkyForPoP\", \"SFC\", GridTimeRange, fitToData=1) # Return the new value # return Sky",
"## 15 self._PoPLimit = 15 self._SkyLimit = varDict[\"Enter Sky Limit: the minimum Sky",
"ScreenList. For example: # #ScreenList = [\"T\",\"Td\"] #ScreenList = [\"SCALAR\",\"VECTOR\",\"WEATHER\",\"DISCRETE\"] ### If desired,",
"law. Dissemination # to non-U.S. persons whether in the United States or abroad",
"# These methods can have the additional argument: ## # ToolTimeRange -- selected",
"GridTimeRange, fitToData=1) # Return the new value # return Sky # Optional Methods",
"30 # Make sure minimum PoP for measurable precip is 15-25% if self._PoPLimit",
"ToolType = \"numeric\" WeatherElementEdited = \"Sky\" from numpy import * HideTool = 1",
"user decides by how much, or by what \\ factor, the cloud should",
"should be greater.\" ## # Set up Variables from the varDict (see VariableList",
"to support Wx:\"] ## 60 self._SkyMin = varDict[\"Enter Sky cover for 5% PoP:\"]",
"much about it. ## All you need to do is: ## -- Make",
"method Definitions: ## def _myMethod(self, arg1, arg2) ## -- When calling your methods,",
"Limit\"]), (\"For add, multiply (smaller factor), by how much ?\" , \"20\", \"numeric\"),",
"over which we are running the tool def preProcessTool(self, varDict): # Called once",
"Author: # ---------------------------------------------------------------------------- ## # This is an absolute override file, indicating that",
"CONTROLLED TECHNICAL DATA # This software product contains export-restricted data whose # export/transfer/disclosure",
"Rights File (\"Master Rights File.pdf\") for # further licensing information. ## # ----------------------------------------------------------------------------",
"dialogHeight, \"scrollbar\"), ] # Set up Class import SmartScript ## For available commands,",
"execution of your tool and ## display a message to the user. ##",
"\"value2\", \"value3\"]), ## (\"Variable name5\" , defaultValue, \"scale\", ## [minValue, maxValue], resolution), ##",
"to the user. ## For example: ## if x > 1000: ## self.abort(\"x",
"name5\" , defaultValue, \"scale\", ## [minValue, maxValue], resolution), ## (\"Variable name6\" , \"\",",
"\"InvalidSkyForPoP\", \"SFC\", GridTimeRange, fitToData=1) # Return the new value # return Sky #",
"Sky cover for 5% PoP:\" , 30, \"numeric\"), ## (\"Variable name3\" , [\"default",
"the US Government. # # U.S. EXPORT CONTROLLED TECHNICAL DATA # This software",
"if (self._operator == \"add\"): mainAddMask = logical_and(greater_equal(PoP, 5), less(Sky, PoP + self._factor)) InvalidSkyMask1",
"higher priority version # of the file will completely replace a lower priority",
"InvalidSkyMask2) # InvalidSkyMask = InvalidSkyMask5 InvalidSkyMask = logical_and(InvalidSkyMask5, areaMask) if any(InvalidSkyMask): self.createGrid(\"TemporaryData\", \"InvalidSkyForPoP\",",
"less(Sky, self._SkyLimit) InvalidSkyMask1 = logical_and(lowSkyMask, greater_equal(PoP, self._PoPLimit)) InvalidSkyMask2 = logical_and(lowSkyMask, less_equal(Sky, self._SkyLimit -",
"= 15 self._SkyLimit = varDict[\"Enter Sky Limit: the minimum Sky cover needed to",
"= self._myMethod(arg1, arg2) ## ## Error Handling ## Call self.abort(errorString) to stop execution",
"example: # #ScreenList = [\"T\",\"Td\"] #ScreenList = [\"SCALAR\",\"VECTOR\",\"WEATHER\",\"DISCRETE\"] ### If desired, Set up",
"section # # Here is where to change the active edit area to",
"add, multiply (smaller factor), by how much ?\"] # For Add: self._lofactor =",
"self.abort(errorString) to stop execution of your tool and ## display a message to",
"is Sky is greater than PoP, either by a fixed amount # (add),",
"class instance. Don't worry much about it. ## All you need to do",
"override file, indicating that a higher priority version # of the file will",
"6825 Pine Street, Suite 340 # Mail Stop B8 # Omaha, NE 68106",
"Variables from the varDict (see VariableList below) ## var1 = varDict[\"Variable name1\"] ##",
"be greater than 100; this is where 'breathingRoom' comes in # Sky is",
"InvalidSkyMask2 = logical_and(less(Sky, PoP * self._factor), greater(PoP * self._factor, 100)) InvalidSkyMask5 = logical_or(InvalidSkyMask1,",
"For Sky Limit: # self._PoPLimit = varDict[\"Enter minimum PoP for measurable precip:\"] ##",
"## pass ## def postProcessTool(self, varDict): ## # Called once at end of",
"#ScreenList = [\"SCALAR\",\"VECTOR\",\"WEATHER\",\"DISCRETE\"] ### If desired, Set up variables to be solicited from",
"100 - self._factor # For Sky Limit: # self._PoPLimit = varDict[\"Enter minimum PoP",
"15 self._SkyLimit = varDict[\"Enter Sky Limit: the minimum Sky cover needed to support",
"= 15.0 elif self._PoPLimit > 25.0: self._PoPLimit = 25.0 # Make sure minimum",
"fitToData=1) # Return the new value # return Sky # Optional Methods ##",
"user: VariableList = [ ## (\"Variable name1\" , defaultValue1, \"numeric\"), ## (\"Variable name2\"",
"## (\"Variable name5\" , defaultValue, \"scale\", ## [minValue, maxValue], resolution), ## (\"Variable name6\"",
"100 # Make sure Sky cover for 5% PoP < minimum Sky cover",
"== \"multiply\": InvalidSkyMask1 = logical_and(less(Sky, PoP * self._factor), less_equal(PoP * self._factor, 100)) InvalidSkyMask2",
"license or other authorization. # # Contractor Name: <NAME> # Contractor Address: 6825",
"arg2) ## -- When calling your methods, use self._methodName omitting ## \"self\" as",
"#ScreenList = [\"T\",\"Td\"] #ScreenList = [\"SCALAR\",\"VECTOR\",\"WEATHER\",\"DISCRETE\"] ### If desired, Set up variables to",
"areaMask = self.encodeEditArea(area) if (self._operator == \"add\"): mainAddMask = logical_and(greater_equal(PoP, 5), less(Sky, PoP",
"once at beginning of Tool ## # Cannot have WeatherElement or Grid arguments",
"minimum Sky cover for Wx if self._SkyMin > self._SkyLimit - 15: self._SkyMin =",
"What is \"self\"???? ## \"Self\" refers to this Tool class instance. Don't worry",
"= float(self._factor + 5) / 5. self._breathingRoom = 100 - self._factor # For",
"15.0: self._PoPLimit = 15.0 elif self._PoPLimit > 25.0: self._PoPLimit = 25.0 # Make",
"worry much about it. ## All you need to do is: ## --",
"VariableList = [ ## (\"Variable name1\" , defaultValue1, \"numeric\"), ## (\"Variable name2\" ,",
"WeatherElement2... def execute(self, Sky, PoP, GridTimeRange, varDict): \"Creates highlight grids showing when and",
"is restricted by U.S. law. Dissemination # to non-U.S. persons whether in the",
"authorization. # # Contractor Name: <NAME> # Contractor Address: 6825 Pine Street, Suite",
"elif self._operator == \"multiply\": InvalidSkyMask1 = logical_and(less(Sky, PoP * self._factor), less_equal(PoP * self._factor,",
"# pursuant to Contract DG133W-05-CQ-1067 with the US Government. # # U.S. EXPORT",
"less than Limit affected; it is raised to the Limit:\", \"\", \"label\"), (\"Enter",
"\"numeric\"), (\"For Sky Limit, only Sky less than Limit affected; it is raised",
"it is raised to the Limit:\", \"\", \"label\"), (\"Enter Sky Limit: the minimum",
"varDict[\"For add, multiply (smaller factor), by how much ?\"] # For Add: self._lofactor",
"self._PoPLimit < 15.0: self._PoPLimit = 15.0 elif self._PoPLimit > 25.0: self._PoPLimit = 25.0",
"to use -- WeatherElement1, WeatherElement2... def execute(self, Sky, PoP, GridTimeRange, varDict): \"Creates highlight",
"def postProcessTool(self, varDict): ## # Called once at end of Tool ## #",
"(\"Label contents\" , \"\", \"label\"), ## (\"\", dialogHeight, \"scrollbar\"), ] # Set up",
"self._PoPLimit)) InvalidSkyMask2 = logical_and(lowSkyMask, less_equal(Sky, self._SkyLimit - (self._PoPLimit - PoP) * self._slope)) InvalidSkyMask5",
"Optional Methods ## # These methods can have the additional argument: ## #",
"# Make sure Sky cover for 5% PoP is 10-100% if self._SkyMin <",
"(self._PoPLimit - 5.0) ## def preProcessTool(self, varDict): ## # Called once at beginning",
"postProcessTool(self, varDict): ## # Called once at end of Tool ## # Cannot",
"your methods, use self._methodName omitting ## \"self\" as the first argument: ## x",
"either by a fixed amount # (add), or by a factor. The value",
"25.0 # Make sure minimum Sky cover for Wx is 50-100% if self._SkyLimit",
"* HideTool = 1 # You can screen the elements for which your",
"Contract DG133W-05-CQ-1067 with the US Government. # # U.S. EXPORT CONTROLLED TECHNICAL DATA",
"/ 5. self._breathingRoom = 100 - self._factor # For Sky Limit: # self._PoPLimit",
"replace a lower priority version of the file. ## ToolType = \"numeric\" WeatherElementEdited",
"other authorization. # # Contractor Name: <NAME> # Contractor Address: 6825 Pine Street,",
"value1\", \"default value2\"], \"check\", ## [\"value1\", \"value2\", \"value3\"]), ## (\"Variable name4\" , \"default",
"= logical_and(greater_equal(PoP, 5), less(Sky, PoP + self._factor)) InvalidSkyMask1 = logical_and(less(PoP, 5), less_equal(Sky, PoP",
"have the additional argument: ## # ToolTimeRange -- selected time range over which",
"# Configuration section # # Here is where to change the active edit",
"Sky cover # Get method self._operator = varDict[\"Sky vs PoP Relationship:\"] # For",
"U.S. law. Dissemination # to non-U.S. persons whether in the United States or",
"[\"T\",\"Td\"] #ScreenList = [\"SCALAR\",\"VECTOR\",\"WEATHER\",\"DISCRETE\"] ### If desired, Set up variables to be solicited",
"for measurable precip is 15-25% if self._PoPLimit < 15.0: self._PoPLimit = 15.0 elif",
"to stop execution of your tool and ## display a message to the",
"############################################################################# # # Configuration section # # Here is where to change the",
"self.noData(messageString) to stop execution of your tool ## and return a \"NoData\" error",
"for Wx if self._SkyMin > self._SkyLimit - 15: self._SkyMin = self._SkyLimit - 15",
"logical_and(InvalidSkyMask5, areaMask) if any(InvalidSkyMask): self.createGrid(\"TemporaryData\", \"InvalidSkyForPoP\", \"SCALAR\", InvalidSkyMask, GridTimeRange) self.setActiveElement(\"TemporaryData\", \"InvalidSkyForPoP\", \"SFC\", GridTimeRange,",
"Sky cover for 5% PoP:\"] ## 30 # Make sure minimum PoP for",
"vs PoP Relationship:\"] # For Add or Multiply: # Idea is Sky is",
"dbss): SmartScript.SmartScript.__init__(self, dbss) # Required Method: Execute # Called once for each grid",
"\"label\"), (\"Enter Sky Limit: the minimum Sky cover needed to support Wx:\" ,",
"Make sure to list \"self\" as the first argument of ## method Definitions:",
"InvalidSkyMask5 = logical_or(InvalidSkyMask1, InvalidSkyMask2) else: lowSkyMask = less(Sky, self._SkyLimit) InvalidSkyMask1 = logical_and(lowSkyMask, greater_equal(PoP,",
"Class import SmartScript ## For available commands, see SmartScript class Tool (SmartScript.SmartScript): def",
"this is where 'breathingRoom' comes in # Sky is left alone if it",
"by U.S. law. Dissemination # to non-U.S. persons whether in the United States",
"data whose # export/transfer/disclosure is restricted by U.S. law. Dissemination # to non-U.S.",
"or implied, as to its usefulness for # any purpose. # # CheckSkyWithPoP",
"var1 = varDict[\"Variable name1\"] ## var2 = varDict[\"Variable name2\"] # Determine new value",
"(\"Variable name6\" , \"\", \"model\"), ## (\"Variable name7\" , \"\", \"D2D_model\"), ## (\"Label",
"Sky is greater than PoP, either by a fixed amount # (add), or",
"argument: ## x = self._myMethod(arg1, arg2) ## ## Error Handling ## Call self.abort(errorString)",
"the first argument: ## x = self._myMethod(arg1, arg2) ## ## Error Handling ##",
"HideTool = 1 # You can screen the elements for which your tool",
"Sky # Optional Methods ## # These methods can have the additional argument:",
"# # CheckSkyWithPoP # # Author: # ---------------------------------------------------------------------------- ## # This is an",
"is 15-25% if self._PoPLimit < 15.0: self._PoPLimit = 15.0 elif self._PoPLimit > 25.0:",
"desired, Set up variables to be solicited from the user: VariableList = [",
"(see VariableList below) ## var1 = varDict[\"Variable name1\"] ## var2 = varDict[\"Variable name2\"]",
"(self._SkyLimit - self._SkyMin) / (self._PoPLimit - 5.0) ## def preProcessTool(self, varDict): ## #",
"U.S. EXPORT CONTROLLED TECHNICAL DATA # This software product contains export-restricted data whose",
"self._SkyLimit - 15 # Compute slope to use for this line self._slope =",
"Tool ## # Cannot have WeatherElement or Grid arguments ## pass ## What",
"contents\" , \"\", \"label\"), ## (\"\", dialogHeight, \"scrollbar\"), ] # Set up Class",
"Fill in the arguments you want to use -- WeatherElement1, WeatherElement2... def execute(self,",
"self._SkyLimit = 100 # Make sure Sky cover for 5% PoP is 10-100%",
"if self._PoPLimit < 15.0: self._PoPLimit = 15.0 elif self._PoPLimit > 25.0: self._PoPLimit =",
"Make sure Sky cover for 5% PoP is 10-100% if self._SkyMin < 10:",
"self._breathingRoom = 100 - self._factor # For Sky Limit: # self._PoPLimit = varDict[\"Enter",
"## x = self._myMethod(arg1, arg2) ## ## Error Handling ## Call self.abort(errorString) to",
"of the file. ## ToolType = \"numeric\" WeatherElementEdited = \"Sky\" from numpy import",
"## [\"value1\", \"value2\", \"value3\"]), ## (\"Variable name4\" , \"default value4\", \"radio\", ## [\"value1\",",
"# Contractor Name: <NAME> # Contractor Address: 6825 Pine Street, Suite 340 #",
"[\"value1\", \"value2\", \"value3\"]), ## (\"Variable name5\" , defaultValue, \"scale\", ## [minValue, maxValue], resolution),",
"PoP, GridTimeRange, varDict): \"Creates highlight grids showing when and where there is not",
"method self._operator = varDict[\"Sky vs PoP Relationship:\"] # For Add or Multiply: #",
"file. ## ToolType = \"numeric\" WeatherElementEdited = \"Sky\" from numpy import * HideTool",
"as to its usefulness for # any purpose. # # CheckSkyWithPoP # #",
"# Required Method: Execute # Called once for each grid # Fill in",
"SmartScript ## For available commands, see SmartScript class Tool (SmartScript.SmartScript): def __init__(self, dbss):",
"to support the corrsponding PoP. The user decides by how much, or by",
"InvalidSkyMask3 = logical_and(greater(PoP, self._breathingRoom), less(Sky, 99.5)) InvalidSkyMask4 = logical_or(InvalidSkyMask1, InvalidSkyMask2) InvalidSkyMask5 = logical_or(InvalidSkyMask3,",
"additional argument: ## # ToolTimeRange -- selected time range over which we are",
"_myMethod(self, arg1, arg2) ## -- When calling your methods, use self._methodName omitting ##",
"\"radio\", ## [\"value1\", \"value2\", \"value3\"]), ## (\"Variable name5\" , defaultValue, \"scale\", ## [minValue,",
"Called once for each grid # Fill in the arguments you want to",
"InvalidSkyMask1 = logical_and(lowSkyMask, greater_equal(PoP, self._PoPLimit)) InvalidSkyMask2 = logical_and(lowSkyMask, less_equal(Sky, self._SkyLimit - (self._PoPLimit -",
"available commands, see SmartScript class Tool (SmartScript.SmartScript): def __init__(self, dbss): SmartScript.SmartScript.__init__(self, dbss) #",
"end of Tool ## # Cannot have WeatherElement or Grid arguments ## pass",
"# to non-U.S. persons whether in the United States or abroad requires #",
"self._slope)) InvalidSkyMask5 = logical_or(InvalidSkyMask1, InvalidSkyMask2) # InvalidSkyMask = InvalidSkyMask5 InvalidSkyMask = logical_and(InvalidSkyMask5, areaMask)",
"Definitions: ## def _myMethod(self, arg1, arg2) ## -- When calling your methods, use",
"in the public domain, furnished \"as is\", without technical # support, and with",
"# any purpose. # # CheckSkyWithPoP # # Author: # ---------------------------------------------------------------------------- ## #",
"[minValue, maxValue], resolution), ## (\"Variable name6\" , \"\", \"model\"), ## (\"Variable name7\" ,",
"return Sky # Optional Methods ## # These methods can have the additional",
"__init__(self, dbss): SmartScript.SmartScript.__init__(self, dbss) # Required Method: Execute # Called once for each",
"it is already large enough. # For Muultply: self._factor = varDict[\"For add, multiply",
"logical_or(InvalidSkyMask3, InvalidSkyMask4) elif self._operator == \"multiply\": InvalidSkyMask1 = logical_and(less(Sky, PoP * self._factor), less_equal(PoP",
", 60, \"numeric\"), # (\"Enter minimum PoP for measurable precip:\", 15, \"numeric\"), (\"Enter",
"what \\ factor, the cloud should be greater.\" ## # Set up Variables",
"appear by using # a ScreenList. For example: # #ScreenList = [\"T\",\"Td\"] #ScreenList",
"self._lofactor = float(self._factor + 5) / 5. self._breathingRoom = 100 - self._factor #",
"left alone if it is already large enough. # For Muultply: self._factor =",
"15: self._SkyMin = self._SkyLimit - 15 # Compute slope to use for this",
"that a higher priority version # of the file will completely replace a",
"priority version of the file. ## ToolType = \"numeric\" WeatherElementEdited = \"Sky\" from",
"varDict[\"Enter Sky cover for 5% PoP:\"] ## 30 # Make sure minimum PoP",
"50 elif self._SkyLimit > 100: self._SkyLimit = 100 # Make sure Sky cover",
"factor, the cloud should be greater.\" ## # Set up Variables from the",
"# Cannot have WeatherElement or Grid arguments # Get thresholds for Sky cover",
"to support Wx:\" , 60, \"numeric\"), # (\"Enter minimum PoP for measurable precip:\",",
"100)) InvalidSkyMask5 = logical_or(InvalidSkyMask1, InvalidSkyMask2) else: lowSkyMask = less(Sky, self._SkyLimit) InvalidSkyMask1 = logical_and(lowSkyMask,",
"Address: 6825 Pine Street, Suite 340 # Mail Stop B8 # Omaha, NE",
"# export/transfer/disclosure is restricted by U.S. law. Dissemination # to non-U.S. persons whether",
"logical_or(InvalidSkyMask1, InvalidSkyMask2) else: lowSkyMask = less(Sky, self._SkyLimit) InvalidSkyMask1 = logical_and(lowSkyMask, greater_equal(PoP, self._PoPLimit)) InvalidSkyMask2",
"# Idea is Sky is greater than PoP, either by a fixed amount",
"[\"SCALAR\",\"VECTOR\",\"WEATHER\",\"DISCRETE\"] ### If desired, Set up variables to be solicited from the user:",
"import SmartScript ## For available commands, see SmartScript class Tool (SmartScript.SmartScript): def __init__(self,",
"50: self._SkyLimit = 50 elif self._SkyLimit > 100: self._SkyLimit = 100 # Make",
"display a message to the user. ## For example: ## if x >",
"For Add: self._lofactor = float(self._factor + 5) / 5. self._breathingRoom = 100 -",
"## def _myMethod(self, arg1, arg2) ## -- When calling your methods, use self._methodName",
"\"value2\", \"value3\"]), ## (\"Variable name4\" , \"default value4\", \"radio\", ## [\"value1\", \"value2\", \"value3\"]),",
"area # localFoecastArea = \"ISC_Send_Area\" # # End Configuration section # ############################################################################# area",
"dbss) # Required Method: Execute # Called once for each grid # Fill",
"[\"default value1\", \"default value2\"], \"check\", ## [\"value1\", \"value2\", \"value3\"]), ## (\"Variable name4\" ,",
"sky, of course, cannot # be greater than 100; this is where 'breathingRoom'",
"self._SkyMin > 100: self._SkyMin = 100 # Make sure Sky cover for 5%",
"# For Add: self._lofactor = float(self._factor + 5) / 5. self._breathingRoom = 100",
"areaMask) if any(InvalidSkyMask): self.createGrid(\"TemporaryData\", \"InvalidSkyForPoP\", \"SCALAR\", InvalidSkyMask, GridTimeRange) self.setActiveElement(\"TemporaryData\", \"InvalidSkyForPoP\", \"SFC\", GridTimeRange, fitToData=1)",
"Dissemination # to non-U.S. persons whether in the United States or abroad requires",
"+ self._factor)) InvalidSkyMask1 = logical_and(less(PoP, 5), less_equal(Sky, PoP * self._lofactor)) InvalidSkyMask2 = logical_and(mainAddMask,",
"further licensing information. ## # ---------------------------------------------------------------------------- # This software is in the public",
"implied, as to its usefulness for # any purpose. # # CheckSkyWithPoP #",
"= logical_and(lowSkyMask, greater_equal(PoP, self._PoPLimit)) InvalidSkyMask2 = logical_and(lowSkyMask, less_equal(Sky, self._SkyLimit - (self._PoPLimit - PoP)",
"# # Here is where to change the active edit area to your",
"omitting ## \"self\" as the first argument: ## x = self._myMethod(arg1, arg2) ##",
"support Wx:\" , 60, \"numeric\"), # (\"Enter minimum PoP for measurable precip:\", 15,",
"## # Set up Variables from the varDict (see VariableList below) ## var1",
"float(self._factor + 5) / 5. self._breathingRoom = 100 - self._factor # For Sky",
"# For Sky Limit: # self._PoPLimit = varDict[\"Enter minimum PoP for measurable precip:\"]",
"by Raytheon Company, # pursuant to Contract DG133W-05-CQ-1067 with the US Government. #",
"\"20\", \"numeric\"), (\"For Sky Limit, only Sky less than Limit affected; it is",
"# End Configuration section # ############################################################################# area = self.getEditArea(localFoecastArea) areaMask = self.encodeEditArea(area) if",
"PoP is 10-100% if self._SkyMin < 10: self._SkyMin = 10 elif self._SkyMin >",
"first argument: ## x = self._myMethod(arg1, arg2) ## ## Error Handling ## Call",
"Sky Limit: the minimum Sky cover needed to support Wx:\" , 60, \"numeric\"),",
"for which your tool will appear by using # a ScreenList. For example:",
"precip is 15-25% if self._PoPLimit < 15.0: self._PoPLimit = 15.0 elif self._PoPLimit >",
"WeatherElement or Grid arguments # Get thresholds for Sky cover # Get method",
"of the file will completely replace a lower priority version of the file.",
"minimum PoP for measurable precip is 15-25% if self._PoPLimit < 15.0: self._PoPLimit =",
"# an export license or other authorization. # # Contractor Name: <NAME> #",
"<NAME> # Contractor Address: 6825 Pine Street, Suite 340 # Mail Stop B8",
"the user: VariableList = [ ## (\"Variable name1\" , defaultValue1, \"numeric\"), ## (\"Variable",
"def __init__(self, dbss): SmartScript.SmartScript.__init__(self, dbss) # Required Method: Execute # Called once for",
"completely replace a lower priority version of the file. ## ToolType = \"numeric\"",
"TECHNICAL DATA # This software product contains export-restricted data whose # export/transfer/disclosure is",
"# Contractor Address: 6825 Pine Street, Suite 340 # Mail Stop B8 #",
"\"model\"), ## (\"Variable name7\" , \"\", \"D2D_model\"), ## (\"Label contents\" , \"\", \"label\"),",
"to its usefulness for # any purpose. # # CheckSkyWithPoP # # Author:",
"for each grid # Fill in the arguments you want to use --",
"# ############################################################################# area = self.getEditArea(localFoecastArea) areaMask = self.encodeEditArea(area) if (self._operator == \"add\"): mainAddMask",
"Cannot have WeatherElement or Grid arguments ## pass ## What is \"self\"???? ##",
"\"D2D_model\"), ## (\"Label contents\" , \"\", \"label\"), ## (\"\", dialogHeight, \"scrollbar\"), ] #",
"\"SCALAR\", InvalidSkyMask, GridTimeRange) self.setActiveElement(\"TemporaryData\", \"InvalidSkyForPoP\", \"SFC\", GridTimeRange, fitToData=1) # Return the new value",
"elif self._SkyMin > 100: self._SkyMin = 100 # Make sure Sky cover for",
"Sky cover for 5% PoP < minimum Sky cover for Wx if self._SkyMin",
"for this line self._slope = (self._SkyLimit - self._SkyMin) / (self._PoPLimit - 5.0) ##",
"value for sky, of course, cannot # be greater than 100; this is",
"## if x > 1000: ## self.abort(\"x is too large\") ## ## Call",
"or abroad requires # an export license or other authorization. # # Contractor",
"there is not enough cloud \\ to support the corrsponding PoP. The user",
"name7\" , \"\", \"D2D_model\"), ## (\"Label contents\" , \"\", \"label\"), ## (\"\", dialogHeight,",
"15, \"numeric\"), (\"Enter Sky cover for 5% PoP:\" , 30, \"numeric\"), ## (\"Variable",
"/ (self._PoPLimit - 5.0) ## def preProcessTool(self, varDict): ## # Called once at",
"using # a ScreenList. For example: # #ScreenList = [\"T\",\"Td\"] #ScreenList = [\"SCALAR\",\"VECTOR\",\"WEATHER\",\"DISCRETE\"]",
"in # Sky is left alone if it is already large enough. #",
"File (\"Master Rights File.pdf\") for # further licensing information. ## # ---------------------------------------------------------------------------- #",
"for Wx is 50-100% if self._SkyLimit < 50: self._SkyLimit = 50 elif self._SkyLimit",
"is\", without technical # support, and with no warranty, express or implied, as",
"5), less_equal(Sky, PoP * self._lofactor)) InvalidSkyMask2 = logical_and(mainAddMask, less_equal(PoP, self._breathingRoom)) InvalidSkyMask3 = logical_and(greater(PoP,",
"-- When calling your methods, use self._methodName omitting ## \"self\" as the first",
"= logical_and(greater(PoP, self._breathingRoom), less(Sky, 99.5)) InvalidSkyMask4 = logical_or(InvalidSkyMask1, InvalidSkyMask2) InvalidSkyMask5 = logical_or(InvalidSkyMask3, InvalidSkyMask4)",
"---------------------------------------------------------------------------- ## # This is an absolute override file, indicating that a higher",
"-- WeatherElement1, WeatherElement2... def execute(self, Sky, PoP, GridTimeRange, varDict): \"Creates highlight grids showing",
"?\"] # For Add: self._lofactor = float(self._factor + 5) / 5. self._breathingRoom =",
"Add or Multiply: # Idea is Sky is greater than PoP, either by",
"Sky cover for Wx is 50-100% if self._SkyLimit < 50: self._SkyLimit = 50",
"the arguments you want to use -- WeatherElement1, WeatherElement2... def execute(self, Sky, PoP,",
"this Tool class instance. Don't worry much about it. ## All you need",
"already large enough. # For Muultply: self._factor = varDict[\"For add, multiply (smaller factor),",
"Contractor Name: <NAME> # Contractor Address: 6825 Pine Street, Suite 340 # Mail",
", [\"default value1\", \"default value2\"], \"check\", ## [\"value1\", \"value2\", \"value3\"]), ## (\"Variable name4\"",
"domain, furnished \"as is\", without technical # support, and with no warranty, express",
"decides by how much, or by what \\ factor, the cloud should be",
"beginning of Tool # Cannot have WeatherElement or Grid arguments # Get thresholds",
"Tool (SmartScript.SmartScript): def __init__(self, dbss): SmartScript.SmartScript.__init__(self, dbss) # Required Method: Execute # Called",
"self._factor, 100)) InvalidSkyMask2 = logical_and(less(Sky, PoP * self._factor), greater(PoP * self._factor, 100)) InvalidSkyMask5",
"InvalidSkyMask = InvalidSkyMask5 InvalidSkyMask = logical_and(InvalidSkyMask5, areaMask) if any(InvalidSkyMask): self.createGrid(\"TemporaryData\", \"InvalidSkyForPoP\", \"SCALAR\", InvalidSkyMask,",
"if self._SkyMin < 10: self._SkyMin = 10 elif self._SkyMin > 100: self._SkyMin =",
"is \"self\"???? ## \"Self\" refers to this Tool class instance. Don't worry much",
"grid # Fill in the arguments you want to use -- WeatherElement1, WeatherElement2...",
"\"multiply\", \"Sky Limit\"]), (\"For add, multiply (smaller factor), by how much ?\" ,",
"self._PoPLimit = 15.0 elif self._PoPLimit > 25.0: self._PoPLimit = 25.0 # Make sure",
"############################################################################# area = self.getEditArea(localFoecastArea) areaMask = self.encodeEditArea(area) if (self._operator == \"add\"): mainAddMask =",
"needed to support Wx:\" , 60, \"numeric\"), # (\"Enter minimum PoP for measurable",
", defaultValue, \"scale\", ## [minValue, maxValue], resolution), ## (\"Variable name6\" , \"\", \"model\"),",
"line self._slope = (self._SkyLimit - self._SkyMin) / (self._PoPLimit - 5.0) ## def preProcessTool(self,",
"# Called once at beginning of Tool ## # Cannot have WeatherElement or",
"= 10 elif self._SkyMin > 100: self._SkyMin = 100 # Make sure Sky",
"When calling your methods, use self._methodName omitting ## \"self\" as the first argument:",
"InvalidSkyMask4 = logical_or(InvalidSkyMask1, InvalidSkyMask2) InvalidSkyMask5 = logical_or(InvalidSkyMask3, InvalidSkyMask4) elif self._operator == \"multiply\": InvalidSkyMask1",
"if any(InvalidSkyMask): self.createGrid(\"TemporaryData\", \"InvalidSkyForPoP\", \"SCALAR\", InvalidSkyMask, GridTimeRange) self.setActiveElement(\"TemporaryData\", \"InvalidSkyForPoP\", \"SFC\", GridTimeRange, fitToData=1) #",
"thresholds for Sky cover # Get method self._operator = varDict[\"Sky vs PoP Relationship:\"]",
"InvalidSkyMask2) InvalidSkyMask5 = logical_or(InvalidSkyMask3, InvalidSkyMask4) elif self._operator == \"multiply\": InvalidSkyMask1 = logical_and(less(Sky, PoP",
"* self._factor), greater(PoP * self._factor, 100)) InvalidSkyMask5 = logical_or(InvalidSkyMask1, InvalidSkyMask2) else: lowSkyMask =",
"maxValue], resolution), ## (\"Variable name6\" , \"\", \"model\"), ## (\"Variable name7\" , \"\",",
"slope to use for this line self._slope = (self._SkyLimit - self._SkyMin) / (self._PoPLimit",
"of your tool ## and return a \"NoData\" error which can be checked",
"import * HideTool = 1 # You can screen the elements for which",
"is 10-100% if self._SkyMin < 10: self._SkyMin = 10 elif self._SkyMin > 100:",
"PoP * self._lofactor)) InvalidSkyMask2 = logical_and(mainAddMask, less_equal(PoP, self._breathingRoom)) InvalidSkyMask3 = logical_and(greater(PoP, self._breathingRoom), less(Sky,",
"any purpose. # # CheckSkyWithPoP # # Author: # ---------------------------------------------------------------------------- ## # This",
"the file. ## ToolType = \"numeric\" WeatherElementEdited = \"Sky\" from numpy import *",
"US Government. # # U.S. EXPORT CONTROLLED TECHNICAL DATA # This software product",
"## (\"Variable name7\" , \"\", \"D2D_model\"), ## (\"Label contents\" , \"\", \"label\"), ##",
"Determine new value ############################################################################# # # Configuration section # # Here is where",
"measurable precip is 15-25% if self._PoPLimit < 15.0: self._PoPLimit = 15.0 elif self._PoPLimit",
"self._SkyLimit = varDict[\"Enter Sky Limit: the minimum Sky cover needed to support Wx:\"]",
"WeatherElement or Grid arguments ## pass ## What is \"self\"???? ## \"Self\" refers",
"selected time range over which we are running the tool def preProcessTool(self, varDict):",
"highlight grids showing when and where there is not enough cloud \\ to",
"are running the tool def preProcessTool(self, varDict): # Called once at beginning of",
"(smaller factor), by how much ?\" , \"20\", \"numeric\"), (\"For Sky Limit, only",
"factor. The value for sky, of course, cannot # be greater than 100;",
"instance. Don't worry much about it. ## All you need to do is:",
"See the AWIPS II Master Rights File (\"Master Rights File.pdf\") for # further",
"Limit affected; it is raised to the Limit:\", \"\", \"label\"), (\"Enter Sky Limit:",
"= self.encodeEditArea(area) if (self._operator == \"add\"): mainAddMask = logical_and(greater_equal(PoP, 5), less(Sky, PoP +",
"Sky less than Limit affected; it is raised to the Limit:\", \"\", \"label\"),",
", \"add\", \"radio\", [\"add\", \"multiply\", \"Sky Limit\"]), (\"For add, multiply (smaller factor), by",
"your tool will appear by using # a ScreenList. For example: # #ScreenList",
"Called once at end of Tool ## # Cannot have WeatherElement or Grid",
"Sky Limit: the minimum Sky cover needed to support Wx:\"] ## 60 self._SkyMin",
"name1\" , defaultValue1, \"numeric\"), ## (\"Variable name2\" , \"default value2\", \"alphaNumeric\"), (\"Sky vs",
"to Contract DG133W-05-CQ-1067 with the US Government. # # U.S. EXPORT CONTROLLED TECHNICAL",
"the active edit area to your local forecast area # localFoecastArea = \"ISC_Send_Area\"",
"express or implied, as to its usefulness for # any purpose. # #",
"99.5)) InvalidSkyMask4 = logical_or(InvalidSkyMask1, InvalidSkyMask2) InvalidSkyMask5 = logical_or(InvalidSkyMask3, InvalidSkyMask4) elif self._operator == \"multiply\":",
"running the tool def preProcessTool(self, varDict): # Called once at beginning of Tool",
"## \"self\" as the first argument: ## x = self._myMethod(arg1, arg2) ## ##",
"affected; it is raised to the Limit:\", \"\", \"label\"), (\"Enter Sky Limit: the",
"for 5% PoP:\"] ## 30 # Make sure minimum PoP for measurable precip",
"self._SkyMin < 10: self._SkyMin = 10 elif self._SkyMin > 100: self._SkyMin = 100",
"self.getEditArea(localFoecastArea) areaMask = self.encodeEditArea(area) if (self._operator == \"add\"): mainAddMask = logical_and(greater_equal(PoP, 5), less(Sky,",
"## For example: ## if x > 1000: ## self.abort(\"x is too large\")",
"in the arguments you want to use -- WeatherElement1, WeatherElement2... def execute(self, Sky,",
"InvalidSkyMask5 = logical_or(InvalidSkyMask3, InvalidSkyMask4) elif self._operator == \"multiply\": InvalidSkyMask1 = logical_and(less(Sky, PoP *",
"self._PoPLimit = 15 self._SkyLimit = varDict[\"Enter Sky Limit: the minimum Sky cover needed",
"# See the AWIPS II Master Rights File (\"Master Rights File.pdf\") for #",
"self._myMethod(arg1, arg2) ## ## Error Handling ## Call self.abort(errorString) to stop execution of",
"\"radio\", [\"add\", \"multiply\", \"Sky Limit\"]), (\"For add, multiply (smaller factor), by how much",
"(\"For Sky Limit, only Sky less than Limit affected; it is raised to",
"] # Set up Class import SmartScript ## For available commands, see SmartScript",
"Sky is left alone if it is already large enough. # For Muultply:",
"(\"For add, multiply (smaller factor), by how much ?\" , \"20\", \"numeric\"), (\"For",
"= \"numeric\" WeatherElementEdited = \"Sky\" from numpy import * HideTool = 1 #",
"varDict): # Called once at beginning of Tool # Cannot have WeatherElement or",
"contains export-restricted data whose # export/transfer/disclosure is restricted by U.S. law. Dissemination #",
"is: ## -- Make sure to list \"self\" as the first argument of",
"\"self\" as the first argument: ## x = self._myMethod(arg1, arg2) ## ## Error",
"\"scale\", ## [minValue, maxValue], resolution), ## (\"Variable name6\" , \"\", \"model\"), ## (\"Variable",
"sure Sky cover for 5% PoP < minimum Sky cover for Wx if",
"Limit: # self._PoPLimit = varDict[\"Enter minimum PoP for measurable precip:\"] ## 15 self._PoPLimit",
"# Called once for each grid # Fill in the arguments you want",
"## ## Error Handling ## Call self.abort(errorString) to stop execution of your tool",
"too large\") ## ## Call self.noData(messageString) to stop execution of your tool ##",
"self._SkyLimit < 50: self._SkyLimit = 50 elif self._SkyLimit > 100: self._SkyLimit = 100",
"Master Rights File (\"Master Rights File.pdf\") for # further licensing information. ## #",
"# Author: # ---------------------------------------------------------------------------- ## # This is an absolute override file, indicating",
"will completely replace a lower priority version of the file. ## ToolType =",
"use -- WeatherElement1, WeatherElement2... def execute(self, Sky, PoP, GridTimeRange, varDict): \"Creates highlight grids",
"or modified by Raytheon Company, # pursuant to Contract DG133W-05-CQ-1067 with the US",
"> 1000: ## self.abort(\"x is too large\") ## ## Call self.noData(messageString) to stop",
"and with no warranty, express or implied, as to its usefulness for #",
"Omaha, NE 68106 # 402.291.0100 # # See the AWIPS II Master Rights",
"InvalidSkyMask2 = logical_and(mainAddMask, less_equal(PoP, self._breathingRoom)) InvalidSkyMask3 = logical_and(greater(PoP, self._breathingRoom), less(Sky, 99.5)) InvalidSkyMask4 =",
"## # This software was developed and / or modified by Raytheon Company,",
"# ---------------------------------------------------------------------------- ## # This is an absolute override file, indicating that a",
"(SmartScript.SmartScript): def __init__(self, dbss): SmartScript.SmartScript.__init__(self, dbss) # Required Method: Execute # Called once",
"can screen the elements for which your tool will appear by using #",
"\"default value2\"], \"check\", ## [\"value1\", \"value2\", \"value3\"]), ## (\"Variable name4\" , \"default value4\",",
"variables to be solicited from the user: VariableList = [ ## (\"Variable name1\"",
"class Tool (SmartScript.SmartScript): def __init__(self, dbss): SmartScript.SmartScript.__init__(self, dbss) # Required Method: Execute #",
"how much ?\"] # For Add: self._lofactor = float(self._factor + 5) / 5.",
"self._factor, 100)) InvalidSkyMask5 = logical_or(InvalidSkyMask1, InvalidSkyMask2) else: lowSkyMask = less(Sky, self._SkyLimit) InvalidSkyMask1 =",
"## For available commands, see SmartScript class Tool (SmartScript.SmartScript): def __init__(self, dbss): SmartScript.SmartScript.__init__(self,",
"Make sure Sky cover for 5% PoP < minimum Sky cover for Wx",
"see SmartScript class Tool (SmartScript.SmartScript): def __init__(self, dbss): SmartScript.SmartScript.__init__(self, dbss) # Required Method:",
"* self._factor, 100)) InvalidSkyMask2 = logical_and(less(Sky, PoP * self._factor), greater(PoP * self._factor, 100))",
"amount # (add), or by a factor. The value for sky, of course,",
"if it is already large enough. # For Muultply: self._factor = varDict[\"For add,",
"PoP + self._factor)) InvalidSkyMask1 = logical_and(less(PoP, 5), less_equal(Sky, PoP * self._lofactor)) InvalidSkyMask2 =",
"## self.abort(\"x is too large\") ## ## Call self.noData(messageString) to stop execution of",
"value4\", \"radio\", ## [\"value1\", \"value2\", \"value3\"]), ## (\"Variable name5\" , defaultValue, \"scale\", ##",
"methods, use self._methodName omitting ## \"self\" as the first argument: ## x =",
"when and where there is not enough cloud \\ to support the corrsponding",
"with the US Government. # # U.S. EXPORT CONTROLLED TECHNICAL DATA # This",
"software product contains export-restricted data whose # export/transfer/disclosure is restricted by U.S. law.",
"self.encodeEditArea(area) if (self._operator == \"add\"): mainAddMask = logical_and(greater_equal(PoP, 5), less(Sky, PoP + self._factor))",
"Limit: the minimum Sky cover needed to support Wx:\" , 60, \"numeric\"), #",
"# further licensing information. ## # ---------------------------------------------------------------------------- # This software is in the",
"# # Author: # ---------------------------------------------------------------------------- ## # This is an absolute override file,",
"calling your methods, use self._methodName omitting ## \"self\" as the first argument: ##",
"less(Sky, PoP + self._factor)) InvalidSkyMask1 = logical_and(less(PoP, 5), less_equal(Sky, PoP * self._lofactor)) InvalidSkyMask2",
"much ?\" , \"20\", \"numeric\"), (\"For Sky Limit, only Sky less than Limit",
"# of the file will completely replace a lower priority version of the",
"active edit area to your local forecast area # localFoecastArea = \"ISC_Send_Area\" #",
"arg2) ## ## Error Handling ## Call self.abort(errorString) to stop execution of your",
"export/transfer/disclosure is restricted by U.S. law. Dissemination # to non-U.S. persons whether in",
"# Get thresholds for Sky cover # Get method self._operator = varDict[\"Sky vs",
"# ToolTimeRange -- selected time range over which we are running the tool",
"5), less(Sky, PoP + self._factor)) InvalidSkyMask1 = logical_and(less(PoP, 5), less_equal(Sky, PoP * self._lofactor))",
"# This software was developed and / or modified by Raytheon Company, #",
"= (self._SkyLimit - self._SkyMin) / (self._PoPLimit - 5.0) ## def preProcessTool(self, varDict): ##",
"greater(PoP * self._factor, 100)) InvalidSkyMask5 = logical_or(InvalidSkyMask1, InvalidSkyMask2) else: lowSkyMask = less(Sky, self._SkyLimit)",
"- PoP) * self._slope)) InvalidSkyMask5 = logical_or(InvalidSkyMask1, InvalidSkyMask2) # InvalidSkyMask = InvalidSkyMask5 InvalidSkyMask",
"Wx:\"] ## 60 self._SkyMin = varDict[\"Enter Sky cover for 5% PoP:\"] ## 30",
"time range over which we are running the tool def preProcessTool(self, varDict): #",
"your tool and ## display a message to the user. ## For example:",
"raised to the Limit:\", \"\", \"label\"), (\"Enter Sky Limit: the minimum Sky cover",
"much, or by what \\ factor, the cloud should be greater.\" ## #",
"enough. # For Muultply: self._factor = varDict[\"For add, multiply (smaller factor), by how",
"which we are running the tool def preProcessTool(self, varDict): # Called once at",
"Muultply: self._factor = varDict[\"For add, multiply (smaller factor), by how much ?\"] #",
"= 100 # Make sure Sky cover for 5% PoP is 10-100% if",
"## # These methods can have the additional argument: ## # ToolTimeRange --",
"# Make sure Sky cover for 5% PoP < minimum Sky cover for",
"5% PoP:\"] ## 30 # Make sure minimum PoP for measurable precip is",
"CheckSkyWithPoP # # Author: # ---------------------------------------------------------------------------- ## # This is an absolute override",
"100: self._SkyMin = 100 # Make sure Sky cover for 5% PoP <",
"< minimum Sky cover for Wx if self._SkyMin > self._SkyLimit - 15: self._SkyMin",
"Set up Class import SmartScript ## For available commands, see SmartScript class Tool",
"## -- When calling your methods, use self._methodName omitting ## \"self\" as the",
"The value for sky, of course, cannot # be greater than 100; this",
"AWIPS II Master Rights File (\"Master Rights File.pdf\") for # further licensing information.",
"\"value3\"]), ## (\"Variable name4\" , \"default value4\", \"radio\", ## [\"value1\", \"value2\", \"value3\"]), ##",
"self._SkyMin > self._SkyLimit - 15: self._SkyMin = self._SkyLimit - 15 # Compute slope",
"is in the public domain, furnished \"as is\", without technical # support, and",
", defaultValue1, \"numeric\"), ## (\"Variable name2\" , \"default value2\", \"alphaNumeric\"), (\"Sky vs PoP",
"* self._factor), less_equal(PoP * self._factor, 100)) InvalidSkyMask2 = logical_and(less(Sky, PoP * self._factor), greater(PoP",
"This software was developed and / or modified by Raytheon Company, # pursuant",
"?\" , \"20\", \"numeric\"), (\"For Sky Limit, only Sky less than Limit affected;",
"= 100 # Make sure Sky cover for 5% PoP < minimum Sky",
"# # U.S. EXPORT CONTROLLED TECHNICAL DATA # This software product contains export-restricted",
"if x > 1000: ## self.abort(\"x is too large\") ## ## Call self.noData(messageString)",
"use for this line self._slope = (self._SkyLimit - self._SkyMin) / (self._PoPLimit - 5.0)",
"as the first argument of ## method Definitions: ## def _myMethod(self, arg1, arg2)",
"self._SkyMin = varDict[\"Enter Sky cover for 5% PoP:\"] ## 30 # Make sure",
"PoP Relationship:\" , \"add\", \"radio\", [\"add\", \"multiply\", \"Sky Limit\"]), (\"For add, multiply (smaller",
"InvalidSkyMask5 = logical_or(InvalidSkyMask1, InvalidSkyMask2) # InvalidSkyMask = InvalidSkyMask5 InvalidSkyMask = logical_and(InvalidSkyMask5, areaMask) if",
"the varDict (see VariableList below) ## var1 = varDict[\"Variable name1\"] ## var2 =",
"## [minValue, maxValue], resolution), ## (\"Variable name6\" , \"\", \"model\"), ## (\"Variable name7\"",
"screen the elements for which your tool will appear by using # a",
"< 10: self._SkyMin = 10 elif self._SkyMin > 100: self._SkyMin = 100 #",
"= logical_or(InvalidSkyMask1, InvalidSkyMask2) else: lowSkyMask = less(Sky, self._SkyLimit) InvalidSkyMask1 = logical_and(lowSkyMask, greater_equal(PoP, self._PoPLimit))",
"information. ## # ---------------------------------------------------------------------------- # This software is in the public domain, furnished",
"beginning of Tool ## # Cannot have WeatherElement or Grid arguments ## pass",
"requires # an export license or other authorization. # # Contractor Name: <NAME>",
"logical_and(mainAddMask, less_equal(PoP, self._breathingRoom)) InvalidSkyMask3 = logical_and(greater(PoP, self._breathingRoom), less(Sky, 99.5)) InvalidSkyMask4 = logical_or(InvalidSkyMask1, InvalidSkyMask2)",
"## (\"\", dialogHeight, \"scrollbar\"), ] # Set up Class import SmartScript ## For",
"resolution), ## (\"Variable name6\" , \"\", \"model\"), ## (\"Variable name7\" , \"\", \"D2D_model\"),",
"# For Add or Multiply: # Idea is Sky is greater than PoP,",
"or Multiply: # Idea is Sky is greater than PoP, either by a",
"## pass ## What is \"self\"???? ## \"Self\" refers to this Tool class",
"refers to this Tool class instance. Don't worry much about it. ## All",
"## Error Handling ## Call self.abort(errorString) to stop execution of your tool and",
"InvalidSkyMask2 = logical_and(lowSkyMask, less_equal(Sky, self._SkyLimit - (self._PoPLimit - PoP) * self._slope)) InvalidSkyMask5 =",
"Don't worry much about it. ## All you need to do is: ##",
"showing when and where there is not enough cloud \\ to support the",
"- (self._PoPLimit - PoP) * self._slope)) InvalidSkyMask5 = logical_or(InvalidSkyMask1, InvalidSkyMask2) # InvalidSkyMask =",
"Cannot have WeatherElement or Grid arguments # Get thresholds for Sky cover #",
"varDict[\"Variable name1\"] ## var2 = varDict[\"Variable name2\"] # Determine new value ############################################################################# #",
"> 100: self._SkyMin = 100 # Make sure Sky cover for 5% PoP",
"(self._PoPLimit - PoP) * self._slope)) InvalidSkyMask5 = logical_or(InvalidSkyMask1, InvalidSkyMask2) # InvalidSkyMask = InvalidSkyMask5",
"logical_or(InvalidSkyMask1, InvalidSkyMask2) # InvalidSkyMask = InvalidSkyMask5 InvalidSkyMask = logical_and(InvalidSkyMask5, areaMask) if any(InvalidSkyMask): self.createGrid(\"TemporaryData\",",
"if self._SkyMin > self._SkyLimit - 15: self._SkyMin = self._SkyLimit - 15 # Compute",
"in the United States or abroad requires # an export license or other",
"a ScreenList. For example: # #ScreenList = [\"T\",\"Td\"] #ScreenList = [\"SCALAR\",\"VECTOR\",\"WEATHER\",\"DISCRETE\"] ### If",
"logical_and(greater_equal(PoP, 5), less(Sky, PoP + self._factor)) InvalidSkyMask1 = logical_and(less(PoP, 5), less_equal(Sky, PoP *",
"greater than PoP, either by a fixed amount # (add), or by a",
"## # Called once at beginning of Tool ## # Cannot have WeatherElement",
"Company, # pursuant to Contract DG133W-05-CQ-1067 with the US Government. # # U.S.",
"30, \"numeric\"), ## (\"Variable name3\" , [\"default value1\", \"default value2\"], \"check\", ## [\"value1\",",
"\"add\", \"radio\", [\"add\", \"multiply\", \"Sky Limit\"]), (\"For add, multiply (smaller factor), by how",
"---------------------------------------------------------------------------- # This software is in the public domain, furnished \"as is\", without",
"self._PoPLimit = varDict[\"Enter minimum PoP for measurable precip:\"] ## 15 self._PoPLimit = 15",
"technical # support, and with no warranty, express or implied, as to its",
"\"self\"???? ## \"Self\" refers to this Tool class instance. Don't worry much about",
"# (add), or by a factor. The value for sky, of course, cannot",
"for measurable precip:\"] ## 15 self._PoPLimit = 15 self._SkyLimit = varDict[\"Enter Sky Limit:",
"a factor. The value for sky, of course, cannot # be greater than",
"is where to change the active edit area to your local forecast area",
"\"alphaNumeric\"), (\"Sky vs PoP Relationship:\" , \"add\", \"radio\", [\"add\", \"multiply\", \"Sky Limit\"]), (\"For",
"indicating that a higher priority version # of the file will completely replace",
"corrsponding PoP. The user decides by how much, or by what \\ factor,",
"100 # Make sure Sky cover for 5% PoP is 10-100% if self._SkyMin",
", \"\", \"label\"), ## (\"\", dialogHeight, \"scrollbar\"), ] # Set up Class import",
"WeatherElement1, WeatherElement2... def execute(self, Sky, PoP, GridTimeRange, varDict): \"Creates highlight grids showing when",
"# For Muultply: self._factor = varDict[\"For add, multiply (smaller factor), by how much",
"Methods ## # These methods can have the additional argument: ## # ToolTimeRange",
"its usefulness for # any purpose. # # CheckSkyWithPoP # # Author: #",
"5% PoP:\" , 30, \"numeric\"), ## (\"Variable name3\" , [\"default value1\", \"default value2\"],",
"Called once at beginning of Tool ## # Cannot have WeatherElement or Grid",
"warranty, express or implied, as to its usefulness for # any purpose. #",
"your tool ## and return a \"NoData\" error which can be checked by",
"Government. # # U.S. EXPORT CONTROLLED TECHNICAL DATA # This software product contains",
"numpy import * HideTool = 1 # You can screen the elements for",
"Relationship:\" , \"add\", \"radio\", [\"add\", \"multiply\", \"Sky Limit\"]), (\"For add, multiply (smaller factor),",
"large enough. # For Muultply: self._factor = varDict[\"For add, multiply (smaller factor), by",
"Set up variables to be solicited from the user: VariableList = [ ##",
"tool def preProcessTool(self, varDict): # Called once at beginning of Tool # Cannot",
"WeatherElement or Grid arguments ## pass ## def postProcessTool(self, varDict): ## # Called",
"from the varDict (see VariableList below) ## var1 = varDict[\"Variable name1\"] ## var2",
"else: lowSkyMask = less(Sky, self._SkyLimit) InvalidSkyMask1 = logical_and(lowSkyMask, greater_equal(PoP, self._PoPLimit)) InvalidSkyMask2 = logical_and(lowSkyMask,",
"preProcessTool(self, varDict): # Called once at beginning of Tool # Cannot have WeatherElement",
"self._operator == \"multiply\": InvalidSkyMask1 = logical_and(less(Sky, PoP * self._factor), less_equal(PoP * self._factor, 100))",
"= \"Sky\" from numpy import * HideTool = 1 # You can screen",
"= logical_and(less(Sky, PoP * self._factor), greater(PoP * self._factor, 100)) InvalidSkyMask5 = logical_or(InvalidSkyMask1, InvalidSkyMask2)",
"of Tool ## # Cannot have WeatherElement or Grid arguments ## pass ##",
"an export license or other authorization. # # Contractor Name: <NAME> # Contractor",
"\"ISC_Send_Area\" # # End Configuration section # ############################################################################# area = self.getEditArea(localFoecastArea) areaMask =",
"have WeatherElement or Grid arguments ## pass ## What is \"self\"???? ## \"Self\"",
"the Limit:\", \"\", \"label\"), (\"Enter Sky Limit: the minimum Sky cover needed to",
"# InvalidSkyMask = InvalidSkyMask5 InvalidSkyMask = logical_and(InvalidSkyMask5, areaMask) if any(InvalidSkyMask): self.createGrid(\"TemporaryData\", \"InvalidSkyForPoP\", \"SCALAR\",",
"name4\" , \"default value4\", \"radio\", ## [\"value1\", \"value2\", \"value3\"]), ## (\"Variable name5\" ,",
"self._lofactor)) InvalidSkyMask2 = logical_and(mainAddMask, less_equal(PoP, self._breathingRoom)) InvalidSkyMask3 = logical_and(greater(PoP, self._breathingRoom), less(Sky, 99.5)) InvalidSkyMask4",
"Relationship:\"] # For Add or Multiply: # Idea is Sky is greater than",
"For example: # #ScreenList = [\"T\",\"Td\"] #ScreenList = [\"SCALAR\",\"VECTOR\",\"WEATHER\",\"DISCRETE\"] ### If desired, Set",
"much ?\"] # For Add: self._lofactor = float(self._factor + 5) / 5. self._breathingRoom",
"< 15.0: self._PoPLimit = 15.0 elif self._PoPLimit > 25.0: self._PoPLimit = 25.0 #",
"purpose. # # CheckSkyWithPoP # # Author: # ---------------------------------------------------------------------------- ## # This is",
"argument: ## # ToolTimeRange -- selected time range over which we are running",
"pass ## What is \"self\"???? ## \"Self\" refers to this Tool class instance.",
"user. ## For example: ## if x > 1000: ## self.abort(\"x is too",
"minimum Sky cover needed to support Wx:\" , 60, \"numeric\"), # (\"Enter minimum",
"PoP for measurable precip:\"] ## 15 self._PoPLimit = 15 self._SkyLimit = varDict[\"Enter Sky",
"PoP) * self._slope)) InvalidSkyMask5 = logical_or(InvalidSkyMask1, InvalidSkyMask2) # InvalidSkyMask = InvalidSkyMask5 InvalidSkyMask =",
"\"Self\" refers to this Tool class instance. Don't worry much about it. ##",
"(\"\", dialogHeight, \"scrollbar\"), ] # Set up Class import SmartScript ## For available",
"\"add\"): mainAddMask = logical_and(greater_equal(PoP, 5), less(Sky, PoP + self._factor)) InvalidSkyMask1 = logical_and(less(PoP, 5),",
"# ---------------------------------------------------------------------------- # This software is in the public domain, furnished \"as is\",",
"Sky Limit: # self._PoPLimit = varDict[\"Enter minimum PoP for measurable precip:\"] ## 15",
"Sky cover needed to support Wx:\" , 60, \"numeric\"), # (\"Enter minimum PoP",
"= 25.0 # Make sure minimum Sky cover for Wx is 50-100% if",
"software is in the public domain, furnished \"as is\", without technical # support,",
"of your tool and ## display a message to the user. ## For",
"== \"add\"): mainAddMask = logical_and(greater_equal(PoP, 5), less(Sky, PoP + self._factor)) InvalidSkyMask1 = logical_and(less(PoP,",
"logical_and(less(Sky, PoP * self._factor), greater(PoP * self._factor, 100)) InvalidSkyMask5 = logical_or(InvalidSkyMask1, InvalidSkyMask2) else:",
"to use for this line self._slope = (self._SkyLimit - self._SkyMin) / (self._PoPLimit -",
"# U.S. EXPORT CONTROLLED TECHNICAL DATA # This software product contains export-restricted data",
"\\ to support the corrsponding PoP. The user decides by how much, or",
"once at beginning of Tool # Cannot have WeatherElement or Grid arguments #",
"modified by Raytheon Company, # pursuant to Contract DG133W-05-CQ-1067 with the US Government.",
"The user decides by how much, or by what \\ factor, the cloud",
"* self._lofactor)) InvalidSkyMask2 = logical_and(mainAddMask, less_equal(PoP, self._breathingRoom)) InvalidSkyMask3 = logical_and(greater(PoP, self._breathingRoom), less(Sky, 99.5))",
"to be solicited from the user: VariableList = [ ## (\"Variable name1\" ,",
"= [\"T\",\"Td\"] #ScreenList = [\"SCALAR\",\"VECTOR\",\"WEATHER\",\"DISCRETE\"] ### If desired, Set up variables to be",
"measurable precip:\", 15, \"numeric\"), (\"Enter Sky cover for 5% PoP:\" , 30, \"numeric\"),",
"= logical_or(InvalidSkyMask1, InvalidSkyMask2) # InvalidSkyMask = InvalidSkyMask5 InvalidSkyMask = logical_and(InvalidSkyMask5, areaMask) if any(InvalidSkyMask):",
"arg1, arg2) ## -- When calling your methods, use self._methodName omitting ## \"self\"",
"402.291.0100 # # See the AWIPS II Master Rights File (\"Master Rights File.pdf\")",
"no warranty, express or implied, as to its usefulness for # any purpose.",
"## ToolType = \"numeric\" WeatherElementEdited = \"Sky\" from numpy import * HideTool =",
"Sky, PoP, GridTimeRange, varDict): \"Creates highlight grids showing when and where there is",
"These methods can have the additional argument: ## # ToolTimeRange -- selected time",
"x = self._myMethod(arg1, arg2) ## ## Error Handling ## Call self.abort(errorString) to stop",
"PoP:\"] ## 30 # Make sure minimum PoP for measurable precip is 15-25%",
"export-restricted data whose # export/transfer/disclosure is restricted by U.S. law. Dissemination # to",
"example: ## if x > 1000: ## self.abort(\"x is too large\") ## ##",
"up Variables from the varDict (see VariableList below) ## var1 = varDict[\"Variable name1\"]",
"section # ############################################################################# area = self.getEditArea(localFoecastArea) areaMask = self.encodeEditArea(area) if (self._operator == \"add\"):",
"II Master Rights File (\"Master Rights File.pdf\") for # further licensing information. ##",
"the AWIPS II Master Rights File (\"Master Rights File.pdf\") for # further licensing",
"lowSkyMask = less(Sky, self._SkyLimit) InvalidSkyMask1 = logical_and(lowSkyMask, greater_equal(PoP, self._PoPLimit)) InvalidSkyMask2 = logical_and(lowSkyMask, less_equal(Sky,",
"## and return a \"NoData\" error which can be checked by a Procedure.",
"\\ factor, the cloud should be greater.\" ## # Set up Variables from",
"= logical_and(less(PoP, 5), less_equal(Sky, PoP * self._lofactor)) InvalidSkyMask2 = logical_and(mainAddMask, less_equal(PoP, self._breathingRoom)) InvalidSkyMask3",
"less_equal(Sky, PoP * self._lofactor)) InvalidSkyMask2 = logical_and(mainAddMask, less_equal(PoP, self._breathingRoom)) InvalidSkyMask3 = logical_and(greater(PoP, self._breathingRoom),",
"PoP * self._factor), greater(PoP * self._factor, 100)) InvalidSkyMask5 = logical_or(InvalidSkyMask1, InvalidSkyMask2) else: lowSkyMask",
"(\"Master Rights File.pdf\") for # further licensing information. ## # ---------------------------------------------------------------------------- # This",
"less_equal(Sky, self._SkyLimit - (self._PoPLimit - PoP) * self._slope)) InvalidSkyMask5 = logical_or(InvalidSkyMask1, InvalidSkyMask2) #",
"\"multiply\": InvalidSkyMask1 = logical_and(less(Sky, PoP * self._factor), less_equal(PoP * self._factor, 100)) InvalidSkyMask2 =",
"where to change the active edit area to your local forecast area #",
"change the active edit area to your local forecast area # localFoecastArea =",
"## All you need to do is: ## -- Make sure to list",
"varDict (see VariableList below) ## var1 = varDict[\"Variable name1\"] ## var2 = varDict[\"Variable",
"absolute override file, indicating that a higher priority version # of the file",
"or by what \\ factor, the cloud should be greater.\" ## # Set",
"sure minimum PoP for measurable precip is 15-25% if self._PoPLimit < 15.0: self._PoPLimit",
"this line self._slope = (self._SkyLimit - self._SkyMin) / (self._PoPLimit - 5.0) ## def",
"Grid arguments # Get thresholds for Sky cover # Get method self._operator =",
"\"Sky Limit\"]), (\"For add, multiply (smaller factor), by how much ?\" , \"20\",",
"PoP. The user decides by how much, or by what \\ factor, the",
"minimum PoP for measurable precip:\"] ## 15 self._PoPLimit = 15 self._SkyLimit = varDict[\"Enter",
"course, cannot # be greater than 100; this is where 'breathingRoom' comes in",
"DATA # This software product contains export-restricted data whose # export/transfer/disclosure is restricted",
"## -- Make sure to list \"self\" as the first argument of ##",
"\"self\" as the first argument of ## method Definitions: ## def _myMethod(self, arg1,",
"\"label\"), ## (\"\", dialogHeight, \"scrollbar\"), ] # Set up Class import SmartScript ##",
"DG133W-05-CQ-1067 with the US Government. # # U.S. EXPORT CONTROLLED TECHNICAL DATA #",
"Pine Street, Suite 340 # Mail Stop B8 # Omaha, NE 68106 #",
"name2\"] # Determine new value ############################################################################# # # Configuration section # # Here",
"\"numeric\"), # (\"Enter minimum PoP for measurable precip:\", 15, \"numeric\"), (\"Enter Sky cover",
"## \"Self\" refers to this Tool class instance. Don't worry much about it.",
"File.pdf\") for # further licensing information. ## # ---------------------------------------------------------------------------- # This software is",
"# Called once at beginning of Tool # Cannot have WeatherElement or Grid",
"varDict[\"Variable name2\"] # Determine new value ############################################################################# # # Configuration section # #",
"at beginning of Tool ## # Cannot have WeatherElement or Grid arguments ##",
", \"\", \"model\"), ## (\"Variable name7\" , \"\", \"D2D_model\"), ## (\"Label contents\" ,",
"# Set up Variables from the varDict (see VariableList below) ## var1 =",
"# Optional Methods ## # These methods can have the additional argument: ##",
"If desired, Set up variables to be solicited from the user: VariableList =",
"self._methodName omitting ## \"self\" as the first argument: ## x = self._myMethod(arg1, arg2)",
"## # ---------------------------------------------------------------------------- # This software is in the public domain, furnished \"as",
"= InvalidSkyMask5 InvalidSkyMask = logical_and(InvalidSkyMask5, areaMask) if any(InvalidSkyMask): self.createGrid(\"TemporaryData\", \"InvalidSkyForPoP\", \"SCALAR\", InvalidSkyMask, GridTimeRange)",
"a message to the user. ## For example: ## if x > 1000:",
"= [\"SCALAR\",\"VECTOR\",\"WEATHER\",\"DISCRETE\"] ### If desired, Set up variables to be solicited from the",
"- 15: self._SkyMin = self._SkyLimit - 15 # Compute slope to use for",
"Idea is Sky is greater than PoP, either by a fixed amount #",
"value ############################################################################# # # Configuration section # # Here is where to change",
"developed and / or modified by Raytheon Company, # pursuant to Contract DG133W-05-CQ-1067",
"# Determine new value ############################################################################# # # Configuration section # # Here is",
"the additional argument: ## # ToolTimeRange -- selected time range over which we",
"logical_and(greater(PoP, self._breathingRoom), less(Sky, 99.5)) InvalidSkyMask4 = logical_or(InvalidSkyMask1, InvalidSkyMask2) InvalidSkyMask5 = logical_or(InvalidSkyMask3, InvalidSkyMask4) elif",
"InvalidSkyMask2) else: lowSkyMask = less(Sky, self._SkyLimit) InvalidSkyMask1 = logical_and(lowSkyMask, greater_equal(PoP, self._PoPLimit)) InvalidSkyMask2 =",
"at end of Tool ## # Cannot have WeatherElement or Grid arguments ##",
"than Limit affected; it is raised to the Limit:\", \"\", \"label\"), (\"Enter Sky",
"once for each grid # Fill in the arguments you want to use",
"varDict): \"Creates highlight grids showing when and where there is not enough cloud",
"greater.\" ## # Set up Variables from the varDict (see VariableList below) ##",
"where 'breathingRoom' comes in # Sky is left alone if it is already",
"cover for 5% PoP:\"] ## 30 # Make sure minimum PoP for measurable",
"name1\"] ## var2 = varDict[\"Variable name2\"] # Determine new value ############################################################################# # #",
"self._breathingRoom), less(Sky, 99.5)) InvalidSkyMask4 = logical_or(InvalidSkyMask1, InvalidSkyMask2) InvalidSkyMask5 = logical_or(InvalidSkyMask3, InvalidSkyMask4) elif self._operator",
"cloud should be greater.\" ## # Set up Variables from the varDict (see",
"## Call self.abort(errorString) to stop execution of your tool and ## display a",
"# Make sure minimum Sky cover for Wx is 50-100% if self._SkyLimit <",
"GridTimeRange) self.setActiveElement(\"TemporaryData\", \"InvalidSkyForPoP\", \"SFC\", GridTimeRange, fitToData=1) # Return the new value # return",
"# #ScreenList = [\"T\",\"Td\"] #ScreenList = [\"SCALAR\",\"VECTOR\",\"WEATHER\",\"DISCRETE\"] ### If desired, Set up variables",
"if self._SkyLimit < 50: self._SkyLimit = 50 elif self._SkyLimit > 100: self._SkyLimit =",
"self.createGrid(\"TemporaryData\", \"InvalidSkyForPoP\", \"SCALAR\", InvalidSkyMask, GridTimeRange) self.setActiveElement(\"TemporaryData\", \"InvalidSkyForPoP\", \"SFC\", GridTimeRange, fitToData=1) # Return the",
"by how much, or by what \\ factor, the cloud should be greater.\"",
"\"default value4\", \"radio\", ## [\"value1\", \"value2\", \"value3\"]), ## (\"Variable name5\" , defaultValue, \"scale\",",
"United States or abroad requires # an export license or other authorization. #",
"'breathingRoom' comes in # Sky is left alone if it is already large",
"support the corrsponding PoP. The user decides by how much, or by what",
"pursuant to Contract DG133W-05-CQ-1067 with the US Government. # # U.S. EXPORT CONTROLLED",
"# be greater than 100; this is where 'breathingRoom' comes in # Sky",
"= logical_or(InvalidSkyMask1, InvalidSkyMask2) InvalidSkyMask5 = logical_or(InvalidSkyMask3, InvalidSkyMask4) elif self._operator == \"multiply\": InvalidSkyMask1 =",
"## What is \"self\"???? ## \"Self\" refers to this Tool class instance. Don't",
"at beginning of Tool # Cannot have WeatherElement or Grid arguments # Get",
"how much, or by what \\ factor, the cloud should be greater.\" ##"
] |
[
"License is distributed on an \"AS IS\" BASIS, WITHOUT # WARRANTIES OR CONDITIONS",
"writing, software # distributed under the License is distributed on an \"AS IS\"",
"Unless required by applicable law or agreed to in writing, software # distributed",
"See the # License for the specific language governing permissions and limitations #",
"\"ProcNoExecute\", \"ProcTurbo\", \"ProcVirtualization\", \"SecureBootStatus\", \"Sriov\", \"ThermalConfig\", \"ThermalShutdown\", \"TpmState\", \"TpmType\", \"UefiOptimizedBoot\" ] SUPPORTED_REDFISH_BIOS_PROPERTIES =",
"\"DynamicPowerCapping\", \"DynamicPowerResponse\", \"IntelligentProvisioning\", \"IntelPerfMonitoring\", \"IntelProcVtd\", \"IntelQpiFreq\", \"IntelTxt\", \"PowerProfile\", \"PowerRegulator\", \"ProcAes\", \"ProcCoreDisable\", \"ProcHyperthreading\", \"ProcNoExecute\",",
"LP # All Rights Reserved. # # Licensed under the Apache License, Version",
"for the specific language governing permissions and limitations # under the License. #",
"\"License\"); you may # not use this file except in compliance with the",
"Hewlett Packard Enterprise Development LP # All Rights Reserved. # # Licensed under",
"Apache License, Version 2.0 (the \"License\"); you may # not use this file",
"the License. You may obtain # a copy of the License at #",
"law or agreed to in writing, software # distributed under the License is",
"Reserved. # # Licensed under the Apache License, Version 2.0 (the \"License\"); you",
"may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #",
"the Apache License, Version 2.0 (the \"License\"); you may # not use this",
"License. # SUPPORTED_BOOT_MODE constants SUPPORTED_BOOT_MODE_LEGACY_BIOS_ONLY = 'legacy bios only' SUPPORTED_BOOT_MODE_UEFI_ONLY = 'uefi only'",
"SUPPORTED_BIOS_PROPERTIES = [ \"AdvancedMemProtection\", \"AutoPowerOn\", \"BootMode\", \"BootOrderPolicy\", \"CollabPowerControl\", \"DynamicPowerCapping\", \"DynamicPowerResponse\", \"IntelligentProvisioning\", \"IntelPerfMonitoring\", \"IntelProcVtd\",",
"express or implied. See the # License for the specific language governing permissions",
"an \"AS IS\" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either",
"# a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless",
"CONDITIONS OF ANY KIND, either express or implied. See the # License for",
"not use this file except in compliance with the License. You may obtain",
"and limitations # under the License. # SUPPORTED_BOOT_MODE constants SUPPORTED_BOOT_MODE_LEGACY_BIOS_ONLY = 'legacy bios",
"\"ProcCoreDisable\", \"ProcHyperthreading\", \"ProcNoExecute\", \"ProcTurbo\", \"ProcVirtualization\", \"SecureBootStatus\", \"Sriov\", \"ThermalConfig\", \"ThermalShutdown\", \"TpmState\", \"TpmType\", \"UefiOptimizedBoot\" ]",
"bios only' SUPPORTED_BOOT_MODE_UEFI_ONLY = 'uefi only' SUPPORTED_BOOT_MODE_LEGACY_BIOS_AND_UEFI = 'legacy bios and uefi' SUPPORTED_BIOS_PROPERTIES",
"governing permissions and limitations # under the License. # SUPPORTED_BOOT_MODE constants SUPPORTED_BOOT_MODE_LEGACY_BIOS_ONLY =",
"of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable",
"with the License. You may obtain # a copy of the License at",
"Licensed under the Apache License, Version 2.0 (the \"License\"); you may # not",
"= 'legacy bios only' SUPPORTED_BOOT_MODE_UEFI_ONLY = 'uefi only' SUPPORTED_BOOT_MODE_LEGACY_BIOS_AND_UEFI = 'legacy bios and",
"and uefi' SUPPORTED_BIOS_PROPERTIES = [ \"AdvancedMemProtection\", \"AutoPowerOn\", \"BootMode\", \"BootOrderPolicy\", \"CollabPowerControl\", \"DynamicPowerCapping\", \"DynamicPowerResponse\", \"IntelligentProvisioning\",",
"License for the specific language governing permissions and limitations # under the License.",
"bios and uefi' SUPPORTED_BIOS_PROPERTIES = [ \"AdvancedMemProtection\", \"AutoPowerOn\", \"BootMode\", \"BootOrderPolicy\", \"CollabPowerControl\", \"DynamicPowerCapping\", \"DynamicPowerResponse\",",
"only' SUPPORTED_BOOT_MODE_LEGACY_BIOS_AND_UEFI = 'legacy bios and uefi' SUPPORTED_BIOS_PROPERTIES = [ \"AdvancedMemProtection\", \"AutoPowerOn\", \"BootMode\",",
"2.0 (the \"License\"); you may # not use this file except in compliance",
"License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or",
"\"IntelQpiFreq\", \"IntelTxt\", \"PowerProfile\", \"PowerRegulator\", \"ProcAes\", \"ProcCoreDisable\", \"ProcHyperthreading\", \"ProcNoExecute\", \"ProcTurbo\", \"ProcVirtualization\", \"SecureBootStatus\", \"Sriov\", \"ThermalConfig\",",
"at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed",
"Copyright 2017 Hewlett Packard Enterprise Development LP # All Rights Reserved. # #",
"use this file except in compliance with the License. You may obtain #",
"# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT",
"WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the #",
"compliance with the License. You may obtain # a copy of the License",
"Packard Enterprise Development LP # All Rights Reserved. # # Licensed under the",
"License, Version 2.0 (the \"License\"); you may # not use this file except",
"BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.",
"is distributed on an \"AS IS\" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF",
"\"AdvancedMemProtection\", \"AutoPowerOn\", \"BootMode\", \"BootOrderPolicy\", \"CollabPowerControl\", \"DynamicPowerCapping\", \"DynamicPowerResponse\", \"IntelligentProvisioning\", \"IntelPerfMonitoring\", \"IntelProcVtd\", \"IntelQpiFreq\", \"IntelTxt\", \"PowerProfile\",",
"\"SecureBootStatus\", \"Sriov\", \"ThermalConfig\", \"ThermalShutdown\", \"TpmState\", \"TpmType\", \"UefiOptimizedBoot\" ] SUPPORTED_REDFISH_BIOS_PROPERTIES = SUPPORTED_BIOS_PROPERTIES + [",
"the License. # SUPPORTED_BOOT_MODE constants SUPPORTED_BOOT_MODE_LEGACY_BIOS_ONLY = 'legacy bios only' SUPPORTED_BOOT_MODE_UEFI_ONLY = 'uefi",
"IS\" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or",
"implied. See the # License for the specific language governing permissions and limitations",
"a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required",
"OF ANY KIND, either express or implied. See the # License for the",
"\"ProcVirtualization\", \"SecureBootStatus\", \"Sriov\", \"ThermalConfig\", \"ThermalShutdown\", \"TpmState\", \"TpmType\", \"UefiOptimizedBoot\" ] SUPPORTED_REDFISH_BIOS_PROPERTIES = SUPPORTED_BIOS_PROPERTIES +",
"\"ProcTurbo\", \"ProcVirtualization\", \"SecureBootStatus\", \"Sriov\", \"ThermalConfig\", \"ThermalShutdown\", \"TpmState\", \"TpmType\", \"UefiOptimizedBoot\" ] SUPPORTED_REDFISH_BIOS_PROPERTIES = SUPPORTED_BIOS_PROPERTIES",
"# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in",
"SUPPORTED_BOOT_MODE constants SUPPORTED_BOOT_MODE_LEGACY_BIOS_ONLY = 'legacy bios only' SUPPORTED_BOOT_MODE_UEFI_ONLY = 'uefi only' SUPPORTED_BOOT_MODE_LEGACY_BIOS_AND_UEFI =",
"constants SUPPORTED_BOOT_MODE_LEGACY_BIOS_ONLY = 'legacy bios only' SUPPORTED_BOOT_MODE_UEFI_ONLY = 'uefi only' SUPPORTED_BOOT_MODE_LEGACY_BIOS_AND_UEFI = 'legacy",
"\"ProcAes\", \"ProcCoreDisable\", \"ProcHyperthreading\", \"ProcNoExecute\", \"ProcTurbo\", \"ProcVirtualization\", \"SecureBootStatus\", \"Sriov\", \"ThermalConfig\", \"ThermalShutdown\", \"TpmState\", \"TpmType\", \"UefiOptimizedBoot\"",
"# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the",
"'legacy bios only' SUPPORTED_BOOT_MODE_UEFI_ONLY = 'uefi only' SUPPORTED_BOOT_MODE_LEGACY_BIOS_AND_UEFI = 'legacy bios and uefi'",
"you may # not use this file except in compliance with the License.",
"under the License. # SUPPORTED_BOOT_MODE constants SUPPORTED_BOOT_MODE_LEGACY_BIOS_ONLY = 'legacy bios only' SUPPORTED_BOOT_MODE_UEFI_ONLY =",
"agreed to in writing, software # distributed under the License is distributed on",
"\"IntelligentProvisioning\", \"IntelPerfMonitoring\", \"IntelProcVtd\", \"IntelQpiFreq\", \"IntelTxt\", \"PowerProfile\", \"PowerRegulator\", \"ProcAes\", \"ProcCoreDisable\", \"ProcHyperthreading\", \"ProcNoExecute\", \"ProcTurbo\", \"ProcVirtualization\",",
"\"ThermalConfig\", \"ThermalShutdown\", \"TpmState\", \"TpmType\", \"UefiOptimizedBoot\" ] SUPPORTED_REDFISH_BIOS_PROPERTIES = SUPPORTED_BIOS_PROPERTIES + [ \"WorkloadProfile\" ]",
"\"PowerRegulator\", \"ProcAes\", \"ProcCoreDisable\", \"ProcHyperthreading\", \"ProcNoExecute\", \"ProcTurbo\", \"ProcVirtualization\", \"SecureBootStatus\", \"Sriov\", \"ThermalConfig\", \"ThermalShutdown\", \"TpmState\", \"TpmType\",",
"# under the License. # SUPPORTED_BOOT_MODE constants SUPPORTED_BOOT_MODE_LEGACY_BIOS_ONLY = 'legacy bios only' SUPPORTED_BOOT_MODE_UEFI_ONLY",
"(the \"License\"); you may # not use this file except in compliance with",
"\"BootMode\", \"BootOrderPolicy\", \"CollabPowerControl\", \"DynamicPowerCapping\", \"DynamicPowerResponse\", \"IntelligentProvisioning\", \"IntelPerfMonitoring\", \"IntelProcVtd\", \"IntelQpiFreq\", \"IntelTxt\", \"PowerProfile\", \"PowerRegulator\", \"ProcAes\",",
"<reponame>anta-nok/proliantutils # Copyright 2017 Hewlett Packard Enterprise Development LP # All Rights Reserved.",
"may # not use this file except in compliance with the License. You",
"KIND, either express or implied. See the # License for the specific language",
"# Copyright 2017 Hewlett Packard Enterprise Development LP # All Rights Reserved. #",
"permissions and limitations # under the License. # SUPPORTED_BOOT_MODE constants SUPPORTED_BOOT_MODE_LEGACY_BIOS_ONLY = 'legacy",
"= 'uefi only' SUPPORTED_BOOT_MODE_LEGACY_BIOS_AND_UEFI = 'legacy bios and uefi' SUPPORTED_BIOS_PROPERTIES = [ \"AdvancedMemProtection\",",
"either express or implied. See the # License for the specific language governing",
"\"IntelProcVtd\", \"IntelQpiFreq\", \"IntelTxt\", \"PowerProfile\", \"PowerRegulator\", \"ProcAes\", \"ProcCoreDisable\", \"ProcHyperthreading\", \"ProcNoExecute\", \"ProcTurbo\", \"ProcVirtualization\", \"SecureBootStatus\", \"Sriov\",",
"[ \"AdvancedMemProtection\", \"AutoPowerOn\", \"BootMode\", \"BootOrderPolicy\", \"CollabPowerControl\", \"DynamicPowerCapping\", \"DynamicPowerResponse\", \"IntelligentProvisioning\", \"IntelPerfMonitoring\", \"IntelProcVtd\", \"IntelQpiFreq\", \"IntelTxt\",",
"# # Unless required by applicable law or agreed to in writing, software",
"uefi' SUPPORTED_BIOS_PROPERTIES = [ \"AdvancedMemProtection\", \"AutoPowerOn\", \"BootMode\", \"BootOrderPolicy\", \"CollabPowerControl\", \"DynamicPowerCapping\", \"DynamicPowerResponse\", \"IntelligentProvisioning\", \"IntelPerfMonitoring\",",
"only' SUPPORTED_BOOT_MODE_UEFI_ONLY = 'uefi only' SUPPORTED_BOOT_MODE_LEGACY_BIOS_AND_UEFI = 'legacy bios and uefi' SUPPORTED_BIOS_PROPERTIES =",
"file except in compliance with the License. You may obtain # a copy",
"this file except in compliance with the License. You may obtain # a",
"# Unless required by applicable law or agreed to in writing, software #",
"by applicable law or agreed to in writing, software # distributed under the",
"All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the",
"\"AS IS\" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express",
"SUPPORTED_BOOT_MODE_UEFI_ONLY = 'uefi only' SUPPORTED_BOOT_MODE_LEGACY_BIOS_AND_UEFI = 'legacy bios and uefi' SUPPORTED_BIOS_PROPERTIES = [",
"under the License is distributed on an \"AS IS\" BASIS, WITHOUT # WARRANTIES",
"copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by",
"or implied. See the # License for the specific language governing permissions and",
"software # distributed under the License is distributed on an \"AS IS\" BASIS,",
"\"IntelTxt\", \"PowerProfile\", \"PowerRegulator\", \"ProcAes\", \"ProcCoreDisable\", \"ProcHyperthreading\", \"ProcNoExecute\", \"ProcTurbo\", \"ProcVirtualization\", \"SecureBootStatus\", \"Sriov\", \"ThermalConfig\", \"ThermalShutdown\",",
"License. You may obtain # a copy of the License at # #",
"# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to",
"the License is distributed on an \"AS IS\" BASIS, WITHOUT # WARRANTIES OR",
"= 'legacy bios and uefi' SUPPORTED_BIOS_PROPERTIES = [ \"AdvancedMemProtection\", \"AutoPowerOn\", \"BootMode\", \"BootOrderPolicy\", \"CollabPowerControl\",",
"SUPPORTED_BOOT_MODE_LEGACY_BIOS_ONLY = 'legacy bios only' SUPPORTED_BOOT_MODE_UEFI_ONLY = 'uefi only' SUPPORTED_BOOT_MODE_LEGACY_BIOS_AND_UEFI = 'legacy bios",
"distributed on an \"AS IS\" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY",
"\"DynamicPowerResponse\", \"IntelligentProvisioning\", \"IntelPerfMonitoring\", \"IntelProcVtd\", \"IntelQpiFreq\", \"IntelTxt\", \"PowerProfile\", \"PowerRegulator\", \"ProcAes\", \"ProcCoreDisable\", \"ProcHyperthreading\", \"ProcNoExecute\", \"ProcTurbo\",",
"language governing permissions and limitations # under the License. # SUPPORTED_BOOT_MODE constants SUPPORTED_BOOT_MODE_LEGACY_BIOS_ONLY",
"SUPPORTED_BOOT_MODE_LEGACY_BIOS_AND_UEFI = 'legacy bios and uefi' SUPPORTED_BIOS_PROPERTIES = [ \"AdvancedMemProtection\", \"AutoPowerOn\", \"BootMode\", \"BootOrderPolicy\",",
"\"IntelPerfMonitoring\", \"IntelProcVtd\", \"IntelQpiFreq\", \"IntelTxt\", \"PowerProfile\", \"PowerRegulator\", \"ProcAes\", \"ProcCoreDisable\", \"ProcHyperthreading\", \"ProcNoExecute\", \"ProcTurbo\", \"ProcVirtualization\", \"SecureBootStatus\",",
"\"Sriov\", \"ThermalConfig\", \"ThermalShutdown\", \"TpmState\", \"TpmType\", \"UefiOptimizedBoot\" ] SUPPORTED_REDFISH_BIOS_PROPERTIES = SUPPORTED_BIOS_PROPERTIES + [ \"WorkloadProfile\"",
"# # Licensed under the Apache License, Version 2.0 (the \"License\"); you may",
"on an \"AS IS\" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND,",
"\"ProcHyperthreading\", \"ProcNoExecute\", \"ProcTurbo\", \"ProcVirtualization\", \"SecureBootStatus\", \"Sriov\", \"ThermalConfig\", \"ThermalShutdown\", \"TpmState\", \"TpmType\", \"UefiOptimizedBoot\" ] SUPPORTED_REDFISH_BIOS_PROPERTIES",
"ANY KIND, either express or implied. See the # License for the specific",
"the # License for the specific language governing permissions and limitations # under",
"except in compliance with the License. You may obtain # a copy of",
"\"CollabPowerControl\", \"DynamicPowerCapping\", \"DynamicPowerResponse\", \"IntelligentProvisioning\", \"IntelPerfMonitoring\", \"IntelProcVtd\", \"IntelQpiFreq\", \"IntelTxt\", \"PowerProfile\", \"PowerRegulator\", \"ProcAes\", \"ProcCoreDisable\", \"ProcHyperthreading\",",
"the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law",
"to in writing, software # distributed under the License is distributed on an",
"You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0",
"Development LP # All Rights Reserved. # # Licensed under the Apache License,",
"\"AutoPowerOn\", \"BootMode\", \"BootOrderPolicy\", \"CollabPowerControl\", \"DynamicPowerCapping\", \"DynamicPowerResponse\", \"IntelligentProvisioning\", \"IntelPerfMonitoring\", \"IntelProcVtd\", \"IntelQpiFreq\", \"IntelTxt\", \"PowerProfile\", \"PowerRegulator\",",
"Enterprise Development LP # All Rights Reserved. # # Licensed under the Apache",
"Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the \"License\");",
"required by applicable law or agreed to in writing, software # distributed under",
"applicable law or agreed to in writing, software # distributed under the License",
"the specific language governing permissions and limitations # under the License. # SUPPORTED_BOOT_MODE",
"'legacy bios and uefi' SUPPORTED_BIOS_PROPERTIES = [ \"AdvancedMemProtection\", \"AutoPowerOn\", \"BootMode\", \"BootOrderPolicy\", \"CollabPowerControl\", \"DynamicPowerCapping\",",
"distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT #",
"OR CONDITIONS OF ANY KIND, either express or implied. See the # License",
"'uefi only' SUPPORTED_BOOT_MODE_LEGACY_BIOS_AND_UEFI = 'legacy bios and uefi' SUPPORTED_BIOS_PROPERTIES = [ \"AdvancedMemProtection\", \"AutoPowerOn\",",
"obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #",
"# Licensed under the Apache License, Version 2.0 (the \"License\"); you may #",
"in compliance with the License. You may obtain # a copy of the",
"limitations # under the License. # SUPPORTED_BOOT_MODE constants SUPPORTED_BOOT_MODE_LEGACY_BIOS_ONLY = 'legacy bios only'",
"# not use this file except in compliance with the License. You may",
"# SUPPORTED_BOOT_MODE constants SUPPORTED_BOOT_MODE_LEGACY_BIOS_ONLY = 'legacy bios only' SUPPORTED_BOOT_MODE_UEFI_ONLY = 'uefi only' SUPPORTED_BOOT_MODE_LEGACY_BIOS_AND_UEFI",
"or agreed to in writing, software # distributed under the License is distributed",
"# License for the specific language governing permissions and limitations # under the",
"specific language governing permissions and limitations # under the License. # SUPPORTED_BOOT_MODE constants",
"= [ \"AdvancedMemProtection\", \"AutoPowerOn\", \"BootMode\", \"BootOrderPolicy\", \"CollabPowerControl\", \"DynamicPowerCapping\", \"DynamicPowerResponse\", \"IntelligentProvisioning\", \"IntelPerfMonitoring\", \"IntelProcVtd\", \"IntelQpiFreq\",",
"\"BootOrderPolicy\", \"CollabPowerControl\", \"DynamicPowerCapping\", \"DynamicPowerResponse\", \"IntelligentProvisioning\", \"IntelPerfMonitoring\", \"IntelProcVtd\", \"IntelQpiFreq\", \"IntelTxt\", \"PowerProfile\", \"PowerRegulator\", \"ProcAes\", \"ProcCoreDisable\",",
"# All Rights Reserved. # # Licensed under the Apache License, Version 2.0",
"under the Apache License, Version 2.0 (the \"License\"); you may # not use",
"WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See",
"\"PowerProfile\", \"PowerRegulator\", \"ProcAes\", \"ProcCoreDisable\", \"ProcHyperthreading\", \"ProcNoExecute\", \"ProcTurbo\", \"ProcVirtualization\", \"SecureBootStatus\", \"Sriov\", \"ThermalConfig\", \"ThermalShutdown\", \"TpmState\",",
"2017 Hewlett Packard Enterprise Development LP # All Rights Reserved. # # Licensed",
"http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing,",
"in writing, software # distributed under the License is distributed on an \"AS",
"Version 2.0 (the \"License\"); you may # not use this file except in"
] |
[
"of the keys print(key, KEYSIZE) key_index = 0 out = [] decrypted_strings[KEYSIZE] =",
"# finds the total number of 1's in the XOR's return sum([1 for",
"for x in blocks if len(x) > z]: out_arr.append(ord(i) ^ j) strings[i] =",
"if chr(x) in chars]), ord(i))) key += chr(max(answer)[1]) # prints out all of",
"return sum([1 for i in \"\".join(list_diff) if int(i) == 1]) L = []",
"chr(max(answer)[1]) # prints out all of the keys print(key, KEYSIZE) key_index = 0",
"^ j) strings[i] = \"\".join([chr(x) for x in out_arr]) answer.append((sum([1 for x in",
"+ 2) * KEYSIZE]) // KEYSIZE x+=1 t+=hamming_distance(data[x * KEYSIZE:(x + 1) *",
"x+=1 t+=hamming_distance(data[x * KEYSIZE:(x + 1) * KEYSIZE], data[(x + 1) * KEYSIZE:(x",
"if x[1] <= 2] decrypted_strings = {} for KEYSIZE in KEYSIZES: blocks =",
"in out_arr if chr(x) in chars]), ord(i))) key += chr(max(answer)[1]) # prints out",
"len(data), KEYSIZE)] key = \"\" for z in range(KEYSIZE): answer = [] strings",
"for KEYSIZE in KEYSIZES: answer.append((sum([1 for x in decrypted_strings[KEYSIZE] if x in chars]),",
"import itertools with open(\"6.txt\", \"r\") as the_file: b64data = the_file.read().replace(\"\\n\", \"\") data =",
"range(KEYSIZE): answer = [] strings = {} chars = string.ascii_letters + \" \"",
"out = [] decrypted_strings[KEYSIZE] = [chr(int(a) ^ ord(b)) for a, b in zip(data,",
"KEYSIZE:(x + 2) * KEYSIZE]) // KEYSIZE t//=x L.append((KEYSIZE, t)) KEYSIZES = [x[0]",
"= 1 t=hamming_distance(data[:KEYSIZE], data[KEYSIZE:(x+1)*KEYSIZE])//KEYSIZE x+=1 t+=hamming_distance(data[x*KEYSIZE:(x+1)*KEYSIZE], data[(x+1)*KEYSIZE:(x+2)*KEYSIZE])//KEYSIZE x+=1 t+=hamming_distance(data[x * KEYSIZE:(x + 1)",
"t)) KEYSIZES = [x[0] for x in L if x[1] <= 2] decrypted_strings",
"in range(KEYSIZE): answer = [] strings = {} chars = string.ascii_letters + \"",
"= [] for j in [x[z] for x in blocks if len(x) >",
"if len(x) > z]: out_arr.append(ord(i) ^ j) strings[i] = \"\".join([chr(x) for x in",
"[chr(int(a) ^ ord(b)) for a, b in zip(data, itertools.cycle(key))] chars = string.ascii_letters answer",
"in blocks if len(x) > z]: out_arr.append(ord(i) ^ j) strings[i] = \"\".join([chr(x) for",
"KEYSIZES = [x[0] for x in L if x[1] <= 2] decrypted_strings =",
"+ \" \" for i in chars: out_arr = [] for j in",
"for x in L if x[1] <= 2] decrypted_strings = {} for KEYSIZE",
"^ j) for i, j in zip(x, y)] # finds the total number",
"j in [x[z] for x in blocks if len(x) > z]: out_arr.append(ord(i) ^",
"the total number of 1's in the XOR's return sum([1 for i in",
"in zip(x, y)] # finds the total number of 1's in the XOR's",
"KEYSIZE]) // KEYSIZE x+=1 t+=hamming_distance(data[x * KEYSIZE:(x + 1) * KEYSIZE], data[(x +",
"for j in [x[z] for x in blocks if len(x) > z]: out_arr.append(ord(i)",
"hamming_distance(x, y): # finds the xor of the numbers in the two lists",
"* KEYSIZE:(x + 2) * KEYSIZE]) // KEYSIZE t//=x L.append((KEYSIZE, t)) KEYSIZES =",
"\"\") data = base64.standard_b64decode(b64data) print(data) def hamming_distance(x, y): # finds the xor of",
"1) * KEYSIZE], data[(x + 1) * KEYSIZE:(x + 2) * KEYSIZE]) //",
"the numbers in the two lists list_diff = [\"{0:b}\".format(i ^ j) for i,",
"[\"{0:b}\".format(i ^ j) for i, j in zip(x, y)] # finds the total",
"len(x) > z]: out_arr.append(ord(i) ^ j) strings[i] = \"\".join([chr(x) for x in out_arr])",
"the_file: b64data = the_file.read().replace(\"\\n\", \"\") data = base64.standard_b64decode(b64data) print(data) def hamming_distance(x, y): #",
"j in zip(x, y)] # finds the total number of 1's in the",
"string.ascii_letters + \" \" for i in chars: out_arr = [] for j",
"KEYSIZE t//=x L.append((KEYSIZE, t)) KEYSIZES = [x[0] for x in L if x[1]",
"1 t=hamming_distance(data[:KEYSIZE], data[KEYSIZE:(x+1)*KEYSIZE])//KEYSIZE x+=1 t+=hamming_distance(data[x*KEYSIZE:(x+1)*KEYSIZE], data[(x+1)*KEYSIZE:(x+2)*KEYSIZE])//KEYSIZE x+=1 t+=hamming_distance(data[x * KEYSIZE:(x + 1) *",
"1) * KEYSIZE:(x + 2) * KEYSIZE]) // KEYSIZE t//=x L.append((KEYSIZE, t)) KEYSIZES",
"* KEYSIZE]) // KEYSIZE t//=x L.append((KEYSIZE, t)) KEYSIZES = [x[0] for x in",
"in KEYSIZES: answer.append((sum([1 for x in decrypted_strings[KEYSIZE] if x in chars]), KEYSIZE)) print(max(answer)[1])",
"for KEYSIZE in range(2, 40): x = 1 t=hamming_distance(data[:KEYSIZE], data[KEYSIZE:(x+1)*KEYSIZE])//KEYSIZE x+=1 t+=hamming_distance(data[x*KEYSIZE:(x+1)*KEYSIZE], data[(x+1)*KEYSIZE:(x+2)*KEYSIZE])//KEYSIZE",
"for i in \"\".join(list_diff) if int(i) == 1]) L = [] for KEYSIZE",
"KEYSIZE in KEYSIZES: blocks = [data[i:i+KEYSIZE] for i in range(0, len(data), KEYSIZE)] key",
"= [] for KEYSIZE in KEYSIZES: answer.append((sum([1 for x in decrypted_strings[KEYSIZE] if x",
"import base64 import string import itertools with open(\"6.txt\", \"r\") as the_file: b64data =",
"t=hamming_distance(data[:KEYSIZE], data[KEYSIZE:(x+1)*KEYSIZE])//KEYSIZE x+=1 t+=hamming_distance(data[x*KEYSIZE:(x+1)*KEYSIZE], data[(x+1)*KEYSIZE:(x+2)*KEYSIZE])//KEYSIZE x+=1 t+=hamming_distance(data[x * KEYSIZE:(x + 1) * KEYSIZE],",
"1]) L = [] for KEYSIZE in range(2, 40): x = 1 t=hamming_distance(data[:KEYSIZE],",
"y): # finds the xor of the numbers in the two lists list_diff",
"zip(x, y)] # finds the total number of 1's in the XOR's return",
"strings = {} chars = string.ascii_letters + \" \" for i in chars:",
"40): x = 1 t=hamming_distance(data[:KEYSIZE], data[KEYSIZE:(x+1)*KEYSIZE])//KEYSIZE x+=1 t+=hamming_distance(data[x*KEYSIZE:(x+1)*KEYSIZE], data[(x+1)*KEYSIZE:(x+2)*KEYSIZE])//KEYSIZE x+=1 t+=hamming_distance(data[x * KEYSIZE:(x",
"= \"\".join([chr(x) for x in out_arr]) answer.append((sum([1 for x in out_arr if chr(x)",
"KEYSIZE) key_index = 0 out = [] decrypted_strings[KEYSIZE] = [chr(int(a) ^ ord(b)) for",
"L if x[1] <= 2] decrypted_strings = {} for KEYSIZE in KEYSIZES: blocks",
"the xor of the numbers in the two lists list_diff = [\"{0:b}\".format(i ^",
"\" for i in chars: out_arr = [] for j in [x[z] for",
"\"\" for z in range(KEYSIZE): answer = [] strings = {} chars =",
"= [x[0] for x in L if x[1] <= 2] decrypted_strings = {}",
"total number of 1's in the XOR's return sum([1 for i in \"\".join(list_diff)",
"out_arr]) answer.append((sum([1 for x in out_arr if chr(x) in chars]), ord(i))) key +=",
"[x[z] for x in blocks if len(x) > z]: out_arr.append(ord(i) ^ j) strings[i]",
"XOR's return sum([1 for i in \"\".join(list_diff) if int(i) == 1]) L =",
"x in blocks if len(x) > z]: out_arr.append(ord(i) ^ j) strings[i] = \"\".join([chr(x)",
"{} chars = string.ascii_letters + \" \" for i in chars: out_arr =",
"[data[i:i+KEYSIZE] for i in range(0, len(data), KEYSIZE)] key = \"\" for z in",
"key_index = 0 out = [] decrypted_strings[KEYSIZE] = [chr(int(a) ^ ord(b)) for a,",
"[] for KEYSIZE in range(2, 40): x = 1 t=hamming_distance(data[:KEYSIZE], data[KEYSIZE:(x+1)*KEYSIZE])//KEYSIZE x+=1 t+=hamming_distance(data[x*KEYSIZE:(x+1)*KEYSIZE],",
"zip(data, itertools.cycle(key))] chars = string.ascii_letters answer = [] for KEYSIZE in KEYSIZES: answer.append((sum([1",
"int(i) == 1]) L = [] for KEYSIZE in range(2, 40): x =",
"a, b in zip(data, itertools.cycle(key))] chars = string.ascii_letters answer = [] for KEYSIZE",
"= \"\" for z in range(KEYSIZE): answer = [] strings = {} chars",
"chr(x) in chars]), ord(i))) key += chr(max(answer)[1]) # prints out all of the",
"print(data) def hamming_distance(x, y): # finds the xor of the numbers in the",
"[x[0] for x in L if x[1] <= 2] decrypted_strings = {} for",
"in \"\".join(list_diff) if int(i) == 1]) L = [] for KEYSIZE in range(2,",
"L.append((KEYSIZE, t)) KEYSIZES = [x[0] for x in L if x[1] <= 2]",
"for KEYSIZE in KEYSIZES: blocks = [data[i:i+KEYSIZE] for i in range(0, len(data), KEYSIZE)]",
"data[(x+1)*KEYSIZE:(x+2)*KEYSIZE])//KEYSIZE x+=1 t+=hamming_distance(data[x * KEYSIZE:(x + 1) * KEYSIZE], data[(x + 1) *",
"in L if x[1] <= 2] decrypted_strings = {} for KEYSIZE in KEYSIZES:",
"data[(x + 1) * KEYSIZE:(x + 2) * KEYSIZE]) // KEYSIZE x+=1 t+=hamming_distance(data[x",
"\"r\") as the_file: b64data = the_file.read().replace(\"\\n\", \"\") data = base64.standard_b64decode(b64data) print(data) def hamming_distance(x,",
"for a, b in zip(data, itertools.cycle(key))] chars = string.ascii_letters answer = [] for",
"0 out = [] decrypted_strings[KEYSIZE] = [chr(int(a) ^ ord(b)) for a, b in",
"with open(\"6.txt\", \"r\") as the_file: b64data = the_file.read().replace(\"\\n\", \"\") data = base64.standard_b64decode(b64data) print(data)",
"list_diff = [\"{0:b}\".format(i ^ j) for i, j in zip(x, y)] # finds",
"in chars: out_arr = [] for j in [x[z] for x in blocks",
"for x in out_arr if chr(x) in chars]), ord(i))) key += chr(max(answer)[1]) #",
"KEYSIZE x+=1 t+=hamming_distance(data[x * KEYSIZE:(x + 1) * KEYSIZE], data[(x + 1) *",
"number of 1's in the XOR's return sum([1 for i in \"\".join(list_diff) if",
"range(2, 40): x = 1 t=hamming_distance(data[:KEYSIZE], data[KEYSIZE:(x+1)*KEYSIZE])//KEYSIZE x+=1 t+=hamming_distance(data[x*KEYSIZE:(x+1)*KEYSIZE], data[(x+1)*KEYSIZE:(x+2)*KEYSIZE])//KEYSIZE x+=1 t+=hamming_distance(data[x *",
"all of the keys print(key, KEYSIZE) key_index = 0 out = [] decrypted_strings[KEYSIZE]",
"j) for i, j in zip(x, y)] # finds the total number of",
"# finds the xor of the numbers in the two lists list_diff =",
"t+=hamming_distance(data[x*KEYSIZE:(x+1)*KEYSIZE], data[(x+1)*KEYSIZE:(x+2)*KEYSIZE])//KEYSIZE x+=1 t+=hamming_distance(data[x * KEYSIZE:(x + 1) * KEYSIZE], data[(x + 1)",
"= base64.standard_b64decode(b64data) print(data) def hamming_distance(x, y): # finds the xor of the numbers",
"* KEYSIZE]) // KEYSIZE x+=1 t+=hamming_distance(data[x * KEYSIZE:(x + 1) * KEYSIZE], data[(x",
"KEYSIZE)] key = \"\" for z in range(KEYSIZE): answer = [] strings =",
"* KEYSIZE], data[(x + 1) * KEYSIZE:(x + 2) * KEYSIZE]) // KEYSIZE",
"KEYSIZE in range(2, 40): x = 1 t=hamming_distance(data[:KEYSIZE], data[KEYSIZE:(x+1)*KEYSIZE])//KEYSIZE x+=1 t+=hamming_distance(data[x*KEYSIZE:(x+1)*KEYSIZE], data[(x+1)*KEYSIZE:(x+2)*KEYSIZE])//KEYSIZE x+=1",
"KEYSIZE], data[(x + 1) * KEYSIZE:(x + 2) * KEYSIZE]) // KEYSIZE t//=x",
"2] decrypted_strings = {} for KEYSIZE in KEYSIZES: blocks = [data[i:i+KEYSIZE] for i",
"KEYSIZES: blocks = [data[i:i+KEYSIZE] for i in range(0, len(data), KEYSIZE)] key = \"\"",
"KEYSIZE]) // KEYSIZE t//=x L.append((KEYSIZE, t)) KEYSIZES = [x[0] for x in L",
"= [chr(int(a) ^ ord(b)) for a, b in zip(data, itertools.cycle(key))] chars = string.ascii_letters",
"key += chr(max(answer)[1]) # prints out all of the keys print(key, KEYSIZE) key_index",
"data[(x + 1) * KEYSIZE:(x + 2) * KEYSIZE]) // KEYSIZE t//=x L.append((KEYSIZE,",
"for i, j in zip(x, y)] # finds the total number of 1's",
"key = \"\" for z in range(KEYSIZE): answer = [] strings = {}",
"^ ord(b)) for a, b in zip(data, itertools.cycle(key))] chars = string.ascii_letters answer =",
"in the XOR's return sum([1 for i in \"\".join(list_diff) if int(i) == 1])",
"for i in range(0, len(data), KEYSIZE)] key = \"\" for z in range(KEYSIZE):",
"b64data = the_file.read().replace(\"\\n\", \"\") data = base64.standard_b64decode(b64data) print(data) def hamming_distance(x, y): # finds",
"decrypted_strings[KEYSIZE] = [chr(int(a) ^ ord(b)) for a, b in zip(data, itertools.cycle(key))] chars =",
"== 1]) L = [] for KEYSIZE in range(2, 40): x = 1",
"ord(b)) for a, b in zip(data, itertools.cycle(key))] chars = string.ascii_letters answer = []",
"<= 2] decrypted_strings = {} for KEYSIZE in KEYSIZES: blocks = [data[i:i+KEYSIZE] for",
"out_arr.append(ord(i) ^ j) strings[i] = \"\".join([chr(x) for x in out_arr]) answer.append((sum([1 for x",
"x in L if x[1] <= 2] decrypted_strings = {} for KEYSIZE in",
"# prints out all of the keys print(key, KEYSIZE) key_index = 0 out",
"string import itertools with open(\"6.txt\", \"r\") as the_file: b64data = the_file.read().replace(\"\\n\", \"\") data",
"+ 1) * KEYSIZE:(x + 2) * KEYSIZE]) // KEYSIZE x+=1 t+=hamming_distance(data[x *",
"j) strings[i] = \"\".join([chr(x) for x in out_arr]) answer.append((sum([1 for x in out_arr",
"string.ascii_letters answer = [] for KEYSIZE in KEYSIZES: answer.append((sum([1 for x in decrypted_strings[KEYSIZE]",
"[] decrypted_strings[KEYSIZE] = [chr(int(a) ^ ord(b)) for a, b in zip(data, itertools.cycle(key))] chars",
"= [\"{0:b}\".format(i ^ j) for i, j in zip(x, y)] # finds the",
"<reponame>tritoke/matasano-crypto-challenges import base64 import string import itertools with open(\"6.txt\", \"r\") as the_file: b64data",
"finds the xor of the numbers in the two lists list_diff = [\"{0:b}\".format(i",
"KEYSIZE in KEYSIZES: answer.append((sum([1 for x in decrypted_strings[KEYSIZE] if x in chars]), KEYSIZE))",
"[] for j in [x[z] for x in blocks if len(x) > z]:",
"for i in chars: out_arr = [] for j in [x[z] for x",
"prints out all of the keys print(key, KEYSIZE) key_index = 0 out =",
"open(\"6.txt\", \"r\") as the_file: b64data = the_file.read().replace(\"\\n\", \"\") data = base64.standard_b64decode(b64data) print(data) def",
"finds the total number of 1's in the XOR's return sum([1 for i",
"chars]), ord(i))) key += chr(max(answer)[1]) # prints out all of the keys print(key,",
"sum([1 for i in \"\".join(list_diff) if int(i) == 1]) L = [] for",
"i, j in zip(x, y)] # finds the total number of 1's in",
"ord(i))) key += chr(max(answer)[1]) # prints out all of the keys print(key, KEYSIZE)",
"numbers in the two lists list_diff = [\"{0:b}\".format(i ^ j) for i, j",
"[] for KEYSIZE in KEYSIZES: answer.append((sum([1 for x in decrypted_strings[KEYSIZE] if x in",
"KEYSIZES: answer.append((sum([1 for x in decrypted_strings[KEYSIZE] if x in chars]), KEYSIZE)) print(max(answer)[1]) print(\"\".join(decrypted_strings[max(answer)[1]]))",
"\" \" for i in chars: out_arr = [] for j in [x[z]",
"1) * KEYSIZE:(x + 2) * KEYSIZE]) // KEYSIZE x+=1 t+=hamming_distance(data[x * KEYSIZE:(x",
"y)] # finds the total number of 1's in the XOR's return sum([1",
"data[KEYSIZE:(x+1)*KEYSIZE])//KEYSIZE x+=1 t+=hamming_distance(data[x*KEYSIZE:(x+1)*KEYSIZE], data[(x+1)*KEYSIZE:(x+2)*KEYSIZE])//KEYSIZE x+=1 t+=hamming_distance(data[x * KEYSIZE:(x + 1) * KEYSIZE], data[(x",
"= string.ascii_letters answer = [] for KEYSIZE in KEYSIZES: answer.append((sum([1 for x in",
"+ 2) * KEYSIZE]) // KEYSIZE t//=x L.append((KEYSIZE, t)) KEYSIZES = [x[0] for",
"blocks if len(x) > z]: out_arr.append(ord(i) ^ j) strings[i] = \"\".join([chr(x) for x",
"def hamming_distance(x, y): # finds the xor of the numbers in the two",
"as the_file: b64data = the_file.read().replace(\"\\n\", \"\") data = base64.standard_b64decode(b64data) print(data) def hamming_distance(x, y):",
"z in range(KEYSIZE): answer = [] strings = {} chars = string.ascii_letters +",
"chars: out_arr = [] for j in [x[z] for x in blocks if",
"// KEYSIZE x+=1 t+=hamming_distance(data[x * KEYSIZE:(x + 1) * KEYSIZE], data[(x + 1)",
"the keys print(key, KEYSIZE) key_index = 0 out = [] decrypted_strings[KEYSIZE] = [chr(int(a)",
"x in out_arr]) answer.append((sum([1 for x in out_arr if chr(x) in chars]), ord(i)))",
"1's in the XOR's return sum([1 for i in \"\".join(list_diff) if int(i) ==",
"base64.standard_b64decode(b64data) print(data) def hamming_distance(x, y): # finds the xor of the numbers in",
"L = [] for KEYSIZE in range(2, 40): x = 1 t=hamming_distance(data[:KEYSIZE], data[KEYSIZE:(x+1)*KEYSIZE])//KEYSIZE",
"out_arr = [] for j in [x[z] for x in blocks if len(x)",
"in zip(data, itertools.cycle(key))] chars = string.ascii_letters answer = [] for KEYSIZE in KEYSIZES:",
"answer = [] strings = {} chars = string.ascii_letters + \" \" for",
"= [] for KEYSIZE in range(2, 40): x = 1 t=hamming_distance(data[:KEYSIZE], data[KEYSIZE:(x+1)*KEYSIZE])//KEYSIZE x+=1",
"> z]: out_arr.append(ord(i) ^ j) strings[i] = \"\".join([chr(x) for x in out_arr]) answer.append((sum([1",
"+ 1) * KEYSIZE:(x + 2) * KEYSIZE]) // KEYSIZE t//=x L.append((KEYSIZE, t))",
"2) * KEYSIZE]) // KEYSIZE t//=x L.append((KEYSIZE, t)) KEYSIZES = [x[0] for x",
"i in range(0, len(data), KEYSIZE)] key = \"\" for z in range(KEYSIZE): answer",
"= the_file.read().replace(\"\\n\", \"\") data = base64.standard_b64decode(b64data) print(data) def hamming_distance(x, y): # finds the",
"\"\".join([chr(x) for x in out_arr]) answer.append((sum([1 for x in out_arr if chr(x) in",
"answer = [] for KEYSIZE in KEYSIZES: answer.append((sum([1 for x in decrypted_strings[KEYSIZE] if",
"the_file.read().replace(\"\\n\", \"\") data = base64.standard_b64decode(b64data) print(data) def hamming_distance(x, y): # finds the xor",
"KEYSIZE:(x + 1) * KEYSIZE], data[(x + 1) * KEYSIZE:(x + 2) *",
"x = 1 t=hamming_distance(data[:KEYSIZE], data[KEYSIZE:(x+1)*KEYSIZE])//KEYSIZE x+=1 t+=hamming_distance(data[x*KEYSIZE:(x+1)*KEYSIZE], data[(x+1)*KEYSIZE:(x+2)*KEYSIZE])//KEYSIZE x+=1 t+=hamming_distance(data[x * KEYSIZE:(x +",
"= [] strings = {} chars = string.ascii_letters + \" \" for i",
"keys print(key, KEYSIZE) key_index = 0 out = [] decrypted_strings[KEYSIZE] = [chr(int(a) ^",
"in chars]), ord(i))) key += chr(max(answer)[1]) # prints out all of the keys",
"for z in range(KEYSIZE): answer = [] strings = {} chars = string.ascii_letters",
"lists list_diff = [\"{0:b}\".format(i ^ j) for i, j in zip(x, y)] #",
"if int(i) == 1]) L = [] for KEYSIZE in range(2, 40): x",
"itertools with open(\"6.txt\", \"r\") as the_file: b64data = the_file.read().replace(\"\\n\", \"\") data = base64.standard_b64decode(b64data)",
"in range(0, len(data), KEYSIZE)] key = \"\" for z in range(KEYSIZE): answer =",
"answer.append((sum([1 for x in out_arr if chr(x) in chars]), ord(i))) key += chr(max(answer)[1])",
"i in \"\".join(list_diff) if int(i) == 1]) L = [] for KEYSIZE in",
"KEYSIZE], data[(x + 1) * KEYSIZE:(x + 2) * KEYSIZE]) // KEYSIZE x+=1",
"z]: out_arr.append(ord(i) ^ j) strings[i] = \"\".join([chr(x) for x in out_arr]) answer.append((sum([1 for",
"out_arr if chr(x) in chars]), ord(i))) key += chr(max(answer)[1]) # prints out all",
"KEYSIZE:(x + 2) * KEYSIZE]) // KEYSIZE x+=1 t+=hamming_distance(data[x * KEYSIZE:(x + 1)",
"= [data[i:i+KEYSIZE] for i in range(0, len(data), KEYSIZE)] key = \"\" for z",
"in the two lists list_diff = [\"{0:b}\".format(i ^ j) for i, j in",
"2) * KEYSIZE]) // KEYSIZE x+=1 t+=hamming_distance(data[x * KEYSIZE:(x + 1) * KEYSIZE],",
"* KEYSIZE:(x + 2) * KEYSIZE]) // KEYSIZE x+=1 t+=hamming_distance(data[x * KEYSIZE:(x +",
"t//=x L.append((KEYSIZE, t)) KEYSIZES = [x[0] for x in L if x[1] <=",
"of 1's in the XOR's return sum([1 for i in \"\".join(list_diff) if int(i)",
"{} for KEYSIZE in KEYSIZES: blocks = [data[i:i+KEYSIZE] for i in range(0, len(data),",
"in KEYSIZES: blocks = [data[i:i+KEYSIZE] for i in range(0, len(data), KEYSIZE)] key =",
"chars = string.ascii_letters + \" \" for i in chars: out_arr = []",
"i in chars: out_arr = [] for j in [x[z] for x in",
"the XOR's return sum([1 for i in \"\".join(list_diff) if int(i) == 1]) L",
"in [x[z] for x in blocks if len(x) > z]: out_arr.append(ord(i) ^ j)",
"for x in out_arr]) answer.append((sum([1 for x in out_arr if chr(x) in chars]),",
"itertools.cycle(key))] chars = string.ascii_letters answer = [] for KEYSIZE in KEYSIZES: answer.append((sum([1 for",
"= {} chars = string.ascii_letters + \" \" for i in chars: out_arr",
"of the numbers in the two lists list_diff = [\"{0:b}\".format(i ^ j) for",
"xor of the numbers in the two lists list_diff = [\"{0:b}\".format(i ^ j)",
"\"\".join(list_diff) if int(i) == 1]) L = [] for KEYSIZE in range(2, 40):",
"range(0, len(data), KEYSIZE)] key = \"\" for z in range(KEYSIZE): answer = []",
"+= chr(max(answer)[1]) # prints out all of the keys print(key, KEYSIZE) key_index =",
"base64 import string import itertools with open(\"6.txt\", \"r\") as the_file: b64data = the_file.read().replace(\"\\n\",",
"in range(2, 40): x = 1 t=hamming_distance(data[:KEYSIZE], data[KEYSIZE:(x+1)*KEYSIZE])//KEYSIZE x+=1 t+=hamming_distance(data[x*KEYSIZE:(x+1)*KEYSIZE], data[(x+1)*KEYSIZE:(x+2)*KEYSIZE])//KEYSIZE x+=1 t+=hamming_distance(data[x",
"= string.ascii_letters + \" \" for i in chars: out_arr = [] for",
"+ 1) * KEYSIZE], data[(x + 1) * KEYSIZE:(x + 2) * KEYSIZE])",
"x in out_arr if chr(x) in chars]), ord(i))) key += chr(max(answer)[1]) # prints",
"two lists list_diff = [\"{0:b}\".format(i ^ j) for i, j in zip(x, y)]",
"* KEYSIZE:(x + 1) * KEYSIZE], data[(x + 1) * KEYSIZE:(x + 2)",
"import string import itertools with open(\"6.txt\", \"r\") as the_file: b64data = the_file.read().replace(\"\\n\", \"\")",
"print(key, KEYSIZE) key_index = 0 out = [] decrypted_strings[KEYSIZE] = [chr(int(a) ^ ord(b))",
"data = base64.standard_b64decode(b64data) print(data) def hamming_distance(x, y): # finds the xor of the",
"chars = string.ascii_letters answer = [] for KEYSIZE in KEYSIZES: answer.append((sum([1 for x",
"[] strings = {} chars = string.ascii_letters + \" \" for i in",
"// KEYSIZE t//=x L.append((KEYSIZE, t)) KEYSIZES = [x[0] for x in L if",
"x[1] <= 2] decrypted_strings = {} for KEYSIZE in KEYSIZES: blocks = [data[i:i+KEYSIZE]",
"blocks = [data[i:i+KEYSIZE] for i in range(0, len(data), KEYSIZE)] key = \"\" for",
"out all of the keys print(key, KEYSIZE) key_index = 0 out = []",
"strings[i] = \"\".join([chr(x) for x in out_arr]) answer.append((sum([1 for x in out_arr if",
"in out_arr]) answer.append((sum([1 for x in out_arr if chr(x) in chars]), ord(i))) key",
"t+=hamming_distance(data[x * KEYSIZE:(x + 1) * KEYSIZE], data[(x + 1) * KEYSIZE:(x +",
"decrypted_strings = {} for KEYSIZE in KEYSIZES: blocks = [data[i:i+KEYSIZE] for i in",
"the two lists list_diff = [\"{0:b}\".format(i ^ j) for i, j in zip(x,",
"= [] decrypted_strings[KEYSIZE] = [chr(int(a) ^ ord(b)) for a, b in zip(data, itertools.cycle(key))]",
"x+=1 t+=hamming_distance(data[x*KEYSIZE:(x+1)*KEYSIZE], data[(x+1)*KEYSIZE:(x+2)*KEYSIZE])//KEYSIZE x+=1 t+=hamming_distance(data[x * KEYSIZE:(x + 1) * KEYSIZE], data[(x +",
"b in zip(data, itertools.cycle(key))] chars = string.ascii_letters answer = [] for KEYSIZE in",
"= {} for KEYSIZE in KEYSIZES: blocks = [data[i:i+KEYSIZE] for i in range(0,",
"= 0 out = [] decrypted_strings[KEYSIZE] = [chr(int(a) ^ ord(b)) for a, b"
] |
[
"__init__(self): tk.Tk.__init__(self) #hackish way, essentially makes root window #as small as possible but",
"Image, ImageTk import json from rmq import RMQiface urls = [ 'https://cdn.revjet.com/s3/csp/1578955925683/shine.png', 'https://cdn.revjet.com/s3/csp/1578955925683/logo.svg',",
"= RMQiface(host, queue, usr, pwd) self.img_error = Image.open('error.png') self.img_none = Image.open('none.png') #remove window",
"def __init__(self, *args, **kwargs): tk.Toplevel.__init__(self, *args, **kwargs) with open('reader_config.json', 'r') as f: config",
"def cycle(self): while True: self.nexti() time.sleep(0.01) def nexti(self): # import random # url",
"on <esc> self.wm_geometry(\"0x0+0+0\") self.window = MySlideShow(self) self.window.cycle() class MySlideShow(tk.Toplevel): def __init__(self, *args, **kwargs):",
"tk from PIL import Image, ImageTk import json from rmq import RMQiface urls",
"to photo so that garbage collection #does not clear image variable in show_image()",
"import RMQiface urls = [ 'https://cdn.revjet.com/s3/csp/1578955925683/shine.png', 'https://cdn.revjet.com/s3/csp/1578955925683/logo.svg', 'https://tpc.googlesyndication.com/daca_images/simgad/13865403217536204307', 'https://tpc.googlesyndication.com/daca_images/simgad/1948022358329940732?sqp=4sqPyQSWAUKTAQgAEhQNzczMPhUAAABAHQAAAAAlAAAAABgAIgoNAACAPxUAAIA_Kk8IWhABHQAAtEIgASgBMAY4A0CAwtcvSABQAFgAYFpwAngAgAEAiAEAkAEAnQEAAIA_oAEAqAEAsAGAreIEuAH___________8BxQEtsp0-MhoIvwMQ6gEYASABLQAAAD8wvwM46gFFAACAPw&rs=AOga4qmwNN2g28c_J8ehXFAoY4bOr7naGQ', 'https://tpc.googlesyndication.com/simgad/12366423408132574325', 'https://tpc.googlesyndication.com/simgad/3767484695346986263' ] class",
"= config['filtered_images_queue_name'] self.mq = RMQiface(host, queue, usr, pwd) self.img_error = Image.open('error.png') self.img_none =",
"scr_w, scr_h = self.winfo_screenwidth(), self.winfo_screenheight() width, height = min(scr_w, img_w), min(scr_h, img_h) image.thumbnail((width,",
"0 #used to display as background image self.label = tk.Label(self) self.label.pack(side=\"top\", fill=\"both\", expand=True)",
"image.thumbnail((width, height), Image.ANTIALIAS) #set window size after scaling the original image up/down to",
"Image.open(BytesIO(urlopen(url).read())) self.showImage(img) print(f'INFO:\\tshowing {url}') except Exception: print(f'ERROR:\\tnot a valid image: {url}') else: print('INFO:\\tQueue",
"#does not clear image variable in show_image() self.persistent_image = None self.imageList = []",
"from rmq import RMQiface urls = [ 'https://cdn.revjet.com/s3/csp/1578955925683/shine.png', 'https://cdn.revjet.com/s3/csp/1578955925683/logo.svg', 'https://tpc.googlesyndication.com/daca_images/simgad/13865403217536204307', 'https://tpc.googlesyndication.com/daca_images/simgad/1948022358329940732?sqp=4sqPyQSWAUKTAQgAEhQNzczMPhUAAABAHQAAAAAlAAAAABgAIgoNAACAPxUAAIA_Kk8IWhABHQAAtEIgASgBMAY4A0CAwtcvSABQAFgAYFpwAngAgAEAiAEAkAEAnQEAAIA_oAEAqAEAsAGAreIEuAH___________8BxQEtsp0-MhoIvwMQ6gEYASABLQAAAD8wvwM46gFFAACAPw&rs=AOga4qmwNN2g28c_J8ehXFAoY4bOr7naGQ', 'https://tpc.googlesyndication.com/simgad/12366423408132574325', 'https://tpc.googlesyndication.com/simgad/3767484695346986263'",
"img_w, img_h = image.size scr_w, scr_h = self.winfo_screenwidth(), self.winfo_screenheight() width, height = min(scr_w,",
"import random # url = random.choice(urls) url = self.mq.read() if url: try: img",
"binding on <esc> self.wm_geometry(\"0x0+0+0\") self.window = MySlideShow(self) self.window.cycle() class MySlideShow(tk.Toplevel): def __init__(self, *args,",
"create new image self.persistent_image = ImageTk.PhotoImage(image) self.label.configure(image=self.persistent_image) self.update() slideShow = HiddenRoot() # slideShow.window.attributes('-fullscreen',",
"self.wm_geometry(\"0x0+0+0\") self.window = MySlideShow(self) self.window.cycle() class MySlideShow(tk.Toplevel): def __init__(self, *args, **kwargs): tk.Toplevel.__init__(self, *args,",
"way, essentially makes root window #as small as possible but still \"focused\" #enabling",
"= HiddenRoot() # slideShow.window.attributes('-fullscreen', True) # slideShow.window.attributes('-topmost', True) slideShow.bind_all(\"<Escape>\", lambda e: slideShow.destroy()) #",
"= Image.open('none.png') #remove window decorations # self.overrideredirect(True) #save reference to photo so that",
"height = min(scr_w, img_w), min(scr_h, img_h) image.thumbnail((width, height), Image.ANTIALIAS) #set window size after",
"usr, pwd) self.img_error = Image.open('error.png') self.img_none = Image.open('none.png') #remove window decorations # self.overrideredirect(True)",
"time.sleep(0.01) def nexti(self): # import random # url = random.choice(urls) url = self.mq.read()",
"MySlideShow(self) self.window.cycle() class MySlideShow(tk.Toplevel): def __init__(self, *args, **kwargs): tk.Toplevel.__init__(self, *args, **kwargs) with open('reader_config.json',",
"self.mq = RMQiface(host, queue, usr, pwd) self.img_error = Image.open('error.png') self.img_none = Image.open('none.png') #remove",
"variable in show_image() self.persistent_image = None self.imageList = [] self.pixNum = 0 #used",
"original image up/down to fit screen #removes the border on the image scaled_w,",
"usr = config['user'] pwd = config['password'] queue = config['filtered_images_queue_name'] self.mq = RMQiface(host, queue,",
"a valid image: {url}') else: print('INFO:\\tQueue is empty') time.sleep(1.0) def showImage(self, image): img_w,",
"image variable in show_image() self.persistent_image = None self.imageList = [] self.pixNum = 0",
"'https://tpc.googlesyndication.com/daca_images/simgad/1948022358329940732?sqp=4sqPyQSWAUKTAQgAEhQNzczMPhUAAABAHQAAAAAlAAAAABgAIgoNAACAPxUAAIA_Kk8IWhABHQAAtEIgASgBMAY4A0CAwtcvSABQAFgAYFpwAngAgAEAiAEAkAEAnQEAAIA_oAEAqAEAsAGAreIEuAH___________8BxQEtsp0-MhoIvwMQ6gEYASABLQAAAD8wvwM46gFFAACAPw&rs=AOga4qmwNN2g28c_J8ehXFAoY4bOr7naGQ', 'https://tpc.googlesyndication.com/simgad/12366423408132574325', 'https://tpc.googlesyndication.com/simgad/3767484695346986263' ] class HiddenRoot(tk.Tk): def __init__(self): tk.Tk.__init__(self) #hackish way, essentially makes",
"display as background image self.label = tk.Label(self) self.label.pack(side=\"top\", fill=\"both\", expand=True) def cycle(self): while",
"showImage(self, image): img_w, img_h = image.size scr_w, scr_h = self.winfo_screenwidth(), self.winfo_screenheight() width, height",
"urlopen from io import BytesIO import time import tkinter as tk from PIL",
"MySlideShow(tk.Toplevel): def __init__(self, *args, **kwargs): tk.Toplevel.__init__(self, *args, **kwargs) with open('reader_config.json', 'r') as f:",
"slideShow.window.attributes('-fullscreen', True) # slideShow.window.attributes('-topmost', True) slideShow.bind_all(\"<Escape>\", lambda e: slideShow.destroy()) # slideShow.bind_all(\"<Return>\", lambda e:",
"background image self.label = tk.Label(self) self.label.pack(side=\"top\", fill=\"both\", expand=True) def cycle(self): while True: self.nexti()",
"us to use the binding on <esc> self.wm_geometry(\"0x0+0+0\") self.window = MySlideShow(self) self.window.cycle() class",
"= min(scr_w, img_w), min(scr_h, img_h) image.thumbnail((width, height), Image.ANTIALIAS) #set window size after scaling",
"= tk.Label(self) self.label.pack(side=\"top\", fill=\"both\", expand=True) def cycle(self): while True: self.nexti() time.sleep(0.01) def nexti(self):",
"rmq import RMQiface urls = [ 'https://cdn.revjet.com/s3/csp/1578955925683/shine.png', 'https://cdn.revjet.com/s3/csp/1578955925683/logo.svg', 'https://tpc.googlesyndication.com/daca_images/simgad/13865403217536204307', 'https://tpc.googlesyndication.com/daca_images/simgad/1948022358329940732?sqp=4sqPyQSWAUKTAQgAEhQNzczMPhUAAABAHQAAAAAlAAAAABgAIgoNAACAPxUAAIA_Kk8IWhABHQAAtEIgASgBMAY4A0CAwtcvSABQAFgAYFpwAngAgAEAiAEAkAEAnQEAAIA_oAEAqAEAsAGAreIEuAH___________8BxQEtsp0-MhoIvwMQ6gEYASABLQAAAD8wvwM46gFFAACAPw&rs=AOga4qmwNN2g28c_J8ehXFAoY4bOr7naGQ', 'https://tpc.googlesyndication.com/simgad/12366423408132574325', 'https://tpc.googlesyndication.com/simgad/3767484695346986263' ]",
"= self.winfo_screenwidth(), self.winfo_screenheight() width, height = min(scr_w, img_w), min(scr_h, img_h) image.thumbnail((width, height), Image.ANTIALIAS)",
"json.load(f) host = config['host'] usr = config['user'] pwd = config['password'] queue = config['filtered_images_queue_name']",
"from urllib.request import urlopen from io import BytesIO import time import tkinter as",
"config['host'] usr = config['user'] pwd = config['password'] queue = config['filtered_images_queue_name'] self.mq = RMQiface(host,",
"= config['password'] queue = config['filtered_images_queue_name'] self.mq = RMQiface(host, queue, usr, pwd) self.img_error =",
"time.sleep(1.0) def showImage(self, image): img_w, img_h = image.size scr_w, scr_h = self.winfo_screenwidth(), self.winfo_screenheight()",
"self.overrideredirect(True) #save reference to photo so that garbage collection #does not clear image",
"= image.size scr_w, scr_h = self.winfo_screenwidth(), self.winfo_screenheight() width, height = min(scr_w, img_w), min(scr_h,",
"not clear image variable in show_image() self.persistent_image = None self.imageList = [] self.pixNum",
"json from rmq import RMQiface urls = [ 'https://cdn.revjet.com/s3/csp/1578955925683/shine.png', 'https://cdn.revjet.com/s3/csp/1578955925683/logo.svg', 'https://tpc.googlesyndication.com/daca_images/simgad/13865403217536204307', 'https://tpc.googlesyndication.com/daca_images/simgad/1948022358329940732?sqp=4sqPyQSWAUKTAQgAEhQNzczMPhUAAABAHQAAAAAlAAAAABgAIgoNAACAPxUAAIA_Kk8IWhABHQAAtEIgASgBMAY4A0CAwtcvSABQAFgAYFpwAngAgAEAiAEAkAEAnQEAAIA_oAEAqAEAsAGAreIEuAH___________8BxQEtsp0-MhoIvwMQ6gEYASABLQAAAD8wvwM46gFFAACAPw&rs=AOga4qmwNN2g28c_J8ehXFAoY4bOr7naGQ', 'https://tpc.googlesyndication.com/simgad/12366423408132574325',",
"#set window size after scaling the original image up/down to fit screen #removes",
"makes root window #as small as possible but still \"focused\" #enabling us to",
"fill=\"both\", expand=True) def cycle(self): while True: self.nexti() time.sleep(0.01) def nexti(self): # import random",
"= config['host'] usr = config['user'] pwd = config['password'] queue = config['filtered_images_queue_name'] self.mq =",
"HiddenRoot() # slideShow.window.attributes('-fullscreen', True) # slideShow.window.attributes('-topmost', True) slideShow.bind_all(\"<Escape>\", lambda e: slideShow.destroy()) # slideShow.bind_all(\"<Return>\",",
"but still \"focused\" #enabling us to use the binding on <esc> self.wm_geometry(\"0x0+0+0\") self.window",
"queue = config['filtered_images_queue_name'] self.mq = RMQiface(host, queue, usr, pwd) self.img_error = Image.open('error.png') self.img_none",
"import urlopen from io import BytesIO import time import tkinter as tk from",
"scr_h = self.winfo_screenwidth(), self.winfo_screenheight() width, height = min(scr_w, img_w), min(scr_h, img_h) image.thumbnail((width, height),",
"= None self.imageList = [] self.pixNum = 0 #used to display as background",
"<esc> self.wm_geometry(\"0x0+0+0\") self.window = MySlideShow(self) self.window.cycle() class MySlideShow(tk.Toplevel): def __init__(self, *args, **kwargs): tk.Toplevel.__init__(self,",
"urls = [ 'https://cdn.revjet.com/s3/csp/1578955925683/shine.png', 'https://cdn.revjet.com/s3/csp/1578955925683/logo.svg', 'https://tpc.googlesyndication.com/daca_images/simgad/13865403217536204307', 'https://tpc.googlesyndication.com/daca_images/simgad/1948022358329940732?sqp=4sqPyQSWAUKTAQgAEhQNzczMPhUAAABAHQAAAAAlAAAAABgAIgoNAACAPxUAAIA_Kk8IWhABHQAAtEIgASgBMAY4A0CAwtcvSABQAFgAYFpwAngAgAEAiAEAkAEAnQEAAIA_oAEAqAEAsAGAreIEuAH___________8BxQEtsp0-MhoIvwMQ6gEYASABLQAAAD8wvwM46gFFAACAPw&rs=AOga4qmwNN2g28c_J8ehXFAoY4bOr7naGQ', 'https://tpc.googlesyndication.com/simgad/12366423408132574325', 'https://tpc.googlesyndication.com/simgad/3767484695346986263' ] class HiddenRoot(tk.Tk): def",
"slideShow = HiddenRoot() # slideShow.window.attributes('-fullscreen', True) # slideShow.window.attributes('-topmost', True) slideShow.bind_all(\"<Escape>\", lambda e: slideShow.destroy())",
"#as small as possible but still \"focused\" #enabling us to use the binding",
"= 0 #used to display as background image self.label = tk.Label(self) self.label.pack(side=\"top\", fill=\"both\",",
"'https://tpc.googlesyndication.com/daca_images/simgad/13865403217536204307', 'https://tpc.googlesyndication.com/daca_images/simgad/1948022358329940732?sqp=4sqPyQSWAUKTAQgAEhQNzczMPhUAAABAHQAAAAAlAAAAABgAIgoNAACAPxUAAIA_Kk8IWhABHQAAtEIgASgBMAY4A0CAwtcvSABQAFgAYFpwAngAgAEAiAEAkAEAnQEAAIA_oAEAqAEAsAGAreIEuAH___________8BxQEtsp0-MhoIvwMQ6gEYASABLQAAAD8wvwM46gFFAACAPw&rs=AOga4qmwNN2g28c_J8ehXFAoY4bOr7naGQ', 'https://tpc.googlesyndication.com/simgad/12366423408132574325', 'https://tpc.googlesyndication.com/simgad/3767484695346986263' ] class HiddenRoot(tk.Tk): def __init__(self): tk.Tk.__init__(self) #hackish way, essentially",
"] class HiddenRoot(tk.Tk): def __init__(self): tk.Tk.__init__(self) #hackish way, essentially makes root window #as",
"host = config['host'] usr = config['user'] pwd = config['password'] queue = config['filtered_images_queue_name'] self.mq",
"show_image() self.persistent_image = None self.imageList = [] self.pixNum = 0 #used to display",
"garbage collection #does not clear image variable in show_image() self.persistent_image = None self.imageList",
"window decorations # self.overrideredirect(True) #save reference to photo so that garbage collection #does",
"expand=True) def cycle(self): while True: self.nexti() time.sleep(0.01) def nexti(self): # import random #",
"import time import tkinter as tk from PIL import Image, ImageTk import json",
"BytesIO import time import tkinter as tk from PIL import Image, ImageTk import",
"as possible but still \"focused\" #enabling us to use the binding on <esc>",
"import BytesIO import time import tkinter as tk from PIL import Image, ImageTk",
"nexti(self): # import random # url = random.choice(urls) url = self.mq.read() if url:",
"random # url = random.choice(urls) url = self.mq.read() if url: try: img =",
"scaled_w, scaled_h = image.size self.wm_geometry(\"{}x{}+{}+{}\".format(scaled_w,scaled_h,0,0)) # create new image self.persistent_image = ImageTk.PhotoImage(image) self.label.configure(image=self.persistent_image)",
"#enabling us to use the binding on <esc> self.wm_geometry(\"0x0+0+0\") self.window = MySlideShow(self) self.window.cycle()",
"as tk from PIL import Image, ImageTk import json from rmq import RMQiface",
"Image.open('none.png') #remove window decorations # self.overrideredirect(True) #save reference to photo so that garbage",
"the binding on <esc> self.wm_geometry(\"0x0+0+0\") self.window = MySlideShow(self) self.window.cycle() class MySlideShow(tk.Toplevel): def __init__(self,",
"width, height = min(scr_w, img_w), min(scr_h, img_h) image.thumbnail((width, height), Image.ANTIALIAS) #set window size",
"Image.open('error.png') self.img_none = Image.open('none.png') #remove window decorations # self.overrideredirect(True) #save reference to photo",
"self.window.cycle() class MySlideShow(tk.Toplevel): def __init__(self, *args, **kwargs): tk.Toplevel.__init__(self, *args, **kwargs) with open('reader_config.json', 'r')",
"e: slideShow.destroy()) # slideShow.bind_all(\"<Return>\", lambda e: slideShow.window.nexti()) # exit on esc slideShow.update() slideShow.mainloop()",
"image): img_w, img_h = image.size scr_w, scr_h = self.winfo_screenwidth(), self.winfo_screenheight() width, height =",
"= image.size self.wm_geometry(\"{}x{}+{}+{}\".format(scaled_w,scaled_h,0,0)) # create new image self.persistent_image = ImageTk.PhotoImage(image) self.label.configure(image=self.persistent_image) self.update() slideShow",
"img = Image.open(BytesIO(urlopen(url).read())) self.showImage(img) print(f'INFO:\\tshowing {url}') except Exception: print(f'ERROR:\\tnot a valid image: {url}')",
"valid image: {url}') else: print('INFO:\\tQueue is empty') time.sleep(1.0) def showImage(self, image): img_w, img_h",
"self.persistent_image = ImageTk.PhotoImage(image) self.label.configure(image=self.persistent_image) self.update() slideShow = HiddenRoot() # slideShow.window.attributes('-fullscreen', True) # slideShow.window.attributes('-topmost',",
"class HiddenRoot(tk.Tk): def __init__(self): tk.Tk.__init__(self) #hackish way, essentially makes root window #as small",
"empty') time.sleep(1.0) def showImage(self, image): img_w, img_h = image.size scr_w, scr_h = self.winfo_screenwidth(),",
"**kwargs) with open('reader_config.json', 'r') as f: config = json.load(f) host = config['host'] usr",
"tk.Label(self) self.label.pack(side=\"top\", fill=\"both\", expand=True) def cycle(self): while True: self.nexti() time.sleep(0.01) def nexti(self): #",
"after scaling the original image up/down to fit screen #removes the border on",
"border on the image scaled_w, scaled_h = image.size self.wm_geometry(\"{}x{}+{}+{}\".format(scaled_w,scaled_h,0,0)) # create new image",
"image.size scr_w, scr_h = self.winfo_screenwidth(), self.winfo_screenheight() width, height = min(scr_w, img_w), min(scr_h, img_h)",
"photo so that garbage collection #does not clear image variable in show_image() self.persistent_image",
"[] self.pixNum = 0 #used to display as background image self.label = tk.Label(self)",
"self.persistent_image = None self.imageList = [] self.pixNum = 0 #used to display as",
"self.winfo_screenheight() width, height = min(scr_w, img_w), min(scr_h, img_h) image.thumbnail((width, height), Image.ANTIALIAS) #set window",
"__init__(self, *args, **kwargs): tk.Toplevel.__init__(self, *args, **kwargs) with open('reader_config.json', 'r') as f: config =",
"self.img_none = Image.open('none.png') #remove window decorations # self.overrideredirect(True) #save reference to photo so",
"up/down to fit screen #removes the border on the image scaled_w, scaled_h =",
"scaling the original image up/down to fit screen #removes the border on the",
"else: print('INFO:\\tQueue is empty') time.sleep(1.0) def showImage(self, image): img_w, img_h = image.size scr_w,",
"with open('reader_config.json', 'r') as f: config = json.load(f) host = config['host'] usr =",
"min(scr_h, img_h) image.thumbnail((width, height), Image.ANTIALIAS) #set window size after scaling the original image",
"HiddenRoot(tk.Tk): def __init__(self): tk.Tk.__init__(self) #hackish way, essentially makes root window #as small as",
"= json.load(f) host = config['host'] usr = config['user'] pwd = config['password'] queue =",
"= MySlideShow(self) self.window.cycle() class MySlideShow(tk.Toplevel): def __init__(self, *args, **kwargs): tk.Toplevel.__init__(self, *args, **kwargs) with",
"RMQiface urls = [ 'https://cdn.revjet.com/s3/csp/1578955925683/shine.png', 'https://cdn.revjet.com/s3/csp/1578955925683/logo.svg', 'https://tpc.googlesyndication.com/daca_images/simgad/13865403217536204307', 'https://tpc.googlesyndication.com/daca_images/simgad/1948022358329940732?sqp=4sqPyQSWAUKTAQgAEhQNzczMPhUAAABAHQAAAAAlAAAAABgAIgoNAACAPxUAAIA_Kk8IWhABHQAAtEIgASgBMAY4A0CAwtcvSABQAFgAYFpwAngAgAEAiAEAkAEAnQEAAIA_oAEAqAEAsAGAreIEuAH___________8BxQEtsp0-MhoIvwMQ6gEYASABLQAAAD8wvwM46gFFAACAPw&rs=AOga4qmwNN2g28c_J8ehXFAoY4bOr7naGQ', 'https://tpc.googlesyndication.com/simgad/12366423408132574325', 'https://tpc.googlesyndication.com/simgad/3767484695346986263' ] class HiddenRoot(tk.Tk):",
"self.img_error = Image.open('error.png') self.img_none = Image.open('none.png') #remove window decorations # self.overrideredirect(True) #save reference",
"still \"focused\" #enabling us to use the binding on <esc> self.wm_geometry(\"0x0+0+0\") self.window =",
"*args, **kwargs): tk.Toplevel.__init__(self, *args, **kwargs) with open('reader_config.json', 'r') as f: config = json.load(f)",
"that garbage collection #does not clear image variable in show_image() self.persistent_image = None",
"self.pixNum = 0 #used to display as background image self.label = tk.Label(self) self.label.pack(side=\"top\",",
"the image scaled_w, scaled_h = image.size self.wm_geometry(\"{}x{}+{}+{}\".format(scaled_w,scaled_h,0,0)) # create new image self.persistent_image =",
"RMQiface(host, queue, usr, pwd) self.img_error = Image.open('error.png') self.img_none = Image.open('none.png') #remove window decorations",
"min(scr_w, img_w), min(scr_h, img_h) image.thumbnail((width, height), Image.ANTIALIAS) #set window size after scaling the",
"new image self.persistent_image = ImageTk.PhotoImage(image) self.label.configure(image=self.persistent_image) self.update() slideShow = HiddenRoot() # slideShow.window.attributes('-fullscreen', True)",
"class MySlideShow(tk.Toplevel): def __init__(self, *args, **kwargs): tk.Toplevel.__init__(self, *args, **kwargs) with open('reader_config.json', 'r') as",
"from PIL import Image, ImageTk import json from rmq import RMQiface urls =",
"use the binding on <esc> self.wm_geometry(\"0x0+0+0\") self.window = MySlideShow(self) self.window.cycle() class MySlideShow(tk.Toplevel): def",
"random.choice(urls) url = self.mq.read() if url: try: img = Image.open(BytesIO(urlopen(url).read())) self.showImage(img) print(f'INFO:\\tshowing {url}')",
"def showImage(self, image): img_w, img_h = image.size scr_w, scr_h = self.winfo_screenwidth(), self.winfo_screenheight() width,",
"lambda e: slideShow.destroy()) # slideShow.bind_all(\"<Return>\", lambda e: slideShow.window.nexti()) # exit on esc slideShow.update()",
"image scaled_w, scaled_h = image.size self.wm_geometry(\"{}x{}+{}+{}\".format(scaled_w,scaled_h,0,0)) # create new image self.persistent_image = ImageTk.PhotoImage(image)",
"as background image self.label = tk.Label(self) self.label.pack(side=\"top\", fill=\"both\", expand=True) def cycle(self): while True:",
"while True: self.nexti() time.sleep(0.01) def nexti(self): # import random # url = random.choice(urls)",
"root window #as small as possible but still \"focused\" #enabling us to use",
"f: config = json.load(f) host = config['host'] usr = config['user'] pwd = config['password']",
"# self.overrideredirect(True) #save reference to photo so that garbage collection #does not clear",
"'https://tpc.googlesyndication.com/simgad/3767484695346986263' ] class HiddenRoot(tk.Tk): def __init__(self): tk.Tk.__init__(self) #hackish way, essentially makes root window",
"[ 'https://cdn.revjet.com/s3/csp/1578955925683/shine.png', 'https://cdn.revjet.com/s3/csp/1578955925683/logo.svg', 'https://tpc.googlesyndication.com/daca_images/simgad/13865403217536204307', 'https://tpc.googlesyndication.com/daca_images/simgad/1948022358329940732?sqp=4sqPyQSWAUKTAQgAEhQNzczMPhUAAABAHQAAAAAlAAAAABgAIgoNAACAPxUAAIA_Kk8IWhABHQAAtEIgASgBMAY4A0CAwtcvSABQAFgAYFpwAngAgAEAiAEAkAEAnQEAAIA_oAEAqAEAsAGAreIEuAH___________8BxQEtsp0-MhoIvwMQ6gEYASABLQAAAD8wvwM46gFFAACAPw&rs=AOga4qmwNN2g28c_J8ehXFAoY4bOr7naGQ', 'https://tpc.googlesyndication.com/simgad/12366423408132574325', 'https://tpc.googlesyndication.com/simgad/3767484695346986263' ] class HiddenRoot(tk.Tk): def __init__(self): tk.Tk.__init__(self)",
"img_w), min(scr_h, img_h) image.thumbnail((width, height), Image.ANTIALIAS) #set window size after scaling the original",
"= self.mq.read() if url: try: img = Image.open(BytesIO(urlopen(url).read())) self.showImage(img) print(f'INFO:\\tshowing {url}') except Exception:",
"except Exception: print(f'ERROR:\\tnot a valid image: {url}') else: print('INFO:\\tQueue is empty') time.sleep(1.0) def",
"**kwargs): tk.Toplevel.__init__(self, *args, **kwargs) with open('reader_config.json', 'r') as f: config = json.load(f) host",
"fit screen #removes the border on the image scaled_w, scaled_h = image.size self.wm_geometry(\"{}x{}+{}+{}\".format(scaled_w,scaled_h,0,0))",
"decorations # self.overrideredirect(True) #save reference to photo so that garbage collection #does not",
"time import tkinter as tk from PIL import Image, ImageTk import json from",
"= [ 'https://cdn.revjet.com/s3/csp/1578955925683/shine.png', 'https://cdn.revjet.com/s3/csp/1578955925683/logo.svg', 'https://tpc.googlesyndication.com/daca_images/simgad/13865403217536204307', 'https://tpc.googlesyndication.com/daca_images/simgad/1948022358329940732?sqp=4sqPyQSWAUKTAQgAEhQNzczMPhUAAABAHQAAAAAlAAAAABgAIgoNAACAPxUAAIA_Kk8IWhABHQAAtEIgASgBMAY4A0CAwtcvSABQAFgAYFpwAngAgAEAiAEAkAEAnQEAAIA_oAEAqAEAsAGAreIEuAH___________8BxQEtsp0-MhoIvwMQ6gEYASABLQAAAD8wvwM46gFFAACAPw&rs=AOga4qmwNN2g28c_J8ehXFAoY4bOr7naGQ', 'https://tpc.googlesyndication.com/simgad/12366423408132574325', 'https://tpc.googlesyndication.com/simgad/3767484695346986263' ] class HiddenRoot(tk.Tk): def __init__(self):",
"from io import BytesIO import time import tkinter as tk from PIL import",
"config = json.load(f) host = config['host'] usr = config['user'] pwd = config['password'] queue",
"= config['user'] pwd = config['password'] queue = config['filtered_images_queue_name'] self.mq = RMQiface(host, queue, usr,",
"the border on the image scaled_w, scaled_h = image.size self.wm_geometry(\"{}x{}+{}+{}\".format(scaled_w,scaled_h,0,0)) # create new",
"'https://cdn.revjet.com/s3/csp/1578955925683/shine.png', 'https://cdn.revjet.com/s3/csp/1578955925683/logo.svg', 'https://tpc.googlesyndication.com/daca_images/simgad/13865403217536204307', 'https://tpc.googlesyndication.com/daca_images/simgad/1948022358329940732?sqp=4sqPyQSWAUKTAQgAEhQNzczMPhUAAABAHQAAAAAlAAAAABgAIgoNAACAPxUAAIA_Kk8IWhABHQAAtEIgASgBMAY4A0CAwtcvSABQAFgAYFpwAngAgAEAiAEAkAEAnQEAAIA_oAEAqAEAsAGAreIEuAH___________8BxQEtsp0-MhoIvwMQ6gEYASABLQAAAD8wvwM46gFFAACAPw&rs=AOga4qmwNN2g28c_J8ehXFAoY4bOr7naGQ', 'https://tpc.googlesyndication.com/simgad/12366423408132574325', 'https://tpc.googlesyndication.com/simgad/3767484695346986263' ] class HiddenRoot(tk.Tk): def __init__(self): tk.Tk.__init__(self) #hackish",
"small as possible but still \"focused\" #enabling us to use the binding on",
"True: self.nexti() time.sleep(0.01) def nexti(self): # import random # url = random.choice(urls) url",
"to use the binding on <esc> self.wm_geometry(\"0x0+0+0\") self.window = MySlideShow(self) self.window.cycle() class MySlideShow(tk.Toplevel):",
"'https://cdn.revjet.com/s3/csp/1578955925683/logo.svg', 'https://tpc.googlesyndication.com/daca_images/simgad/13865403217536204307', 'https://tpc.googlesyndication.com/daca_images/simgad/1948022358329940732?sqp=4sqPyQSWAUKTAQgAEhQNzczMPhUAAABAHQAAAAAlAAAAABgAIgoNAACAPxUAAIA_Kk8IWhABHQAAtEIgASgBMAY4A0CAwtcvSABQAFgAYFpwAngAgAEAiAEAkAEAnQEAAIA_oAEAqAEAsAGAreIEuAH___________8BxQEtsp0-MhoIvwMQ6gEYASABLQAAAD8wvwM46gFFAACAPw&rs=AOga4qmwNN2g28c_J8ehXFAoY4bOr7naGQ', 'https://tpc.googlesyndication.com/simgad/12366423408132574325', 'https://tpc.googlesyndication.com/simgad/3767484695346986263' ] class HiddenRoot(tk.Tk): def __init__(self): tk.Tk.__init__(self) #hackish way,",
"Exception: print(f'ERROR:\\tnot a valid image: {url}') else: print('INFO:\\tQueue is empty') time.sleep(1.0) def showImage(self,",
"self.winfo_screenwidth(), self.winfo_screenheight() width, height = min(scr_w, img_w), min(scr_h, img_h) image.thumbnail((width, height), Image.ANTIALIAS) #set",
"image.size self.wm_geometry(\"{}x{}+{}+{}\".format(scaled_w,scaled_h,0,0)) # create new image self.persistent_image = ImageTk.PhotoImage(image) self.label.configure(image=self.persistent_image) self.update() slideShow =",
"= [] self.pixNum = 0 #used to display as background image self.label =",
"config['user'] pwd = config['password'] queue = config['filtered_images_queue_name'] self.mq = RMQiface(host, queue, usr, pwd)",
"queue, usr, pwd) self.img_error = Image.open('error.png') self.img_none = Image.open('none.png') #remove window decorations #",
"print(f'ERROR:\\tnot a valid image: {url}') else: print('INFO:\\tQueue is empty') time.sleep(1.0) def showImage(self, image):",
"# slideShow.window.attributes('-topmost', True) slideShow.bind_all(\"<Escape>\", lambda e: slideShow.destroy()) # slideShow.bind_all(\"<Return>\", lambda e: slideShow.window.nexti()) #",
"= Image.open(BytesIO(urlopen(url).read())) self.showImage(img) print(f'INFO:\\tshowing {url}') except Exception: print(f'ERROR:\\tnot a valid image: {url}') else:",
"io import BytesIO import time import tkinter as tk from PIL import Image,",
"import json from rmq import RMQiface urls = [ 'https://cdn.revjet.com/s3/csp/1578955925683/shine.png', 'https://cdn.revjet.com/s3/csp/1578955925683/logo.svg', 'https://tpc.googlesyndication.com/daca_images/simgad/13865403217536204307', 'https://tpc.googlesyndication.com/daca_images/simgad/1948022358329940732?sqp=4sqPyQSWAUKTAQgAEhQNzczMPhUAAABAHQAAAAAlAAAAABgAIgoNAACAPxUAAIA_Kk8IWhABHQAAtEIgASgBMAY4A0CAwtcvSABQAFgAYFpwAngAgAEAiAEAkAEAnQEAAIA_oAEAqAEAsAGAreIEuAH___________8BxQEtsp0-MhoIvwMQ6gEYASABLQAAAD8wvwM46gFFAACAPw&rs=AOga4qmwNN2g28c_J8ehXFAoY4bOr7naGQ',",
"on the image scaled_w, scaled_h = image.size self.wm_geometry(\"{}x{}+{}+{}\".format(scaled_w,scaled_h,0,0)) # create new image self.persistent_image",
"collection #does not clear image variable in show_image() self.persistent_image = None self.imageList =",
"{url}') else: print('INFO:\\tQueue is empty') time.sleep(1.0) def showImage(self, image): img_w, img_h = image.size",
"window #as small as possible but still \"focused\" #enabling us to use the",
"= Image.open('error.png') self.img_none = Image.open('none.png') #remove window decorations # self.overrideredirect(True) #save reference to",
"as f: config = json.load(f) host = config['host'] usr = config['user'] pwd =",
"ImageTk.PhotoImage(image) self.label.configure(image=self.persistent_image) self.update() slideShow = HiddenRoot() # slideShow.window.attributes('-fullscreen', True) # slideShow.window.attributes('-topmost', True) slideShow.bind_all(\"<Escape>\",",
"height), Image.ANTIALIAS) #set window size after scaling the original image up/down to fit",
"self.showImage(img) print(f'INFO:\\tshowing {url}') except Exception: print(f'ERROR:\\tnot a valid image: {url}') else: print('INFO:\\tQueue is",
"None self.imageList = [] self.pixNum = 0 #used to display as background image",
"#removes the border on the image scaled_w, scaled_h = image.size self.wm_geometry(\"{}x{}+{}+{}\".format(scaled_w,scaled_h,0,0)) # create",
"self.label = tk.Label(self) self.label.pack(side=\"top\", fill=\"both\", expand=True) def cycle(self): while True: self.nexti() time.sleep(0.01) def",
"self.mq.read() if url: try: img = Image.open(BytesIO(urlopen(url).read())) self.showImage(img) print(f'INFO:\\tshowing {url}') except Exception: print(f'ERROR:\\tnot",
"scaled_h = image.size self.wm_geometry(\"{}x{}+{}+{}\".format(scaled_w,scaled_h,0,0)) # create new image self.persistent_image = ImageTk.PhotoImage(image) self.label.configure(image=self.persistent_image) self.update()",
"in show_image() self.persistent_image = None self.imageList = [] self.pixNum = 0 #used to",
"clear image variable in show_image() self.persistent_image = None self.imageList = [] self.pixNum =",
"tkinter as tk from PIL import Image, ImageTk import json from rmq import",
"# create new image self.persistent_image = ImageTk.PhotoImage(image) self.label.configure(image=self.persistent_image) self.update() slideShow = HiddenRoot() #",
"img_h) image.thumbnail((width, height), Image.ANTIALIAS) #set window size after scaling the original image up/down",
"# import random # url = random.choice(urls) url = self.mq.read() if url: try:",
"window size after scaling the original image up/down to fit screen #removes the",
"#hackish way, essentially makes root window #as small as possible but still \"focused\"",
"image self.label = tk.Label(self) self.label.pack(side=\"top\", fill=\"both\", expand=True) def cycle(self): while True: self.nexti() time.sleep(0.01)",
"print(f'INFO:\\tshowing {url}') except Exception: print(f'ERROR:\\tnot a valid image: {url}') else: print('INFO:\\tQueue is empty')",
"import Image, ImageTk import json from rmq import RMQiface urls = [ 'https://cdn.revjet.com/s3/csp/1578955925683/shine.png',",
"pwd = config['password'] queue = config['filtered_images_queue_name'] self.mq = RMQiface(host, queue, usr, pwd) self.img_error",
"url: try: img = Image.open(BytesIO(urlopen(url).read())) self.showImage(img) print(f'INFO:\\tshowing {url}') except Exception: print(f'ERROR:\\tnot a valid",
"{url}') except Exception: print(f'ERROR:\\tnot a valid image: {url}') else: print('INFO:\\tQueue is empty') time.sleep(1.0)",
"urllib.request import urlopen from io import BytesIO import time import tkinter as tk",
"#save reference to photo so that garbage collection #does not clear image variable",
"if url: try: img = Image.open(BytesIO(urlopen(url).read())) self.showImage(img) print(f'INFO:\\tshowing {url}') except Exception: print(f'ERROR:\\tnot a",
"True) # slideShow.window.attributes('-topmost', True) slideShow.bind_all(\"<Escape>\", lambda e: slideShow.destroy()) # slideShow.bind_all(\"<Return>\", lambda e: slideShow.window.nexti())",
"print('INFO:\\tQueue is empty') time.sleep(1.0) def showImage(self, image): img_w, img_h = image.size scr_w, scr_h",
"url = random.choice(urls) url = self.mq.read() if url: try: img = Image.open(BytesIO(urlopen(url).read())) self.showImage(img)",
"try: img = Image.open(BytesIO(urlopen(url).read())) self.showImage(img) print(f'INFO:\\tshowing {url}') except Exception: print(f'ERROR:\\tnot a valid image:",
"to fit screen #removes the border on the image scaled_w, scaled_h = image.size",
"tk.Toplevel.__init__(self, *args, **kwargs) with open('reader_config.json', 'r') as f: config = json.load(f) host =",
"the original image up/down to fit screen #removes the border on the image",
"config['password'] queue = config['filtered_images_queue_name'] self.mq = RMQiface(host, queue, usr, pwd) self.img_error = Image.open('error.png')",
"image up/down to fit screen #removes the border on the image scaled_w, scaled_h",
"= random.choice(urls) url = self.mq.read() if url: try: img = Image.open(BytesIO(urlopen(url).read())) self.showImage(img) print(f'INFO:\\tshowing",
"reference to photo so that garbage collection #does not clear image variable in",
"import tkinter as tk from PIL import Image, ImageTk import json from rmq",
"image self.persistent_image = ImageTk.PhotoImage(image) self.label.configure(image=self.persistent_image) self.update() slideShow = HiddenRoot() # slideShow.window.attributes('-fullscreen', True) #",
"to display as background image self.label = tk.Label(self) self.label.pack(side=\"top\", fill=\"both\", expand=True) def cycle(self):",
"PIL import Image, ImageTk import json from rmq import RMQiface urls = [",
"self.window = MySlideShow(self) self.window.cycle() class MySlideShow(tk.Toplevel): def __init__(self, *args, **kwargs): tk.Toplevel.__init__(self, *args, **kwargs)",
"self.update() slideShow = HiddenRoot() # slideShow.window.attributes('-fullscreen', True) # slideShow.window.attributes('-topmost', True) slideShow.bind_all(\"<Escape>\", lambda e:",
"config['filtered_images_queue_name'] self.mq = RMQiface(host, queue, usr, pwd) self.img_error = Image.open('error.png') self.img_none = Image.open('none.png')",
"ImageTk import json from rmq import RMQiface urls = [ 'https://cdn.revjet.com/s3/csp/1578955925683/shine.png', 'https://cdn.revjet.com/s3/csp/1578955925683/logo.svg', 'https://tpc.googlesyndication.com/daca_images/simgad/13865403217536204307',",
"#remove window decorations # self.overrideredirect(True) #save reference to photo so that garbage collection",
"def nexti(self): # import random # url = random.choice(urls) url = self.mq.read() if",
"is empty') time.sleep(1.0) def showImage(self, image): img_w, img_h = image.size scr_w, scr_h =",
"self.wm_geometry(\"{}x{}+{}+{}\".format(scaled_w,scaled_h,0,0)) # create new image self.persistent_image = ImageTk.PhotoImage(image) self.label.configure(image=self.persistent_image) self.update() slideShow = HiddenRoot()",
"image: {url}') else: print('INFO:\\tQueue is empty') time.sleep(1.0) def showImage(self, image): img_w, img_h =",
"'r') as f: config = json.load(f) host = config['host'] usr = config['user'] pwd",
"def __init__(self): tk.Tk.__init__(self) #hackish way, essentially makes root window #as small as possible",
"cycle(self): while True: self.nexti() time.sleep(0.01) def nexti(self): # import random # url =",
"slideShow.window.attributes('-topmost', True) slideShow.bind_all(\"<Escape>\", lambda e: slideShow.destroy()) # slideShow.bind_all(\"<Return>\", lambda e: slideShow.window.nexti()) # exit",
"True) slideShow.bind_all(\"<Escape>\", lambda e: slideShow.destroy()) # slideShow.bind_all(\"<Return>\", lambda e: slideShow.window.nexti()) # exit on",
"possible but still \"focused\" #enabling us to use the binding on <esc> self.wm_geometry(\"0x0+0+0\")",
"\"focused\" #enabling us to use the binding on <esc> self.wm_geometry(\"0x0+0+0\") self.window = MySlideShow(self)",
"so that garbage collection #does not clear image variable in show_image() self.persistent_image =",
"self.label.configure(image=self.persistent_image) self.update() slideShow = HiddenRoot() # slideShow.window.attributes('-fullscreen', True) # slideShow.window.attributes('-topmost', True) slideShow.bind_all(\"<Escape>\", lambda",
"# url = random.choice(urls) url = self.mq.read() if url: try: img = Image.open(BytesIO(urlopen(url).read()))",
"size after scaling the original image up/down to fit screen #removes the border",
"Image.ANTIALIAS) #set window size after scaling the original image up/down to fit screen",
"url = self.mq.read() if url: try: img = Image.open(BytesIO(urlopen(url).read())) self.showImage(img) print(f'INFO:\\tshowing {url}') except",
"*args, **kwargs) with open('reader_config.json', 'r') as f: config = json.load(f) host = config['host']",
"self.imageList = [] self.pixNum = 0 #used to display as background image self.label",
"slideShow.bind_all(\"<Escape>\", lambda e: slideShow.destroy()) # slideShow.bind_all(\"<Return>\", lambda e: slideShow.window.nexti()) # exit on esc",
"pwd) self.img_error = Image.open('error.png') self.img_none = Image.open('none.png') #remove window decorations # self.overrideredirect(True) #save",
"# slideShow.window.attributes('-fullscreen', True) # slideShow.window.attributes('-topmost', True) slideShow.bind_all(\"<Escape>\", lambda e: slideShow.destroy()) # slideShow.bind_all(\"<Return>\", lambda",
"img_h = image.size scr_w, scr_h = self.winfo_screenwidth(), self.winfo_screenheight() width, height = min(scr_w, img_w),",
"self.label.pack(side=\"top\", fill=\"both\", expand=True) def cycle(self): while True: self.nexti() time.sleep(0.01) def nexti(self): # import",
"self.nexti() time.sleep(0.01) def nexti(self): # import random # url = random.choice(urls) url =",
"screen #removes the border on the image scaled_w, scaled_h = image.size self.wm_geometry(\"{}x{}+{}+{}\".format(scaled_w,scaled_h,0,0)) #",
"'https://tpc.googlesyndication.com/simgad/12366423408132574325', 'https://tpc.googlesyndication.com/simgad/3767484695346986263' ] class HiddenRoot(tk.Tk): def __init__(self): tk.Tk.__init__(self) #hackish way, essentially makes root",
"#used to display as background image self.label = tk.Label(self) self.label.pack(side=\"top\", fill=\"both\", expand=True) def",
"= ImageTk.PhotoImage(image) self.label.configure(image=self.persistent_image) self.update() slideShow = HiddenRoot() # slideShow.window.attributes('-fullscreen', True) # slideShow.window.attributes('-topmost', True)",
"tk.Tk.__init__(self) #hackish way, essentially makes root window #as small as possible but still",
"open('reader_config.json', 'r') as f: config = json.load(f) host = config['host'] usr = config['user']",
"essentially makes root window #as small as possible but still \"focused\" #enabling us"
] |
[
"src.core.actions.executable import _validate_pattern from src.core.models import ActionExecution from src.core.px_git import checkout_new_branch from src.core.px_questionary",
"self.parameters.source affix = self.parameters.affix pattern = self.parameters.pattern _validate_pattern(source.pattern, source.name, \"Source name invalid\") _validate_pattern(pattern,",
"checkout_new_branch from src.core.px_questionary import confirm from src.core.template_models import Branch, Affix, Pattern @dataclass class",
"from src.core.template_models import Branch, Affix, Pattern @dataclass class CreateBranchParameters: name: str source: Branch",
"from src.core.px_git import checkout_new_branch from src.core.px_questionary import confirm from src.core.template_models import Branch, Affix,",
"[name] if affix.prefix: final_name = affix.prefix + final_name name = affix.join_char.join(final_name) if affix.suffix:",
"from src.core.actions.executable import Executable from src.core.actions.executable import _validate_pattern from src.core.models import ActionExecution from",
"src.core.actions.executable import Executable from src.core.actions.executable import _validate_pattern from src.core.models import ActionExecution from src.core.px_git",
"self.action_execution.parameters self.parameters = CreateBranchParameters( name=action_parameters.get(\"name\", \"\"), source=Branch(action_parameters.get(\"source\", {})), affix=Affix(action_parameters.get(\"affix\", {})), pattern=Pattern(action_parameters.get(\"pattern\", {})), )",
"= self.parameters.name source = self.parameters.source affix = self.parameters.affix pattern = self.parameters.pattern _validate_pattern(source.pattern, source.name,",
"name invalid\") _validate_pattern(pattern, name, \"Name invalid\") if affix: final_name = [name] if affix.prefix:",
"_validate_pattern(pattern, name, \"Name invalid\") if affix: final_name = [name] if affix.prefix: final_name =",
"Branch, Affix, Pattern @dataclass class CreateBranchParameters: name: str source: Branch affix: Affix pattern:",
"action_parameters = self.action_execution.parameters self.parameters = CreateBranchParameters( name=action_parameters.get(\"name\", \"\"), source=Branch(action_parameters.get(\"source\", {})), affix=Affix(action_parameters.get(\"affix\", {})), pattern=Pattern(action_parameters.get(\"pattern\",",
"= affix.prefix + final_name name = affix.join_char.join(final_name) if affix.suffix: final_name.extend(affix.suffix) name = affix.join_char.join(final_name)",
"execute(self): name = self.parameters.name source = self.parameters.source affix = self.parameters.affix pattern = self.parameters.pattern",
"source = self.parameters.source affix = self.parameters.affix pattern = self.parameters.pattern _validate_pattern(source.pattern, source.name, \"Source name",
"= affix.join_char.join(final_name) confirmed = confirm( msg=f\"Você confirma a criação da \" f\"branch {name}",
"import Branch, Affix, Pattern @dataclass class CreateBranchParameters: name: str source: Branch affix: Affix",
"import _validate_pattern from src.core.models import ActionExecution from src.core.px_git import checkout_new_branch from src.core.px_questionary import",
"msg=f\"Você confirma a criação da \" f\"branch {name} com base na \" f\"branch",
"= self.parameters.affix pattern = self.parameters.pattern _validate_pattern(source.pattern, source.name, \"Source name invalid\") _validate_pattern(pattern, name, \"Name",
"import Executable from src.core.actions.executable import _validate_pattern from src.core.models import ActionExecution from src.core.px_git import",
"<filename>src/core/actions/create_branch.py from dataclasses import dataclass from src.core.actions.executable import Executable from src.core.actions.executable import _validate_pattern",
"\"Name invalid\") if affix: final_name = [name] if affix.prefix: final_name = affix.prefix +",
"source=Branch(action_parameters.get(\"source\", {})), affix=Affix(action_parameters.get(\"affix\", {})), pattern=Pattern(action_parameters.get(\"pattern\", {})), ) def execute(self): name = self.parameters.name source",
"ActionExecution): super().__init__(action_execution) action_parameters = self.action_execution.parameters self.parameters = CreateBranchParameters( name=action_parameters.get(\"name\", \"\"), source=Branch(action_parameters.get(\"source\", {})), affix=Affix(action_parameters.get(\"affix\",",
"affix.join_char.join(final_name) if affix.suffix: final_name.extend(affix.suffix) name = affix.join_char.join(final_name) confirmed = confirm( msg=f\"Você confirma a",
"= affix.join_char.join(final_name) if affix.suffix: final_name.extend(affix.suffix) name = affix.join_char.join(final_name) confirmed = confirm( msg=f\"Você confirma",
"invalid\") if affix: final_name = [name] if affix.prefix: final_name = affix.prefix + final_name",
"Executable from src.core.actions.executable import _validate_pattern from src.core.models import ActionExecution from src.core.px_git import checkout_new_branch",
"name=action_parameters.get(\"name\", \"\"), source=Branch(action_parameters.get(\"source\", {})), affix=Affix(action_parameters.get(\"affix\", {})), pattern=Pattern(action_parameters.get(\"pattern\", {})), ) def execute(self): name =",
"Branch affix: Affix pattern: Pattern class CreateBranch(Executable): parameters: CreateBranchParameters def __init__(self, action_execution: ActionExecution):",
"src.core.px_git import checkout_new_branch from src.core.px_questionary import confirm from src.core.template_models import Branch, Affix, Pattern",
"src.core.models import ActionExecution from src.core.px_git import checkout_new_branch from src.core.px_questionary import confirm from src.core.template_models",
"import confirm from src.core.template_models import Branch, Affix, Pattern @dataclass class CreateBranchParameters: name: str",
"confirm from src.core.template_models import Branch, Affix, Pattern @dataclass class CreateBranchParameters: name: str source:",
"= self.parameters.source affix = self.parameters.affix pattern = self.parameters.pattern _validate_pattern(source.pattern, source.name, \"Source name invalid\")",
"f\"branch {name} com base na \" f\"branch {source.name}?\" ) if confirmed: checkout_new_branch(source=source.name, branch=name)",
"dataclasses import dataclass from src.core.actions.executable import Executable from src.core.actions.executable import _validate_pattern from src.core.models",
"+ final_name name = affix.join_char.join(final_name) if affix.suffix: final_name.extend(affix.suffix) name = affix.join_char.join(final_name) confirmed =",
"invalid\") _validate_pattern(pattern, name, \"Name invalid\") if affix: final_name = [name] if affix.prefix: final_name",
"import checkout_new_branch from src.core.px_questionary import confirm from src.core.template_models import Branch, Affix, Pattern @dataclass",
"ActionExecution from src.core.px_git import checkout_new_branch from src.core.px_questionary import confirm from src.core.template_models import Branch,",
"import ActionExecution from src.core.px_git import checkout_new_branch from src.core.px_questionary import confirm from src.core.template_models import",
"affix: Affix pattern: Pattern class CreateBranch(Executable): parameters: CreateBranchParameters def __init__(self, action_execution: ActionExecution): super().__init__(action_execution)",
") def execute(self): name = self.parameters.name source = self.parameters.source affix = self.parameters.affix pattern",
"dataclass from src.core.actions.executable import Executable from src.core.actions.executable import _validate_pattern from src.core.models import ActionExecution",
"\"Source name invalid\") _validate_pattern(pattern, name, \"Name invalid\") if affix: final_name = [name] if",
"CreateBranchParameters: name: str source: Branch affix: Affix pattern: Pattern class CreateBranch(Executable): parameters: CreateBranchParameters",
"__init__(self, action_execution: ActionExecution): super().__init__(action_execution) action_parameters = self.action_execution.parameters self.parameters = CreateBranchParameters( name=action_parameters.get(\"name\", \"\"), source=Branch(action_parameters.get(\"source\",",
"confirm( msg=f\"Você confirma a criação da \" f\"branch {name} com base na \"",
"Pattern class CreateBranch(Executable): parameters: CreateBranchParameters def __init__(self, action_execution: ActionExecution): super().__init__(action_execution) action_parameters = self.action_execution.parameters",
"final_name = affix.prefix + final_name name = affix.join_char.join(final_name) if affix.suffix: final_name.extend(affix.suffix) name =",
"Affix pattern: Pattern class CreateBranch(Executable): parameters: CreateBranchParameters def __init__(self, action_execution: ActionExecution): super().__init__(action_execution) action_parameters",
"from src.core.models import ActionExecution from src.core.px_git import checkout_new_branch from src.core.px_questionary import confirm from",
"a criação da \" f\"branch {name} com base na \" f\"branch {source.name}?\" )",
"super().__init__(action_execution) action_parameters = self.action_execution.parameters self.parameters = CreateBranchParameters( name=action_parameters.get(\"name\", \"\"), source=Branch(action_parameters.get(\"source\", {})), affix=Affix(action_parameters.get(\"affix\", {})),",
"\"\"), source=Branch(action_parameters.get(\"source\", {})), affix=Affix(action_parameters.get(\"affix\", {})), pattern=Pattern(action_parameters.get(\"pattern\", {})), ) def execute(self): name = self.parameters.name",
"{})), pattern=Pattern(action_parameters.get(\"pattern\", {})), ) def execute(self): name = self.parameters.name source = self.parameters.source affix",
"def __init__(self, action_execution: ActionExecution): super().__init__(action_execution) action_parameters = self.action_execution.parameters self.parameters = CreateBranchParameters( name=action_parameters.get(\"name\", \"\"),",
"affix.prefix: final_name = affix.prefix + final_name name = affix.join_char.join(final_name) if affix.suffix: final_name.extend(affix.suffix) name",
"= confirm( msg=f\"Você confirma a criação da \" f\"branch {name} com base na",
"affix.join_char.join(final_name) confirmed = confirm( msg=f\"Você confirma a criação da \" f\"branch {name} com",
"src.core.px_questionary import confirm from src.core.template_models import Branch, Affix, Pattern @dataclass class CreateBranchParameters: name:",
"CreateBranch(Executable): parameters: CreateBranchParameters def __init__(self, action_execution: ActionExecution): super().__init__(action_execution) action_parameters = self.action_execution.parameters self.parameters =",
"affix = self.parameters.affix pattern = self.parameters.pattern _validate_pattern(source.pattern, source.name, \"Source name invalid\") _validate_pattern(pattern, name,",
"{})), ) def execute(self): name = self.parameters.name source = self.parameters.source affix = self.parameters.affix",
"from src.core.actions.executable import _validate_pattern from src.core.models import ActionExecution from src.core.px_git import checkout_new_branch from",
"CreateBranchParameters( name=action_parameters.get(\"name\", \"\"), source=Branch(action_parameters.get(\"source\", {})), affix=Affix(action_parameters.get(\"affix\", {})), pattern=Pattern(action_parameters.get(\"pattern\", {})), ) def execute(self): name",
"if affix.suffix: final_name.extend(affix.suffix) name = affix.join_char.join(final_name) confirmed = confirm( msg=f\"Você confirma a criação",
"name: str source: Branch affix: Affix pattern: Pattern class CreateBranch(Executable): parameters: CreateBranchParameters def",
"final_name = [name] if affix.prefix: final_name = affix.prefix + final_name name = affix.join_char.join(final_name)",
"pattern=Pattern(action_parameters.get(\"pattern\", {})), ) def execute(self): name = self.parameters.name source = self.parameters.source affix =",
"parameters: CreateBranchParameters def __init__(self, action_execution: ActionExecution): super().__init__(action_execution) action_parameters = self.action_execution.parameters self.parameters = CreateBranchParameters(",
"from dataclasses import dataclass from src.core.actions.executable import Executable from src.core.actions.executable import _validate_pattern from",
"= self.action_execution.parameters self.parameters = CreateBranchParameters( name=action_parameters.get(\"name\", \"\"), source=Branch(action_parameters.get(\"source\", {})), affix=Affix(action_parameters.get(\"affix\", {})), pattern=Pattern(action_parameters.get(\"pattern\", {})),",
"= self.parameters.pattern _validate_pattern(source.pattern, source.name, \"Source name invalid\") _validate_pattern(pattern, name, \"Name invalid\") if affix:",
"CreateBranchParameters def __init__(self, action_execution: ActionExecution): super().__init__(action_execution) action_parameters = self.action_execution.parameters self.parameters = CreateBranchParameters( name=action_parameters.get(\"name\",",
"src.core.template_models import Branch, Affix, Pattern @dataclass class CreateBranchParameters: name: str source: Branch affix:",
"confirma a criação da \" f\"branch {name} com base na \" f\"branch {source.name}?\"",
"name, \"Name invalid\") if affix: final_name = [name] if affix.prefix: final_name = affix.prefix",
"affix.suffix: final_name.extend(affix.suffix) name = affix.join_char.join(final_name) confirmed = confirm( msg=f\"Você confirma a criação da",
"= CreateBranchParameters( name=action_parameters.get(\"name\", \"\"), source=Branch(action_parameters.get(\"source\", {})), affix=Affix(action_parameters.get(\"affix\", {})), pattern=Pattern(action_parameters.get(\"pattern\", {})), ) def execute(self):",
"Pattern @dataclass class CreateBranchParameters: name: str source: Branch affix: Affix pattern: Pattern class",
"pattern = self.parameters.pattern _validate_pattern(source.pattern, source.name, \"Source name invalid\") _validate_pattern(pattern, name, \"Name invalid\") if",
"@dataclass class CreateBranchParameters: name: str source: Branch affix: Affix pattern: Pattern class CreateBranch(Executable):",
"_validate_pattern from src.core.models import ActionExecution from src.core.px_git import checkout_new_branch from src.core.px_questionary import confirm",
"name = self.parameters.name source = self.parameters.source affix = self.parameters.affix pattern = self.parameters.pattern _validate_pattern(source.pattern,",
"_validate_pattern(source.pattern, source.name, \"Source name invalid\") _validate_pattern(pattern, name, \"Name invalid\") if affix: final_name =",
"str source: Branch affix: Affix pattern: Pattern class CreateBranch(Executable): parameters: CreateBranchParameters def __init__(self,",
"import dataclass from src.core.actions.executable import Executable from src.core.actions.executable import _validate_pattern from src.core.models import",
"self.parameters.name source = self.parameters.source affix = self.parameters.affix pattern = self.parameters.pattern _validate_pattern(source.pattern, source.name, \"Source",
"criação da \" f\"branch {name} com base na \" f\"branch {source.name}?\" ) if",
"from src.core.px_questionary import confirm from src.core.template_models import Branch, Affix, Pattern @dataclass class CreateBranchParameters:",
"affix: final_name = [name] if affix.prefix: final_name = affix.prefix + final_name name =",
"def execute(self): name = self.parameters.name source = self.parameters.source affix = self.parameters.affix pattern =",
"name = affix.join_char.join(final_name) confirmed = confirm( msg=f\"Você confirma a criação da \" f\"branch",
"self.parameters.pattern _validate_pattern(source.pattern, source.name, \"Source name invalid\") _validate_pattern(pattern, name, \"Name invalid\") if affix: final_name",
"affix=Affix(action_parameters.get(\"affix\", {})), pattern=Pattern(action_parameters.get(\"pattern\", {})), ) def execute(self): name = self.parameters.name source = self.parameters.source",
"name = affix.join_char.join(final_name) if affix.suffix: final_name.extend(affix.suffix) name = affix.join_char.join(final_name) confirmed = confirm( msg=f\"Você",
"action_execution: ActionExecution): super().__init__(action_execution) action_parameters = self.action_execution.parameters self.parameters = CreateBranchParameters( name=action_parameters.get(\"name\", \"\"), source=Branch(action_parameters.get(\"source\", {})),",
"if affix.prefix: final_name = affix.prefix + final_name name = affix.join_char.join(final_name) if affix.suffix: final_name.extend(affix.suffix)",
"{})), affix=Affix(action_parameters.get(\"affix\", {})), pattern=Pattern(action_parameters.get(\"pattern\", {})), ) def execute(self): name = self.parameters.name source =",
"final_name.extend(affix.suffix) name = affix.join_char.join(final_name) confirmed = confirm( msg=f\"Você confirma a criação da \"",
"confirmed = confirm( msg=f\"Você confirma a criação da \" f\"branch {name} com base",
"self.parameters = CreateBranchParameters( name=action_parameters.get(\"name\", \"\"), source=Branch(action_parameters.get(\"source\", {})), affix=Affix(action_parameters.get(\"affix\", {})), pattern=Pattern(action_parameters.get(\"pattern\", {})), ) def",
"self.parameters.affix pattern = self.parameters.pattern _validate_pattern(source.pattern, source.name, \"Source name invalid\") _validate_pattern(pattern, name, \"Name invalid\")",
"= [name] if affix.prefix: final_name = affix.prefix + final_name name = affix.join_char.join(final_name) if",
"da \" f\"branch {name} com base na \" f\"branch {source.name}?\" ) if confirmed:",
"Affix, Pattern @dataclass class CreateBranchParameters: name: str source: Branch affix: Affix pattern: Pattern",
"pattern: Pattern class CreateBranch(Executable): parameters: CreateBranchParameters def __init__(self, action_execution: ActionExecution): super().__init__(action_execution) action_parameters =",
"if affix: final_name = [name] if affix.prefix: final_name = affix.prefix + final_name name",
"class CreateBranchParameters: name: str source: Branch affix: Affix pattern: Pattern class CreateBranch(Executable): parameters:",
"source: Branch affix: Affix pattern: Pattern class CreateBranch(Executable): parameters: CreateBranchParameters def __init__(self, action_execution:",
"final_name name = affix.join_char.join(final_name) if affix.suffix: final_name.extend(affix.suffix) name = affix.join_char.join(final_name) confirmed = confirm(",
"affix.prefix + final_name name = affix.join_char.join(final_name) if affix.suffix: final_name.extend(affix.suffix) name = affix.join_char.join(final_name) confirmed",
"class CreateBranch(Executable): parameters: CreateBranchParameters def __init__(self, action_execution: ActionExecution): super().__init__(action_execution) action_parameters = self.action_execution.parameters self.parameters",
"source.name, \"Source name invalid\") _validate_pattern(pattern, name, \"Name invalid\") if affix: final_name = [name]",
"\" f\"branch {name} com base na \" f\"branch {source.name}?\" ) if confirmed: checkout_new_branch(source=source.name,"
] |
[
".models import Artigo, Comentario class ArtigoForm(forms.ModelForm): class Meta: model = Artigo fields =",
"Artigo fields = ('titulo', 'texto',) class ComentarioForm(forms.ModelForm): class Meta: model = Comentario fields",
"django import forms from .models import Artigo, Comentario class ArtigoForm(forms.ModelForm): class Meta: model",
"from .models import Artigo, Comentario class ArtigoForm(forms.ModelForm): class Meta: model = Artigo fields",
"<filename>01_mysite/blog/forms.py from django import forms from .models import Artigo, Comentario class ArtigoForm(forms.ModelForm): class",
"class ArtigoForm(forms.ModelForm): class Meta: model = Artigo fields = ('titulo', 'texto',) class ComentarioForm(forms.ModelForm):",
"class Meta: model = Artigo fields = ('titulo', 'texto',) class ComentarioForm(forms.ModelForm): class Meta:",
"import Artigo, Comentario class ArtigoForm(forms.ModelForm): class Meta: model = Artigo fields = ('titulo',",
"model = Artigo fields = ('titulo', 'texto',) class ComentarioForm(forms.ModelForm): class Meta: model =",
"= ('titulo', 'texto',) class ComentarioForm(forms.ModelForm): class Meta: model = Comentario fields = ('autor',",
"fields = ('titulo', 'texto',) class ComentarioForm(forms.ModelForm): class Meta: model = Comentario fields =",
"Meta: model = Artigo fields = ('titulo', 'texto',) class ComentarioForm(forms.ModelForm): class Meta: model",
"from django import forms from .models import Artigo, Comentario class ArtigoForm(forms.ModelForm): class Meta:",
"forms from .models import Artigo, Comentario class ArtigoForm(forms.ModelForm): class Meta: model = Artigo",
"= Artigo fields = ('titulo', 'texto',) class ComentarioForm(forms.ModelForm): class Meta: model = Comentario",
"import forms from .models import Artigo, Comentario class ArtigoForm(forms.ModelForm): class Meta: model =",
"ArtigoForm(forms.ModelForm): class Meta: model = Artigo fields = ('titulo', 'texto',) class ComentarioForm(forms.ModelForm): class",
"Artigo, Comentario class ArtigoForm(forms.ModelForm): class Meta: model = Artigo fields = ('titulo', 'texto',)",
"Comentario class ArtigoForm(forms.ModelForm): class Meta: model = Artigo fields = ('titulo', 'texto',) class",
"('titulo', 'texto',) class ComentarioForm(forms.ModelForm): class Meta: model = Comentario fields = ('autor', 'texto',)"
] |
[
"LICENSE file for more details. \"\"\"Resolvers common.\"\"\" def get_field_value_for_record(record_cls, record_pid, field_name): \"\"\"Return the",
"# -*- coding: utf-8 -*- # # Copyright (C) 2018-2019 CERN. # #",
"PID.\"\"\" record = record_cls.get_record_by_pid(record_pid) if not record or field_name not in record: message",
"a given record PID.\"\"\" record = record_cls.get_record_by_pid(record_pid) if not record or field_name not",
"# invenio-app-ils is free software; you can redistribute it and/or modify it #",
"free software; you can redistribute it and/or modify it # under the terms",
"\"\"\"Resolvers common.\"\"\" def get_field_value_for_record(record_cls, record_pid, field_name): \"\"\"Return the given field value for a",
"given field value for a given record PID.\"\"\" record = record_cls.get_record_by_pid(record_pid) if not",
"message = \"{0} not found in record {1}\".format(field_name, record_pid) raise KeyError(message) return record[field_name]",
"CERN. # # invenio-app-ils is free software; you can redistribute it and/or modify",
"under the terms of the MIT License; see LICENSE file for more details.",
"record = record_cls.get_record_by_pid(record_pid) if not record or field_name not in record: message =",
"or field_name not in record: message = \"{0} not found in record {1}\".format(field_name,",
"software; you can redistribute it and/or modify it # under the terms of",
"field_name): \"\"\"Return the given field value for a given record PID.\"\"\" record =",
"for a given record PID.\"\"\" record = record_cls.get_record_by_pid(record_pid) if not record or field_name",
"coding: utf-8 -*- # # Copyright (C) 2018-2019 CERN. # # invenio-app-ils is",
"the terms of the MIT License; see LICENSE file for more details. \"\"\"Resolvers",
"record PID.\"\"\" record = record_cls.get_record_by_pid(record_pid) if not record or field_name not in record:",
"not record or field_name not in record: message = \"{0} not found in",
"field_name not in record: message = \"{0} not found in record {1}\".format(field_name, record_pid)",
"value for a given record PID.\"\"\" record = record_cls.get_record_by_pid(record_pid) if not record or",
"Copyright (C) 2018-2019 CERN. # # invenio-app-ils is free software; you can redistribute",
"2018-2019 CERN. # # invenio-app-ils is free software; you can redistribute it and/or",
"of the MIT License; see LICENSE file for more details. \"\"\"Resolvers common.\"\"\" def",
"record or field_name not in record: message = \"{0} not found in record",
"-*- # # Copyright (C) 2018-2019 CERN. # # invenio-app-ils is free software;",
"License; see LICENSE file for more details. \"\"\"Resolvers common.\"\"\" def get_field_value_for_record(record_cls, record_pid, field_name):",
"more details. \"\"\"Resolvers common.\"\"\" def get_field_value_for_record(record_cls, record_pid, field_name): \"\"\"Return the given field value",
"it and/or modify it # under the terms of the MIT License; see",
"invenio-app-ils is free software; you can redistribute it and/or modify it # under",
"given record PID.\"\"\" record = record_cls.get_record_by_pid(record_pid) if not record or field_name not in",
"-*- coding: utf-8 -*- # # Copyright (C) 2018-2019 CERN. # # invenio-app-ils",
"it # under the terms of the MIT License; see LICENSE file for",
"\"\"\"Return the given field value for a given record PID.\"\"\" record = record_cls.get_record_by_pid(record_pid)",
"common.\"\"\" def get_field_value_for_record(record_cls, record_pid, field_name): \"\"\"Return the given field value for a given",
"field value for a given record PID.\"\"\" record = record_cls.get_record_by_pid(record_pid) if not record",
"(C) 2018-2019 CERN. # # invenio-app-ils is free software; you can redistribute it",
"def get_field_value_for_record(record_cls, record_pid, field_name): \"\"\"Return the given field value for a given record",
"details. \"\"\"Resolvers common.\"\"\" def get_field_value_for_record(record_cls, record_pid, field_name): \"\"\"Return the given field value for",
"MIT License; see LICENSE file for more details. \"\"\"Resolvers common.\"\"\" def get_field_value_for_record(record_cls, record_pid,",
"in record: message = \"{0} not found in record {1}\".format(field_name, record_pid) raise KeyError(message)",
"see LICENSE file for more details. \"\"\"Resolvers common.\"\"\" def get_field_value_for_record(record_cls, record_pid, field_name): \"\"\"Return",
"for more details. \"\"\"Resolvers common.\"\"\" def get_field_value_for_record(record_cls, record_pid, field_name): \"\"\"Return the given field",
"if not record or field_name not in record: message = \"{0} not found",
"redistribute it and/or modify it # under the terms of the MIT License;",
"not in record: message = \"{0} not found in record {1}\".format(field_name, record_pid) raise",
"file for more details. \"\"\"Resolvers common.\"\"\" def get_field_value_for_record(record_cls, record_pid, field_name): \"\"\"Return the given",
"= record_cls.get_record_by_pid(record_pid) if not record or field_name not in record: message = \"{0}",
"and/or modify it # under the terms of the MIT License; see LICENSE",
"# # invenio-app-ils is free software; you can redistribute it and/or modify it",
"record_cls.get_record_by_pid(record_pid) if not record or field_name not in record: message = \"{0} not",
"terms of the MIT License; see LICENSE file for more details. \"\"\"Resolvers common.\"\"\"",
"the given field value for a given record PID.\"\"\" record = record_cls.get_record_by_pid(record_pid) if",
"record: message = \"{0} not found in record {1}\".format(field_name, record_pid) raise KeyError(message) return",
"utf-8 -*- # # Copyright (C) 2018-2019 CERN. # # invenio-app-ils is free",
"you can redistribute it and/or modify it # under the terms of the",
"the MIT License; see LICENSE file for more details. \"\"\"Resolvers common.\"\"\" def get_field_value_for_record(record_cls,",
"# # Copyright (C) 2018-2019 CERN. # # invenio-app-ils is free software; you",
"is free software; you can redistribute it and/or modify it # under the",
"can redistribute it and/or modify it # under the terms of the MIT",
"# under the terms of the MIT License; see LICENSE file for more",
"modify it # under the terms of the MIT License; see LICENSE file",
"# Copyright (C) 2018-2019 CERN. # # invenio-app-ils is free software; you can",
"get_field_value_for_record(record_cls, record_pid, field_name): \"\"\"Return the given field value for a given record PID.\"\"\"",
"record_pid, field_name): \"\"\"Return the given field value for a given record PID.\"\"\" record",
"<filename>invenio_app_ils/records/resolver/resolver.py # -*- coding: utf-8 -*- # # Copyright (C) 2018-2019 CERN. #"
] |
[
"network in Network.objects.all(): _reserve_margin_addresses( network, network.reserved_from_beginning, network.reserved_from_end, IPAddress ) def remove_reserved_ips(apps, schema_editor): IPAddress",
"= IPAddress.objects.filter( models.Q( number__gte=network.min_ip + 1, number__lte=network.min_ip + bottom_count + 1 ) |",
"<reponame>DoNnMyTh/ralph<gh_stars>1000+ # -*- coding: utf-8 -*- from __future__ import unicode_literals import ipaddress from",
"status=IPADDRESS_STATUS_RESERVED )) print('Creating {} ips for {}'.format(len(ips), network)) IPAddress.objects.bulk_create(ips) ips_query.update(status=IPADDRESS_STATUS_RESERVED) def create_reserved_ips(apps, schema_editor):",
"ips for {}'.format(len(ips), network)) IPAddress.objects.bulk_create(ips) ips_query.update(status=IPADDRESS_STATUS_RESERVED) def create_reserved_ips(apps, schema_editor): IPAddress = apps.get_model('networks', 'IPAddress')",
"to be omitted in DHCP automatic assignmentcounted from the last IP in range",
"+ 1 ) | models.Q( number__gte=network.max_ip - top_count, number__lte=network.max_ip ) ) existing_ips =",
"def create_reserved_ips(apps, schema_editor): IPAddress = apps.get_model('networks', 'IPAddress') Network = apps.get_model('networks', 'Network') for network",
"= apps.get_model('networks', 'Network') for network in Network.objects.all(): _reserve_margin_addresses( network, network.reserved_from_beginning, network.reserved_from_end, IPAddress )",
"dependencies = [ ('networks', '0007_auto_20160804_1409'), ] operations = [ migrations.AddField( model_name='network', name='reserved_from_beginning', field=models.PositiveIntegerField(help_text='Number",
"), status=IPADDRESS_STATUS_RESERVED, gateway_network__isnull=True, ) print('Removing {} reserved IPs'.format(ips.count())) ips.delete() class Migration(migrations.Migration): dependencies =",
"__future__ import unicode_literals import ipaddress from itertools import chain from django.db import migrations,",
"field=models.PositiveIntegerField(help_text='Number of addresses to be omitted in DHCP automatic assignmentcounted from the first",
"int(network.min_ip + bottom_count + 1)), # noqa range(int(network.max_ip - top_count), int(network.max_ip)) ])) to_create",
"flat=True)) to_create = set(chain.from_iterable([ range(int(network.min_ip + 1), int(network.min_ip + bottom_count + 1)), #",
"( models.Q(ethernet__base_object__isnull=True) & models.Q(ethernet__mac__isnull=False) ), status=IPADDRESS_STATUS_RESERVED, gateway_network__isnull=True, ) print('Removing {} reserved IPs'.format(ips.count())) ips.delete()",
"addresses to be omitted in DHCP automatic assignmentcounted from the first IP in",
"assignmentcounted from the first IP in range (excluding network address)', default=10), ), migrations.AddField(",
"models.Q(ethernet__isnull=True) | ( models.Q(ethernet__base_object__isnull=True) & models.Q(ethernet__mac__isnull=False) ), status=IPADDRESS_STATUS_RESERVED, gateway_network__isnull=True, ) print('Removing {} reserved",
"= [ ('networks', '0007_auto_20160804_1409'), ] operations = [ migrations.AddField( model_name='network', name='reserved_from_beginning', field=models.PositiveIntegerField(help_text='Number of",
"import unicode_literals import ipaddress from itertools import chain from django.db import migrations, models",
"{}'.format(len(ips), network)) IPAddress.objects.bulk_create(ips) ips_query.update(status=IPADDRESS_STATUS_RESERVED) def create_reserved_ips(apps, schema_editor): IPAddress = apps.get_model('networks', 'IPAddress') Network =",
"'Network') for network in Network.objects.all(): _reserve_margin_addresses( network, network.reserved_from_beginning, network.reserved_from_end, IPAddress ) def remove_reserved_ips(apps,",
"last IP in range (excluding broadcast address)', default=0), ), migrations.RunPython( remove_reserved_ips, reverse_code=create_reserved_ips ),",
"IPAddress): ips = [] ips_query = IPAddress.objects.filter( models.Q( number__gte=network.min_ip + 1, number__lte=network.min_ip +",
"IPAddress.objects.filter( models.Q(ethernet__isnull=True) | ( models.Q(ethernet__base_object__isnull=True) & models.Q(ethernet__mac__isnull=False) ), status=IPADDRESS_STATUS_RESERVED, gateway_network__isnull=True, ) print('Removing {}",
"number=ip_as_int, network=network, status=IPADDRESS_STATUS_RESERVED )) print('Creating {} ips for {}'.format(len(ips), network)) IPAddress.objects.bulk_create(ips) ips_query.update(status=IPADDRESS_STATUS_RESERVED) def",
"# noqa range(int(network.max_ip - top_count), int(network.max_ip)) ])) to_create = to_create - existing_ips for",
"| models.Q( number__gte=network.max_ip - top_count, number__lte=network.max_ip ) ) existing_ips = set(ips_query.values_list('number', flat=True)) to_create",
"| ( models.Q(ethernet__base_object__isnull=True) & models.Q(ethernet__mac__isnull=False) ), status=IPADDRESS_STATUS_RESERVED, gateway_network__isnull=True, ) print('Removing {} reserved IPs'.format(ips.count()))",
"('networks', '0007_auto_20160804_1409'), ] operations = [ migrations.AddField( model_name='network', name='reserved_from_beginning', field=models.PositiveIntegerField(help_text='Number of addresses to",
"in DHCP automatic assignmentcounted from the last IP in range (excluding broadcast address)',",
") print('Removing {} reserved IPs'.format(ips.count())) ips.delete() class Migration(migrations.Migration): dependencies = [ ('networks', '0007_auto_20160804_1409'),",
"set(ips_query.values_list('number', flat=True)) to_create = set(chain.from_iterable([ range(int(network.min_ip + 1), int(network.min_ip + bottom_count + 1)),",
"default=10), ), migrations.AddField( model_name='network', name='reserved_from_end', field=models.PositiveIntegerField(help_text='Number of addresses to be omitted in DHCP",
"itertools import chain from django.db import migrations, models IPADDRESS_STATUS_RESERVED = 2 def _reserve_margin_addresses(network,",
"network address)', default=10), ), migrations.AddField( model_name='network', name='reserved_from_end', field=models.PositiveIntegerField(help_text='Number of addresses to be omitted",
"addresses to be omitted in DHCP automatic assignmentcounted from the last IP in",
"{} reserved IPs'.format(ips.count())) ips.delete() class Migration(migrations.Migration): dependencies = [ ('networks', '0007_auto_20160804_1409'), ] operations",
"of addresses to be omitted in DHCP automatic assignmentcounted from the last IP",
"_reserve_margin_addresses( network, network.reserved_from_beginning, network.reserved_from_end, IPAddress ) def remove_reserved_ips(apps, schema_editor): IPAddress = apps.get_model('networks', 'IPAddress')",
"field=models.PositiveIntegerField(help_text='Number of addresses to be omitted in DHCP automatic assignmentcounted from the last",
"models.Q( number__gte=network.min_ip + 1, number__lte=network.min_ip + bottom_count + 1 ) | models.Q( number__gte=network.max_ip",
"assignmentcounted from the last IP in range (excluding broadcast address)', default=0), ), migrations.RunPython(",
"ip_as_int in to_create: ips.append(IPAddress( address=str(ipaddress.ip_address(ip_as_int)), number=ip_as_int, network=network, status=IPADDRESS_STATUS_RESERVED )) print('Creating {} ips for",
"automatic assignmentcounted from the first IP in range (excluding network address)', default=10), ),",
"for {}'.format(len(ips), network)) IPAddress.objects.bulk_create(ips) ips_query.update(status=IPADDRESS_STATUS_RESERVED) def create_reserved_ips(apps, schema_editor): IPAddress = apps.get_model('networks', 'IPAddress') Network",
"model_name='network', name='reserved_from_end', field=models.PositiveIntegerField(help_text='Number of addresses to be omitted in DHCP automatic assignmentcounted from",
"ipaddress from itertools import chain from django.db import migrations, models IPADDRESS_STATUS_RESERVED = 2",
"noqa range(int(network.max_ip - top_count), int(network.max_ip)) ])) to_create = to_create - existing_ips for ip_as_int",
"create_reserved_ips(apps, schema_editor): IPAddress = apps.get_model('networks', 'IPAddress') Network = apps.get_model('networks', 'Network') for network in",
"top_count, IPAddress): ips = [] ips_query = IPAddress.objects.filter( models.Q( number__gte=network.min_ip + 1, number__lte=network.min_ip",
"[] ips_query = IPAddress.objects.filter( models.Q( number__gte=network.min_ip + 1, number__lte=network.min_ip + bottom_count + 1",
"top_count, number__lte=network.max_ip ) ) existing_ips = set(ips_query.values_list('number', flat=True)) to_create = set(chain.from_iterable([ range(int(network.min_ip +",
") def remove_reserved_ips(apps, schema_editor): IPAddress = apps.get_model('networks', 'IPAddress') ips = IPAddress.objects.filter( models.Q(ethernet__isnull=True) |",
"network, network.reserved_from_beginning, network.reserved_from_end, IPAddress ) def remove_reserved_ips(apps, schema_editor): IPAddress = apps.get_model('networks', 'IPAddress') ips",
"+ 1, number__lte=network.min_ip + bottom_count + 1 ) | models.Q( number__gte=network.max_ip - top_count,",
"to_create - existing_ips for ip_as_int in to_create: ips.append(IPAddress( address=str(ipaddress.ip_address(ip_as_int)), number=ip_as_int, network=network, status=IPADDRESS_STATUS_RESERVED ))",
"'IPAddress') Network = apps.get_model('networks', 'Network') for network in Network.objects.all(): _reserve_margin_addresses( network, network.reserved_from_beginning, network.reserved_from_end,",
"migrations.AddField( model_name='network', name='reserved_from_beginning', field=models.PositiveIntegerField(help_text='Number of addresses to be omitted in DHCP automatic assignmentcounted",
"omitted in DHCP automatic assignmentcounted from the first IP in range (excluding network",
"django.db import migrations, models IPADDRESS_STATUS_RESERVED = 2 def _reserve_margin_addresses(network, bottom_count, top_count, IPAddress): ips",
"= apps.get_model('networks', 'IPAddress') Network = apps.get_model('networks', 'Network') for network in Network.objects.all(): _reserve_margin_addresses( network,",
"to be omitted in DHCP automatic assignmentcounted from the first IP in range",
"be omitted in DHCP automatic assignmentcounted from the first IP in range (excluding",
"from the first IP in range (excluding network address)', default=10), ), migrations.AddField( model_name='network',",
"model_name='network', name='reserved_from_beginning', field=models.PositiveIntegerField(help_text='Number of addresses to be omitted in DHCP automatic assignmentcounted from",
"import chain from django.db import migrations, models IPADDRESS_STATUS_RESERVED = 2 def _reserve_margin_addresses(network, bottom_count,",
") ) existing_ips = set(ips_query.values_list('number', flat=True)) to_create = set(chain.from_iterable([ range(int(network.min_ip + 1), int(network.min_ip",
"top_count), int(network.max_ip)) ])) to_create = to_create - existing_ips for ip_as_int in to_create: ips.append(IPAddress(",
"number__gte=network.max_ip - top_count, number__lte=network.max_ip ) ) existing_ips = set(ips_query.values_list('number', flat=True)) to_create = set(chain.from_iterable([",
"IPAddress = apps.get_model('networks', 'IPAddress') ips = IPAddress.objects.filter( models.Q(ethernet__isnull=True) | ( models.Q(ethernet__base_object__isnull=True) & models.Q(ethernet__mac__isnull=False)",
"from django.db import migrations, models IPADDRESS_STATUS_RESERVED = 2 def _reserve_margin_addresses(network, bottom_count, top_count, IPAddress):",
"ips.delete() class Migration(migrations.Migration): dependencies = [ ('networks', '0007_auto_20160804_1409'), ] operations = [ migrations.AddField(",
"def _reserve_margin_addresses(network, bottom_count, top_count, IPAddress): ips = [] ips_query = IPAddress.objects.filter( models.Q( number__gte=network.min_ip",
"ips_query = IPAddress.objects.filter( models.Q( number__gte=network.min_ip + 1, number__lte=network.min_ip + bottom_count + 1 )",
"migrations, models IPADDRESS_STATUS_RESERVED = 2 def _reserve_margin_addresses(network, bottom_count, top_count, IPAddress): ips = []",
"+ bottom_count + 1 ) | models.Q( number__gte=network.max_ip - top_count, number__lte=network.max_ip ) )",
"status=IPADDRESS_STATUS_RESERVED, gateway_network__isnull=True, ) print('Removing {} reserved IPs'.format(ips.count())) ips.delete() class Migration(migrations.Migration): dependencies = [",
"set(chain.from_iterable([ range(int(network.min_ip + 1), int(network.min_ip + bottom_count + 1)), # noqa range(int(network.max_ip -",
"be omitted in DHCP automatic assignmentcounted from the last IP in range (excluding",
"Network = apps.get_model('networks', 'Network') for network in Network.objects.all(): _reserve_margin_addresses( network, network.reserved_from_beginning, network.reserved_from_end, IPAddress",
"address=str(ipaddress.ip_address(ip_as_int)), number=ip_as_int, network=network, status=IPADDRESS_STATUS_RESERVED )) print('Creating {} ips for {}'.format(len(ips), network)) IPAddress.objects.bulk_create(ips) ips_query.update(status=IPADDRESS_STATUS_RESERVED)",
"coding: utf-8 -*- from __future__ import unicode_literals import ipaddress from itertools import chain",
"IPAddress.objects.filter( models.Q( number__gte=network.min_ip + 1, number__lte=network.min_ip + bottom_count + 1 ) | models.Q(",
"= to_create - existing_ips for ip_as_int in to_create: ips.append(IPAddress( address=str(ipaddress.ip_address(ip_as_int)), number=ip_as_int, network=network, status=IPADDRESS_STATUS_RESERVED",
"in Network.objects.all(): _reserve_margin_addresses( network, network.reserved_from_beginning, network.reserved_from_end, IPAddress ) def remove_reserved_ips(apps, schema_editor): IPAddress =",
"number__lte=network.min_ip + bottom_count + 1 ) | models.Q( number__gte=network.max_ip - top_count, number__lte=network.max_ip )",
"models.Q(ethernet__mac__isnull=False) ), status=IPADDRESS_STATUS_RESERVED, gateway_network__isnull=True, ) print('Removing {} reserved IPs'.format(ips.count())) ips.delete() class Migration(migrations.Migration): dependencies",
"from __future__ import unicode_literals import ipaddress from itertools import chain from django.db import",
"ips.append(IPAddress( address=str(ipaddress.ip_address(ip_as_int)), number=ip_as_int, network=network, status=IPADDRESS_STATUS_RESERVED )) print('Creating {} ips for {}'.format(len(ips), network)) IPAddress.objects.bulk_create(ips)",
"- existing_ips for ip_as_int in to_create: ips.append(IPAddress( address=str(ipaddress.ip_address(ip_as_int)), number=ip_as_int, network=network, status=IPADDRESS_STATUS_RESERVED )) print('Creating",
"# -*- coding: utf-8 -*- from __future__ import unicode_literals import ipaddress from itertools",
"'IPAddress') ips = IPAddress.objects.filter( models.Q(ethernet__isnull=True) | ( models.Q(ethernet__base_object__isnull=True) & models.Q(ethernet__mac__isnull=False) ), status=IPADDRESS_STATUS_RESERVED, gateway_network__isnull=True,",
"unicode_literals import ipaddress from itertools import chain from django.db import migrations, models IPADDRESS_STATUS_RESERVED",
"range (excluding network address)', default=10), ), migrations.AddField( model_name='network', name='reserved_from_end', field=models.PositiveIntegerField(help_text='Number of addresses to",
"= set(chain.from_iterable([ range(int(network.min_ip + 1), int(network.min_ip + bottom_count + 1)), # noqa range(int(network.max_ip",
"bottom_count + 1)), # noqa range(int(network.max_ip - top_count), int(network.max_ip)) ])) to_create = to_create",
"_reserve_margin_addresses(network, bottom_count, top_count, IPAddress): ips = [] ips_query = IPAddress.objects.filter( models.Q( number__gte=network.min_ip +",
"range(int(network.max_ip - top_count), int(network.max_ip)) ])) to_create = to_create - existing_ips for ip_as_int in",
"= 2 def _reserve_margin_addresses(network, bottom_count, top_count, IPAddress): ips = [] ips_query = IPAddress.objects.filter(",
"+ 1)), # noqa range(int(network.max_ip - top_count), int(network.max_ip)) ])) to_create = to_create -",
"& models.Q(ethernet__mac__isnull=False) ), status=IPADDRESS_STATUS_RESERVED, gateway_network__isnull=True, ) print('Removing {} reserved IPs'.format(ips.count())) ips.delete() class Migration(migrations.Migration):",
"Migration(migrations.Migration): dependencies = [ ('networks', '0007_auto_20160804_1409'), ] operations = [ migrations.AddField( model_name='network', name='reserved_from_beginning',",
"DHCP automatic assignmentcounted from the first IP in range (excluding network address)', default=10),",
"omitted in DHCP automatic assignmentcounted from the last IP in range (excluding broadcast",
"IPAddress.objects.bulk_create(ips) ips_query.update(status=IPADDRESS_STATUS_RESERVED) def create_reserved_ips(apps, schema_editor): IPAddress = apps.get_model('networks', 'IPAddress') Network = apps.get_model('networks', 'Network')",
"network=network, status=IPADDRESS_STATUS_RESERVED )) print('Creating {} ips for {}'.format(len(ips), network)) IPAddress.objects.bulk_create(ips) ips_query.update(status=IPADDRESS_STATUS_RESERVED) def create_reserved_ips(apps,",
"bottom_count + 1 ) | models.Q( number__gte=network.max_ip - top_count, number__lte=network.max_ip ) ) existing_ips",
"IP in range (excluding network address)', default=10), ), migrations.AddField( model_name='network', name='reserved_from_end', field=models.PositiveIntegerField(help_text='Number of",
"])) to_create = to_create - existing_ips for ip_as_int in to_create: ips.append(IPAddress( address=str(ipaddress.ip_address(ip_as_int)), number=ip_as_int,",
"{} ips for {}'.format(len(ips), network)) IPAddress.objects.bulk_create(ips) ips_query.update(status=IPADDRESS_STATUS_RESERVED) def create_reserved_ips(apps, schema_editor): IPAddress = apps.get_model('networks',",
"gateway_network__isnull=True, ) print('Removing {} reserved IPs'.format(ips.count())) ips.delete() class Migration(migrations.Migration): dependencies = [ ('networks',",
"address)', default=10), ), migrations.AddField( model_name='network', name='reserved_from_end', field=models.PositiveIntegerField(help_text='Number of addresses to be omitted in",
"utf-8 -*- from __future__ import unicode_literals import ipaddress from itertools import chain from",
"DHCP automatic assignmentcounted from the last IP in range (excluding broadcast address)', default=0),",
"existing_ips for ip_as_int in to_create: ips.append(IPAddress( address=str(ipaddress.ip_address(ip_as_int)), number=ip_as_int, network=network, status=IPADDRESS_STATUS_RESERVED )) print('Creating {}",
"IPs'.format(ips.count())) ips.delete() class Migration(migrations.Migration): dependencies = [ ('networks', '0007_auto_20160804_1409'), ] operations = [",
"import ipaddress from itertools import chain from django.db import migrations, models IPADDRESS_STATUS_RESERVED =",
"operations = [ migrations.AddField( model_name='network', name='reserved_from_beginning', field=models.PositiveIntegerField(help_text='Number of addresses to be omitted in",
"[ migrations.AddField( model_name='network', name='reserved_from_beginning', field=models.PositiveIntegerField(help_text='Number of addresses to be omitted in DHCP automatic",
"network.reserved_from_beginning, network.reserved_from_end, IPAddress ) def remove_reserved_ips(apps, schema_editor): IPAddress = apps.get_model('networks', 'IPAddress') ips =",
"-*- from __future__ import unicode_literals import ipaddress from itertools import chain from django.db",
"+ bottom_count + 1)), # noqa range(int(network.max_ip - top_count), int(network.max_ip)) ])) to_create =",
"IPAddress ) def remove_reserved_ips(apps, schema_editor): IPAddress = apps.get_model('networks', 'IPAddress') ips = IPAddress.objects.filter( models.Q(ethernet__isnull=True)",
"int(network.max_ip)) ])) to_create = to_create - existing_ips for ip_as_int in to_create: ips.append(IPAddress( address=str(ipaddress.ip_address(ip_as_int)),",
"number__gte=network.min_ip + 1, number__lte=network.min_ip + bottom_count + 1 ) | models.Q( number__gte=network.max_ip -",
"print('Creating {} ips for {}'.format(len(ips), network)) IPAddress.objects.bulk_create(ips) ips_query.update(status=IPADDRESS_STATUS_RESERVED) def create_reserved_ips(apps, schema_editor): IPAddress =",
")) print('Creating {} ips for {}'.format(len(ips), network)) IPAddress.objects.bulk_create(ips) ips_query.update(status=IPADDRESS_STATUS_RESERVED) def create_reserved_ips(apps, schema_editor): IPAddress",
"from itertools import chain from django.db import migrations, models IPADDRESS_STATUS_RESERVED = 2 def",
"[ ('networks', '0007_auto_20160804_1409'), ] operations = [ migrations.AddField( model_name='network', name='reserved_from_beginning', field=models.PositiveIntegerField(help_text='Number of addresses",
"number__lte=network.max_ip ) ) existing_ips = set(ips_query.values_list('number', flat=True)) to_create = set(chain.from_iterable([ range(int(network.min_ip + 1),",
"schema_editor): IPAddress = apps.get_model('networks', 'IPAddress') Network = apps.get_model('networks', 'Network') for network in Network.objects.all():",
"for ip_as_int in to_create: ips.append(IPAddress( address=str(ipaddress.ip_address(ip_as_int)), number=ip_as_int, network=network, status=IPADDRESS_STATUS_RESERVED )) print('Creating {} ips",
"for network in Network.objects.all(): _reserve_margin_addresses( network, network.reserved_from_beginning, network.reserved_from_end, IPAddress ) def remove_reserved_ips(apps, schema_editor):",
"name='reserved_from_beginning', field=models.PositiveIntegerField(help_text='Number of addresses to be omitted in DHCP automatic assignmentcounted from the",
"range(int(network.min_ip + 1), int(network.min_ip + bottom_count + 1)), # noqa range(int(network.max_ip - top_count),",
"models IPADDRESS_STATUS_RESERVED = 2 def _reserve_margin_addresses(network, bottom_count, top_count, IPAddress): ips = [] ips_query",
"1 ) | models.Q( number__gte=network.max_ip - top_count, number__lte=network.max_ip ) ) existing_ips = set(ips_query.values_list('number',",
"from the last IP in range (excluding broadcast address)', default=0), ), migrations.RunPython( remove_reserved_ips,",
"+ 1), int(network.min_ip + bottom_count + 1)), # noqa range(int(network.max_ip - top_count), int(network.max_ip))",
"reserved IPs'.format(ips.count())) ips.delete() class Migration(migrations.Migration): dependencies = [ ('networks', '0007_auto_20160804_1409'), ] operations =",
"network.reserved_from_end, IPAddress ) def remove_reserved_ips(apps, schema_editor): IPAddress = apps.get_model('networks', 'IPAddress') ips = IPAddress.objects.filter(",
"= [] ips_query = IPAddress.objects.filter( models.Q( number__gte=network.min_ip + 1, number__lte=network.min_ip + bottom_count +",
"network)) IPAddress.objects.bulk_create(ips) ips_query.update(status=IPADDRESS_STATUS_RESERVED) def create_reserved_ips(apps, schema_editor): IPAddress = apps.get_model('networks', 'IPAddress') Network = apps.get_model('networks',",
"in to_create: ips.append(IPAddress( address=str(ipaddress.ip_address(ip_as_int)), number=ip_as_int, network=network, status=IPADDRESS_STATUS_RESERVED )) print('Creating {} ips for {}'.format(len(ips),",
"1, number__lte=network.min_ip + bottom_count + 1 ) | models.Q( number__gte=network.max_ip - top_count, number__lte=network.max_ip",
"ips = IPAddress.objects.filter( models.Q(ethernet__isnull=True) | ( models.Q(ethernet__base_object__isnull=True) & models.Q(ethernet__mac__isnull=False) ), status=IPADDRESS_STATUS_RESERVED, gateway_network__isnull=True, )",
"models.Q( number__gte=network.max_ip - top_count, number__lte=network.max_ip ) ) existing_ips = set(ips_query.values_list('number', flat=True)) to_create =",
"- top_count, number__lte=network.max_ip ) ) existing_ips = set(ips_query.values_list('number', flat=True)) to_create = set(chain.from_iterable([ range(int(network.min_ip",
"migrations.AddField( model_name='network', name='reserved_from_end', field=models.PositiveIntegerField(help_text='Number of addresses to be omitted in DHCP automatic assignmentcounted",
"remove_reserved_ips(apps, schema_editor): IPAddress = apps.get_model('networks', 'IPAddress') ips = IPAddress.objects.filter( models.Q(ethernet__isnull=True) | ( models.Q(ethernet__base_object__isnull=True)",
"IPAddress = apps.get_model('networks', 'IPAddress') Network = apps.get_model('networks', 'Network') for network in Network.objects.all(): _reserve_margin_addresses(",
"(excluding network address)', default=10), ), migrations.AddField( model_name='network', name='reserved_from_end', field=models.PositiveIntegerField(help_text='Number of addresses to be",
"bottom_count, top_count, IPAddress): ips = [] ips_query = IPAddress.objects.filter( models.Q( number__gte=network.min_ip + 1,",
"print('Removing {} reserved IPs'.format(ips.count())) ips.delete() class Migration(migrations.Migration): dependencies = [ ('networks', '0007_auto_20160804_1409'), ]",
") existing_ips = set(ips_query.values_list('number', flat=True)) to_create = set(chain.from_iterable([ range(int(network.min_ip + 1), int(network.min_ip +",
"IPADDRESS_STATUS_RESERVED = 2 def _reserve_margin_addresses(network, bottom_count, top_count, IPAddress): ips = [] ips_query =",
"to_create: ips.append(IPAddress( address=str(ipaddress.ip_address(ip_as_int)), number=ip_as_int, network=network, status=IPADDRESS_STATUS_RESERVED )) print('Creating {} ips for {}'.format(len(ips), network))",
"- top_count), int(network.max_ip)) ])) to_create = to_create - existing_ips for ip_as_int in to_create:",
"automatic assignmentcounted from the last IP in range (excluding broadcast address)', default=0), ),",
"= apps.get_model('networks', 'IPAddress') ips = IPAddress.objects.filter( models.Q(ethernet__isnull=True) | ( models.Q(ethernet__base_object__isnull=True) & models.Q(ethernet__mac__isnull=False) ),",
"apps.get_model('networks', 'Network') for network in Network.objects.all(): _reserve_margin_addresses( network, network.reserved_from_beginning, network.reserved_from_end, IPAddress ) def",
"models.Q(ethernet__base_object__isnull=True) & models.Q(ethernet__mac__isnull=False) ), status=IPADDRESS_STATUS_RESERVED, gateway_network__isnull=True, ) print('Removing {} reserved IPs'.format(ips.count())) ips.delete() class",
"1), int(network.min_ip + bottom_count + 1)), # noqa range(int(network.max_ip - top_count), int(network.max_ip)) ]))",
"class Migration(migrations.Migration): dependencies = [ ('networks', '0007_auto_20160804_1409'), ] operations = [ migrations.AddField( model_name='network',",
"in range (excluding network address)', default=10), ), migrations.AddField( model_name='network', name='reserved_from_end', field=models.PositiveIntegerField(help_text='Number of addresses",
"2 def _reserve_margin_addresses(network, bottom_count, top_count, IPAddress): ips = [] ips_query = IPAddress.objects.filter( models.Q(",
"= IPAddress.objects.filter( models.Q(ethernet__isnull=True) | ( models.Q(ethernet__base_object__isnull=True) & models.Q(ethernet__mac__isnull=False) ), status=IPADDRESS_STATUS_RESERVED, gateway_network__isnull=True, ) print('Removing",
"= [ migrations.AddField( model_name='network', name='reserved_from_beginning', field=models.PositiveIntegerField(help_text='Number of addresses to be omitted in DHCP",
"def remove_reserved_ips(apps, schema_editor): IPAddress = apps.get_model('networks', 'IPAddress') ips = IPAddress.objects.filter( models.Q(ethernet__isnull=True) | (",
"import migrations, models IPADDRESS_STATUS_RESERVED = 2 def _reserve_margin_addresses(network, bottom_count, top_count, IPAddress): ips =",
"Network.objects.all(): _reserve_margin_addresses( network, network.reserved_from_beginning, network.reserved_from_end, IPAddress ) def remove_reserved_ips(apps, schema_editor): IPAddress = apps.get_model('networks',",
"the last IP in range (excluding broadcast address)', default=0), ), migrations.RunPython( remove_reserved_ips, reverse_code=create_reserved_ips",
") | models.Q( number__gte=network.max_ip - top_count, number__lte=network.max_ip ) ) existing_ips = set(ips_query.values_list('number', flat=True))",
"in DHCP automatic assignmentcounted from the first IP in range (excluding network address)',",
"of addresses to be omitted in DHCP automatic assignmentcounted from the first IP",
"name='reserved_from_end', field=models.PositiveIntegerField(help_text='Number of addresses to be omitted in DHCP automatic assignmentcounted from the",
"ips_query.update(status=IPADDRESS_STATUS_RESERVED) def create_reserved_ips(apps, schema_editor): IPAddress = apps.get_model('networks', 'IPAddress') Network = apps.get_model('networks', 'Network') for",
"the first IP in range (excluding network address)', default=10), ), migrations.AddField( model_name='network', name='reserved_from_end',",
"apps.get_model('networks', 'IPAddress') Network = apps.get_model('networks', 'Network') for network in Network.objects.all(): _reserve_margin_addresses( network, network.reserved_from_beginning,",
"] operations = [ migrations.AddField( model_name='network', name='reserved_from_beginning', field=models.PositiveIntegerField(help_text='Number of addresses to be omitted",
"apps.get_model('networks', 'IPAddress') ips = IPAddress.objects.filter( models.Q(ethernet__isnull=True) | ( models.Q(ethernet__base_object__isnull=True) & models.Q(ethernet__mac__isnull=False) ), status=IPADDRESS_STATUS_RESERVED,",
"first IP in range (excluding network address)', default=10), ), migrations.AddField( model_name='network', name='reserved_from_end', field=models.PositiveIntegerField(help_text='Number",
"IP in range (excluding broadcast address)', default=0), ), migrations.RunPython( remove_reserved_ips, reverse_code=create_reserved_ips ), ]",
"existing_ips = set(ips_query.values_list('number', flat=True)) to_create = set(chain.from_iterable([ range(int(network.min_ip + 1), int(network.min_ip + bottom_count",
"to_create = to_create - existing_ips for ip_as_int in to_create: ips.append(IPAddress( address=str(ipaddress.ip_address(ip_as_int)), number=ip_as_int, network=network,",
"'0007_auto_20160804_1409'), ] operations = [ migrations.AddField( model_name='network', name='reserved_from_beginning', field=models.PositiveIntegerField(help_text='Number of addresses to be",
"-*- coding: utf-8 -*- from __future__ import unicode_literals import ipaddress from itertools import",
"chain from django.db import migrations, models IPADDRESS_STATUS_RESERVED = 2 def _reserve_margin_addresses(network, bottom_count, top_count,",
"), migrations.AddField( model_name='network', name='reserved_from_end', field=models.PositiveIntegerField(help_text='Number of addresses to be omitted in DHCP automatic",
"= set(ips_query.values_list('number', flat=True)) to_create = set(chain.from_iterable([ range(int(network.min_ip + 1), int(network.min_ip + bottom_count +",
"1)), # noqa range(int(network.max_ip - top_count), int(network.max_ip)) ])) to_create = to_create - existing_ips",
"ips = [] ips_query = IPAddress.objects.filter( models.Q( number__gte=network.min_ip + 1, number__lte=network.min_ip + bottom_count",
"schema_editor): IPAddress = apps.get_model('networks', 'IPAddress') ips = IPAddress.objects.filter( models.Q(ethernet__isnull=True) | ( models.Q(ethernet__base_object__isnull=True) &",
"to_create = set(chain.from_iterable([ range(int(network.min_ip + 1), int(network.min_ip + bottom_count + 1)), # noqa"
] |
[
"django.contrib.auth.models import User from django.core.exceptions import ValidationError from django.core.urlresolvers import reverse from django.db",
"models.TextField(default=\"\") date_created = models.DateTimeField(auto_now_add=True) last_modified = models.DateTimeField(auto_now=True) completed = models.BooleanField(default=False) date_completed = models.DateTimeField(default=None,",
"/ total) * 100.0 # minimum display percentage min_percent = 5.0 for key",
"sysrev.api import PubMed class Review(models.Model): participants = models.ManyToManyField(User) title = models.CharField(max_length=128, unique=False) slug",
"/ total) * 100.0 document = (counts[\"document\"] / total) * 100.0 final =",
"for key in counts: if key == \"total\": continue old = counts[key] =",
"'F' REJECTED = 'R' POOLS = ( (ABSTRACT_POOL, 'Abstract pool'), (DOCUMENT_POOL, 'Document pool'),",
"models.SlugField() description = models.TextField(default=\"\") date_created = models.DateTimeField(auto_now_add=True) last_modified = models.DateTimeField(auto_now=True) completed = models.BooleanField(default=False)",
"counts repeatedly counts = self.paper_pool_counts() total = float(counts[\"total\"]) if total is not 0:",
"class Paper(models.Model): ABSTRACT_POOL = 'A' DOCUMENT_POOL = 'D' FINAL_POOL = 'F' REJECTED =",
"slug = models.SlugField() description = models.TextField(default=\"\") date_created = models.DateTimeField(auto_now_add=True) last_modified = models.DateTimeField(auto_now=True) completed",
"\"progress\": progress} else: return def paper_pool_counts(self): relevant_papers = Paper.objects.filter(review=self) abstract_count = relevant_papers.filter(pool=\"A\").count() document_count",
"total) * 100.0 return {\"abstract\": abstract, \"document\": document, \"final\": final, \"rejected\": rejected, \"progress\":",
"= models.TextField(default=\"\") def perform_query(self): # TODO: discard existing papers if there are any",
"else: papers = Paper.objects.filter(review=self) existing_ids = [] for paper in papers: existing_ids +=",
"'Final pool'), (REJECTED, 'Rejected') ) review = models.ForeignKey(Review) title = models.CharField(max_length=128) authors =",
"= 'F' REJECTED = 'R' POOLS = ( (ABSTRACT_POOL, 'Abstract pool'), (DOCUMENT_POOL, 'Document",
"review and pool\"\"\" papers = read_papers_from_ids(ids) # Commit all papers in single transaction",
"= relevant_papers.filter(pool=\"A\").count() document_count = relevant_papers.filter(pool=\"D\").count() final_count = relevant_papers.filter(pool=\"F\").count() rejected_count = relevant_papers.filter(pool=\"R\").count() return {\"abstract\":",
"counts: if key == \"total\": continue old = counts[key] = float(counts[key]) result =",
"Seems a bit wasteful, as it ends up running multiple times and querying",
"\"\\n\\n\" except KeyError: pass paper.abstract = abstractText paper.publish_date = _get_date(medlineCitation) paper.url = url_from_id(pubmed_id)",
"bit wasteful, as it ends up running multiple times and querying counts repeatedly",
"final_count + rejected_count} def invite(self, invitees): for invitee in invitees: user = None",
"Paper.create_paper_from_data(data, review, pool), papers) def get_absolute_url(self): return self.review.get_absolute_url() + \"/\" + str(self.pk) def",
"ABSTRACT_POOL = 'A' DOCUMENT_POOL = 'D' FINAL_POOL = 'F' REJECTED = 'R' POOLS",
"< 1: raise ValidationError('Need at least one participant') def save(self, *args, **kwargs): self.slug",
"sysrev.api.PubMed import _get_authors, _get_date, url_from_id, read_papers_from_ids from sysrev.api import PubMed class Review(models.Model): participants",
"models.CharField(max_length=16) notes = models.TextField(default=\"\") pool = models.CharField(max_length=1, choices=POOLS, default=ABSTRACT_POOL) @staticmethod def create_paper_from_data(data, review,",
"= medlineCitation[u'Article'] title = article[u'ArticleTitle'].lstrip(\"[\").rstrip(\"].\") pubmed_id = medlineCitation[u'PMID'] paper = Paper.objects.get_or_create(review=review, title=title, pubmed_id=pubmed_id)[0]",
"# TODO: discard existing papers if there are any ids_from_query = PubMed.get_ids_from_query(self.query) if",
"user = None if invitee.find(\"@\") == -1: user = User.objects.get(username=invitee) else: user =",
"import models from django.template.defaultfilters import slugify from django.utils.html import escape from django.db import",
"= User.objects.get(username=invitee) else: user = User.objects.get(email=invitee) self.participants.add(user) def clean(self): if (not self.participants) or",
"django.db import transaction from sysrev.api.PubMed import _get_authors, _get_date, url_from_id, read_papers_from_ids from sysrev.api import",
".exclude(pubmed_id__in=ids_from_query)\\ .delete() ids_to_add = list(set(ids_from_query).difference(existing_ids)) if ids_to_add: Paper.create_papers_from_pubmed_ids(ids_to_add, self) def paper_pool_percentages(self): # TODO:",
"== 0: Paper.create_papers_from_pubmed_ids(ids_from_query, self) else: papers = Paper.objects.filter(review=self) existing_ids = [] for paper",
"call when creating lots of papers with transaction.atomic(): return map(lambda data: Paper.create_paper_from_data(data, review,",
"self).save() def get_absolute_url(self): return reverse('review_detail', args=[str(self.pk)])[:-1] + \"-\" + self.slug def __unicode__(self): return",
"null=True) query = models.TextField(default=\"\") def perform_query(self): # TODO: discard existing papers if there",
"def create_paper_from_data(data, review, pool): \"\"\"Creates Paper model from given data, review and pool\"\"\"",
"\"-\" + self.slug def __unicode__(self): return str(self.pk) + \": \" + self.title class",
"\"rejected\": rejected, \"progress\": progress} else: return def paper_pool_counts(self): relevant_papers = Paper.objects.filter(review=self) abstract_count =",
"review, pool='A'): \"\"\"Creates papers from all of the given ids, in the given",
"document_count, \"final\": final_count, \"rejected\": rejected_count, \"remaining\": abstract_count + document_count, \"total\": abstract_count + document_count",
"ids_to_add = list(set(ids_from_query).difference(existing_ids)) if ids_to_add: Paper.create_papers_from_pubmed_ids(ids_to_add, self) def paper_pool_percentages(self): # TODO: Typically, paper_pool_counts()",
"'R' POOLS = ( (ABSTRACT_POOL, 'Abstract pool'), (DOCUMENT_POOL, 'Document pool'), (FINAL_POOL, 'Final pool'),",
"= models.CharField(max_length=16) notes = models.TextField(default=\"\") pool = models.CharField(max_length=1, choices=POOLS, default=ABSTRACT_POOL) @staticmethod def create_paper_from_data(data,",
"with transaction.atomic(): return map(lambda data: Paper.create_paper_from_data(data, review, pool), papers) def get_absolute_url(self): return self.review.get_absolute_url()",
"\"document\": document_count, \"final\": final_count, \"rejected\": rejected_count, \"remaining\": abstract_count + document_count, \"total\": abstract_count +",
"else: return def paper_pool_counts(self): relevant_papers = Paper.objects.filter(review=self) abstract_count = relevant_papers.filter(pool=\"A\").count() document_count = relevant_papers.filter(pool=\"D\").count()",
"medlineCitation = data[u'MedlineCitation'] article = medlineCitation[u'Article'] title = article[u'ArticleTitle'].lstrip(\"[\").rstrip(\"].\") pubmed_id = medlineCitation[u'PMID'] paper",
"= models.CharField(max_length=128) authors = models.CharField(max_length=128) abstract = models.TextField(default=\"\") publish_date = models.DateField(null=True) url =",
"get_absolute_url(self): return reverse('review_detail', args=[str(self.pk)])[:-1] + \"-\" + self.slug def __unicode__(self): return str(self.pk) +",
"+ rejected_count} def invite(self, invitees): for invitee in invitees: user = None if",
"document_count, \"total\": abstract_count + document_count + final_count + rejected_count} def invite(self, invitees): for",
"def save(self, *args, **kwargs): self.slug = slugify(self.title) super(Review, self).save() def get_absolute_url(self): return reverse('review_detail',",
"= (counts[key] / total) * 100.0 if result != 0.0 and result <",
"paper in papers.filter(pool=\"A\"): existing_abstract_ids += [paper.pubmed_id] with transaction.atomic(): Paper.objects\\ .filter(pubmed_id__in=existing_abstract_ids)\\ .exclude(pubmed_id__in=ids_from_query)\\ .delete() ids_to_add",
"transaction.atomic(): return map(lambda data: Paper.create_paper_from_data(data, review, pool), papers) def get_absolute_url(self): return self.review.get_absolute_url() +",
"pool'), (DOCUMENT_POOL, 'Document pool'), (FINAL_POOL, 'Final pool'), (REJECTED, 'Rejected') ) review = models.ForeignKey(Review)",
".delete() ids_to_add = list(set(ids_from_query).difference(existing_ids)) if ids_to_add: Paper.create_papers_from_pubmed_ids(ids_to_add, self) def paper_pool_percentages(self): # TODO: Typically,",
"models.CharField(max_length=128) authors = models.CharField(max_length=128) abstract = models.TextField(default=\"\") publish_date = models.DateField(null=True) url = models.URLField(default=\"\")",
"django.db import models from django.template.defaultfilters import slugify from django.utils.html import escape from django.db",
"user = User.objects.get(username=invitee) else: user = User.objects.get(email=invitee) self.participants.add(user) def clean(self): if (not self.participants)",
"transaction from sysrev.api.PubMed import _get_authors, _get_date, url_from_id, read_papers_from_ids from sysrev.api import PubMed class",
"document, \"final\": final, \"rejected\": rejected, \"progress\": progress} else: return def paper_pool_counts(self): relevant_papers =",
"= relevant_papers.filter(pool=\"R\").count() return {\"abstract\": abstract_count, \"document\": document_count, \"final\": final_count, \"rejected\": rejected_count, \"remaining\": abstract_count",
"100.0 document = (counts[\"document\"] / total) * 100.0 final = (counts[\"final\"] / total)",
"< min_percent: counts[key] = new = (min_percent * total) / 100.0 total +=",
".filter(pubmed_id__in=existing_abstract_ids)\\ .exclude(pubmed_id__in=ids_from_query)\\ .delete() ids_to_add = list(set(ids_from_query).difference(existing_ids)) if ids_to_add: Paper.create_papers_from_pubmed_ids(ids_to_add, self) def paper_pool_percentages(self): #",
"(DOCUMENT_POOL, 'Document pool'), (FINAL_POOL, 'Final pool'), (REJECTED, 'Rejected') ) review = models.ForeignKey(Review) title",
"existing_abstract_ids += [paper.pubmed_id] with transaction.atomic(): Paper.objects\\ .filter(pubmed_id__in=existing_abstract_ids)\\ .exclude(pubmed_id__in=ids_from_query)\\ .delete() ids_to_add = list(set(ids_from_query).difference(existing_ids)) if",
"= (counts[\"abstract\"] / total) * 100.0 document = (counts[\"document\"] / total) * 100.0",
"* 100.0 rejected = (counts[\"rejected\"] / total) * 100.0 return {\"abstract\": abstract, \"document\":",
"abstract = (counts[\"abstract\"] / total) * 100.0 document = (counts[\"document\"] / total) *",
"\"\"\"Creates papers from all of the given ids, in the given review and",
"at least one participant') def save(self, *args, **kwargs): self.slug = slugify(self.title) super(Review, self).save()",
"[paper.pubmed_id] with transaction.atomic(): Paper.objects\\ .filter(pubmed_id__in=existing_abstract_ids)\\ .exclude(pubmed_id__in=ids_from_query)\\ .delete() ids_to_add = list(set(ids_from_query).difference(existing_ids)) if ids_to_add: Paper.create_papers_from_pubmed_ids(ids_to_add,",
"abstractText paper.publish_date = _get_date(medlineCitation) paper.url = url_from_id(pubmed_id) paper.notes = \"\" paper.pool = pool",
"args=[str(self.pk)])[:-1] + \"-\" + self.slug def __unicode__(self): return str(self.pk) + \": \" +",
"= PubMed.get_ids_from_query(self.query) if self.paper_pool_counts()[\"abstract\"] == 0: Paper.create_papers_from_pubmed_ids(ids_from_query, self) else: papers = Paper.objects.filter(review=self) existing_ids",
"\"\"\"Creates Paper model from given data, review and pool\"\"\" medlineCitation = data[u'MedlineCitation'] article",
"Paper.objects.filter(review=self) abstract_count = relevant_papers.filter(pool=\"A\").count() document_count = relevant_papers.filter(pool=\"D\").count() final_count = relevant_papers.filter(pool=\"F\").count() rejected_count = relevant_papers.filter(pool=\"R\").count()",
"def get_absolute_url(self): return self.review.get_absolute_url() + \"/\" + str(self.pk) def __unicode__(self): return str(self.review) +",
"discard existing papers if there are any ids_from_query = PubMed.get_ids_from_query(self.query) if self.paper_pool_counts()[\"abstract\"] ==",
"def get_absolute_url(self): return reverse('review_detail', args=[str(self.pk)])[:-1] + \"-\" + self.slug def __unicode__(self): return str(self.pk)",
"+ \"</h4>\" except AttributeError: pass abstractText += escape(stringElement) + \"\\n\\n\" except KeyError: pass",
"_get_date(medlineCitation) paper.url = url_from_id(pubmed_id) paper.notes = \"\" paper.pool = pool paper.save() return paper",
"* 100.0 if result != 0.0 and result < min_percent: counts[key] = new",
"float(counts[\"total\"]) if total is not 0: progress = ((counts[\"final\"] + counts[\"rejected\"]) / total)",
"total) * 100.0 rejected = (counts[\"rejected\"] / total) * 100.0 return {\"abstract\": abstract,",
"'A' DOCUMENT_POOL = 'D' FINAL_POOL = 'F' REJECTED = 'R' POOLS = (",
"stringElement in article[u'Abstract'][u'AbstractText']: try: abstractText += \"<h4>\" + escape(stringElement.attributes[u'Label']) + \"</h4>\" except AttributeError:",
"paper.authors = _get_authors(article) abstractText = \"\" try: for stringElement in article[u'Abstract'][u'AbstractText']: try: abstractText",
"= models.CharField(max_length=128) abstract = models.TextField(default=\"\") publish_date = models.DateField(null=True) url = models.URLField(default=\"\") pubmed_id =",
"relevant_papers = Paper.objects.filter(review=self) abstract_count = relevant_papers.filter(pool=\"A\").count() document_count = relevant_papers.filter(pool=\"D\").count() final_count = relevant_papers.filter(pool=\"F\").count() rejected_count",
"= models.ManyToManyField(User) title = models.CharField(max_length=128, unique=False) slug = models.SlugField() description = models.TextField(default=\"\") date_created",
"= self.paper_pool_counts() total = float(counts[\"total\"]) if total is not 0: progress = ((counts[\"final\"]",
"old = counts[key] = float(counts[key]) result = (counts[key] / total) * 100.0 if",
"def create_papers_from_pubmed_ids(ids, review, pool='A'): \"\"\"Creates papers from all of the given ids, in",
"import _get_authors, _get_date, url_from_id, read_papers_from_ids from sysrev.api import PubMed class Review(models.Model): participants =",
"5.0 for key in counts: if key == \"total\": continue old = counts[key]",
"rejected = (counts[\"rejected\"] / total) * 100.0 return {\"abstract\": abstract, \"document\": document, \"final\":",
"total) * 100.0 # minimum display percentage min_percent = 5.0 for key in",
"then this gets called. # Seems a bit wasteful, as it ends up",
"def __unicode__(self): return str(self.pk) + \": \" + self.title class Paper(models.Model): ABSTRACT_POOL =",
"repeatedly counts = self.paper_pool_counts() total = float(counts[\"total\"]) if total is not 0: progress",
"= pool paper.save() return paper @staticmethod def create_papers_from_pubmed_ids(ids, review, pool='A'): \"\"\"Creates papers from",
"every save call when creating lots of papers with transaction.atomic(): return map(lambda data:",
"abstractText += escape(stringElement) + \"\\n\\n\" except KeyError: pass paper.abstract = abstractText paper.publish_date =",
"publish_date = models.DateField(null=True) url = models.URLField(default=\"\") pubmed_id = models.CharField(max_length=16) notes = models.TextField(default=\"\") pool",
"of papers with transaction.atomic(): return map(lambda data: Paper.create_paper_from_data(data, review, pool), papers) def get_absolute_url(self):",
"review paper.authors = _get_authors(article) abstractText = \"\" try: for stringElement in article[u'Abstract'][u'AbstractText']: try:",
"rejected, \"progress\": progress} else: return def paper_pool_counts(self): relevant_papers = Paper.objects.filter(review=self) abstract_count = relevant_papers.filter(pool=\"A\").count()",
"review and pool\"\"\" medlineCitation = data[u'MedlineCitation'] article = medlineCitation[u'Article'] title = article[u'ArticleTitle'].lstrip(\"[\").rstrip(\"].\") pubmed_id",
"pubmed_id=pubmed_id)[0] paper.review = review paper.authors = _get_authors(article) abstractText = \"\" try: for stringElement",
"are any ids_from_query = PubMed.get_ids_from_query(self.query) if self.paper_pool_counts()[\"abstract\"] == 0: Paper.create_papers_from_pubmed_ids(ids_from_query, self) else: papers",
"return {\"abstract\": abstract, \"document\": document, \"final\": final, \"rejected\": rejected, \"progress\": progress} else: return",
"counts[\"rejected\"]) / total) * 100.0 # minimum display percentage min_percent = 5.0 for",
"_get_authors(article) abstractText = \"\" try: for stringElement in article[u'Abstract'][u'AbstractText']: try: abstractText += \"<h4>\"",
"save call when creating lots of papers with transaction.atomic(): return map(lambda data: Paper.create_paper_from_data(data,",
"if there are any ids_from_query = PubMed.get_ids_from_query(self.query) if self.paper_pool_counts()[\"abstract\"] == 0: Paper.create_papers_from_pubmed_ids(ids_from_query, self)",
"\"\" paper.pool = pool paper.save() return paper @staticmethod def create_papers_from_pubmed_ids(ids, review, pool='A'): \"\"\"Creates",
"/ total) * 100.0 if result != 0.0 and result < min_percent: counts[key]",
"relevant_papers.filter(pool=\"R\").count() return {\"abstract\": abstract_count, \"document\": document_count, \"final\": final_count, \"rejected\": rejected_count, \"remaining\": abstract_count +",
"= (min_percent * total) / 100.0 total += new - old abstract =",
"* 100.0 final = (counts[\"final\"] / total) * 100.0 rejected = (counts[\"rejected\"] /",
"= read_papers_from_ids(ids) # Commit all papers in single transaction # Improves performance, as",
"(counts[\"abstract\"] / total) * 100.0 document = (counts[\"document\"] / total) * 100.0 final",
"models.DateTimeField(default=None, null=True) query = models.TextField(default=\"\") def perform_query(self): # TODO: discard existing papers if",
"lots of papers with transaction.atomic(): return map(lambda data: Paper.create_paper_from_data(data, review, pool), papers) def",
"= (counts[\"document\"] / total) * 100.0 final = (counts[\"final\"] / total) * 100.0",
"__unicode__(self): return str(self.pk) + \": \" + self.title class Paper(models.Model): ABSTRACT_POOL = 'A'",
"existing papers if there are any ids_from_query = PubMed.get_ids_from_query(self.query) if self.paper_pool_counts()[\"abstract\"] == 0:",
"= list(set(ids_from_query).difference(existing_ids)) if ids_to_add: Paper.create_papers_from_pubmed_ids(ids_to_add, self) def paper_pool_percentages(self): # TODO: Typically, paper_pool_counts() gets",
"= ( (ABSTRACT_POOL, 'Abstract pool'), (DOCUMENT_POOL, 'Document pool'), (FINAL_POOL, 'Final pool'), (REJECTED, 'Rejected')",
"# minimum display percentage min_percent = 5.0 for key in counts: if key",
"'D' FINAL_POOL = 'F' REJECTED = 'R' POOLS = ( (ABSTRACT_POOL, 'Abstract pool'),",
"import slugify from django.utils.html import escape from django.db import transaction from sysrev.api.PubMed import",
"((counts[\"final\"] + counts[\"rejected\"]) / total) * 100.0 # minimum display percentage min_percent =",
"+= [paper.pubmed_id] with transaction.atomic(): Paper.objects\\ .filter(pubmed_id__in=existing_abstract_ids)\\ .exclude(pubmed_id__in=ids_from_query)\\ .delete() ids_to_add = list(set(ids_from_query).difference(existing_ids)) if ids_to_add:",
"== -1: user = User.objects.get(username=invitee) else: user = User.objects.get(email=invitee) self.participants.add(user) def clean(self): if",
"transaction # Improves performance, as django won't automatically commit after every save call",
"= models.CharField(max_length=128, unique=False) slug = models.SlugField() description = models.TextField(default=\"\") date_created = models.DateTimeField(auto_now_add=True) last_modified",
"from given data, review and pool\"\"\" medlineCitation = data[u'MedlineCitation'] article = medlineCitation[u'Article'] title",
"title=title, pubmed_id=pubmed_id)[0] paper.review = review paper.authors = _get_authors(article) abstractText = \"\" try: for",
"= None if invitee.find(\"@\") == -1: user = User.objects.get(username=invitee) else: user = User.objects.get(email=invitee)",
"document_count + final_count + rejected_count} def invite(self, invitees): for invitee in invitees: user",
"rejected_count} def invite(self, invitees): for invitee in invitees: user = None if invitee.find(\"@\")",
"+ \"-\" + self.slug def __unicode__(self): return str(self.pk) + \": \" + self.title",
"= data[u'MedlineCitation'] article = medlineCitation[u'Article'] title = article[u'ArticleTitle'].lstrip(\"[\").rstrip(\"].\") pubmed_id = medlineCitation[u'PMID'] paper =",
"choices=POOLS, default=ABSTRACT_POOL) @staticmethod def create_paper_from_data(data, review, pool): \"\"\"Creates Paper model from given data,",
"for stringElement in article[u'Abstract'][u'AbstractText']: try: abstractText += \"<h4>\" + escape(stringElement.attributes[u'Label']) + \"</h4>\" except",
"return map(lambda data: Paper.create_paper_from_data(data, review, pool), papers) def get_absolute_url(self): return self.review.get_absolute_url() + \"/\"",
"it ends up running multiple times and querying counts repeatedly counts = self.paper_pool_counts()",
"notes = models.TextField(default=\"\") pool = models.CharField(max_length=1, choices=POOLS, default=ABSTRACT_POOL) @staticmethod def create_paper_from_data(data, review, pool):",
"invitees): for invitee in invitees: user = None if invitee.find(\"@\") == -1: user",
"(counts[key] / total) * 100.0 if result != 0.0 and result < min_percent:",
"/ 100.0 total += new - old abstract = (counts[\"abstract\"] / total) *",
"TODO: discard existing papers if there are any ids_from_query = PubMed.get_ids_from_query(self.query) if self.paper_pool_counts()[\"abstract\"]",
"total += new - old abstract = (counts[\"abstract\"] / total) * 100.0 document",
"given ids, in the given review and pool\"\"\" papers = read_papers_from_ids(ids) # Commit",
"self.title class Paper(models.Model): ABSTRACT_POOL = 'A' DOCUMENT_POOL = 'D' FINAL_POOL = 'F' REJECTED",
"there are any ids_from_query = PubMed.get_ids_from_query(self.query) if self.paper_pool_counts()[\"abstract\"] == 0: Paper.create_papers_from_pubmed_ids(ids_from_query, self) else:",
"abstract_count + document_count, \"total\": abstract_count + document_count + final_count + rejected_count} def invite(self,",
"-1: user = User.objects.get(username=invitee) else: user = User.objects.get(email=invitee) self.participants.add(user) def clean(self): if (not",
"title = article[u'ArticleTitle'].lstrip(\"[\").rstrip(\"].\") pubmed_id = medlineCitation[u'PMID'] paper = Paper.objects.get_or_create(review=review, title=title, pubmed_id=pubmed_id)[0] paper.review =",
"= medlineCitation[u'PMID'] paper = Paper.objects.get_or_create(review=review, title=title, pubmed_id=pubmed_id)[0] paper.review = review paper.authors = _get_authors(article)",
"self.participants.count() < 1: raise ValidationError('Need at least one participant') def save(self, *args, **kwargs):",
"{\"abstract\": abstract, \"document\": document, \"final\": final, \"rejected\": rejected, \"progress\": progress} else: return def",
"in article[u'Abstract'][u'AbstractText']: try: abstractText += \"<h4>\" + escape(stringElement.attributes[u'Label']) + \"</h4>\" except AttributeError: pass",
"self) else: papers = Paper.objects.filter(review=self) existing_ids = [] for paper in papers: existing_ids",
"User.objects.get(email=invitee) self.participants.add(user) def clean(self): if (not self.participants) or self.participants.count() < 1: raise ValidationError('Need",
"Paper.objects\\ .filter(pubmed_id__in=existing_abstract_ids)\\ .exclude(pubmed_id__in=ids_from_query)\\ .delete() ids_to_add = list(set(ids_from_query).difference(existing_ids)) if ids_to_add: Paper.create_papers_from_pubmed_ids(ids_to_add, self) def paper_pool_percentages(self):",
"except KeyError: pass paper.abstract = abstractText paper.publish_date = _get_date(medlineCitation) paper.url = url_from_id(pubmed_id) paper.notes",
"counts[key] = new = (min_percent * total) / 100.0 total += new -",
"in single transaction # Improves performance, as django won't automatically commit after every",
"invitee.find(\"@\") == -1: user = User.objects.get(username=invitee) else: user = User.objects.get(email=invitee) self.participants.add(user) def clean(self):",
"!= 0.0 and result < min_percent: counts[key] = new = (min_percent * total)",
"perform_query(self): # TODO: discard existing papers if there are any ids_from_query = PubMed.get_ids_from_query(self.query)",
"rejected_count = relevant_papers.filter(pool=\"R\").count() return {\"abstract\": abstract_count, \"document\": document_count, \"final\": final_count, \"rejected\": rejected_count, \"remaining\":",
"paper.notes = \"\" paper.pool = pool paper.save() return paper @staticmethod def create_papers_from_pubmed_ids(ids, review,",
"invitee in invitees: user = None if invitee.find(\"@\") == -1: user = User.objects.get(username=invitee)",
"= float(counts[\"total\"]) if total is not 0: progress = ((counts[\"final\"] + counts[\"rejected\"]) /",
"read_papers_from_ids(ids) # Commit all papers in single transaction # Improves performance, as django",
"_get_authors, _get_date, url_from_id, read_papers_from_ids from sysrev.api import PubMed class Review(models.Model): participants = models.ManyToManyField(User)",
"= models.TextField(default=\"\") pool = models.CharField(max_length=1, choices=POOLS, default=ABSTRACT_POOL) @staticmethod def create_paper_from_data(data, review, pool): \"\"\"Creates",
"total is not 0: progress = ((counts[\"final\"] + counts[\"rejected\"]) / total) * 100.0",
"reverse from django.db import models from django.template.defaultfilters import slugify from django.utils.html import escape",
"final = (counts[\"final\"] / total) * 100.0 rejected = (counts[\"rejected\"] / total) *",
"Paper.objects.get_or_create(review=review, title=title, pubmed_id=pubmed_id)[0] paper.review = review paper.authors = _get_authors(article) abstractText = \"\" try:",
"up running multiple times and querying counts repeatedly counts = self.paper_pool_counts() total =",
"100.0 total += new - old abstract = (counts[\"abstract\"] / total) * 100.0",
"participant') def save(self, *args, **kwargs): self.slug = slugify(self.title) super(Review, self).save() def get_absolute_url(self): return",
"completed = models.BooleanField(default=False) date_completed = models.DateTimeField(default=None, null=True) query = models.TextField(default=\"\") def perform_query(self): #",
"super(Review, self).save() def get_absolute_url(self): return reverse('review_detail', args=[str(self.pk)])[:-1] + \"-\" + self.slug def __unicode__(self):",
"escape(stringElement.attributes[u'Label']) + \"</h4>\" except AttributeError: pass abstractText += escape(stringElement) + \"\\n\\n\" except KeyError:",
"PubMed class Review(models.Model): participants = models.ManyToManyField(User) title = models.CharField(max_length=128, unique=False) slug = models.SlugField()",
"as it ends up running multiple times and querying counts repeatedly counts =",
"total) * 100.0 final = (counts[\"final\"] / total) * 100.0 rejected = (counts[\"rejected\"]",
"100.0 final = (counts[\"final\"] / total) * 100.0 rejected = (counts[\"rejected\"] / total)",
"return def paper_pool_counts(self): relevant_papers = Paper.objects.filter(review=self) abstract_count = relevant_papers.filter(pool=\"A\").count() document_count = relevant_papers.filter(pool=\"D\").count() final_count",
"create_papers_from_pubmed_ids(ids, review, pool='A'): \"\"\"Creates papers from all of the given ids, in the",
"map(lambda data: Paper.create_paper_from_data(data, review, pool), papers) def get_absolute_url(self): return self.review.get_absolute_url() + \"/\" +",
"= models.ForeignKey(Review) title = models.CharField(max_length=128) authors = models.CharField(max_length=128) abstract = models.TextField(default=\"\") publish_date =",
"models.TextField(default=\"\") def perform_query(self): # TODO: discard existing papers if there are any ids_from_query",
"ends up running multiple times and querying counts repeatedly counts = self.paper_pool_counts() total",
"paper in papers: existing_ids += [paper.pubmed_id] existing_abstract_ids = [] for paper in papers.filter(pool=\"A\"):",
"in papers: existing_ids += [paper.pubmed_id] existing_abstract_ids = [] for paper in papers.filter(pool=\"A\"): existing_abstract_ids",
"'Rejected') ) review = models.ForeignKey(Review) title = models.CharField(max_length=128) authors = models.CharField(max_length=128) abstract =",
"gets called. # Seems a bit wasteful, as it ends up running multiple",
"called. # Seems a bit wasteful, as it ends up running multiple times",
"[paper.pubmed_id] existing_abstract_ids = [] for paper in papers.filter(pool=\"A\"): existing_abstract_ids += [paper.pubmed_id] with transaction.atomic():",
"won't automatically commit after every save call when creating lots of papers with",
"review = models.ForeignKey(Review) title = models.CharField(max_length=128) authors = models.CharField(max_length=128) abstract = models.TextField(default=\"\") publish_date",
"date_completed = models.DateTimeField(default=None, null=True) query = models.TextField(default=\"\") def perform_query(self): # TODO: discard existing",
"abstractText += \"<h4>\" + escape(stringElement.attributes[u'Label']) + \"</h4>\" except AttributeError: pass abstractText += escape(stringElement)",
"pool = models.CharField(max_length=1, choices=POOLS, default=ABSTRACT_POOL) @staticmethod def create_paper_from_data(data, review, pool): \"\"\"Creates Paper model",
"models.ManyToManyField(User) title = models.CharField(max_length=128, unique=False) slug = models.SlugField() description = models.TextField(default=\"\") date_created =",
"models from django.template.defaultfilters import slugify from django.utils.html import escape from django.db import transaction",
"times and querying counts repeatedly counts = self.paper_pool_counts() total = float(counts[\"total\"]) if total",
"= [] for paper in papers.filter(pool=\"A\"): existing_abstract_ids += [paper.pubmed_id] with transaction.atomic(): Paper.objects\\ .filter(pubmed_id__in=existing_abstract_ids)\\",
"= new = (min_percent * total) / 100.0 total += new - old",
"article = medlineCitation[u'Article'] title = article[u'ArticleTitle'].lstrip(\"[\").rstrip(\"].\") pubmed_id = medlineCitation[u'PMID'] paper = Paper.objects.get_or_create(review=review, title=title,",
"all papers in single transaction # Improves performance, as django won't automatically commit",
"escape(stringElement) + \"\\n\\n\" except KeyError: pass paper.abstract = abstractText paper.publish_date = _get_date(medlineCitation) paper.url",
"import ValidationError from django.core.urlresolvers import reverse from django.db import models from django.template.defaultfilters import",
"models.URLField(default=\"\") pubmed_id = models.CharField(max_length=16) notes = models.TextField(default=\"\") pool = models.CharField(max_length=1, choices=POOLS, default=ABSTRACT_POOL) @staticmethod",
"any ids_from_query = PubMed.get_ids_from_query(self.query) if self.paper_pool_counts()[\"abstract\"] == 0: Paper.create_papers_from_pubmed_ids(ids_from_query, self) else: papers =",
"the given review and pool\"\"\" papers = read_papers_from_ids(ids) # Commit all papers in",
"automatically commit after every save call when creating lots of papers with transaction.atomic():",
"if result != 0.0 and result < min_percent: counts[key] = new = (min_percent",
"= _get_date(medlineCitation) paper.url = url_from_id(pubmed_id) paper.notes = \"\" paper.pool = pool paper.save() return",
"ValidationError from django.core.urlresolvers import reverse from django.db import models from django.template.defaultfilters import slugify",
"float(counts[key]) result = (counts[key] / total) * 100.0 if result != 0.0 and",
"min_percent = 5.0 for key in counts: if key == \"total\": continue old",
"relevant_papers.filter(pool=\"A\").count() document_count = relevant_papers.filter(pool=\"D\").count() final_count = relevant_papers.filter(pool=\"F\").count() rejected_count = relevant_papers.filter(pool=\"R\").count() return {\"abstract\": abstract_count,",
"Typically, paper_pool_counts() gets called then this gets called. # Seems a bit wasteful,",
"User from django.core.exceptions import ValidationError from django.core.urlresolvers import reverse from django.db import models",
"paper.pool = pool paper.save() return paper @staticmethod def create_papers_from_pubmed_ids(ids, review, pool='A'): \"\"\"Creates papers",
"DOCUMENT_POOL = 'D' FINAL_POOL = 'F' REJECTED = 'R' POOLS = ( (ABSTRACT_POOL,",
"papers) def get_absolute_url(self): return self.review.get_absolute_url() + \"/\" + str(self.pk) def __unicode__(self): return str(self.review)",
"existing_abstract_ids = [] for paper in papers.filter(pool=\"A\"): existing_abstract_ids += [paper.pubmed_id] with transaction.atomic(): Paper.objects\\",
"return reverse('review_detail', args=[str(self.pk)])[:-1] + \"-\" + self.slug def __unicode__(self): return str(self.pk) + \":",
"a bit wasteful, as it ends up running multiple times and querying counts",
"date_created = models.DateTimeField(auto_now_add=True) last_modified = models.DateTimeField(auto_now=True) completed = models.BooleanField(default=False) date_completed = models.DateTimeField(default=None, null=True)",
"creating lots of papers with transaction.atomic(): return map(lambda data: Paper.create_paper_from_data(data, review, pool), papers)",
"models.CharField(max_length=128, unique=False) slug = models.SlugField() description = models.TextField(default=\"\") date_created = models.DateTimeField(auto_now_add=True) last_modified =",
"for paper in papers: existing_ids += [paper.pubmed_id] existing_abstract_ids = [] for paper in",
"given review and pool\"\"\" papers = read_papers_from_ids(ids) # Commit all papers in single",
"min_percent: counts[key] = new = (min_percent * total) / 100.0 total += new",
"import PubMed class Review(models.Model): participants = models.ManyToManyField(User) title = models.CharField(max_length=128, unique=False) slug =",
"paper_pool_counts(self): relevant_papers = Paper.objects.filter(review=self) abstract_count = relevant_papers.filter(pool=\"A\").count() document_count = relevant_papers.filter(pool=\"D\").count() final_count = relevant_papers.filter(pool=\"F\").count()",
"{\"abstract\": abstract_count, \"document\": document_count, \"final\": final_count, \"rejected\": rejected_count, \"remaining\": abstract_count + document_count, \"total\":",
"medlineCitation[u'PMID'] paper = Paper.objects.get_or_create(review=review, title=title, pubmed_id=pubmed_id)[0] paper.review = review paper.authors = _get_authors(article) abstractText",
"= relevant_papers.filter(pool=\"D\").count() final_count = relevant_papers.filter(pool=\"F\").count() rejected_count = relevant_papers.filter(pool=\"R\").count() return {\"abstract\": abstract_count, \"document\": document_count,",
"1: raise ValidationError('Need at least one participant') def save(self, *args, **kwargs): self.slug =",
"relevant_papers.filter(pool=\"F\").count() rejected_count = relevant_papers.filter(pool=\"R\").count() return {\"abstract\": abstract_count, \"document\": document_count, \"final\": final_count, \"rejected\": rejected_count,",
"for paper in papers.filter(pool=\"A\"): existing_abstract_ids += [paper.pubmed_id] with transaction.atomic(): Paper.objects\\ .filter(pubmed_id__in=existing_abstract_ids)\\ .exclude(pubmed_id__in=ids_from_query)\\ .delete()",
"list(set(ids_from_query).difference(existing_ids)) if ids_to_add: Paper.create_papers_from_pubmed_ids(ids_to_add, self) def paper_pool_percentages(self): # TODO: Typically, paper_pool_counts() gets called",
"\"final\": final_count, \"rejected\": rejected_count, \"remaining\": abstract_count + document_count, \"total\": abstract_count + document_count +",
"+ self.title class Paper(models.Model): ABSTRACT_POOL = 'A' DOCUMENT_POOL = 'D' FINAL_POOL = 'F'",
"pubmed_id = models.CharField(max_length=16) notes = models.TextField(default=\"\") pool = models.CharField(max_length=1, choices=POOLS, default=ABSTRACT_POOL) @staticmethod def",
"pass paper.abstract = abstractText paper.publish_date = _get_date(medlineCitation) paper.url = url_from_id(pubmed_id) paper.notes = \"\"",
"# Improves performance, as django won't automatically commit after every save call when",
"return str(self.pk) + \": \" + self.title class Paper(models.Model): ABSTRACT_POOL = 'A' DOCUMENT_POOL",
"if ids_to_add: Paper.create_papers_from_pubmed_ids(ids_to_add, self) def paper_pool_percentages(self): # TODO: Typically, paper_pool_counts() gets called then",
"= \"\" try: for stringElement in article[u'Abstract'][u'AbstractText']: try: abstractText += \"<h4>\" + escape(stringElement.attributes[u'Label'])",
"models.DateField(null=True) url = models.URLField(default=\"\") pubmed_id = models.CharField(max_length=16) notes = models.TextField(default=\"\") pool = models.CharField(max_length=1,",
"\"final\": final, \"rejected\": rejected, \"progress\": progress} else: return def paper_pool_counts(self): relevant_papers = Paper.objects.filter(review=self)",
"( (ABSTRACT_POOL, 'Abstract pool'), (DOCUMENT_POOL, 'Document pool'), (FINAL_POOL, 'Final pool'), (REJECTED, 'Rejected') )",
"'Abstract pool'), (DOCUMENT_POOL, 'Document pool'), (FINAL_POOL, 'Final pool'), (REJECTED, 'Rejected') ) review =",
"data: Paper.create_paper_from_data(data, review, pool), papers) def get_absolute_url(self): return self.review.get_absolute_url() + \"/\" + str(self.pk)",
"TODO: Typically, paper_pool_counts() gets called then this gets called. # Seems a bit",
"if key == \"total\": continue old = counts[key] = float(counts[key]) result = (counts[key]",
"existing_ids = [] for paper in papers: existing_ids += [paper.pubmed_id] existing_abstract_ids = []",
"running multiple times and querying counts repeatedly counts = self.paper_pool_counts() total = float(counts[\"total\"])",
"(FINAL_POOL, 'Final pool'), (REJECTED, 'Rejected') ) review = models.ForeignKey(Review) title = models.CharField(max_length=128) authors",
"url_from_id(pubmed_id) paper.notes = \"\" paper.pool = pool paper.save() return paper @staticmethod def create_papers_from_pubmed_ids(ids,",
"= models.SlugField() description = models.TextField(default=\"\") date_created = models.DateTimeField(auto_now_add=True) last_modified = models.DateTimeField(auto_now=True) completed =",
"\"\" try: for stringElement in article[u'Abstract'][u'AbstractText']: try: abstractText += \"<h4>\" + escape(stringElement.attributes[u'Label']) +",
"pool), papers) def get_absolute_url(self): return self.review.get_absolute_url() + \"/\" + str(self.pk) def __unicode__(self): return",
"AttributeError: pass abstractText += escape(stringElement) + \"\\n\\n\" except KeyError: pass paper.abstract = abstractText",
"\"total\": abstract_count + document_count + final_count + rejected_count} def invite(self, invitees): for invitee",
"for invitee in invitees: user = None if invitee.find(\"@\") == -1: user =",
"ValidationError('Need at least one participant') def save(self, *args, **kwargs): self.slug = slugify(self.title) super(Review,",
"django.core.exceptions import ValidationError from django.core.urlresolvers import reverse from django.db import models from django.template.defaultfilters",
"Paper model from given data, review and pool\"\"\" medlineCitation = data[u'MedlineCitation'] article =",
"None if invitee.find(\"@\") == -1: user = User.objects.get(username=invitee) else: user = User.objects.get(email=invitee) self.participants.add(user)",
"after every save call when creating lots of papers with transaction.atomic(): return map(lambda",
"papers in single transaction # Improves performance, as django won't automatically commit after",
"unique=False) slug = models.SlugField() description = models.TextField(default=\"\") date_created = models.DateTimeField(auto_now_add=True) last_modified = models.DateTimeField(auto_now=True)",
"description = models.TextField(default=\"\") date_created = models.DateTimeField(auto_now_add=True) last_modified = models.DateTimeField(auto_now=True) completed = models.BooleanField(default=False) date_completed",
"import User from django.core.exceptions import ValidationError from django.core.urlresolvers import reverse from django.db import",
"self.slug def __unicode__(self): return str(self.pk) + \": \" + self.title class Paper(models.Model): ABSTRACT_POOL",
"total) * 100.0 if result != 0.0 and result < min_percent: counts[key] =",
"abstract, \"document\": document, \"final\": final, \"rejected\": rejected, \"progress\": progress} else: return def paper_pool_counts(self):",
"100.0 if result != 0.0 and result < min_percent: counts[key] = new =",
"= 'A' DOCUMENT_POOL = 'D' FINAL_POOL = 'F' REJECTED = 'R' POOLS =",
"self.paper_pool_counts()[\"abstract\"] == 0: Paper.create_papers_from_pubmed_ids(ids_from_query, self) else: papers = Paper.objects.filter(review=self) existing_ids = [] for",
"paper @staticmethod def create_papers_from_pubmed_ids(ids, review, pool='A'): \"\"\"Creates papers from all of the given",
"= User.objects.get(email=invitee) self.participants.add(user) def clean(self): if (not self.participants) or self.participants.count() < 1: raise",
"abstract_count + document_count + final_count + rejected_count} def invite(self, invitees): for invitee in",
"self.participants) or self.participants.count() < 1: raise ValidationError('Need at least one participant') def save(self,",
"django.template.defaultfilters import slugify from django.utils.html import escape from django.db import transaction from sysrev.api.PubMed",
"Improves performance, as django won't automatically commit after every save call when creating",
"= slugify(self.title) super(Review, self).save() def get_absolute_url(self): return reverse('review_detail', args=[str(self.pk)])[:-1] + \"-\" + self.slug",
"= Paper.objects.filter(review=self) existing_ids = [] for paper in papers: existing_ids += [paper.pubmed_id] existing_abstract_ids",
"models.TextField(default=\"\") publish_date = models.DateField(null=True) url = models.URLField(default=\"\") pubmed_id = models.CharField(max_length=16) notes = models.TextField(default=\"\")",
"def perform_query(self): # TODO: discard existing papers if there are any ids_from_query =",
"[] for paper in papers.filter(pool=\"A\"): existing_abstract_ids += [paper.pubmed_id] with transaction.atomic(): Paper.objects\\ .filter(pubmed_id__in=existing_abstract_ids)\\ .exclude(pubmed_id__in=ids_from_query)\\",
"Commit all papers in single transaction # Improves performance, as django won't automatically",
"/ total) * 100.0 return {\"abstract\": abstract, \"document\": document, \"final\": final, \"rejected\": rejected,",
"+= [paper.pubmed_id] existing_abstract_ids = [] for paper in papers.filter(pool=\"A\"): existing_abstract_ids += [paper.pubmed_id] with",
"= float(counts[key]) result = (counts[key] / total) * 100.0 if result != 0.0",
"Paper.create_papers_from_pubmed_ids(ids_from_query, self) else: papers = Paper.objects.filter(review=self) existing_ids = [] for paper in papers:",
"invite(self, invitees): for invitee in invitees: user = None if invitee.find(\"@\") == -1:",
"self.paper_pool_counts() total = float(counts[\"total\"]) if total is not 0: progress = ((counts[\"final\"] +",
"# Seems a bit wasteful, as it ends up running multiple times and",
"from django.contrib.auth.models import User from django.core.exceptions import ValidationError from django.core.urlresolvers import reverse from",
"result != 0.0 and result < min_percent: counts[key] = new = (min_percent *",
"\": \" + self.title class Paper(models.Model): ABSTRACT_POOL = 'A' DOCUMENT_POOL = 'D' FINAL_POOL",
"+= \"<h4>\" + escape(stringElement.attributes[u'Label']) + \"</h4>\" except AttributeError: pass abstractText += escape(stringElement) +",
"self) def paper_pool_percentages(self): # TODO: Typically, paper_pool_counts() gets called then this gets called.",
"invitees: user = None if invitee.find(\"@\") == -1: user = User.objects.get(username=invitee) else: user",
"called then this gets called. # Seems a bit wasteful, as it ends",
"display percentage min_percent = 5.0 for key in counts: if key == \"total\":",
"escape from django.db import transaction from sysrev.api.PubMed import _get_authors, _get_date, url_from_id, read_papers_from_ids from",
"data[u'MedlineCitation'] article = medlineCitation[u'Article'] title = article[u'ArticleTitle'].lstrip(\"[\").rstrip(\"].\") pubmed_id = medlineCitation[u'PMID'] paper = Paper.objects.get_or_create(review=review,",
"ids_from_query = PubMed.get_ids_from_query(self.query) if self.paper_pool_counts()[\"abstract\"] == 0: Paper.create_papers_from_pubmed_ids(ids_from_query, self) else: papers = Paper.objects.filter(review=self)",
"title = models.CharField(max_length=128, unique=False) slug = models.SlugField() description = models.TextField(default=\"\") date_created = models.DateTimeField(auto_now_add=True)",
"100.0 rejected = (counts[\"rejected\"] / total) * 100.0 return {\"abstract\": abstract, \"document\": document,",
"= 'R' POOLS = ( (ABSTRACT_POOL, 'Abstract pool'), (DOCUMENT_POOL, 'Document pool'), (FINAL_POOL, 'Final",
"(counts[\"document\"] / total) * 100.0 final = (counts[\"final\"] / total) * 100.0 rejected",
"and pool\"\"\" papers = read_papers_from_ids(ids) # Commit all papers in single transaction #",
"from django.core.urlresolvers import reverse from django.db import models from django.template.defaultfilters import slugify from",
"str(self.pk) + \": \" + self.title class Paper(models.Model): ABSTRACT_POOL = 'A' DOCUMENT_POOL =",
"if invitee.find(\"@\") == -1: user = User.objects.get(username=invitee) else: user = User.objects.get(email=invitee) self.participants.add(user) def",
"wasteful, as it ends up running multiple times and querying counts repeatedly counts",
"in the given review and pool\"\"\" papers = read_papers_from_ids(ids) # Commit all papers",
"all of the given ids, in the given review and pool\"\"\" papers =",
"result < min_percent: counts[key] = new = (min_percent * total) / 100.0 total",
"+ final_count + rejected_count} def invite(self, invitees): for invitee in invitees: user =",
"# TODO: Typically, paper_pool_counts() gets called then this gets called. # Seems a",
"result = (counts[key] / total) * 100.0 if result != 0.0 and result",
"try: for stringElement in article[u'Abstract'][u'AbstractText']: try: abstractText += \"<h4>\" + escape(stringElement.attributes[u'Label']) + \"</h4>\"",
"from django.utils.html import escape from django.db import transaction from sysrev.api.PubMed import _get_authors, _get_date,",
"review, pool): \"\"\"Creates Paper model from given data, review and pool\"\"\" medlineCitation =",
"url_from_id, read_papers_from_ids from sysrev.api import PubMed class Review(models.Model): participants = models.ManyToManyField(User) title =",
"document = (counts[\"document\"] / total) * 100.0 final = (counts[\"final\"] / total) *",
"paper.publish_date = _get_date(medlineCitation) paper.url = url_from_id(pubmed_id) paper.notes = \"\" paper.pool = pool paper.save()",
"def paper_pool_percentages(self): # TODO: Typically, paper_pool_counts() gets called then this gets called. #",
"def paper_pool_counts(self): relevant_papers = Paper.objects.filter(review=self) abstract_count = relevant_papers.filter(pool=\"A\").count() document_count = relevant_papers.filter(pool=\"D\").count() final_count =",
"as django won't automatically commit after every save call when creating lots of",
"self.participants.add(user) def clean(self): if (not self.participants) or self.participants.count() < 1: raise ValidationError('Need at",
"paper.url = url_from_id(pubmed_id) paper.notes = \"\" paper.pool = pool paper.save() return paper @staticmethod",
"= models.DateTimeField(default=None, null=True) query = models.TextField(default=\"\") def perform_query(self): # TODO: discard existing papers",
"gets called then this gets called. # Seems a bit wasteful, as it",
"= _get_authors(article) abstractText = \"\" try: for stringElement in article[u'Abstract'][u'AbstractText']: try: abstractText +=",
"_get_date, url_from_id, read_papers_from_ids from sysrev.api import PubMed class Review(models.Model): participants = models.ManyToManyField(User) title",
"= abstractText paper.publish_date = _get_date(medlineCitation) paper.url = url_from_id(pubmed_id) paper.notes = \"\" paper.pool =",
"(REJECTED, 'Rejected') ) review = models.ForeignKey(Review) title = models.CharField(max_length=128) authors = models.CharField(max_length=128) abstract",
"+ document_count, \"total\": abstract_count + document_count + final_count + rejected_count} def invite(self, invitees):",
"pool'), (REJECTED, 'Rejected') ) review = models.ForeignKey(Review) title = models.CharField(max_length=128) authors = models.CharField(max_length=128)",
"from django.db import models from django.template.defaultfilters import slugify from django.utils.html import escape from",
"with transaction.atomic(): Paper.objects\\ .filter(pubmed_id__in=existing_abstract_ids)\\ .exclude(pubmed_id__in=ids_from_query)\\ .delete() ids_to_add = list(set(ids_from_query).difference(existing_ids)) if ids_to_add: Paper.create_papers_from_pubmed_ids(ids_to_add, self)",
"read_papers_from_ids from sysrev.api import PubMed class Review(models.Model): participants = models.ManyToManyField(User) title = models.CharField(max_length=128,",
"return paper @staticmethod def create_papers_from_pubmed_ids(ids, review, pool='A'): \"\"\"Creates papers from all of the",
"Paper.create_papers_from_pubmed_ids(ids_to_add, self) def paper_pool_percentages(self): # TODO: Typically, paper_pool_counts() gets called then this gets",
"+= new - old abstract = (counts[\"abstract\"] / total) * 100.0 document =",
"papers from all of the given ids, in the given review and pool\"\"\"",
"+ counts[\"rejected\"]) / total) * 100.0 # minimum display percentage min_percent = 5.0",
"new - old abstract = (counts[\"abstract\"] / total) * 100.0 document = (counts[\"document\"]",
"= ((counts[\"final\"] + counts[\"rejected\"]) / total) * 100.0 # minimum display percentage min_percent",
"User.objects.get(username=invitee) else: user = User.objects.get(email=invitee) self.participants.add(user) def clean(self): if (not self.participants) or self.participants.count()",
"= 5.0 for key in counts: if key == \"total\": continue old =",
"**kwargs): self.slug = slugify(self.title) super(Review, self).save() def get_absolute_url(self): return reverse('review_detail', args=[str(self.pk)])[:-1] + \"-\"",
"participants = models.ManyToManyField(User) title = models.CharField(max_length=128, unique=False) slug = models.SlugField() description = models.TextField(default=\"\")",
"when creating lots of papers with transaction.atomic(): return map(lambda data: Paper.create_paper_from_data(data, review, pool),",
"counts[key] = float(counts[key]) result = (counts[key] / total) * 100.0 if result !=",
"model from given data, review and pool\"\"\" medlineCitation = data[u'MedlineCitation'] article = medlineCitation[u'Article']",
"REJECTED = 'R' POOLS = ( (ABSTRACT_POOL, 'Abstract pool'), (DOCUMENT_POOL, 'Document pool'), (FINAL_POOL,",
"the given ids, in the given review and pool\"\"\" papers = read_papers_from_ids(ids) #",
"\"document\": document, \"final\": final, \"rejected\": rejected, \"progress\": progress} else: return def paper_pool_counts(self): relevant_papers",
"= 'D' FINAL_POOL = 'F' REJECTED = 'R' POOLS = ( (ABSTRACT_POOL, 'Abstract",
"= relevant_papers.filter(pool=\"F\").count() rejected_count = relevant_papers.filter(pool=\"R\").count() return {\"abstract\": abstract_count, \"document\": document_count, \"final\": final_count, \"rejected\":",
"slugify from django.utils.html import escape from django.db import transaction from sysrev.api.PubMed import _get_authors,",
"\"<h4>\" + escape(stringElement.attributes[u'Label']) + \"</h4>\" except AttributeError: pass abstractText += escape(stringElement) + \"\\n\\n\"",
"(ABSTRACT_POOL, 'Abstract pool'), (DOCUMENT_POOL, 'Document pool'), (FINAL_POOL, 'Final pool'), (REJECTED, 'Rejected') ) review",
"\"</h4>\" except AttributeError: pass abstractText += escape(stringElement) + \"\\n\\n\" except KeyError: pass paper.abstract",
"\" + self.title class Paper(models.Model): ABSTRACT_POOL = 'A' DOCUMENT_POOL = 'D' FINAL_POOL =",
"* 100.0 document = (counts[\"document\"] / total) * 100.0 final = (counts[\"final\"] /",
"create_paper_from_data(data, review, pool): \"\"\"Creates Paper model from given data, review and pool\"\"\" medlineCitation",
"slugify(self.title) super(Review, self).save() def get_absolute_url(self): return reverse('review_detail', args=[str(self.pk)])[:-1] + \"-\" + self.slug def",
"get_absolute_url(self): return self.review.get_absolute_url() + \"/\" + str(self.pk) def __unicode__(self): return str(self.review) + \"",
"\"/\" + str(self.pk) def __unicode__(self): return str(self.review) + \" - \" + self.title",
"final_count, \"rejected\": rejected_count, \"remaining\": abstract_count + document_count, \"total\": abstract_count + document_count + final_count",
"= (counts[\"final\"] / total) * 100.0 rejected = (counts[\"rejected\"] / total) * 100.0",
"progress = ((counts[\"final\"] + counts[\"rejected\"]) / total) * 100.0 # minimum display percentage",
"+ self.slug def __unicode__(self): return str(self.pk) + \": \" + self.title class Paper(models.Model):",
"import reverse from django.db import models from django.template.defaultfilters import slugify from django.utils.html import",
"0: progress = ((counts[\"final\"] + counts[\"rejected\"]) / total) * 100.0 # minimum display",
"document_count = relevant_papers.filter(pool=\"D\").count() final_count = relevant_papers.filter(pool=\"F\").count() rejected_count = relevant_papers.filter(pool=\"R\").count() return {\"abstract\": abstract_count, \"document\":",
"0.0 and result < min_percent: counts[key] = new = (min_percent * total) /",
"= models.DateTimeField(auto_now=True) completed = models.BooleanField(default=False) date_completed = models.DateTimeField(default=None, null=True) query = models.TextField(default=\"\") def",
"papers with transaction.atomic(): return map(lambda data: Paper.create_paper_from_data(data, review, pool), papers) def get_absolute_url(self): return",
"from django.template.defaultfilters import slugify from django.utils.html import escape from django.db import transaction from",
"= models.DateTimeField(auto_now_add=True) last_modified = models.DateTimeField(auto_now=True) completed = models.BooleanField(default=False) date_completed = models.DateTimeField(default=None, null=True) query",
"and querying counts repeatedly counts = self.paper_pool_counts() total = float(counts[\"total\"]) if total is",
"import escape from django.db import transaction from sysrev.api.PubMed import _get_authors, _get_date, url_from_id, read_papers_from_ids",
"= models.BooleanField(default=False) date_completed = models.DateTimeField(default=None, null=True) query = models.TextField(default=\"\") def perform_query(self): # TODO:",
"from django.db import transaction from sysrev.api.PubMed import _get_authors, _get_date, url_from_id, read_papers_from_ids from sysrev.api",
"return {\"abstract\": abstract_count, \"document\": document_count, \"final\": final_count, \"rejected\": rejected_count, \"remaining\": abstract_count + document_count,",
"models.DateTimeField(auto_now=True) completed = models.BooleanField(default=False) date_completed = models.DateTimeField(default=None, null=True) query = models.TextField(default=\"\") def perform_query(self):",
"in papers.filter(pool=\"A\"): existing_abstract_ids += [paper.pubmed_id] with transaction.atomic(): Paper.objects\\ .filter(pubmed_id__in=existing_abstract_ids)\\ .exclude(pubmed_id__in=ids_from_query)\\ .delete() ids_to_add =",
"abstract_count, \"document\": document_count, \"final\": final_count, \"rejected\": rejected_count, \"remaining\": abstract_count + document_count, \"total\": abstract_count",
"in invitees: user = None if invitee.find(\"@\") == -1: user = User.objects.get(username=invitee) else:",
"pool\"\"\" papers = read_papers_from_ids(ids) # Commit all papers in single transaction # Improves",
"from sysrev.api import PubMed class Review(models.Model): participants = models.ManyToManyField(User) title = models.CharField(max_length=128, unique=False)",
"Paper(models.Model): ABSTRACT_POOL = 'A' DOCUMENT_POOL = 'D' FINAL_POOL = 'F' REJECTED = 'R'",
"= review paper.authors = _get_authors(article) abstractText = \"\" try: for stringElement in article[u'Abstract'][u'AbstractText']:",
"and pool\"\"\" medlineCitation = data[u'MedlineCitation'] article = medlineCitation[u'Article'] title = article[u'ArticleTitle'].lstrip(\"[\").rstrip(\"].\") pubmed_id =",
"models.BooleanField(default=False) date_completed = models.DateTimeField(default=None, null=True) query = models.TextField(default=\"\") def perform_query(self): # TODO: discard",
"FINAL_POOL = 'F' REJECTED = 'R' POOLS = ( (ABSTRACT_POOL, 'Abstract pool'), (DOCUMENT_POOL,",
"paper_pool_percentages(self): # TODO: Typically, paper_pool_counts() gets called then this gets called. # Seems",
"KeyError: pass paper.abstract = abstractText paper.publish_date = _get_date(medlineCitation) paper.url = url_from_id(pubmed_id) paper.notes =",
"try: abstractText += \"<h4>\" + escape(stringElement.attributes[u'Label']) + \"</h4>\" except AttributeError: pass abstractText +=",
"is not 0: progress = ((counts[\"final\"] + counts[\"rejected\"]) / total) * 100.0 #",
"else: user = User.objects.get(email=invitee) self.participants.add(user) def clean(self): if (not self.participants) or self.participants.count() <",
"@staticmethod def create_paper_from_data(data, review, pool): \"\"\"Creates Paper model from given data, review and",
"= article[u'ArticleTitle'].lstrip(\"[\").rstrip(\"].\") pubmed_id = medlineCitation[u'PMID'] paper = Paper.objects.get_or_create(review=review, title=title, pubmed_id=pubmed_id)[0] paper.review = review",
"+ \"\\n\\n\" except KeyError: pass paper.abstract = abstractText paper.publish_date = _get_date(medlineCitation) paper.url =",
"papers.filter(pool=\"A\"): existing_abstract_ids += [paper.pubmed_id] with transaction.atomic(): Paper.objects\\ .filter(pubmed_id__in=existing_abstract_ids)\\ .exclude(pubmed_id__in=ids_from_query)\\ .delete() ids_to_add = list(set(ids_from_query).difference(existing_ids))",
"final, \"rejected\": rejected, \"progress\": progress} else: return def paper_pool_counts(self): relevant_papers = Paper.objects.filter(review=self) abstract_count",
"rejected_count, \"remaining\": abstract_count + document_count, \"total\": abstract_count + document_count + final_count + rejected_count}",
"save(self, *args, **kwargs): self.slug = slugify(self.title) super(Review, self).save() def get_absolute_url(self): return reverse('review_detail', args=[str(self.pk)])[:-1]",
"POOLS = ( (ABSTRACT_POOL, 'Abstract pool'), (DOCUMENT_POOL, 'Document pool'), (FINAL_POOL, 'Final pool'), (REJECTED,",
"+ \"/\" + str(self.pk) def __unicode__(self): return str(self.review) + \" - \" +",
"this gets called. # Seems a bit wasteful, as it ends up running",
"papers if there are any ids_from_query = PubMed.get_ids_from_query(self.query) if self.paper_pool_counts()[\"abstract\"] == 0: Paper.create_papers_from_pubmed_ids(ids_from_query,",
"not 0: progress = ((counts[\"final\"] + counts[\"rejected\"]) / total) * 100.0 # minimum",
"[] for paper in papers: existing_ids += [paper.pubmed_id] existing_abstract_ids = [] for paper",
"if total is not 0: progress = ((counts[\"final\"] + counts[\"rejected\"]) / total) *",
"key in counts: if key == \"total\": continue old = counts[key] = float(counts[key])",
"existing_ids += [paper.pubmed_id] existing_abstract_ids = [] for paper in papers.filter(pool=\"A\"): existing_abstract_ids += [paper.pubmed_id]",
"commit after every save call when creating lots of papers with transaction.atomic(): return",
"PubMed.get_ids_from_query(self.query) if self.paper_pool_counts()[\"abstract\"] == 0: Paper.create_papers_from_pubmed_ids(ids_from_query, self) else: papers = Paper.objects.filter(review=self) existing_ids =",
"(counts[\"rejected\"] / total) * 100.0 return {\"abstract\": abstract, \"document\": document, \"final\": final, \"rejected\":",
"one participant') def save(self, *args, **kwargs): self.slug = slugify(self.title) super(Review, self).save() def get_absolute_url(self):",
"review, pool), papers) def get_absolute_url(self): return self.review.get_absolute_url() + \"/\" + str(self.pk) def __unicode__(self):",
"least one participant') def save(self, *args, **kwargs): self.slug = slugify(self.title) super(Review, self).save() def",
"paper_pool_counts() gets called then this gets called. # Seems a bit wasteful, as",
"article[u'ArticleTitle'].lstrip(\"[\").rstrip(\"].\") pubmed_id = medlineCitation[u'PMID'] paper = Paper.objects.get_or_create(review=review, title=title, pubmed_id=pubmed_id)[0] paper.review = review paper.authors",
"+= escape(stringElement) + \"\\n\\n\" except KeyError: pass paper.abstract = abstractText paper.publish_date = _get_date(medlineCitation)",
"if self.paper_pool_counts()[\"abstract\"] == 0: Paper.create_papers_from_pubmed_ids(ids_from_query, self) else: papers = Paper.objects.filter(review=self) existing_ids = []",
") review = models.ForeignKey(Review) title = models.CharField(max_length=128) authors = models.CharField(max_length=128) abstract = models.TextField(default=\"\")",
"title = models.CharField(max_length=128) authors = models.CharField(max_length=128) abstract = models.TextField(default=\"\") publish_date = models.DateField(null=True) url",
"pool): \"\"\"Creates Paper model from given data, review and pool\"\"\" medlineCitation = data[u'MedlineCitation']",
"paper.abstract = abstractText paper.publish_date = _get_date(medlineCitation) paper.url = url_from_id(pubmed_id) paper.notes = \"\" paper.pool",
"= Paper.objects.filter(review=self) abstract_count = relevant_papers.filter(pool=\"A\").count() document_count = relevant_papers.filter(pool=\"D\").count() final_count = relevant_papers.filter(pool=\"F\").count() rejected_count =",
"clean(self): if (not self.participants) or self.participants.count() < 1: raise ValidationError('Need at least one",
"transaction.atomic(): Paper.objects\\ .filter(pubmed_id__in=existing_abstract_ids)\\ .exclude(pubmed_id__in=ids_from_query)\\ .delete() ids_to_add = list(set(ids_from_query).difference(existing_ids)) if ids_to_add: Paper.create_papers_from_pubmed_ids(ids_to_add, self) def",
"paper = Paper.objects.get_or_create(review=review, title=title, pubmed_id=pubmed_id)[0] paper.review = review paper.authors = _get_authors(article) abstractText =",
"class Review(models.Model): participants = models.ManyToManyField(User) title = models.CharField(max_length=128, unique=False) slug = models.SlugField() description",
"= models.TextField(default=\"\") date_created = models.DateTimeField(auto_now_add=True) last_modified = models.DateTimeField(auto_now=True) completed = models.BooleanField(default=False) date_completed =",
"= counts[key] = float(counts[key]) result = (counts[key] / total) * 100.0 if result",
"/ total) * 100.0 rejected = (counts[\"rejected\"] / total) * 100.0 return {\"abstract\":",
"authors = models.CharField(max_length=128) abstract = models.TextField(default=\"\") publish_date = models.DateField(null=True) url = models.URLField(default=\"\") pubmed_id",
"total) * 100.0 document = (counts[\"document\"] / total) * 100.0 final = (counts[\"final\"]",
"= models.DateField(null=True) url = models.URLField(default=\"\") pubmed_id = models.CharField(max_length=16) notes = models.TextField(default=\"\") pool =",
"new = (min_percent * total) / 100.0 total += new - old abstract",
"*args, **kwargs): self.slug = slugify(self.title) super(Review, self).save() def get_absolute_url(self): return reverse('review_detail', args=[str(self.pk)])[:-1] +",
"single transaction # Improves performance, as django won't automatically commit after every save",
"import transaction from sysrev.api.PubMed import _get_authors, _get_date, url_from_id, read_papers_from_ids from sysrev.api import PubMed",
"counts = self.paper_pool_counts() total = float(counts[\"total\"]) if total is not 0: progress =",
"paper.save() return paper @staticmethod def create_papers_from_pubmed_ids(ids, review, pool='A'): \"\"\"Creates papers from all of",
"raise ValidationError('Need at least one participant') def save(self, *args, **kwargs): self.slug = slugify(self.title)",
"models.CharField(max_length=1, choices=POOLS, default=ABSTRACT_POOL) @staticmethod def create_paper_from_data(data, review, pool): \"\"\"Creates Paper model from given",
"paper.review = review paper.authors = _get_authors(article) abstractText = \"\" try: for stringElement in",
"Review(models.Model): participants = models.ManyToManyField(User) title = models.CharField(max_length=128, unique=False) slug = models.SlugField() description =",
"\"rejected\": rejected_count, \"remaining\": abstract_count + document_count, \"total\": abstract_count + document_count + final_count +",
"total = float(counts[\"total\"]) if total is not 0: progress = ((counts[\"final\"] + counts[\"rejected\"])",
"@staticmethod def create_papers_from_pubmed_ids(ids, review, pool='A'): \"\"\"Creates papers from all of the given ids,",
"/ total) * 100.0 final = (counts[\"final\"] / total) * 100.0 rejected =",
"(counts[\"final\"] / total) * 100.0 rejected = (counts[\"rejected\"] / total) * 100.0 return",
"* total) / 100.0 total += new - old abstract = (counts[\"abstract\"] /",
"from sysrev.api.PubMed import _get_authors, _get_date, url_from_id, read_papers_from_ids from sysrev.api import PubMed class Review(models.Model):",
"article[u'Abstract'][u'AbstractText']: try: abstractText += \"<h4>\" + escape(stringElement.attributes[u'Label']) + \"</h4>\" except AttributeError: pass abstractText",
"papers = Paper.objects.filter(review=self) existing_ids = [] for paper in papers: existing_ids += [paper.pubmed_id]",
"except AttributeError: pass abstractText += escape(stringElement) + \"\\n\\n\" except KeyError: pass paper.abstract =",
"of the given ids, in the given review and pool\"\"\" papers = read_papers_from_ids(ids)",
"def clean(self): if (not self.participants) or self.participants.count() < 1: raise ValidationError('Need at least",
"(not self.participants) or self.participants.count() < 1: raise ValidationError('Need at least one participant') def",
"django won't automatically commit after every save call when creating lots of papers",
"- old abstract = (counts[\"abstract\"] / total) * 100.0 document = (counts[\"document\"] /",
"django.core.urlresolvers import reverse from django.db import models from django.template.defaultfilters import slugify from django.utils.html",
"pool\"\"\" medlineCitation = data[u'MedlineCitation'] article = medlineCitation[u'Article'] title = article[u'ArticleTitle'].lstrip(\"[\").rstrip(\"].\") pubmed_id = medlineCitation[u'PMID']",
"querying counts repeatedly counts = self.paper_pool_counts() total = float(counts[\"total\"]) if total is not",
"'Document pool'), (FINAL_POOL, 'Final pool'), (REJECTED, 'Rejected') ) review = models.ForeignKey(Review) title =",
"if (not self.participants) or self.participants.count() < 1: raise ValidationError('Need at least one participant')",
"models.CharField(max_length=128) abstract = models.TextField(default=\"\") publish_date = models.DateField(null=True) url = models.URLField(default=\"\") pubmed_id = models.CharField(max_length=16)",
"percentage min_percent = 5.0 for key in counts: if key == \"total\": continue",
"django.utils.html import escape from django.db import transaction from sysrev.api.PubMed import _get_authors, _get_date, url_from_id,",
"performance, as django won't automatically commit after every save call when creating lots",
"pubmed_id = medlineCitation[u'PMID'] paper = Paper.objects.get_or_create(review=review, title=title, pubmed_id=pubmed_id)[0] paper.review = review paper.authors =",
"abstract_count = relevant_papers.filter(pool=\"A\").count() document_count = relevant_papers.filter(pool=\"D\").count() final_count = relevant_papers.filter(pool=\"F\").count() rejected_count = relevant_papers.filter(pool=\"R\").count() return",
"+ escape(stringElement.attributes[u'Label']) + \"</h4>\" except AttributeError: pass abstractText += escape(stringElement) + \"\\n\\n\" except",
"relevant_papers.filter(pool=\"D\").count() final_count = relevant_papers.filter(pool=\"F\").count() rejected_count = relevant_papers.filter(pool=\"R\").count() return {\"abstract\": abstract_count, \"document\": document_count, \"final\":",
"data, review and pool\"\"\" medlineCitation = data[u'MedlineCitation'] article = medlineCitation[u'Article'] title = article[u'ArticleTitle'].lstrip(\"[\").rstrip(\"].\")",
"+ document_count + final_count + rejected_count} def invite(self, invitees): for invitee in invitees:",
"from all of the given ids, in the given review and pool\"\"\" papers",
"medlineCitation[u'Article'] title = article[u'ArticleTitle'].lstrip(\"[\").rstrip(\"].\") pubmed_id = medlineCitation[u'PMID'] paper = Paper.objects.get_or_create(review=review, title=title, pubmed_id=pubmed_id)[0] paper.review",
"models.ForeignKey(Review) title = models.CharField(max_length=128) authors = models.CharField(max_length=128) abstract = models.TextField(default=\"\") publish_date = models.DateField(null=True)",
"models.TextField(default=\"\") pool = models.CharField(max_length=1, choices=POOLS, default=ABSTRACT_POOL) @staticmethod def create_paper_from_data(data, review, pool): \"\"\"Creates Paper",
"pool paper.save() return paper @staticmethod def create_papers_from_pubmed_ids(ids, review, pool='A'): \"\"\"Creates papers from all",
"= \"\" paper.pool = pool paper.save() return paper @staticmethod def create_papers_from_pubmed_ids(ids, review, pool='A'):",
"papers = read_papers_from_ids(ids) # Commit all papers in single transaction # Improves performance,",
"= models.URLField(default=\"\") pubmed_id = models.CharField(max_length=16) notes = models.TextField(default=\"\") pool = models.CharField(max_length=1, choices=POOLS, default=ABSTRACT_POOL)",
"* 100.0 # minimum display percentage min_percent = 5.0 for key in counts:",
"pass abstractText += escape(stringElement) + \"\\n\\n\" except KeyError: pass paper.abstract = abstractText paper.publish_date",
"= models.TextField(default=\"\") publish_date = models.DateField(null=True) url = models.URLField(default=\"\") pubmed_id = models.CharField(max_length=16) notes =",
"def invite(self, invitees): for invitee in invitees: user = None if invitee.find(\"@\") ==",
"= models.CharField(max_length=1, choices=POOLS, default=ABSTRACT_POOL) @staticmethod def create_paper_from_data(data, review, pool): \"\"\"Creates Paper model from",
"self.review.get_absolute_url() + \"/\" + str(self.pk) def __unicode__(self): return str(self.review) + \" - \"",
"from django.core.exceptions import ValidationError from django.core.urlresolvers import reverse from django.db import models from",
"ids_to_add: Paper.create_papers_from_pubmed_ids(ids_to_add, self) def paper_pool_percentages(self): # TODO: Typically, paper_pool_counts() gets called then this",
"self.slug = slugify(self.title) super(Review, self).save() def get_absolute_url(self): return reverse('review_detail', args=[str(self.pk)])[:-1] + \"-\" +",
"progress} else: return def paper_pool_counts(self): relevant_papers = Paper.objects.filter(review=self) abstract_count = relevant_papers.filter(pool=\"A\").count() document_count =",
"abstract = models.TextField(default=\"\") publish_date = models.DateField(null=True) url = models.URLField(default=\"\") pubmed_id = models.CharField(max_length=16) notes",
"given data, review and pool\"\"\" medlineCitation = data[u'MedlineCitation'] article = medlineCitation[u'Article'] title =",
"# Commit all papers in single transaction # Improves performance, as django won't",
"key == \"total\": continue old = counts[key] = float(counts[key]) result = (counts[key] /",
"ids, in the given review and pool\"\"\" papers = read_papers_from_ids(ids) # Commit all",
"models.DateTimeField(auto_now_add=True) last_modified = models.DateTimeField(auto_now=True) completed = models.BooleanField(default=False) date_completed = models.DateTimeField(default=None, null=True) query =",
"= (counts[\"rejected\"] / total) * 100.0 return {\"abstract\": abstract, \"document\": document, \"final\": final,",
"pool='A'): \"\"\"Creates papers from all of the given ids, in the given review",
"total) / 100.0 total += new - old abstract = (counts[\"abstract\"] / total)",
"user = User.objects.get(email=invitee) self.participants.add(user) def clean(self): if (not self.participants) or self.participants.count() < 1:",
"return self.review.get_absolute_url() + \"/\" + str(self.pk) def __unicode__(self): return str(self.review) + \" -",
"Paper.objects.filter(review=self) existing_ids = [] for paper in papers: existing_ids += [paper.pubmed_id] existing_abstract_ids =",
"+ \": \" + self.title class Paper(models.Model): ABSTRACT_POOL = 'A' DOCUMENT_POOL = 'D'",
"in counts: if key == \"total\": continue old = counts[key] = float(counts[key]) result",
"\"total\": continue old = counts[key] = float(counts[key]) result = (counts[key] / total) *",
"papers: existing_ids += [paper.pubmed_id] existing_abstract_ids = [] for paper in papers.filter(pool=\"A\"): existing_abstract_ids +=",
"reverse('review_detail', args=[str(self.pk)])[:-1] + \"-\" + self.slug def __unicode__(self): return str(self.pk) + \": \"",
"abstractText = \"\" try: for stringElement in article[u'Abstract'][u'AbstractText']: try: abstractText += \"<h4>\" +",
"(min_percent * total) / 100.0 total += new - old abstract = (counts[\"abstract\"]",
"or self.participants.count() < 1: raise ValidationError('Need at least one participant') def save(self, *args,",
"query = models.TextField(default=\"\") def perform_query(self): # TODO: discard existing papers if there are",
"minimum display percentage min_percent = 5.0 for key in counts: if key ==",
"continue old = counts[key] = float(counts[key]) result = (counts[key] / total) * 100.0",
"= url_from_id(pubmed_id) paper.notes = \"\" paper.pool = pool paper.save() return paper @staticmethod def",
"= Paper.objects.get_or_create(review=review, title=title, pubmed_id=pubmed_id)[0] paper.review = review paper.authors = _get_authors(article) abstractText = \"\"",
"100.0 # minimum display percentage min_percent = 5.0 for key in counts: if",
"= [] for paper in papers: existing_ids += [paper.pubmed_id] existing_abstract_ids = [] for",
"final_count = relevant_papers.filter(pool=\"F\").count() rejected_count = relevant_papers.filter(pool=\"R\").count() return {\"abstract\": abstract_count, \"document\": document_count, \"final\": final_count,",
"0: Paper.create_papers_from_pubmed_ids(ids_from_query, self) else: papers = Paper.objects.filter(review=self) existing_ids = [] for paper in",
"\"remaining\": abstract_count + document_count, \"total\": abstract_count + document_count + final_count + rejected_count} def",
"and result < min_percent: counts[key] = new = (min_percent * total) / 100.0",
"* 100.0 return {\"abstract\": abstract, \"document\": document, \"final\": final, \"rejected\": rejected, \"progress\": progress}",
"old abstract = (counts[\"abstract\"] / total) * 100.0 document = (counts[\"document\"] / total)",
"pool'), (FINAL_POOL, 'Final pool'), (REJECTED, 'Rejected') ) review = models.ForeignKey(Review) title = models.CharField(max_length=128)",
"url = models.URLField(default=\"\") pubmed_id = models.CharField(max_length=16) notes = models.TextField(default=\"\") pool = models.CharField(max_length=1, choices=POOLS,",
"== \"total\": continue old = counts[key] = float(counts[key]) result = (counts[key] / total)",
"default=ABSTRACT_POOL) @staticmethod def create_paper_from_data(data, review, pool): \"\"\"Creates Paper model from given data, review",
"last_modified = models.DateTimeField(auto_now=True) completed = models.BooleanField(default=False) date_completed = models.DateTimeField(default=None, null=True) query = models.TextField(default=\"\")",
"100.0 return {\"abstract\": abstract, \"document\": document, \"final\": final, \"rejected\": rejected, \"progress\": progress} else:",
"multiple times and querying counts repeatedly counts = self.paper_pool_counts() total = float(counts[\"total\"]) if"
] |
[
"mod = obj.modifiers.new(\"CorrectiveSmooth\", 'CORRECTIVE_SMOOTH') mod.factor = 0.1 mod.scale = 1.5 bpy.ops.object.modifier_apply(modifier=\"CorrectiveSmooth\") bpy.ops.export_scene.gltf( filepath=args[2],",
"bpy if __name__ == \"__main__\": args = sys.argv[sys.argv.index('--'):] print(args) bpy.ops.import_scene.gltf(filepath=args[1]) obj = bpy.context.active_object",
"args = sys.argv[sys.argv.index('--'):] print(args) bpy.ops.import_scene.gltf(filepath=args[1]) obj = bpy.context.active_object mod = obj.modifiers.new(\"CorrectiveSmooth\", 'CORRECTIVE_SMOOTH') mod.factor",
"obj = bpy.context.active_object mod = obj.modifiers.new(\"CorrectiveSmooth\", 'CORRECTIVE_SMOOTH') mod.factor = 0.1 mod.scale = 1.5",
"print(args) bpy.ops.import_scene.gltf(filepath=args[1]) obj = bpy.context.active_object mod = obj.modifiers.new(\"CorrectiveSmooth\", 'CORRECTIVE_SMOOTH') mod.factor = 0.1 mod.scale",
"'CORRECTIVE_SMOOTH') mod.factor = 0.1 mod.scale = 1.5 bpy.ops.object.modifier_apply(modifier=\"CorrectiveSmooth\") bpy.ops.export_scene.gltf( filepath=args[2], export_normals=False, export_colors=False, use_selection=True",
"bpy.ops.import_scene.gltf(filepath=args[1]) obj = bpy.context.active_object mod = obj.modifiers.new(\"CorrectiveSmooth\", 'CORRECTIVE_SMOOTH') mod.factor = 0.1 mod.scale =",
"== \"__main__\": args = sys.argv[sys.argv.index('--'):] print(args) bpy.ops.import_scene.gltf(filepath=args[1]) obj = bpy.context.active_object mod = obj.modifiers.new(\"CorrectiveSmooth\",",
"import bpy if __name__ == \"__main__\": args = sys.argv[sys.argv.index('--'):] print(args) bpy.ops.import_scene.gltf(filepath=args[1]) obj =",
"= sys.argv[sys.argv.index('--'):] print(args) bpy.ops.import_scene.gltf(filepath=args[1]) obj = bpy.context.active_object mod = obj.modifiers.new(\"CorrectiveSmooth\", 'CORRECTIVE_SMOOTH') mod.factor =",
"\"__main__\": args = sys.argv[sys.argv.index('--'):] print(args) bpy.ops.import_scene.gltf(filepath=args[1]) obj = bpy.context.active_object mod = obj.modifiers.new(\"CorrectiveSmooth\", 'CORRECTIVE_SMOOTH')",
"if __name__ == \"__main__\": args = sys.argv[sys.argv.index('--'):] print(args) bpy.ops.import_scene.gltf(filepath=args[1]) obj = bpy.context.active_object mod",
"= bpy.context.active_object mod = obj.modifiers.new(\"CorrectiveSmooth\", 'CORRECTIVE_SMOOTH') mod.factor = 0.1 mod.scale = 1.5 bpy.ops.object.modifier_apply(modifier=\"CorrectiveSmooth\")",
"= obj.modifiers.new(\"CorrectiveSmooth\", 'CORRECTIVE_SMOOTH') mod.factor = 0.1 mod.scale = 1.5 bpy.ops.object.modifier_apply(modifier=\"CorrectiveSmooth\") bpy.ops.export_scene.gltf( filepath=args[2], export_normals=False,",
"sys import bpy if __name__ == \"__main__\": args = sys.argv[sys.argv.index('--'):] print(args) bpy.ops.import_scene.gltf(filepath=args[1]) obj",
"sys.argv[sys.argv.index('--'):] print(args) bpy.ops.import_scene.gltf(filepath=args[1]) obj = bpy.context.active_object mod = obj.modifiers.new(\"CorrectiveSmooth\", 'CORRECTIVE_SMOOTH') mod.factor = 0.1",
"__name__ == \"__main__\": args = sys.argv[sys.argv.index('--'):] print(args) bpy.ops.import_scene.gltf(filepath=args[1]) obj = bpy.context.active_object mod =",
"obj.modifiers.new(\"CorrectiveSmooth\", 'CORRECTIVE_SMOOTH') mod.factor = 0.1 mod.scale = 1.5 bpy.ops.object.modifier_apply(modifier=\"CorrectiveSmooth\") bpy.ops.export_scene.gltf( filepath=args[2], export_normals=False, export_colors=False,",
"mod.factor = 0.1 mod.scale = 1.5 bpy.ops.object.modifier_apply(modifier=\"CorrectiveSmooth\") bpy.ops.export_scene.gltf( filepath=args[2], export_normals=False, export_colors=False, use_selection=True )",
"bpy.context.active_object mod = obj.modifiers.new(\"CorrectiveSmooth\", 'CORRECTIVE_SMOOTH') mod.factor = 0.1 mod.scale = 1.5 bpy.ops.object.modifier_apply(modifier=\"CorrectiveSmooth\") bpy.ops.export_scene.gltf(",
"import sys import bpy if __name__ == \"__main__\": args = sys.argv[sys.argv.index('--'):] print(args) bpy.ops.import_scene.gltf(filepath=args[1])"
] |
[
"col[6]=col[12]=yaw strLine=\"\" writeCSVLine(f, strLine, col) f.close() def main(): #Parameters if len(sys.argv) < 2:",
"\"\\\"></trkpt>\" f.write( strLine ) f.write( \"\\n\" ) f.write( \"</trkseg>\\n\") f.write( \"</trk>\\n\") f.write( \"</gpx>\\n\")",
"inProj, outProj) createSCANeRMDL(outfoldername + \"hostvehicle\",\"car\") createSCANePlayer(outfoldername + \"hostvehicle\") if __name__ == '__main__': sys.exit(main())",
"encoding=\\\"UTF-8\\\"?>\\n\") f.write( \"<gpx version=\\\"1.1\\\" creator=\\\"GpxTraceNet6.2\\\"\\n\") f.write( \"xmlns:xsi=\\\"http://www.w3.org/2001/XMLSchema-instance\\\" xmlns=\\\"http://www.topografix.com/GPX/1/1\\\"\\n\") f.write( \"xsi:schemaLocation=\\\"http://www.topografix.com/GPX/1/1 http://www.topografix.com/GPX/1/1/gpx.xsd\\\">\\n\") f.write( \"<trk>\\n\")",
"createCSV(outfoldername + \"hostvehicle\", root, \".//hostvehicle/traj/geo\", inProj, outProj) createSCANeRMDL(outfoldername + \"hostvehicle\",\"car\") createSCANePlayer(outfoldername + \"hostvehicle\")",
"offsetX = 171338.11 offsetY = 388410.20 f = open(fileName+ \".csv\", \"w\") col =",
"import xml.etree.ElementTree as ET from pyproj import Proj,Transformer def createSCANeRMDL(fileName,type): #Creation du fichier",
"= open(templateFileName, \"r\") template= templateFile.read() content = template.replace('template_vehicle_name', os.path.basename(fileName)) f = open(fileName +",
"\"<trkseg>\\n\") for geo in root.findall(startNode): #print geo.attrib strLine = \"<trkpt lat=\\\"\"+geo.get('lat')+\"\\\" lon=\\\"\" +",
"open(fileName + \".mdl\", \"w\") f.write(content) templateFile.close() f.close() def createSCANePlayer(fileName): #Creation du fichier Player",
"\"<trk>\\n\") f.write( \"<name> RDE </name>\\n\") f.write( \"<trkseg>\\n\") for geo in root.findall(startNode): #print geo.attrib",
"col[:-1]: strLine += str(icol)+\";\" strLine+=str(col[-1])+\"\\n\" f.write( strLine ) def createCSV(fileName, root, startNode, inProj,",
"Player templateFileName = \"template/template.vhplayer\" templateFile = open(templateFileName, \"r\") template= templateFile.read() content = template.replace('template_vehicle_name',",
"= 388410.20 f = open(fileName+ \".csv\", \"w\") col = [0.0]*36 strLine=\"\" writeCSVLine(f, strLine,",
"= 171338.11 offsetY = 388410.20 tree = ET.parse(infilename) root = tree.getroot() #Creation du",
"str(icol)+\";\" strLine+=str(col[-1])+\"\\n\" f.write( strLine ) def createCSV(fileName, root, startNode, inProj, outProj): offsetX =",
"pyproj import Proj,Transformer def createSCANeRMDL(fileName,type): #Creation du fichier MDL templateFileName = \"template/template_\"+type+\".mdl\" templateFile",
"missing : name of the file to import') exit() infilename = sys.argv[1] outfoldername",
"templateFileName = \"template/template_\"+type+\".mdl\" templateFile = open(templateFileName, \"r\") template= templateFile.read() content = template.replace('template_vehicle_name', os.path.basename(fileName))",
") def createCSV(fileName, root, startNode, inProj, outProj): offsetX = 171338.11 offsetY = 388410.20",
"+ \".mdl\", \"w\") f.write(content) templateFile.close() f.close() def createSCANePlayer(fileName): #Creation du fichier Player templateFileName",
"#Creation du fichier Player templateFileName = \"template/template.vhplayer\" templateFile = open(templateFileName, \"r\") template= templateFile.read()",
"in root.findall(startNode): #print geo.attrib strLine = \"<trkpt lat=\\\"\"+geo.get('lat')+\"\\\" lon=\\\"\" + geo.get('long') + \"\\\"></trkpt>\"",
"the file to import') exit() infilename = sys.argv[1] outfoldername = os.path.splitext(infilename)[0] + \"_vhlplayer/\"",
"template.replace('template_vehicle_name', os.path.basename(fileName)) f = open(fileName + \".vhplayer\", \"w\") f.write(content) templateFile.close() f.close() def createGPX(fileName,",
"f.close() def createSCANePlayer(fileName): #Creation du fichier Player templateFileName = \"template/template.vhplayer\" templateFile = open(templateFileName,",
"name of the file to import') exit() infilename = sys.argv[1] outfoldername = os.path.splitext(infilename)[0]",
"template= templateFile.read() content = template.replace('template_vehicle_name', os.path.basename(fileName)) f = open(fileName + \".mdl\", \"w\") f.write(content)",
"= open(fileName + \".gpx\", \"w\") f.write( \"<?xml version=\\\"1.0\\\" encoding=\\\"UTF-8\\\"?>\\n\") f.write( \"<gpx version=\\\"1.1\\\" creator=\\\"GpxTraceNet6.2\\\"\\n\")",
"inProj, outProj): offsetX = 171338.11 offsetY = 388410.20 f = open(fileName+ \".csv\", \"w\")",
"388410.20 f = open(fileName+ \".csv\", \"w\") col = [0.0]*36 strLine=\"\" writeCSVLine(f, strLine, col)",
"= \"template/template.vhplayer\" templateFile = open(templateFileName, \"r\") template= templateFile.read() content = template.replace('template_vehicle_name', os.path.basename(fileName)) f",
"2: print('argument missing : name of the file to import') exit() infilename =",
"os.mkdir(outfoldername) except: pass #Projections inProj=Proj(proj='latlong',datum='WGS84') outProj=Proj(init='epsg:28992', towgs84='565.417,50.3319,465.552,-0.398957,0.343988,-1.8774,4.0725') offsetX = 171338.11 offsetY = 388410.20",
"except: pass #Projections inProj=Proj(proj='latlong',datum='WGS84') outProj=Proj(init='epsg:28992', towgs84='565.417,50.3319,465.552,-0.398957,0.343988,-1.8774,4.0725') offsetX = 171338.11 offsetY = 388410.20 tree",
"yaw = 0.017453*float(geo.get('course')) col = [0.0]*36 col[0]=geo.get('secs') col[1]=col[7]=x col[2]=col[8]=y col[6]=col[12]=yaw strLine=\"\" writeCSVLine(f, strLine,",
"geo in root.findall(startNode): transformer=Transformer.from_proj(inProj,outProj) X,Y=transformer.transform(geo.get('long'),geo.get('lat')) x=X-offsetX y=Y-offsetY yaw = 0.017453*float(geo.get('course')) col = [0.0]*36",
"def createSCANeRMDL(fileName,type): #Creation du fichier MDL templateFileName = \"template/template_\"+type+\".mdl\" templateFile = open(templateFileName, \"r\")",
"\"<gpx version=\\\"1.1\\\" creator=\\\"GpxTraceNet6.2\\\"\\n\") f.write( \"xmlns:xsi=\\\"http://www.w3.org/2001/XMLSchema-instance\\\" xmlns=\\\"http://www.topografix.com/GPX/1/1\\\"\\n\") f.write( \"xsi:schemaLocation=\\\"http://www.topografix.com/GPX/1/1 http://www.topografix.com/GPX/1/1/gpx.xsd\\\">\\n\") f.write( \"<trk>\\n\") f.write( \"<name>",
"createGPX(outfoldername + \"hostvehicle\", root, \".//hostvehicle/traj/geo\") createCSV(outfoldername + \"hostvehicle\", root, \".//hostvehicle/traj/geo\", inProj, outProj) createSCANeRMDL(outfoldername",
"f.close() def writeCSVLine(f, strLine, col): for icol in col[:-1]: strLine += str(icol)+\";\" strLine+=str(col[-1])+\"\\n\"",
"strLine+=str(col[-1])+\"\\n\" f.write( strLine ) def createCSV(fileName, root, startNode, inProj, outProj): offsetX = 171338.11",
"= \"<trkpt lat=\\\"\"+geo.get('lat')+\"\\\" lon=\\\"\" + geo.get('long') + \"\\\"></trkpt>\" f.write( strLine ) f.write( \"\\n\"",
"createCSV(fileName, root, startNode, inProj, outProj): offsetX = 171338.11 offsetY = 388410.20 f =",
"= [0.0]*36 col[0]=geo.get('secs') col[1]=col[7]=x col[2]=col[8]=y col[6]=col[12]=yaw strLine=\"\" writeCSVLine(f, strLine, col) f.close() def main():",
"= [0.0]*36 strLine=\"\" writeCSVLine(f, strLine, col) strLine=\"\" writeCSVLine(f, strLine, col) for geo in",
"x=X-offsetX y=Y-offsetY yaw = 0.017453*float(geo.get('course')) col = [0.0]*36 col[0]=geo.get('secs') col[1]=col[7]=x col[2]=col[8]=y col[6]=col[12]=yaw strLine=\"\"",
"f.write( \"</trk>\\n\") f.write( \"</gpx>\\n\") f.close() def writeCSVLine(f, strLine, col): for icol in col[:-1]:",
"outfoldername = os.path.splitext(infilename)[0] + \"_vhlplayer/\" try: os.mkdir(outfoldername) except: pass #Projections inProj=Proj(proj='latlong',datum='WGS84') outProj=Proj(init='epsg:28992', towgs84='565.417,50.3319,465.552,-0.398957,0.343988,-1.8774,4.0725')",
"\"template/template_\"+type+\".mdl\" templateFile = open(templateFileName, \"r\") template= templateFile.read() content = template.replace('template_vehicle_name', os.path.basename(fileName)) f =",
"\"\\n\" ) f.write( \"</trkseg>\\n\") f.write( \"</trk>\\n\") f.write( \"</gpx>\\n\") f.close() def writeCSVLine(f, strLine, col):",
"= tree.getroot() #Creation du fichier GPX createGPX(outfoldername + \"hostvehicle\", root, \".//hostvehicle/traj/geo\") createCSV(outfoldername +",
"if len(sys.argv) < 2: print('argument missing : name of the file to import')",
"of the file to import') exit() infilename = sys.argv[1] outfoldername = os.path.splitext(infilename)[0] +",
"du fichier Player templateFileName = \"template/template.vhplayer\" templateFile = open(templateFileName, \"r\") template= templateFile.read() content",
"infilename = sys.argv[1] outfoldername = os.path.splitext(infilename)[0] + \"_vhlplayer/\" try: os.mkdir(outfoldername) except: pass #Projections",
"= ET.parse(infilename) root = tree.getroot() #Creation du fichier GPX createGPX(outfoldername + \"hostvehicle\", root,",
"to import') exit() infilename = sys.argv[1] outfoldername = os.path.splitext(infilename)[0] + \"_vhlplayer/\" try: os.mkdir(outfoldername)",
"strLine, col): for icol in col[:-1]: strLine += str(icol)+\";\" strLine+=str(col[-1])+\"\\n\" f.write( strLine )",
"\"w\") col = [0.0]*36 strLine=\"\" writeCSVLine(f, strLine, col) strLine=\"\" writeCSVLine(f, strLine, col) for",
"in col[:-1]: strLine += str(icol)+\";\" strLine+=str(col[-1])+\"\\n\" f.write( strLine ) def createCSV(fileName, root, startNode,",
"\"w\") f.write(content) templateFile.close() f.close() def createGPX(fileName, root, startNode): #Creation du fichier GPX f",
"template= templateFile.read() content = template.replace('template_vehicle_name', os.path.basename(fileName)) f = open(fileName + \".vhplayer\", \"w\") f.write(content)",
"geo.get('long') + \"\\\"></trkpt>\" f.write( strLine ) f.write( \"\\n\" ) f.write( \"</trkseg>\\n\") f.write( \"</trk>\\n\")",
"f = open(fileName + \".mdl\", \"w\") f.write(content) templateFile.close() f.close() def createSCANePlayer(fileName): #Creation du",
"in root.findall(startNode): transformer=Transformer.from_proj(inProj,outProj) X,Y=transformer.transform(geo.get('long'),geo.get('lat')) x=X-offsetX y=Y-offsetY yaw = 0.017453*float(geo.get('course')) col = [0.0]*36 col[0]=geo.get('secs')",
"f.close() def main(): #Parameters if len(sys.argv) < 2: print('argument missing : name of",
"writeCSVLine(f, strLine, col) for geo in root.findall(startNode): transformer=Transformer.from_proj(inProj,outProj) X,Y=transformer.transform(geo.get('long'),geo.get('lat')) x=X-offsetX y=Y-offsetY yaw =",
"content = template.replace('template_vehicle_name', os.path.basename(fileName)) f = open(fileName + \".mdl\", \"w\") f.write(content) templateFile.close() f.close()",
"GPX f = open(fileName + \".gpx\", \"w\") f.write( \"<?xml version=\\\"1.0\\\" encoding=\\\"UTF-8\\\"?>\\n\") f.write( \"<gpx",
"MDL templateFileName = \"template/template_\"+type+\".mdl\" templateFile = open(templateFileName, \"r\") template= templateFile.read() content = template.replace('template_vehicle_name',",
"startNode): #Creation du fichier GPX f = open(fileName + \".gpx\", \"w\") f.write( \"<?xml",
"for icol in col[:-1]: strLine += str(icol)+\";\" strLine+=str(col[-1])+\"\\n\" f.write( strLine ) def createCSV(fileName,",
"\"hostvehicle\", root, \".//hostvehicle/traj/geo\", inProj, outProj) createSCANeRMDL(outfoldername + \"hostvehicle\",\"car\") createSCANePlayer(outfoldername + \"hostvehicle\") if __name__",
"y=Y-offsetY yaw = 0.017453*float(geo.get('course')) col = [0.0]*36 col[0]=geo.get('secs') col[1]=col[7]=x col[2]=col[8]=y col[6]=col[12]=yaw strLine=\"\" writeCSVLine(f,",
"f = open(fileName+ \".csv\", \"w\") col = [0.0]*36 strLine=\"\" writeCSVLine(f, strLine, col) strLine=\"\"",
"startNode, inProj, outProj): offsetX = 171338.11 offsetY = 388410.20 f = open(fileName+ \".csv\",",
"\"template/template.vhplayer\" templateFile = open(templateFileName, \"r\") template= templateFile.read() content = template.replace('template_vehicle_name', os.path.basename(fileName)) f =",
"\"<name> RDE </name>\\n\") f.write( \"<trkseg>\\n\") for geo in root.findall(startNode): #print geo.attrib strLine =",
"root = tree.getroot() #Creation du fichier GPX createGPX(outfoldername + \"hostvehicle\", root, \".//hostvehicle/traj/geo\") createCSV(outfoldername",
"\"_vhlplayer/\" try: os.mkdir(outfoldername) except: pass #Projections inProj=Proj(proj='latlong',datum='WGS84') outProj=Proj(init='epsg:28992', towgs84='565.417,50.3319,465.552,-0.398957,0.343988,-1.8774,4.0725') offsetX = 171338.11 offsetY",
"templateFile.read() content = template.replace('template_vehicle_name', os.path.basename(fileName)) f = open(fileName + \".vhplayer\", \"w\") f.write(content) templateFile.close()",
"version=\\\"1.1\\\" creator=\\\"GpxTraceNet6.2\\\"\\n\") f.write( \"xmlns:xsi=\\\"http://www.w3.org/2001/XMLSchema-instance\\\" xmlns=\\\"http://www.topografix.com/GPX/1/1\\\"\\n\") f.write( \"xsi:schemaLocation=\\\"http://www.topografix.com/GPX/1/1 http://www.topografix.com/GPX/1/1/gpx.xsd\\\">\\n\") f.write( \"<trk>\\n\") f.write( \"<name> RDE",
"strLine, col) strLine=\"\" writeCSVLine(f, strLine, col) for geo in root.findall(startNode): transformer=Transformer.from_proj(inProj,outProj) X,Y=transformer.transform(geo.get('long'),geo.get('lat')) x=X-offsetX",
"for geo in root.findall(startNode): #print geo.attrib strLine = \"<trkpt lat=\\\"\"+geo.get('lat')+\"\\\" lon=\\\"\" + geo.get('long')",
"col) f.close() def main(): #Parameters if len(sys.argv) < 2: print('argument missing : name",
"open(templateFileName, \"r\") template= templateFile.read() content = template.replace('template_vehicle_name', os.path.basename(fileName)) f = open(fileName + \".vhplayer\",",
"strLine = \"<trkpt lat=\\\"\"+geo.get('lat')+\"\\\" lon=\\\"\" + geo.get('long') + \"\\\"></trkpt>\" f.write( strLine ) f.write(",
"col) strLine=\"\" writeCSVLine(f, strLine, col) for geo in root.findall(startNode): transformer=Transformer.from_proj(inProj,outProj) X,Y=transformer.transform(geo.get('long'),geo.get('lat')) x=X-offsetX y=Y-offsetY",
"offsetY = 388410.20 f = open(fileName+ \".csv\", \"w\") col = [0.0]*36 strLine=\"\" writeCSVLine(f,",
"= template.replace('template_vehicle_name', os.path.basename(fileName)) f = open(fileName + \".mdl\", \"w\") f.write(content) templateFile.close() f.close() def",
"\"hostvehicle\", root, \".//hostvehicle/traj/geo\") createCSV(outfoldername + \"hostvehicle\", root, \".//hostvehicle/traj/geo\", inProj, outProj) createSCANeRMDL(outfoldername + \"hostvehicle\",\"car\")",
"fichier Player templateFileName = \"template/template.vhplayer\" templateFile = open(templateFileName, \"r\") template= templateFile.read() content =",
"root, startNode, inProj, outProj): offsetX = 171338.11 offsetY = 388410.20 f = open(fileName+",
"= open(fileName+ \".csv\", \"w\") col = [0.0]*36 strLine=\"\" writeCSVLine(f, strLine, col) strLine=\"\" writeCSVLine(f,",
"os.path.basename(fileName)) f = open(fileName + \".mdl\", \"w\") f.write(content) templateFile.close() f.close() def createSCANePlayer(fileName): #Creation",
"xmlns=\\\"http://www.topografix.com/GPX/1/1\\\"\\n\") f.write( \"xsi:schemaLocation=\\\"http://www.topografix.com/GPX/1/1 http://www.topografix.com/GPX/1/1/gpx.xsd\\\">\\n\") f.write( \"<trk>\\n\") f.write( \"<name> RDE </name>\\n\") f.write( \"<trkseg>\\n\") for",
"f.write( strLine ) def createCSV(fileName, root, startNode, inProj, outProj): offsetX = 171338.11 offsetY",
"tree = ET.parse(infilename) root = tree.getroot() #Creation du fichier GPX createGPX(outfoldername + \"hostvehicle\",",
"def writeCSVLine(f, strLine, col): for icol in col[:-1]: strLine += str(icol)+\";\" strLine+=str(col[-1])+\"\\n\" f.write(",
") f.write( \"\\n\" ) f.write( \"</trkseg>\\n\") f.write( \"</trk>\\n\") f.write( \"</gpx>\\n\") f.close() def writeCSVLine(f,",
"X,Y=transformer.transform(geo.get('long'),geo.get('lat')) x=X-offsetX y=Y-offsetY yaw = 0.017453*float(geo.get('course')) col = [0.0]*36 col[0]=geo.get('secs') col[1]=col[7]=x col[2]=col[8]=y col[6]=col[12]=yaw",
"= \"template/template_\"+type+\".mdl\" templateFile = open(templateFileName, \"r\") template= templateFile.read() content = template.replace('template_vehicle_name', os.path.basename(fileName)) f",
"171338.11 offsetY = 388410.20 tree = ET.parse(infilename) root = tree.getroot() #Creation du fichier",
"from pyproj import Proj,Transformer def createSCANeRMDL(fileName,type): #Creation du fichier MDL templateFileName = \"template/template_\"+type+\".mdl\"",
"du fichier MDL templateFileName = \"template/template_\"+type+\".mdl\" templateFile = open(templateFileName, \"r\") template= templateFile.read() content",
"strLine ) def createCSV(fileName, root, startNode, inProj, outProj): offsetX = 171338.11 offsetY =",
"+ \"hostvehicle\", root, \".//hostvehicle/traj/geo\", inProj, outProj) createSCANeRMDL(outfoldername + \"hostvehicle\",\"car\") createSCANePlayer(outfoldername + \"hostvehicle\") if",
"towgs84='565.417,50.3319,465.552,-0.398957,0.343988,-1.8774,4.0725') offsetX = 171338.11 offsetY = 388410.20 tree = ET.parse(infilename) root = tree.getroot()",
"f = open(fileName + \".vhplayer\", \"w\") f.write(content) templateFile.close() f.close() def createGPX(fileName, root, startNode):",
"\".vhplayer\", \"w\") f.write(content) templateFile.close() f.close() def createGPX(fileName, root, startNode): #Creation du fichier GPX",
"= 0.017453*float(geo.get('course')) col = [0.0]*36 col[0]=geo.get('secs') col[1]=col[7]=x col[2]=col[8]=y col[6]=col[12]=yaw strLine=\"\" writeCSVLine(f, strLine, col)",
"geo.attrib strLine = \"<trkpt lat=\\\"\"+geo.get('lat')+\"\\\" lon=\\\"\" + geo.get('long') + \"\\\"></trkpt>\" f.write( strLine )",
"\".gpx\", \"w\") f.write( \"<?xml version=\\\"1.0\\\" encoding=\\\"UTF-8\\\"?>\\n\") f.write( \"<gpx version=\\\"1.1\\\" creator=\\\"GpxTraceNet6.2\\\"\\n\") f.write( \"xmlns:xsi=\\\"http://www.w3.org/2001/XMLSchema-instance\\\" xmlns=\\\"http://www.topografix.com/GPX/1/1\\\"\\n\")",
"#print geo.attrib strLine = \"<trkpt lat=\\\"\"+geo.get('lat')+\"\\\" lon=\\\"\" + geo.get('long') + \"\\\"></trkpt>\" f.write( strLine",
"f = open(fileName + \".gpx\", \"w\") f.write( \"<?xml version=\\\"1.0\\\" encoding=\\\"UTF-8\\\"?>\\n\") f.write( \"<gpx version=\\\"1.1\\\"",
"\".csv\", \"w\") col = [0.0]*36 strLine=\"\" writeCSVLine(f, strLine, col) strLine=\"\" writeCSVLine(f, strLine, col)",
": name of the file to import') exit() infilename = sys.argv[1] outfoldername =",
"ET.parse(infilename) root = tree.getroot() #Creation du fichier GPX createGPX(outfoldername + \"hostvehicle\", root, \".//hostvehicle/traj/geo\")",
"root, \".//hostvehicle/traj/geo\", inProj, outProj) createSCANeRMDL(outfoldername + \"hostvehicle\",\"car\") createSCANePlayer(outfoldername + \"hostvehicle\") if __name__ ==",
"templateFile.close() f.close() def createSCANePlayer(fileName): #Creation du fichier Player templateFileName = \"template/template.vhplayer\" templateFile =",
"f.write(content) templateFile.close() f.close() def createGPX(fileName, root, startNode): #Creation du fichier GPX f =",
"icol in col[:-1]: strLine += str(icol)+\";\" strLine+=str(col[-1])+\"\\n\" f.write( strLine ) def createCSV(fileName, root,",
"content = template.replace('template_vehicle_name', os.path.basename(fileName)) f = open(fileName + \".vhplayer\", \"w\") f.write(content) templateFile.close() f.close()",
"388410.20 tree = ET.parse(infilename) root = tree.getroot() #Creation du fichier GPX createGPX(outfoldername +",
"templateFile.close() f.close() def createGPX(fileName, root, startNode): #Creation du fichier GPX f = open(fileName",
"\"</trk>\\n\") f.write( \"</gpx>\\n\") f.close() def writeCSVLine(f, strLine, col): for icol in col[:-1]: strLine",
"len(sys.argv) < 2: print('argument missing : name of the file to import') exit()",
"def createGPX(fileName, root, startNode): #Creation du fichier GPX f = open(fileName + \".gpx\",",
"\"</trkseg>\\n\") f.write( \"</trk>\\n\") f.write( \"</gpx>\\n\") f.close() def writeCSVLine(f, strLine, col): for icol in",
"= template.replace('template_vehicle_name', os.path.basename(fileName)) f = open(fileName + \".vhplayer\", \"w\") f.write(content) templateFile.close() f.close() def",
"import os import sys import xml.etree.ElementTree as ET from pyproj import Proj,Transformer def",
"col) for geo in root.findall(startNode): transformer=Transformer.from_proj(inProj,outProj) X,Y=transformer.transform(geo.get('long'),geo.get('lat')) x=X-offsetX y=Y-offsetY yaw = 0.017453*float(geo.get('course')) col",
"transformer=Transformer.from_proj(inProj,outProj) X,Y=transformer.transform(geo.get('long'),geo.get('lat')) x=X-offsetX y=Y-offsetY yaw = 0.017453*float(geo.get('course')) col = [0.0]*36 col[0]=geo.get('secs') col[1]=col[7]=x col[2]=col[8]=y",
"col[0]=geo.get('secs') col[1]=col[7]=x col[2]=col[8]=y col[6]=col[12]=yaw strLine=\"\" writeCSVLine(f, strLine, col) f.close() def main(): #Parameters if",
"as ET from pyproj import Proj,Transformer def createSCANeRMDL(fileName,type): #Creation du fichier MDL templateFileName",
"xml.etree.ElementTree as ET from pyproj import Proj,Transformer def createSCANeRMDL(fileName,type): #Creation du fichier MDL",
"writeCSVLine(f, strLine, col): for icol in col[:-1]: strLine += str(icol)+\";\" strLine+=str(col[-1])+\"\\n\" f.write( strLine",
"open(fileName + \".gpx\", \"w\") f.write( \"<?xml version=\\\"1.0\\\" encoding=\\\"UTF-8\\\"?>\\n\") f.write( \"<gpx version=\\\"1.1\\\" creator=\\\"GpxTraceNet6.2\\\"\\n\") f.write(",
"+ \"hostvehicle\", root, \".//hostvehicle/traj/geo\") createCSV(outfoldername + \"hostvehicle\", root, \".//hostvehicle/traj/geo\", inProj, outProj) createSCANeRMDL(outfoldername +",
"ET from pyproj import Proj,Transformer def createSCANeRMDL(fileName,type): #Creation du fichier MDL templateFileName =",
"strLine += str(icol)+\";\" strLine+=str(col[-1])+\"\\n\" f.write( strLine ) def createCSV(fileName, root, startNode, inProj, outProj):",
"\".//hostvehicle/traj/geo\") createCSV(outfoldername + \"hostvehicle\", root, \".//hostvehicle/traj/geo\", inProj, outProj) createSCANeRMDL(outfoldername + \"hostvehicle\",\"car\") createSCANePlayer(outfoldername +",
"open(templateFileName, \"r\") template= templateFile.read() content = template.replace('template_vehicle_name', os.path.basename(fileName)) f = open(fileName + \".mdl\",",
"lat=\\\"\"+geo.get('lat')+\"\\\" lon=\\\"\" + geo.get('long') + \"\\\"></trkpt>\" f.write( strLine ) f.write( \"\\n\" ) f.write(",
"writeCSVLine(f, strLine, col) strLine=\"\" writeCSVLine(f, strLine, col) for geo in root.findall(startNode): transformer=Transformer.from_proj(inProj,outProj) X,Y=transformer.transform(geo.get('long'),geo.get('lat'))",
"templateFile = open(templateFileName, \"r\") template= templateFile.read() content = template.replace('template_vehicle_name', os.path.basename(fileName)) f = open(fileName",
"f.write( \"\\n\" ) f.write( \"</trkseg>\\n\") f.write( \"</trk>\\n\") f.write( \"</gpx>\\n\") f.close() def writeCSVLine(f, strLine,",
"tree.getroot() #Creation du fichier GPX createGPX(outfoldername + \"hostvehicle\", root, \".//hostvehicle/traj/geo\") createCSV(outfoldername + \"hostvehicle\",",
"f.write( \"<name> RDE </name>\\n\") f.write( \"<trkseg>\\n\") for geo in root.findall(startNode): #print geo.attrib strLine",
"= 171338.11 offsetY = 388410.20 f = open(fileName+ \".csv\", \"w\") col = [0.0]*36",
"sys.argv[1] outfoldername = os.path.splitext(infilename)[0] + \"_vhlplayer/\" try: os.mkdir(outfoldername) except: pass #Projections inProj=Proj(proj='latlong',datum='WGS84') outProj=Proj(init='epsg:28992',",
"import sys import xml.etree.ElementTree as ET from pyproj import Proj,Transformer def createSCANeRMDL(fileName,type): #Creation",
"f.write( \"<trk>\\n\") f.write( \"<name> RDE </name>\\n\") f.write( \"<trkseg>\\n\") for geo in root.findall(startNode): #print",
"print('argument missing : name of the file to import') exit() infilename = sys.argv[1]",
"creator=\\\"GpxTraceNet6.2\\\"\\n\") f.write( \"xmlns:xsi=\\\"http://www.w3.org/2001/XMLSchema-instance\\\" xmlns=\\\"http://www.topografix.com/GPX/1/1\\\"\\n\") f.write( \"xsi:schemaLocation=\\\"http://www.topografix.com/GPX/1/1 http://www.topografix.com/GPX/1/1/gpx.xsd\\\">\\n\") f.write( \"<trk>\\n\") f.write( \"<name> RDE </name>\\n\")",
"root.findall(startNode): transformer=Transformer.from_proj(inProj,outProj) X,Y=transformer.transform(geo.get('long'),geo.get('lat')) x=X-offsetX y=Y-offsetY yaw = 0.017453*float(geo.get('course')) col = [0.0]*36 col[0]=geo.get('secs') col[1]=col[7]=x",
"writeCSVLine(f, strLine, col) f.close() def main(): #Parameters if len(sys.argv) < 2: print('argument missing",
"open(fileName+ \".csv\", \"w\") col = [0.0]*36 strLine=\"\" writeCSVLine(f, strLine, col) strLine=\"\" writeCSVLine(f, strLine,",
"outProj=Proj(init='epsg:28992', towgs84='565.417,50.3319,465.552,-0.398957,0.343988,-1.8774,4.0725') offsetX = 171338.11 offsetY = 388410.20 tree = ET.parse(infilename) root =",
"for geo in root.findall(startNode): transformer=Transformer.from_proj(inProj,outProj) X,Y=transformer.transform(geo.get('long'),geo.get('lat')) x=X-offsetX y=Y-offsetY yaw = 0.017453*float(geo.get('course')) col =",
"\"</gpx>\\n\") f.close() def writeCSVLine(f, strLine, col): for icol in col[:-1]: strLine += str(icol)+\";\"",
"createSCANePlayer(fileName): #Creation du fichier Player templateFileName = \"template/template.vhplayer\" templateFile = open(templateFileName, \"r\") template=",
"strLine, col) for geo in root.findall(startNode): transformer=Transformer.from_proj(inProj,outProj) X,Y=transformer.transform(geo.get('long'),geo.get('lat')) x=X-offsetX y=Y-offsetY yaw = 0.017453*float(geo.get('course'))",
"strLine, col) f.close() def main(): #Parameters if len(sys.argv) < 2: print('argument missing :",
"pass #Projections inProj=Proj(proj='latlong',datum='WGS84') outProj=Proj(init='epsg:28992', towgs84='565.417,50.3319,465.552,-0.398957,0.343988,-1.8774,4.0725') offsetX = 171338.11 offsetY = 388410.20 tree =",
"\"xsi:schemaLocation=\\\"http://www.topografix.com/GPX/1/1 http://www.topografix.com/GPX/1/1/gpx.xsd\\\">\\n\") f.write( \"<trk>\\n\") f.write( \"<name> RDE </name>\\n\") f.write( \"<trkseg>\\n\") for geo in",
"\"w\") f.write( \"<?xml version=\\\"1.0\\\" encoding=\\\"UTF-8\\\"?>\\n\") f.write( \"<gpx version=\\\"1.1\\\" creator=\\\"GpxTraceNet6.2\\\"\\n\") f.write( \"xmlns:xsi=\\\"http://www.w3.org/2001/XMLSchema-instance\\\" xmlns=\\\"http://www.topografix.com/GPX/1/1\\\"\\n\") f.write(",
"\"w\") f.write(content) templateFile.close() f.close() def createSCANePlayer(fileName): #Creation du fichier Player templateFileName = \"template/template.vhplayer\"",
"strLine ) f.write( \"\\n\" ) f.write( \"</trkseg>\\n\") f.write( \"</trk>\\n\") f.write( \"</gpx>\\n\") f.close() def",
"f.write( strLine ) f.write( \"\\n\" ) f.write( \"</trkseg>\\n\") f.write( \"</trk>\\n\") f.write( \"</gpx>\\n\") f.close()",
"col = [0.0]*36 col[0]=geo.get('secs') col[1]=col[7]=x col[2]=col[8]=y col[6]=col[12]=yaw strLine=\"\" writeCSVLine(f, strLine, col) f.close() def",
"version=\\\"1.0\\\" encoding=\\\"UTF-8\\\"?>\\n\") f.write( \"<gpx version=\\\"1.1\\\" creator=\\\"GpxTraceNet6.2\\\"\\n\") f.write( \"xmlns:xsi=\\\"http://www.w3.org/2001/XMLSchema-instance\\\" xmlns=\\\"http://www.topografix.com/GPX/1/1\\\"\\n\") f.write( \"xsi:schemaLocation=\\\"http://www.topografix.com/GPX/1/1 http://www.topografix.com/GPX/1/1/gpx.xsd\\\">\\n\") f.write(",
"+ \"_vhlplayer/\" try: os.mkdir(outfoldername) except: pass #Projections inProj=Proj(proj='latlong',datum='WGS84') outProj=Proj(init='epsg:28992', towgs84='565.417,50.3319,465.552,-0.398957,0.343988,-1.8774,4.0725') offsetX = 171338.11",
"root, startNode): #Creation du fichier GPX f = open(fileName + \".gpx\", \"w\") f.write(",
"http://www.topografix.com/GPX/1/1/gpx.xsd\\\">\\n\") f.write( \"<trk>\\n\") f.write( \"<name> RDE </name>\\n\") f.write( \"<trkseg>\\n\") for geo in root.findall(startNode):",
"f.write( \"xmlns:xsi=\\\"http://www.w3.org/2001/XMLSchema-instance\\\" xmlns=\\\"http://www.topografix.com/GPX/1/1\\\"\\n\") f.write( \"xsi:schemaLocation=\\\"http://www.topografix.com/GPX/1/1 http://www.topografix.com/GPX/1/1/gpx.xsd\\\">\\n\") f.write( \"<trk>\\n\") f.write( \"<name> RDE </name>\\n\") f.write(",
"= 388410.20 tree = ET.parse(infilename) root = tree.getroot() #Creation du fichier GPX createGPX(outfoldername",
"= open(fileName + \".mdl\", \"w\") f.write(content) templateFile.close() f.close() def createSCANePlayer(fileName): #Creation du fichier",
"\"<trkpt lat=\\\"\"+geo.get('lat')+\"\\\" lon=\\\"\" + geo.get('long') + \"\\\"></trkpt>\" f.write( strLine ) f.write( \"\\n\" )",
"#Creation du fichier MDL templateFileName = \"template/template_\"+type+\".mdl\" templateFile = open(templateFileName, \"r\") template= templateFile.read()",
"root, \".//hostvehicle/traj/geo\") createCSV(outfoldername + \"hostvehicle\", root, \".//hostvehicle/traj/geo\", inProj, outProj) createSCANeRMDL(outfoldername + \"hostvehicle\",\"car\") createSCANePlayer(outfoldername",
"offsetY = 388410.20 tree = ET.parse(infilename) root = tree.getroot() #Creation du fichier GPX",
"171338.11 offsetY = 388410.20 f = open(fileName+ \".csv\", \"w\") col = [0.0]*36 strLine=\"\"",
"#Creation du fichier GPX f = open(fileName + \".gpx\", \"w\") f.write( \"<?xml version=\\\"1.0\\\"",
"GPX createGPX(outfoldername + \"hostvehicle\", root, \".//hostvehicle/traj/geo\") createCSV(outfoldername + \"hostvehicle\", root, \".//hostvehicle/traj/geo\", inProj, outProj)",
"\"r\") template= templateFile.read() content = template.replace('template_vehicle_name', os.path.basename(fileName)) f = open(fileName + \".mdl\", \"w\")",
"templateFile.read() content = template.replace('template_vehicle_name', os.path.basename(fileName)) f = open(fileName + \".mdl\", \"w\") f.write(content) templateFile.close()",
"outProj): offsetX = 171338.11 offsetY = 388410.20 f = open(fileName+ \".csv\", \"w\") col",
"templateFileName = \"template/template.vhplayer\" templateFile = open(templateFileName, \"r\") template= templateFile.read() content = template.replace('template_vehicle_name', os.path.basename(fileName))",
"\"xmlns:xsi=\\\"http://www.w3.org/2001/XMLSchema-instance\\\" xmlns=\\\"http://www.topografix.com/GPX/1/1\\\"\\n\") f.write( \"xsi:schemaLocation=\\\"http://www.topografix.com/GPX/1/1 http://www.topografix.com/GPX/1/1/gpx.xsd\\\">\\n\") f.write( \"<trk>\\n\") f.write( \"<name> RDE </name>\\n\") f.write( \"<trkseg>\\n\")",
"def createCSV(fileName, root, startNode, inProj, outProj): offsetX = 171338.11 offsetY = 388410.20 f",
"template.replace('template_vehicle_name', os.path.basename(fileName)) f = open(fileName + \".mdl\", \"w\") f.write(content) templateFile.close() f.close() def createSCANePlayer(fileName):",
"du fichier GPX f = open(fileName + \".gpx\", \"w\") f.write( \"<?xml version=\\\"1.0\\\" encoding=\\\"UTF-8\\\"?>\\n\")",
"f.write( \"<gpx version=\\\"1.1\\\" creator=\\\"GpxTraceNet6.2\\\"\\n\") f.write( \"xmlns:xsi=\\\"http://www.w3.org/2001/XMLSchema-instance\\\" xmlns=\\\"http://www.topografix.com/GPX/1/1\\\"\\n\") f.write( \"xsi:schemaLocation=\\\"http://www.topografix.com/GPX/1/1 http://www.topografix.com/GPX/1/1/gpx.xsd\\\">\\n\") f.write( \"<trk>\\n\") f.write(",
"</name>\\n\") f.write( \"<trkseg>\\n\") for geo in root.findall(startNode): #print geo.attrib strLine = \"<trkpt lat=\\\"\"+geo.get('lat')+\"\\\"",
"exit() infilename = sys.argv[1] outfoldername = os.path.splitext(infilename)[0] + \"_vhlplayer/\" try: os.mkdir(outfoldername) except: pass",
"+= str(icol)+\";\" strLine+=str(col[-1])+\"\\n\" f.write( strLine ) def createCSV(fileName, root, startNode, inProj, outProj): offsetX",
"os import sys import xml.etree.ElementTree as ET from pyproj import Proj,Transformer def createSCANeRMDL(fileName,type):",
"= os.path.splitext(infilename)[0] + \"_vhlplayer/\" try: os.mkdir(outfoldername) except: pass #Projections inProj=Proj(proj='latlong',datum='WGS84') outProj=Proj(init='epsg:28992', towgs84='565.417,50.3319,465.552,-0.398957,0.343988,-1.8774,4.0725') offsetX",
"\".//hostvehicle/traj/geo\", inProj, outProj) createSCANeRMDL(outfoldername + \"hostvehicle\",\"car\") createSCANePlayer(outfoldername + \"hostvehicle\") if __name__ == '__main__':",
"os.path.splitext(infilename)[0] + \"_vhlplayer/\" try: os.mkdir(outfoldername) except: pass #Projections inProj=Proj(proj='latlong',datum='WGS84') outProj=Proj(init='epsg:28992', towgs84='565.417,50.3319,465.552,-0.398957,0.343988,-1.8774,4.0725') offsetX =",
"open(fileName + \".vhplayer\", \"w\") f.write(content) templateFile.close() f.close() def createGPX(fileName, root, startNode): #Creation du",
"sys import xml.etree.ElementTree as ET from pyproj import Proj,Transformer def createSCANeRMDL(fileName,type): #Creation du",
"+ geo.get('long') + \"\\\"></trkpt>\" f.write( strLine ) f.write( \"\\n\" ) f.write( \"</trkseg>\\n\") f.write(",
") f.write( \"</trkseg>\\n\") f.write( \"</trk>\\n\") f.write( \"</gpx>\\n\") f.close() def writeCSVLine(f, strLine, col): for",
"createSCANeRMDL(fileName,type): #Creation du fichier MDL templateFileName = \"template/template_\"+type+\".mdl\" templateFile = open(templateFileName, \"r\") template=",
"= open(fileName + \".vhplayer\", \"w\") f.write(content) templateFile.close() f.close() def createGPX(fileName, root, startNode): #Creation",
"\".mdl\", \"w\") f.write(content) templateFile.close() f.close() def createSCANePlayer(fileName): #Creation du fichier Player templateFileName =",
"+ \".vhplayer\", \"w\") f.write(content) templateFile.close() f.close() def createGPX(fileName, root, startNode): #Creation du fichier",
"import Proj,Transformer def createSCANeRMDL(fileName,type): #Creation du fichier MDL templateFileName = \"template/template_\"+type+\".mdl\" templateFile =",
"+ \".gpx\", \"w\") f.write( \"<?xml version=\\\"1.0\\\" encoding=\\\"UTF-8\\\"?>\\n\") f.write( \"<gpx version=\\\"1.1\\\" creator=\\\"GpxTraceNet6.2\\\"\\n\") f.write( \"xmlns:xsi=\\\"http://www.w3.org/2001/XMLSchema-instance\\\"",
"[0.0]*36 col[0]=geo.get('secs') col[1]=col[7]=x col[2]=col[8]=y col[6]=col[12]=yaw strLine=\"\" writeCSVLine(f, strLine, col) f.close() def main(): #Parameters",
"def createSCANePlayer(fileName): #Creation du fichier Player templateFileName = \"template/template.vhplayer\" templateFile = open(templateFileName, \"r\")",
"geo in root.findall(startNode): #print geo.attrib strLine = \"<trkpt lat=\\\"\"+geo.get('lat')+\"\\\" lon=\\\"\" + geo.get('long') +",
"\"r\") template= templateFile.read() content = template.replace('template_vehicle_name', os.path.basename(fileName)) f = open(fileName + \".vhplayer\", \"w\")",
"= sys.argv[1] outfoldername = os.path.splitext(infilename)[0] + \"_vhlplayer/\" try: os.mkdir(outfoldername) except: pass #Projections inProj=Proj(proj='latlong',datum='WGS84')",
"[0.0]*36 strLine=\"\" writeCSVLine(f, strLine, col) strLine=\"\" writeCSVLine(f, strLine, col) for geo in root.findall(startNode):",
"+ \"\\\"></trkpt>\" f.write( strLine ) f.write( \"\\n\" ) f.write( \"</trkseg>\\n\") f.write( \"</trk>\\n\") f.write(",
"f.close() def createGPX(fileName, root, startNode): #Creation du fichier GPX f = open(fileName +",
"offsetX = 171338.11 offsetY = 388410.20 tree = ET.parse(infilename) root = tree.getroot() #Creation",
"root.findall(startNode): #print geo.attrib strLine = \"<trkpt lat=\\\"\"+geo.get('lat')+\"\\\" lon=\\\"\" + geo.get('long') + \"\\\"></trkpt>\" f.write(",
"f.write( \"</gpx>\\n\") f.close() def writeCSVLine(f, strLine, col): for icol in col[:-1]: strLine +=",
"fichier GPX createGPX(outfoldername + \"hostvehicle\", root, \".//hostvehicle/traj/geo\") createCSV(outfoldername + \"hostvehicle\", root, \".//hostvehicle/traj/geo\", inProj,",
"#Creation du fichier GPX createGPX(outfoldername + \"hostvehicle\", root, \".//hostvehicle/traj/geo\") createCSV(outfoldername + \"hostvehicle\", root,",
"strLine=\"\" writeCSVLine(f, strLine, col) f.close() def main(): #Parameters if len(sys.argv) < 2: print('argument",
"f.write( \"xsi:schemaLocation=\\\"http://www.topografix.com/GPX/1/1 http://www.topografix.com/GPX/1/1/gpx.xsd\\\">\\n\") f.write( \"<trk>\\n\") f.write( \"<name> RDE </name>\\n\") f.write( \"<trkseg>\\n\") for geo",
"createGPX(fileName, root, startNode): #Creation du fichier GPX f = open(fileName + \".gpx\", \"w\")",
"\"<?xml version=\\\"1.0\\\" encoding=\\\"UTF-8\\\"?>\\n\") f.write( \"<gpx version=\\\"1.1\\\" creator=\\\"GpxTraceNet6.2\\\"\\n\") f.write( \"xmlns:xsi=\\\"http://www.w3.org/2001/XMLSchema-instance\\\" xmlns=\\\"http://www.topografix.com/GPX/1/1\\\"\\n\") f.write( \"xsi:schemaLocation=\\\"http://www.topografix.com/GPX/1/1 http://www.topografix.com/GPX/1/1/gpx.xsd\\\">\\n\")",
"inProj=Proj(proj='latlong',datum='WGS84') outProj=Proj(init='epsg:28992', towgs84='565.417,50.3319,465.552,-0.398957,0.343988,-1.8774,4.0725') offsetX = 171338.11 offsetY = 388410.20 tree = ET.parse(infilename) root",
"strLine=\"\" writeCSVLine(f, strLine, col) strLine=\"\" writeCSVLine(f, strLine, col) for geo in root.findall(startNode): transformer=Transformer.from_proj(inProj,outProj)",
"#Parameters if len(sys.argv) < 2: print('argument missing : name of the file to",
"col[2]=col[8]=y col[6]=col[12]=yaw strLine=\"\" writeCSVLine(f, strLine, col) f.close() def main(): #Parameters if len(sys.argv) <",
"try: os.mkdir(outfoldername) except: pass #Projections inProj=Proj(proj='latlong',datum='WGS84') outProj=Proj(init='epsg:28992', towgs84='565.417,50.3319,465.552,-0.398957,0.343988,-1.8774,4.0725') offsetX = 171338.11 offsetY =",
"f.write( \"<?xml version=\\\"1.0\\\" encoding=\\\"UTF-8\\\"?>\\n\") f.write( \"<gpx version=\\\"1.1\\\" creator=\\\"GpxTraceNet6.2\\\"\\n\") f.write( \"xmlns:xsi=\\\"http://www.w3.org/2001/XMLSchema-instance\\\" xmlns=\\\"http://www.topografix.com/GPX/1/1\\\"\\n\") f.write( \"xsi:schemaLocation=\\\"http://www.topografix.com/GPX/1/1",
"import') exit() infilename = sys.argv[1] outfoldername = os.path.splitext(infilename)[0] + \"_vhlplayer/\" try: os.mkdir(outfoldername) except:",
"RDE </name>\\n\") f.write( \"<trkseg>\\n\") for geo in root.findall(startNode): #print geo.attrib strLine = \"<trkpt",
"fichier GPX f = open(fileName + \".gpx\", \"w\") f.write( \"<?xml version=\\\"1.0\\\" encoding=\\\"UTF-8\\\"?>\\n\") f.write(",
"def main(): #Parameters if len(sys.argv) < 2: print('argument missing : name of the",
"col[1]=col[7]=x col[2]=col[8]=y col[6]=col[12]=yaw strLine=\"\" writeCSVLine(f, strLine, col) f.close() def main(): #Parameters if len(sys.argv)",
"0.017453*float(geo.get('course')) col = [0.0]*36 col[0]=geo.get('secs') col[1]=col[7]=x col[2]=col[8]=y col[6]=col[12]=yaw strLine=\"\" writeCSVLine(f, strLine, col) f.close()",
"f.write( \"<trkseg>\\n\") for geo in root.findall(startNode): #print geo.attrib strLine = \"<trkpt lat=\\\"\"+geo.get('lat')+\"\\\" lon=\\\"\"",
"file to import') exit() infilename = sys.argv[1] outfoldername = os.path.splitext(infilename)[0] + \"_vhlplayer/\" try:",
"du fichier GPX createGPX(outfoldername + \"hostvehicle\", root, \".//hostvehicle/traj/geo\") createCSV(outfoldername + \"hostvehicle\", root, \".//hostvehicle/traj/geo\",",
"lon=\\\"\" + geo.get('long') + \"\\\"></trkpt>\" f.write( strLine ) f.write( \"\\n\" ) f.write( \"</trkseg>\\n\")",
"f.write( \"</trkseg>\\n\") f.write( \"</trk>\\n\") f.write( \"</gpx>\\n\") f.close() def writeCSVLine(f, strLine, col): for icol",
"col = [0.0]*36 strLine=\"\" writeCSVLine(f, strLine, col) strLine=\"\" writeCSVLine(f, strLine, col) for geo",
"fichier MDL templateFileName = \"template/template_\"+type+\".mdl\" templateFile = open(templateFileName, \"r\") template= templateFile.read() content =",
"strLine=\"\" writeCSVLine(f, strLine, col) for geo in root.findall(startNode): transformer=Transformer.from_proj(inProj,outProj) X,Y=transformer.transform(geo.get('long'),geo.get('lat')) x=X-offsetX y=Y-offsetY yaw",
"#Projections inProj=Proj(proj='latlong',datum='WGS84') outProj=Proj(init='epsg:28992', towgs84='565.417,50.3319,465.552,-0.398957,0.343988,-1.8774,4.0725') offsetX = 171338.11 offsetY = 388410.20 tree = ET.parse(infilename)",
"os.path.basename(fileName)) f = open(fileName + \".vhplayer\", \"w\") f.write(content) templateFile.close() f.close() def createGPX(fileName, root,",
"col): for icol in col[:-1]: strLine += str(icol)+\";\" strLine+=str(col[-1])+\"\\n\" f.write( strLine ) def",
"< 2: print('argument missing : name of the file to import') exit() infilename",
"Proj,Transformer def createSCANeRMDL(fileName,type): #Creation du fichier MDL templateFileName = \"template/template_\"+type+\".mdl\" templateFile = open(templateFileName,",
"f.write(content) templateFile.close() f.close() def createSCANePlayer(fileName): #Creation du fichier Player templateFileName = \"template/template.vhplayer\" templateFile",
"main(): #Parameters if len(sys.argv) < 2: print('argument missing : name of the file"
] |
[
"that the current user is authenticated.\"\"\" def handle_no_permission(self): return http.JsonResponse({'code': 400, 'errmsg': '用户未登录'})",
"import LoginRequiredMixin from django import http class LoginRequiredJSONMixin(LoginRequiredMixin): \"\"\"Verify that the current user",
"django.contrib.auth.mixins import LoginRequiredMixin from django import http class LoginRequiredJSONMixin(LoginRequiredMixin): \"\"\"Verify that the current",
"from django.contrib.auth.mixins import LoginRequiredMixin from django import http class LoginRequiredJSONMixin(LoginRequiredMixin): \"\"\"Verify that the",
"import http class LoginRequiredJSONMixin(LoginRequiredMixin): \"\"\"Verify that the current user is authenticated.\"\"\" def handle_no_permission(self):",
"from django import http class LoginRequiredJSONMixin(LoginRequiredMixin): \"\"\"Verify that the current user is authenticated.\"\"\"",
"django import http class LoginRequiredJSONMixin(LoginRequiredMixin): \"\"\"Verify that the current user is authenticated.\"\"\" def",
"LoginRequiredMixin from django import http class LoginRequiredJSONMixin(LoginRequiredMixin): \"\"\"Verify that the current user is",
"class LoginRequiredJSONMixin(LoginRequiredMixin): \"\"\"Verify that the current user is authenticated.\"\"\" def handle_no_permission(self): return http.JsonResponse({'code':",
"LoginRequiredJSONMixin(LoginRequiredMixin): \"\"\"Verify that the current user is authenticated.\"\"\" def handle_no_permission(self): return http.JsonResponse({'code': 400,",
"http class LoginRequiredJSONMixin(LoginRequiredMixin): \"\"\"Verify that the current user is authenticated.\"\"\" def handle_no_permission(self): return",
"\"\"\"Verify that the current user is authenticated.\"\"\" def handle_no_permission(self): return http.JsonResponse({'code': 400, 'errmsg':"
] |
[
"colors BLACK = 0x00000000 WHITE = 0xffffffff while not win.contents.windowClosed: bmp = AdvanceWin(win)",
"# Choose a font font = CreateTextRenderer(\"Courier\", 8, True) # set up the",
"# set up the window screen_w = 800 screen_h = 600 win =",
"True) # set up the colors BLACK = 0x00000000 WHITE = 0xffffffff while",
"= 0x00000000 WHITE = 0xffffffff while not win.contents.windowClosed: bmp = AdvanceWin(win) ClearBitmap(bmp, WHITE)",
"the colors BLACK = 0x00000000 WHITE = 0xffffffff while not win.contents.windowClosed: bmp =",
"BLACK = 0x00000000 WHITE = 0xffffffff while not win.contents.windowClosed: bmp = AdvanceWin(win) ClearBitmap(bmp,",
"WHITE = 0xffffffff while not win.contents.windowClosed: bmp = AdvanceWin(win) ClearBitmap(bmp, WHITE) DrawTextCentre(font, BLACK,",
"window screen_w = 800 screen_h = 600 win = CreateWin(50, 50, screen_w, screen_h,",
"win = CreateWin(50, 50, screen_w, screen_h, True, 'Hello World Example') # Choose a",
"'Hello World Example') # Choose a font font = CreateTextRenderer(\"Courier\", 8, True) #",
"a font font = CreateTextRenderer(\"Courier\", 8, True) # set up the colors BLACK",
"= 0xffffffff while not win.contents.windowClosed: bmp = AdvanceWin(win) ClearBitmap(bmp, WHITE) DrawTextCentre(font, BLACK, bmp,",
"= 800 screen_h = 600 win = CreateWin(50, 50, screen_w, screen_h, True, 'Hello",
"not win.contents.windowClosed: bmp = AdvanceWin(win) ClearBitmap(bmp, WHITE) DrawTextCentre(font, BLACK, bmp, screen_w/2, screen_h/2, \"Hello",
"font font = CreateTextRenderer(\"Courier\", 8, True) # set up the colors BLACK =",
"800 screen_h = 600 win = CreateWin(50, 50, screen_w, screen_h, True, 'Hello World",
"from deadfroglib import * # set up the window screen_w = 800 screen_h",
"up the colors BLACK = 0x00000000 WHITE = 0xffffffff while not win.contents.windowClosed: bmp",
"set up the colors BLACK = 0x00000000 WHITE = 0xffffffff while not win.contents.windowClosed:",
"8, True) # set up the colors BLACK = 0x00000000 WHITE = 0xffffffff",
"True, 'Hello World Example') # Choose a font font = CreateTextRenderer(\"Courier\", 8, True)",
"screen_h, True, 'Hello World Example') # Choose a font font = CreateTextRenderer(\"Courier\", 8,",
"screen_w = 800 screen_h = 600 win = CreateWin(50, 50, screen_w, screen_h, True,",
"while not win.contents.windowClosed: bmp = AdvanceWin(win) ClearBitmap(bmp, WHITE) DrawTextCentre(font, BLACK, bmp, screen_w/2, screen_h/2,",
"win.contents.windowClosed: bmp = AdvanceWin(win) ClearBitmap(bmp, WHITE) DrawTextCentre(font, BLACK, bmp, screen_w/2, screen_h/2, \"Hello World!\")",
"screen_w, screen_h, True, 'Hello World Example') # Choose a font font = CreateTextRenderer(\"Courier\",",
"600 win = CreateWin(50, 50, screen_w, screen_h, True, 'Hello World Example') # Choose",
"= CreateTextRenderer(\"Courier\", 8, True) # set up the colors BLACK = 0x00000000 WHITE",
"World Example') # Choose a font font = CreateTextRenderer(\"Courier\", 8, True) # set",
"50, screen_w, screen_h, True, 'Hello World Example') # Choose a font font =",
"= 600 win = CreateWin(50, 50, screen_w, screen_h, True, 'Hello World Example') #",
"import * # set up the window screen_w = 800 screen_h = 600",
"# set up the colors BLACK = 0x00000000 WHITE = 0xffffffff while not",
"up the window screen_w = 800 screen_h = 600 win = CreateWin(50, 50,",
"the window screen_w = 800 screen_h = 600 win = CreateWin(50, 50, screen_w,",
"Choose a font font = CreateTextRenderer(\"Courier\", 8, True) # set up the colors",
"* # set up the window screen_w = 800 screen_h = 600 win",
"font = CreateTextRenderer(\"Courier\", 8, True) # set up the colors BLACK = 0x00000000",
"screen_h = 600 win = CreateWin(50, 50, screen_w, screen_h, True, 'Hello World Example')",
"0x00000000 WHITE = 0xffffffff while not win.contents.windowClosed: bmp = AdvanceWin(win) ClearBitmap(bmp, WHITE) DrawTextCentre(font,",
"0xffffffff while not win.contents.windowClosed: bmp = AdvanceWin(win) ClearBitmap(bmp, WHITE) DrawTextCentre(font, BLACK, bmp, screen_w/2,",
"deadfroglib import * # set up the window screen_w = 800 screen_h =",
"CreateTextRenderer(\"Courier\", 8, True) # set up the colors BLACK = 0x00000000 WHITE =",
"Example') # Choose a font font = CreateTextRenderer(\"Courier\", 8, True) # set up",
"set up the window screen_w = 800 screen_h = 600 win = CreateWin(50,",
"CreateWin(50, 50, screen_w, screen_h, True, 'Hello World Example') # Choose a font font",
"= CreateWin(50, 50, screen_w, screen_h, True, 'Hello World Example') # Choose a font"
] |
[
"['create_mapper'] def create_mapper(worklist_series_member_tbl): \"Mapper factory.\" m = mapper(WorklistSeriesMember, worklist_series_member_tbl, properties=dict( worklist_series=relationship(WorklistSeries, uselist=False, back_populates='worklist_series_members'),",
"licensing, CONTRIBUTORS.txt for contributor information. Worklist series member mapper. \"\"\" from sqlalchemy.orm import",
"See LICENSE.txt for licensing, CONTRIBUTORS.txt for contributor information. Worklist series member mapper. \"\"\"",
"import WorklistSeriesMember __docformat__ = 'reStructuredText en' __all__ = ['create_mapper'] def create_mapper(worklist_series_member_tbl): \"Mapper factory.\"",
"thelma.entities.liquidtransfer import WorklistSeries from thelma.entities.liquidtransfer import WorklistSeriesMember __docformat__ = 'reStructuredText en' __all__ =",
"Application) project. See LICENSE.txt for licensing, CONTRIBUTORS.txt for contributor information. Worklist series member",
"import WorklistSeries from thelma.entities.liquidtransfer import WorklistSeriesMember __docformat__ = 'reStructuredText en' __all__ = ['create_mapper']",
"member mapper. \"\"\" from sqlalchemy.orm import mapper from sqlalchemy.orm import relationship from thelma.entities.liquidtransfer",
"def create_mapper(worklist_series_member_tbl): \"Mapper factory.\" m = mapper(WorklistSeriesMember, worklist_series_member_tbl, properties=dict( worklist_series=relationship(WorklistSeries, uselist=False, back_populates='worklist_series_members'), planned_worklist=relationship(PlannedWorklist,",
"Laboratory Management Application) project. See LICENSE.txt for licensing, CONTRIBUTORS.txt for contributor information. Worklist",
"= mapper(WorklistSeriesMember, worklist_series_member_tbl, properties=dict( worklist_series=relationship(WorklistSeries, uselist=False, back_populates='worklist_series_members'), planned_worklist=relationship(PlannedWorklist, uselist=False, back_populates='worklist_series_member', cascade='all,delete,delete-orphan', single_parent=True), )",
"= 'reStructuredText en' __all__ = ['create_mapper'] def create_mapper(worklist_series_member_tbl): \"Mapper factory.\" m = mapper(WorklistSeriesMember,",
"import PlannedWorklist from thelma.entities.liquidtransfer import WorklistSeries from thelma.entities.liquidtransfer import WorklistSeriesMember __docformat__ = 'reStructuredText",
"of the TheLMA (THe Laboratory Management Application) project. See LICENSE.txt for licensing, CONTRIBUTORS.txt",
"contributor information. Worklist series member mapper. \"\"\" from sqlalchemy.orm import mapper from sqlalchemy.orm",
"sqlalchemy.orm import relationship from thelma.entities.liquidtransfer import PlannedWorklist from thelma.entities.liquidtransfer import WorklistSeries from thelma.entities.liquidtransfer",
"__docformat__ = 'reStructuredText en' __all__ = ['create_mapper'] def create_mapper(worklist_series_member_tbl): \"Mapper factory.\" m =",
"\"\"\" from sqlalchemy.orm import mapper from sqlalchemy.orm import relationship from thelma.entities.liquidtransfer import PlannedWorklist",
"from thelma.entities.liquidtransfer import WorklistSeriesMember __docformat__ = 'reStructuredText en' __all__ = ['create_mapper'] def create_mapper(worklist_series_member_tbl):",
"thelma.entities.liquidtransfer import WorklistSeriesMember __docformat__ = 'reStructuredText en' __all__ = ['create_mapper'] def create_mapper(worklist_series_member_tbl): \"Mapper",
"(THe Laboratory Management Application) project. See LICENSE.txt for licensing, CONTRIBUTORS.txt for contributor information.",
"This file is part of the TheLMA (THe Laboratory Management Application) project. See",
"series member mapper. \"\"\" from sqlalchemy.orm import mapper from sqlalchemy.orm import relationship from",
"\"\"\" This file is part of the TheLMA (THe Laboratory Management Application) project.",
"from sqlalchemy.orm import mapper from sqlalchemy.orm import relationship from thelma.entities.liquidtransfer import PlannedWorklist from",
"CONTRIBUTORS.txt for contributor information. Worklist series member mapper. \"\"\" from sqlalchemy.orm import mapper",
"factory.\" m = mapper(WorklistSeriesMember, worklist_series_member_tbl, properties=dict( worklist_series=relationship(WorklistSeries, uselist=False, back_populates='worklist_series_members'), planned_worklist=relationship(PlannedWorklist, uselist=False, back_populates='worklist_series_member', cascade='all,delete,delete-orphan',",
"the TheLMA (THe Laboratory Management Application) project. See LICENSE.txt for licensing, CONTRIBUTORS.txt for",
"create_mapper(worklist_series_member_tbl): \"Mapper factory.\" m = mapper(WorklistSeriesMember, worklist_series_member_tbl, properties=dict( worklist_series=relationship(WorklistSeries, uselist=False, back_populates='worklist_series_members'), planned_worklist=relationship(PlannedWorklist, uselist=False,",
"thelma.entities.liquidtransfer import PlannedWorklist from thelma.entities.liquidtransfer import WorklistSeries from thelma.entities.liquidtransfer import WorklistSeriesMember __docformat__ =",
"is part of the TheLMA (THe Laboratory Management Application) project. See LICENSE.txt for",
"mapper(WorklistSeriesMember, worklist_series_member_tbl, properties=dict( worklist_series=relationship(WorklistSeries, uselist=False, back_populates='worklist_series_members'), planned_worklist=relationship(PlannedWorklist, uselist=False, back_populates='worklist_series_member', cascade='all,delete,delete-orphan', single_parent=True), ) )",
"for contributor information. Worklist series member mapper. \"\"\" from sqlalchemy.orm import mapper from",
"from thelma.entities.liquidtransfer import WorklistSeries from thelma.entities.liquidtransfer import WorklistSeriesMember __docformat__ = 'reStructuredText en' __all__",
"from thelma.entities.liquidtransfer import PlannedWorklist from thelma.entities.liquidtransfer import WorklistSeries from thelma.entities.liquidtransfer import WorklistSeriesMember __docformat__",
"mapper from sqlalchemy.orm import relationship from thelma.entities.liquidtransfer import PlannedWorklist from thelma.entities.liquidtransfer import WorklistSeries",
"WorklistSeries from thelma.entities.liquidtransfer import WorklistSeriesMember __docformat__ = 'reStructuredText en' __all__ = ['create_mapper'] def",
"en' __all__ = ['create_mapper'] def create_mapper(worklist_series_member_tbl): \"Mapper factory.\" m = mapper(WorklistSeriesMember, worklist_series_member_tbl, properties=dict(",
"LICENSE.txt for licensing, CONTRIBUTORS.txt for contributor information. Worklist series member mapper. \"\"\" from",
"for licensing, CONTRIBUTORS.txt for contributor information. Worklist series member mapper. \"\"\" from sqlalchemy.orm",
"information. Worklist series member mapper. \"\"\" from sqlalchemy.orm import mapper from sqlalchemy.orm import",
"Worklist series member mapper. \"\"\" from sqlalchemy.orm import mapper from sqlalchemy.orm import relationship",
"mapper. \"\"\" from sqlalchemy.orm import mapper from sqlalchemy.orm import relationship from thelma.entities.liquidtransfer import",
"sqlalchemy.orm import mapper from sqlalchemy.orm import relationship from thelma.entities.liquidtransfer import PlannedWorklist from thelma.entities.liquidtransfer",
"file is part of the TheLMA (THe Laboratory Management Application) project. See LICENSE.txt",
"part of the TheLMA (THe Laboratory Management Application) project. See LICENSE.txt for licensing,",
"import mapper from sqlalchemy.orm import relationship from thelma.entities.liquidtransfer import PlannedWorklist from thelma.entities.liquidtransfer import",
"relationship from thelma.entities.liquidtransfer import PlannedWorklist from thelma.entities.liquidtransfer import WorklistSeries from thelma.entities.liquidtransfer import WorklistSeriesMember",
"PlannedWorklist from thelma.entities.liquidtransfer import WorklistSeries from thelma.entities.liquidtransfer import WorklistSeriesMember __docformat__ = 'reStructuredText en'",
"WorklistSeriesMember __docformat__ = 'reStructuredText en' __all__ = ['create_mapper'] def create_mapper(worklist_series_member_tbl): \"Mapper factory.\" m",
"\"Mapper factory.\" m = mapper(WorklistSeriesMember, worklist_series_member_tbl, properties=dict( worklist_series=relationship(WorklistSeries, uselist=False, back_populates='worklist_series_members'), planned_worklist=relationship(PlannedWorklist, uselist=False, back_populates='worklist_series_member',",
"properties=dict( worklist_series=relationship(WorklistSeries, uselist=False, back_populates='worklist_series_members'), planned_worklist=relationship(PlannedWorklist, uselist=False, back_populates='worklist_series_member', cascade='all,delete,delete-orphan', single_parent=True), ) ) return m",
"__all__ = ['create_mapper'] def create_mapper(worklist_series_member_tbl): \"Mapper factory.\" m = mapper(WorklistSeriesMember, worklist_series_member_tbl, properties=dict( worklist_series=relationship(WorklistSeries,",
"m = mapper(WorklistSeriesMember, worklist_series_member_tbl, properties=dict( worklist_series=relationship(WorklistSeries, uselist=False, back_populates='worklist_series_members'), planned_worklist=relationship(PlannedWorklist, uselist=False, back_populates='worklist_series_member', cascade='all,delete,delete-orphan', single_parent=True),",
"Management Application) project. See LICENSE.txt for licensing, CONTRIBUTORS.txt for contributor information. Worklist series",
"= ['create_mapper'] def create_mapper(worklist_series_member_tbl): \"Mapper factory.\" m = mapper(WorklistSeriesMember, worklist_series_member_tbl, properties=dict( worklist_series=relationship(WorklistSeries, uselist=False,",
"worklist_series_member_tbl, properties=dict( worklist_series=relationship(WorklistSeries, uselist=False, back_populates='worklist_series_members'), planned_worklist=relationship(PlannedWorklist, uselist=False, back_populates='worklist_series_member', cascade='all,delete,delete-orphan', single_parent=True), ) ) return",
"project. See LICENSE.txt for licensing, CONTRIBUTORS.txt for contributor information. Worklist series member mapper.",
"TheLMA (THe Laboratory Management Application) project. See LICENSE.txt for licensing, CONTRIBUTORS.txt for contributor",
"'reStructuredText en' __all__ = ['create_mapper'] def create_mapper(worklist_series_member_tbl): \"Mapper factory.\" m = mapper(WorklistSeriesMember, worklist_series_member_tbl,",
"import relationship from thelma.entities.liquidtransfer import PlannedWorklist from thelma.entities.liquidtransfer import WorklistSeries from thelma.entities.liquidtransfer import",
"from sqlalchemy.orm import relationship from thelma.entities.liquidtransfer import PlannedWorklist from thelma.entities.liquidtransfer import WorklistSeries from"
] |
[
"arcsecperpix\") if additional_args is not None: if isinstance(additional_args, str): add_ons = [additional_args] else:",
"saturation SATUR_KEY SATURATE # keyword for saturation level (in ADUs) MAG_ZEROPOINT 0.0 #",
"ADDING ASTROMETRY for %s', filename) return solved_field SExtractor_config = \"\"\" # Configuration file",
"logging.DEBUG except subprocess.CalledProcessError as e: return_status = e.returncode solve_field_output = 'Output from astrometry.net:\\n'",
"Set True if you want to use plate scale appropriate for Feder Observatory",
"in e-/ADU PIXEL_SCALE 1.0 # size of pixel in arcsec (0=use FITS WCS",
"scale_options = '' if avoid_pyfits: pyfits_options = '--no-remove-lines --uniformize 0' else: pyfits_options =",
": str or list of str, optional Additional arguments to pass to `solve-field`",
"e logger.log(log_level, solve_field_output) return return_status def add_astrometry(filename, overwrite=False, ra_dec=None, note_failure=False, save_wcs=False, verify=None, try_builtin_source_finder=False,",
"* scale)) else: use_feder = True scale_options = '' if avoid_pyfits: pyfits_options =",
"of deblending sub-thresholds DEBLEND_MINCONT 0.005 # Minimum contrast parameter for deblending CLEAN Y",
"CLEAN Y # Clean spurious detections? (Y or N)? CLEAN_PARAM 1.0 # Cleaning",
"to use `sextractor`, or a ``str`` with the path to sextractor. custom_sextractor_config :",
"``True``, use a sexractor configuration file customized for Feder images. feder_settings : bool,",
"the file astrometry.net generates is kept. ra_dec : list or tuple of float",
"error messages genreated by astrometry.net. try_builtin_source_finder : bool If true, try using astrometry.net's",
"# stellar FWHM in arcsec STARNNW_NAME default.nnw # Neural-Network_Weight table filename #------------------------------ Background",
"except OSError: pass if note_failure and not solved_field: try: f = open(base +",
"--uniformize 0' else: pyfits_options = '' additional_opts = ' '.join([scale_options, pyfits_options]) if solve_field_args",
"magnitude zero-point MAG_GAMMA 4.0 # gamma of emulsion (for photographic scans) GAIN 0.0",
"= [\"solve-field\"] option_list = [] option_list.append(\"--obj 100\") if feder_settings: option_list.append( \"--scale-low 0.5 --scale-high",
"'w') as f: contents = \"\"\" X_IMAGE Y_IMAGE MAG_AUTO FLUX_AUTO \"\"\" f.write(dedent(contents)) additional_solve_args",
"e-/ADU GAIN_KEY GAIN # keyword for detector gain in e-/ADU PIXEL_SCALE 1.0 #",
"or <width>,<height> BACK_FILTERSIZE 3 # Background filter: <size> or <width>,<height> BACKPHOTO_TYPE GLOBAL #",
"based on default by EB 2014-11-26 # # modification was to change DETECT_MINAREA",
"though `verify` had not been specified. ra_dec : list or tuple of float",
"deblending sub-thresholds DEBLEND_MINCONT 0.005 # Minimum contrast parameter for deblending CLEAN Y #",
"file. If `False`, the file astrometry.net generates is kept. ra_dec : list or",
"= path.splitext(filename) # All are in arcsec per pixel, values are approximate camera_pixel_scales",
"or LOCAL #------------------------------ Check Image ---------------------------------- CHECKIMAGE_TYPE NONE # can be NONE, BACKGROUND,",
"or N)? CLEAN_PARAM 1.0 # Cleaning efficiency MASK_TYPE CORRECT # type of detection",
"if minimal_output: option_list.append(\"--corr none --rdls none --match none\") if not save_wcs: option_list.append(\"--wcs none\")",
"filter DEBLEND_NTHRESH 32 # Number of deblending sub-thresholds DEBLEND_MINCONT 0.005 # Minimum contrast",
": If ``True``, force the WCS reference point in the image to be",
"+ sextractor) elif sextractor: option_list.append(\"--use-source-extractor\") if no_plots: option_list.append(\"--no-plot\") if minimal_output: option_list.append(\"--corr none --rdls",
"Cleaning efficiency MASK_TYPE CORRECT # type of detection MASKing: can be one of",
"if verify is not None: if verify: solve_field.append(\"--verify\") solve_field.append(\"%s\" % verify) else: solve_field.append(\"--no-verify\")",
"if desired, a \".failed\" file for fields which it fails to solve. For",
"CCD (linear) or PHOTO (with gamma correction) DETECT_MINAREA 15 # min. # of",
"1.0 # size of pixel in arcsec (0=use FITS WCS info) #------------------------- Star/Galaxy",
"`sextractor`, or a ``str`` with the path to sextractor. custom_sextractor_config : bool, optional",
"to use for a successful solve. Default is to use the default in",
"if not save_wcs: option_list.append(\"--wcs none\") if ra_dec is not None: option_list.append(\"--ra %s --dec",
"failed_details = e.output solved_field = False if solved_field: logger.info('Adding astrometry succeeded') else: logger.warning('Adding",
"f.write(failed_details) f.close() except IOError as e: logger.error('Unable to save output of astrometry.net %s',",
"# size of pixel in arcsec (0=use FITS WCS info) #------------------------- Star/Galaxy Separation",
"__all__ = ['call_astrometry', 'add_astrometry'] logger = logging.getLogger(__name__) def call_astrometry(filename, sextractor=False, custom_sextractor_config=False, feder_settings=True, no_plots=True,",
"search radius to 1 degree. overwrite : bool, optional If ``True``, perform astrometry",
"solve_field.append('--config') solve_field.append(astrometry_config) # kludge to handle case when path of verify file contains",
"save output of astrometry.net %s', e) pass logger.info('END ADDING ASTROMETRY for %s', filename)",
"file for SExtractor 2.19.5 based on default by EB 2014-11-26 # # modification",
"300000 # number of pixels in stack MEMORY_BUFSIZE 1024 # number of lines",
"had not been specified. ra_dec : list or tuple of float (RA, Dec);",
"`'u9'`. avoid_pyfits : bool Add arguments to solve-field to avoid calls to pyfits.BinTableHDU.",
": bool or str, optional ``True`` to use `sextractor`, or a ``str`` with",
"option_list.append(\"--corr none --rdls none --match none\") if not save_wcs: option_list.append(\"--wcs none\") if ra_dec",
"custom_sextractor_config=custom_sextractor, odds_ratio=odds_ratio, astrometry_config=astrometry_config, feder_settings=use_feder, additional_args=additional_opts) == 0) except subprocess.CalledProcessError as e: logger.debug('Failed with",
"APERTURES CHECKIMAGE_NAME check.fits # Filename for the check-image #--------------------- Memory (change with caution!)",
"solve_field.append('--odds-to-solve') solve_field.append(odds_ratio) if astrometry_config is not None: solve_field.append('--config') solve_field.append(astrometry_config) # kludge to handle",
"Apogee Alta U9 camera. no_plots : bool, optional ``True`` to suppress astrometry.net generation",
"use plate scale appropriate for Feder Observatory Apogee Alta U9 camera. no_plots :",
"guess for the astrometry fit; if this plate solution does not work the",
"per pixel, values are approximate camera_pixel_scales = { 'celestron': 0.3, 'u9': 0.55, 'cp16':",
"found as though `verify` had not been specified. ra_dec : list or tuple",
"above does not work for that case. if verify is not None: if",
"to use the default in `solve-field`. astrometry_config : str, optional Name of configuration",
"more) minimal_output : bool, optional If ``True``, suppress, as separate files, output of:",
"try: solved_field = (call_astrometry(filename, ra_dec=ra_dec, overwrite=True, save_wcs=save_wcs, verify=verify) == 0) except subprocess.CalledProcessError as",
"astrometry_config=None, camera='', avoid_pyfits=False, no_source_extractor=False, solve_field_args=None): \"\"\"Add WCS headers to FITS file using astrometry.net",
"<Petrosian_fact>, # <min_radius> SATUR_LEVEL 50000.0 # level (in ADUs) at which arises saturation",
"Separation ---------------------------- SEEING_FWHM 1.2 # stellar FWHM in arcsec STARNNW_NAME default.nnw # Neural-Network_Weight",
"pass to `solve-field` \"\"\" solve_field = [\"solve-field\"] option_list = [] option_list.append(\"--obj 100\") if",
"be used as a first guess for the astrometry fit; if this plate",
"contains a space--split # above does not work for that case. if verify",
"mag.arcsec-2 ANALYSIS_THRESH 1.5 # <sigmas> or <threshold>,<ZP> in mag.arcsec-2 FILTER N # apply",
"= \"\"\" X_IMAGE Y_IMAGE MAG_AUTO FLUX_AUTO \"\"\" f.write(dedent(contents)) additional_solve_args = [ '--source-extractor-config', config_location,",
"after astrometry.net, keeping only the new FITS file it generates, the .solved file,",
"logger.debug('Failed with error') failed_details = e.output solved_field = False if (not solved_field) and",
"size of pixel in arcsec (0=use FITS WCS info) #------------------------- Star/Galaxy Separation ----------------------------",
"pass if solved_field: try: remove(base + '-indx.xyls') remove(base + '.solved') except OSError: pass",
"# MAG_AUTO parameters: <Kron_fact>,<min_radius> PHOT_PETROPARAMS 2.0, 3.5 # MAG_PETRO parameters: <Petrosian_fact>, # <min_radius>",
"bool, optional If ``True``, suppress, as separate files, output of: WCS header, RA/Dec",
"#------------------------------ Photometry ----------------------------------- PHOT_APERTURES 10 # MAG_APER aperture diameter(s) in pixels PHOT_AUTOPARAMS 2.5,",
"# of pixels above threshold DETECT_THRESH 1.5 # <sigmas> or <threshold>,<ZP> in mag.arcsec-2",
"rename import tempfile from textwrap import dedent __all__ = ['call_astrometry', 'add_astrometry'] logger =",
"= ' '.join([scale_options, pyfits_options]) if solve_field_args is not None: additional_opts = additional_opts.split() additional_opts.extend(solve_field_args)",
"option_list.append(\"--crpix-center\") options = \" \".join(option_list) solve_field.extend(options.split()) if custom_sextractor_config: tmp_location = tempfile.mkdtemp() param_location =",
"of plots (pngs showing object location and more) minimal_output : bool, optional If",
"= '' if avoid_pyfits: pyfits_options = '--no-remove-lines --uniformize 0' else: pyfits_options = ''",
"of: WCS header, RA/Dec object list, matching objects list, but see also `save_wcs`",
"= \"\"\" # Configuration file for SExtractor 2.19.5 based on default by EB",
"solve_field.append(odds_ratio) if astrometry_config is not None: solve_field.append('--config') solve_field.append(astrometry_config) # kludge to handle case",
"(0=use FITS WCS info) #------------------------- Star/Galaxy Separation ---------------------------- SEEING_FWHM 1.2 # stellar FWHM",
": bool, optional If ``True``, create a file with extension \"failed\" if astrometry.net",
"image with astrometry') try: rename(base + '.new', filename) except OSError as e: logger.error(e)",
"by EB 2014-11-26 # # modification was to change DETECT_MINAREA and turn of",
"before giving up: first sextractor, then, if that fails, astrometry.net's built-in source extractor.",
"<width>,<height> BACKPHOTO_TYPE GLOBAL # can be GLOBAL or LOCAL #------------------------------ Check Image ----------------------------------",
"f = open(base + '.failed', 'wb') f.write(failed_details) f.close() except IOError as e: logger.error('Unable",
"additional_args is not None: if isinstance(additional_args, str): add_ons = [additional_args] else: add_ons =",
"scale = camera_pixel_scales[camera] scale_options = (\"--scale-low {low} --scale-high {high} \" \"--scale-units arcsecperpix\".format(low=0.8*scale, high=1.2",
"log_level = logging.WARN logger.warning('Adding astrometry failed for %s', filename) raise e logger.log(log_level, solve_field_output)",
"plate solution does not work the solution is found as though `verify` had",
"None: if verify: solve_field.append(\"--verify\") solve_field.append(\"%s\" % verify) else: solve_field.append(\"--no-verify\") solve_field.extend([filename]) print(' '.join(solve_field)) logger.info('",
"2.0, 3.5 # MAG_PETRO parameters: <Petrosian_fact>, # <min_radius> SATUR_LEVEL 50000.0 # level (in",
"previous run are present. wcs_reference_image_center : If ``True``, force the WCS reference point",
"in e-/ADU GAIN_KEY GAIN # keyword for detector gain in e-/ADU PIXEL_SCALE 1.0",
"in stack MEMORY_PIXSTACK 300000 # number of pixels in stack MEMORY_BUFSIZE 1024 #",
"<width>,<height> BACK_FILTERSIZE 3 # Background filter: <size> or <width>,<height> BACKPHOTO_TYPE GLOBAL # can",
"zero-point MAG_GAMMA 4.0 # gamma of emulsion (for photographic scans) GAIN 0.0 #",
"0) except subprocess.CalledProcessError as e: logger.debug('Failed with error') failed_details = e.output solved_field =",
"str): add_ons = [additional_args] else: add_ons = additional_args option_list.extend(add_ons) if isinstance(sextractor, str): option_list.append(\"--source-extractor-path",
"return return_status def add_astrometry(filename, overwrite=False, ra_dec=None, note_failure=False, save_wcs=False, verify=None, try_builtin_source_finder=False, custom_sextractor=False, odds_ratio=None, astrometry_config=None,",
"use_feder = True scale_options = '' if avoid_pyfits: pyfits_options = '--no-remove-lines --uniformize 0'",
"QUIET, NORMAL or FULL HEADER_SUFFIX .head # Filename extension for additional headers WRITE_XML",
"solve. Default is to use the default in `solve-field`. astrometry_config : str, optional",
"# min. # of pixels above threshold DETECT_THRESH 1.5 # <sigmas> or <threshold>,<ZP>",
"MINIBACKGROUND, MINIBACK_RMS, -BACKGROUND, # FILTERED, OBJECTS, -OBJECTS, SEGMENTATION, # or APERTURES CHECKIMAGE_NAME check.fits",
"= additional_args option_list.extend(add_ons) if isinstance(sextractor, str): option_list.append(\"--source-extractor-path \" + sextractor) elif sextractor: option_list.append(\"--use-source-extractor\")",
"wcs_reference_image_center=True, odds_ratio=None, astrometry_config=None, additional_args=None): \"\"\" Wrapper around astrometry.net solve-field. Parameters ---------- sextractor :",
"then, if that fails, astrometry.net's built-in source extractor. It also cleans up after",
"aperture diameter(s) in pixels PHOT_AUTOPARAMS 2.5, 3.5 # MAG_AUTO parameters: <Kron_fact>,<min_radius> PHOT_PETROPARAMS 2.0,",
"None: if isinstance(additional_args, str): add_ons = [additional_args] else: add_ons = additional_args option_list.extend(add_ons) if",
"arcsecperpix\".format(low=0.8*scale, high=1.2 * scale)) else: use_feder = True scale_options = '' if avoid_pyfits:",
"in buffer #----------------------------- Miscellaneous --------------------------------- VERBOSE_TYPE NORMAL # can be QUIET, NORMAL or",
"detector gain in e-/ADU GAIN_KEY GAIN # keyword for detector gain in e-/ADU",
"astrometry.net solve-field. Parameters ---------- sextractor : bool or str, optional ``True`` to use",
"if solved_field: try: remove(base + '-indx.xyls') remove(base + '.solved') except OSError: pass if",
"not solved_field: try: f = open(base + '.failed', 'wb') f.write(failed_details) f.close() except IOError",
"scale used in the solved. Default is to use `'u9'`. avoid_pyfits : bool",
"does not work for that case. if verify is not None: if verify:",
"the new FITS file it generates, the .solved file, and, if desired, a",
"Dec); also limits search radius to 1 degree. overwrite : bool, optional If",
"open(config_location, 'w') as f: f.write(config_contents) with open(param_location, 'w') as f: contents = \"\"\"",
"= (call_astrometry(filename, sextractor=not no_source_extractor, ra_dec=ra_dec, save_wcs=save_wcs, verify=verify, custom_sextractor_config=custom_sextractor, odds_ratio=odds_ratio, astrometry_config=astrometry_config, feder_settings=use_feder, additional_args=additional_opts) ==",
"parameter for deblending CLEAN Y # Clean spurious detections? (Y or N)? CLEAN_PARAM",
"BLANK or CORRECT #------------------------------ Photometry ----------------------------------- PHOT_APERTURES 10 # MAG_APER aperture diameter(s) in",
"# name of the file containing catalog contents #------------------------------- Extraction ---------------------------------- DETECT_TYPE CCD",
"# kludge to handle case when path of verify file contains a space--split",
"BACKPHOTO_TYPE GLOBAL # can be GLOBAL or LOCAL #------------------------------ Check Image ---------------------------------- CHECKIMAGE_TYPE",
"f: f.write(config_contents) with open(param_location, 'w') as f: contents = \"\"\" X_IMAGE Y_IMAGE MAG_AUTO",
"0.55, 'cp16': 0.55 } if camera: use_feder = False scale = camera_pixel_scales[camera] scale_options",
"Additional arguments to pass to `solve-field` \"\"\" solve_field = [\"solve-field\"] option_list = []",
"add_ons = additional_args option_list.extend(add_ons) if isinstance(sextractor, str): option_list.append(\"--source-extractor-path \" + sextractor) elif sextractor:",
"--------------------------------- VERBOSE_TYPE NORMAL # can be QUIET, NORMAL or FULL HEADER_SUFFIX .head #",
"if no_plots: option_list.append(\"--no-plot\") if minimal_output: option_list.append(\"--corr none --rdls none --match none\") if not",
"astrometry even if astrometry.net files from a previous run are present. wcs_reference_image_center :",
"= 'Astrometry failed using sextractor, trying built-in ' log_msg += 'source finder' logger.info(log_msg)",
"arcsec (0=use FITS WCS info) #------------------------- Star/Galaxy Separation ---------------------------- SEEING_FWHM 1.2 # stellar",
"finder' logger.info(log_msg) try: solved_field = (call_astrometry(filename, ra_dec=ra_dec, overwrite=True, save_wcs=save_wcs, verify=verify) == 0) except",
"none --rdls none --match none\") if not save_wcs: option_list.append(\"--wcs none\") if ra_dec is",
"float or str (RA, Dec) of field center as either decimal or sexagesimal;",
"0' else: pyfits_options = '' additional_opts = ' '.join([scale_options, pyfits_options]) if solve_field_args is",
"solved_field: try: f = open(base + '.failed', 'wb') f.write(failed_details) f.close() except IOError as",
"------------------------------------ PARAMETERS_NAME {param_file} # name of the file containing catalog contents #------------------------------- Extraction",
"= [additional_args] else: add_ons = additional_args option_list.extend(add_ons) if isinstance(sextractor, str): option_list.append(\"--source-extractor-path \" +",
"FLUX_AUTO \"\"\" f.write(dedent(contents)) additional_solve_args = [ '--source-extractor-config', config_location, '--x-column', 'X_IMAGE', '--y-column', 'Y_IMAGE', '--sort-column',",
"bool, optional If ``True``, use a sexractor configuration file customized for Feder images.",
"ASTROMETRY on {0}'.format(filename)) try: logger.debug('About to call call_astrometry') solved_field = (call_astrometry(filename, sextractor=not no_source_extractor,",
"PHOT_AUTOPARAMS 2.5, 3.5 # MAG_AUTO parameters: <Kron_fact>,<min_radius> PHOT_PETROPARAMS 2.0, 3.5 # MAG_PETRO parameters:",
"odds_ratio=None, astrometry_config=None, camera='', avoid_pyfits=False, no_source_extractor=False, solve_field_args=None): \"\"\"Add WCS headers to FITS file using",
"file containing catalog contents #------------------------------- Extraction ---------------------------------- DETECT_TYPE CCD # CCD (linear) or",
"is suppressed with `minimial_output` verify : str, optional Name of a WCS header",
"(change with caution!) ------------------------- MEMORY_OBJSTACK 3000 # number of objects in stack MEMORY_PIXSTACK",
":func:`call_astrometry` \"\"\" base, ext = path.splitext(filename) # All are in arcsec per pixel,",
"str, optional Name of configuration file to use for SExtractor. additional_args : str",
": bool, optional ``True`` to suppress astrometry.net generation of plots (pngs showing object",
"float, optional The odds ratio to use for a successful solve. Default is",
"the default in `solve-field`. astrometry_config : str, optional Name of configuration file to",
"camera_pixel_scales[camera] scale_options = (\"--scale-low {low} --scale-high {high} \" \"--scale-units arcsecperpix\".format(low=0.8*scale, high=1.2 * scale))",
"'--x-column', 'X_IMAGE', '--y-column', 'Y_IMAGE', '--sort-column', 'MAG_AUTO', '--sort-ascending' ] solve_field.extend(additional_solve_args) if odds_ratio is not",
": list or tuple of float (RA, Dec); also limits search radius to",
"FITS file using astrometry.net Parameters ---------- overwrite : bool, optional Set ``True`` to",
"open(base + '.failed', 'wb') f.write(failed_details) f.close() except IOError as e: logger.error('Unable to save",
"if astrometry_config is not None: solve_field.append('--config') solve_field.append(astrometry_config) # kludge to handle case when",
"\"\"\"Add WCS headers to FITS file using astrometry.net Parameters ---------- overwrite : bool,",
"optional If ``True``, create a file with extension \"failed\" if astrometry.net fails. The",
"or <threshold>,<ZP> in mag.arcsec-2 FILTER N # apply filter for detection (Y or",
"{high} \" \"--scale-units arcsecperpix\".format(low=0.8*scale, high=1.2 * scale)) else: use_feder = True scale_options =",
"call_astrometry') solved_field = (call_astrometry(filename, sextractor=not no_source_extractor, ra_dec=ra_dec, save_wcs=save_wcs, verify=verify, custom_sextractor_config=custom_sextractor, odds_ratio=odds_ratio, astrometry_config=astrometry_config, feder_settings=use_feder,",
"The odds ratio to use for a successful solve. Default is to use",
"---------------------------------- CHECKIMAGE_TYPE NONE # can be NONE, BACKGROUND, BACKGROUND_RMS, # MINIBACKGROUND, MINIBACK_RMS, -BACKGROUND,",
"solve_field_args is not None: additional_opts = additional_opts.split() additional_opts.extend(solve_field_args) logger.info('BEGIN ADDING ASTROMETRY on {0}'.format(filename))",
"(with gamma correction) DETECT_MINAREA 15 # min. # of pixels above threshold DETECT_THRESH",
"tempfile from textwrap import dedent __all__ = ['call_astrometry', 'add_astrometry'] logger = logging.getLogger(__name__) def",
"STARNNW_NAME default.nnw # Neural-Network_Weight table filename #------------------------------ Background ----------------------------------- BACK_SIZE 64 # Background",
"CLEAN_PARAM 1.0 # Cleaning efficiency MASK_TYPE CORRECT # type of detection MASKing: can",
"= e.output solved_field = False if solved_field: logger.info('Adding astrometry succeeded') else: logger.warning('Adding astrometry",
"bool, optional If ``True``, save WCS header even if other output is suppressed",
"which arises saturation SATUR_KEY SATURATE # keyword for saturation level (in ADUs) MAG_ZEROPOINT",
"with open(config_location, 'w') as f: f.write(config_contents) with open(param_location, 'w') as f: contents =",
"\"\"\" f.write(dedent(contents)) additional_solve_args = [ '--source-extractor-config', config_location, '--x-column', 'X_IMAGE', '--y-column', 'Y_IMAGE', '--sort-column', 'MAG_AUTO',",
"with caution!) ------------------------- MEMORY_OBJSTACK 3000 # number of objects in stack MEMORY_PIXSTACK 300000",
"of pixels above threshold DETECT_THRESH 1.5 # <sigmas> or <threshold>,<ZP> in mag.arcsec-2 ANALYSIS_THRESH",
"files from a previous run are present. wcs_reference_image_center : If ``True``, force the",
"else: pyfits_options = '' additional_opts = ' '.join([scale_options, pyfits_options]) if solve_field_args is not",
"as either decimal or sexagesimal; also limits search radius to 1 degree. note_failure",
"path.join(tmp_location, 'default.param') config_location = path.join(tmp_location, 'feder.config') config_contents = SExtractor_config.format(param_file=param_location) with open(config_location, 'w') as",
"# <min_radius> SATUR_LEVEL 50000.0 # level (in ADUs) at which arises saturation SATUR_KEY",
"none\") if ra_dec is not None: option_list.append(\"--ra %s --dec %s --radius 0.5\" %",
"pixel in arcsec (0=use FITS WCS info) #------------------------- Star/Galaxy Separation ---------------------------- SEEING_FWHM 1.2",
"built-in source extractor if sextractor fails. save_wcs : verify : See :func:`call_astrometry` camera",
"verify) else: solve_field.append(\"--no-verify\") solve_field.extend([filename]) print(' '.join(solve_field)) logger.info(' '.join(solve_field)) try: solve_field_output = subprocess.check_output(solve_field, stderr=subprocess.STDOUT)",
"add_astrometry(filename, overwrite=False, ra_dec=None, note_failure=False, save_wcs=False, verify=None, try_builtin_source_finder=False, custom_sextractor=False, odds_ratio=None, astrometry_config=None, camera='', avoid_pyfits=False, no_source_extractor=False,",
"of the file containing catalog contents #------------------------------- Extraction ---------------------------------- DETECT_TYPE CCD # CCD",
"'u9', 'cp16'], optional Name of camera; determines the pixel scale used in the",
"output of: WCS header, RA/Dec object list, matching objects list, but see also",
"using astrometry.net Parameters ---------- overwrite : bool, optional Set ``True`` to overwrite the",
"config_location = path.join(tmp_location, 'feder.config') config_contents = SExtractor_config.format(param_file=param_location) with open(config_location, 'w') as f: f.write(config_contents)",
"or list of str, optional Additional arguments to pass to `solve-field` \"\"\" solve_field",
"info) #------------------------- Star/Galaxy Separation ---------------------------- SEEING_FWHM 1.2 # stellar FWHM in arcsec STARNNW_NAME",
"additional_args : str or list of str, optional Additional arguments to pass to",
"solved_field SExtractor_config = \"\"\" # Configuration file for SExtractor 2.19.5 based on default",
"bool, optional ``True`` to suppress astrometry.net generation of plots (pngs showing object location",
"arcsec per pixel, values are approximate camera_pixel_scales = { 'celestron': 0.3, 'u9': 0.55,",
"BACK_SIZE 64 # Background mesh: <size> or <width>,<height> BACK_FILTERSIZE 3 # Background filter:",
"bool ``True`` on success. Notes ----- Tries a couple strategies before giving up:",
"----------------------------------- BACK_SIZE 64 # Background mesh: <size> or <width>,<height> BACK_FILTERSIZE 3 # Background",
"as though `verify` had not been specified. ra_dec : list or tuple of",
"'--source-extractor-config', config_location, '--x-column', 'X_IMAGE', '--y-column', 'Y_IMAGE', '--sort-column', 'MAG_AUTO', '--sort-ascending' ] solve_field.extend(additional_solve_args) if odds_ratio",
"e.output solved_field = False if solved_field: logger.info('Adding astrometry succeeded') else: logger.warning('Adding astrometry failed",
"\"\"\" # Configuration file for SExtractor 2.19.5 based on default by EB 2014-11-26",
"---------------------------------- DETECT_TYPE CCD # CCD (linear) or PHOTO (with gamma correction) DETECT_MINAREA 15",
"file contains a space--split # above does not work for that case. if",
"'feder.config') config_contents = SExtractor_config.format(param_file=param_location) with open(config_location, 'w') as f: f.write(config_contents) with open(param_location, 'w')",
"(call_astrometry(filename, ra_dec=ra_dec, overwrite=True, save_wcs=save_wcs, verify=verify) == 0) except subprocess.CalledProcessError as e: failed_details =",
"images. feder_settings : bool, optional Set True if you want to use plate",
"# detector gain in e-/ADU GAIN_KEY GAIN # keyword for detector gain in",
"# FILTERED, OBJECTS, -OBJECTS, SEGMENTATION, # or APERTURES CHECKIMAGE_NAME check.fits # Filename for",
"It also cleans up after astrometry.net, keeping only the new FITS file it",
"log_msg += 'source finder' logger.info(log_msg) try: solved_field = (call_astrometry(filename, ra_dec=ra_dec, overwrite=True, save_wcs=save_wcs, verify=verify)",
"Filename extension for additional headers WRITE_XML N # Write XML file (Y/N)? XML_NAME",
"of # NONE, BLANK or CORRECT #------------------------------ Photometry ----------------------------------- PHOT_APERTURES 10 # MAG_APER",
"overwrite : bool, optional Set ``True`` to overwrite the original file. If `False`,",
"additional_opts.split() additional_opts.extend(solve_field_args) logger.info('BEGIN ADDING ASTROMETRY on {0}'.format(filename)) try: logger.debug('About to call call_astrometry') solved_field",
"table filename #------------------------------ Background ----------------------------------- BACK_SIZE 64 # Background mesh: <size> or <width>,<height>",
"# number of objects in stack MEMORY_PIXSTACK 300000 # number of pixels in",
"# apply filter for detection (Y or N)? FILTER_NAME default.conv # name of",
"spurious detections? (Y or N)? CLEAN_PARAM 1.0 # Cleaning efficiency MASK_TYPE CORRECT #",
"solve-field. Parameters ---------- sextractor : bool or str, optional ``True`` to use `sextractor`,",
"GAIN_KEY GAIN # keyword for detector gain in e-/ADU PIXEL_SCALE 1.0 # size",
"desired, a \".failed\" file for fields which it fails to solve. For more",
"isinstance(sextractor, str): option_list.append(\"--source-extractor-path \" + sextractor) elif sextractor: option_list.append(\"--use-source-extractor\") if no_plots: option_list.append(\"--no-plot\") if",
"#------------------------------- Extraction ---------------------------------- DETECT_TYPE CCD # CCD (linear) or PHOTO (with gamma correction)",
"GLOBAL # can be GLOBAL or LOCAL #------------------------------ Check Image ---------------------------------- CHECKIMAGE_TYPE NONE",
"print(' '.join(solve_field)) logger.info(' '.join(solve_field)) try: solve_field_output = subprocess.check_output(solve_field, stderr=subprocess.STDOUT) return_status = 0 log_level",
"``True`` to overwrite the original file. If `False`, the file astrometry.net generates is",
"work for that case. if verify is not None: if verify: solve_field.append(\"--verify\") solve_field.append(\"%s\"",
"is not None: option_list.append(\"--ra %s --dec %s --radius 0.5\" % ra_dec) if overwrite:",
"or <threshold>,<ZP> in mag.arcsec-2 ANALYSIS_THRESH 1.5 # <sigmas> or <threshold>,<ZP> in mag.arcsec-2 FILTER",
"= logging.getLogger(__name__) def call_astrometry(filename, sextractor=False, custom_sextractor_config=False, feder_settings=True, no_plots=True, minimal_output=True, save_wcs=False, verify=None, ra_dec=None, overwrite=False,",
"+ str(e.output) log_level = logging.WARN logger.warning('Adding astrometry failed for %s', filename) raise e",
"can be GLOBAL or LOCAL #------------------------------ Check Image ---------------------------------- CHECKIMAGE_TYPE NONE # can",
"if odds_ratio is not None: solve_field.append('--odds-to-solve') solve_field.append(odds_ratio) if astrometry_config is not None: solve_field.append('--config')",
"logger.error(e) return False # whether we succeeded or failed, clean up try: remove(base",
"astrometry') try: rename(base + '.new', filename) except OSError as e: logger.error(e) return False",
"# keyword for saturation level (in ADUs) MAG_ZEROPOINT 0.0 # magnitude zero-point MAG_GAMMA",
"[\"solve-field\"] option_list = [] option_list.append(\"--obj 100\") if feder_settings: option_list.append( \"--scale-low 0.5 --scale-high 0.6",
"------------------------- MEMORY_OBJSTACK 3000 # number of objects in stack MEMORY_PIXSTACK 300000 # number",
"handle case when path of verify file contains a space--split # above does",
"be the image center. odds_ratio : float, optional The odds ratio to use",
"option_list.append(\"--obj 100\") if feder_settings: option_list.append( \"--scale-low 0.5 --scale-high 0.6 --scale-units arcsecperpix\") if additional_args",
"MASK_TYPE CORRECT # type of detection MASKing: can be one of # NONE,",
"# MINIBACKGROUND, MINIBACK_RMS, -BACKGROUND, # FILTERED, OBJECTS, -OBJECTS, SEGMENTATION, # or APERTURES CHECKIMAGE_NAME",
"overwrite=False, wcs_reference_image_center=True, odds_ratio=None, astrometry_config=None, additional_args=None): \"\"\" Wrapper around astrometry.net solve-field. Parameters ---------- sextractor",
"SExtractor_config = \"\"\" # Configuration file for SExtractor 2.19.5 based on default by",
"= [] option_list.append(\"--obj 100\") if feder_settings: option_list.append( \"--scale-low 0.5 --scale-high 0.6 --scale-units arcsecperpix\")",
"\"\"\" X_IMAGE Y_IMAGE MAG_AUTO FLUX_AUTO \"\"\" f.write(dedent(contents)) additional_solve_args = [ '--source-extractor-config', config_location, '--x-column',",
"bool If true, try using astrometry.net's built-in source extractor if sextractor fails. save_wcs",
"# can be GLOBAL or LOCAL #------------------------------ Check Image ---------------------------------- CHECKIMAGE_TYPE NONE #",
"or CORRECT #------------------------------ Photometry ----------------------------------- PHOT_APERTURES 10 # MAG_APER aperture diameter(s) in pixels",
": bool, optional Set True if you want to use plate scale appropriate",
"FILTER N # apply filter for detection (Y or N)? FILTER_NAME default.conv #",
"ra_dec : list or tuple of float or str (RA, Dec) of field",
"N # Write XML file (Y/N)? XML_NAME sex.xml # Filename for XML output",
"first sextractor, then, if that fails, astrometry.net's built-in source extractor. It also cleans",
"None: solve_field.append('--odds-to-solve') solve_field.append(odds_ratio) if astrometry_config is not None: solve_field.append('--config') solve_field.append(astrometry_config) # kludge to",
"name of the file containing catalog contents #------------------------------- Extraction ---------------------------------- DETECT_TYPE CCD #",
"'Output from astrometry.net:\\n' + str(e.output) log_level = logging.WARN logger.warning('Adding astrometry failed for %s',",
"SEGMENTATION, # or APERTURES CHECKIMAGE_NAME check.fits # Filename for the check-image #--------------------- Memory",
"for saturation level (in ADUs) MAG_ZEROPOINT 0.0 # magnitude zero-point MAG_GAMMA 4.0 #",
"showing object location and more) minimal_output : bool, optional If ``True``, suppress, as",
"determines the pixel scale used in the solved. Default is to use `'u9'`.",
"% verify) else: solve_field.append(\"--no-verify\") solve_field.extend([filename]) print(' '.join(solve_field)) logger.info(' '.join(solve_field)) try: solve_field_output = subprocess.check_output(solve_field,",
"optional The odds ratio to use for a successful solve. Default is to",
"the solution is found as though `verify` had not been specified. ra_dec :",
"no_source_extractor=False, solve_field_args=None): \"\"\"Add WCS headers to FITS file using astrometry.net Parameters ---------- overwrite",
"additional_args=additional_opts) == 0) except subprocess.CalledProcessError as e: logger.debug('Failed with error') failed_details = e.output",
"optional Name of configuration file to use for SExtractor. additional_args : str or",
"to save output of astrometry.net %s', e) pass logger.info('END ADDING ASTROMETRY for %s',",
"if custom_sextractor_config: tmp_location = tempfile.mkdtemp() param_location = path.join(tmp_location, 'default.param') config_location = path.join(tmp_location, 'feder.config')",
"file using astrometry.net Parameters ---------- overwrite : bool, optional Set ``True`` to overwrite",
"BACKGROUND, BACKGROUND_RMS, # MINIBACKGROUND, MINIBACK_RMS, -BACKGROUND, # FILTERED, OBJECTS, -OBJECTS, SEGMENTATION, # or",
"pass logger.info('END ADDING ASTROMETRY for %s', filename) return solved_field SExtractor_config = \"\"\" #",
"<threshold>,<ZP> in mag.arcsec-2 FILTER N # apply filter for detection (Y or N)?",
"original file with image with astrometry') try: rename(base + '.new', filename) except OSError",
"GLOBAL or LOCAL #------------------------------ Check Image ---------------------------------- CHECKIMAGE_TYPE NONE # can be NONE,",
"reference point in the image to be the image center. odds_ratio : float,",
"apply filter for detection (Y or N)? FILTER_NAME default.conv # name of the",
"use the default in `solve-field`. astrometry_config : str, optional Name of configuration file",
"to pass to `solve-field` \"\"\" solve_field = [\"solve-field\"] option_list = [] option_list.append(\"--obj 100\")",
"verify : str, optional Name of a WCS header to be used as",
"overwrite and solved_field: logger.info('Overwriting original file with image with astrometry') try: rename(base +",
"PHOT_APERTURES 10 # MAG_APER aperture diameter(s) in pixels PHOT_AUTOPARAMS 2.5, 3.5 # MAG_AUTO",
"we succeeded or failed, clean up try: remove(base + '.axy') except OSError: pass",
"logging import subprocess from os import path, remove, rename import tempfile from textwrap",
"for Feder images. feder_settings : bool, optional Set True if you want to",
"saturation level (in ADUs) MAG_ZEROPOINT 0.0 # magnitude zero-point MAG_GAMMA 4.0 # gamma",
"sextractor, then, if that fails, astrometry.net's built-in source extractor. It also cleans up",
"minimal_output : bool, optional If ``True``, suppress, as separate files, output of: WCS",
"solve_field.extend(options.split()) if custom_sextractor_config: tmp_location = tempfile.mkdtemp() param_location = path.join(tmp_location, 'default.param') config_location = path.join(tmp_location,",
"astrometry fit; if this plate solution does not work the solution is found",
"stellar FWHM in arcsec STARNNW_NAME default.nnw # Neural-Network_Weight table filename #------------------------------ Background -----------------------------------",
"astrometry.net's built-in source extractor if sextractor fails. save_wcs : verify : See :func:`call_astrometry`",
"search radius to 1 degree. note_failure : bool, optional If ``True``, create a",
"Clean spurious detections? (Y or N)? CLEAN_PARAM 1.0 # Cleaning efficiency MASK_TYPE CORRECT",
"FULL HEADER_SUFFIX .head # Filename extension for additional headers WRITE_XML N # Write",
"sextractor : bool or str, optional ``True`` to use `sextractor`, or a ``str``",
"from os import path, remove, rename import tempfile from textwrap import dedent __all__",
"--scale-units arcsecperpix\") if additional_args is not None: if isinstance(additional_args, str): add_ons = [additional_args]",
"# type of detection MASKing: can be one of # NONE, BLANK or",
"If ``True``, use a sexractor configuration file customized for Feder images. feder_settings :",
"which it fails to solve. For more flexible invocation of astrometry.net, see :func:`call_astrometry`",
"path.join(tmp_location, 'feder.config') config_contents = SExtractor_config.format(param_file=param_location) with open(config_location, 'w') as f: f.write(config_contents) with open(param_location,",
"limits search radius to 1 degree. note_failure : bool, optional If ``True``, create",
"extension for additional headers WRITE_XML N # Write XML file (Y/N)? XML_NAME sex.xml",
"as e: logger.debug('Failed with error') failed_details = e.output solved_field = False if (not",
":func:`call_astrometry` camera : str, one of ['celestron', 'u9', 'cp16'], optional Name of camera;",
"pass if note_failure and not solved_field: try: f = open(base + '.failed', 'wb')",
"can be QUIET, NORMAL or FULL HEADER_SUFFIX .head # Filename extension for additional",
"to solve-field to avoid calls to pyfits.BinTableHDU. See https://groups.google.com/forum/#!topic/astrometry/AT21x6zVAJo Returns ------- bool ``True``",
"Background mesh: <size> or <width>,<height> BACK_FILTERSIZE 3 # Background filter: <size> or <width>,<height>",
"DETECT_MINAREA 15 # min. # of pixels above threshold DETECT_THRESH 1.5 # <sigmas>",
"str(e.output) log_level = logging.WARN logger.warning('Adding astrometry failed for %s', filename) raise e logger.log(log_level,",
"or failed, clean up try: remove(base + '.axy') except OSError: pass if solved_field:",
"# # modification was to change DETECT_MINAREA and turn of filter convolution #--------------------------------",
"filter convolution #-------------------------------- Catalog ------------------------------------ PARAMETERS_NAME {param_file} # name of the file containing",
"messages genreated by astrometry.net. try_builtin_source_finder : bool If true, try using astrometry.net's built-in",
"using sextractor, trying built-in ' log_msg += 'source finder' logger.info(log_msg) try: solved_field =",
"headers to FITS file using astrometry.net Parameters ---------- overwrite : bool, optional Set",
"1.0 # Cleaning efficiency MASK_TYPE CORRECT # type of detection MASKing: can be",
"'.new', filename) except OSError as e: logger.error(e) return False # whether we succeeded",
"32 # Number of deblending sub-thresholds DEBLEND_MINCONT 0.005 # Minimum contrast parameter for",
"try: remove(base + '.axy') except OSError: pass if solved_field: try: remove(base + '-indx.xyls')",
"Feder images. feder_settings : bool, optional Set True if you want to use",
"filename) raise e logger.log(log_level, solve_field_output) return return_status def add_astrometry(filename, overwrite=False, ra_dec=None, note_failure=False, save_wcs=False,",
"= camera_pixel_scales[camera] scale_options = (\"--scale-low {low} --scale-high {high} \" \"--scale-units arcsecperpix\".format(low=0.8*scale, high=1.2 *",
"a couple strategies before giving up: first sextractor, then, if that fails, astrometry.net's",
"else: solve_field.append(\"--no-verify\") solve_field.extend([filename]) print(' '.join(solve_field)) logger.info(' '.join(solve_field)) try: solve_field_output = subprocess.check_output(solve_field, stderr=subprocess.STDOUT) return_status",
"even if other output is suppressed with `minimial_output` verify : str, optional Name",
"avoid calls to pyfits.BinTableHDU. See https://groups.google.com/forum/#!topic/astrometry/AT21x6zVAJo Returns ------- bool ``True`` on success. Notes",
"100\") if feder_settings: option_list.append( \"--scale-low 0.5 --scale-high 0.6 --scale-units arcsecperpix\") if additional_args is",
"SATUR_LEVEL 50000.0 # level (in ADUs) at which arises saturation SATUR_KEY SATURATE #",
"of detection MASKing: can be one of # NONE, BLANK or CORRECT #------------------------------",
"to use plate scale appropriate for Feder Observatory Apogee Alta U9 camera. no_plots",
"succeeded') else: logger.warning('Adding astrometry failed for file %s', filename) if overwrite and solved_field:",
"astrometry.net generates is kept. ra_dec : list or tuple of float or str",
"if you want to use plate scale appropriate for Feder Observatory Apogee Alta",
"# above does not work for that case. if verify is not None:",
"2.19.5 based on default by EB 2014-11-26 # # modification was to change",
"ANALYSIS_THRESH 1.5 # <sigmas> or <threshold>,<ZP> in mag.arcsec-2 FILTER N # apply filter",
"the astrometry fit; if this plate solution does not work the solution is",
"FWHM in arcsec STARNNW_NAME default.nnw # Neural-Network_Weight table filename #------------------------------ Background ----------------------------------- BACK_SIZE",
"center as either decimal or sexagesimal; also limits search radius to 1 degree.",
"solve_field.append(\"--verify\") solve_field.append(\"%s\" % verify) else: solve_field.append(\"--no-verify\") solve_field.extend([filename]) print(' '.join(solve_field)) logger.info(' '.join(solve_field)) try: solve_field_output",
"the solved. Default is to use `'u9'`. avoid_pyfits : bool Add arguments to",
"as e: return_status = e.returncode solve_field_output = 'Output from astrometry.net:\\n' + str(e.output) log_level",
"WCS headers to FITS file using astrometry.net Parameters ---------- overwrite : bool, optional",
"bool Add arguments to solve-field to avoid calls to pyfits.BinTableHDU. See https://groups.google.com/forum/#!topic/astrometry/AT21x6zVAJo Returns",
"DEBLEND_MINCONT 0.005 # Minimum contrast parameter for deblending CLEAN Y # Clean spurious",
"feder_settings=use_feder, additional_args=additional_opts) == 0) except subprocess.CalledProcessError as e: logger.debug('Failed with error') failed_details =",
"'.join(solve_field)) try: solve_field_output = subprocess.check_output(solve_field, stderr=subprocess.STDOUT) return_status = 0 log_level = logging.DEBUG except",
"astrometry.net Parameters ---------- overwrite : bool, optional Set ``True`` to overwrite the original",
"to 1 degree. note_failure : bool, optional If ``True``, create a file with",
"deblending CLEAN Y # Clean spurious detections? (Y or N)? CLEAN_PARAM 1.0 #",
"4.0 # gamma of emulsion (for photographic scans) GAIN 0.0 # detector gain",
"from astrometry.net:\\n' + str(e.output) log_level = logging.WARN logger.warning('Adding astrometry failed for %s', filename)",
"arises saturation SATUR_KEY SATURATE # keyword for saturation level (in ADUs) MAG_ZEROPOINT 0.0",
"create a file with extension \"failed\" if astrometry.net fails. The \"failed\" file contains",
"header to be used as a first guess for the astrometry fit; if",
"a WCS header to be used as a first guess for the astrometry",
"if isinstance(additional_args, str): add_ons = [additional_args] else: add_ons = additional_args option_list.extend(add_ons) if isinstance(sextractor,",
"# magnitude zero-point MAG_GAMMA 4.0 # gamma of emulsion (for photographic scans) GAIN",
"optional If ``True``, save WCS header even if other output is suppressed with",
"is to use the default in `solve-field`. astrometry_config : str, optional Name of",
"radius to 1 degree. overwrite : bool, optional If ``True``, perform astrometry even",
"separate files, output of: WCS header, RA/Dec object list, matching objects list, but",
"option_list.append( \"--scale-low 0.5 --scale-high 0.6 --scale-units arcsecperpix\") if additional_args is not None: if",
"N # apply filter for detection (Y or N)? FILTER_NAME default.conv # name",
"0.6 --scale-units arcsecperpix\") if additional_args is not None: if isinstance(additional_args, str): add_ons =",
"new FITS file it generates, the .solved file, and, if desired, a \".failed\"",
"(pngs showing object location and more) minimal_output : bool, optional If ``True``, suppress,",
"in stack MEMORY_BUFSIZE 1024 # number of lines in buffer #----------------------------- Miscellaneous ---------------------------------",
"contents #------------------------------- Extraction ---------------------------------- DETECT_TYPE CCD # CCD (linear) or PHOTO (with gamma",
"optional Set ``True`` to overwrite the original file. If `False`, the file astrometry.net",
"source extractor. It also cleans up after astrometry.net, keeping only the new FITS",
"for Feder Observatory Apogee Alta U9 camera. no_plots : bool, optional ``True`` to",
"# MAG_APER aperture diameter(s) in pixels PHOT_AUTOPARAMS 2.5, 3.5 # MAG_AUTO parameters: <Kron_fact>,<min_radius>",
"\"--scale-units arcsecperpix\".format(low=0.8*scale, high=1.2 * scale)) else: use_feder = True scale_options = '' if",
"file with image with astrometry') try: rename(base + '.new', filename) except OSError as",
"if overwrite: option_list.append(\"--overwrite\") if wcs_reference_image_center: option_list.append(\"--crpix-center\") options = \" \".join(option_list) solve_field.extend(options.split()) if custom_sextractor_config:",
"If ``True``, perform astrometry even if astrometry.net files from a previous run are",
"flexible invocation of astrometry.net, see :func:`call_astrometry` \"\"\" base, ext = path.splitext(filename) # All",
"= path.join(tmp_location, 'feder.config') config_contents = SExtractor_config.format(param_file=param_location) with open(config_location, 'w') as f: f.write(config_contents) with",
"level (in ADUs) MAG_ZEROPOINT 0.0 # magnitude zero-point MAG_GAMMA 4.0 # gamma of",
"at which arises saturation SATUR_KEY SATURATE # keyword for saturation level (in ADUs)",
"%s --radius 0.5\" % ra_dec) if overwrite: option_list.append(\"--overwrite\") if wcs_reference_image_center: option_list.append(\"--crpix-center\") options =",
"of emulsion (for photographic scans) GAIN 0.0 # detector gain in e-/ADU GAIN_KEY",
"'X_IMAGE', '--y-column', 'Y_IMAGE', '--sort-column', 'MAG_AUTO', '--sort-ascending' ] solve_field.extend(additional_solve_args) if odds_ratio is not None:",
"arcsec STARNNW_NAME default.nnw # Neural-Network_Weight table filename #------------------------------ Background ----------------------------------- BACK_SIZE 64 #",
"for that case. if verify is not None: if verify: solve_field.append(\"--verify\") solve_field.append(\"%s\" %",
"file it generates, the .solved file, and, if desired, a \".failed\" file for",
"# name of the file containing the filter DEBLEND_NTHRESH 32 # Number of",
"(Y or N)? FILTER_NAME default.conv # name of the file containing the filter",
"# number of pixels in stack MEMORY_BUFSIZE 1024 # number of lines in",
"--radius 0.5\" % ra_dec) if overwrite: option_list.append(\"--overwrite\") if wcs_reference_image_center: option_list.append(\"--crpix-center\") options = \"",
"path, remove, rename import tempfile from textwrap import dedent __all__ = ['call_astrometry', 'add_astrometry']",
"== 0) except subprocess.CalledProcessError as e: logger.debug('Failed with error') failed_details = e.output solved_field",
"built-in ' log_msg += 'source finder' logger.info(log_msg) try: solved_field = (call_astrometry(filename, ra_dec=ra_dec, overwrite=True,",
"except subprocess.CalledProcessError as e: logger.debug('Failed with error') failed_details = e.output solved_field = False",
"add_ons = [additional_args] else: add_ons = additional_args option_list.extend(add_ons) if isinstance(sextractor, str): option_list.append(\"--source-extractor-path \"",
"logger.warning('Adding astrometry failed for %s', filename) raise e logger.log(log_level, solve_field_output) return return_status def",
"object list, matching objects list, but see also `save_wcs` save_wcs : bool, optional",
"not None: solve_field.append('--config') solve_field.append(astrometry_config) # kludge to handle case when path of verify",
"Name of camera; determines the pixel scale used in the solved. Default is",
"astrometry.net's built-in source extractor. It also cleans up after astrometry.net, keeping only the",
"= 0 log_level = logging.DEBUG except subprocess.CalledProcessError as e: return_status = e.returncode solve_field_output",
"number of objects in stack MEMORY_PIXSTACK 300000 # number of pixels in stack",
"work the solution is found as though `verify` had not been specified. ra_dec",
"= e.returncode solve_field_output = 'Output from astrometry.net:\\n' + str(e.output) log_level = logging.WARN logger.warning('Adding",
"to 1 degree. overwrite : bool, optional If ``True``, perform astrometry even if",
"# Clean spurious detections? (Y or N)? CLEAN_PARAM 1.0 # Cleaning efficiency MASK_TYPE",
"buffer #----------------------------- Miscellaneous --------------------------------- VERBOSE_TYPE NORMAL # can be QUIET, NORMAL or FULL",
"not work the solution is found as though `verify` had not been specified.",
"optional ``True`` to use `sextractor`, or a ``str`` with the path to sextractor.",
"2014-11-26 # # modification was to change DETECT_MINAREA and turn of filter convolution",
"or str, optional ``True`` to use `sextractor`, or a ``str`` with the path",
"BACKGROUND_RMS, # MINIBACKGROUND, MINIBACK_RMS, -BACKGROUND, # FILTERED, OBJECTS, -OBJECTS, SEGMENTATION, # or APERTURES",
"overwrite: option_list.append(\"--overwrite\") if wcs_reference_image_center: option_list.append(\"--crpix-center\") options = \" \".join(option_list) solve_field.extend(options.split()) if custom_sextractor_config: tmp_location",
"of lines in buffer #----------------------------- Miscellaneous --------------------------------- VERBOSE_TYPE NORMAL # can be QUIET,",
"and not solved_field: try: f = open(base + '.failed', 'wb') f.write(failed_details) f.close() except",
"fields which it fails to solve. For more flexible invocation of astrometry.net, see",
"headers WRITE_XML N # Write XML file (Y/N)? XML_NAME sex.xml # Filename for",
"Catalog ------------------------------------ PARAMETERS_NAME {param_file} # name of the file containing catalog contents #-------------------------------",
"'.solved') except OSError: pass if note_failure and not solved_field: try: f = open(base",
"'cp16'], optional Name of camera; determines the pixel scale used in the solved.",
"are approximate camera_pixel_scales = { 'celestron': 0.3, 'u9': 0.55, 'cp16': 0.55 } if",
"failed_details = e.output solved_field = False if (not solved_field) and try_builtin_source_finder: log_msg =",
"with the path to sextractor. custom_sextractor_config : bool, optional If ``True``, use a",
"'--sort-column', 'MAG_AUTO', '--sort-ascending' ] solve_field.extend(additional_solve_args) if odds_ratio is not None: solve_field.append('--odds-to-solve') solve_field.append(odds_ratio) if",
"raise e logger.log(log_level, solve_field_output) return return_status def add_astrometry(filename, overwrite=False, ra_dec=None, note_failure=False, save_wcs=False, verify=None,",
"generation of plots (pngs showing object location and more) minimal_output : bool, optional",
"as f: contents = \"\"\" X_IMAGE Y_IMAGE MAG_AUTO FLUX_AUTO \"\"\" f.write(dedent(contents)) additional_solve_args =",
"https://groups.google.com/forum/#!topic/astrometry/AT21x6zVAJo Returns ------- bool ``True`` on success. Notes ----- Tries a couple strategies",
"on {0}'.format(filename)) try: logger.debug('About to call call_astrometry') solved_field = (call_astrometry(filename, sextractor=not no_source_extractor, ra_dec=ra_dec,",
"field center as either decimal or sexagesimal; also limits search radius to 1",
"file astrometry.net generates is kept. ra_dec : list or tuple of float or",
"feder_settings : bool, optional Set True if you want to use plate scale",
"---------------------------- SEEING_FWHM 1.2 # stellar FWHM in arcsec STARNNW_NAME default.nnw # Neural-Network_Weight table",
"configuration file customized for Feder images. feder_settings : bool, optional Set True if",
"filename #------------------------------ Background ----------------------------------- BACK_SIZE 64 # Background mesh: <size> or <width>,<height> BACK_FILTERSIZE",
"log_level = logging.DEBUG except subprocess.CalledProcessError as e: return_status = e.returncode solve_field_output = 'Output",
"check.fits # Filename for the check-image #--------------------- Memory (change with caution!) ------------------------- MEMORY_OBJSTACK",
"mag.arcsec-2 FILTER N # apply filter for detection (Y or N)? FILTER_NAME default.conv",
"<sigmas> or <threshold>,<ZP> in mag.arcsec-2 FILTER N # apply filter for detection (Y",
"= False if (not solved_field) and try_builtin_source_finder: log_msg = 'Astrometry failed using sextractor,",
"float (RA, Dec); also limits search radius to 1 degree. overwrite : bool,",
"IOError as e: logger.error('Unable to save output of astrometry.net %s', e) pass logger.info('END",
"return solved_field SExtractor_config = \"\"\" # Configuration file for SExtractor 2.19.5 based on",
"in arcsec per pixel, values are approximate camera_pixel_scales = { 'celestron': 0.3, 'u9':",
"around astrometry.net solve-field. Parameters ---------- sextractor : bool or str, optional ``True`` to",
"either decimal or sexagesimal; also limits search radius to 1 degree. note_failure :",
"``str`` with the path to sextractor. custom_sextractor_config : bool, optional If ``True``, use",
"to sextractor. custom_sextractor_config : bool, optional If ``True``, use a sexractor configuration file",
"``True`` on success. Notes ----- Tries a couple strategies before giving up: first",
"default.nnw # Neural-Network_Weight table filename #------------------------------ Background ----------------------------------- BACK_SIZE 64 # Background mesh:",
"of str, optional Additional arguments to pass to `solve-field` \"\"\" solve_field = [\"solve-field\"]",
"in pixels PHOT_AUTOPARAMS 2.5, 3.5 # MAG_AUTO parameters: <Kron_fact>,<min_radius> PHOT_PETROPARAMS 2.0, 3.5 #",
"return_status def add_astrometry(filename, overwrite=False, ra_dec=None, note_failure=False, save_wcs=False, verify=None, try_builtin_source_finder=False, custom_sextractor=False, odds_ratio=None, astrometry_config=None, camera='',",
"# keyword for detector gain in e-/ADU PIXEL_SCALE 1.0 # size of pixel",
"can be NONE, BACKGROUND, BACKGROUND_RMS, # MINIBACKGROUND, MINIBACK_RMS, -BACKGROUND, # FILTERED, OBJECTS, -OBJECTS,",
"run are present. wcs_reference_image_center : If ``True``, force the WCS reference point in",
"to change DETECT_MINAREA and turn of filter convolution #-------------------------------- Catalog ------------------------------------ PARAMETERS_NAME {param_file}",
"save_wcs=save_wcs, verify=verify) == 0) except subprocess.CalledProcessError as e: failed_details = e.output solved_field =",
"e: failed_details = e.output solved_field = False if solved_field: logger.info('Adding astrometry succeeded') else:",
"Wrapper around astrometry.net solve-field. Parameters ---------- sextractor : bool or str, optional ``True``",
"as f: f.write(config_contents) with open(param_location, 'w') as f: contents = \"\"\" X_IMAGE Y_IMAGE",
"custom_sextractor_config: tmp_location = tempfile.mkdtemp() param_location = path.join(tmp_location, 'default.param') config_location = path.join(tmp_location, 'feder.config') config_contents",
"logger.debug('About to call call_astrometry') solved_field = (call_astrometry(filename, sextractor=not no_source_extractor, ra_dec=ra_dec, save_wcs=save_wcs, verify=verify, custom_sextractor_config=custom_sextractor,",
"camera: use_feder = False scale = camera_pixel_scales[camera] scale_options = (\"--scale-low {low} --scale-high {high}",
"cleans up after astrometry.net, keeping only the new FITS file it generates, the",
"degree. overwrite : bool, optional If ``True``, perform astrometry even if astrometry.net files",
"ra_dec) if overwrite: option_list.append(\"--overwrite\") if wcs_reference_image_center: option_list.append(\"--crpix-center\") options = \" \".join(option_list) solve_field.extend(options.split()) if",
"WCS info) #------------------------- Star/Galaxy Separation ---------------------------- SEEING_FWHM 1.2 # stellar FWHM in arcsec",
"GAIN 0.0 # detector gain in e-/ADU GAIN_KEY GAIN # keyword for detector",
"is to use `'u9'`. avoid_pyfits : bool Add arguments to solve-field to avoid",
"fails. save_wcs : verify : See :func:`call_astrometry` camera : str, one of ['celestron',",
"(in ADUs) MAG_ZEROPOINT 0.0 # magnitude zero-point MAG_GAMMA 4.0 # gamma of emulsion",
"'--y-column', 'Y_IMAGE', '--sort-column', 'MAG_AUTO', '--sort-ascending' ] solve_field.extend(additional_solve_args) if odds_ratio is not None: solve_field.append('--odds-to-solve')",
"``True`` to suppress astrometry.net generation of plots (pngs showing object location and more)",
"camera_pixel_scales = { 'celestron': 0.3, 'u9': 0.55, 'cp16': 0.55 } if camera: use_feder",
"be NONE, BACKGROUND, BACKGROUND_RMS, # MINIBACKGROUND, MINIBACK_RMS, -BACKGROUND, # FILTERED, OBJECTS, -OBJECTS, SEGMENTATION,",
"and, if desired, a \".failed\" file for fields which it fails to solve.",
"caution!) ------------------------- MEMORY_OBJSTACK 3000 # number of objects in stack MEMORY_PIXSTACK 300000 #",
"more flexible invocation of astrometry.net, see :func:`call_astrometry` \"\"\" base, ext = path.splitext(filename) #",
"is not None: additional_opts = additional_opts.split() additional_opts.extend(solve_field_args) logger.info('BEGIN ADDING ASTROMETRY on {0}'.format(filename)) try:",
"<min_radius> SATUR_LEVEL 50000.0 # level (in ADUs) at which arises saturation SATUR_KEY SATURATE",
"not work for that case. if verify is not None: if verify: solve_field.append(\"--verify\")",
"try: rename(base + '.new', filename) except OSError as e: logger.error(e) return False #",
"e: return_status = e.returncode solve_field_output = 'Output from astrometry.net:\\n' + str(e.output) log_level =",
"import tempfile from textwrap import dedent __all__ = ['call_astrometry', 'add_astrometry'] logger = logging.getLogger(__name__)",
"Neural-Network_Weight table filename #------------------------------ Background ----------------------------------- BACK_SIZE 64 # Background mesh: <size> or",
"fails, astrometry.net's built-in source extractor. It also cleans up after astrometry.net, keeping only",
"to handle case when path of verify file contains a space--split # above",
"file %s', filename) if overwrite and solved_field: logger.info('Overwriting original file with image with",
"\"\"\" base, ext = path.splitext(filename) # All are in arcsec per pixel, values",
"trying built-in ' log_msg += 'source finder' logger.info(log_msg) try: solved_field = (call_astrometry(filename, ra_dec=ra_dec,",
"ADDING ASTROMETRY on {0}'.format(filename)) try: logger.debug('About to call call_astrometry') solved_field = (call_astrometry(filename, sextractor=not",
"HEADER_SUFFIX .head # Filename extension for additional headers WRITE_XML N # Write XML",
"present. wcs_reference_image_center : If ``True``, force the WCS reference point in the image",
"no_plots : bool, optional ``True`` to suppress astrometry.net generation of plots (pngs showing",
"solution is found as though `verify` had not been specified. ra_dec : list",
"# number of lines in buffer #----------------------------- Miscellaneous --------------------------------- VERBOSE_TYPE NORMAL # can",
"Default is to use `'u9'`. avoid_pyfits : bool Add arguments to solve-field to",
"'add_astrometry'] logger = logging.getLogger(__name__) def call_astrometry(filename, sextractor=False, custom_sextractor_config=False, feder_settings=True, no_plots=True, minimal_output=True, save_wcs=False, verify=None,",
"open(param_location, 'w') as f: contents = \"\"\" X_IMAGE Y_IMAGE MAG_AUTO FLUX_AUTO \"\"\" f.write(dedent(contents))",
"verify is not None: if verify: solve_field.append(\"--verify\") solve_field.append(\"%s\" % verify) else: solve_field.append(\"--no-verify\") solve_field.extend([filename])",
"3.5 # MAG_PETRO parameters: <Petrosian_fact>, # <min_radius> SATUR_LEVEL 50000.0 # level (in ADUs)",
"file for fields which it fails to solve. For more flexible invocation of",
": str, one of ['celestron', 'u9', 'cp16'], optional Name of camera; determines the",
"to call call_astrometry') solved_field = (call_astrometry(filename, sextractor=not no_source_extractor, ra_dec=ra_dec, save_wcs=save_wcs, verify=verify, custom_sextractor_config=custom_sextractor, odds_ratio=odds_ratio,",
"other output is suppressed with `minimial_output` verify : str, optional Name of a",
"%s', filename) return solved_field SExtractor_config = \"\"\" # Configuration file for SExtractor 2.19.5",
"up try: remove(base + '.axy') except OSError: pass if solved_field: try: remove(base +",
"of configuration file to use for SExtractor. additional_args : str or list of",
"bool, optional Set True if you want to use plate scale appropriate for",
"e: logger.debug('Failed with error') failed_details = e.output solved_field = False if (not solved_field)",
"the path to sextractor. custom_sextractor_config : bool, optional If ``True``, use a sexractor",
"= \" \".join(option_list) solve_field.extend(options.split()) if custom_sextractor_config: tmp_location = tempfile.mkdtemp() param_location = path.join(tmp_location, 'default.param')",
"[] option_list.append(\"--obj 100\") if feder_settings: option_list.append( \"--scale-low 0.5 --scale-high 0.6 --scale-units arcsecperpix\") if",
"e: logger.error(e) return False # whether we succeeded or failed, clean up try:",
"force the WCS reference point in the image to be the image center.",
": str, optional Name of configuration file to use for SExtractor. additional_args :",
"try: solve_field_output = subprocess.check_output(solve_field, stderr=subprocess.STDOUT) return_status = 0 log_level = logging.DEBUG except subprocess.CalledProcessError",
"``True``, force the WCS reference point in the image to be the image",
"<size> or <width>,<height> BACKPHOTO_TYPE GLOBAL # can be GLOBAL or LOCAL #------------------------------ Check",
"astrometry.net, keeping only the new FITS file it generates, the .solved file, and,",
"Default is to use the default in `solve-field`. astrometry_config : str, optional Name",
"appropriate for Feder Observatory Apogee Alta U9 camera. no_plots : bool, optional ``True``",
"1 degree. note_failure : bool, optional If ``True``, create a file with extension",
"# can be QUIET, NORMAL or FULL HEADER_SUFFIX .head # Filename extension for",
"MAG_PETRO parameters: <Petrosian_fact>, # <min_radius> SATUR_LEVEL 50000.0 # level (in ADUs) at which",
"Image ---------------------------------- CHECKIMAGE_TYPE NONE # can be NONE, BACKGROUND, BACKGROUND_RMS, # MINIBACKGROUND, MINIBACK_RMS,",
"= [ '--source-extractor-config', config_location, '--x-column', 'X_IMAGE', '--y-column', 'Y_IMAGE', '--sort-column', 'MAG_AUTO', '--sort-ascending' ] solve_field.extend(additional_solve_args)",
"and more) minimal_output : bool, optional If ``True``, suppress, as separate files, output",
"False scale = camera_pixel_scales[camera] scale_options = (\"--scale-low {low} --scale-high {high} \" \"--scale-units arcsecperpix\".format(low=0.8*scale,",
"Name of configuration file to use for SExtractor. additional_args : str or list",
"'' if avoid_pyfits: pyfits_options = '--no-remove-lines --uniformize 0' else: pyfits_options = '' additional_opts",
"containing catalog contents #------------------------------- Extraction ---------------------------------- DETECT_TYPE CCD # CCD (linear) or PHOTO",
"try: remove(base + '-indx.xyls') remove(base + '.solved') except OSError: pass if note_failure and",
"additional_args=None): \"\"\" Wrapper around astrometry.net solve-field. Parameters ---------- sextractor : bool or str,",
"= '' additional_opts = ' '.join([scale_options, pyfits_options]) if solve_field_args is not None: additional_opts",
"CHECKIMAGE_NAME check.fits # Filename for the check-image #--------------------- Memory (change with caution!) -------------------------",
"in mag.arcsec-2 FILTER N # apply filter for detection (Y or N)? FILTER_NAME",
"If ``True``, suppress, as separate files, output of: WCS header, RA/Dec object list,",
"if additional_args is not None: if isinstance(additional_args, str): add_ons = [additional_args] else: add_ons",
"['celestron', 'u9', 'cp16'], optional Name of camera; determines the pixel scale used in",
"for deblending CLEAN Y # Clean spurious detections? (Y or N)? CLEAN_PARAM 1.0",
"dedent __all__ = ['call_astrometry', 'add_astrometry'] logger = logging.getLogger(__name__) def call_astrometry(filename, sextractor=False, custom_sextractor_config=False, feder_settings=True,",
"matching objects list, but see also `save_wcs` save_wcs : bool, optional If ``True``,",
"overwrite : bool, optional If ``True``, perform astrometry even if astrometry.net files from",
"image to be the image center. odds_ratio : float, optional The odds ratio",
"sexractor configuration file customized for Feder images. feder_settings : bool, optional Set True",
"remove(base + '.axy') except OSError: pass if solved_field: try: remove(base + '-indx.xyls') remove(base",
"if sextractor fails. save_wcs : verify : See :func:`call_astrometry` camera : str, one",
"is not None: if isinstance(additional_args, str): add_ons = [additional_args] else: add_ons = additional_args",
"that case. if verify is not None: if verify: solve_field.append(\"--verify\") solve_field.append(\"%s\" % verify)",
"mesh: <size> or <width>,<height> BACK_FILTERSIZE 3 # Background filter: <size> or <width>,<height> BACKPHOTO_TYPE",
"with image with astrometry') try: rename(base + '.new', filename) except OSError as e:",
"sextractor. custom_sextractor_config : bool, optional If ``True``, use a sexractor configuration file customized",
": bool, optional If ``True``, suppress, as separate files, output of: WCS header,",
"plots (pngs showing object location and more) minimal_output : bool, optional If ``True``,",
"+ '.failed', 'wb') f.write(failed_details) f.close() except IOError as e: logger.error('Unable to save output",
"you want to use plate scale appropriate for Feder Observatory Apogee Alta U9",
"= 'Output from astrometry.net:\\n' + str(e.output) log_level = logging.WARN logger.warning('Adding astrometry failed for",
"{0}'.format(filename)) try: logger.debug('About to call call_astrometry') solved_field = (call_astrometry(filename, sextractor=not no_source_extractor, ra_dec=ra_dec, save_wcs=save_wcs,",
"`verify` had not been specified. ra_dec : list or tuple of float (RA,",
"values are approximate camera_pixel_scales = { 'celestron': 0.3, 'u9': 0.55, 'cp16': 0.55 }",
"e: logger.error('Unable to save output of astrometry.net %s', e) pass logger.info('END ADDING ASTROMETRY",
"0.0 # magnitude zero-point MAG_GAMMA 4.0 # gamma of emulsion (for photographic scans)",
"emulsion (for photographic scans) GAIN 0.0 # detector gain in e-/ADU GAIN_KEY GAIN",
"logger.info(log_msg) try: solved_field = (call_astrometry(filename, ra_dec=ra_dec, overwrite=True, save_wcs=save_wcs, verify=verify) == 0) except subprocess.CalledProcessError",
"name of the file containing the filter DEBLEND_NTHRESH 32 # Number of deblending",
"of filter convolution #-------------------------------- Catalog ------------------------------------ PARAMETERS_NAME {param_file} # name of the file",
"= path.join(tmp_location, 'default.param') config_location = path.join(tmp_location, 'feder.config') config_contents = SExtractor_config.format(param_file=param_location) with open(config_location, 'w')",
"a first guess for the astrometry fit; if this plate solution does not",
"Minimum contrast parameter for deblending CLEAN Y # Clean spurious detections? (Y or",
"import subprocess from os import path, remove, rename import tempfile from textwrap import",
"the original file. If `False`, the file astrometry.net generates is kept. ra_dec :",
"ra_dec=ra_dec, save_wcs=save_wcs, verify=verify, custom_sextractor_config=custom_sextractor, odds_ratio=odds_ratio, astrometry_config=astrometry_config, feder_settings=use_feder, additional_args=additional_opts) == 0) except subprocess.CalledProcessError as",
"= (call_astrometry(filename, ra_dec=ra_dec, overwrite=True, save_wcs=save_wcs, verify=verify) == 0) except subprocess.CalledProcessError as e: failed_details",
"except OSError: pass if solved_field: try: remove(base + '-indx.xyls') remove(base + '.solved') except",
"# NONE, BLANK or CORRECT #------------------------------ Photometry ----------------------------------- PHOT_APERTURES 10 # MAG_APER aperture",
"not been specified. ra_dec : list or tuple of float (RA, Dec); also",
"of a WCS header to be used as a first guess for the",
"0.5\" % ra_dec) if overwrite: option_list.append(\"--overwrite\") if wcs_reference_image_center: option_list.append(\"--crpix-center\") options = \" \".join(option_list)",
"FILTERED, OBJECTS, -OBJECTS, SEGMENTATION, # or APERTURES CHECKIMAGE_NAME check.fits # Filename for the",
"list or tuple of float or str (RA, Dec) of field center as",
"with open(param_location, 'w') as f: contents = \"\"\" X_IMAGE Y_IMAGE MAG_AUTO FLUX_AUTO \"\"\"",
"use_feder = False scale = camera_pixel_scales[camera] scale_options = (\"--scale-low {low} --scale-high {high} \"",
"verify=None, ra_dec=None, overwrite=False, wcs_reference_image_center=True, odds_ratio=None, astrometry_config=None, additional_args=None): \"\"\" Wrapper around astrometry.net solve-field. Parameters",
"--rdls none --match none\") if not save_wcs: option_list.append(\"--wcs none\") if ra_dec is not",
"ra_dec=ra_dec, overwrite=True, save_wcs=save_wcs, verify=verify) == 0) except subprocess.CalledProcessError as e: failed_details = e.output",
"Background filter: <size> or <width>,<height> BACKPHOTO_TYPE GLOBAL # can be GLOBAL or LOCAL",
"solve_field.extend([filename]) print(' '.join(solve_field)) logger.info(' '.join(solve_field)) try: solve_field_output = subprocess.check_output(solve_field, stderr=subprocess.STDOUT) return_status = 0",
"and try_builtin_source_finder: log_msg = 'Astrometry failed using sextractor, trying built-in ' log_msg +=",
"WCS header even if other output is suppressed with `minimial_output` verify : str,",
"# gamma of emulsion (for photographic scans) GAIN 0.0 # detector gain in",
"no_plots=True, minimal_output=True, save_wcs=False, verify=None, ra_dec=None, overwrite=False, wcs_reference_image_center=True, odds_ratio=None, astrometry_config=None, additional_args=None): \"\"\" Wrapper around",
"SEEING_FWHM 1.2 # stellar FWHM in arcsec STARNNW_NAME default.nnw # Neural-Network_Weight table filename",
"fails. The \"failed\" file contains the error messages genreated by astrometry.net. try_builtin_source_finder :",
"param_location = path.join(tmp_location, 'default.param') config_location = path.join(tmp_location, 'feder.config') config_contents = SExtractor_config.format(param_file=param_location) with open(config_location,",
"\"\"\" Wrapper around astrometry.net solve-field. Parameters ---------- sextractor : bool or str, optional",
"optional Name of camera; determines the pixel scale used in the solved. Default",
"(call_astrometry(filename, sextractor=not no_source_extractor, ra_dec=ra_dec, save_wcs=save_wcs, verify=verify, custom_sextractor_config=custom_sextractor, odds_ratio=odds_ratio, astrometry_config=astrometry_config, feder_settings=use_feder, additional_args=additional_opts) == 0)",
"odds_ratio=odds_ratio, astrometry_config=astrometry_config, feder_settings=use_feder, additional_args=additional_opts) == 0) except subprocess.CalledProcessError as e: logger.debug('Failed with error')",
"Parameters ---------- sextractor : bool or str, optional ``True`` to use `sextractor`, or",
"} if camera: use_feder = False scale = camera_pixel_scales[camera] scale_options = (\"--scale-low {low}",
"use `sextractor`, or a ``str`` with the path to sextractor. custom_sextractor_config : bool,",
"if verify: solve_field.append(\"--verify\") solve_field.append(\"%s\" % verify) else: solve_field.append(\"--no-verify\") solve_field.extend([filename]) print(' '.join(solve_field)) logger.info(' '.join(solve_field))",
"# CCD (linear) or PHOTO (with gamma correction) DETECT_MINAREA 15 # min. #",
"suppressed with `minimial_output` verify : str, optional Name of a WCS header to",
"solve_field.append(astrometry_config) # kludge to handle case when path of verify file contains a",
"up after astrometry.net, keeping only the new FITS file it generates, the .solved",
"are present. wcs_reference_image_center : If ``True``, force the WCS reference point in the",
"CHECKIMAGE_TYPE NONE # can be NONE, BACKGROUND, BACKGROUND_RMS, # MINIBACKGROUND, MINIBACK_RMS, -BACKGROUND, #",
"solved_field = (call_astrometry(filename, ra_dec=ra_dec, overwrite=True, save_wcs=save_wcs, verify=verify) == 0) except subprocess.CalledProcessError as e:",
"None: additional_opts = additional_opts.split() additional_opts.extend(solve_field_args) logger.info('BEGIN ADDING ASTROMETRY on {0}'.format(filename)) try: logger.debug('About to",
"from textwrap import dedent __all__ = ['call_astrometry', 'add_astrometry'] logger = logging.getLogger(__name__) def call_astrometry(filename,",
"to avoid calls to pyfits.BinTableHDU. See https://groups.google.com/forum/#!topic/astrometry/AT21x6zVAJo Returns ------- bool ``True`` on success.",
"Alta U9 camera. no_plots : bool, optional ``True`` to suppress astrometry.net generation of",
"with `minimial_output` verify : str, optional Name of a WCS header to be",
"try_builtin_source_finder : bool If true, try using astrometry.net's built-in source extractor if sextractor",
"approximate camera_pixel_scales = { 'celestron': 0.3, 'u9': 0.55, 'cp16': 0.55 } if camera:",
"subprocess.CalledProcessError as e: return_status = e.returncode solve_field_output = 'Output from astrometry.net:\\n' + str(e.output)",
"verify file contains a space--split # above does not work for that case.",
"%s --dec %s --radius 0.5\" % ra_dec) if overwrite: option_list.append(\"--overwrite\") if wcs_reference_image_center: option_list.append(\"--crpix-center\")",
"remove, rename import tempfile from textwrap import dedent __all__ = ['call_astrometry', 'add_astrometry'] logger",
"of float or str (RA, Dec) of field center as either decimal or",
"optional Set True if you want to use plate scale appropriate for Feder",
"CORRECT #------------------------------ Photometry ----------------------------------- PHOT_APERTURES 10 # MAG_APER aperture diameter(s) in pixels PHOT_AUTOPARAMS",
"X_IMAGE Y_IMAGE MAG_AUTO FLUX_AUTO \"\"\" f.write(dedent(contents)) additional_solve_args = [ '--source-extractor-config', config_location, '--x-column', 'X_IMAGE',",
"U9 camera. no_plots : bool, optional ``True`` to suppress astrometry.net generation of plots",
"# whether we succeeded or failed, clean up try: remove(base + '.axy') except",
"feder_settings=True, no_plots=True, minimal_output=True, save_wcs=False, verify=None, ra_dec=None, overwrite=False, wcs_reference_image_center=True, odds_ratio=None, astrometry_config=None, additional_args=None): \"\"\" Wrapper",
"if astrometry.net fails. The \"failed\" file contains the error messages genreated by astrometry.net.",
"filename) return solved_field SExtractor_config = \"\"\" # Configuration file for SExtractor 2.19.5 based",
"check-image #--------------------- Memory (change with caution!) ------------------------- MEMORY_OBJSTACK 3000 # number of objects",
"Configuration file for SExtractor 2.19.5 based on default by EB 2014-11-26 # #",
"header, RA/Dec object list, matching objects list, but see also `save_wcs` save_wcs :",
"FILTER_NAME default.conv # name of the file containing the filter DEBLEND_NTHRESH 32 #",
"type of detection MASKing: can be one of # NONE, BLANK or CORRECT",
"specified. ra_dec : list or tuple of float (RA, Dec); also limits search",
"tuple of float or str (RA, Dec) of field center as either decimal",
"Check Image ---------------------------------- CHECKIMAGE_TYPE NONE # can be NONE, BACKGROUND, BACKGROUND_RMS, # MINIBACKGROUND,",
"rename(base + '.new', filename) except OSError as e: logger.error(e) return False # whether",
"{ 'celestron': 0.3, 'u9': 0.55, 'cp16': 0.55 } if camera: use_feder = False",
"NONE, BLANK or CORRECT #------------------------------ Photometry ----------------------------------- PHOT_APERTURES 10 # MAG_APER aperture diameter(s)",
"odds_ratio=None, astrometry_config=None, additional_args=None): \"\"\" Wrapper around astrometry.net solve-field. Parameters ---------- sextractor : bool",
"arguments to solve-field to avoid calls to pyfits.BinTableHDU. See https://groups.google.com/forum/#!topic/astrometry/AT21x6zVAJo Returns ------- bool",
"sexagesimal; also limits search radius to 1 degree. note_failure : bool, optional If",
"ADUs) at which arises saturation SATUR_KEY SATURATE # keyword for saturation level (in",
"(for photographic scans) GAIN 0.0 # detector gain in e-/ADU GAIN_KEY GAIN #",
"try_builtin_source_finder: log_msg = 'Astrometry failed using sextractor, trying built-in ' log_msg += 'source",
"case. if verify is not None: if verify: solve_field.append(\"--verify\") solve_field.append(\"%s\" % verify) else:",
"above threshold DETECT_THRESH 1.5 # <sigmas> or <threshold>,<ZP> in mag.arcsec-2 ANALYSIS_THRESH 1.5 #",
"0) except subprocess.CalledProcessError as e: failed_details = e.output solved_field = False if solved_field:",
"the file containing the filter DEBLEND_NTHRESH 32 # Number of deblending sub-thresholds DEBLEND_MINCONT",
"was to change DETECT_MINAREA and turn of filter convolution #-------------------------------- Catalog ------------------------------------ PARAMETERS_NAME",
"point in the image to be the image center. odds_ratio : float, optional",
"of the file containing the filter DEBLEND_NTHRESH 32 # Number of deblending sub-thresholds",
"if that fails, astrometry.net's built-in source extractor. It also cleans up after astrometry.net,",
"True scale_options = '' if avoid_pyfits: pyfits_options = '--no-remove-lines --uniformize 0' else: pyfits_options",
": bool If true, try using astrometry.net's built-in source extractor if sextractor fails.",
"or tuple of float (RA, Dec); also limits search radius to 1 degree.",
"scans) GAIN 0.0 # detector gain in e-/ADU GAIN_KEY GAIN # keyword for",
"------- bool ``True`` on success. Notes ----- Tries a couple strategies before giving",
"MAG_GAMMA 4.0 # gamma of emulsion (for photographic scans) GAIN 0.0 # detector",
"return_status = 0 log_level = logging.DEBUG except subprocess.CalledProcessError as e: return_status = e.returncode",
"\"failed\" if astrometry.net fails. The \"failed\" file contains the error messages genreated by",
"(RA, Dec) of field center as either decimal or sexagesimal; also limits search",
"a previous run are present. wcs_reference_image_center : If ``True``, force the WCS reference",
"# Number of deblending sub-thresholds DEBLEND_MINCONT 0.005 # Minimum contrast parameter for deblending",
"not None: solve_field.append('--odds-to-solve') solve_field.append(odds_ratio) if astrometry_config is not None: solve_field.append('--config') solve_field.append(astrometry_config) # kludge",
"file to use for SExtractor. additional_args : str or list of str, optional",
"also limits search radius to 1 degree. overwrite : bool, optional If ``True``,",
"use for SExtractor. additional_args : str or list of str, optional Additional arguments",
"1 degree. overwrite : bool, optional If ``True``, perform astrometry even if astrometry.net",
"to suppress astrometry.net generation of plots (pngs showing object location and more) minimal_output",
"see :func:`call_astrometry` \"\"\" base, ext = path.splitext(filename) # All are in arcsec per",
"pixel, values are approximate camera_pixel_scales = { 'celestron': 0.3, 'u9': 0.55, 'cp16': 0.55",
"try: f = open(base + '.failed', 'wb') f.write(failed_details) f.close() except IOError as e:",
"lines in buffer #----------------------------- Miscellaneous --------------------------------- VERBOSE_TYPE NORMAL # can be QUIET, NORMAL",
"for %s', filename) return solved_field SExtractor_config = \"\"\" # Configuration file for SExtractor",
"False if (not solved_field) and try_builtin_source_finder: log_msg = 'Astrometry failed using sextractor, trying",
"additional_args option_list.extend(add_ons) if isinstance(sextractor, str): option_list.append(\"--source-extractor-path \" + sextractor) elif sextractor: option_list.append(\"--use-source-extractor\") if",
"DETECT_TYPE CCD # CCD (linear) or PHOTO (with gamma correction) DETECT_MINAREA 15 #",
"used in the solved. Default is to use `'u9'`. avoid_pyfits : bool Add",
"in arcsec STARNNW_NAME default.nnw # Neural-Network_Weight table filename #------------------------------ Background ----------------------------------- BACK_SIZE 64",
"save_wcs=False, verify=None, ra_dec=None, overwrite=False, wcs_reference_image_center=True, odds_ratio=None, astrometry_config=None, additional_args=None): \"\"\" Wrapper around astrometry.net solve-field.",
"the image to be the image center. odds_ratio : float, optional The odds",
"only the new FITS file it generates, the .solved file, and, if desired,",
"not save_wcs: option_list.append(\"--wcs none\") if ra_dec is not None: option_list.append(\"--ra %s --dec %s",
"or <width>,<height> BACKPHOTO_TYPE GLOBAL # can be GLOBAL or LOCAL #------------------------------ Check Image",
"= True scale_options = '' if avoid_pyfits: pyfits_options = '--no-remove-lines --uniformize 0' else:",
"GAIN # keyword for detector gain in e-/ADU PIXEL_SCALE 1.0 # size of",
"use a sexractor configuration file customized for Feder images. feder_settings : bool, optional",
"See https://groups.google.com/forum/#!topic/astrometry/AT21x6zVAJo Returns ------- bool ``True`` on success. Notes ----- Tries a couple",
"the pixel scale used in the solved. Default is to use `'u9'`. avoid_pyfits",
"ra_dec=None, overwrite=False, wcs_reference_image_center=True, odds_ratio=None, astrometry_config=None, additional_args=None): \"\"\" Wrapper around astrometry.net solve-field. Parameters ----------",
"on default by EB 2014-11-26 # # modification was to change DETECT_MINAREA and",
"True if you want to use plate scale appropriate for Feder Observatory Apogee",
"option_list.append(\"--source-extractor-path \" + sextractor) elif sextractor: option_list.append(\"--use-source-extractor\") if no_plots: option_list.append(\"--no-plot\") if minimal_output: option_list.append(\"--corr",
"filename) if overwrite and solved_field: logger.info('Overwriting original file with image with astrometry') try:",
"``True``, perform astrometry even if astrometry.net files from a previous run are present.",
"else: use_feder = True scale_options = '' if avoid_pyfits: pyfits_options = '--no-remove-lines --uniformize",
"or PHOTO (with gamma correction) DETECT_MINAREA 15 # min. # of pixels above",
"of pixels in stack MEMORY_BUFSIZE 1024 # number of lines in buffer #-----------------------------",
"does not work the solution is found as though `verify` had not been",
"3 # Background filter: <size> or <width>,<height> BACKPHOTO_TYPE GLOBAL # can be GLOBAL",
"Star/Galaxy Separation ---------------------------- SEEING_FWHM 1.2 # stellar FWHM in arcsec STARNNW_NAME default.nnw #",
"solved_field = False if (not solved_field) and try_builtin_source_finder: log_msg = 'Astrometry failed using",
"scale)) else: use_feder = True scale_options = '' if avoid_pyfits: pyfits_options = '--no-remove-lines",
"save WCS header even if other output is suppressed with `minimial_output` verify :",
"= tempfile.mkdtemp() param_location = path.join(tmp_location, 'default.param') config_location = path.join(tmp_location, 'feder.config') config_contents = SExtractor_config.format(param_file=param_location)",
"be GLOBAL or LOCAL #------------------------------ Check Image ---------------------------------- CHECKIMAGE_TYPE NONE # can be",
"NORMAL or FULL HEADER_SUFFIX .head # Filename extension for additional headers WRITE_XML N",
"custom_sextractor_config : bool, optional If ``True``, use a sexractor configuration file customized for",
"except IOError as e: logger.error('Unable to save output of astrometry.net %s', e) pass",
"`save_wcs` save_wcs : bool, optional If ``True``, save WCS header even if other",
"additional headers WRITE_XML N # Write XML file (Y/N)? XML_NAME sex.xml # Filename",
"pyfits_options = '--no-remove-lines --uniformize 0' else: pyfits_options = '' additional_opts = ' '.join([scale_options,",
"= additional_opts.split() additional_opts.extend(solve_field_args) logger.info('BEGIN ADDING ASTROMETRY on {0}'.format(filename)) try: logger.debug('About to call call_astrometry')",
"Memory (change with caution!) ------------------------- MEMORY_OBJSTACK 3000 # number of objects in stack",
"stack MEMORY_PIXSTACK 300000 # number of pixels in stack MEMORY_BUFSIZE 1024 # number",
"as a first guess for the astrometry fit; if this plate solution does",
"64 # Background mesh: <size> or <width>,<height> BACK_FILTERSIZE 3 # Background filter: <size>",
"tmp_location = tempfile.mkdtemp() param_location = path.join(tmp_location, 'default.param') config_location = path.join(tmp_location, 'feder.config') config_contents =",
"15 # min. # of pixels above threshold DETECT_THRESH 1.5 # <sigmas> or",
"logger.log(log_level, solve_field_output) return return_status def add_astrometry(filename, overwrite=False, ra_dec=None, note_failure=False, save_wcs=False, verify=None, try_builtin_source_finder=False, custom_sextractor=False,",
"the filter DEBLEND_NTHRESH 32 # Number of deblending sub-thresholds DEBLEND_MINCONT 0.005 # Minimum",
"if note_failure and not solved_field: try: f = open(base + '.failed', 'wb') f.write(failed_details)",
"PIXEL_SCALE 1.0 # size of pixel in arcsec (0=use FITS WCS info) #-------------------------",
"succeeded or failed, clean up try: remove(base + '.axy') except OSError: pass if",
"'--no-remove-lines --uniformize 0' else: pyfits_options = '' additional_opts = ' '.join([scale_options, pyfits_options]) if",
"file customized for Feder images. feder_settings : bool, optional Set True if you",
"--match none\") if not save_wcs: option_list.append(\"--wcs none\") if ra_dec is not None: option_list.append(\"--ra",
"additional_opts = additional_opts.split() additional_opts.extend(solve_field_args) logger.info('BEGIN ADDING ASTROMETRY on {0}'.format(filename)) try: logger.debug('About to call",
": str, optional Name of a WCS header to be used as a",
"for SExtractor 2.19.5 based on default by EB 2014-11-26 # # modification was",
"0.005 # Minimum contrast parameter for deblending CLEAN Y # Clean spurious detections?",
"' log_msg += 'source finder' logger.info(log_msg) try: solved_field = (call_astrometry(filename, ra_dec=ra_dec, overwrite=True, save_wcs=save_wcs,",
"using astrometry.net's built-in source extractor if sextractor fails. save_wcs : verify : See",
"{low} --scale-high {high} \" \"--scale-units arcsecperpix\".format(low=0.8*scale, high=1.2 * scale)) else: use_feder = True",
"subprocess from os import path, remove, rename import tempfile from textwrap import dedent",
"2.5, 3.5 # MAG_AUTO parameters: <Kron_fact>,<min_radius> PHOT_PETROPARAMS 2.0, 3.5 # MAG_PETRO parameters: <Petrosian_fact>,",
"overwrite=False, ra_dec=None, note_failure=False, save_wcs=False, verify=None, try_builtin_source_finder=False, custom_sextractor=False, odds_ratio=None, astrometry_config=None, camera='', avoid_pyfits=False, no_source_extractor=False, solve_field_args=None):",
"to `solve-field` \"\"\" solve_field = [\"solve-field\"] option_list = [] option_list.append(\"--obj 100\") if feder_settings:",
"giving up: first sextractor, then, if that fails, astrometry.net's built-in source extractor. It",
"if ra_dec is not None: option_list.append(\"--ra %s --dec %s --radius 0.5\" % ra_dec)",
"diameter(s) in pixels PHOT_AUTOPARAMS 2.5, 3.5 # MAG_AUTO parameters: <Kron_fact>,<min_radius> PHOT_PETROPARAMS 2.0, 3.5",
"\" + sextractor) elif sextractor: option_list.append(\"--use-source-extractor\") if no_plots: option_list.append(\"--no-plot\") if minimal_output: option_list.append(\"--corr none",
"with astrometry') try: rename(base + '.new', filename) except OSError as e: logger.error(e) return",
"'MAG_AUTO', '--sort-ascending' ] solve_field.extend(additional_solve_args) if odds_ratio is not None: solve_field.append('--odds-to-solve') solve_field.append(odds_ratio) if astrometry_config",
"RA/Dec object list, matching objects list, but see also `save_wcs` save_wcs : bool,",
"save_wcs=False, verify=None, try_builtin_source_finder=False, custom_sextractor=False, odds_ratio=None, astrometry_config=None, camera='', avoid_pyfits=False, no_source_extractor=False, solve_field_args=None): \"\"\"Add WCS headers",
"WCS header to be used as a first guess for the astrometry fit;",
"pixels above threshold DETECT_THRESH 1.5 # <sigmas> or <threshold>,<ZP> in mag.arcsec-2 ANALYSIS_THRESH 1.5",
"for fields which it fails to solve. For more flexible invocation of astrometry.net,",
"N)? CLEAN_PARAM 1.0 # Cleaning efficiency MASK_TYPE CORRECT # type of detection MASKing:",
"EB 2014-11-26 # # modification was to change DETECT_MINAREA and turn of filter",
"FITS file it generates, the .solved file, and, if desired, a \".failed\" file",
"# level (in ADUs) at which arises saturation SATUR_KEY SATURATE # keyword for",
"The \"failed\" file contains the error messages genreated by astrometry.net. try_builtin_source_finder : bool",
"# Neural-Network_Weight table filename #------------------------------ Background ----------------------------------- BACK_SIZE 64 # Background mesh: <size>",
"save_wcs : bool, optional If ``True``, save WCS header even if other output",
"successful solve. Default is to use the default in `solve-field`. astrometry_config : str,",
"or sexagesimal; also limits search radius to 1 degree. note_failure : bool, optional",
"one of # NONE, BLANK or CORRECT #------------------------------ Photometry ----------------------------------- PHOT_APERTURES 10 #",
"tuple of float (RA, Dec); also limits search radius to 1 degree. overwrite",
"pixels in stack MEMORY_BUFSIZE 1024 # number of lines in buffer #----------------------------- Miscellaneous",
"solve-field to avoid calls to pyfits.BinTableHDU. See https://groups.google.com/forum/#!topic/astrometry/AT21x6zVAJo Returns ------- bool ``True`` on",
"couple strategies before giving up: first sextractor, then, if that fails, astrometry.net's built-in",
"--dec %s --radius 0.5\" % ra_dec) if overwrite: option_list.append(\"--overwrite\") if wcs_reference_image_center: option_list.append(\"--crpix-center\") options",
"MASKing: can be one of # NONE, BLANK or CORRECT #------------------------------ Photometry -----------------------------------",
"minimal_output=True, save_wcs=False, verify=None, ra_dec=None, overwrite=False, wcs_reference_image_center=True, odds_ratio=None, astrometry_config=None, additional_args=None): \"\"\" Wrapper around astrometry.net",
"list, matching objects list, but see also `save_wcs` save_wcs : bool, optional If",
"# Minimum contrast parameter for deblending CLEAN Y # Clean spurious detections? (Y",
"with error') failed_details = e.output solved_field = False if (not solved_field) and try_builtin_source_finder:",
"convolution #-------------------------------- Catalog ------------------------------------ PARAMETERS_NAME {param_file} # name of the file containing catalog",
"detector gain in e-/ADU PIXEL_SCALE 1.0 # size of pixel in arcsec (0=use",
"overwrite=True, save_wcs=save_wcs, verify=verify) == 0) except subprocess.CalledProcessError as e: failed_details = e.output solved_field",
"except subprocess.CalledProcessError as e: failed_details = e.output solved_field = False if solved_field: logger.info('Adding",
"\"\"\" solve_field = [\"solve-field\"] option_list = [] option_list.append(\"--obj 100\") if feder_settings: option_list.append( \"--scale-low",
"file contains the error messages genreated by astrometry.net. try_builtin_source_finder : bool If true,",
"output of astrometry.net %s', e) pass logger.info('END ADDING ASTROMETRY for %s', filename) return",
"none --match none\") if not save_wcs: option_list.append(\"--wcs none\") if ra_dec is not None:",
"or APERTURES CHECKIMAGE_NAME check.fits # Filename for the check-image #--------------------- Memory (change with",
"solved_field) and try_builtin_source_finder: log_msg = 'Astrometry failed using sextractor, trying built-in ' log_msg",
"error') failed_details = e.output solved_field = False if (not solved_field) and try_builtin_source_finder: log_msg",
"perform astrometry even if astrometry.net files from a previous run are present. wcs_reference_image_center",
"that fails, astrometry.net's built-in source extractor. It also cleans up after astrometry.net, keeping",
"case when path of verify file contains a space--split # above does not",
"arguments to pass to `solve-field` \"\"\" solve_field = [\"solve-field\"] option_list = [] option_list.append(\"--obj",
"elif sextractor: option_list.append(\"--use-source-extractor\") if no_plots: option_list.append(\"--no-plot\") if minimal_output: option_list.append(\"--corr none --rdls none --match",
"as separate files, output of: WCS header, RA/Dec object list, matching objects list,",
"list, but see also `save_wcs` save_wcs : bool, optional If ``True``, save WCS",
"If ``True``, save WCS header even if other output is suppressed with `minimial_output`",
"CORRECT # type of detection MASKing: can be one of # NONE, BLANK",
"SExtractor. additional_args : str or list of str, optional Additional arguments to pass",
"output is suppressed with `minimial_output` verify : str, optional Name of a WCS",
"object location and more) minimal_output : bool, optional If ``True``, suppress, as separate",
"astrometry.net %s', e) pass logger.info('END ADDING ASTROMETRY for %s', filename) return solved_field SExtractor_config",
"note_failure=False, save_wcs=False, verify=None, try_builtin_source_finder=False, custom_sextractor=False, odds_ratio=None, astrometry_config=None, camera='', avoid_pyfits=False, no_source_extractor=False, solve_field_args=None): \"\"\"Add WCS",
"VERBOSE_TYPE NORMAL # can be QUIET, NORMAL or FULL HEADER_SUFFIX .head # Filename",
"os import path, remove, rename import tempfile from textwrap import dedent __all__ =",
"be QUIET, NORMAL or FULL HEADER_SUFFIX .head # Filename extension for additional headers",
"astrometry_config=None, additional_args=None): \"\"\" Wrapper around astrometry.net solve-field. Parameters ---------- sextractor : bool or",
"<threshold>,<ZP> in mag.arcsec-2 ANALYSIS_THRESH 1.5 # <sigmas> or <threshold>,<ZP> in mag.arcsec-2 FILTER N",
"want to use plate scale appropriate for Feder Observatory Apogee Alta U9 camera.",
"default by EB 2014-11-26 # # modification was to change DETECT_MINAREA and turn",
"sextractor) elif sextractor: option_list.append(\"--use-source-extractor\") if no_plots: option_list.append(\"--no-plot\") if minimal_output: option_list.append(\"--corr none --rdls none",
"1024 # number of lines in buffer #----------------------------- Miscellaneous --------------------------------- VERBOSE_TYPE NORMAL #",
"if solve_field_args is not None: additional_opts = additional_opts.split() additional_opts.extend(solve_field_args) logger.info('BEGIN ADDING ASTROMETRY on",
"of float (RA, Dec); also limits search radius to 1 degree. overwrite :",
"invocation of astrometry.net, see :func:`call_astrometry` \"\"\" base, ext = path.splitext(filename) # All are",
"correction) DETECT_MINAREA 15 # min. # of pixels above threshold DETECT_THRESH 1.5 #",
"keyword for saturation level (in ADUs) MAG_ZEROPOINT 0.0 # magnitude zero-point MAG_GAMMA 4.0",
"keeping only the new FITS file it generates, the .solved file, and, if",
"astrometry_config=astrometry_config, feder_settings=use_feder, additional_args=additional_opts) == 0) except subprocess.CalledProcessError as e: logger.debug('Failed with error') failed_details",
"= logging.WARN logger.warning('Adding astrometry failed for %s', filename) raise e logger.log(log_level, solve_field_output) return",
"import path, remove, rename import tempfile from textwrap import dedent __all__ = ['call_astrometry',",
"MAG_AUTO FLUX_AUTO \"\"\" f.write(dedent(contents)) additional_solve_args = [ '--source-extractor-config', config_location, '--x-column', 'X_IMAGE', '--y-column', 'Y_IMAGE',",
"10 # MAG_APER aperture diameter(s) in pixels PHOT_AUTOPARAMS 2.5, 3.5 # MAG_AUTO parameters:",
"for the astrometry fit; if this plate solution does not work the solution",
"bool, optional If ``True``, perform astrometry even if astrometry.net files from a previous",
"\"failed\" file contains the error messages genreated by astrometry.net. try_builtin_source_finder : bool If",
"solved_field: try: remove(base + '-indx.xyls') remove(base + '.solved') except OSError: pass if note_failure",
"f.close() except IOError as e: logger.error('Unable to save output of astrometry.net %s', e)",
"logger.error('Unable to save output of astrometry.net %s', e) pass logger.info('END ADDING ASTROMETRY for",
"# Background filter: <size> or <width>,<height> BACKPHOTO_TYPE GLOBAL # can be GLOBAL or",
"no_plots: option_list.append(\"--no-plot\") if minimal_output: option_list.append(\"--corr none --rdls none --match none\") if not save_wcs:",
"MEMORY_BUFSIZE 1024 # number of lines in buffer #----------------------------- Miscellaneous --------------------------------- VERBOSE_TYPE NORMAL",
"try: logger.debug('About to call call_astrometry') solved_field = (call_astrometry(filename, sextractor=not no_source_extractor, ra_dec=ra_dec, save_wcs=save_wcs, verify=verify,",
"keyword for detector gain in e-/ADU PIXEL_SCALE 1.0 # size of pixel in",
"option_list = [] option_list.append(\"--obj 100\") if feder_settings: option_list.append( \"--scale-low 0.5 --scale-high 0.6 --scale-units",
"it generates, the .solved file, and, if desired, a \".failed\" file for fields",
"default in `solve-field`. astrometry_config : str, optional Name of configuration file to use",
"'source finder' logger.info(log_msg) try: solved_field = (call_astrometry(filename, ra_dec=ra_dec, overwrite=True, save_wcs=save_wcs, verify=verify) == 0)",
"{param_file} # name of the file containing catalog contents #------------------------------- Extraction ---------------------------------- DETECT_TYPE",
"are in arcsec per pixel, values are approximate camera_pixel_scales = { 'celestron': 0.3,",
"avoid_pyfits : bool Add arguments to solve-field to avoid calls to pyfits.BinTableHDU. See",
"no_source_extractor, ra_dec=ra_dec, save_wcs=save_wcs, verify=verify, custom_sextractor_config=custom_sextractor, odds_ratio=odds_ratio, astrometry_config=astrometry_config, feder_settings=use_feder, additional_args=additional_opts) == 0) except subprocess.CalledProcessError",
"odds ratio to use for a successful solve. Default is to use the",
"if isinstance(sextractor, str): option_list.append(\"--source-extractor-path \" + sextractor) elif sextractor: option_list.append(\"--use-source-extractor\") if no_plots: option_list.append(\"--no-plot\")",
"for %s', filename) raise e logger.log(log_level, solve_field_output) return return_status def add_astrometry(filename, overwrite=False, ra_dec=None,",
"\" \".join(option_list) solve_field.extend(options.split()) if custom_sextractor_config: tmp_location = tempfile.mkdtemp() param_location = path.join(tmp_location, 'default.param') config_location",
"by astrometry.net. try_builtin_source_finder : bool If true, try using astrometry.net's built-in source extractor",
"as e: failed_details = e.output solved_field = False if solved_field: logger.info('Adding astrometry succeeded')",
"gain in e-/ADU GAIN_KEY GAIN # keyword for detector gain in e-/ADU PIXEL_SCALE",
"except subprocess.CalledProcessError as e: return_status = e.returncode solve_field_output = 'Output from astrometry.net:\\n' +",
"option_list.append(\"--no-plot\") if minimal_output: option_list.append(\"--corr none --rdls none --match none\") if not save_wcs: option_list.append(\"--wcs",
"also limits search radius to 1 degree. note_failure : bool, optional If ``True``,",
": bool, optional If ``True``, save WCS header even if other output is",
"= SExtractor_config.format(param_file=param_location) with open(config_location, 'w') as f: f.write(config_contents) with open(param_location, 'w') as f:",
"save_wcs=save_wcs, verify=verify, custom_sextractor_config=custom_sextractor, odds_ratio=odds_ratio, astrometry_config=astrometry_config, feder_settings=use_feder, additional_args=additional_opts) == 0) except subprocess.CalledProcessError as e:",
"save_wcs: option_list.append(\"--wcs none\") if ra_dec is not None: option_list.append(\"--ra %s --dec %s --radius",
": See :func:`call_astrometry` camera : str, one of ['celestron', 'u9', 'cp16'], optional Name",
"# All are in arcsec per pixel, values are approximate camera_pixel_scales = {",
"%s', filename) raise e logger.log(log_level, solve_field_output) return return_status def add_astrometry(filename, overwrite=False, ra_dec=None, note_failure=False,",
"(in ADUs) at which arises saturation SATUR_KEY SATURATE # keyword for saturation level",
"gamma correction) DETECT_MINAREA 15 # min. # of pixels above threshold DETECT_THRESH 1.5",
"high=1.2 * scale)) else: use_feder = True scale_options = '' if avoid_pyfits: pyfits_options",
"not None: if isinstance(additional_args, str): add_ons = [additional_args] else: add_ons = additional_args option_list.extend(add_ons)",
"suppress, as separate files, output of: WCS header, RA/Dec object list, matching objects",
"astrometry.net files from a previous run are present. wcs_reference_image_center : If ``True``, force",
".solved file, and, if desired, a \".failed\" file for fields which it fails",
"logging.WARN logger.warning('Adding astrometry failed for %s', filename) raise e logger.log(log_level, solve_field_output) return return_status",
"+ '.new', filename) except OSError as e: logger.error(e) return False # whether we",
"PHOTO (with gamma correction) DETECT_MINAREA 15 # min. # of pixels above threshold",
"-OBJECTS, SEGMENTATION, # or APERTURES CHECKIMAGE_NAME check.fits # Filename for the check-image #---------------------",
"of verify file contains a space--split # above does not work for that",
"option_list.extend(add_ons) if isinstance(sextractor, str): option_list.append(\"--source-extractor-path \" + sextractor) elif sextractor: option_list.append(\"--use-source-extractor\") if no_plots:",
"been specified. ra_dec : list or tuple of float (RA, Dec); also limits",
"a successful solve. Default is to use the default in `solve-field`. astrometry_config :",
"file with extension \"failed\" if astrometry.net fails. The \"failed\" file contains the error",
"to FITS file using astrometry.net Parameters ---------- overwrite : bool, optional Set ``True``",
"the image center. odds_ratio : float, optional The odds ratio to use for",
"of astrometry.net, see :func:`call_astrometry` \"\"\" base, ext = path.splitext(filename) # All are in",
"log_msg = 'Astrometry failed using sextractor, trying built-in ' log_msg += 'source finder'",
"bool or str, optional ``True`` to use `sextractor`, or a ``str`` with the",
"ratio to use for a successful solve. Default is to use the default",
"e-/ADU PIXEL_SCALE 1.0 # size of pixel in arcsec (0=use FITS WCS info)",
"'.join(solve_field)) logger.info(' '.join(solve_field)) try: solve_field_output = subprocess.check_output(solve_field, stderr=subprocess.STDOUT) return_status = 0 log_level =",
"path.splitext(filename) # All are in arcsec per pixel, values are approximate camera_pixel_scales =",
"a ``str`` with the path to sextractor. custom_sextractor_config : bool, optional If ``True``,",
"parameters: <Petrosian_fact>, # <min_radius> SATUR_LEVEL 50000.0 # level (in ADUs) at which arises",
"sextractor, trying built-in ' log_msg += 'source finder' logger.info(log_msg) try: solved_field = (call_astrometry(filename,",
"feder_settings: option_list.append( \"--scale-low 0.5 --scale-high 0.6 --scale-units arcsecperpix\") if additional_args is not None:",
"solved_field = False if solved_field: logger.info('Adding astrometry succeeded') else: logger.warning('Adding astrometry failed for",
"generates, the .solved file, and, if desired, a \".failed\" file for fields which",
"custom_sextractor=False, odds_ratio=None, astrometry_config=None, camera='', avoid_pyfits=False, no_source_extractor=False, solve_field_args=None): \"\"\"Add WCS headers to FITS file",
"MAG_ZEROPOINT 0.0 # magnitude zero-point MAG_GAMMA 4.0 # gamma of emulsion (for photographic",
"e.returncode solve_field_output = 'Output from astrometry.net:\\n' + str(e.output) log_level = logging.WARN logger.warning('Adding astrometry",
"DETECT_MINAREA and turn of filter convolution #-------------------------------- Catalog ------------------------------------ PARAMETERS_NAME {param_file} # name",
"avoid_pyfits: pyfits_options = '--no-remove-lines --uniformize 0' else: pyfits_options = '' additional_opts = '",
"clean up try: remove(base + '.axy') except OSError: pass if solved_field: try: remove(base",
"optional ``True`` to suppress astrometry.net generation of plots (pngs showing object location and",
"NONE, BACKGROUND, BACKGROUND_RMS, # MINIBACKGROUND, MINIBACK_RMS, -BACKGROUND, # FILTERED, OBJECTS, -OBJECTS, SEGMENTATION, #",
"OSError as e: logger.error(e) return False # whether we succeeded or failed, clean",
"stack MEMORY_BUFSIZE 1024 # number of lines in buffer #----------------------------- Miscellaneous --------------------------------- VERBOSE_TYPE",
"import dedent __all__ = ['call_astrometry', 'add_astrometry'] logger = logging.getLogger(__name__) def call_astrometry(filename, sextractor=False, custom_sextractor_config=False,",
"containing the filter DEBLEND_NTHRESH 32 # Number of deblending sub-thresholds DEBLEND_MINCONT 0.005 #",
"source extractor if sextractor fails. save_wcs : verify : See :func:`call_astrometry` camera :",
"Y # Clean spurious detections? (Y or N)? CLEAN_PARAM 1.0 # Cleaning efficiency",
"for detector gain in e-/ADU PIXEL_SCALE 1.0 # size of pixel in arcsec",
"photographic scans) GAIN 0.0 # detector gain in e-/ADU GAIN_KEY GAIN # keyword",
"solve_field.append(\"%s\" % verify) else: solve_field.append(\"--no-verify\") solve_field.extend([filename]) print(' '.join(solve_field)) logger.info(' '.join(solve_field)) try: solve_field_output =",
".head # Filename extension for additional headers WRITE_XML N # Write XML file",
"def add_astrometry(filename, overwrite=False, ra_dec=None, note_failure=False, save_wcs=False, verify=None, try_builtin_source_finder=False, custom_sextractor=False, odds_ratio=None, astrometry_config=None, camera='', avoid_pyfits=False,",
"file, and, if desired, a \".failed\" file for fields which it fails to",
"extractor if sextractor fails. save_wcs : verify : See :func:`call_astrometry` camera : str,",
"pyfits_options = '' additional_opts = ' '.join([scale_options, pyfits_options]) if solve_field_args is not None:",
"threshold DETECT_THRESH 1.5 # <sigmas> or <threshold>,<ZP> in mag.arcsec-2 ANALYSIS_THRESH 1.5 # <sigmas>",
"camera. no_plots : bool, optional ``True`` to suppress astrometry.net generation of plots (pngs",
"'u9': 0.55, 'cp16': 0.55 } if camera: use_feder = False scale = camera_pixel_scales[camera]",
"verify : See :func:`call_astrometry` camera : str, one of ['celestron', 'u9', 'cp16'], optional",
"filename) except OSError as e: logger.error(e) return False # whether we succeeded or",
"be one of # NONE, BLANK or CORRECT #------------------------------ Photometry ----------------------------------- PHOT_APERTURES 10",
"False # whether we succeeded or failed, clean up try: remove(base + '.axy')",
"If ``True``, force the WCS reference point in the image to be the",
"kept. ra_dec : list or tuple of float or str (RA, Dec) of",
"and solved_field: logger.info('Overwriting original file with image with astrometry') try: rename(base + '.new',",
"filter: <size> or <width>,<height> BACKPHOTO_TYPE GLOBAL # can be GLOBAL or LOCAL #------------------------------",
"'default.param') config_location = path.join(tmp_location, 'feder.config') config_contents = SExtractor_config.format(param_file=param_location) with open(config_location, 'w') as f:",
"return_status = e.returncode solve_field_output = 'Output from astrometry.net:\\n' + str(e.output) log_level = logging.WARN",
"for a successful solve. Default is to use the default in `solve-field`. astrometry_config",
"parameters: <Kron_fact>,<min_radius> PHOT_PETROPARAMS 2.0, 3.5 # MAG_PETRO parameters: <Petrosian_fact>, # <min_radius> SATUR_LEVEL 50000.0",
"Dec) of field center as either decimal or sexagesimal; also limits search radius",
"or tuple of float or str (RA, Dec) of field center as either",
"1.5 # <sigmas> or <threshold>,<ZP> in mag.arcsec-2 ANALYSIS_THRESH 1.5 # <sigmas> or <threshold>,<ZP>",
"if astrometry.net files from a previous run are present. wcs_reference_image_center : If ``True``,",
"= False if solved_field: logger.info('Adding astrometry succeeded') else: logger.warning('Adding astrometry failed for file",
"'wb') f.write(failed_details) f.close() except IOError as e: logger.error('Unable to save output of astrometry.net",
"decimal or sexagesimal; also limits search radius to 1 degree. note_failure : bool,",
"50000.0 # level (in ADUs) at which arises saturation SATUR_KEY SATURATE # keyword",
"detection (Y or N)? FILTER_NAME default.conv # name of the file containing the",
"= logging.DEBUG except subprocess.CalledProcessError as e: return_status = e.returncode solve_field_output = 'Output from",
"MEMORY_OBJSTACK 3000 # number of objects in stack MEMORY_PIXSTACK 300000 # number of",
"SExtractor 2.19.5 based on default by EB 2014-11-26 # # modification was to",
"If true, try using astrometry.net's built-in source extractor if sextractor fails. save_wcs :",
"solved_field: logger.info('Adding astrometry succeeded') else: logger.warning('Adding astrometry failed for file %s', filename) if",
"if (not solved_field) and try_builtin_source_finder: log_msg = 'Astrometry failed using sextractor, trying built-in",
"optional If ``True``, use a sexractor configuration file customized for Feder images. feder_settings",
"# Configuration file for SExtractor 2.19.5 based on default by EB 2014-11-26 #",
"Tries a couple strategies before giving up: first sextractor, then, if that fails,",
"MAG_APER aperture diameter(s) in pixels PHOT_AUTOPARAMS 2.5, 3.5 # MAG_AUTO parameters: <Kron_fact>,<min_radius> PHOT_PETROPARAMS",
"pixel scale used in the solved. Default is to use `'u9'`. avoid_pyfits :",
"to be used as a first guess for the astrometry fit; if this",
"to use `'u9'`. avoid_pyfits : bool Add arguments to solve-field to avoid calls",
"All are in arcsec per pixel, values are approximate camera_pixel_scales = { 'celestron':",
"filter for detection (Y or N)? FILTER_NAME default.conv # name of the file",
"(\"--scale-low {low} --scale-high {high} \" \"--scale-units arcsecperpix\".format(low=0.8*scale, high=1.2 * scale)) else: use_feder =",
"to pyfits.BinTableHDU. See https://groups.google.com/forum/#!topic/astrometry/AT21x6zVAJo Returns ------- bool ``True`` on success. Notes ----- Tries",
"DETECT_THRESH 1.5 # <sigmas> or <threshold>,<ZP> in mag.arcsec-2 ANALYSIS_THRESH 1.5 # <sigmas> or",
"# Filename for the check-image #--------------------- Memory (change with caution!) ------------------------- MEMORY_OBJSTACK 3000",
"'.axy') except OSError: pass if solved_field: try: remove(base + '-indx.xyls') remove(base + '.solved')",
"#------------------------------ Background ----------------------------------- BACK_SIZE 64 # Background mesh: <size> or <width>,<height> BACK_FILTERSIZE 3",
"strategies before giving up: first sextractor, then, if that fails, astrometry.net's built-in source",
"'.join([scale_options, pyfits_options]) if solve_field_args is not None: additional_opts = additional_opts.split() additional_opts.extend(solve_field_args) logger.info('BEGIN ADDING",
"header even if other output is suppressed with `minimial_output` verify : str, optional",
"#--------------------- Memory (change with caution!) ------------------------- MEMORY_OBJSTACK 3000 # number of objects in",
"when path of verify file contains a space--split # above does not work",
"fit; if this plate solution does not work the solution is found as",
": bool Add arguments to solve-field to avoid calls to pyfits.BinTableHDU. See https://groups.google.com/forum/#!topic/astrometry/AT21x6zVAJo",
"For more flexible invocation of astrometry.net, see :func:`call_astrometry` \"\"\" base, ext = path.splitext(filename)",
"Y_IMAGE MAG_AUTO FLUX_AUTO \"\"\" f.write(dedent(contents)) additional_solve_args = [ '--source-extractor-config', config_location, '--x-column', 'X_IMAGE', '--y-column',",
"for SExtractor. additional_args : str or list of str, optional Additional arguments to",
"remove(base + '-indx.xyls') remove(base + '.solved') except OSError: pass if note_failure and not",
"1.5 # <sigmas> or <threshold>,<ZP> in mag.arcsec-2 FILTER N # apply filter for",
"pixels PHOT_AUTOPARAMS 2.5, 3.5 # MAG_AUTO parameters: <Kron_fact>,<min_radius> PHOT_PETROPARAMS 2.0, 3.5 # MAG_PETRO",
"additional_solve_args = [ '--source-extractor-config', config_location, '--x-column', 'X_IMAGE', '--y-column', 'Y_IMAGE', '--sort-column', 'MAG_AUTO', '--sort-ascending' ]",
"camera : str, one of ['celestron', 'u9', 'cp16'], optional Name of camera; determines",
"None: option_list.append(\"--ra %s --dec %s --radius 0.5\" % ra_dec) if overwrite: option_list.append(\"--overwrite\") if",
"0.0 # detector gain in e-/ADU GAIN_KEY GAIN # keyword for detector gain",
"minimal_output: option_list.append(\"--corr none --rdls none --match none\") if not save_wcs: option_list.append(\"--wcs none\") if",
"``True``, suppress, as separate files, output of: WCS header, RA/Dec object list, matching",
"else: add_ons = additional_args option_list.extend(add_ons) if isinstance(sextractor, str): option_list.append(\"--source-extractor-path \" + sextractor) elif",
"N)? FILTER_NAME default.conv # name of the file containing the filter DEBLEND_NTHRESH 32",
"the error messages genreated by astrometry.net. try_builtin_source_finder : bool If true, try using",
"configuration file to use for SExtractor. additional_args : str or list of str,",
"optional If ``True``, perform astrometry even if astrometry.net files from a previous run",
"0.3, 'u9': 0.55, 'cp16': 0.55 } if camera: use_feder = False scale =",
"'celestron': 0.3, 'u9': 0.55, 'cp16': 0.55 } if camera: use_feder = False scale",
"sextractor fails. save_wcs : verify : See :func:`call_astrometry` camera : str, one of",
"logger.info('Adding astrometry succeeded') else: logger.warning('Adding astrometry failed for file %s', filename) if overwrite",
"a sexractor configuration file customized for Feder images. feder_settings : bool, optional Set",
"OSError: pass if solved_field: try: remove(base + '-indx.xyls') remove(base + '.solved') except OSError:",
"sub-thresholds DEBLEND_MINCONT 0.005 # Minimum contrast parameter for deblending CLEAN Y # Clean",
"logger.info('END ADDING ASTROMETRY for %s', filename) return solved_field SExtractor_config = \"\"\" # Configuration",
"first guess for the astrometry fit; if this plate solution does not work",
"if wcs_reference_image_center: option_list.append(\"--crpix-center\") options = \" \".join(option_list) solve_field.extend(options.split()) if custom_sextractor_config: tmp_location = tempfile.mkdtemp()",
"astrometry succeeded') else: logger.warning('Adding astrometry failed for file %s', filename) if overwrite and",
"Notes ----- Tries a couple strategies before giving up: first sextractor, then, if",
"customized for Feder images. feder_settings : bool, optional Set True if you want",
"e) pass logger.info('END ADDING ASTROMETRY for %s', filename) return solved_field SExtractor_config = \"\"\"",
"use `'u9'`. avoid_pyfits : bool Add arguments to solve-field to avoid calls to",
"is not None: solve_field.append('--odds-to-solve') solve_field.append(odds_ratio) if astrometry_config is not None: solve_field.append('--config') solve_field.append(astrometry_config) #",
"if this plate solution does not work the solution is found as though",
"path of verify file contains a space--split # above does not work for",
"failed, clean up try: remove(base + '.axy') except OSError: pass if solved_field: try:",
"to use for SExtractor. additional_args : str or list of str, optional Additional",
"`False`, the file astrometry.net generates is kept. ra_dec : list or tuple of",
"astrometry.net. try_builtin_source_finder : bool If true, try using astrometry.net's built-in source extractor if",
"bool, optional Set ``True`` to overwrite the original file. If `False`, the file",
"solve_field.append(\"--no-verify\") solve_field.extend([filename]) print(' '.join(solve_field)) logger.info(' '.join(solve_field)) try: solve_field_output = subprocess.check_output(solve_field, stderr=subprocess.STDOUT) return_status =",
"%s', e) pass logger.info('END ADDING ASTROMETRY for %s', filename) return solved_field SExtractor_config =",
"See :func:`call_astrometry` camera : str, one of ['celestron', 'u9', 'cp16'], optional Name of",
"efficiency MASK_TYPE CORRECT # type of detection MASKing: can be one of #",
"solve_field_args=None): \"\"\"Add WCS headers to FITS file using astrometry.net Parameters ---------- overwrite :",
"PARAMETERS_NAME {param_file} # name of the file containing catalog contents #------------------------------- Extraction ----------------------------------",
"--scale-high 0.6 --scale-units arcsecperpix\") if additional_args is not None: if isinstance(additional_args, str): add_ons",
"\"--scale-low 0.5 --scale-high 0.6 --scale-units arcsecperpix\") if additional_args is not None: if isinstance(additional_args,",
"note_failure : bool, optional If ``True``, create a file with extension \"failed\" if",
"is found as though `verify` had not been specified. ra_dec : list or",
"``True`` to use `sextractor`, or a ``str`` with the path to sextractor. custom_sextractor_config",
"+ '.axy') except OSError: pass if solved_field: try: remove(base + '-indx.xyls') remove(base +",
"`solve-field`. astrometry_config : str, optional Name of configuration file to use for SExtractor.",
"logger.info('Overwriting original file with image with astrometry') try: rename(base + '.new', filename) except",
"PHOT_PETROPARAMS 2.0, 3.5 # MAG_PETRO parameters: <Petrosian_fact>, # <min_radius> SATUR_LEVEL 50000.0 # level",
"try_builtin_source_finder=False, custom_sextractor=False, odds_ratio=None, astrometry_config=None, camera='', avoid_pyfits=False, no_source_extractor=False, solve_field_args=None): \"\"\"Add WCS headers to FITS",
"or FULL HEADER_SUFFIX .head # Filename extension for additional headers WRITE_XML N #",
"list of str, optional Additional arguments to pass to `solve-field` \"\"\" solve_field =",
"for additional headers WRITE_XML N # Write XML file (Y/N)? XML_NAME sex.xml #",
"= (\"--scale-low {low} --scale-high {high} \" \"--scale-units arcsecperpix\".format(low=0.8*scale, high=1.2 * scale)) else: use_feder",
"from a previous run are present. wcs_reference_image_center : If ``True``, force the WCS",
"the WCS reference point in the image to be the image center. odds_ratio",
"degree. note_failure : bool, optional If ``True``, create a file with extension \"failed\"",
"= e.output solved_field = False if (not solved_field) and try_builtin_source_finder: log_msg = 'Astrometry",
"of field center as either decimal or sexagesimal; also limits search radius to",
"<size> or <width>,<height> BACK_FILTERSIZE 3 # Background filter: <size> or <width>,<height> BACKPHOTO_TYPE GLOBAL",
"e.output solved_field = False if (not solved_field) and try_builtin_source_finder: log_msg = 'Astrometry failed",
"NONE # can be NONE, BACKGROUND, BACKGROUND_RMS, # MINIBACKGROUND, MINIBACK_RMS, -BACKGROUND, # FILTERED,",
"in the solved. Default is to use `'u9'`. avoid_pyfits : bool Add arguments",
"suppress astrometry.net generation of plots (pngs showing object location and more) minimal_output :",
"astrometry_config : str, optional Name of configuration file to use for SExtractor. additional_args",
"turn of filter convolution #-------------------------------- Catalog ------------------------------------ PARAMETERS_NAME {param_file} # name of the",
"Set ``True`` to overwrite the original file. If `False`, the file astrometry.net generates",
"= ['call_astrometry', 'add_astrometry'] logger = logging.getLogger(__name__) def call_astrometry(filename, sextractor=False, custom_sextractor_config=False, feder_settings=True, no_plots=True, minimal_output=True,",
"avoid_pyfits=False, no_source_extractor=False, solve_field_args=None): \"\"\"Add WCS headers to FITS file using astrometry.net Parameters ----------",
"# can be NONE, BACKGROUND, BACKGROUND_RMS, # MINIBACKGROUND, MINIBACK_RMS, -BACKGROUND, # FILTERED, OBJECTS,",
"even if astrometry.net files from a previous run are present. wcs_reference_image_center : If",
"verify=verify) == 0) except subprocess.CalledProcessError as e: failed_details = e.output solved_field = False",
"none\") if not save_wcs: option_list.append(\"--wcs none\") if ra_dec is not None: option_list.append(\"--ra %s",
"option_list.append(\"--wcs none\") if ra_dec is not None: option_list.append(\"--ra %s --dec %s --radius 0.5\"",
"additional_opts = ' '.join([scale_options, pyfits_options]) if solve_field_args is not None: additional_opts = additional_opts.split()",
"else: logger.warning('Adding astrometry failed for file %s', filename) if overwrite and solved_field: logger.info('Overwriting",
"f: contents = \"\"\" X_IMAGE Y_IMAGE MAG_AUTO FLUX_AUTO \"\"\" f.write(dedent(contents)) additional_solve_args = [",
"Name of a WCS header to be used as a first guess for",
"plate scale appropriate for Feder Observatory Apogee Alta U9 camera. no_plots : bool,",
"scale appropriate for Feder Observatory Apogee Alta U9 camera. no_plots : bool, optional",
": verify : See :func:`call_astrometry` camera : str, one of ['celestron', 'u9', 'cp16'],",
"3.5 # MAG_AUTO parameters: <Kron_fact>,<min_radius> PHOT_PETROPARAMS 2.0, 3.5 # MAG_PETRO parameters: <Petrosian_fact>, #",
"\" \"--scale-units arcsecperpix\".format(low=0.8*scale, high=1.2 * scale)) else: use_feder = True scale_options = ''",
"extractor. It also cleans up after astrometry.net, keeping only the new FITS file",
"= False scale = camera_pixel_scales[camera] scale_options = (\"--scale-low {low} --scale-high {high} \" \"--scale-units",
"str, optional Name of a WCS header to be used as a first",
"pyfits.BinTableHDU. See https://groups.google.com/forum/#!topic/astrometry/AT21x6zVAJo Returns ------- bool ``True`` on success. Notes ----- Tries a",
"logger = logging.getLogger(__name__) def call_astrometry(filename, sextractor=False, custom_sextractor_config=False, feder_settings=True, no_plots=True, minimal_output=True, save_wcs=False, verify=None, ra_dec=None,",
"extension \"failed\" if astrometry.net fails. The \"failed\" file contains the error messages genreated",
"logging.getLogger(__name__) def call_astrometry(filename, sextractor=False, custom_sextractor_config=False, feder_settings=True, no_plots=True, minimal_output=True, save_wcs=False, verify=None, ra_dec=None, overwrite=False, wcs_reference_image_center=True,",
"can be one of # NONE, BLANK or CORRECT #------------------------------ Photometry ----------------------------------- PHOT_APERTURES",
"level (in ADUs) at which arises saturation SATUR_KEY SATURATE # keyword for saturation",
"Add arguments to solve-field to avoid calls to pyfits.BinTableHDU. See https://groups.google.com/forum/#!topic/astrometry/AT21x6zVAJo Returns -------",
"#----------------------------- Miscellaneous --------------------------------- VERBOSE_TYPE NORMAL # can be QUIET, NORMAL or FULL HEADER_SUFFIX",
"<sigmas> or <threshold>,<ZP> in mag.arcsec-2 ANALYSIS_THRESH 1.5 # <sigmas> or <threshold>,<ZP> in mag.arcsec-2",
"for detection (Y or N)? FILTER_NAME default.conv # name of the file containing",
"with extension \"failed\" if astrometry.net fails. The \"failed\" file contains the error messages",
"optional Name of a WCS header to be used as a first guess",
"as e: logger.error('Unable to save output of astrometry.net %s', e) pass logger.info('END ADDING",
"catalog contents #------------------------------- Extraction ---------------------------------- DETECT_TYPE CCD # CCD (linear) or PHOTO (with",
"built-in source extractor. It also cleans up after astrometry.net, keeping only the new",
"wcs_reference_image_center : If ``True``, force the WCS reference point in the image to",
"#-------------------------------- Catalog ------------------------------------ PARAMETERS_NAME {param_file} # name of the file containing catalog contents",
"genreated by astrometry.net. try_builtin_source_finder : bool If true, try using astrometry.net's built-in source",
"sextractor: option_list.append(\"--use-source-extractor\") if no_plots: option_list.append(\"--no-plot\") if minimal_output: option_list.append(\"--corr none --rdls none --match none\")",
"``True``, save WCS header even if other output is suppressed with `minimial_output` verify",
"number of lines in buffer #----------------------------- Miscellaneous --------------------------------- VERBOSE_TYPE NORMAL # can be",
"camera='', avoid_pyfits=False, no_source_extractor=False, solve_field_args=None): \"\"\"Add WCS headers to FITS file using astrometry.net Parameters",
"not None: option_list.append(\"--ra %s --dec %s --radius 0.5\" % ra_dec) if overwrite: option_list.append(\"--overwrite\")",
"also `save_wcs` save_wcs : bool, optional If ``True``, save WCS header even if",
"3000 # number of objects in stack MEMORY_PIXSTACK 300000 # number of pixels",
"is not None: if verify: solve_field.append(\"--verify\") solve_field.append(\"%s\" % verify) else: solve_field.append(\"--no-verify\") solve_field.extend([filename]) print('",
"(RA, Dec); also limits search radius to 1 degree. overwrite : bool, optional",
"odds_ratio is not None: solve_field.append('--odds-to-solve') solve_field.append(odds_ratio) if astrometry_config is not None: solve_field.append('--config') solve_field.append(astrometry_config)",
"to be the image center. odds_ratio : float, optional The odds ratio to",
"[additional_args] else: add_ons = additional_args option_list.extend(add_ons) if isinstance(sextractor, str): option_list.append(\"--source-extractor-path \" + sextractor)",
"default.conv # name of the file containing the filter DEBLEND_NTHRESH 32 # Number",
"in mag.arcsec-2 ANALYSIS_THRESH 1.5 # <sigmas> or <threshold>,<ZP> in mag.arcsec-2 FILTER N #",
"file containing the filter DEBLEND_NTHRESH 32 # Number of deblending sub-thresholds DEBLEND_MINCONT 0.005",
"failed for %s', filename) raise e logger.log(log_level, solve_field_output) return return_status def add_astrometry(filename, overwrite=False,",
"this plate solution does not work the solution is found as though `verify`",
"pyfits_options]) if solve_field_args is not None: additional_opts = additional_opts.split() additional_opts.extend(solve_field_args) logger.info('BEGIN ADDING ASTROMETRY",
"= open(base + '.failed', 'wb') f.write(failed_details) f.close() except IOError as e: logger.error('Unable to",
"verify: solve_field.append(\"--verify\") solve_field.append(\"%s\" % verify) else: solve_field.append(\"--no-verify\") solve_field.extend([filename]) print(' '.join(solve_field)) logger.info(' '.join(solve_field)) try:",
"NORMAL # can be QUIET, NORMAL or FULL HEADER_SUFFIX .head # Filename extension",
"center. odds_ratio : float, optional The odds ratio to use for a successful",
"image center. odds_ratio : float, optional The odds ratio to use for a",
"subprocess.CalledProcessError as e: logger.debug('Failed with error') failed_details = e.output solved_field = False if",
"to solve. For more flexible invocation of astrometry.net, see :func:`call_astrometry` \"\"\" base, ext",
"or a ``str`` with the path to sextractor. custom_sextractor_config : bool, optional If",
"or str (RA, Dec) of field center as either decimal or sexagesimal; also",
"to overwrite the original file. If `False`, the file astrometry.net generates is kept.",
"None: solve_field.append('--config') solve_field.append(astrometry_config) # kludge to handle case when path of verify file",
"'cp16': 0.55 } if camera: use_feder = False scale = camera_pixel_scales[camera] scale_options =",
"solved. Default is to use `'u9'`. avoid_pyfits : bool Add arguments to solve-field",
"gamma of emulsion (for photographic scans) GAIN 0.0 # detector gain in e-/ADU",
"#------------------------- Star/Galaxy Separation ---------------------------- SEEING_FWHM 1.2 # stellar FWHM in arcsec STARNNW_NAME default.nnw",
"--scale-high {high} \" \"--scale-units arcsecperpix\".format(low=0.8*scale, high=1.2 * scale)) else: use_feder = True scale_options",
"contrast parameter for deblending CLEAN Y # Clean spurious detections? (Y or N)?",
"the file containing catalog contents #------------------------------- Extraction ---------------------------------- DETECT_TYPE CCD # CCD (linear)",
"Parameters ---------- overwrite : bool, optional Set ``True`` to overwrite the original file.",
"stderr=subprocess.STDOUT) return_status = 0 log_level = logging.DEBUG except subprocess.CalledProcessError as e: return_status =",
"If ``True``, create a file with extension \"failed\" if astrometry.net fails. The \"failed\"",
"Feder Observatory Apogee Alta U9 camera. no_plots : bool, optional ``True`` to suppress",
"see also `save_wcs` save_wcs : bool, optional If ``True``, save WCS header even",
"option_list.append(\"--ra %s --dec %s --radius 0.5\" % ra_dec) if overwrite: option_list.append(\"--overwrite\") if wcs_reference_image_center:",
"Returns ------- bool ``True`` on success. Notes ----- Tries a couple strategies before",
"call call_astrometry') solved_field = (call_astrometry(filename, sextractor=not no_source_extractor, ra_dec=ra_dec, save_wcs=save_wcs, verify=verify, custom_sextractor_config=custom_sextractor, odds_ratio=odds_ratio, astrometry_config=astrometry_config,",
"solved_field = (call_astrometry(filename, sextractor=not no_source_extractor, ra_dec=ra_dec, save_wcs=save_wcs, verify=verify, custom_sextractor_config=custom_sextractor, odds_ratio=odds_ratio, astrometry_config=astrometry_config, feder_settings=use_feder, additional_args=additional_opts)",
"sextractor=not no_source_extractor, ra_dec=ra_dec, save_wcs=save_wcs, verify=verify, custom_sextractor_config=custom_sextractor, odds_ratio=odds_ratio, astrometry_config=astrometry_config, feder_settings=use_feder, additional_args=additional_opts) == 0) except",
"# <sigmas> or <threshold>,<ZP> in mag.arcsec-2 FILTER N # apply filter for detection",
"# Filename extension for additional headers WRITE_XML N # Write XML file (Y/N)?",
"min. # of pixels above threshold DETECT_THRESH 1.5 # <sigmas> or <threshold>,<ZP> in",
"str (RA, Dec) of field center as either decimal or sexagesimal; also limits",
"used as a first guess for the astrometry fit; if this plate solution",
"custom_sextractor_config=False, feder_settings=True, no_plots=True, minimal_output=True, save_wcs=False, verify=None, ra_dec=None, overwrite=False, wcs_reference_image_center=True, odds_ratio=None, astrometry_config=None, additional_args=None): \"\"\"",
"solution does not work the solution is found as though `verify` had not",
"(not solved_field) and try_builtin_source_finder: log_msg = 'Astrometry failed using sextractor, trying built-in '",
"logger.warning('Adding astrometry failed for file %s', filename) if overwrite and solved_field: logger.info('Overwriting original",
"If `False`, the file astrometry.net generates is kept. ra_dec : list or tuple",
"logger.info(' '.join(solve_field)) try: solve_field_output = subprocess.check_output(solve_field, stderr=subprocess.STDOUT) return_status = 0 log_level = logging.DEBUG",
"'-indx.xyls') remove(base + '.solved') except OSError: pass if note_failure and not solved_field: try:",
"in arcsec (0=use FITS WCS info) #------------------------- Star/Galaxy Separation ---------------------------- SEEING_FWHM 1.2 #",
"of pixel in arcsec (0=use FITS WCS info) #------------------------- Star/Galaxy Separation ---------------------------- SEEING_FWHM",
"the .solved file, and, if desired, a \".failed\" file for fields which it",
"astrometry.net:\\n' + str(e.output) log_level = logging.WARN logger.warning('Adding astrometry failed for %s', filename) raise",
"not None: if verify: solve_field.append(\"--verify\") solve_field.append(\"%s\" % verify) else: solve_field.append(\"--no-verify\") solve_field.extend([filename]) print(' '.join(solve_field))",
"(linear) or PHOTO (with gamma correction) DETECT_MINAREA 15 # min. # of pixels",
"config_contents = SExtractor_config.format(param_file=param_location) with open(config_location, 'w') as f: f.write(config_contents) with open(param_location, 'w') as",
"overwrite the original file. If `False`, the file astrometry.net generates is kept. ra_dec",
": bool, optional If ``True``, use a sexractor configuration file customized for Feder",
"location and more) minimal_output : bool, optional If ``True``, suppress, as separate files,",
"LOCAL #------------------------------ Check Image ---------------------------------- CHECKIMAGE_TYPE NONE # can be NONE, BACKGROUND, BACKGROUND_RMS,",
"contents = \"\"\" X_IMAGE Y_IMAGE MAG_AUTO FLUX_AUTO \"\"\" f.write(dedent(contents)) additional_solve_args = [ '--source-extractor-config',",
"space--split # above does not work for that case. if verify is not",
"WCS reference point in the image to be the image center. odds_ratio :",
"['call_astrometry', 'add_astrometry'] logger = logging.getLogger(__name__) def call_astrometry(filename, sextractor=False, custom_sextractor_config=False, feder_settings=True, no_plots=True, minimal_output=True, save_wcs=False,",
"# MAG_PETRO parameters: <Petrosian_fact>, # <min_radius> SATUR_LEVEL 50000.0 # level (in ADUs) at",
"DEBLEND_NTHRESH 32 # Number of deblending sub-thresholds DEBLEND_MINCONT 0.005 # Minimum contrast parameter",
"(Y or N)? CLEAN_PARAM 1.0 # Cleaning efficiency MASK_TYPE CORRECT # type of",
"also cleans up after astrometry.net, keeping only the new FITS file it generates,",
"radius to 1 degree. note_failure : bool, optional If ``True``, create a file",
"for file %s', filename) if overwrite and solved_field: logger.info('Overwriting original file with image",
"optional Additional arguments to pass to `solve-field` \"\"\" solve_field = [\"solve-field\"] option_list =",
"save_wcs : verify : See :func:`call_astrometry` camera : str, one of ['celestron', 'u9',",
"%s', filename) if overwrite and solved_field: logger.info('Overwriting original file with image with astrometry')",
"= subprocess.check_output(solve_field, stderr=subprocess.STDOUT) return_status = 0 log_level = logging.DEBUG except subprocess.CalledProcessError as e:",
"0 log_level = logging.DEBUG except subprocess.CalledProcessError as e: return_status = e.returncode solve_field_output =",
"original file. If `False`, the file astrometry.net generates is kept. ra_dec : list",
": list or tuple of float or str (RA, Dec) of field center",
"Filename for the check-image #--------------------- Memory (change with caution!) ------------------------- MEMORY_OBJSTACK 3000 #",
"0.5 --scale-high 0.6 --scale-units arcsecperpix\") if additional_args is not None: if isinstance(additional_args, str):",
"not None: additional_opts = additional_opts.split() additional_opts.extend(solve_field_args) logger.info('BEGIN ADDING ASTROMETRY on {0}'.format(filename)) try: logger.debug('About",
"% ra_dec) if overwrite: option_list.append(\"--overwrite\") if wcs_reference_image_center: option_list.append(\"--crpix-center\") options = \" \".join(option_list) solve_field.extend(options.split())",
"if overwrite and solved_field: logger.info('Overwriting original file with image with astrometry') try: rename(base",
"option_list.append(\"--overwrite\") if wcs_reference_image_center: option_list.append(\"--crpix-center\") options = \" \".join(option_list) solve_field.extend(options.split()) if custom_sextractor_config: tmp_location =",
"Miscellaneous --------------------------------- VERBOSE_TYPE NORMAL # can be QUIET, NORMAL or FULL HEADER_SUFFIX .head",
"solve. For more flexible invocation of astrometry.net, see :func:`call_astrometry` \"\"\" base, ext =",
"ADUs) MAG_ZEROPOINT 0.0 # magnitude zero-point MAG_GAMMA 4.0 # gamma of emulsion (for",
"solve_field = [\"solve-field\"] option_list = [] option_list.append(\"--obj 100\") if feder_settings: option_list.append( \"--scale-low 0.5",
"if camera: use_feder = False scale = camera_pixel_scales[camera] scale_options = (\"--scale-low {low} --scale-high",
"but see also `save_wcs` save_wcs : bool, optional If ``True``, save WCS header",
"f.write(dedent(contents)) additional_solve_args = [ '--source-extractor-config', config_location, '--x-column', 'X_IMAGE', '--y-column', 'Y_IMAGE', '--sort-column', 'MAG_AUTO', '--sort-ascending'",
"change DETECT_MINAREA and turn of filter convolution #-------------------------------- Catalog ------------------------------------ PARAMETERS_NAME {param_file} #",
"False if solved_field: logger.info('Adding astrometry succeeded') else: logger.warning('Adding astrometry failed for file %s',",
"astrometry_config is not None: solve_field.append('--config') solve_field.append(astrometry_config) # kludge to handle case when path",
"MINIBACK_RMS, -BACKGROUND, # FILTERED, OBJECTS, -OBJECTS, SEGMENTATION, # or APERTURES CHECKIMAGE_NAME check.fits #",
"base, ext = path.splitext(filename) # All are in arcsec per pixel, values are",
"contains the error messages genreated by astrometry.net. try_builtin_source_finder : bool If true, try",
"WRITE_XML N # Write XML file (Y/N)? XML_NAME sex.xml # Filename for XML",
"ra_dec : list or tuple of float (RA, Dec); also limits search radius",
"one of ['celestron', 'u9', 'cp16'], optional Name of camera; determines the pixel scale",
"and turn of filter convolution #-------------------------------- Catalog ------------------------------------ PARAMETERS_NAME {param_file} # name of",
"odds_ratio : float, optional The odds ratio to use for a successful solve.",
"= '--no-remove-lines --uniformize 0' else: pyfits_options = '' additional_opts = ' '.join([scale_options, pyfits_options])",
"or N)? FILTER_NAME default.conv # name of the file containing the filter DEBLEND_NTHRESH",
"# Background mesh: <size> or <width>,<height> BACK_FILTERSIZE 3 # Background filter: <size> or",
"str, optional Additional arguments to pass to `solve-field` \"\"\" solve_field = [\"solve-field\"] option_list",
"solve_field_output = 'Output from astrometry.net:\\n' + str(e.output) log_level = logging.WARN logger.warning('Adding astrometry failed",
"use for a successful solve. Default is to use the default in `solve-field`.",
"if avoid_pyfits: pyfits_options = '--no-remove-lines --uniformize 0' else: pyfits_options = '' additional_opts =",
"<Kron_fact>,<min_radius> PHOT_PETROPARAMS 2.0, 3.5 # MAG_PETRO parameters: <Petrosian_fact>, # <min_radius> SATUR_LEVEL 50000.0 #",
"gain in e-/ADU PIXEL_SCALE 1.0 # size of pixel in arcsec (0=use FITS",
"' '.join([scale_options, pyfits_options]) if solve_field_args is not None: additional_opts = additional_opts.split() additional_opts.extend(solve_field_args) logger.info('BEGIN",
"ra_dec is not None: option_list.append(\"--ra %s --dec %s --radius 0.5\" % ra_dec) if",
"SATURATE # keyword for saturation level (in ADUs) MAG_ZEROPOINT 0.0 # magnitude zero-point",
"return False # whether we succeeded or failed, clean up try: remove(base +",
"in `solve-field`. astrometry_config : str, optional Name of configuration file to use for",
"#------------------------------ Check Image ---------------------------------- CHECKIMAGE_TYPE NONE # can be NONE, BACKGROUND, BACKGROUND_RMS, #",
"subprocess.check_output(solve_field, stderr=subprocess.STDOUT) return_status = 0 log_level = logging.DEBUG except subprocess.CalledProcessError as e: return_status",
"+= 'source finder' logger.info(log_msg) try: solved_field = (call_astrometry(filename, ra_dec=ra_dec, overwrite=True, save_wcs=save_wcs, verify=verify) ==",
"config_location, '--x-column', 'X_IMAGE', '--y-column', 'Y_IMAGE', '--sort-column', 'MAG_AUTO', '--sort-ascending' ] solve_field.extend(additional_solve_args) if odds_ratio is",
"detections? (Y or N)? CLEAN_PARAM 1.0 # Cleaning efficiency MASK_TYPE CORRECT # type",
"f.write(config_contents) with open(param_location, 'w') as f: contents = \"\"\" X_IMAGE Y_IMAGE MAG_AUTO FLUX_AUTO",
"astrometry.net, see :func:`call_astrometry` \"\"\" base, ext = path.splitext(filename) # All are in arcsec",
"optional If ``True``, suppress, as separate files, output of: WCS header, RA/Dec object",
"of astrometry.net %s', e) pass logger.info('END ADDING ASTROMETRY for %s', filename) return solved_field",
"a \".failed\" file for fields which it fails to solve. For more flexible",
"+ '.solved') except OSError: pass if note_failure and not solved_field: try: f =",
"'Astrometry failed using sextractor, trying built-in ' log_msg += 'source finder' logger.info(log_msg) try:",
"a space--split # above does not work for that case. if verify is",
"the check-image #--------------------- Memory (change with caution!) ------------------------- MEMORY_OBJSTACK 3000 # number of",
"true, try using astrometry.net's built-in source extractor if sextractor fails. save_wcs : verify",
"a file with extension \"failed\" if astrometry.net fails. The \"failed\" file contains the",
"[ '--source-extractor-config', config_location, '--x-column', 'X_IMAGE', '--y-column', 'Y_IMAGE', '--sort-column', 'MAG_AUTO', '--sort-ascending' ] solve_field.extend(additional_solve_args) if",
"number of pixels in stack MEMORY_BUFSIZE 1024 # number of lines in buffer",
"# modification was to change DETECT_MINAREA and turn of filter convolution #-------------------------------- Catalog",
"generates is kept. ra_dec : list or tuple of float or str (RA,",
"whether we succeeded or failed, clean up try: remove(base + '.axy') except OSError:",
"``True``, create a file with extension \"failed\" if astrometry.net fails. The \"failed\" file",
"str): option_list.append(\"--source-extractor-path \" + sextractor) elif sextractor: option_list.append(\"--use-source-extractor\") if no_plots: option_list.append(\"--no-plot\") if minimal_output:",
"limits search radius to 1 degree. overwrite : bool, optional If ``True``, perform",
"----------------------------------- PHOT_APERTURES 10 # MAG_APER aperture diameter(s) in pixels PHOT_AUTOPARAMS 2.5, 3.5 #",
"objects list, but see also `save_wcs` save_wcs : bool, optional If ``True``, save",
"logger.info('BEGIN ADDING ASTROMETRY on {0}'.format(filename)) try: logger.debug('About to call call_astrometry') solved_field = (call_astrometry(filename,",
"OBJECTS, -OBJECTS, SEGMENTATION, # or APERTURES CHECKIMAGE_NAME check.fits # Filename for the check-image",
"str or list of str, optional Additional arguments to pass to `solve-field` \"\"\"",
"of camera; determines the pixel scale used in the solved. Default is to",
"verify=None, try_builtin_source_finder=False, custom_sextractor=False, odds_ratio=None, astrometry_config=None, camera='', avoid_pyfits=False, no_source_extractor=False, solve_field_args=None): \"\"\"Add WCS headers to",
"tempfile.mkdtemp() param_location = path.join(tmp_location, 'default.param') config_location = path.join(tmp_location, 'feder.config') config_contents = SExtractor_config.format(param_file=param_location) with",
"scale_options = (\"--scale-low {low} --scale-high {high} \" \"--scale-units arcsecperpix\".format(low=0.8*scale, high=1.2 * scale)) else:",
"MEMORY_PIXSTACK 300000 # number of pixels in stack MEMORY_BUFSIZE 1024 # number of",
"Photometry ----------------------------------- PHOT_APERTURES 10 # MAG_APER aperture diameter(s) in pixels PHOT_AUTOPARAMS 2.5, 3.5",
"in the image to be the image center. odds_ratio : float, optional The",
"1.2 # stellar FWHM in arcsec STARNNW_NAME default.nnw # Neural-Network_Weight table filename #------------------------------",
"sextractor=False, custom_sextractor_config=False, feder_settings=True, no_plots=True, minimal_output=True, save_wcs=False, verify=None, ra_dec=None, overwrite=False, wcs_reference_image_center=True, odds_ratio=None, astrometry_config=None, additional_args=None):",
"options = \" \".join(option_list) solve_field.extend(options.split()) if custom_sextractor_config: tmp_location = tempfile.mkdtemp() param_location = path.join(tmp_location,",
"Number of deblending sub-thresholds DEBLEND_MINCONT 0.005 # Minimum contrast parameter for deblending CLEAN",
"try using astrometry.net's built-in source extractor if sextractor fails. save_wcs : verify :",
"Background ----------------------------------- BACK_SIZE 64 # Background mesh: <size> or <width>,<height> BACK_FILTERSIZE 3 #",
"BACK_FILTERSIZE 3 # Background filter: <size> or <width>,<height> BACKPHOTO_TYPE GLOBAL # can be",
"str, optional ``True`` to use `sextractor`, or a ``str`` with the path to",
"calls to pyfits.BinTableHDU. See https://groups.google.com/forum/#!topic/astrometry/AT21x6zVAJo Returns ------- bool ``True`` on success. Notes -----",
"additional_opts.extend(solve_field_args) logger.info('BEGIN ADDING ASTROMETRY on {0}'.format(filename)) try: logger.debug('About to call call_astrometry') solved_field =",
"+ '-indx.xyls') remove(base + '.solved') except OSError: pass if note_failure and not solved_field:",
"objects in stack MEMORY_PIXSTACK 300000 # number of pixels in stack MEMORY_BUFSIZE 1024",
"Observatory Apogee Alta U9 camera. no_plots : bool, optional ``True`` to suppress astrometry.net",
"on success. Notes ----- Tries a couple strategies before giving up: first sextractor,",
"SExtractor_config.format(param_file=param_location) with open(config_location, 'w') as f: f.write(config_contents) with open(param_location, 'w') as f: contents",
"# <sigmas> or <threshold>,<ZP> in mag.arcsec-2 ANALYSIS_THRESH 1.5 # <sigmas> or <threshold>,<ZP> in",
"0.55 } if camera: use_feder = False scale = camera_pixel_scales[camera] scale_options = (\"--scale-low",
"'' additional_opts = ' '.join([scale_options, pyfits_options]) if solve_field_args is not None: additional_opts =",
"verify=verify, custom_sextractor_config=custom_sextractor, odds_ratio=odds_ratio, astrometry_config=astrometry_config, feder_settings=use_feder, additional_args=additional_opts) == 0) except subprocess.CalledProcessError as e: logger.debug('Failed",
"'--sort-ascending' ] solve_field.extend(additional_solve_args) if odds_ratio is not None: solve_field.append('--odds-to-solve') solve_field.append(odds_ratio) if astrometry_config is",
"it fails to solve. For more flexible invocation of astrometry.net, see :func:`call_astrometry` \"\"\"",
"as e: logger.error(e) return False # whether we succeeded or failed, clean up",
"files, output of: WCS header, RA/Dec object list, matching objects list, but see",
"def call_astrometry(filename, sextractor=False, custom_sextractor_config=False, feder_settings=True, no_plots=True, minimal_output=True, save_wcs=False, verify=None, ra_dec=None, overwrite=False, wcs_reference_image_center=True, odds_ratio=None,",
"detection MASKing: can be one of # NONE, BLANK or CORRECT #------------------------------ Photometry",
"path to sextractor. custom_sextractor_config : bool, optional If ``True``, use a sexractor configuration",
"isinstance(additional_args, str): add_ons = [additional_args] else: add_ons = additional_args option_list.extend(add_ons) if isinstance(sextractor, str):",
"SATUR_KEY SATURATE # keyword for saturation level (in ADUs) MAG_ZEROPOINT 0.0 # magnitude",
"except OSError as e: logger.error(e) return False # whether we succeeded or failed,",
"for the check-image #--------------------- Memory (change with caution!) ------------------------- MEMORY_OBJSTACK 3000 # number",
"WCS header, RA/Dec object list, matching objects list, but see also `save_wcs` save_wcs",
"of ['celestron', 'u9', 'cp16'], optional Name of camera; determines the pixel scale used",
"modification was to change DETECT_MINAREA and turn of filter convolution #-------------------------------- Catalog ------------------------------------",
"list or tuple of float (RA, Dec); also limits search radius to 1",
"`solve-field` \"\"\" solve_field = [\"solve-field\"] option_list = [] option_list.append(\"--obj 100\") if feder_settings: option_list.append(",
"solve_field_output) return return_status def add_astrometry(filename, overwrite=False, ra_dec=None, note_failure=False, save_wcs=False, verify=None, try_builtin_source_finder=False, custom_sextractor=False, odds_ratio=None,",
": bool, optional If ``True``, perform astrometry even if astrometry.net files from a",
"] solve_field.extend(additional_solve_args) if odds_ratio is not None: solve_field.append('--odds-to-solve') solve_field.append(odds_ratio) if astrometry_config is not",
"'w') as f: f.write(config_contents) with open(param_location, 'w') as f: contents = \"\"\" X_IMAGE",
"FITS WCS info) #------------------------- Star/Galaxy Separation ---------------------------- SEEING_FWHM 1.2 # stellar FWHM in",
"astrometry failed for %s', filename) raise e logger.log(log_level, solve_field_output) return return_status def add_astrometry(filename,",
"is not None: solve_field.append('--config') solve_field.append(astrometry_config) # kludge to handle case when path of",
"textwrap import dedent __all__ = ['call_astrometry', 'add_astrometry'] logger = logging.getLogger(__name__) def call_astrometry(filename, sextractor=False,",
": bool, optional Set ``True`` to overwrite the original file. If `False`, the",
"astrometry failed for file %s', filename) if overwrite and solved_field: logger.info('Overwriting original file",
"if solved_field: logger.info('Adding astrometry succeeded') else: logger.warning('Adding astrometry failed for file %s', filename)",
"camera; determines the pixel scale used in the solved. Default is to use",
"fails to solve. For more flexible invocation of astrometry.net, see :func:`call_astrometry` \"\"\" base,",
"is kept. ra_dec : list or tuple of float or str (RA, Dec)",
"---------- sextractor : bool or str, optional ``True`` to use `sextractor`, or a",
"failed using sextractor, trying built-in ' log_msg += 'source finder' logger.info(log_msg) try: solved_field",
"Extraction ---------------------------------- DETECT_TYPE CCD # CCD (linear) or PHOTO (with gamma correction) DETECT_MINAREA",
"solve_field_output = subprocess.check_output(solve_field, stderr=subprocess.STDOUT) return_status = 0 log_level = logging.DEBUG except subprocess.CalledProcessError as",
"----- Tries a couple strategies before giving up: first sextractor, then, if that",
"== 0) except subprocess.CalledProcessError as e: failed_details = e.output solved_field = False if",
"-BACKGROUND, # FILTERED, OBJECTS, -OBJECTS, SEGMENTATION, # or APERTURES CHECKIMAGE_NAME check.fits # Filename",
"= { 'celestron': 0.3, 'u9': 0.55, 'cp16': 0.55 } if camera: use_feder =",
"MAG_AUTO parameters: <Kron_fact>,<min_radius> PHOT_PETROPARAMS 2.0, 3.5 # MAG_PETRO parameters: <Petrosian_fact>, # <min_radius> SATUR_LEVEL",
"note_failure and not solved_field: try: f = open(base + '.failed', 'wb') f.write(failed_details) f.close()",
"kludge to handle case when path of verify file contains a space--split #",
"solved_field: logger.info('Overwriting original file with image with astrometry') try: rename(base + '.new', filename)",
"call_astrometry(filename, sextractor=False, custom_sextractor_config=False, feder_settings=True, no_plots=True, minimal_output=True, save_wcs=False, verify=None, ra_dec=None, overwrite=False, wcs_reference_image_center=True, odds_ratio=None, astrometry_config=None,",
"ext = path.splitext(filename) # All are in arcsec per pixel, values are approximate",
"if other output is suppressed with `minimial_output` verify : str, optional Name of",
"\".failed\" file for fields which it fails to solve. For more flexible invocation",
"ra_dec=None, note_failure=False, save_wcs=False, verify=None, try_builtin_source_finder=False, custom_sextractor=False, odds_ratio=None, astrometry_config=None, camera='', avoid_pyfits=False, no_source_extractor=False, solve_field_args=None): \"\"\"Add",
"# Write XML file (Y/N)? XML_NAME sex.xml # Filename for XML output \"\"\"",
"---------- overwrite : bool, optional Set ``True`` to overwrite the original file. If",
"# or APERTURES CHECKIMAGE_NAME check.fits # Filename for the check-image #--------------------- Memory (change",
"`minimial_output` verify : str, optional Name of a WCS header to be used",
"subprocess.CalledProcessError as e: failed_details = e.output solved_field = False if solved_field: logger.info('Adding astrometry",
"success. Notes ----- Tries a couple strategies before giving up: first sextractor, then,",
"astrometry.net fails. The \"failed\" file contains the error messages genreated by astrometry.net. try_builtin_source_finder",
"'.failed', 'wb') f.write(failed_details) f.close() except IOError as e: logger.error('Unable to save output of",
"option_list.append(\"--use-source-extractor\") if no_plots: option_list.append(\"--no-plot\") if minimal_output: option_list.append(\"--corr none --rdls none --match none\") if",
"of objects in stack MEMORY_PIXSTACK 300000 # number of pixels in stack MEMORY_BUFSIZE",
"if feder_settings: option_list.append( \"--scale-low 0.5 --scale-high 0.6 --scale-units arcsecperpix\") if additional_args is not",
"astrometry.net generation of plots (pngs showing object location and more) minimal_output : bool,",
"failed for file %s', filename) if overwrite and solved_field: logger.info('Overwriting original file with",
"# Cleaning efficiency MASK_TYPE CORRECT # type of detection MASKing: can be one",
"ASTROMETRY for %s', filename) return solved_field SExtractor_config = \"\"\" # Configuration file for",
"'Y_IMAGE', '--sort-column', 'MAG_AUTO', '--sort-ascending' ] solve_field.extend(additional_solve_args) if odds_ratio is not None: solve_field.append('--odds-to-solve') solve_field.append(odds_ratio)",
"CCD # CCD (linear) or PHOTO (with gamma correction) DETECT_MINAREA 15 # min.",
"bool, optional If ``True``, create a file with extension \"failed\" if astrometry.net fails.",
"import logging import subprocess from os import path, remove, rename import tempfile from",
"wcs_reference_image_center: option_list.append(\"--crpix-center\") options = \" \".join(option_list) solve_field.extend(options.split()) if custom_sextractor_config: tmp_location = tempfile.mkdtemp() param_location",
": float, optional The odds ratio to use for a successful solve. Default",
"remove(base + '.solved') except OSError: pass if note_failure and not solved_field: try: f",
"\".join(option_list) solve_field.extend(options.split()) if custom_sextractor_config: tmp_location = tempfile.mkdtemp() param_location = path.join(tmp_location, 'default.param') config_location =",
"solve_field.extend(additional_solve_args) if odds_ratio is not None: solve_field.append('--odds-to-solve') solve_field.append(odds_ratio) if astrometry_config is not None:",
"str, one of ['celestron', 'u9', 'cp16'], optional Name of camera; determines the pixel",
"up: first sextractor, then, if that fails, astrometry.net's built-in source extractor. It also",
"OSError: pass if note_failure and not solved_field: try: f = open(base + '.failed',"
] |
[
"getpass from ontology.common.address import Address from ontology.ont_sdk import OntologySdk from punica.utils.file_system import (",
"Address.address_from_vm_code(hex_avm_code).to_reverse_hex_str() return hex_contract_address @staticmethod def check_deploy_state(tx_hash, project_path: str = '', network: str =",
"== '': project_dir = os.getcwd() avm_dir_path = os.path.join(project_dir, 'contracts', 'build') rpc_address = handle_network_config(project_dir,",
"project_dir == '': project_dir = os.getcwd() avm_dir_path = os.path.join(project_dir, 'contracts', 'build') rpc_address =",
"author = deploy_information.get('author', '') email = deploy_information.get('email', '') desc = deploy_information.get('desc', '') b58_payer_address",
"punica.exception.punica_exception import PunicaException, PunicaError class Deploy: @staticmethod def generate_signed_deploy_transaction(hex_avm_code: str, project_path: str =",
"'': avm_dir_path = os.path.join(os.getcwd(), 'build', 'contracts') if not os.path.isdir(avm_dir_path): raise PunicaException(PunicaError.dir_path_error) hex_avm_code =",
"deploy_smart_contract(project_dir: str = '', network: str = '', avm_file_name: str = '', wallet_file_name:",
"False) ontology = OntologySdk() ontology.rpc.set_address(rpc_address) time.sleep(6) tx = ontology.rpc.get_raw_transaction(tx_hash) if tx == 'unknown",
"def generate_signed_deploy_transaction(hex_avm_code: str, project_path: str = '', wallet_file_name: str = ''): wallet_dir_path =",
"os.path.split(project_path)[1]) version = deploy_information.get('version', '0.0.1') author = deploy_information.get('author', '') email = deploy_information.get('email', '')",
"= OntologySdk() ontology.rpc.set_address(rpc_address) time.sleep(6) tx = ontology.rpc.get_raw_transaction(tx_hash) if tx == 'unknown transaction': return",
"= read_avm(avm_dir_path, avm_file_name)[0] hex_contract_address = Address.address_from_vm_code(hex_avm_code).to_reverse_hex_str() return hex_contract_address @staticmethod def check_deploy_state(tx_hash, project_path: str",
"str = '') -> str: if avm_dir_path == '': avm_dir_path = os.path.join(os.getcwd(), 'build',",
"handle_network_config(project_dir, network) hex_avm_code, avm_file_name = read_avm(avm_dir_path, avm_file_name) if hex_avm_code == '': raise PunicaException(PunicaError.avm_file_empty)",
") from punica.exception.punica_exception import PunicaException, PunicaError class Deploy: @staticmethod def generate_signed_deploy_transaction(hex_avm_code: str, project_path:",
"'') b58_payer_address = deploy_information.get('payer', wallet_manager.get_default_account().get_address()) gas_limit = deploy_information.get('gasLimit', 21000000) gas_price = deploy_information.get('gasPrice', 500)",
"project_path = os.getcwd() if not os.path.isdir(project_path): raise PunicaException(PunicaError.dir_path_error) rpc_address = handle_network_config(project_path, network, False)",
"= ontology.rpc.get_smart_contract(hex_contract_address) print('Running deployment: {}'.format(avm_file_name)) if contract == 'unknow contracts': print('\\tDeploying...') print('\\t... 0x{}'.format(hex_avm_code[:64]))",
"contracts': print('\\tDeploying...') print('\\t... 0x{}'.format(hex_avm_code[:64])) tx = Deploy.generate_signed_deploy_transaction(hex_avm_code, project_dir, wallet_file_name) ontology.rpc.set_address(rpc_address) tx_hash = ontology.rpc.send_raw_transaction(tx)",
"0x{}'.format(hex_avm_code[:64])) tx = Deploy.generate_signed_deploy_transaction(hex_avm_code, project_dir, wallet_file_name) ontology.rpc.set_address(rpc_address) tx_hash = ontology.rpc.send_raw_transaction(tx) return tx_hash else:",
"= os.path.join(project_dir, 'contracts', 'build') rpc_address = handle_network_config(project_dir, network) hex_avm_code, avm_file_name = read_avm(avm_dir_path, avm_file_name)",
"= Deploy.generate_signed_deploy_transaction(hex_avm_code, project_dir, wallet_file_name) ontology.rpc.set_address(rpc_address) tx_hash = ontology.rpc.send_raw_transaction(tx) return tx_hash else: print('\\tDeploy failed...')",
"email = deploy_information.get('email', '') desc = deploy_information.get('desc', '') b58_payer_address = deploy_information.get('payer', wallet_manager.get_default_account().get_address()) gas_limit",
"'build', 'contracts') if not os.path.isdir(avm_dir_path): raise PunicaException(PunicaError.dir_path_error) hex_avm_code = read_avm(avm_dir_path, avm_file_name)[0] hex_contract_address =",
"'wallet') wallet_manager = read_wallet(wallet_dir_path, wallet_file_name) deploy_dir_path = os.path.join(project_path, 'contracts') deploy_information = handle_deploy_config(deploy_dir_path) need_storage",
"ontology.ont_sdk import OntologySdk from punica.utils.file_system import ( read_avm, read_wallet ) from punica.utils.handle_config import",
"check_deploy_state(tx_hash, project_path: str = '', network: str = ''): if project_path == '':",
"import getpass from ontology.common.address import Address from ontology.ont_sdk import OntologySdk from punica.utils.file_system import",
"punica.utils.file_system import ( read_avm, read_wallet ) from punica.utils.handle_config import ( handle_network_config, handle_deploy_config )",
"= read_avm(avm_dir_path, avm_file_name) if hex_avm_code == '': raise PunicaException(PunicaError.avm_file_empty) hex_contract_address = Deploy.generate_contract_address(avm_dir_path, avm_file_name)",
"str = '', avm_file_name: str = '', wallet_file_name: str = ''): if project_dir",
"return tx @staticmethod def generate_contract_address(avm_dir_path: str = '', avm_file_name: str = '') ->",
"500) ontology = OntologySdk() tx = ontology.neo_vm().make_deploy_transaction(hex_avm_code, need_storage, name, version, author, email, desc,",
"from punica.utils.handle_config import ( handle_network_config, handle_deploy_config ) from punica.exception.punica_exception import PunicaException, PunicaError class",
"wallet_file_name: str = ''): wallet_dir_path = os.path.join(project_path, 'wallet') wallet_manager = read_wallet(wallet_dir_path, wallet_file_name) deploy_dir_path",
"deploy_information.get('payer', wallet_manager.get_default_account().get_address()) gas_limit = deploy_information.get('gasLimit', 21000000) gas_price = deploy_information.get('gasPrice', 500) ontology = OntologySdk()",
"network: str = ''): if project_path == '': project_path = os.getcwd() if not",
"def deploy_smart_contract(project_dir: str = '', network: str = '', avm_file_name: str = '',",
"ontology = OntologySdk() ontology.rpc.set_address(rpc_address) time.sleep(6) tx = ontology.rpc.get_raw_transaction(tx_hash) if tx == 'unknown transaction':",
"@staticmethod def check_deploy_state(tx_hash, project_path: str = '', network: str = ''): if project_path",
"hex_avm_code, avm_file_name = read_avm(avm_dir_path, avm_file_name) if hex_avm_code == '': raise PunicaException(PunicaError.avm_file_empty) hex_contract_address =",
"utf-8 -*- import os import time import getpass from ontology.common.address import Address from",
"= ontology.rpc.send_raw_transaction(tx) return tx_hash else: print('\\tDeploy failed...') print('\\tContract has been deployed...') print('\\tContract address",
"PunicaError class Deploy: @staticmethod def generate_signed_deploy_transaction(hex_avm_code: str, project_path: str = '', wallet_file_name: str",
"tx = ontology.rpc.get_raw_transaction(tx_hash) if tx == 'unknown transaction': return False else: return True",
"wallet_manager = read_wallet(wallet_dir_path, wallet_file_name) deploy_dir_path = os.path.join(project_path, 'contracts') deploy_information = handle_deploy_config(deploy_dir_path) need_storage =",
"'') desc = deploy_information.get('desc', '') b58_payer_address = deploy_information.get('payer', wallet_manager.get_default_account().get_address()) gas_limit = deploy_information.get('gasLimit', 21000000)",
"input payer account password: ') payer_acct = wallet_manager.get_account(b58_payer_address, password) ontology.sign_transaction(tx, payer_acct) return tx",
"os import time import getpass from ontology.common.address import Address from ontology.ont_sdk import OntologySdk",
"gas_limit = deploy_information.get('gasLimit', 21000000) gas_price = deploy_information.get('gasPrice', 500) ontology = OntologySdk() tx =",
"import Address from ontology.ont_sdk import OntologySdk from punica.utils.file_system import ( read_avm, read_wallet )",
"avm_dir_path == '': avm_dir_path = os.path.join(os.getcwd(), 'build', 'contracts') if not os.path.isdir(avm_dir_path): raise PunicaException(PunicaError.dir_path_error)",
"deploy_information.get('version', '0.0.1') author = deploy_information.get('author', '') email = deploy_information.get('email', '') desc = deploy_information.get('desc',",
"generate_contract_address(avm_dir_path: str = '', avm_file_name: str = '') -> str: if avm_dir_path ==",
"deploy_information = handle_deploy_config(deploy_dir_path) need_storage = deploy_information.get('needStorage', True) name = deploy_information.get('name', os.path.split(project_path)[1]) version =",
"'unknow contracts': print('\\tDeploying...') print('\\t... 0x{}'.format(hex_avm_code[:64])) tx = Deploy.generate_signed_deploy_transaction(hex_avm_code, project_dir, wallet_file_name) ontology.rpc.set_address(rpc_address) tx_hash =",
"ontology.rpc.set_address(rpc_address) contract = ontology.rpc.get_smart_contract(hex_contract_address) print('Running deployment: {}'.format(avm_file_name)) if contract == 'unknow contracts': print('\\tDeploying...')",
"@staticmethod def generate_signed_deploy_transaction(hex_avm_code: str, project_path: str = '', wallet_file_name: str = ''): wallet_dir_path",
"def check_deploy_state(tx_hash, project_path: str = '', network: str = ''): if project_path ==",
"= '', network: str = '', avm_file_name: str = '', wallet_file_name: str =",
"= ''): if project_dir == '': project_dir = os.getcwd() avm_dir_path = os.path.join(project_dir, 'contracts',",
"str = '', avm_file_name: str = '') -> str: if avm_dir_path == '':",
"= os.path.join(os.getcwd(), 'build', 'contracts') if not os.path.isdir(avm_dir_path): raise PunicaException(PunicaError.dir_path_error) hex_avm_code = read_avm(avm_dir_path, avm_file_name)[0]",
"deploy_information.get('needStorage', True) name = deploy_information.get('name', os.path.split(project_path)[1]) version = deploy_information.get('version', '0.0.1') author = deploy_information.get('author',",
"transaction': return False else: return True @staticmethod def deploy_smart_contract(project_dir: str = '', network:",
"desc, b58_payer_address, gas_limit, gas_price) password = <PASSWORD>pass.getpass('\\tPlease input payer account password: ') payer_acct",
"str: if avm_dir_path == '': avm_dir_path = os.path.join(os.getcwd(), 'build', 'contracts') if not os.path.isdir(avm_dir_path):",
"wallet_dir_path = os.path.join(project_path, 'wallet') wallet_manager = read_wallet(wallet_dir_path, wallet_file_name) deploy_dir_path = os.path.join(project_path, 'contracts') deploy_information",
"= '', wallet_file_name: str = ''): if project_dir == '': project_dir = os.getcwd()",
"'contracts', 'build') rpc_address = handle_network_config(project_dir, network) hex_avm_code, avm_file_name = read_avm(avm_dir_path, avm_file_name) if hex_avm_code",
"ontology = OntologySdk() ontology.rpc.set_address(rpc_address) contract = ontology.rpc.get_smart_contract(hex_contract_address) print('Running deployment: {}'.format(avm_file_name)) if contract ==",
"read_avm(avm_dir_path, avm_file_name) if hex_avm_code == '': raise PunicaException(PunicaError.avm_file_empty) hex_contract_address = Deploy.generate_contract_address(avm_dir_path, avm_file_name) ontology",
"OntologySdk() tx = ontology.neo_vm().make_deploy_transaction(hex_avm_code, need_storage, name, version, author, email, desc, b58_payer_address, gas_limit, gas_price)",
"') payer_acct = wallet_manager.get_account(b58_payer_address, password) ontology.sign_transaction(tx, payer_acct) return tx @staticmethod def generate_contract_address(avm_dir_path: str",
"read_wallet(wallet_dir_path, wallet_file_name) deploy_dir_path = os.path.join(project_path, 'contracts') deploy_information = handle_deploy_config(deploy_dir_path) need_storage = deploy_information.get('needStorage', True)",
"@staticmethod def generate_contract_address(avm_dir_path: str = '', avm_file_name: str = '') -> str: if",
"project_path == '': project_path = os.getcwd() if not os.path.isdir(project_path): raise PunicaException(PunicaError.dir_path_error) rpc_address =",
"read_avm(avm_dir_path, avm_file_name)[0] hex_contract_address = Address.address_from_vm_code(hex_avm_code).to_reverse_hex_str() return hex_contract_address @staticmethod def check_deploy_state(tx_hash, project_path: str =",
"coding: utf-8 -*- import os import time import getpass from ontology.common.address import Address",
"return True @staticmethod def deploy_smart_contract(project_dir: str = '', network: str = '', avm_file_name:",
"os.path.join(project_path, 'contracts') deploy_information = handle_deploy_config(deploy_dir_path) need_storage = deploy_information.get('needStorage', True) name = deploy_information.get('name', os.path.split(project_path)[1])",
"from punica.utils.file_system import ( read_avm, read_wallet ) from punica.utils.handle_config import ( handle_network_config, handle_deploy_config",
"read_wallet ) from punica.utils.handle_config import ( handle_network_config, handle_deploy_config ) from punica.exception.punica_exception import PunicaException,",
"raise PunicaException(PunicaError.dir_path_error) hex_avm_code = read_avm(avm_dir_path, avm_file_name)[0] hex_contract_address = Address.address_from_vm_code(hex_avm_code).to_reverse_hex_str() return hex_contract_address @staticmethod def",
"network) hex_avm_code, avm_file_name = read_avm(avm_dir_path, avm_file_name) if hex_avm_code == '': raise PunicaException(PunicaError.avm_file_empty) hex_contract_address",
"os.path.join(os.getcwd(), 'build', 'contracts') if not os.path.isdir(avm_dir_path): raise PunicaException(PunicaError.dir_path_error) hex_avm_code = read_avm(avm_dir_path, avm_file_name)[0] hex_contract_address",
"= os.path.join(project_path, 'contracts') deploy_information = handle_deploy_config(deploy_dir_path) need_storage = deploy_information.get('needStorage', True) name = deploy_information.get('name',",
"''): wallet_dir_path = os.path.join(project_path, 'wallet') wallet_manager = read_wallet(wallet_dir_path, wallet_file_name) deploy_dir_path = os.path.join(project_path, 'contracts')",
"tx = ontology.neo_vm().make_deploy_transaction(hex_avm_code, need_storage, name, version, author, email, desc, b58_payer_address, gas_limit, gas_price) password",
"= '', network: str = ''): if project_path == '': project_path = os.getcwd()",
"deploy_information.get('desc', '') b58_payer_address = deploy_information.get('payer', wallet_manager.get_default_account().get_address()) gas_limit = deploy_information.get('gasLimit', 21000000) gas_price = deploy_information.get('gasPrice',",
"payer_acct) return tx @staticmethod def generate_contract_address(avm_dir_path: str = '', avm_file_name: str = '')",
"handle_deploy_config ) from punica.exception.punica_exception import PunicaException, PunicaError class Deploy: @staticmethod def generate_signed_deploy_transaction(hex_avm_code: str,",
"== '': raise PunicaException(PunicaError.avm_file_empty) hex_contract_address = Deploy.generate_contract_address(avm_dir_path, avm_file_name) ontology = OntologySdk() ontology.rpc.set_address(rpc_address) contract",
"project_dir = os.getcwd() avm_dir_path = os.path.join(project_dir, 'contracts', 'build') rpc_address = handle_network_config(project_dir, network) hex_avm_code,",
"= handle_network_config(project_dir, network) hex_avm_code, avm_file_name = read_avm(avm_dir_path, avm_file_name) if hex_avm_code == '': raise",
"ontology.common.address import Address from ontology.ont_sdk import OntologySdk from punica.utils.file_system import ( read_avm, read_wallet",
"project_path: str = '', wallet_file_name: str = ''): wallet_dir_path = os.path.join(project_path, 'wallet') wallet_manager",
"deploy_information.get('author', '') email = deploy_information.get('email', '') desc = deploy_information.get('desc', '') b58_payer_address = deploy_information.get('payer',",
"'', wallet_file_name: str = ''): wallet_dir_path = os.path.join(project_path, 'wallet') wallet_manager = read_wallet(wallet_dir_path, wallet_file_name)",
"'unknown transaction': return False else: return True @staticmethod def deploy_smart_contract(project_dir: str = '',",
"hex_contract_address @staticmethod def check_deploy_state(tx_hash, project_path: str = '', network: str = ''): if",
"desc = deploy_information.get('desc', '') b58_payer_address = deploy_information.get('payer', wallet_manager.get_default_account().get_address()) gas_limit = deploy_information.get('gasLimit', 21000000) gas_price",
"password = <PASSWORD>pass.getpass('\\tPlease input payer account password: ') payer_acct = wallet_manager.get_account(b58_payer_address, password) ontology.sign_transaction(tx,",
"( read_avm, read_wallet ) from punica.utils.handle_config import ( handle_network_config, handle_deploy_config ) from punica.exception.punica_exception",
"return hex_contract_address @staticmethod def check_deploy_state(tx_hash, project_path: str = '', network: str = ''):",
"project_path: str = '', network: str = ''): if project_path == '': project_path",
"raise PunicaException(PunicaError.avm_file_empty) hex_contract_address = Deploy.generate_contract_address(avm_dir_path, avm_file_name) ontology = OntologySdk() ontology.rpc.set_address(rpc_address) contract = ontology.rpc.get_smart_contract(hex_contract_address)",
"os.path.join(project_dir, 'contracts', 'build') rpc_address = handle_network_config(project_dir, network) hex_avm_code, avm_file_name = read_avm(avm_dir_path, avm_file_name) if",
"print('Running deployment: {}'.format(avm_file_name)) if contract == 'unknow contracts': print('\\tDeploying...') print('\\t... 0x{}'.format(hex_avm_code[:64])) tx =",
"payer_acct = wallet_manager.get_account(b58_payer_address, password) ontology.sign_transaction(tx, payer_acct) return tx @staticmethod def generate_contract_address(avm_dir_path: str =",
"hex_avm_code = read_avm(avm_dir_path, avm_file_name)[0] hex_contract_address = Address.address_from_vm_code(hex_avm_code).to_reverse_hex_str() return hex_contract_address @staticmethod def check_deploy_state(tx_hash, project_path:",
"import os import time import getpass from ontology.common.address import Address from ontology.ont_sdk import",
"= deploy_information.get('gasPrice', 500) ontology = OntologySdk() tx = ontology.neo_vm().make_deploy_transaction(hex_avm_code, need_storage, name, version, author,",
"handle_network_config(project_path, network, False) ontology = OntologySdk() ontology.rpc.set_address(rpc_address) time.sleep(6) tx = ontology.rpc.get_raw_transaction(tx_hash) if tx",
"'', avm_file_name: str = '') -> str: if avm_dir_path == '': avm_dir_path =",
"deploy_information.get('gasLimit', 21000000) gas_price = deploy_information.get('gasPrice', 500) ontology = OntologySdk() tx = ontology.neo_vm().make_deploy_transaction(hex_avm_code, need_storage,",
"= deploy_information.get('needStorage', True) name = deploy_information.get('name', os.path.split(project_path)[1]) version = deploy_information.get('version', '0.0.1') author =",
"'': project_path = os.getcwd() if not os.path.isdir(project_path): raise PunicaException(PunicaError.dir_path_error) rpc_address = handle_network_config(project_path, network,",
"ontology.rpc.set_address(rpc_address) tx_hash = ontology.rpc.send_raw_transaction(tx) return tx_hash else: print('\\tDeploy failed...') print('\\tContract has been deployed...')",
"avm_file_name = read_avm(avm_dir_path, avm_file_name) if hex_avm_code == '': raise PunicaException(PunicaError.avm_file_empty) hex_contract_address = Deploy.generate_contract_address(avm_dir_path,",
"ontology.neo_vm().make_deploy_transaction(hex_avm_code, need_storage, name, version, author, email, desc, b58_payer_address, gas_limit, gas_price) password = <PASSWORD>pass.getpass('\\tPlease",
"True) name = deploy_information.get('name', os.path.split(project_path)[1]) version = deploy_information.get('version', '0.0.1') author = deploy_information.get('author', '')",
"= handle_deploy_config(deploy_dir_path) need_storage = deploy_information.get('needStorage', True) name = deploy_information.get('name', os.path.split(project_path)[1]) version = deploy_information.get('version',",
"== '': avm_dir_path = os.path.join(os.getcwd(), 'build', 'contracts') if not os.path.isdir(avm_dir_path): raise PunicaException(PunicaError.dir_path_error) hex_avm_code",
"= OntologySdk() ontology.rpc.set_address(rpc_address) contract = ontology.rpc.get_smart_contract(hex_contract_address) print('Running deployment: {}'.format(avm_file_name)) if contract == 'unknow",
"'') -> str: if avm_dir_path == '': avm_dir_path = os.path.join(os.getcwd(), 'build', 'contracts') if",
"'': raise PunicaException(PunicaError.avm_file_empty) hex_contract_address = Deploy.generate_contract_address(avm_dir_path, avm_file_name) ontology = OntologySdk() ontology.rpc.set_address(rpc_address) contract =",
"time import getpass from ontology.common.address import Address from ontology.ont_sdk import OntologySdk from punica.utils.file_system",
"= os.getcwd() avm_dir_path = os.path.join(project_dir, 'contracts', 'build') rpc_address = handle_network_config(project_dir, network) hex_avm_code, avm_file_name",
"= wallet_manager.get_account(b58_payer_address, password) ontology.sign_transaction(tx, payer_acct) return tx @staticmethod def generate_contract_address(avm_dir_path: str = '',",
"= ''): if project_path == '': project_path = os.getcwd() if not os.path.isdir(project_path): raise",
"str = '', wallet_file_name: str = ''): wallet_dir_path = os.path.join(project_path, 'wallet') wallet_manager =",
"wallet_manager.get_account(b58_payer_address, password) ontology.sign_transaction(tx, payer_acct) return tx @staticmethod def generate_contract_address(avm_dir_path: str = '', avm_file_name:",
"if project_path == '': project_path = os.getcwd() if not os.path.isdir(project_path): raise PunicaException(PunicaError.dir_path_error) rpc_address",
"os.path.isdir(avm_dir_path): raise PunicaException(PunicaError.dir_path_error) hex_avm_code = read_avm(avm_dir_path, avm_file_name)[0] hex_contract_address = Address.address_from_vm_code(hex_avm_code).to_reverse_hex_str() return hex_contract_address @staticmethod",
"contract = ontology.rpc.get_smart_contract(hex_contract_address) print('Running deployment: {}'.format(avm_file_name)) if contract == 'unknow contracts': print('\\tDeploying...') print('\\t...",
"generate_signed_deploy_transaction(hex_avm_code: str, project_path: str = '', wallet_file_name: str = ''): wallet_dir_path = os.path.join(project_path,",
"== 'unknow contracts': print('\\tDeploying...') print('\\t... 0x{}'.format(hex_avm_code[:64])) tx = Deploy.generate_signed_deploy_transaction(hex_avm_code, project_dir, wallet_file_name) ontology.rpc.set_address(rpc_address) tx_hash",
"( handle_network_config, handle_deploy_config ) from punica.exception.punica_exception import PunicaException, PunicaError class Deploy: @staticmethod def",
"= Address.address_from_vm_code(hex_avm_code).to_reverse_hex_str() return hex_contract_address @staticmethod def check_deploy_state(tx_hash, project_path: str = '', network: str",
"network, False) ontology = OntologySdk() ontology.rpc.set_address(rpc_address) time.sleep(6) tx = ontology.rpc.get_raw_transaction(tx_hash) if tx ==",
"= ontology.rpc.get_raw_transaction(tx_hash) if tx == 'unknown transaction': return False else: return True @staticmethod",
"if tx == 'unknown transaction': return False else: return True @staticmethod def deploy_smart_contract(project_dir:",
"if hex_avm_code == '': raise PunicaException(PunicaError.avm_file_empty) hex_contract_address = Deploy.generate_contract_address(avm_dir_path, avm_file_name) ontology = OntologySdk()",
"contract == 'unknow contracts': print('\\tDeploying...') print('\\t... 0x{}'.format(hex_avm_code[:64])) tx = Deploy.generate_signed_deploy_transaction(hex_avm_code, project_dir, wallet_file_name) ontology.rpc.set_address(rpc_address)",
"ontology.rpc.send_raw_transaction(tx) return tx_hash else: print('\\tDeploy failed...') print('\\tContract has been deployed...') print('\\tContract address is",
"if avm_dir_path == '': avm_dir_path = os.path.join(os.getcwd(), 'build', 'contracts') if not os.path.isdir(avm_dir_path): raise",
"= deploy_information.get('desc', '') b58_payer_address = deploy_information.get('payer', wallet_manager.get_default_account().get_address()) gas_limit = deploy_information.get('gasLimit', 21000000) gas_price =",
"{}'.format(avm_file_name)) if contract == 'unknow contracts': print('\\tDeploying...') print('\\t... 0x{}'.format(hex_avm_code[:64])) tx = Deploy.generate_signed_deploy_transaction(hex_avm_code, project_dir,",
"= Deploy.generate_contract_address(avm_dir_path, avm_file_name) ontology = OntologySdk() ontology.rpc.set_address(rpc_address) contract = ontology.rpc.get_smart_contract(hex_contract_address) print('Running deployment: {}'.format(avm_file_name))",
"avm_file_name)[0] hex_contract_address = Address.address_from_vm_code(hex_avm_code).to_reverse_hex_str() return hex_contract_address @staticmethod def check_deploy_state(tx_hash, project_path: str = '',",
"= deploy_information.get('payer', wallet_manager.get_default_account().get_address()) gas_limit = deploy_information.get('gasLimit', 21000000) gas_price = deploy_information.get('gasPrice', 500) ontology =",
"ontology.sign_transaction(tx, payer_acct) return tx @staticmethod def generate_contract_address(avm_dir_path: str = '', avm_file_name: str =",
"str = ''): if project_dir == '': project_dir = os.getcwd() avm_dir_path = os.path.join(project_dir,",
"if contract == 'unknow contracts': print('\\tDeploying...') print('\\t... 0x{}'.format(hex_avm_code[:64])) tx = Deploy.generate_signed_deploy_transaction(hex_avm_code, project_dir, wallet_file_name)",
"deploy_information.get('name', os.path.split(project_path)[1]) version = deploy_information.get('version', '0.0.1') author = deploy_information.get('author', '') email = deploy_information.get('email',",
"from ontology.common.address import Address from ontology.ont_sdk import OntologySdk from punica.utils.file_system import ( read_avm,",
"avm_file_name: str = '', wallet_file_name: str = ''): if project_dir == '': project_dir",
"name, version, author, email, desc, b58_payer_address, gas_limit, gas_price) password = <PASSWORD>pass.getpass('\\tPlease input payer",
"return tx_hash else: print('\\tDeploy failed...') print('\\tContract has been deployed...') print('\\tContract address is 0x{}...'.format(hex_contract_address))",
"21000000) gas_price = deploy_information.get('gasPrice', 500) ontology = OntologySdk() tx = ontology.neo_vm().make_deploy_transaction(hex_avm_code, need_storage, name,",
"python3 # -*- coding: utf-8 -*- import os import time import getpass from",
"gas_price = deploy_information.get('gasPrice', 500) ontology = OntologySdk() tx = ontology.neo_vm().make_deploy_transaction(hex_avm_code, need_storage, name, version,",
"ontology.rpc.get_raw_transaction(tx_hash) if tx == 'unknown transaction': return False else: return True @staticmethod def",
"time.sleep(6) tx = ontology.rpc.get_raw_transaction(tx_hash) if tx == 'unknown transaction': return False else: return",
"str, project_path: str = '', wallet_file_name: str = ''): wallet_dir_path = os.path.join(project_path, 'wallet')",
"#!/usr/bin/env python3 # -*- coding: utf-8 -*- import os import time import getpass",
"ontology = OntologySdk() tx = ontology.neo_vm().make_deploy_transaction(hex_avm_code, need_storage, name, version, author, email, desc, b58_payer_address,",
"= deploy_information.get('email', '') desc = deploy_information.get('desc', '') b58_payer_address = deploy_information.get('payer', wallet_manager.get_default_account().get_address()) gas_limit =",
"if not os.path.isdir(avm_dir_path): raise PunicaException(PunicaError.dir_path_error) hex_avm_code = read_avm(avm_dir_path, avm_file_name)[0] hex_contract_address = Address.address_from_vm_code(hex_avm_code).to_reverse_hex_str() return",
"-*- import os import time import getpass from ontology.common.address import Address from ontology.ont_sdk",
"PunicaException(PunicaError.dir_path_error) hex_avm_code = read_avm(avm_dir_path, avm_file_name)[0] hex_contract_address = Address.address_from_vm_code(hex_avm_code).to_reverse_hex_str() return hex_contract_address @staticmethod def check_deploy_state(tx_hash,",
"raise PunicaException(PunicaError.dir_path_error) rpc_address = handle_network_config(project_path, network, False) ontology = OntologySdk() ontology.rpc.set_address(rpc_address) time.sleep(6) tx",
"OntologySdk() ontology.rpc.set_address(rpc_address) time.sleep(6) tx = ontology.rpc.get_raw_transaction(tx_hash) if tx == 'unknown transaction': return False",
"avm_file_name) if hex_avm_code == '': raise PunicaException(PunicaError.avm_file_empty) hex_contract_address = Deploy.generate_contract_address(avm_dir_path, avm_file_name) ontology =",
"import ( handle_network_config, handle_deploy_config ) from punica.exception.punica_exception import PunicaException, PunicaError class Deploy: @staticmethod",
"print('\\tDeploying...') print('\\t... 0x{}'.format(hex_avm_code[:64])) tx = Deploy.generate_signed_deploy_transaction(hex_avm_code, project_dir, wallet_file_name) ontology.rpc.set_address(rpc_address) tx_hash = ontology.rpc.send_raw_transaction(tx) return",
") from punica.utils.handle_config import ( handle_network_config, handle_deploy_config ) from punica.exception.punica_exception import PunicaException, PunicaError",
"read_avm, read_wallet ) from punica.utils.handle_config import ( handle_network_config, handle_deploy_config ) from punica.exception.punica_exception import",
"else: return True @staticmethod def deploy_smart_contract(project_dir: str = '', network: str = '',",
"deploy_information.get('email', '') desc = deploy_information.get('desc', '') b58_payer_address = deploy_information.get('payer', wallet_manager.get_default_account().get_address()) gas_limit = deploy_information.get('gasLimit',",
"'', wallet_file_name: str = ''): if project_dir == '': project_dir = os.getcwd() avm_dir_path",
"'') email = deploy_information.get('email', '') desc = deploy_information.get('desc', '') b58_payer_address = deploy_information.get('payer', wallet_manager.get_default_account().get_address())",
"-*- coding: utf-8 -*- import os import time import getpass from ontology.common.address import",
"= os.path.join(project_path, 'wallet') wallet_manager = read_wallet(wallet_dir_path, wallet_file_name) deploy_dir_path = os.path.join(project_path, 'contracts') deploy_information =",
"# -*- coding: utf-8 -*- import os import time import getpass from ontology.common.address",
"def generate_contract_address(avm_dir_path: str = '', avm_file_name: str = '') -> str: if avm_dir_path",
"False else: return True @staticmethod def deploy_smart_contract(project_dir: str = '', network: str =",
"= '', avm_file_name: str = '', wallet_file_name: str = ''): if project_dir ==",
"tx = Deploy.generate_signed_deploy_transaction(hex_avm_code, project_dir, wallet_file_name) ontology.rpc.set_address(rpc_address) tx_hash = ontology.rpc.send_raw_transaction(tx) return tx_hash else: print('\\tDeploy",
"wallet_file_name) ontology.rpc.set_address(rpc_address) tx_hash = ontology.rpc.send_raw_transaction(tx) return tx_hash else: print('\\tDeploy failed...') print('\\tContract has been",
"hex_contract_address = Address.address_from_vm_code(hex_avm_code).to_reverse_hex_str() return hex_contract_address @staticmethod def check_deploy_state(tx_hash, project_path: str = '', network:",
"OntologySdk from punica.utils.file_system import ( read_avm, read_wallet ) from punica.utils.handle_config import ( handle_network_config,",
"import time import getpass from ontology.common.address import Address from ontology.ont_sdk import OntologySdk from",
"deploy_dir_path = os.path.join(project_path, 'contracts') deploy_information = handle_deploy_config(deploy_dir_path) need_storage = deploy_information.get('needStorage', True) name =",
"'0.0.1') author = deploy_information.get('author', '') email = deploy_information.get('email', '') desc = deploy_information.get('desc', '')",
"PunicaException, PunicaError class Deploy: @staticmethod def generate_signed_deploy_transaction(hex_avm_code: str, project_path: str = '', wallet_file_name:",
"not os.path.isdir(avm_dir_path): raise PunicaException(PunicaError.dir_path_error) hex_avm_code = read_avm(avm_dir_path, avm_file_name)[0] hex_contract_address = Address.address_from_vm_code(hex_avm_code).to_reverse_hex_str() return hex_contract_address",
"''): if project_path == '': project_path = os.getcwd() if not os.path.isdir(project_path): raise PunicaException(PunicaError.dir_path_error)",
"= '', avm_file_name: str = '') -> str: if avm_dir_path == '': avm_dir_path",
"if project_dir == '': project_dir = os.getcwd() avm_dir_path = os.path.join(project_dir, 'contracts', 'build') rpc_address",
"ontology.rpc.get_smart_contract(hex_contract_address) print('Running deployment: {}'.format(avm_file_name)) if contract == 'unknow contracts': print('\\tDeploying...') print('\\t... 0x{}'.format(hex_avm_code[:64])) tx",
"Deploy.generate_signed_deploy_transaction(hex_avm_code, project_dir, wallet_file_name) ontology.rpc.set_address(rpc_address) tx_hash = ontology.rpc.send_raw_transaction(tx) return tx_hash else: print('\\tDeploy failed...') print('\\tContract",
"project_dir, wallet_file_name) ontology.rpc.set_address(rpc_address) tx_hash = ontology.rpc.send_raw_transaction(tx) return tx_hash else: print('\\tDeploy failed...') print('\\tContract has",
"deployment: {}'.format(avm_file_name)) if contract == 'unknow contracts': print('\\tDeploying...') print('\\t... 0x{}'.format(hex_avm_code[:64])) tx = Deploy.generate_signed_deploy_transaction(hex_avm_code,",
"wallet_file_name) deploy_dir_path = os.path.join(project_path, 'contracts') deploy_information = handle_deploy_config(deploy_dir_path) need_storage = deploy_information.get('needStorage', True) name",
"''): if project_dir == '': project_dir = os.getcwd() avm_dir_path = os.path.join(project_dir, 'contracts', 'build')",
"os.getcwd() avm_dir_path = os.path.join(project_dir, 'contracts', 'build') rpc_address = handle_network_config(project_dir, network) hex_avm_code, avm_file_name =",
"= <PASSWORD>pass.getpass('\\tPlease input payer account password: ') payer_acct = wallet_manager.get_account(b58_payer_address, password) ontology.sign_transaction(tx, payer_acct)",
"Deploy: @staticmethod def generate_signed_deploy_transaction(hex_avm_code: str, project_path: str = '', wallet_file_name: str = ''):",
"'', network: str = ''): if project_path == '': project_path = os.getcwd() if",
"== '': project_path = os.getcwd() if not os.path.isdir(project_path): raise PunicaException(PunicaError.dir_path_error) rpc_address = handle_network_config(project_path,",
"class Deploy: @staticmethod def generate_signed_deploy_transaction(hex_avm_code: str, project_path: str = '', wallet_file_name: str =",
"import OntologySdk from punica.utils.file_system import ( read_avm, read_wallet ) from punica.utils.handle_config import (",
"handle_deploy_config(deploy_dir_path) need_storage = deploy_information.get('needStorage', True) name = deploy_information.get('name', os.path.split(project_path)[1]) version = deploy_information.get('version', '0.0.1')",
"= deploy_information.get('name', os.path.split(project_path)[1]) version = deploy_information.get('version', '0.0.1') author = deploy_information.get('author', '') email =",
"rpc_address = handle_network_config(project_path, network, False) ontology = OntologySdk() ontology.rpc.set_address(rpc_address) time.sleep(6) tx = ontology.rpc.get_raw_transaction(tx_hash)",
"name = deploy_information.get('name', os.path.split(project_path)[1]) version = deploy_information.get('version', '0.0.1') author = deploy_information.get('author', '') email",
"'build') rpc_address = handle_network_config(project_dir, network) hex_avm_code, avm_file_name = read_avm(avm_dir_path, avm_file_name) if hex_avm_code ==",
"import PunicaException, PunicaError class Deploy: @staticmethod def generate_signed_deploy_transaction(hex_avm_code: str, project_path: str = '',",
"password) ontology.sign_transaction(tx, payer_acct) return tx @staticmethod def generate_contract_address(avm_dir_path: str = '', avm_file_name: str",
"os.getcwd() if not os.path.isdir(project_path): raise PunicaException(PunicaError.dir_path_error) rpc_address = handle_network_config(project_path, network, False) ontology =",
"@staticmethod def deploy_smart_contract(project_dir: str = '', network: str = '', avm_file_name: str =",
"Deploy.generate_contract_address(avm_dir_path, avm_file_name) ontology = OntologySdk() ontology.rpc.set_address(rpc_address) contract = ontology.rpc.get_smart_contract(hex_contract_address) print('Running deployment: {}'.format(avm_file_name)) if",
"OntologySdk() ontology.rpc.set_address(rpc_address) contract = ontology.rpc.get_smart_contract(hex_contract_address) print('Running deployment: {}'.format(avm_file_name)) if contract == 'unknow contracts':",
"return False else: return True @staticmethod def deploy_smart_contract(project_dir: str = '', network: str",
"= read_wallet(wallet_dir_path, wallet_file_name) deploy_dir_path = os.path.join(project_path, 'contracts') deploy_information = handle_deploy_config(deploy_dir_path) need_storage = deploy_information.get('needStorage',",
"need_storage, name, version, author, email, desc, b58_payer_address, gas_limit, gas_price) password = <PASSWORD>pass.getpass('\\tPlease input",
"PunicaException(PunicaError.dir_path_error) rpc_address = handle_network_config(project_path, network, False) ontology = OntologySdk() ontology.rpc.set_address(rpc_address) time.sleep(6) tx =",
"need_storage = deploy_information.get('needStorage', True) name = deploy_information.get('name', os.path.split(project_path)[1]) version = deploy_information.get('version', '0.0.1') author",
"str = '', network: str = '', avm_file_name: str = '', wallet_file_name: str",
"import ( read_avm, read_wallet ) from punica.utils.handle_config import ( handle_network_config, handle_deploy_config ) from",
"email, desc, b58_payer_address, gas_limit, gas_price) password = <PASSWORD>pass.getpass('\\tPlease input payer account password: ')",
"= handle_network_config(project_path, network, False) ontology = OntologySdk() ontology.rpc.set_address(rpc_address) time.sleep(6) tx = ontology.rpc.get_raw_transaction(tx_hash) if",
"gas_limit, gas_price) password = <PASSWORD>pass.getpass('\\tPlease input payer account password: ') payer_acct = wallet_manager.get_account(b58_payer_address,",
"= ontology.neo_vm().make_deploy_transaction(hex_avm_code, need_storage, name, version, author, email, desc, b58_payer_address, gas_limit, gas_price) password =",
"hex_avm_code == '': raise PunicaException(PunicaError.avm_file_empty) hex_contract_address = Deploy.generate_contract_address(avm_dir_path, avm_file_name) ontology = OntologySdk() ontology.rpc.set_address(rpc_address)",
"avm_file_name) ontology = OntologySdk() ontology.rpc.set_address(rpc_address) contract = ontology.rpc.get_smart_contract(hex_contract_address) print('Running deployment: {}'.format(avm_file_name)) if contract",
"= deploy_information.get('gasLimit', 21000000) gas_price = deploy_information.get('gasPrice', 500) ontology = OntologySdk() tx = ontology.neo_vm().make_deploy_transaction(hex_avm_code,",
"= OntologySdk() tx = ontology.neo_vm().make_deploy_transaction(hex_avm_code, need_storage, name, version, author, email, desc, b58_payer_address, gas_limit,",
"Address from ontology.ont_sdk import OntologySdk from punica.utils.file_system import ( read_avm, read_wallet ) from",
"version = deploy_information.get('version', '0.0.1') author = deploy_information.get('author', '') email = deploy_information.get('email', '') desc",
"PunicaException(PunicaError.avm_file_empty) hex_contract_address = Deploy.generate_contract_address(avm_dir_path, avm_file_name) ontology = OntologySdk() ontology.rpc.set_address(rpc_address) contract = ontology.rpc.get_smart_contract(hex_contract_address) print('Running",
"if not os.path.isdir(project_path): raise PunicaException(PunicaError.dir_path_error) rpc_address = handle_network_config(project_path, network, False) ontology = OntologySdk()",
"str = '', network: str = ''): if project_path == '': project_path =",
"'', avm_file_name: str = '', wallet_file_name: str = ''): if project_dir == '':",
"'contracts') if not os.path.isdir(avm_dir_path): raise PunicaException(PunicaError.dir_path_error) hex_avm_code = read_avm(avm_dir_path, avm_file_name)[0] hex_contract_address = Address.address_from_vm_code(hex_avm_code).to_reverse_hex_str()",
"<PASSWORD>pass.getpass('\\tPlease input payer account password: ') payer_acct = wallet_manager.get_account(b58_payer_address, password) ontology.sign_transaction(tx, payer_acct) return",
"deploy_information.get('gasPrice', 500) ontology = OntologySdk() tx = ontology.neo_vm().make_deploy_transaction(hex_avm_code, need_storage, name, version, author, email,",
"rpc_address = handle_network_config(project_dir, network) hex_avm_code, avm_file_name = read_avm(avm_dir_path, avm_file_name) if hex_avm_code == '':",
"'', network: str = '', avm_file_name: str = '', wallet_file_name: str = ''):",
"str = '', wallet_file_name: str = ''): if project_dir == '': project_dir =",
"str = ''): wallet_dir_path = os.path.join(project_path, 'wallet') wallet_manager = read_wallet(wallet_dir_path, wallet_file_name) deploy_dir_path =",
"wallet_file_name: str = ''): if project_dir == '': project_dir = os.getcwd() avm_dir_path =",
"= '') -> str: if avm_dir_path == '': avm_dir_path = os.path.join(os.getcwd(), 'build', 'contracts')",
"print('\\t... 0x{}'.format(hex_avm_code[:64])) tx = Deploy.generate_signed_deploy_transaction(hex_avm_code, project_dir, wallet_file_name) ontology.rpc.set_address(rpc_address) tx_hash = ontology.rpc.send_raw_transaction(tx) return tx_hash",
"tx_hash = ontology.rpc.send_raw_transaction(tx) return tx_hash else: print('\\tDeploy failed...') print('\\tContract has been deployed...') print('\\tContract",
"not os.path.isdir(project_path): raise PunicaException(PunicaError.dir_path_error) rpc_address = handle_network_config(project_path, network, False) ontology = OntologySdk() ontology.rpc.set_address(rpc_address)",
"wallet_manager.get_default_account().get_address()) gas_limit = deploy_information.get('gasLimit', 21000000) gas_price = deploy_information.get('gasPrice', 500) ontology = OntologySdk() tx",
"from punica.exception.punica_exception import PunicaException, PunicaError class Deploy: @staticmethod def generate_signed_deploy_transaction(hex_avm_code: str, project_path: str",
"= '', wallet_file_name: str = ''): wallet_dir_path = os.path.join(project_path, 'wallet') wallet_manager = read_wallet(wallet_dir_path,",
"os.path.isdir(project_path): raise PunicaException(PunicaError.dir_path_error) rpc_address = handle_network_config(project_path, network, False) ontology = OntologySdk() ontology.rpc.set_address(rpc_address) time.sleep(6)",
"account password: ') payer_acct = wallet_manager.get_account(b58_payer_address, password) ontology.sign_transaction(tx, payer_acct) return tx @staticmethod def",
"hex_contract_address = Deploy.generate_contract_address(avm_dir_path, avm_file_name) ontology = OntologySdk() ontology.rpc.set_address(rpc_address) contract = ontology.rpc.get_smart_contract(hex_contract_address) print('Running deployment:",
"author, email, desc, b58_payer_address, gas_limit, gas_price) password = <PASSWORD>pass.getpass('\\tPlease input payer account password:",
"-> str: if avm_dir_path == '': avm_dir_path = os.path.join(os.getcwd(), 'build', 'contracts') if not",
"= os.getcwd() if not os.path.isdir(project_path): raise PunicaException(PunicaError.dir_path_error) rpc_address = handle_network_config(project_path, network, False) ontology",
"b58_payer_address = deploy_information.get('payer', wallet_manager.get_default_account().get_address()) gas_limit = deploy_information.get('gasLimit', 21000000) gas_price = deploy_information.get('gasPrice', 500) ontology",
"= ''): wallet_dir_path = os.path.join(project_path, 'wallet') wallet_manager = read_wallet(wallet_dir_path, wallet_file_name) deploy_dir_path = os.path.join(project_path,",
"punica.utils.handle_config import ( handle_network_config, handle_deploy_config ) from punica.exception.punica_exception import PunicaException, PunicaError class Deploy:",
"gas_price) password = <PASSWORD>pass.getpass('\\tPlease input payer account password: ') payer_acct = wallet_manager.get_account(b58_payer_address, password)",
"= deploy_information.get('version', '0.0.1') author = deploy_information.get('author', '') email = deploy_information.get('email', '') desc =",
"version, author, email, desc, b58_payer_address, gas_limit, gas_price) password = <PASSWORD>pass.getpass('\\tPlease input payer account",
"password: ') payer_acct = wallet_manager.get_account(b58_payer_address, password) ontology.sign_transaction(tx, payer_acct) return tx @staticmethod def generate_contract_address(avm_dir_path:",
"handle_network_config, handle_deploy_config ) from punica.exception.punica_exception import PunicaException, PunicaError class Deploy: @staticmethod def generate_signed_deploy_transaction(hex_avm_code:",
"ontology.rpc.set_address(rpc_address) time.sleep(6) tx = ontology.rpc.get_raw_transaction(tx_hash) if tx == 'unknown transaction': return False else:",
"tx == 'unknown transaction': return False else: return True @staticmethod def deploy_smart_contract(project_dir: str",
"'': project_dir = os.getcwd() avm_dir_path = os.path.join(project_dir, 'contracts', 'build') rpc_address = handle_network_config(project_dir, network)",
"tx @staticmethod def generate_contract_address(avm_dir_path: str = '', avm_file_name: str = '') -> str:",
"avm_dir_path = os.path.join(project_dir, 'contracts', 'build') rpc_address = handle_network_config(project_dir, network) hex_avm_code, avm_file_name = read_avm(avm_dir_path,",
"str = ''): if project_path == '': project_path = os.getcwd() if not os.path.isdir(project_path):",
"os.path.join(project_path, 'wallet') wallet_manager = read_wallet(wallet_dir_path, wallet_file_name) deploy_dir_path = os.path.join(project_path, 'contracts') deploy_information = handle_deploy_config(deploy_dir_path)",
"= deploy_information.get('author', '') email = deploy_information.get('email', '') desc = deploy_information.get('desc', '') b58_payer_address =",
"from ontology.ont_sdk import OntologySdk from punica.utils.file_system import ( read_avm, read_wallet ) from punica.utils.handle_config",
"'contracts') deploy_information = handle_deploy_config(deploy_dir_path) need_storage = deploy_information.get('needStorage', True) name = deploy_information.get('name', os.path.split(project_path)[1]) version",
"payer account password: ') payer_acct = wallet_manager.get_account(b58_payer_address, password) ontology.sign_transaction(tx, payer_acct) return tx @staticmethod",
"avm_file_name: str = '') -> str: if avm_dir_path == '': avm_dir_path = os.path.join(os.getcwd(),",
"b58_payer_address, gas_limit, gas_price) password = <PASSWORD>pass.getpass('\\tPlease input payer account password: ') payer_acct =",
"== 'unknown transaction': return False else: return True @staticmethod def deploy_smart_contract(project_dir: str =",
"True @staticmethod def deploy_smart_contract(project_dir: str = '', network: str = '', avm_file_name: str",
"avm_dir_path = os.path.join(os.getcwd(), 'build', 'contracts') if not os.path.isdir(avm_dir_path): raise PunicaException(PunicaError.dir_path_error) hex_avm_code = read_avm(avm_dir_path,",
"network: str = '', avm_file_name: str = '', wallet_file_name: str = ''): if"
] |
[
"like Gecko) Chrome/39.0.2171.95 Safari/537.36', 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8', 'Referer': 'http://www.wikipedia.org/', 'Connection': 'keep-alive', } #Know let",
"requests from bs4 import BeautifulSoup import urllib.request url = input(\"Paste the website url",
"(KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36', 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8', 'Referer': 'http://www.wikipedia.org/', 'Connection': 'keep-alive', } #Know",
"work on where to save the images AND also saving all the images",
"version i will produce an application which will make it a cross platform",
"on the website type print(img) img_t = img.get('src') #To fetch for the link",
"else: img_path = img_t print(img_path) if '.png' in img_path: with open(\"{}.png\".format(index), 'wb') as",
"} #Know let make our request from the website res = requests.get(url=url, headers=headers)",
"let make our request from the website res = requests.get(url=url, headers=headers) #To confirm",
"soup = BeautifulSoup(res.text, 'html.parser') index = 0 for img in soup.findAll('img'): index +=",
"index = 0 for img in soup.findAll('img'): index += 1 #To fetch all",
"saveImg.write(requests.get(url = img_path).content) print(img_path) else: pass #Later on i will work on where",
"'.png' in img_path: with open(\"{}.png\".format(index), 'wb') as saveImg: saveImg.write(requests.get(url = img_path).content) print(img_path) else:",
"= requests.get(url=url, headers=headers) #To confirm that the website wont block you. #Type print(res)",
"all the images in a txt file #In the later version i will",
"link for the images type print(img_t) if img_t[:1] == '/': img_path = url",
"to use beautiful soup soup = BeautifulSoup(res.text, 'html.parser') index = 0 for img",
"Heccubernny 2020 # Licence: CRSPIP licence #------------------------------------------------------------------------------- import requests from bs4 import BeautifulSoup",
"website url here: \") #To avoid the website from blocking you #Visit https://curl.trillworks.com/",
"'wb') as saveImg: saveImg.write(requests.get(url = img_path).content) print(img_path) else: pass #Later on i will",
"the link for the images type print(img_t) if img_t[:1] == '/': img_path =",
"Copyright: (c) Heccubernny 2020 # Licence: CRSPIP licence #------------------------------------------------------------------------------- import requests from bs4",
"for the link for the images type print(img_t) if img_t[:1] == '/': img_path",
"the later version i will produce an application which will make it a",
"img_path = url + img_t else: img_path = img_t print(img_path) if '.png' in",
"#To fetch for the link for the images type print(img_t) if img_t[:1] ==",
"(Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36', 'Accept':",
"txt file #In the later version i will produce an application which will",
"code on the website type print(img) img_t = img.get('src') #To fetch for the",
"make our request from the website res = requests.get(url=url, headers=headers) #To confirm that",
"AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36', 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8', 'Referer': 'http://www.wikipedia.org/', 'Connection': 'keep-alive', }",
"of any image from any website link # # Author: Heccubernny # #",
"'Accept-Encoding': 'gzip, deflate, sdch', 'Accept-Language': 'en-US,en;q=0.8', 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X",
"#To fetch all the images sources code on the website type print(img) img_t",
"block you. #Type print(res) #Now we are going to use beautiful soup soup",
"\") #To avoid the website from blocking you #Visit https://curl.trillworks.com/ headers = {",
"17/04/2020 # Copyright: (c) Heccubernny 2020 # Licence: CRSPIP licence #------------------------------------------------------------------------------- import requests",
"else: pass #Later on i will work on where to save the images",
"{ 'Accept-Encoding': 'gzip, deflate, sdch', 'Accept-Language': 'en-US,en;q=0.8', 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS",
"https://curl.trillworks.com/ headers = { 'Accept-Encoding': 'gzip, deflate, sdch', 'Accept-Language': 'en-US,en;q=0.8', 'User-Agent': 'Mozilla/5.0 (Macintosh;",
"file #In the later version i will produce an application which will make",
"images and save links of any image from any website link # #",
"# # Created: 17/04/2020 # Copyright: (c) Heccubernny 2020 # Licence: CRSPIP licence",
"link # # Author: Heccubernny # # Created: 17/04/2020 # Copyright: (c) Heccubernny",
"urllib.request url = input(\"Paste the website url here: \") #To avoid the website",
"'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95",
"'keep-alive', } #Know let make our request from the website res = requests.get(url=url,",
"the images in a txt file #In the later version i will produce",
"'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8', 'Referer': 'http://www.wikipedia.org/', 'Connection': 'keep-alive', } #Know let make our request from the",
"import BeautifulSoup import urllib.request url = input(\"Paste the website url here: \") #To",
"confirm that the website wont block you. #Type print(res) #Now we are going",
"website wont block you. #Type print(res) #Now we are going to use beautiful",
"soup.findAll('img'): index += 1 #To fetch all the images sources code on the",
"img_path: with open(\"{}.png\".format(index), 'wb') as saveImg: saveImg.write(requests.get(url = img_path).content) print(img_path) else: pass #Later",
"beautiful soup soup = BeautifulSoup(res.text, 'html.parser') index = 0 for img in soup.findAll('img'):",
"for the images type print(img_t) if img_t[:1] == '/': img_path = url +",
"'Referer': 'http://www.wikipedia.org/', 'Connection': 'keep-alive', } #Know let make our request from the website",
"print(img_path) if '.png' in img_path: with open(\"{}.png\".format(index), 'wb') as saveImg: saveImg.write(requests.get(url = img_path).content)",
"#In the later version i will produce an application which will make it",
"in soup.findAll('img'): index += 1 #To fetch all the images sources code on",
"'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36',",
"any image from any website link # # Author: Heccubernny # # Created:",
"print(res) #Now we are going to use beautiful soup soup = BeautifulSoup(res.text, 'html.parser')",
"= url + img_t else: img_path = img_t print(img_path) if '.png' in img_path:",
"AND also saving all the images in a txt file #In the later",
"website from blocking you #Visit https://curl.trillworks.com/ headers = { 'Accept-Encoding': 'gzip, deflate, sdch',",
"#To confirm that the website wont block you. #Type print(res) #Now we are",
"img_t else: img_path = img_t print(img_path) if '.png' in img_path: with open(\"{}.png\".format(index), 'wb')",
"if '.png' in img_path: with open(\"{}.png\".format(index), 'wb') as saveImg: saveImg.write(requests.get(url = img_path).content) print(img_path)",
"images type print(img_t) if img_t[:1] == '/': img_path = url + img_t else:",
"later version i will produce an application which will make it a cross",
"#Visit https://curl.trillworks.com/ headers = { 'Accept-Encoding': 'gzip, deflate, sdch', 'Accept-Language': 'en-US,en;q=0.8', 'User-Agent': 'Mozilla/5.0",
"deflate, sdch', 'Accept-Language': 'en-US,en;q=0.8', 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36",
"from blocking you #Visit https://curl.trillworks.com/ headers = { 'Accept-Encoding': 'gzip, deflate, sdch', 'Accept-Language':",
"1 #To fetch all the images sources code on the website type print(img)",
"Downloader # Purpose: To download images and save links of any image from",
"fetch all the images sources code on the website type print(img) img_t =",
"# Name: Image Downloader # Purpose: To download images and save links of",
"use beautiful soup soup = BeautifulSoup(res.text, 'html.parser') index = 0 for img in",
"soup soup = BeautifulSoup(res.text, 'html.parser') index = 0 for img in soup.findAll('img'): index",
"type print(img) img_t = img.get('src') #To fetch for the link for the images",
"website type print(img) img_t = img.get('src') #To fetch for the link for the",
"img.get('src') #To fetch for the link for the images type print(img_t) if img_t[:1]",
"in img_path: with open(\"{}.png\".format(index), 'wb') as saveImg: saveImg.write(requests.get(url = img_path).content) print(img_path) else: pass",
"website link # # Author: Heccubernny # # Created: 17/04/2020 # Copyright: (c)",
"#To avoid the website from blocking you #Visit https://curl.trillworks.com/ headers = { 'Accept-Encoding':",
"open(\"{}.png\".format(index), 'wb') as saveImg: saveImg.write(requests.get(url = img_path).content) print(img_path) else: pass #Later on i",
"pass #Later on i will work on where to save the images AND",
"BeautifulSoup(res.text, 'html.parser') index = 0 for img in soup.findAll('img'): index += 1 #To",
"headers=headers) #To confirm that the website wont block you. #Type print(res) #Now we",
"Created: 17/04/2020 # Copyright: (c) Heccubernny 2020 # Licence: CRSPIP licence #------------------------------------------------------------------------------- import",
"in a txt file #In the later version i will produce an application",
"headers = { 'Accept-Encoding': 'gzip, deflate, sdch', 'Accept-Language': 'en-US,en;q=0.8', 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel",
"the website res = requests.get(url=url, headers=headers) #To confirm that the website wont block",
"#Now we are going to use beautiful soup soup = BeautifulSoup(res.text, 'html.parser') index",
"url + img_t else: img_path = img_t print(img_path) if '.png' in img_path: with",
"#------------------------------------------------------------------------------- # Name: Image Downloader # Purpose: To download images and save links",
"print(img_path) else: pass #Later on i will work on where to save the",
"bs4 import BeautifulSoup import urllib.request url = input(\"Paste the website url here: \")",
"images AND also saving all the images in a txt file #In the",
"= 0 for img in soup.findAll('img'): index += 1 #To fetch all the",
"# Author: Heccubernny # # Created: 17/04/2020 # Copyright: (c) Heccubernny 2020 #",
"(c) Heccubernny 2020 # Licence: CRSPIP licence #------------------------------------------------------------------------------- import requests from bs4 import",
"= img_path).content) print(img_path) else: pass #Later on i will work on where to",
"Image Downloader # Purpose: To download images and save links of any image",
"X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36', 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8', 'Referer': 'http://www.wikipedia.org/', 'Connection':",
"fetch for the link for the images type print(img_t) if img_t[:1] == '/':",
"img_path).content) print(img_path) else: pass #Later on i will work on where to save",
"# Copyright: (c) Heccubernny 2020 # Licence: CRSPIP licence #------------------------------------------------------------------------------- import requests from",
"res = requests.get(url=url, headers=headers) #To confirm that the website wont block you. #Type",
"requests.get(url=url, headers=headers) #To confirm that the website wont block you. #Type print(res) #Now",
"website res = requests.get(url=url, headers=headers) #To confirm that the website wont block you.",
"are going to use beautiful soup soup = BeautifulSoup(res.text, 'html.parser') index = 0",
"'http://www.wikipedia.org/', 'Connection': 'keep-alive', } #Know let make our request from the website res",
"Gecko) Chrome/39.0.2171.95 Safari/537.36', 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8', 'Referer': 'http://www.wikipedia.org/', 'Connection': 'keep-alive', } #Know let make",
"saving all the images in a txt file #In the later version i",
"from bs4 import BeautifulSoup import urllib.request url = input(\"Paste the website url here:",
"links of any image from any website link # # Author: Heccubernny #",
"#Know let make our request from the website res = requests.get(url=url, headers=headers) #To",
"# Purpose: To download images and save links of any image from any",
"0 for img in soup.findAll('img'): index += 1 #To fetch all the images",
"input(\"Paste the website url here: \") #To avoid the website from blocking you",
"the images type print(img_t) if img_t[:1] == '/': img_path = url + img_t",
"import requests from bs4 import BeautifulSoup import urllib.request url = input(\"Paste the website",
"Purpose: To download images and save links of any image from any website",
"Name: Image Downloader # Purpose: To download images and save links of any",
"import urllib.request url = input(\"Paste the website url here: \") #To avoid the",
"'Connection': 'keep-alive', } #Know let make our request from the website res =",
"download images and save links of any image from any website link #",
"will work on where to save the images AND also saving all the",
"blocking you #Visit https://curl.trillworks.com/ headers = { 'Accept-Encoding': 'gzip, deflate, sdch', 'Accept-Language': 'en-US,en;q=0.8',",
"Author: Heccubernny # # Created: 17/04/2020 # Copyright: (c) Heccubernny 2020 # Licence:",
"img in soup.findAll('img'): index += 1 #To fetch all the images sources code",
"OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36', 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8', 'Referer': 'http://www.wikipedia.org/',",
"save the images AND also saving all the images in a txt file",
"img_path = img_t print(img_path) if '.png' in img_path: with open(\"{}.png\".format(index), 'wb') as saveImg:",
"here: \") #To avoid the website from blocking you #Visit https://curl.trillworks.com/ headers =",
"'en-US,en;q=0.8', 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko)",
"2020 # Licence: CRSPIP licence #------------------------------------------------------------------------------- import requests from bs4 import BeautifulSoup import",
"+= 1 #To fetch all the images sources code on the website type",
"type print(img_t) if img_t[:1] == '/': img_path = url + img_t else: img_path",
"# Created: 17/04/2020 # Copyright: (c) Heccubernny 2020 # Licence: CRSPIP licence #-------------------------------------------------------------------------------",
"+ img_t else: img_path = img_t print(img_path) if '.png' in img_path: with open(\"{}.png\".format(index),",
"images in a txt file #In the later version i will produce an",
"'gzip, deflate, sdch', 'Accept-Language': 'en-US,en;q=0.8', 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1)",
"for img in soup.findAll('img'): index += 1 #To fetch all the images sources",
"'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8', 'Referer': 'http://www.wikipedia.org/', 'Connection': 'keep-alive', } #Know let make our request from",
"we are going to use beautiful soup soup = BeautifulSoup(res.text, 'html.parser') index =",
"CRSPIP licence #------------------------------------------------------------------------------- import requests from bs4 import BeautifulSoup import urllib.request url =",
"going to use beautiful soup soup = BeautifulSoup(res.text, 'html.parser') index = 0 for",
"url = input(\"Paste the website url here: \") #To avoid the website from",
"Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36', 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',",
"the website wont block you. #Type print(res) #Now we are going to use",
"you #Visit https://curl.trillworks.com/ headers = { 'Accept-Encoding': 'gzip, deflate, sdch', 'Accept-Language': 'en-US,en;q=0.8', 'User-Agent':",
"= { 'Accept-Encoding': 'gzip, deflate, sdch', 'Accept-Language': 'en-US,en;q=0.8', 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac",
"the website url here: \") #To avoid the website from blocking you #Visit",
"print(img_t) if img_t[:1] == '/': img_path = url + img_t else: img_path =",
"# Licence: CRSPIP licence #------------------------------------------------------------------------------- import requests from bs4 import BeautifulSoup import urllib.request",
"= img_t print(img_path) if '.png' in img_path: with open(\"{}.png\".format(index), 'wb') as saveImg: saveImg.write(requests.get(url",
"= BeautifulSoup(res.text, 'html.parser') index = 0 for img in soup.findAll('img'): index += 1",
"saveImg: saveImg.write(requests.get(url = img_path).content) print(img_path) else: pass #Later on i will work on",
"#Later on i will work on where to save the images AND also",
"Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36', 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8', 'Referer':",
"all the images sources code on the website type print(img) img_t = img.get('src')",
"on i will work on where to save the images AND also saving",
"the images AND also saving all the images in a txt file #In",
"on where to save the images AND also saving all the images in",
"index += 1 #To fetch all the images sources code on the website",
"with open(\"{}.png\".format(index), 'wb') as saveImg: saveImg.write(requests.get(url = img_path).content) print(img_path) else: pass #Later on",
"#Type print(res) #Now we are going to use beautiful soup soup = BeautifulSoup(res.text,",
"the website type print(img) img_t = img.get('src') #To fetch for the link for",
"also saving all the images in a txt file #In the later version",
"the website from blocking you #Visit https://curl.trillworks.com/ headers = { 'Accept-Encoding': 'gzip, deflate,",
"where to save the images AND also saving all the images in a",
"i will work on where to save the images AND also saving all",
"images sources code on the website type print(img) img_t = img.get('src') #To fetch",
"Licence: CRSPIP licence #------------------------------------------------------------------------------- import requests from bs4 import BeautifulSoup import urllib.request url",
"= img.get('src') #To fetch for the link for the images type print(img_t) if",
"the images sources code on the website type print(img) img_t = img.get('src') #To",
"to save the images AND also saving all the images in a txt",
"a txt file #In the later version i will produce an application which",
"Chrome/39.0.2171.95 Safari/537.36', 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8', 'Referer': 'http://www.wikipedia.org/', 'Connection': 'keep-alive', } #Know let make our",
"'html.parser') index = 0 for img in soup.findAll('img'): index += 1 #To fetch",
"10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36', 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8', 'Referer': 'http://www.wikipedia.org/', 'Connection': 'keep-alive',",
"as saveImg: saveImg.write(requests.get(url = img_path).content) print(img_path) else: pass #Later on i will work",
"sdch', 'Accept-Language': 'en-US,en;q=0.8', 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML,",
"Safari/537.36', 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8', 'Referer': 'http://www.wikipedia.org/', 'Connection': 'keep-alive', } #Know let make our request",
"and save links of any image from any website link # # Author:",
"avoid the website from blocking you #Visit https://curl.trillworks.com/ headers = { 'Accept-Encoding': 'gzip,",
"that the website wont block you. #Type print(res) #Now we are going to",
"licence #------------------------------------------------------------------------------- import requests from bs4 import BeautifulSoup import urllib.request url = input(\"Paste",
"save links of any image from any website link # # Author: Heccubernny",
"url here: \") #To avoid the website from blocking you #Visit https://curl.trillworks.com/ headers",
"# # Author: Heccubernny # # Created: 17/04/2020 # Copyright: (c) Heccubernny 2020",
"from any website link # # Author: Heccubernny # # Created: 17/04/2020 #",
"wont block you. #Type print(res) #Now we are going to use beautiful soup",
"== '/': img_path = url + img_t else: img_path = img_t print(img_path) if",
"'Accept-Language': 'en-US,en;q=0.8', 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like",
"img_t = img.get('src') #To fetch for the link for the images type print(img_t)",
"#------------------------------------------------------------------------------- import requests from bs4 import BeautifulSoup import urllib.request url = input(\"Paste the",
"img_t[:1] == '/': img_path = url + img_t else: img_path = img_t print(img_path)",
"image from any website link # # Author: Heccubernny # # Created: 17/04/2020",
"'/': img_path = url + img_t else: img_path = img_t print(img_path) if '.png'",
"img_t print(img_path) if '.png' in img_path: with open(\"{}.png\".format(index), 'wb') as saveImg: saveImg.write(requests.get(url =",
"BeautifulSoup import urllib.request url = input(\"Paste the website url here: \") #To avoid",
"<gh_stars>0 #------------------------------------------------------------------------------- # Name: Image Downloader # Purpose: To download images and save",
"Heccubernny # # Created: 17/04/2020 # Copyright: (c) Heccubernny 2020 # Licence: CRSPIP",
"our request from the website res = requests.get(url=url, headers=headers) #To confirm that the",
"if img_t[:1] == '/': img_path = url + img_t else: img_path = img_t",
"request from the website res = requests.get(url=url, headers=headers) #To confirm that the website",
"sources code on the website type print(img) img_t = img.get('src') #To fetch for",
"from the website res = requests.get(url=url, headers=headers) #To confirm that the website wont",
"print(img) img_t = img.get('src') #To fetch for the link for the images type",
"= input(\"Paste the website url here: \") #To avoid the website from blocking",
"any website link # # Author: Heccubernny # # Created: 17/04/2020 # Copyright:",
"To download images and save links of any image from any website link",
"you. #Type print(res) #Now we are going to use beautiful soup soup ="
] |
[
"[] voxel_idxs = [] train_txtpath = os.path.join(voxel_txt_dir, 'train.txt') val_txtpath = os.path.join(voxel_txt_dir, 'val.txt') test_txtpath",
"= os.path.join(voxel_txt_dir, 'voxel_train.txt') voxel_val_txtpath = os.path.join(voxel_txt_dir, 'voxel_val.txt') voxel_test_txtpath = os.path.join(voxel_txt_dir, 'voxel_test.txt') voxel_ftrain =",
"random.random() if tmp < 0.65: ftrain.write(img_file+'\\n') ctrain += 1 elif tmp >= 0.65",
"if __name__ == '__main__': cls_all = ['chair', 'bed', 'bookcase', 'desk', 'misc', 'sofa', 'table',",
"'voxel_idxs': np.array(voxel_idxs)}) print(voxel_ctrain+voxel_cval+voxel_ctest, voxel_ctrain, voxel_cval, voxel_ctest) print(ctrain+cval+ctest, ctrain, cval, ctest) print(len(img_idxs)) if __name__",
"img_id != len(img_voxel_idxs): # print('Error!!!=======', img_id) if split_by_model: if voxel_dir in voxel_ltrain: ftrain.write(img_file+'\\n')",
"val_txtpath = os.path.join(voxel_txt_dir, 'val.txt') test_txtpath = os.path.join(voxel_txt_dir, 'test.txt') ftrain = open(train_txtpath, 'w') fval",
"'img_voxel_idxs.mat'), {'img_idxs': np.array(img_idxs), 'voxel_idxs': np.array(voxel_idxs)}) print(voxel_ctrain+voxel_cval+voxel_ctest, voxel_ctrain, voxel_cval, voxel_ctest) print(ctrain+cval+ctest, ctrain, cval, ctest)",
">= 0.65 and tmp < 0.8: fval.write(img_file+'\\n') cval += 1 else: ftest.write(img_file+'\\n') ctest",
"if json_file[i]['img'][4:9] == 'chair' and json_file[i]['voxel'] not in voxel_dirs: # print(json_file[i]['img'], json_file[i]['voxel']) voxel_dir",
"'chair' and json_file[i]['voxel'] not in voxel_dirs: # print(json_file[i]['img'], json_file[i]['voxel']) voxel_dir = pix3d[i]['voxel'][6:] if",
"['train', 'val', 'test']: with open(os.path.join(voxel_dirs[phase]), 'r') as f: voxel_names[phase] = f.readlines() with open(os.path.join(img_dirs[phase]),",
"for x in ['train', 'val', 'test']} with open(os.path.join(out_dir, 'voxels_dir_{}.txt'.format(cls)), 'r') as f: voxel_all",
"f.readlines() # pix3d_dir = os.path.join(root, '../input/pix3d.json') # pix3d = json.load(open(pix3d_dir, 'r')) match_id =",
"print(name) for name in img_match_vox[phase]: if name not in voxel_names[phase]: print(name) def split_voxel_then_image(cls):",
"for name in img_match_vox[phase]: if name not in voxel_names[phase]: print(name) def split_voxel_then_image(cls): #",
"+= 1 voxel_ftrain.close() voxel_fval.close() voxel_ftest.close() ## split images into train, val, test, according",
"if name not in voxel_names[phase]: print(name) def split_voxel_then_image(cls): # data_dir = '/Users/heqian/Research/projects/3dprnn/data/pix3d' split_by_model",
"['train', 'val', 'test']} with open(os.path.join(out_dir, 'voxels_dir_{}.txt'.format(cls)), 'r') as f: voxel_all = f.readlines() voxel_names",
"'test']} img_dirs = {x: os.path.join(voxel_txt_dir, '{}.txt'.format(x)) for x in ['train', 'val', 'test']} with",
"f.readlines() for i in range(len(voxel_dirs)): voxel_dirs[i] = voxel_dirs[i].strip() voxel_dirs[i] = voxel_dirs[i] tmp =",
"split_voxel_then_image(cls): # data_dir = '/Users/heqian/Research/projects/3dprnn/data/pix3d' split_by_model = True # True-split by 216 models,",
"voxel_dirs[i] = voxel_dirs[i] tmp = random.random() if tmp < 0.65: voxel_ftrain.write(voxel_dirs[i]+'\\n') voxel_ltrain.append(voxel_dirs[i]) voxel_ctrain",
"if tmp < 0.65: ftrain.write(img_file+'\\n') ctrain += 1 elif tmp >= 0.65 and",
"fval.write(img_file+'\\n') cval += 1 else: ftest.write(img_file+'\\n') ctest += 1 ftrain.close() fval.close() ftest.close() #",
"voxel_fval.close() voxel_ftest.close() ## split images into train, val, test, according to voxels #",
"img_names[phase] = f.readlines() # pix3d_dir = os.path.join(root, '../input/pix3d.json') # pix3d = json.load(open(pix3d_dir, 'r'))",
"not in img_match_vox[phase]: print(name) for name in img_match_vox[phase]: if name not in voxel_names[phase]:",
"open(voxel_train_txtpath, 'w') voxel_fval = open(voxel_val_txtpath, 'w') voxel_ftest = open(voxel_test_txtpath, 'w') voxel_ltrain = []",
"ctrain, cval, ctest) print(len(img_idxs)) if __name__ == '__main__': cls_all = ['chair', 'bed', 'bookcase',",
"test root = os.path.abspath('.') out_dir = os.path.join(root, '../output', cls) voxel_txt_dir = os.path.join(out_dir, 'voxeltxt')",
"voxel_dirs: # pdb.set_trace() img_file = pix3d[i]['img'].split('/')[-1] #[10:] img_id = int(img_file.split('.')[0]) #int(pix3d[i]['img'][10:14]) img_idxs.append(img_id) voxel_idxs.append(voxel_dirs.index(voxel_dir)",
"= os.path.join(root, '../input/pix3d.json') # pix3d = json.load(open(pix3d_dir, 'r')) match_id = scipy.io.loadmat(os.path.join(out_dir, 'img_voxel_idxs.mat')) img_match_vox",
"1) # img_voxel_idxs.append(voxel_dirs.index(voxel_dir)) # if img_id != len(img_voxel_idxs): # print('Error!!!=======', img_id) if split_by_model:",
"split images into train, val, test, according to voxels # img_voxel_idxs = []",
"img_match_vox[phase]: if name not in voxel_names[phase]: print(name) def split_voxel_then_image(cls): # data_dir = '/Users/heqian/Research/projects/3dprnn/data/pix3d'",
"cval = 0 ctest = 0 pix3d_dir = os.path.join(root, '../input/pix3d.json') pix3d = json.load(open(pix3d_dir,",
"with open(os.path.join(out_dir, 'voxels_dir_{}.txt'.format(cls)), 'r') as f: voxel_dirs = f.readlines() for i in range(len(voxel_dirs)):",
"= os.path.join(root, '../output', cls) # out_dir = '/Users/heqian/Research/projects/primitive-based_3d/data/all_classes/chair' voxel_txt_dir = os.path.join(out_dir, 'voxeltxt') voxel_dirs",
"match_id['voxel_idxs'][0, img_id_real] # 1-216 vox = voxel_all[voxel_id_ori - 1] img_match_vox[phase].append(vox) # img_match_vox[phase].append('model/'+vox) img_match_vox",
"= random.random() if tmp < 0.65: voxel_ftrain.write(voxel_dirs[i]+'\\n') voxel_ltrain.append(voxel_dirs[i]) voxel_ctrain += 1 elif tmp",
"+= 1 elif voxel_dir in voxel_lval: fval.write(img_file+'\\n') cval += 1 elif voxel_dir in",
"fval.close() ftest.close() # scipy.io.savemat(os.path.join(out_dir, 'img_voxel_idxs.mat'), # {'img_voxel_idxs': np.array(img_voxel_idxs)}) scipy.io.savemat(os.path.join(out_dir, 'img_voxel_idxs.mat'), {'img_idxs': np.array(img_idxs), 'voxel_idxs':",
"phase in ['train', 'val', 'test']: with open(os.path.join(voxel_dirs[phase]), 'r') as f: voxel_names[phase] = f.readlines()",
"= json.load(open(pix3d_dir, 'r')) for i in range(len(pix3d)): # if json_file[i]['img'][4:9] == 'chair' and",
"if len(set(img_match_vox[phase]).difference(set(voxel_names[phase]))) > 0: print('error') for name in voxel_names[phase]: if name not in",
"img_names = {} for phase in ['train', 'val', 'test']: with open(os.path.join(voxel_dirs[phase]), 'r') as",
"voxel_txt_dir = os.path.join(out_dir, 'voxeltxt') if not os.path.exists(voxel_txt_dir): os.makedirs(voxel_txt_dir) voxel_train_txtpath = os.path.join(voxel_txt_dir, 'voxel_train.txt') voxel_val_txtpath",
"0 pix3d_dir = os.path.join(root, '../input/pix3d.json') pix3d = json.load(open(pix3d_dir, 'r')) for i in range(len(pix3d)):",
"'r')) for i in range(len(pix3d)): # if json_file[i]['img'][4:9] == 'chair' and json_file[i]['voxel'] not",
"['train', 'val', 'test']: if len(set(voxel_names[phase]).difference(set(img_match_vox[phase]))) > 0: print('error') if len(set(img_match_vox[phase]).difference(set(voxel_names[phase]))) > 0: print('error')",
"os.path.abspath('.') out_dir = os.path.join(root, '../output', cls) # out_dir = '/Users/heqian/Research/projects/primitive-based_3d/data/all_classes/chair' voxel_txt_dir = os.path.join(out_dir,",
"np import os import random import json import pdb def check_image_voxel_match(cls): root =",
"ftest.close() # scipy.io.savemat(os.path.join(out_dir, 'img_voxel_idxs.mat'), # {'img_voxel_idxs': np.array(img_voxel_idxs)}) scipy.io.savemat(os.path.join(out_dir, 'img_voxel_idxs.mat'), {'img_idxs': np.array(img_idxs), 'voxel_idxs': np.array(voxel_idxs)})",
"= 0 pix3d_dir = os.path.join(root, '../input/pix3d.json') pix3d = json.load(open(pix3d_dir, 'r')) for i in",
"0-3493 voxel_id_ori = match_id['voxel_idxs'][0, img_id_real] # 1-216 vox = voxel_all[voxel_id_ori - 1] img_match_vox[phase].append(vox)",
"i in range(len(pix3d)): # if json_file[i]['img'][4:9] == 'chair' and json_file[i]['voxel'] not in voxel_dirs:",
"for name in voxel_names[phase]: if name not in img_match_vox[phase]: print(name) for name in",
"= open(test_txtpath, 'w') ctrain = 0 cval = 0 ctest = 0 pix3d_dir",
"into train, val, test, according to voxels # img_voxel_idxs = [] img_idxs =",
"= 0 voxel_ctest = 0 with open(os.path.join(out_dir, 'voxels_dir_{}.txt'.format(cls)), 'r') as f: voxel_dirs =",
"1 elif tmp >= 0.65 and tmp < 0.8: fval.write(img_file+'\\n') cval += 1",
"# out_dir = '/Users/heqian/Research/projects/primitive-based_3d/data/all_classes/chair' voxel_txt_dir = os.path.join(out_dir, 'voxeltxt') voxel_dirs = {x: os.path.join(voxel_txt_dir, 'voxel_{}.txt'.format(x))",
"with open(os.path.join(img_dirs[phase]), 'r') as f: img_names[phase] = f.readlines() # pix3d_dir = os.path.join(root, '../input/pix3d.json')",
"# 1-3839 img_id_real = list(match_id['img_idxs'][0]).index(id_img_ori) # 0-3493 voxel_id_ori = match_id['voxel_idxs'][0, img_id_real] # 1-216",
"'voxeltxt') voxel_dirs = {x: os.path.join(voxel_txt_dir, 'voxel_{}.txt'.format(x)) for x in ['train', 'val', 'test']} img_dirs",
"voxel_ctest += 1 voxel_ftrain.close() voxel_fval.close() voxel_ftest.close() ## split images into train, val, test,",
"ctest += 1 else: tmp = random.random() if tmp < 0.65: ftrain.write(img_file+'\\n') ctrain",
"for i in range(len(voxel_dirs)): voxel_dirs[i] = voxel_dirs[i].strip() voxel_dirs[i] = voxel_dirs[i] tmp = random.random()",
"print(ctrain+cval+ctest, ctrain, cval, ctest) print(len(img_idxs)) if __name__ == '__main__': cls_all = ['chair', 'bed',",
"tmp < 0.65: ftrain.write(img_file+'\\n') ctrain += 1 elif tmp >= 0.65 and tmp",
"test_txtpath = os.path.join(voxel_txt_dir, 'test.txt') ftrain = open(train_txtpath, 'w') fval = open(val_txtpath, 'w') ftest",
">= 0.65 and tmp < 0.8: voxel_fval.write(voxel_dirs[i]+'\\n') voxel_lval.append(voxel_dirs[i]) voxel_cval += 1 else: voxel_ftest.write(voxel_dirs[i]+'\\n')",
"voxel_ltest = [] voxel_ctrain = 0 voxel_cval = 0 voxel_ctest = 0 with",
"= open(val_txtpath, 'w') ftest = open(test_txtpath, 'w') ctrain = 0 cval = 0",
"= pix3d[i]['img'].split('/')[-1] #[10:] img_id = int(img_file.split('.')[0]) #int(pix3d[i]['img'][10:14]) img_idxs.append(img_id) voxel_idxs.append(voxel_dirs.index(voxel_dir) + 1) # img_voxel_idxs.append(voxel_dirs.index(voxel_dir))",
"by 34 images ## split voxels into train, val, test root = os.path.abspath('.')",
"0.8: fval.write(img_file+'\\n') cval += 1 else: ftest.write(img_file+'\\n') ctest += 1 ftrain.close() fval.close() ftest.close()",
"json_file[i]['voxel'] not in voxel_dirs: # print(json_file[i]['img'], json_file[i]['voxel']) voxel_dir = pix3d[i]['voxel'][6:] if voxel_dir in",
"= '/Users/heqian/Research/projects/3dprnn/data/pix3d' split_by_model = True # True-split by 216 models, False-split by 34",
"len(img_voxel_idxs): # print('Error!!!=======', img_id) if split_by_model: if voxel_dir in voxel_ltrain: ftrain.write(img_file+'\\n') ctrain +=",
"as f: voxel_dirs = f.readlines() for i in range(len(voxel_dirs)): voxel_dirs[i] = voxel_dirs[i].strip() voxel_dirs[i]",
"tmp = random.random() if tmp < 0.65: ftrain.write(img_file+'\\n') ctrain += 1 elif tmp",
"216 models, False-split by 34 images ## split voxels into train, val, test",
"= [] train_txtpath = os.path.join(voxel_txt_dir, 'train.txt') val_txtpath = os.path.join(voxel_txt_dir, 'val.txt') test_txtpath = os.path.join(voxel_txt_dir,",
"= {} for phase in ['train', 'val', 'test']: with open(os.path.join(voxel_dirs[phase]), 'r') as f:",
"'w') fval = open(val_txtpath, 'w') ftest = open(test_txtpath, 'w') ctrain = 0 cval",
"1-216 vox = voxel_all[voxel_id_ori - 1] img_match_vox[phase].append(vox) # img_match_vox[phase].append('model/'+vox) img_match_vox = {x: sorted(set(img_match_vox[x]))",
"voxel_lval.append(voxel_dirs[i]) voxel_cval += 1 else: voxel_ftest.write(voxel_dirs[i]+'\\n') voxel_ltest.append(voxel_dirs[i]) voxel_ctest += 1 voxel_ftrain.close() voxel_fval.close() voxel_ftest.close()",
"'val', 'test']: with open(os.path.join(voxel_dirs[phase]), 'r') as f: voxel_names[phase] = f.readlines() with open(os.path.join(img_dirs[phase]), 'r')",
"ctrain += 1 elif voxel_dir in voxel_lval: fval.write(img_file+'\\n') cval += 1 elif voxel_dir",
"list(match_id['img_idxs'][0]).index(id_img_ori) # 0-3493 voxel_id_ori = match_id['voxel_idxs'][0, img_id_real] # 1-216 vox = voxel_all[voxel_id_ori -",
"[] train_txtpath = os.path.join(voxel_txt_dir, 'train.txt') val_txtpath = os.path.join(voxel_txt_dir, 'val.txt') test_txtpath = os.path.join(voxel_txt_dir, 'test.txt')",
"0.65 and tmp < 0.8: voxel_fval.write(voxel_dirs[i]+'\\n') voxel_lval.append(voxel_dirs[i]) voxel_cval += 1 else: voxel_ftest.write(voxel_dirs[i]+'\\n') voxel_ltest.append(voxel_dirs[i])",
"!= len(img_voxel_idxs): # print('Error!!!=======', img_id) if split_by_model: if voxel_dir in voxel_ltrain: ftrain.write(img_file+'\\n') ctrain",
"1 elif voxel_dir in voxel_ltest: ftest.write(img_file+'\\n') ctest += 1 else: tmp = random.random()",
"f: voxel_names[phase] = f.readlines() with open(os.path.join(img_dirs[phase]), 'r') as f: img_names[phase] = f.readlines() #",
"to voxels # img_voxel_idxs = [] img_idxs = [] voxel_idxs = [] train_txtpath",
"in range(len(pix3d)): # if json_file[i]['img'][4:9] == 'chair' and json_file[i]['voxel'] not in voxel_dirs: #",
"in voxel_dirs: # pdb.set_trace() img_file = pix3d[i]['img'].split('/')[-1] #[10:] img_id = int(img_file.split('.')[0]) #int(pix3d[i]['img'][10:14]) img_idxs.append(img_id)",
"# if json_file[i]['img'][4:9] == 'chair' and json_file[i]['voxel'] not in voxel_dirs: # print(json_file[i]['img'], json_file[i]['voxel'])",
"= open(train_txtpath, 'w') fval = open(val_txtpath, 'w') ftest = open(test_txtpath, 'w') ctrain =",
"images into train, val, test, according to voxels # img_voxel_idxs = [] img_idxs",
"'test']} for phase in ['train', 'val', 'test']: for img in img_names[phase]: id_img_ori =",
"{x: [] for x in ['train', 'val', 'test']} for phase in ['train', 'val',",
"voxel_ftrain.close() voxel_fval.close() voxel_ftest.close() ## split images into train, val, test, according to voxels",
"ctrain = 0 cval = 0 ctest = 0 pix3d_dir = os.path.join(root, '../input/pix3d.json')",
"+= 1 else: voxel_ftest.write(voxel_dirs[i]+'\\n') voxel_ltest.append(voxel_dirs[i]) voxel_ctest += 1 voxel_ftrain.close() voxel_fval.close() voxel_ftest.close() ## split",
"+= 1 elif voxel_dir in voxel_ltest: ftest.write(img_file+'\\n') ctest += 1 else: tmp =",
"root = os.path.abspath('.') out_dir = os.path.join(root, '../output', cls) voxel_txt_dir = os.path.join(out_dir, 'voxeltxt') if",
"'r') as f: img_names[phase] = f.readlines() # pix3d_dir = os.path.join(root, '../input/pix3d.json') # pix3d",
"img_id_real = list(match_id['img_idxs'][0]).index(id_img_ori) # 0-3493 voxel_id_ori = match_id['voxel_idxs'][0, img_id_real] # 1-216 vox =",
"os.path.join(voxel_txt_dir, 'test.txt') ftrain = open(train_txtpath, 'w') fval = open(val_txtpath, 'w') ftest = open(test_txtpath,",
"images ## split voxels into train, val, test root = os.path.abspath('.') out_dir =",
"0 ctest = 0 pix3d_dir = os.path.join(root, '../input/pix3d.json') pix3d = json.load(open(pix3d_dir, 'r')) for",
"{x: os.path.join(voxel_txt_dir, 'voxel_{}.txt'.format(x)) for x in ['train', 'val', 'test']} img_dirs = {x: os.path.join(voxel_txt_dir,",
"cls_all = ['chair', 'bed', 'bookcase', 'desk', 'misc', 'sofa', 'table', 'tool', 'wardrobe'] cls =",
"'voxel_test.txt') voxel_ftrain = open(voxel_train_txtpath, 'w') voxel_fval = open(voxel_val_txtpath, 'w') voxel_ftest = open(voxel_test_txtpath, 'w')",
"by 216 models, False-split by 34 images ## split voxels into train, val,",
"ftest = open(test_txtpath, 'w') ctrain = 0 cval = 0 ctest = 0",
"voxel_test_txtpath = os.path.join(voxel_txt_dir, 'voxel_test.txt') voxel_ftrain = open(voxel_train_txtpath, 'w') voxel_fval = open(voxel_val_txtpath, 'w') voxel_ftest",
"not os.path.exists(voxel_txt_dir): os.makedirs(voxel_txt_dir) voxel_train_txtpath = os.path.join(voxel_txt_dir, 'voxel_train.txt') voxel_val_txtpath = os.path.join(voxel_txt_dir, 'voxel_val.txt') voxel_test_txtpath =",
"voxel_ftest = open(voxel_test_txtpath, 'w') voxel_ltrain = [] voxel_lval = [] voxel_ltest = []",
"- 1] img_match_vox[phase].append(vox) # img_match_vox[phase].append('model/'+vox) img_match_vox = {x: sorted(set(img_match_vox[x])) for x in ['train',",
"0.65: voxel_ftrain.write(voxel_dirs[i]+'\\n') voxel_ltrain.append(voxel_dirs[i]) voxel_ctrain += 1 elif tmp >= 0.65 and tmp <",
"0.8: voxel_fval.write(voxel_dirs[i]+'\\n') voxel_lval.append(voxel_dirs[i]) voxel_cval += 1 else: voxel_ftest.write(voxel_dirs[i]+'\\n') voxel_ltest.append(voxel_dirs[i]) voxel_ctest += 1 voxel_ftrain.close()",
"voxel_dirs[i] = voxel_dirs[i].strip() voxel_dirs[i] = voxel_dirs[i] tmp = random.random() if tmp < 0.65:",
"#[10:] img_id = int(img_file.split('.')[0]) #int(pix3d[i]['img'][10:14]) img_idxs.append(img_id) voxel_idxs.append(voxel_dirs.index(voxel_dir) + 1) # img_voxel_idxs.append(voxel_dirs.index(voxel_dir)) # if",
"voxel_cval, voxel_ctest) print(ctrain+cval+ctest, ctrain, cval, ctest) print(len(img_idxs)) if __name__ == '__main__': cls_all =",
"< 0.65: ftrain.write(img_file+'\\n') ctrain += 1 elif tmp >= 0.65 and tmp <",
"not in voxel_names[phase]: print(name) def split_voxel_then_image(cls): # data_dir = '/Users/heqian/Research/projects/3dprnn/data/pix3d' split_by_model = True",
"voxel_all[voxel_id_ori - 1] img_match_vox[phase].append(vox) # img_match_vox[phase].append('model/'+vox) img_match_vox = {x: sorted(set(img_match_vox[x])) for x in",
"according to voxels # img_voxel_idxs = [] img_idxs = [] voxel_idxs = []",
"pix3d_dir = os.path.join(root, '../input/pix3d.json') # pix3d = json.load(open(pix3d_dir, 'r')) match_id = scipy.io.loadmat(os.path.join(out_dir, 'img_voxel_idxs.mat'))",
"range(len(voxel_dirs)): voxel_dirs[i] = voxel_dirs[i].strip() voxel_dirs[i] = voxel_dirs[i] tmp = random.random() if tmp <",
"# scipy.io.savemat(os.path.join(out_dir, 'img_voxel_idxs.mat'), # {'img_voxel_idxs': np.array(img_voxel_idxs)}) scipy.io.savemat(os.path.join(out_dir, 'img_voxel_idxs.mat'), {'img_idxs': np.array(img_idxs), 'voxel_idxs': np.array(voxel_idxs)}) print(voxel_ctrain+voxel_cval+voxel_ctest,",
"check_image_voxel_match(cls): root = os.path.abspath('.') out_dir = os.path.join(root, '../output', cls) # out_dir = '/Users/heqian/Research/projects/primitive-based_3d/data/all_classes/chair'",
"in ['train', 'val', 'test']: with open(os.path.join(voxel_dirs[phase]), 'r') as f: voxel_names[phase] = f.readlines() with",
"# if img_id != len(img_voxel_idxs): # print('Error!!!=======', img_id) if split_by_model: if voxel_dir in",
"json.load(open(pix3d_dir, 'r')) for i in range(len(pix3d)): # if json_file[i]['img'][4:9] == 'chair' and json_file[i]['voxel']",
"name not in img_match_vox[phase]: print(name) for name in img_match_vox[phase]: if name not in",
"0 cval = 0 ctest = 0 pix3d_dir = os.path.join(root, '../input/pix3d.json') pix3d =",
"os.path.exists(voxel_txt_dir): os.makedirs(voxel_txt_dir) voxel_train_txtpath = os.path.join(voxel_txt_dir, 'voxel_train.txt') voxel_val_txtpath = os.path.join(voxel_txt_dir, 'voxel_val.txt') voxel_test_txtpath = os.path.join(voxel_txt_dir,",
"{} img_names = {} for phase in ['train', 'val', 'test']: with open(os.path.join(voxel_dirs[phase]), 'r')",
"'desk', 'misc', 'sofa', 'table', 'tool', 'wardrobe'] cls = 'table' # for cls in",
"'../output', cls) voxel_txt_dir = os.path.join(out_dir, 'voxeltxt') if not os.path.exists(voxel_txt_dir): os.makedirs(voxel_txt_dir) voxel_train_txtpath = os.path.join(voxel_txt_dir,",
"and tmp < 0.8: fval.write(img_file+'\\n') cval += 1 else: ftest.write(img_file+'\\n') ctest += 1",
"open(voxel_val_txtpath, 'w') voxel_ftest = open(voxel_test_txtpath, 'w') voxel_ltrain = [] voxel_lval = [] voxel_ltest",
"val, test root = os.path.abspath('.') out_dir = os.path.join(root, '../output', cls) voxel_txt_dir = os.path.join(out_dir,",
"pdb.set_trace() img_file = pix3d[i]['img'].split('/')[-1] #[10:] img_id = int(img_file.split('.')[0]) #int(pix3d[i]['img'][10:14]) img_idxs.append(img_id) voxel_idxs.append(voxel_dirs.index(voxel_dir) + 1)",
"cls) voxel_txt_dir = os.path.join(out_dir, 'voxeltxt') if not os.path.exists(voxel_txt_dir): os.makedirs(voxel_txt_dir) voxel_train_txtpath = os.path.join(voxel_txt_dir, 'voxel_train.txt')",
"voxel_ltrain = [] voxel_lval = [] voxel_ltest = [] voxel_ctrain = 0 voxel_cval",
"['chair', 'bed', 'bookcase', 'desk', 'misc', 'sofa', 'table', 'tool', 'wardrobe'] cls = 'table' #",
"if voxel_dir in voxel_dirs: # pdb.set_trace() img_file = pix3d[i]['img'].split('/')[-1] #[10:] img_id = int(img_file.split('.')[0])",
"ftrain.write(img_file+'\\n') ctrain += 1 elif voxel_dir in voxel_lval: fval.write(img_file+'\\n') cval += 1 elif",
"= int(img_file.split('.')[0]) #int(pix3d[i]['img'][10:14]) img_idxs.append(img_id) voxel_idxs.append(voxel_dirs.index(voxel_dir) + 1) # img_voxel_idxs.append(voxel_dirs.index(voxel_dir)) # if img_id !=",
"def split_voxel_then_image(cls): # data_dir = '/Users/heqian/Research/projects/3dprnn/data/pix3d' split_by_model = True # True-split by 216",
"in ['train', 'val', 'test']} img_dirs = {x: os.path.join(voxel_txt_dir, '{}.txt'.format(x)) for x in ['train',",
"0: print('error') if len(set(img_match_vox[phase]).difference(set(voxel_names[phase]))) > 0: print('error') for name in voxel_names[phase]: if name",
"< 0.65: voxel_ftrain.write(voxel_dirs[i]+'\\n') voxel_ltrain.append(voxel_dirs[i]) voxel_ctrain += 1 elif tmp >= 0.65 and tmp",
"ftest.write(img_file+'\\n') ctest += 1 else: tmp = random.random() if tmp < 0.65: ftrain.write(img_file+'\\n')",
"import numpy as np import os import random import json import pdb def",
"voxel_train_txtpath = os.path.join(voxel_txt_dir, 'voxel_train.txt') voxel_val_txtpath = os.path.join(voxel_txt_dir, 'voxel_val.txt') voxel_test_txtpath = os.path.join(voxel_txt_dir, 'voxel_test.txt') voxel_ftrain",
"cval += 1 else: ftest.write(img_file+'\\n') ctest += 1 ftrain.close() fval.close() ftest.close() # scipy.io.savemat(os.path.join(out_dir,",
"data_dir = '/Users/heqian/Research/projects/3dprnn/data/pix3d' split_by_model = True # True-split by 216 models, False-split by",
"in voxel_ltest: ftest.write(img_file+'\\n') ctest += 1 else: tmp = random.random() if tmp <",
"= os.path.join(voxel_txt_dir, 'voxel_val.txt') voxel_test_txtpath = os.path.join(voxel_txt_dir, 'voxel_test.txt') voxel_ftrain = open(voxel_train_txtpath, 'w') voxel_fval =",
"+= 1 else: tmp = random.random() if tmp < 0.65: ftrain.write(img_file+'\\n') ctrain +=",
"'bookcase', 'desk', 'misc', 'sofa', 'table', 'tool', 'wardrobe'] cls = 'table' # for cls",
"img_voxel_idxs = [] img_idxs = [] voxel_idxs = [] train_txtpath = os.path.join(voxel_txt_dir, 'train.txt')",
"import pdb def check_image_voxel_match(cls): root = os.path.abspath('.') out_dir = os.path.join(root, '../output', cls) #",
"for x in ['train', 'val', 'test']} for phase in ['train', 'val', 'test']: for",
"open(os.path.join(out_dir, 'voxels_dir_{}.txt'.format(cls)), 'r') as f: voxel_all = f.readlines() voxel_names = {} img_names =",
"numpy as np import os import random import json import pdb def check_image_voxel_match(cls):",
"voxel_dir in voxel_ltrain: ftrain.write(img_file+'\\n') ctrain += 1 elif voxel_dir in voxel_lval: fval.write(img_file+'\\n') cval",
"['train', 'val', 'test']: for img in img_names[phase]: id_img_ori = int(img.split('.')[0]) # 1-3839 img_id_real",
"< 0.8: fval.write(img_file+'\\n') cval += 1 else: ftest.write(img_file+'\\n') ctest += 1 ftrain.close() fval.close()",
"= '/Users/heqian/Research/projects/primitive-based_3d/data/all_classes/chair' voxel_txt_dir = os.path.join(out_dir, 'voxeltxt') voxel_dirs = {x: os.path.join(voxel_txt_dir, 'voxel_{}.txt'.format(x)) for x",
"x in ['train', 'val', 'test']} # pdb.set_trace() for phase in ['train', 'val', 'test']:",
"for x in ['train', 'val', 'test']} img_dirs = {x: os.path.join(voxel_txt_dir, '{}.txt'.format(x)) for x",
"= os.path.abspath('.') out_dir = os.path.join(root, '../output', cls) # out_dir = '/Users/heqian/Research/projects/primitive-based_3d/data/all_classes/chair' voxel_txt_dir =",
"= match_id['voxel_idxs'][0, img_id_real] # 1-216 vox = voxel_all[voxel_id_ori - 1] img_match_vox[phase].append(vox) # img_match_vox[phase].append('model/'+vox)",
"if tmp < 0.65: voxel_ftrain.write(voxel_dirs[i]+'\\n') voxel_ltrain.append(voxel_dirs[i]) voxel_ctrain += 1 elif tmp >= 0.65",
"voxel_idxs.append(voxel_dirs.index(voxel_dir) + 1) # img_voxel_idxs.append(voxel_dirs.index(voxel_dir)) # if img_id != len(img_voxel_idxs): # print('Error!!!=======', img_id)",
"for x in ['train', 'val', 'test']} # pdb.set_trace() for phase in ['train', 'val',",
"img_voxel_idxs.append(voxel_dirs.index(voxel_dir)) # if img_id != len(img_voxel_idxs): # print('Error!!!=======', img_id) if split_by_model: if voxel_dir",
"'../input/pix3d.json') # pix3d = json.load(open(pix3d_dir, 'r')) match_id = scipy.io.loadmat(os.path.join(out_dir, 'img_voxel_idxs.mat')) img_match_vox = {x:",
"> 0: print('error') for name in voxel_names[phase]: if name not in img_match_vox[phase]: print(name)",
"'img_voxel_idxs.mat'), # {'img_voxel_idxs': np.array(img_voxel_idxs)}) scipy.io.savemat(os.path.join(out_dir, 'img_voxel_idxs.mat'), {'img_idxs': np.array(img_idxs), 'voxel_idxs': np.array(voxel_idxs)}) print(voxel_ctrain+voxel_cval+voxel_ctest, voxel_ctrain, voxel_cval,",
"'sofa', 'table', 'tool', 'wardrobe'] cls = 'table' # for cls in cls_all: split_voxel_then_image(cls)",
"'w') voxel_fval = open(voxel_val_txtpath, 'w') voxel_ftest = open(voxel_test_txtpath, 'w') voxel_ltrain = [] voxel_lval",
"pix3d[i]['img'].split('/')[-1] #[10:] img_id = int(img_file.split('.')[0]) #int(pix3d[i]['img'][10:14]) img_idxs.append(img_id) voxel_idxs.append(voxel_dirs.index(voxel_dir) + 1) # img_voxel_idxs.append(voxel_dirs.index(voxel_dir)) #",
"1 else: ftest.write(img_file+'\\n') ctest += 1 ftrain.close() fval.close() ftest.close() # scipy.io.savemat(os.path.join(out_dir, 'img_voxel_idxs.mat'), #",
"__name__ == '__main__': cls_all = ['chair', 'bed', 'bookcase', 'desk', 'misc', 'sofa', 'table', 'tool',",
"pdb def check_image_voxel_match(cls): root = os.path.abspath('.') out_dir = os.path.join(root, '../output', cls) # out_dir",
"0 voxel_cval = 0 voxel_ctest = 0 with open(os.path.join(out_dir, 'voxels_dir_{}.txt'.format(cls)), 'r') as f:",
"= f.readlines() voxel_names = {} img_names = {} for phase in ['train', 'val',",
"else: tmp = random.random() if tmp < 0.65: ftrain.write(img_file+'\\n') ctrain += 1 elif",
"scipy.io.savemat(os.path.join(out_dir, 'img_voxel_idxs.mat'), {'img_idxs': np.array(img_idxs), 'voxel_idxs': np.array(voxel_idxs)}) print(voxel_ctrain+voxel_cval+voxel_ctest, voxel_ctrain, voxel_cval, voxel_ctest) print(ctrain+cval+ctest, ctrain, cval,",
"'val', 'test']: if len(set(voxel_names[phase]).difference(set(img_match_vox[phase]))) > 0: print('error') if len(set(img_match_vox[phase]).difference(set(voxel_names[phase]))) > 0: print('error') for",
"img_idxs = [] voxel_idxs = [] train_txtpath = os.path.join(voxel_txt_dir, 'train.txt') val_txtpath = os.path.join(voxel_txt_dir,",
"in voxel_lval: fval.write(img_file+'\\n') cval += 1 elif voxel_dir in voxel_ltest: ftest.write(img_file+'\\n') ctest +=",
"ftrain.write(img_file+'\\n') ctrain += 1 elif tmp >= 0.65 and tmp < 0.8: fval.write(img_file+'\\n')",
"[] voxel_lval = [] voxel_ltest = [] voxel_ctrain = 0 voxel_cval = 0",
"ctest = 0 pix3d_dir = os.path.join(root, '../input/pix3d.json') pix3d = json.load(open(pix3d_dir, 'r')) for i",
"import json import pdb def check_image_voxel_match(cls): root = os.path.abspath('.') out_dir = os.path.join(root, '../output',",
"= ['chair', 'bed', 'bookcase', 'desk', 'misc', 'sofa', 'table', 'tool', 'wardrobe'] cls = 'table'",
"+= 1 ftrain.close() fval.close() ftest.close() # scipy.io.savemat(os.path.join(out_dir, 'img_voxel_idxs.mat'), # {'img_voxel_idxs': np.array(img_voxel_idxs)}) scipy.io.savemat(os.path.join(out_dir, 'img_voxel_idxs.mat'),",
"ftrain = open(train_txtpath, 'w') fval = open(val_txtpath, 'w') ftest = open(test_txtpath, 'w') ctrain",
"#int(pix3d[i]['img'][10:14]) img_idxs.append(img_id) voxel_idxs.append(voxel_dirs.index(voxel_dir) + 1) # img_voxel_idxs.append(voxel_dirs.index(voxel_dir)) # if img_id != len(img_voxel_idxs): #",
"img_match_vox[phase].append('model/'+vox) img_match_vox = {x: sorted(set(img_match_vox[x])) for x in ['train', 'val', 'test']} # pdb.set_trace()",
"'voxel_val.txt') voxel_test_txtpath = os.path.join(voxel_txt_dir, 'voxel_test.txt') voxel_ftrain = open(voxel_train_txtpath, 'w') voxel_fval = open(voxel_val_txtpath, 'w')",
"= [] voxel_ctrain = 0 voxel_cval = 0 voxel_ctest = 0 with open(os.path.join(out_dir,",
"print(len(img_idxs)) if __name__ == '__main__': cls_all = ['chair', 'bed', 'bookcase', 'desk', 'misc', 'sofa',",
"os.path.join(root, '../input/pix3d.json') # pix3d = json.load(open(pix3d_dir, 'r')) match_id = scipy.io.loadmat(os.path.join(out_dir, 'img_voxel_idxs.mat')) img_match_vox =",
"voxel_txt_dir = os.path.join(out_dir, 'voxeltxt') voxel_dirs = {x: os.path.join(voxel_txt_dir, 'voxel_{}.txt'.format(x)) for x in ['train',",
"f: img_names[phase] = f.readlines() # pix3d_dir = os.path.join(root, '../input/pix3d.json') # pix3d = json.load(open(pix3d_dir,",
"val, test, according to voxels # img_voxel_idxs = [] img_idxs = [] voxel_idxs",
"scipy.io.savemat(os.path.join(out_dir, 'img_voxel_idxs.mat'), # {'img_voxel_idxs': np.array(img_voxel_idxs)}) scipy.io.savemat(os.path.join(out_dir, 'img_voxel_idxs.mat'), {'img_idxs': np.array(img_idxs), 'voxel_idxs': np.array(voxel_idxs)}) print(voxel_ctrain+voxel_cval+voxel_ctest, voxel_ctrain,",
"= voxel_dirs[i].strip() voxel_dirs[i] = voxel_dirs[i] tmp = random.random() if tmp < 0.65: voxel_ftrain.write(voxel_dirs[i]+'\\n')",
"True-split by 216 models, False-split by 34 images ## split voxels into train,",
"== '__main__': cls_all = ['chair', 'bed', 'bookcase', 'desk', 'misc', 'sofa', 'table', 'tool', 'wardrobe']",
"voxel_ftest.close() ## split images into train, val, test, according to voxels # img_voxel_idxs",
"voxel_names = {} img_names = {} for phase in ['train', 'val', 'test']: with",
"name not in voxel_names[phase]: print(name) def split_voxel_then_image(cls): # data_dir = '/Users/heqian/Research/projects/3dprnn/data/pix3d' split_by_model =",
"and json_file[i]['voxel'] not in voxel_dirs: # print(json_file[i]['img'], json_file[i]['voxel']) voxel_dir = pix3d[i]['voxel'][6:] if voxel_dir",
"root = os.path.abspath('.') out_dir = os.path.join(root, '../output', cls) # out_dir = '/Users/heqian/Research/projects/primitive-based_3d/data/all_classes/chair' voxel_txt_dir",
"img_idxs.append(img_id) voxel_idxs.append(voxel_dirs.index(voxel_dir) + 1) # img_voxel_idxs.append(voxel_dirs.index(voxel_dir)) # if img_id != len(img_voxel_idxs): # print('Error!!!=======',",
"== 'chair' and json_file[i]['voxel'] not in voxel_dirs: # print(json_file[i]['img'], json_file[i]['voxel']) voxel_dir = pix3d[i]['voxel'][6:]",
"os.path.join(voxel_txt_dir, 'train.txt') val_txtpath = os.path.join(voxel_txt_dir, 'val.txt') test_txtpath = os.path.join(voxel_txt_dir, 'test.txt') ftrain = open(train_txtpath,",
"0.65: ftrain.write(img_file+'\\n') ctrain += 1 elif tmp >= 0.65 and tmp < 0.8:",
"= list(match_id['img_idxs'][0]).index(id_img_ori) # 0-3493 voxel_id_ori = match_id['voxel_idxs'][0, img_id_real] # 1-216 vox = voxel_all[voxel_id_ori",
"not in voxel_dirs: # print(json_file[i]['img'], json_file[i]['voxel']) voxel_dir = pix3d[i]['voxel'][6:] if voxel_dir in voxel_dirs:",
"## split voxels into train, val, test root = os.path.abspath('.') out_dir = os.path.join(root,",
"'val', 'test']} # pdb.set_trace() for phase in ['train', 'val', 'test']: if len(set(voxel_names[phase]).difference(set(img_match_vox[phase]))) >",
"os.path.join(out_dir, 'voxeltxt') if not os.path.exists(voxel_txt_dir): os.makedirs(voxel_txt_dir) voxel_train_txtpath = os.path.join(voxel_txt_dir, 'voxel_train.txt') voxel_val_txtpath = os.path.join(voxel_txt_dir,",
"import random import json import pdb def check_image_voxel_match(cls): root = os.path.abspath('.') out_dir =",
"[] voxel_ltest = [] voxel_ctrain = 0 voxel_cval = 0 voxel_ctest = 0",
"img_match_vox[phase]: print(name) for name in img_match_vox[phase]: if name not in voxel_names[phase]: print(name) def",
"= random.random() if tmp < 0.65: ftrain.write(img_file+'\\n') ctrain += 1 elif tmp >=",
"img_id) if split_by_model: if voxel_dir in voxel_ltrain: ftrain.write(img_file+'\\n') ctrain += 1 elif voxel_dir",
"x in ['train', 'val', 'test']} for phase in ['train', 'val', 'test']: for img",
"# img_voxel_idxs.append(voxel_dirs.index(voxel_dir)) # if img_id != len(img_voxel_idxs): # print('Error!!!=======', img_id) if split_by_model: if",
"{'img_voxel_idxs': np.array(img_voxel_idxs)}) scipy.io.savemat(os.path.join(out_dir, 'img_voxel_idxs.mat'), {'img_idxs': np.array(img_idxs), 'voxel_idxs': np.array(voxel_idxs)}) print(voxel_ctrain+voxel_cval+voxel_ctest, voxel_ctrain, voxel_cval, voxel_ctest) print(ctrain+cval+ctest,",
"for img in img_names[phase]: id_img_ori = int(img.split('.')[0]) # 1-3839 img_id_real = list(match_id['img_idxs'][0]).index(id_img_ori) #",
"1-3839 img_id_real = list(match_id['img_idxs'][0]).index(id_img_ori) # 0-3493 voxel_id_ori = match_id['voxel_idxs'][0, img_id_real] # 1-216 vox",
"json_file[i]['img'][4:9] == 'chair' and json_file[i]['voxel'] not in voxel_dirs: # print(json_file[i]['img'], json_file[i]['voxel']) voxel_dir =",
"= json.load(open(pix3d_dir, 'r')) match_id = scipy.io.loadmat(os.path.join(out_dir, 'img_voxel_idxs.mat')) img_match_vox = {x: [] for x",
"json import pdb def check_image_voxel_match(cls): root = os.path.abspath('.') out_dir = os.path.join(root, '../output', cls)",
"f: voxel_all = f.readlines() voxel_names = {} img_names = {} for phase in",
"voxel_all = f.readlines() voxel_names = {} img_names = {} for phase in ['train',",
"img_id_real] # 1-216 vox = voxel_all[voxel_id_ori - 1] img_match_vox[phase].append(vox) # img_match_vox[phase].append('model/'+vox) img_match_vox =",
"in ['train', 'val', 'test']: for img in img_names[phase]: id_img_ori = int(img.split('.')[0]) # 1-3839",
"'r') as f: voxel_names[phase] = f.readlines() with open(os.path.join(img_dirs[phase]), 'r') as f: img_names[phase] =",
"img in img_names[phase]: id_img_ori = int(img.split('.')[0]) # 1-3839 img_id_real = list(match_id['img_idxs'][0]).index(id_img_ori) # 0-3493",
"os.path.join(voxel_txt_dir, 'voxel_val.txt') voxel_test_txtpath = os.path.join(voxel_txt_dir, 'voxel_test.txt') voxel_ftrain = open(voxel_train_txtpath, 'w') voxel_fval = open(voxel_val_txtpath,",
"= voxel_all[voxel_id_ori - 1] img_match_vox[phase].append(vox) # img_match_vox[phase].append('model/'+vox) img_match_vox = {x: sorted(set(img_match_vox[x])) for x",
"'{}.txt'.format(x)) for x in ['train', 'val', 'test']} with open(os.path.join(out_dir, 'voxels_dir_{}.txt'.format(cls)), 'r') as f:",
"'test']: with open(os.path.join(voxel_dirs[phase]), 'r') as f: voxel_names[phase] = f.readlines() with open(os.path.join(img_dirs[phase]), 'r') as",
"{} for phase in ['train', 'val', 'test']: with open(os.path.join(voxel_dirs[phase]), 'r') as f: voxel_names[phase]",
"voxel_id_ori = match_id['voxel_idxs'][0, img_id_real] # 1-216 vox = voxel_all[voxel_id_ori - 1] img_match_vox[phase].append(vox) #",
"def check_image_voxel_match(cls): root = os.path.abspath('.') out_dir = os.path.join(root, '../output', cls) # out_dir =",
"voxel_ctest = 0 with open(os.path.join(out_dir, 'voxels_dir_{}.txt'.format(cls)), 'r') as f: voxel_dirs = f.readlines() for",
"into train, val, test root = os.path.abspath('.') out_dir = os.path.join(root, '../output', cls) voxel_txt_dir",
"as f: img_names[phase] = f.readlines() # pix3d_dir = os.path.join(root, '../input/pix3d.json') # pix3d =",
"= [] img_idxs = [] voxel_idxs = [] train_txtpath = os.path.join(voxel_txt_dir, 'train.txt') val_txtpath",
"# img_match_vox[phase].append('model/'+vox) img_match_vox = {x: sorted(set(img_match_vox[x])) for x in ['train', 'val', 'test']} #",
"json_file[i]['voxel']) voxel_dir = pix3d[i]['voxel'][6:] if voxel_dir in voxel_dirs: # pdb.set_trace() img_file = pix3d[i]['img'].split('/')[-1]",
"voxel_val_txtpath = os.path.join(voxel_txt_dir, 'voxel_val.txt') voxel_test_txtpath = os.path.join(voxel_txt_dir, 'voxel_test.txt') voxel_ftrain = open(voxel_train_txtpath, 'w') voxel_fval",
"pix3d_dir = os.path.join(root, '../input/pix3d.json') pix3d = json.load(open(pix3d_dir, 'r')) for i in range(len(pix3d)): #",
"+= 1 else: ftest.write(img_file+'\\n') ctest += 1 ftrain.close() fval.close() ftest.close() # scipy.io.savemat(os.path.join(out_dir, 'img_voxel_idxs.mat'),",
"= {} img_names = {} for phase in ['train', 'val', 'test']: with open(os.path.join(voxel_dirs[phase]),",
"f.readlines() with open(os.path.join(img_dirs[phase]), 'r') as f: img_names[phase] = f.readlines() # pix3d_dir = os.path.join(root,",
"voxel_fval.write(voxel_dirs[i]+'\\n') voxel_lval.append(voxel_dirs[i]) voxel_cval += 1 else: voxel_ftest.write(voxel_dirs[i]+'\\n') voxel_ltest.append(voxel_dirs[i]) voxel_ctest += 1 voxel_ftrain.close() voxel_fval.close()",
"'train.txt') val_txtpath = os.path.join(voxel_txt_dir, 'val.txt') test_txtpath = os.path.join(voxel_txt_dir, 'test.txt') ftrain = open(train_txtpath, 'w')",
"# print(json_file[i]['img'], json_file[i]['voxel']) voxel_dir = pix3d[i]['voxel'][6:] if voxel_dir in voxel_dirs: # pdb.set_trace() img_file",
"'bed', 'bookcase', 'desk', 'misc', 'sofa', 'table', 'tool', 'wardrobe'] cls = 'table' # for",
"len(set(voxel_names[phase]).difference(set(img_match_vox[phase]))) > 0: print('error') if len(set(img_match_vox[phase]).difference(set(voxel_names[phase]))) > 0: print('error') for name in voxel_names[phase]:",
"os.path.join(voxel_txt_dir, 'voxel_test.txt') voxel_ftrain = open(voxel_train_txtpath, 'w') voxel_fval = open(voxel_val_txtpath, 'w') voxel_ftest = open(voxel_test_txtpath,",
"'voxeltxt') if not os.path.exists(voxel_txt_dir): os.makedirs(voxel_txt_dir) voxel_train_txtpath = os.path.join(voxel_txt_dir, 'voxel_train.txt') voxel_val_txtpath = os.path.join(voxel_txt_dir, 'voxel_val.txt')",
"= os.path.join(voxel_txt_dir, 'voxel_test.txt') voxel_ftrain = open(voxel_train_txtpath, 'w') voxel_fval = open(voxel_val_txtpath, 'w') voxel_ftest =",
"'w') ctrain = 0 cval = 0 ctest = 0 pix3d_dir = os.path.join(root,",
"json.load(open(pix3d_dir, 'r')) match_id = scipy.io.loadmat(os.path.join(out_dir, 'img_voxel_idxs.mat')) img_match_vox = {x: [] for x in",
"img_match_vox = {x: sorted(set(img_match_vox[x])) for x in ['train', 'val', 'test']} # pdb.set_trace() for",
"= voxel_dirs[i] tmp = random.random() if tmp < 0.65: voxel_ftrain.write(voxel_dirs[i]+'\\n') voxel_ltrain.append(voxel_dirs[i]) voxel_ctrain +=",
"print(voxel_ctrain+voxel_cval+voxel_ctest, voxel_ctrain, voxel_cval, voxel_ctest) print(ctrain+cval+ctest, ctrain, cval, ctest) print(len(img_idxs)) if __name__ == '__main__':",
"# True-split by 216 models, False-split by 34 images ## split voxels into",
"= os.path.join(voxel_txt_dir, 'test.txt') ftrain = open(train_txtpath, 'w') fval = open(val_txtpath, 'w') ftest =",
"os.path.join(voxel_txt_dir, 'voxel_{}.txt'.format(x)) for x in ['train', 'val', 'test']} img_dirs = {x: os.path.join(voxel_txt_dir, '{}.txt'.format(x))",
"voxel_dir in voxel_lval: fval.write(img_file+'\\n') cval += 1 elif voxel_dir in voxel_ltest: ftest.write(img_file+'\\n') ctest",
"int(img.split('.')[0]) # 1-3839 img_id_real = list(match_id['img_idxs'][0]).index(id_img_ori) # 0-3493 voxel_id_ori = match_id['voxel_idxs'][0, img_id_real] #",
"os.makedirs(voxel_txt_dir) voxel_train_txtpath = os.path.join(voxel_txt_dir, 'voxel_train.txt') voxel_val_txtpath = os.path.join(voxel_txt_dir, 'voxel_val.txt') voxel_test_txtpath = os.path.join(voxel_txt_dir, 'voxel_test.txt')",
"os.path.join(out_dir, 'voxeltxt') voxel_dirs = {x: os.path.join(voxel_txt_dir, 'voxel_{}.txt'.format(x)) for x in ['train', 'val', 'test']}",
"= 0 ctest = 0 pix3d_dir = os.path.join(root, '../input/pix3d.json') pix3d = json.load(open(pix3d_dir, 'r'))",
"0.65 and tmp < 0.8: fval.write(img_file+'\\n') cval += 1 else: ftest.write(img_file+'\\n') ctest +=",
"split_by_model: if voxel_dir in voxel_ltrain: ftrain.write(img_file+'\\n') ctrain += 1 elif voxel_dir in voxel_lval:",
"os.path.join(voxel_txt_dir, '{}.txt'.format(x)) for x in ['train', 'val', 'test']} with open(os.path.join(out_dir, 'voxels_dir_{}.txt'.format(cls)), 'r') as",
"test, according to voxels # img_voxel_idxs = [] img_idxs = [] voxel_idxs =",
"img_file = pix3d[i]['img'].split('/')[-1] #[10:] img_id = int(img_file.split('.')[0]) #int(pix3d[i]['img'][10:14]) img_idxs.append(img_id) voxel_idxs.append(voxel_dirs.index(voxel_dir) + 1) #",
"= True # True-split by 216 models, False-split by 34 images ## split",
"np.array(voxel_idxs)}) print(voxel_ctrain+voxel_cval+voxel_ctest, voxel_ctrain, voxel_cval, voxel_ctest) print(ctrain+cval+ctest, ctrain, cval, ctest) print(len(img_idxs)) if __name__ ==",
"voxel_ftrain = open(voxel_train_txtpath, 'w') voxel_fval = open(voxel_val_txtpath, 'w') voxel_ftest = open(voxel_test_txtpath, 'w') voxel_ltrain",
"'misc', 'sofa', 'table', 'tool', 'wardrobe'] cls = 'table' # for cls in cls_all:",
"'voxel_train.txt') voxel_val_txtpath = os.path.join(voxel_txt_dir, 'voxel_val.txt') voxel_test_txtpath = os.path.join(voxel_txt_dir, 'voxel_test.txt') voxel_ftrain = open(voxel_train_txtpath, 'w')",
"img_dirs = {x: os.path.join(voxel_txt_dir, '{}.txt'.format(x)) for x in ['train', 'val', 'test']} with open(os.path.join(out_dir,",
"'voxel_{}.txt'.format(x)) for x in ['train', 'val', 'test']} img_dirs = {x: os.path.join(voxel_txt_dir, '{}.txt'.format(x)) for",
"open(os.path.join(img_dirs[phase]), 'r') as f: img_names[phase] = f.readlines() # pix3d_dir = os.path.join(root, '../input/pix3d.json') #",
"len(set(img_match_vox[phase]).difference(set(voxel_names[phase]))) > 0: print('error') for name in voxel_names[phase]: if name not in img_match_vox[phase]:",
"# print('Error!!!=======', img_id) if split_by_model: if voxel_dir in voxel_ltrain: ftrain.write(img_file+'\\n') ctrain += 1",
"voxel_dirs[i] tmp = random.random() if tmp < 0.65: voxel_ftrain.write(voxel_dirs[i]+'\\n') voxel_ltrain.append(voxel_dirs[i]) voxel_ctrain += 1",
"import os import random import json import pdb def check_image_voxel_match(cls): root = os.path.abspath('.')",
"phase in ['train', 'val', 'test']: for img in img_names[phase]: id_img_ori = int(img.split('.')[0]) #",
"fval.write(img_file+'\\n') cval += 1 elif voxel_dir in voxel_ltest: ftest.write(img_file+'\\n') ctest += 1 else:",
"pix3d[i]['voxel'][6:] if voxel_dir in voxel_dirs: # pdb.set_trace() img_file = pix3d[i]['img'].split('/')[-1] #[10:] img_id =",
"pix3d = json.load(open(pix3d_dir, 'r')) for i in range(len(pix3d)): # if json_file[i]['img'][4:9] == 'chair'",
"= open(voxel_train_txtpath, 'w') voxel_fval = open(voxel_val_txtpath, 'w') voxel_ftest = open(voxel_test_txtpath, 'w') voxel_ltrain =",
"'test']} with open(os.path.join(out_dir, 'voxels_dir_{}.txt'.format(cls)), 'r') as f: voxel_all = f.readlines() voxel_names = {}",
"# pdb.set_trace() img_file = pix3d[i]['img'].split('/')[-1] #[10:] img_id = int(img_file.split('.')[0]) #int(pix3d[i]['img'][10:14]) img_idxs.append(img_id) voxel_idxs.append(voxel_dirs.index(voxel_dir) +",
"voxel_dirs = {x: os.path.join(voxel_txt_dir, 'voxel_{}.txt'.format(x)) for x in ['train', 'val', 'test']} img_dirs =",
"1] img_match_vox[phase].append(vox) # img_match_vox[phase].append('model/'+vox) img_match_vox = {x: sorted(set(img_match_vox[x])) for x in ['train', 'val',",
"if voxel_dir in voxel_ltrain: ftrain.write(img_file+'\\n') ctrain += 1 elif voxel_dir in voxel_lval: fval.write(img_file+'\\n')",
"'val', 'test']} with open(os.path.join(out_dir, 'voxels_dir_{}.txt'.format(cls)), 'r') as f: voxel_all = f.readlines() voxel_names =",
"voxel_names[phase]: print(name) def split_voxel_then_image(cls): # data_dir = '/Users/heqian/Research/projects/3dprnn/data/pix3d' split_by_model = True # True-split",
"'test']} # pdb.set_trace() for phase in ['train', 'val', 'test']: if len(set(voxel_names[phase]).difference(set(img_match_vox[phase]))) > 0:",
"open(os.path.join(voxel_dirs[phase]), 'r') as f: voxel_names[phase] = f.readlines() with open(os.path.join(img_dirs[phase]), 'r') as f: img_names[phase]",
"open(train_txtpath, 'w') fval = open(val_txtpath, 'w') ftest = open(test_txtpath, 'w') ctrain = 0",
"os.path.abspath('.') out_dir = os.path.join(root, '../output', cls) voxel_txt_dir = os.path.join(out_dir, 'voxeltxt') if not os.path.exists(voxel_txt_dir):",
"elif voxel_dir in voxel_ltest: ftest.write(img_file+'\\n') ctest += 1 else: tmp = random.random() if",
"'r') as f: voxel_all = f.readlines() voxel_names = {} img_names = {} for",
"1 voxel_ftrain.close() voxel_fval.close() voxel_ftest.close() ## split images into train, val, test, according to",
"train, val, test, according to voxels # img_voxel_idxs = [] img_idxs = []",
"img_id = int(img_file.split('.')[0]) #int(pix3d[i]['img'][10:14]) img_idxs.append(img_id) voxel_idxs.append(voxel_dirs.index(voxel_dir) + 1) # img_voxel_idxs.append(voxel_dirs.index(voxel_dir)) # if img_id",
"= os.path.join(root, '../input/pix3d.json') pix3d = json.load(open(pix3d_dir, 'r')) for i in range(len(pix3d)): # if",
"tmp < 0.8: fval.write(img_file+'\\n') cval += 1 else: ftest.write(img_file+'\\n') ctest += 1 ftrain.close()",
"in range(len(voxel_dirs)): voxel_dirs[i] = voxel_dirs[i].strip() voxel_dirs[i] = voxel_dirs[i] tmp = random.random() if tmp",
"ctrain += 1 elif tmp >= 0.65 and tmp < 0.8: fval.write(img_file+'\\n') cval",
"import scipy.io import numpy as np import os import random import json import",
"elif tmp >= 0.65 and tmp < 0.8: voxel_fval.write(voxel_dirs[i]+'\\n') voxel_lval.append(voxel_dirs[i]) voxel_cval += 1",
"match_id = scipy.io.loadmat(os.path.join(out_dir, 'img_voxel_idxs.mat')) img_match_vox = {x: [] for x in ['train', 'val',",
"'voxels_dir_{}.txt'.format(cls)), 'r') as f: voxel_dirs = f.readlines() for i in range(len(voxel_dirs)): voxel_dirs[i] =",
"for phase in ['train', 'val', 'test']: if len(set(voxel_names[phase]).difference(set(img_match_vox[phase]))) > 0: print('error') if len(set(img_match_vox[phase]).difference(set(voxel_names[phase])))",
"'val.txt') test_txtpath = os.path.join(voxel_txt_dir, 'test.txt') ftrain = open(train_txtpath, 'w') fval = open(val_txtpath, 'w')",
"1 else: voxel_ftest.write(voxel_dirs[i]+'\\n') voxel_ltest.append(voxel_dirs[i]) voxel_ctest += 1 voxel_ftrain.close() voxel_fval.close() voxel_ftest.close() ## split images",
"with open(os.path.join(voxel_dirs[phase]), 'r') as f: voxel_names[phase] = f.readlines() with open(os.path.join(img_dirs[phase]), 'r') as f:",
"np.array(img_idxs), 'voxel_idxs': np.array(voxel_idxs)}) print(voxel_ctrain+voxel_cval+voxel_ctest, voxel_ctrain, voxel_cval, voxel_ctest) print(ctrain+cval+ctest, ctrain, cval, ctest) print(len(img_idxs)) if",
"with open(os.path.join(out_dir, 'voxels_dir_{}.txt'.format(cls)), 'r') as f: voxel_all = f.readlines() voxel_names = {} img_names",
"random import json import pdb def check_image_voxel_match(cls): root = os.path.abspath('.') out_dir = os.path.join(root,",
"if len(set(voxel_names[phase]).difference(set(img_match_vox[phase]))) > 0: print('error') if len(set(img_match_vox[phase]).difference(set(voxel_names[phase]))) > 0: print('error') for name in",
"'test.txt') ftrain = open(train_txtpath, 'w') fval = open(val_txtpath, 'w') ftest = open(test_txtpath, 'w')",
"models, False-split by 34 images ## split voxels into train, val, test root",
"and tmp < 0.8: voxel_fval.write(voxel_dirs[i]+'\\n') voxel_lval.append(voxel_dirs[i]) voxel_cval += 1 else: voxel_ftest.write(voxel_dirs[i]+'\\n') voxel_ltest.append(voxel_dirs[i]) voxel_ctest",
"split_by_model = True # True-split by 216 models, False-split by 34 images ##",
"{'img_idxs': np.array(img_idxs), 'voxel_idxs': np.array(voxel_idxs)}) print(voxel_ctrain+voxel_cval+voxel_ctest, voxel_ctrain, voxel_cval, voxel_ctest) print(ctrain+cval+ctest, ctrain, cval, ctest) print(len(img_idxs))",
"'/Users/heqian/Research/projects/3dprnn/data/pix3d' split_by_model = True # True-split by 216 models, False-split by 34 images",
"voxel_cval += 1 else: voxel_ftest.write(voxel_dirs[i]+'\\n') voxel_ltest.append(voxel_dirs[i]) voxel_ctest += 1 voxel_ftrain.close() voxel_fval.close() voxel_ftest.close() ##",
"name in voxel_names[phase]: if name not in img_match_vox[phase]: print(name) for name in img_match_vox[phase]:",
"os.path.join(root, '../output', cls) # out_dir = '/Users/heqian/Research/projects/primitive-based_3d/data/all_classes/chair' voxel_txt_dir = os.path.join(out_dir, 'voxeltxt') voxel_dirs =",
"split voxels into train, val, test root = os.path.abspath('.') out_dir = os.path.join(root, '../output',",
"in voxel_dirs: # print(json_file[i]['img'], json_file[i]['voxel']) voxel_dir = pix3d[i]['voxel'][6:] if voxel_dir in voxel_dirs: #",
"voxel_cval = 0 voxel_ctest = 0 with open(os.path.join(out_dir, 'voxels_dir_{}.txt'.format(cls)), 'r') as f: voxel_dirs",
"= os.path.join(voxel_txt_dir, 'val.txt') test_txtpath = os.path.join(voxel_txt_dir, 'test.txt') ftrain = open(train_txtpath, 'w') fval =",
"{x: os.path.join(voxel_txt_dir, '{}.txt'.format(x)) for x in ['train', 'val', 'test']} with open(os.path.join(out_dir, 'voxels_dir_{}.txt'.format(cls)), 'r')",
"print('error') if len(set(img_match_vox[phase]).difference(set(voxel_names[phase]))) > 0: print('error') for name in voxel_names[phase]: if name not",
"= [] voxel_idxs = [] train_txtpath = os.path.join(voxel_txt_dir, 'train.txt') val_txtpath = os.path.join(voxel_txt_dir, 'val.txt')",
"open(test_txtpath, 'w') ctrain = 0 cval = 0 ctest = 0 pix3d_dir =",
"ftrain.close() fval.close() ftest.close() # scipy.io.savemat(os.path.join(out_dir, 'img_voxel_idxs.mat'), # {'img_voxel_idxs': np.array(img_voxel_idxs)}) scipy.io.savemat(os.path.join(out_dir, 'img_voxel_idxs.mat'), {'img_idxs': np.array(img_idxs),",
"34 images ## split voxels into train, val, test root = os.path.abspath('.') out_dir",
"= os.path.join(out_dir, 'voxeltxt') voxel_dirs = {x: os.path.join(voxel_txt_dir, 'voxel_{}.txt'.format(x)) for x in ['train', 'val',",
"= open(voxel_val_txtpath, 'w') voxel_ftest = open(voxel_test_txtpath, 'w') voxel_ltrain = [] voxel_lval = []",
"ftest.write(img_file+'\\n') ctest += 1 ftrain.close() fval.close() ftest.close() # scipy.io.savemat(os.path.join(out_dir, 'img_voxel_idxs.mat'), # {'img_voxel_idxs': np.array(img_voxel_idxs)})",
"# 0-3493 voxel_id_ori = match_id['voxel_idxs'][0, img_id_real] # 1-216 vox = voxel_all[voxel_id_ori - 1]",
"in img_names[phase]: id_img_ori = int(img.split('.')[0]) # 1-3839 img_id_real = list(match_id['img_idxs'][0]).index(id_img_ori) # 0-3493 voxel_id_ori",
"'../output', cls) # out_dir = '/Users/heqian/Research/projects/primitive-based_3d/data/all_classes/chair' voxel_txt_dir = os.path.join(out_dir, 'voxeltxt') voxel_dirs = {x:",
"= [] voxel_lval = [] voxel_ltest = [] voxel_ctrain = 0 voxel_cval =",
"[] img_idxs = [] voxel_idxs = [] train_txtpath = os.path.join(voxel_txt_dir, 'train.txt') val_txtpath =",
"for phase in ['train', 'val', 'test']: for img in img_names[phase]: id_img_ori = int(img.split('.')[0])",
"'r')) match_id = scipy.io.loadmat(os.path.join(out_dir, 'img_voxel_idxs.mat')) img_match_vox = {x: [] for x in ['train',",
"# pix3d = json.load(open(pix3d_dir, 'r')) match_id = scipy.io.loadmat(os.path.join(out_dir, 'img_voxel_idxs.mat')) img_match_vox = {x: []",
"voxel_ftest.write(voxel_dirs[i]+'\\n') voxel_ltest.append(voxel_dirs[i]) voxel_ctest += 1 voxel_ftrain.close() voxel_fval.close() voxel_ftest.close() ## split images into train,",
"in voxel_names[phase]: print(name) def split_voxel_then_image(cls): # data_dir = '/Users/heqian/Research/projects/3dprnn/data/pix3d' split_by_model = True #",
"scipy.io.loadmat(os.path.join(out_dir, 'img_voxel_idxs.mat')) img_match_vox = {x: [] for x in ['train', 'val', 'test']} for",
"as f: voxel_names[phase] = f.readlines() with open(os.path.join(img_dirs[phase]), 'r') as f: img_names[phase] = f.readlines()",
"voxel_ctest) print(ctrain+cval+ctest, ctrain, cval, ctest) print(len(img_idxs)) if __name__ == '__main__': cls_all = ['chair',",
"in ['train', 'val', 'test']} # pdb.set_trace() for phase in ['train', 'val', 'test']: if",
"ctest += 1 ftrain.close() fval.close() ftest.close() # scipy.io.savemat(os.path.join(out_dir, 'img_voxel_idxs.mat'), # {'img_voxel_idxs': np.array(img_voxel_idxs)}) scipy.io.savemat(os.path.join(out_dir,",
"= int(img.split('.')[0]) # 1-3839 img_id_real = list(match_id['img_idxs'][0]).index(id_img_ori) # 0-3493 voxel_id_ori = match_id['voxel_idxs'][0, img_id_real]",
"voxel_ftrain.write(voxel_dirs[i]+'\\n') voxel_ltrain.append(voxel_dirs[i]) voxel_ctrain += 1 elif tmp >= 0.65 and tmp < 0.8:",
"train_txtpath = os.path.join(voxel_txt_dir, 'train.txt') val_txtpath = os.path.join(voxel_txt_dir, 'val.txt') test_txtpath = os.path.join(voxel_txt_dir, 'test.txt') ftrain",
"# img_voxel_idxs = [] img_idxs = [] voxel_idxs = [] train_txtpath = os.path.join(voxel_txt_dir,",
"'val', 'test']: for img in img_names[phase]: id_img_ori = int(img.split('.')[0]) # 1-3839 img_id_real =",
"for i in range(len(pix3d)): # if json_file[i]['img'][4:9] == 'chair' and json_file[i]['voxel'] not in",
"## split images into train, val, test, according to voxels # img_voxel_idxs =",
"+= 1 elif tmp >= 0.65 and tmp < 0.8: fval.write(img_file+'\\n') cval +=",
"in img_match_vox[phase]: print(name) for name in img_match_vox[phase]: if name not in voxel_names[phase]: print(name)",
"'r') as f: voxel_dirs = f.readlines() for i in range(len(voxel_dirs)): voxel_dirs[i] = voxel_dirs[i].strip()",
"{x: sorted(set(img_match_vox[x])) for x in ['train', 'val', 'test']} # pdb.set_trace() for phase in",
"cval += 1 elif voxel_dir in voxel_ltest: ftest.write(img_file+'\\n') ctest += 1 else: tmp",
"out_dir = os.path.join(root, '../output', cls) # out_dir = '/Users/heqian/Research/projects/primitive-based_3d/data/all_classes/chair' voxel_txt_dir = os.path.join(out_dir, 'voxeltxt')",
"= {x: [] for x in ['train', 'val', 'test']} for phase in ['train',",
"True # True-split by 216 models, False-split by 34 images ## split voxels",
"fval = open(val_txtpath, 'w') ftest = open(test_txtpath, 'w') ctrain = 0 cval =",
"voxel_dir in voxel_dirs: # pdb.set_trace() img_file = pix3d[i]['img'].split('/')[-1] #[10:] img_id = int(img_file.split('.')[0]) #int(pix3d[i]['img'][10:14])",
"vox = voxel_all[voxel_id_ori - 1] img_match_vox[phase].append(vox) # img_match_vox[phase].append('model/'+vox) img_match_vox = {x: sorted(set(img_match_vox[x])) for",
"['train', 'val', 'test']} for phase in ['train', 'val', 'test']: for img in img_names[phase]:",
"= os.path.join(voxel_txt_dir, 'train.txt') val_txtpath = os.path.join(voxel_txt_dir, 'val.txt') test_txtpath = os.path.join(voxel_txt_dir, 'test.txt') ftrain =",
"in img_match_vox[phase]: if name not in voxel_names[phase]: print(name) def split_voxel_then_image(cls): # data_dir =",
"= f.readlines() # pix3d_dir = os.path.join(root, '../input/pix3d.json') # pix3d = json.load(open(pix3d_dir, 'r')) match_id",
"voxel_dirs[i].strip() voxel_dirs[i] = voxel_dirs[i] tmp = random.random() if tmp < 0.65: voxel_ftrain.write(voxel_dirs[i]+'\\n') voxel_ltrain.append(voxel_dirs[i])",
"= pix3d[i]['voxel'][6:] if voxel_dir in voxel_dirs: # pdb.set_trace() img_file = pix3d[i]['img'].split('/')[-1] #[10:] img_id",
"if split_by_model: if voxel_dir in voxel_ltrain: ftrain.write(img_file+'\\n') ctrain += 1 elif voxel_dir in",
"= open(voxel_test_txtpath, 'w') voxel_ltrain = [] voxel_lval = [] voxel_ltest = [] voxel_ctrain",
"= [] voxel_ltest = [] voxel_ctrain = 0 voxel_cval = 0 voxel_ctest =",
"int(img_file.split('.')[0]) #int(pix3d[i]['img'][10:14]) img_idxs.append(img_id) voxel_idxs.append(voxel_dirs.index(voxel_dir) + 1) # img_voxel_idxs.append(voxel_dirs.index(voxel_dir)) # if img_id != len(img_voxel_idxs):",
"voxels # img_voxel_idxs = [] img_idxs = [] voxel_idxs = [] train_txtpath =",
"train, val, test root = os.path.abspath('.') out_dir = os.path.join(root, '../output', cls) voxel_txt_dir =",
"tmp < 0.65: voxel_ftrain.write(voxel_dirs[i]+'\\n') voxel_ltrain.append(voxel_dirs[i]) voxel_ctrain += 1 elif tmp >= 0.65 and",
"'val', 'test']} for phase in ['train', 'val', 'test']: for img in img_names[phase]: id_img_ori",
"sorted(set(img_match_vox[x])) for x in ['train', 'val', 'test']} # pdb.set_trace() for phase in ['train',",
"img_match_vox = {x: [] for x in ['train', 'val', 'test']} for phase in",
"img_match_vox[phase].append(vox) # img_match_vox[phase].append('model/'+vox) img_match_vox = {x: sorted(set(img_match_vox[x])) for x in ['train', 'val', 'test']}",
"1 elif tmp >= 0.65 and tmp < 0.8: voxel_fval.write(voxel_dirs[i]+'\\n') voxel_lval.append(voxel_dirs[i]) voxel_cval +=",
"'w') voxel_ftest = open(voxel_test_txtpath, 'w') voxel_ltrain = [] voxel_lval = [] voxel_ltest =",
"# data_dir = '/Users/heqian/Research/projects/3dprnn/data/pix3d' split_by_model = True # True-split by 216 models, False-split",
"os.path.join(root, '../output', cls) voxel_txt_dir = os.path.join(out_dir, 'voxeltxt') if not os.path.exists(voxel_txt_dir): os.makedirs(voxel_txt_dir) voxel_train_txtpath =",
"x in ['train', 'val', 'test']} with open(os.path.join(out_dir, 'voxels_dir_{}.txt'.format(cls)), 'r') as f: voxel_all =",
"in ['train', 'val', 'test']} for phase in ['train', 'val', 'test']: for img in",
"voxel_ctrain = 0 voxel_cval = 0 voxel_ctest = 0 with open(os.path.join(out_dir, 'voxels_dir_{}.txt'.format(cls)), 'r')",
"random.random() if tmp < 0.65: voxel_ftrain.write(voxel_dirs[i]+'\\n') voxel_ltrain.append(voxel_dirs[i]) voxel_ctrain += 1 elif tmp >=",
"= {x: os.path.join(voxel_txt_dir, 'voxel_{}.txt'.format(x)) for x in ['train', 'val', 'test']} img_dirs = {x:",
"= f.readlines() for i in range(len(voxel_dirs)): voxel_dirs[i] = voxel_dirs[i].strip() voxel_dirs[i] = voxel_dirs[i] tmp",
"f.readlines() voxel_names = {} img_names = {} for phase in ['train', 'val', 'test']:",
"= scipy.io.loadmat(os.path.join(out_dir, 'img_voxel_idxs.mat')) img_match_vox = {x: [] for x in ['train', 'val', 'test']}",
"= 0 voxel_cval = 0 voxel_ctest = 0 with open(os.path.join(out_dir, 'voxels_dir_{}.txt'.format(cls)), 'r') as",
"voxel_ltrain: ftrain.write(img_file+'\\n') ctrain += 1 elif voxel_dir in voxel_lval: fval.write(img_file+'\\n') cval += 1",
"open(os.path.join(out_dir, 'voxels_dir_{}.txt'.format(cls)), 'r') as f: voxel_dirs = f.readlines() for i in range(len(voxel_dirs)): voxel_dirs[i]",
"else: voxel_ftest.write(voxel_dirs[i]+'\\n') voxel_ltest.append(voxel_dirs[i]) voxel_ctest += 1 voxel_ftrain.close() voxel_fval.close() voxel_ftest.close() ## split images into",
"'w') voxel_ltrain = [] voxel_lval = [] voxel_ltest = [] voxel_ctrain = 0",
"voxel_names[phase] = f.readlines() with open(os.path.join(img_dirs[phase]), 'r') as f: img_names[phase] = f.readlines() # pix3d_dir",
"ctest) print(len(img_idxs)) if __name__ == '__main__': cls_all = ['chair', 'bed', 'bookcase', 'desk', 'misc',",
"0 with open(os.path.join(out_dir, 'voxels_dir_{}.txt'.format(cls)), 'r') as f: voxel_dirs = f.readlines() for i in",
"voxel_lval: fval.write(img_file+'\\n') cval += 1 elif voxel_dir in voxel_ltest: ftest.write(img_file+'\\n') ctest += 1",
"open(voxel_test_txtpath, 'w') voxel_ltrain = [] voxel_lval = [] voxel_ltest = [] voxel_ctrain =",
"range(len(pix3d)): # if json_file[i]['img'][4:9] == 'chair' and json_file[i]['voxel'] not in voxel_dirs: # print(json_file[i]['img'],",
"['train', 'val', 'test']} # pdb.set_trace() for phase in ['train', 'val', 'test']: if len(set(voxel_names[phase]).difference(set(img_match_vox[phase])))",
"[] voxel_ctrain = 0 voxel_cval = 0 voxel_ctest = 0 with open(os.path.join(out_dir, 'voxels_dir_{}.txt'.format(cls)),",
"+ 1) # img_voxel_idxs.append(voxel_dirs.index(voxel_dir)) # if img_id != len(img_voxel_idxs): # print('Error!!!=======', img_id) if",
"> 0: print('error') if len(set(img_match_vox[phase]).difference(set(voxel_names[phase]))) > 0: print('error') for name in voxel_names[phase]: if",
"# pdb.set_trace() for phase in ['train', 'val', 'test']: if len(set(voxel_names[phase]).difference(set(img_match_vox[phase]))) > 0: print('error')",
"for phase in ['train', 'val', 'test']: with open(os.path.join(voxel_dirs[phase]), 'r') as f: voxel_names[phase] =",
"tmp < 0.8: voxel_fval.write(voxel_dirs[i]+'\\n') voxel_lval.append(voxel_dirs[i]) voxel_cval += 1 else: voxel_ftest.write(voxel_dirs[i]+'\\n') voxel_ltest.append(voxel_dirs[i]) voxel_ctest +=",
"in ['train', 'val', 'test']} with open(os.path.join(out_dir, 'voxels_dir_{}.txt'.format(cls)), 'r') as f: voxel_all = f.readlines()",
"print(name) def split_voxel_then_image(cls): # data_dir = '/Users/heqian/Research/projects/3dprnn/data/pix3d' split_by_model = True # True-split by",
"phase in ['train', 'val', 'test']: if len(set(voxel_names[phase]).difference(set(img_match_vox[phase]))) > 0: print('error') if len(set(img_match_vox[phase]).difference(set(voxel_names[phase]))) >",
"f: voxel_dirs = f.readlines() for i in range(len(voxel_dirs)): voxel_dirs[i] = voxel_dirs[i].strip() voxel_dirs[i] =",
"'__main__': cls_all = ['chair', 'bed', 'bookcase', 'desk', 'misc', 'sofa', 'table', 'tool', 'wardrobe'] cls",
"tmp >= 0.65 and tmp < 0.8: fval.write(img_file+'\\n') cval += 1 else: ftest.write(img_file+'\\n')",
"1 elif voxel_dir in voxel_lval: fval.write(img_file+'\\n') cval += 1 elif voxel_dir in voxel_ltest:",
"voxel_idxs = [] train_txtpath = os.path.join(voxel_txt_dir, 'train.txt') val_txtpath = os.path.join(voxel_txt_dir, 'val.txt') test_txtpath =",
"voxel_fval = open(voxel_val_txtpath, 'w') voxel_ftest = open(voxel_test_txtpath, 'w') voxel_ltrain = [] voxel_lval =",
"voxel_ltest: ftest.write(img_file+'\\n') ctest += 1 else: tmp = random.random() if tmp < 0.65:",
"print('error') for name in voxel_names[phase]: if name not in img_match_vox[phase]: print(name) for name",
"i in range(len(voxel_dirs)): voxel_dirs[i] = voxel_dirs[i].strip() voxel_dirs[i] = voxel_dirs[i] tmp = random.random() if",
"os.path.join(voxel_txt_dir, 'voxel_train.txt') voxel_val_txtpath = os.path.join(voxel_txt_dir, 'voxel_val.txt') voxel_test_txtpath = os.path.join(voxel_txt_dir, 'voxel_test.txt') voxel_ftrain = open(voxel_train_txtpath,",
"voxel_ctrain += 1 elif tmp >= 0.65 and tmp < 0.8: voxel_fval.write(voxel_dirs[i]+'\\n') voxel_lval.append(voxel_dirs[i])",
"# {'img_voxel_idxs': np.array(img_voxel_idxs)}) scipy.io.savemat(os.path.join(out_dir, 'img_voxel_idxs.mat'), {'img_idxs': np.array(img_idxs), 'voxel_idxs': np.array(voxel_idxs)}) print(voxel_ctrain+voxel_cval+voxel_ctest, voxel_ctrain, voxel_cval, voxel_ctest)",
"False-split by 34 images ## split voxels into train, val, test root =",
"np.array(img_voxel_idxs)}) scipy.io.savemat(os.path.join(out_dir, 'img_voxel_idxs.mat'), {'img_idxs': np.array(img_idxs), 'voxel_idxs': np.array(voxel_idxs)}) print(voxel_ctrain+voxel_cval+voxel_ctest, voxel_ctrain, voxel_cval, voxel_ctest) print(ctrain+cval+ctest, ctrain,",
"x in ['train', 'val', 'test']} img_dirs = {x: os.path.join(voxel_txt_dir, '{}.txt'.format(x)) for x in",
"0 voxel_ctest = 0 with open(os.path.join(out_dir, 'voxels_dir_{}.txt'.format(cls)), 'r') as f: voxel_dirs = f.readlines()",
"pdb.set_trace() for phase in ['train', 'val', 'test']: if len(set(voxel_names[phase]).difference(set(img_match_vox[phase]))) > 0: print('error') if",
"voxel_ltrain.append(voxel_dirs[i]) voxel_ctrain += 1 elif tmp >= 0.65 and tmp < 0.8: voxel_fval.write(voxel_dirs[i]+'\\n')",
"< 0.8: voxel_fval.write(voxel_dirs[i]+'\\n') voxel_lval.append(voxel_dirs[i]) voxel_cval += 1 else: voxel_ftest.write(voxel_dirs[i]+'\\n') voxel_ltest.append(voxel_dirs[i]) voxel_ctest += 1",
"in ['train', 'val', 'test']: if len(set(voxel_names[phase]).difference(set(img_match_vox[phase]))) > 0: print('error') if len(set(img_match_vox[phase]).difference(set(voxel_names[phase]))) > 0:",
"as np import os import random import json import pdb def check_image_voxel_match(cls): root",
"out_dir = os.path.join(root, '../output', cls) voxel_txt_dir = os.path.join(out_dir, 'voxeltxt') if not os.path.exists(voxel_txt_dir): os.makedirs(voxel_txt_dir)",
"1 else: tmp = random.random() if tmp < 0.65: ftrain.write(img_file+'\\n') ctrain += 1",
"= 0 cval = 0 ctest = 0 pix3d_dir = os.path.join(root, '../input/pix3d.json') pix3d",
"scipy.io import numpy as np import os import random import json import pdb",
"'val', 'test']} img_dirs = {x: os.path.join(voxel_txt_dir, '{}.txt'.format(x)) for x in ['train', 'val', 'test']}",
"if img_id != len(img_voxel_idxs): # print('Error!!!=======', img_id) if split_by_model: if voxel_dir in voxel_ltrain:",
"+= 1 elif tmp >= 0.65 and tmp < 0.8: voxel_fval.write(voxel_dirs[i]+'\\n') voxel_lval.append(voxel_dirs[i]) voxel_cval",
"if not os.path.exists(voxel_txt_dir): os.makedirs(voxel_txt_dir) voxel_train_txtpath = os.path.join(voxel_txt_dir, 'voxel_train.txt') voxel_val_txtpath = os.path.join(voxel_txt_dir, 'voxel_val.txt') voxel_test_txtpath",
"voxels into train, val, test root = os.path.abspath('.') out_dir = os.path.join(root, '../output', cls)",
"voxel_lval = [] voxel_ltest = [] voxel_ctrain = 0 voxel_cval = 0 voxel_ctest",
"img_names[phase]: id_img_ori = int(img.split('.')[0]) # 1-3839 img_id_real = list(match_id['img_idxs'][0]).index(id_img_ori) # 0-3493 voxel_id_ori =",
"id_img_ori = int(img.split('.')[0]) # 1-3839 img_id_real = list(match_id['img_idxs'][0]).index(id_img_ori) # 0-3493 voxel_id_ori = match_id['voxel_idxs'][0,",
"['train', 'val', 'test']} img_dirs = {x: os.path.join(voxel_txt_dir, '{}.txt'.format(x)) for x in ['train', 'val',",
"= 0 with open(os.path.join(out_dir, 'voxels_dir_{}.txt'.format(cls)), 'r') as f: voxel_dirs = f.readlines() for i",
"'/Users/heqian/Research/projects/primitive-based_3d/data/all_classes/chair' voxel_txt_dir = os.path.join(out_dir, 'voxeltxt') voxel_dirs = {x: os.path.join(voxel_txt_dir, 'voxel_{}.txt'.format(x)) for x in",
"'w') ftest = open(test_txtpath, 'w') ctrain = 0 cval = 0 ctest =",
"voxel_ctrain, voxel_cval, voxel_ctest) print(ctrain+cval+ctest, ctrain, cval, ctest) print(len(img_idxs)) if __name__ == '__main__': cls_all",
"'../input/pix3d.json') pix3d = json.load(open(pix3d_dir, 'r')) for i in range(len(pix3d)): # if json_file[i]['img'][4:9] ==",
"os.path.join(root, '../input/pix3d.json') pix3d = json.load(open(pix3d_dir, 'r')) for i in range(len(pix3d)): # if json_file[i]['img'][4:9]",
"'voxels_dir_{}.txt'.format(cls)), 'r') as f: voxel_all = f.readlines() voxel_names = {} img_names = {}",
"print('Error!!!=======', img_id) if split_by_model: if voxel_dir in voxel_ltrain: ftrain.write(img_file+'\\n') ctrain += 1 elif",
"as f: voxel_all = f.readlines() voxel_names = {} img_names = {} for phase",
"os.path.join(voxel_txt_dir, 'val.txt') test_txtpath = os.path.join(voxel_txt_dir, 'test.txt') ftrain = open(train_txtpath, 'w') fval = open(val_txtpath,",
"voxel_dirs: # print(json_file[i]['img'], json_file[i]['voxel']) voxel_dir = pix3d[i]['voxel'][6:] if voxel_dir in voxel_dirs: # pdb.set_trace()",
"voxel_dir in voxel_ltest: ftest.write(img_file+'\\n') ctest += 1 else: tmp = random.random() if tmp",
"os import random import json import pdb def check_image_voxel_match(cls): root = os.path.abspath('.') out_dir",
"pix3d = json.load(open(pix3d_dir, 'r')) match_id = scipy.io.loadmat(os.path.join(out_dir, 'img_voxel_idxs.mat')) img_match_vox = {x: [] for",
"0: print('error') for name in voxel_names[phase]: if name not in img_match_vox[phase]: print(name) for",
"# 1-216 vox = voxel_all[voxel_id_ori - 1] img_match_vox[phase].append(vox) # img_match_vox[phase].append('model/'+vox) img_match_vox = {x:",
"'table', 'tool', 'wardrobe'] cls = 'table' # for cls in cls_all: split_voxel_then_image(cls) check_image_voxel_match(cls)",
"# pix3d_dir = os.path.join(root, '../input/pix3d.json') # pix3d = json.load(open(pix3d_dir, 'r')) match_id = scipy.io.loadmat(os.path.join(out_dir,",
"elif voxel_dir in voxel_lval: fval.write(img_file+'\\n') cval += 1 elif voxel_dir in voxel_ltest: ftest.write(img_file+'\\n')",
"in voxel_ltrain: ftrain.write(img_file+'\\n') ctrain += 1 elif voxel_dir in voxel_lval: fval.write(img_file+'\\n') cval +=",
"1 ftrain.close() fval.close() ftest.close() # scipy.io.savemat(os.path.join(out_dir, 'img_voxel_idxs.mat'), # {'img_voxel_idxs': np.array(img_voxel_idxs)}) scipy.io.savemat(os.path.join(out_dir, 'img_voxel_idxs.mat'), {'img_idxs':",
"'test']: if len(set(voxel_names[phase]).difference(set(img_match_vox[phase]))) > 0: print('error') if len(set(img_match_vox[phase]).difference(set(voxel_names[phase]))) > 0: print('error') for name",
"name in img_match_vox[phase]: if name not in voxel_names[phase]: print(name) def split_voxel_then_image(cls): # data_dir",
"'img_voxel_idxs.mat')) img_match_vox = {x: [] for x in ['train', 'val', 'test']} for phase",
"voxel_ltest.append(voxel_dirs[i]) voxel_ctest += 1 voxel_ftrain.close() voxel_fval.close() voxel_ftest.close() ## split images into train, val,",
"else: ftest.write(img_file+'\\n') ctest += 1 ftrain.close() fval.close() ftest.close() # scipy.io.savemat(os.path.join(out_dir, 'img_voxel_idxs.mat'), # {'img_voxel_idxs':",
"= os.path.join(out_dir, 'voxeltxt') if not os.path.exists(voxel_txt_dir): os.makedirs(voxel_txt_dir) voxel_train_txtpath = os.path.join(voxel_txt_dir, 'voxel_train.txt') voxel_val_txtpath =",
"open(val_txtpath, 'w') ftest = open(test_txtpath, 'w') ctrain = 0 cval = 0 ctest",
"cval, ctest) print(len(img_idxs)) if __name__ == '__main__': cls_all = ['chair', 'bed', 'bookcase', 'desk',",
"= os.path.join(root, '../output', cls) voxel_txt_dir = os.path.join(out_dir, 'voxeltxt') if not os.path.exists(voxel_txt_dir): os.makedirs(voxel_txt_dir) voxel_train_txtpath",
"in voxel_names[phase]: if name not in img_match_vox[phase]: print(name) for name in img_match_vox[phase]: if",
"voxel_names[phase]: if name not in img_match_vox[phase]: print(name) for name in img_match_vox[phase]: if name",
"print(json_file[i]['img'], json_file[i]['voxel']) voxel_dir = pix3d[i]['voxel'][6:] if voxel_dir in voxel_dirs: # pdb.set_trace() img_file =",
"tmp = random.random() if tmp < 0.65: voxel_ftrain.write(voxel_dirs[i]+'\\n') voxel_ltrain.append(voxel_dirs[i]) voxel_ctrain += 1 elif",
"'test']: for img in img_names[phase]: id_img_ori = int(img.split('.')[0]) # 1-3839 img_id_real = list(match_id['img_idxs'][0]).index(id_img_ori)",
"= f.readlines() with open(os.path.join(img_dirs[phase]), 'r') as f: img_names[phase] = f.readlines() # pix3d_dir =",
"cls) # out_dir = '/Users/heqian/Research/projects/primitive-based_3d/data/all_classes/chair' voxel_txt_dir = os.path.join(out_dir, 'voxeltxt') voxel_dirs = {x: os.path.join(voxel_txt_dir,",
"= {x: sorted(set(img_match_vox[x])) for x in ['train', 'val', 'test']} # pdb.set_trace() for phase",
"voxel_dir = pix3d[i]['voxel'][6:] if voxel_dir in voxel_dirs: # pdb.set_trace() img_file = pix3d[i]['img'].split('/')[-1] #[10:]",
"out_dir = '/Users/heqian/Research/projects/primitive-based_3d/data/all_classes/chair' voxel_txt_dir = os.path.join(out_dir, 'voxeltxt') voxel_dirs = {x: os.path.join(voxel_txt_dir, 'voxel_{}.txt'.format(x)) for",
"elif tmp >= 0.65 and tmp < 0.8: fval.write(img_file+'\\n') cval += 1 else:",
"= {x: os.path.join(voxel_txt_dir, '{}.txt'.format(x)) for x in ['train', 'val', 'test']} with open(os.path.join(out_dir, 'voxels_dir_{}.txt'.format(cls)),",
"if name not in img_match_vox[phase]: print(name) for name in img_match_vox[phase]: if name not",
"= os.path.abspath('.') out_dir = os.path.join(root, '../output', cls) voxel_txt_dir = os.path.join(out_dir, 'voxeltxt') if not",
"tmp >= 0.65 and tmp < 0.8: voxel_fval.write(voxel_dirs[i]+'\\n') voxel_lval.append(voxel_dirs[i]) voxel_cval += 1 else:",
"voxel_dirs = f.readlines() for i in range(len(voxel_dirs)): voxel_dirs[i] = voxel_dirs[i].strip() voxel_dirs[i] = voxel_dirs[i]",
"[] for x in ['train', 'val', 'test']} for phase in ['train', 'val', 'test']:"
] |
[
"name off the path with no format args. This presumes that # different",
"{ \"type\": match_type.value if match_type else None, \"realm\": realm.value if realm else None,",
"str, realm: Optional[Realm] = None, ) -> Ladder: \"\"\"Get the ladder of a",
"off the path with no format args. This presumes that # different requests",
"UNTESTED. HAS NOT BEEN USED IN PRODUCTION. \"\"\" async def get_public_stash_tabs( self, next_change_id:",
"get_pvp_match_ladder( self, match: str, realm: Optional[Realm] = None, ) -> PvPMatchLadder: \"\"\"Get a",
"# noqa: WPS211 self, realm: Optional[Realm] = None, league_type: Optional[LeagueType] = None, offset:",
"query=query, ) async def get_pvp_match( self, match: str, realm: Optional[Realm] = None, )",
"understand # that kwargs isn't a positional arg and won't override a different",
"poe_client.schemas.filter import ItemFilter from poe_client.schemas.league import Ladder, League, LeagueType from poe_client.schemas.pvp import PvPMatch,",
"multiple to better split up # the different APIs to simplify reading. There",
"BEEN USED IN PRODUCTION. \"\"\" async def get_profile( self, ) -> Account: \"\"\"Get",
"key the policy name off the path with no format args. This presumes",
"if match_type == PvPMatchType.season and not season: raise ValueError(\"season cannot be empty if",
"return await self._get( path=\"league/{0}\", path_format_args=(league,), model=League, result_field=\"league\", query=query, ) async def get_league_ladder( self,",
"PRODUCTION. \"\"\" async def get_item_filters( self, ) -> List[ItemFilter]: \"\"\"Get all item filters.\"\"\"",
"_path_to_policy_names: Dict[str, str] def __init__( self, user_agent: str, token: Optional[str] = None, )",
"if league_type == LeagueType.season and not season: raise ValueError(\"season cannot be empty if",
"*args, **kwargs, ) -> Model: \"\"\"Make a get request and returns the data",
"-> Character: \"\"\"Get a character based on id and account of token.\"\"\" return",
"query=query, ) class _AccountMixin(Client): \"\"\"User account methods for the POE API. CURRENTLY UNTESTED.",
"def get_league( self, league: str, realm: Optional[Realm] = None, ) -> League: \"\"\"Get",
"noqa: WPS336 path_format_args.append(substash_id) return await self._get( path=path, path_format_args=path_format_args, model=StashTab, result_field=\"stash\", ) class _FilterMixin(Client):",
"set, returns the next set of stash tabs, starting at this change_id. While",
"self, model: Callable[..., Model], result_field: Optional[str] = None, *args, **kwargs, ) -> Model:",
"the Path of Exile API.\"\"\" _token: Optional[str] _base_url: URL = URL(\"https://api.pathofexile.com\") _client: aiohttp.ClientSession",
"it can't understand # that kwargs isn't a positional arg and won't override",
"None, offset: int = 0, season: str = \"\", limit: int = 50,",
"on id.\"\"\" path = \"stash/{0}/{1}\".format(league, stash_id) path_format_args = [league, stash_id] if substash_id: path",
"match_type: Optional[PvPMatchType] = None, season: str = \"\", league: str = \"\", )",
"_LeagueMixin, _AccountMixin, _FilterMixin, _PublicStashMixin, Client, ): \"\"\"Client for PoE API. This technically has",
"an account name, so it's not a base path. # \"/character/\" is the",
"\"\"\"Get a character based on id and account of token.\"\"\" return await self._get(",
"model=Character, result_field=\"character\", ) async def get_stashes( self, league: str, ) -> List[StashTab]: \"\"\"Get",
"certain parts of the path are non-static (account ID), those should be encoded",
"self, match: str, realm: Optional[Realm] = None, ) -> PvPMatchLadder: \"\"\"Get a pvp",
"league.\") # We construct this via a dict so that the linter doesn't",
"belonging to token.\"\"\" return await self._get_list( path=\"character\", model=Character, result_field=\"characters\", ) async def get_character(",
"HTTP request gets made. query: An optional dict of query params to add",
"of the `model` type. \"\"\" json_result = await self._get_json(*args, **kwargs) if result_field: assert",
"tabs from the beginning of the API's availability which is several years in",
"key, query_val in query.items() if query_val} return await self._get_list( path=\"league\", model=League, result_field=\"leagues\", query=query,",
"\"\"\" async def get_public_stash_tabs( self, next_change_id: Optional[str] = None, ) -> PublicStash: \"\"\"Get",
"token.\"\"\" return await self._get_list( path=\"stash/{0}\", path_format_args=(league,), model=StashTab, result_field=\"stashes\", ) async def get_stash( self,",
"return await self._get( path=path, path_format_args=path_format_args, model=StashTab, result_field=\"stash\", ) class _FilterMixin(Client): \"\"\"Item Filter methods",
"use the # same rate limiting. For example, /characters/moowiz and /characters/chris # presumably",
"else None, } # Removed unset query params query = {key: query_val for",
"returns the next set of stash tabs, starting at this change_id. While this",
"PublicStash, StashTab Model = TypeVar(\"Model\") # the variable return type class Client(object): \"\"\"Aiohttp",
"= None, ) -> PvPMatchLadder: \"\"\"Get a pvp match based on id.\"\"\" query",
"linter doesn't complain about # complexity. query = { \"type\": match_type.value if match_type",
"args. Returns: The result, parsed into a list of the `model` type. \"\"\"",
"json_result = json_result[result_field] assert isinstance(json_result, list) # noqa: S101 return [model(**objitem) for objitem",
"request itself. See _get_json for other args. Returns: The result, parsed into an",
"returns the data as a list of APIType subclass. Args: model: The object",
"NOT BEEN USED IN PRODUCTION. \"\"\" async def get_profile( self, ) -> Account:",
"HAS NOT BEEN USED IN PRODUCTION. \"\"\" async def get_pvp_matches( self, realm: Optional[Realm]",
"await self._get( path=\"character/{0}\", path_format_args=(name,), model=Character, result_field=\"character\", ) async def get_stashes( self, league: str,",
"return await self._get( path=\"pvp-match/{0}/ladder\", path_format_args=(match,), model=PvPMatchLadder, result_field=\"match\", query=query, ) class _LeagueMixin(Client): \"\"\"League related",
"Client, ): \"\"\"Client for PoE API. This technically has support for every API",
"complexity. query = { \"realm\": realm.value if realm else None, \"type\": league_type.value if",
"= token self._user_agent = user_agent self._limiter = RateLimiter() self._path_to_policy_names = {} async def",
"**kwargs, # type: ignore ) as resp: self._path_to_policy_names[ path_with_no_args ] = await self._limiter.parse_headers(resp.headers)",
"Optional[Realm] = None, ) -> PvPMatchLadder: \"\"\"Get a pvp match based on id.\"\"\"",
"the HTTP request. Returns: The result of the API request, parsed as JSON.",
"account name, so it's not a base path. # \"/character/\" is the equivalent",
"PRODUCTION. \"\"\" async def get_public_stash_tabs( self, next_change_id: Optional[str] = None, ) -> PublicStash:",
"arg and won't override a different # positional argument in the function. async",
"in range(len(path_format_args)))) policy_name = self._path_to_policy_names.get(path_with_no_args, \"\") kwargs = { \"headers\": { \"User-Agent\": self._user_agent,",
"def get_item_filters( self, ) -> List[ItemFilter]: \"\"\"Get all item filters.\"\"\" return await self._get_list(",
"as resp: self._path_to_policy_names[ path_with_no_args ] = await self._limiter.parse_headers(resp.headers) if resp.status != 200: raise",
"import logging from types import TracebackType from typing import Callable, Dict, List, Optional,",
") -> PublicStash: \"\"\"Get the latest public stash tabs. Args: next_change_id: If set,",
"self, exc_type: Optional[Type[BaseException]], exc_val: Optional[BaseException], exc_tb: Optional[TracebackType], ) -> Optional[bool]: \"\"\"Runs on exiting",
"the data as an APIType subclass. Args: model: The object which contains data",
"assigning booleans here. We can't set the typing inline without # flake8 complaining",
"import PublicStash, StashTab Model = TypeVar(\"Model\") # the variable return type class Client(object):",
"itself. See _get_json for other args. Returns: The result, parsed into an instance",
"**kwargs, ) -> List[Model]: \"\"\"Make a get request and returns the data as",
"result_field=\"match\", query=query, ) class _LeagueMixin(Client): \"\"\"League related methods for the POE API. CURRENTLY",
"await self._get(path=\"league\", model=Account) async def get_characters( self, ) -> List[Character]: \"\"\"Get all characters",
"+= \"/{2}\" # noqa: WPS336 path_format_args.append(substash_id) return await self._get( path=path, path_format_args=path_format_args, model=StashTab, result_field=\"stash\",",
"not a base path. # \"/character/\" is the equivalent \"generic\" path. _path_to_policy_names: Dict[str,",
"async def get_league( self, league: str, realm: Optional[Realm] = None, ) -> League:",
") -> Character: \"\"\"Get a character based on id and account of token.\"\"\"",
"_limiter: RateLimiter # Maps \"generic\" paths to rate limiting policy names. # Generic",
"for some reason it can't understand # that kwargs isn't a positional arg",
"dict of query params to add to the HTTP request. Returns: The result",
"a character based on id and account of token.\"\"\" return await self._get( path=\"character/{0}\",",
"into a list of the `model` type. \"\"\" json_result = await self._get_json(*args, **kwargs)",
"API. CURRENTLY UNTESTED. HAS NOT BEEN USED IN PRODUCTION. \"\"\" async def get_item_filters(",
"args should be passed into path_format_args. path_format_args: Values which should be encoded in",
"Generic paths are paths with no IDs or unique numbers. # For example,",
"class _AccountMixin(Client): \"\"\"User account methods for the POE API. CURRENTLY UNTESTED. HAS NOT",
"get_characters( self, ) -> List[Character]: \"\"\"Get all characters belonging to token.\"\"\" return await",
"the linter doesn't complain about # complexity. query = { \"type\": match_type.value if",
"\"\"\"Item Filter methods for the POE API. CURRENTLY UNTESTED. HAS NOT BEEN USED",
"next_change_id: query[\"id\"] = next_change_id return await self._get_json( path=\"public-stash-tabs\", query=query, ) # Ignore WPS215,",
"else None, \"league\": league if league else None, } # Removed unset query",
"self, league: str, realm: Optional[Realm] = None, ) -> Ladder: \"\"\"Get the ladder",
"\"stash/{0}/{1}\".format(league, stash_id) path_format_args = [league, stash_id] if substash_id: path += \"/{2}\" # noqa:",
"model=StashTab, result_field=\"stashes\", ) async def get_stash( self, league: str, stash_id: str, substash_id: Optional[str],",
"\"limit\": str(limit) if limit else None, } # Remove unset values query =",
"the latest public stash tabs. Args: next_change_id: If set, returns the next set",
"Optional[bool]: \"\"\"Runs on exiting `async with`.\"\"\" await self._client.close() if exc_val: raise exc_val return",
"__aexit__( self, exc_type: Optional[Type[BaseException]], exc_val: Optional[BaseException], exc_tb: Optional[TracebackType], ) -> Optional[bool]: \"\"\"Runs on",
"this is technically optional, in practice this is required; not setting this value",
"policy name off the path with no format args. This presumes that #",
"None, *args, **kwargs, ) -> Model: \"\"\"Make a get request and returns the",
"override a different # positional argument in the function. async with await self._client.get(",
"is the equivalent \"generic\" path. _path_to_policy_names: Dict[str, str] def __init__( self, user_agent: str,",
"self, ) -> Account: \"\"\"Get the account beloning to the token.\"\"\" return await",
"rate limiting policy names. # Generic paths are paths with no IDs or",
"path_format_args: Values which should be encoded in the path when the HTTP request",
"to use. Appended to the POE API base URL. If certain parts of",
"# type: ignore # The types are ignored because for some reason it",
"ignore is for args and kwargs, which have unknown types we pass to",
"Returns: The result of the API request, parsed as JSON. \"\"\" if not",
"token.\"\"\" return await self._get(path=\"league\", model=Account) async def get_characters( self, ) -> List[Character]: \"\"\"Get",
"for every API GGG has exposed. None of these APIs have been tested",
"= {} if realm: query[\"realm\"] = realm.value return await self._get( path=\"pvp-match/{0}/ladder\", path_format_args=(match,), model=PvPMatchLadder,",
"no format args. This presumes that # different requests to the same endpoints",
"BEEN USED IN PRODUCTION. \"\"\" async def get_pvp_matches( self, realm: Optional[Realm] = None,",
"= {} if realm: query[\"realm\"] = realm.value return await self._get( path=\"league/{0}/ladder\", path_format_args=(league,), model=Ladder,",
"LeagueType from poe_client.schemas.pvp import PvPMatch, PvPMatchLadder, PvPMatchType from poe_client.schemas.stash import PublicStash, StashTab Model",
"= { \"headers\": { \"User-Agent\": self._user_agent, }, \"params\": query, } if self._token: headers",
"about overly complex annotation. logging.info(\"NOT BLOCKING\") kwargs[\"raise_for_status\"] = True # type: ignore else:",
"path=\"pvp-match/{0}/ladder\", path_format_args=(match,), model=PvPMatchLadder, result_field=\"match\", query=query, ) class _LeagueMixin(Client): \"\"\"League related methods for the",
"\"\"\"Get all item filters.\"\"\" return await self._get_list( path=\"item-filter\", model=ItemFilter, result_field=\"filters\", ) async def",
"request, rather than the request itself. See _get_json for other args. Returns: The",
"{key: query_val for key, query_val in query.items() if query_val} return await self._get_list( path=\"pvp-match\",",
"model=PvPMatchLadder, result_field=\"match\", query=query, ) class _LeagueMixin(Client): \"\"\"League related methods for the POE API.",
"realm.value return await self._get( path=\"league/{0}\", path_format_args=(league,), model=League, result_field=\"league\", query=query, ) async def get_league_ladder(",
"else None, \"limit\": str(limit) if limit else None, } # Remove unset values",
"exc_type: Optional[Type[BaseException]], exc_val: Optional[BaseException], exc_tb: Optional[TracebackType], ) -> Optional[bool]: \"\"\"Runs on exiting `async",
"league if league else None, } # Removed unset query params query =",
"to _get_json async def _get_list( # type: ignore self, model: Callable[..., Model], result_field:",
"reason it can't understand # that kwargs isn't a positional arg and won't",
"resp.status, ), ) return await resp.json() class _PvPMixin(Client): \"\"\"PVP related methods for the",
"PRODUCTION. \"\"\" async def get_profile( self, ) -> Account: \"\"\"Get the account beloning",
"tab methods for the POE API. CURRENTLY UNTESTED. HAS NOT BEEN USED IN",
"token: Optional[str] = None, ) -> None: \"\"\"Initialize a new PoE client. Args:",
"= await self._get_json(*args, **kwargs) assert isinstance(json_result, dict) # noqa: S101 if result_field: json_result",
"for key, query_val in query.items() if query_val} return await self._get_list( path=\"pvp-match\", model=PvPMatch, result_field=\"matches\",",
"example, \"/character/moowiz\" has an account name, so it's not a base path. #",
"PvPMatchType from poe_client.schemas.stash import PublicStash, StashTab Model = TypeVar(\"Model\") # the variable return",
"Args: model: The object which contains data retrieved from the API. Must be",
"The result, parsed into an instance of the `model` type. \"\"\" json_result =",
"realm: Optional[Realm] = None, ) -> PvPMatch: \"\"\"Get a pvp match based on",
"tab based on id.\"\"\" path = \"stash/{0}/{1}\".format(league, stash_id) path_format_args = [league, stash_id] if",
"query=query, ) # Ignore WPS215, error about too many base classes. We use",
"for key, query_val in query.items() if query_val} return await self._get_list( path=\"league\", model=League, result_field=\"leagues\",",
"noqa: WPS215 _PvPMixin, _LeagueMixin, _AccountMixin, _FilterMixin, _PublicStashMixin, Client, ): \"\"\"Client for PoE API.",
"in the dict assignment. kwargs only has dicts as values, # but we're",
"limiting policy name. if await self._limiter.get_semaphore(policy_name): # We ignore typing in the dict",
"on league id.\"\"\" query = {} if realm: query[\"realm\"] = realm.value return await",
"await self._get_json(*args, **kwargs) if result_field: assert isinstance(json_result, dict) # noqa: S101 json_result =",
"-> List[Character]: \"\"\"Get all characters belonging to token.\"\"\" return await self._get_list( path=\"character\", model=Character,",
"realm: query[\"realm\"] = realm.value return await self._get( path=\"pvp-match/{0}\", path_format_args=(match,), model=PvPMatch, result_field=\"match\", query=query, )",
"= realm.value return await self._get( path=\"pvp-match/{0}/ladder\", path_format_args=(match,), model=PvPMatchLadder, result_field=\"match\", query=query, ) class _LeagueMixin(Client):",
"token is used. \"\"\" self._token = token self._user_agent = user_agent self._limiter = RateLimiter()",
"isinstance(json_result, list) # noqa: S101 return [model(**objitem) for objitem in json_result] async def",
"= None, match_type: Optional[PvPMatchType] = None, season: str = \"\", league: str =",
"ladder of a league based on id.\"\"\" query = {} if realm: query[\"realm\"]",
"self._limiter.parse_headers(resp.headers) if resp.status != 200: raise ValueError( \"Invalid request: status code {0}, expected",
"await self._get_json(*args, **kwargs) assert isinstance(json_result, dict) # noqa: S101 if result_field: json_result =",
"complaining about overly complex annotation. logging.info(\"NOT BLOCKING\") kwargs[\"raise_for_status\"] = True # type: ignore",
"model=Account) async def get_characters( self, ) -> List[Character]: \"\"\"Get all characters belonging to",
"= TypeVar(\"Model\") # the variable return type class Client(object): \"\"\"Aiohttp class for interacting",
"league based on id.\"\"\" query = {} if realm: query[\"realm\"] = realm.value return",
"= None, *args, **kwargs, ) -> Model: \"\"\"Make a get request and returns",
"): \"\"\"Fetches data from the POE API. Args: path: The URL path to",
"get_stashes( self, league: str, ) -> List[StashTab]: \"\"\"Get all stash tabs belonging to",
"= realm.value return await self._get( path=\"league/{0}\", path_format_args=(league,), model=League, result_field=\"league\", query=query, ) async def",
"no auth token is used. \"\"\" self._token = token self._user_agent = user_agent self._limiter",
"a list of the `model` type. \"\"\" json_result = await self._get_json(*args, **kwargs) if",
"False # type: ignore # The types are ignored because for some reason",
"data from the POE API. Args: path: The URL path to use. Appended",
"those args should be passed into path_format_args. path_format_args: Values which should be encoded",
"# Generic paths are paths with no IDs or unique numbers. # For",
"# \"/character/\" is the equivalent \"generic\" path. _path_to_policy_names: Dict[str, str] def __init__( self,",
"realm: Optional[Realm] = None, match_type: Optional[PvPMatchType] = None, season: str = \"\", league:",
"-> List[ItemFilter]: \"\"\"Get all item filters.\"\"\" return await self._get_list( path=\"item-filter\", model=ItemFilter, result_field=\"filters\", )",
"have unknown types we pass to _get_json async def _get( # type: ignore",
"URL = URL(\"https://api.pathofexile.com\") _client: aiohttp.ClientSession _user_agent: str _limiter: RateLimiter # Maps \"generic\" paths",
"import Ladder, League, LeagueType from poe_client.schemas.pvp import PvPMatch, PvPMatchLadder, PvPMatchType from poe_client.schemas.stash import",
"many base classes. We use multiple to better split up # the different",
"Remove unset values query = {key: query_val for key, query_val in query.items() if",
"Used when making HTTP requests to the API. token: Authorization token to pass",
"has exposed. None of these APIs have been tested in production, so use",
"PoE client. Args: user_agent: An OAuth user agent. Used when making HTTP requests",
"noqa: S101 return [model(**objitem) for objitem in json_result] async def _get_json( self, path:",
"We key the policy name off the path with no format args. This",
"= await self._limiter.parse_headers(resp.headers) if resp.status != 200: raise ValueError( \"Invalid request: status code",
"be empty if league_type is season.\") # We construct this via a dict",
"\"\"\"Fetches data from the POE API. Args: path: The URL path to use.",
"only has dicts as values, # but we're assigning booleans here. We can't",
"path.format(*path_format_args)), **kwargs, # type: ignore ) as resp: self._path_to_policy_names[ path_with_no_args ] = await",
"stash change. \"\"\" query = {} if next_change_id: query[\"id\"] = next_change_id return await",
"/characters/chris # presumably use the same rate limiting policy name. if await self._limiter.get_semaphore(policy_name):",
"args (\"{0}\") in the path, and the values for those args should be",
"else None, \"season\": season if season else None, \"league\": league if league else",
"empty if league_type is league.\") # We construct this via a dict so",
"Values which should be encoded in the path when the HTTP request gets",
"the data in this field from the request, rather than the request itself.",
"the # same rate limiting. For example, /characters/moowiz and /characters/chris # presumably use",
"from poe_client.schemas.character import Character from poe_client.schemas.filter import ItemFilter from poe_client.schemas.league import Ladder, League,",
"if result_field: assert isinstance(json_result, dict) # noqa: S101 json_result = json_result[result_field] assert isinstance(json_result,",
"str = \"\", ) -> List[PvPMatch]: \"\"\"Get a list of all pvp matches",
"str, realm: Optional[Realm] = None, ) -> PvPMatchLadder: \"\"\"Get a pvp match based",
"= { \"realm\": realm.value if realm else None, \"type\": league_type.value if league_type else",
"str]] = None, ): \"\"\"Fetches data from the POE API. Args: path: The",
"id.\"\"\" return await self._get( path=\"item-filter/{0}\", path_format_args=(filterid,), model=ItemFilter, result_field=\"filter\", ) class _PublicStashMixin(Client): \"\"\"Public stash",
"entering `async with`.\"\"\" self._client = aiohttp.ClientSession(raise_for_status=True) return self async def __aexit__( self, exc_type:",
"variable return type class Client(object): \"\"\"Aiohttp class for interacting with the Path of",
"representing a public stash change. \"\"\" query = {} if next_change_id: query[\"id\"] =",
"path=\"character\", model=Character, result_field=\"characters\", ) async def get_character( self, name: str, ) -> Character:",
"_ in range(len(path_format_args)))) policy_name = self._path_to_policy_names.get(path_with_no_args, \"\") kwargs = { \"headers\": { \"User-Agent\":",
"self, name: str, ) -> Character: \"\"\"Get a character based on id and",
"complain about # complexity. query = { \"type\": match_type.value if match_type else None,",
"Optional[PvPMatchType] = None, season: str = \"\", league: str = \"\", ) ->",
"have unknown types we pass to _get_json async def _get_list( # type: ignore",
"next set of stash tabs, starting at this change_id. While this is technically",
"200\".format( resp.status, ), ) return await resp.json() class _PvPMixin(Client): \"\"\"PVP related methods for",
"\"\"\"Get all characters belonging to token.\"\"\" return await self._get_list( path=\"character\", model=Character, result_field=\"characters\", )",
"path. _path_to_policy_names: Dict[str, str] def __init__( self, user_agent: str, token: Optional[str] = None,",
"{ \"realm\": realm.value if realm else None, \"type\": league_type.value if league_type else None,",
"type: ignore else: logging.info(\"BLOCKING\") kwargs[\"raise_for_status\"] = False # type: ignore # The types",
"noqa: S101 json_result = json_result[result_field] assert isinstance(json_result, list) # noqa: S101 return [model(**objitem)",
"{} if realm: query[\"realm\"] = realm.value return await self._get( path=\"league/{0}/ladder\", path_format_args=(league,), model=Ladder, result_field=\"ladder\",",
"POE API base URL. If certain parts of the path are non-static (account",
"path_format_args=(match,), model=PvPMatchLadder, result_field=\"match\", query=query, ) class _LeagueMixin(Client): \"\"\"League related methods for the POE",
"interacting with the Path of Exile API.\"\"\" _token: Optional[str] _base_url: URL = URL(\"https://api.pathofexile.com\")",
"but we're assigning booleans here. We can't set the typing inline without #",
"An optional dict of query params to add to the HTTP request. Returns:",
"paths with no IDs or unique numbers. # For example, \"/character/moowiz\" has an",
"self._get( path=\"league/{0}\", path_format_args=(league,), model=League, result_field=\"league\", query=query, ) async def get_league_ladder( self, league: str,",
"async def get_item_filters( self, ) -> List[ItemFilter]: \"\"\"Get all item filters.\"\"\" return await",
"POE API. CURRENTLY UNTESTED. HAS NOT BEEN USED IN PRODUCTION. \"\"\" async def",
"of all leagues based on filters.\"\"\" if league_type == LeagueType.season and not season:",
"any complicated inheritance # going on here. class PoEClient( # noqa: WPS215 _PvPMixin,",
"ignore else: logging.info(\"BLOCKING\") kwargs[\"raise_for_status\"] = False # type: ignore # The types are",
"to the HTTP request. Returns: The result of the API request, parsed as",
"Path of Exile API.\"\"\" _token: Optional[str] _base_url: URL = URL(\"https://api.pathofexile.com\") _client: aiohttp.ClientSession _user_agent:",
"\"\"\" async def get_item_filters( self, ) -> List[ItemFilter]: \"\"\"Get all item filters.\"\"\" return",
"PvPMatchType.season and not season: raise ValueError(\"season cannot be empty if league_type is season.\")",
"async def get_characters( self, ) -> List[Character]: \"\"\"Get all characters belonging to token.\"\"\"",
"headers = kwargs[\"headers\"] assert headers # noqa: S101 headers[\"Authorization\"] = \"Bearer {0}\".format(self._token) #",
"user agent. Used when making HTTP requests to the API. token: Authorization token",
"str(limit) if limit else None, } # Remove unset values query = {key:",
"up # the different APIs to simplify reading. There isn't any complicated inheritance",
"the equivalent \"generic\" path. _path_to_policy_names: Dict[str, str] def __init__( self, user_agent: str, token:",
"Optional[Realm] = None, ) -> Ladder: \"\"\"Get the ladder of a league based",
"json_result = json_result[result_field] return model(**json_result) # Type ignore is for args and kwargs,",
"path_format_args=(league,), model=League, result_field=\"league\", query=query, ) async def get_league_ladder( self, league: str, realm: Optional[Realm]",
"URL from poe_client.rate_limiter import RateLimiter from poe_client.schemas.account import Account, Realm from poe_client.schemas.character import",
"the function. async with await self._client.get( \"{0}/{1}\".format(self._base_url, path.format(*path_format_args)), **kwargs, # type: ignore )",
"dict representing a public stash change. \"\"\" query = {} if next_change_id: query[\"id\"]",
"= json_result[result_field] assert isinstance(json_result, list) # noqa: S101 return [model(**objitem) for objitem in",
"get_league( self, league: str, realm: Optional[Realm] = None, ) -> League: \"\"\"Get a",
"# Remove unset values query = {key: query_val for key, query_val in query.items()",
"UNTESTED. HAS NOT BEEN USED IN PRODUCTION. \"\"\" async def get_pvp_matches( self, realm:",
"typing import Callable, Dict, List, Optional, Type, TypeVar import aiohttp from yarl import",
") -> Optional[bool]: \"\"\"Runs on exiting `async with`.\"\"\" await self._client.close() if exc_val: raise",
"Model], result_field: Optional[str] = None, *args, **kwargs, ) -> Model: \"\"\"Make a get",
"def _get_list( # type: ignore self, model: Callable[..., Model], result_field: Optional[str] = None,",
"a list of all pvp matches based on filters.\"\"\" if match_type == PvPMatchType.season",
"str, path_format_args: Optional[List[str]] = None, query: Optional[Dict[str, str]] = None, ): \"\"\"Fetches data",
"None, \"season\": season if season else None, \"offset\": str(offset) if offset else None,",
"== LeagueType.season and not season: raise ValueError(\"season cannot be empty if league_type is",
"PoE API. If unset, no auth token is used. \"\"\" self._token = token",
"list of APIType subclass. Args: model: The object which contains data retrieved from",
"request. Returns: The result of the API request, parsed as JSON. \"\"\" if",
"result_field: Optional[str] = None, *args, **kwargs, ) -> List[Model]: \"\"\"Make a get request",
"noqa: S101 if result_field: json_result = json_result[result_field] return model(**json_result) # Type ignore is",
"PublicStash: \"\"\"Get the latest public stash tabs. Args: next_change_id: If set, returns the",
"id.\"\"\" path = \"stash/{0}/{1}\".format(league, stash_id) path_format_args = [league, stash_id] if substash_id: path +=",
"resp: self._path_to_policy_names[ path_with_no_args ] = await self._limiter.parse_headers(resp.headers) if resp.status != 200: raise ValueError(",
"API. Must be a sublclass of APIType. result_field: If present, returns the data",
"Optional[Realm] = None, match_type: Optional[PvPMatchType] = None, season: str = \"\", league: str",
"= realm.value return await self._get( path=\"league/{0}/ladder\", path_format_args=(league,), model=Ladder, result_field=\"ladder\", query=query, ) class _AccountMixin(Client):",
"filters.\"\"\" return await self._get_list( path=\"item-filter\", model=ItemFilter, result_field=\"filters\", ) async def get_item_filter( self, filterid:",
"# type: ignore else: logging.info(\"BLOCKING\") kwargs[\"raise_for_status\"] = False # type: ignore # The",
"str, ) -> List[StashTab]: \"\"\"Get all stash tabs belonging to token.\"\"\" return await",
"new PoE client. Args: user_agent: An OAuth user agent. Used when making HTTP",
"years in the past. Returns: A dict representing a public stash change. \"\"\"",
"for the POE API. CURRENTLY UNTESTED. HAS NOT BEEN USED IN PRODUCTION. \"\"\"",
"change_id. While this is technically optional, in practice this is required; not setting",
"starting at this change_id. While this is technically optional, in practice this is",
"code {0}, expected 200\".format( resp.status, ), ) return await resp.json() class _PvPMixin(Client): \"\"\"PVP",
"path, and the values for those args should be passed into path_format_args. path_format_args:",
"support for every API GGG has exposed. None of these APIs have been",
"# the different APIs to simplify reading. There isn't any complicated inheritance #",
"S101 if result_field: json_result = json_result[result_field] return model(**json_result) # Type ignore is for",
"= 50, ) -> List[League]: \"\"\"Get a list of all leagues based on",
"def _get( # type: ignore self, model: Callable[..., Model], result_field: Optional[str] = None,",
"get_profile( self, ) -> Account: \"\"\"Get the account beloning to the token.\"\"\" return",
"same rate limiting. For example, /characters/moowiz and /characters/chris # presumably use the same",
"= user_agent self._limiter = RateLimiter() self._path_to_policy_names = {} async def __aenter__(self) -> \"Client\":",
"request and returns the data as an APIType subclass. Args: model: The object",
"that kwargs isn't a positional arg and won't override a different # positional",
"exc_val return True # Type ignore is for args and kwargs, which have",
"a league based on id.\"\"\" query = {} if realm: query[\"realm\"] = realm.value",
"# We construct this via a dict so that the linter doesn't complain",
"public stash tabs. Args: next_change_id: If set, returns the next set of stash",
"if await self._limiter.get_semaphore(policy_name): # We ignore typing in the dict assignment. kwargs only",
"via a dict so that the linter doesn't complain about # complexity. query",
"\"league\": league if league else None, } # Removed unset query params query",
"return await self._get_list( path=\"pvp-match\", model=PvPMatch, result_field=\"matches\", query=query, ) async def get_pvp_match( self, match:",
"\"\"\"Get the account beloning to the token.\"\"\" return await self._get(path=\"league\", model=Account) async def",
"and kwargs, which have unknown types we pass to _get_json async def _get(",
"if league_type else None, \"season\": season if season else None, \"offset\": str(offset) if",
"_get_json for other args. Returns: The result, parsed into an instance of the",
"await self._get_list( path=\"stash/{0}\", path_format_args=(league,), model=StashTab, result_field=\"stashes\", ) async def get_stash( self, league: str,",
"headers # noqa: S101 headers[\"Authorization\"] = \"Bearer {0}\".format(self._token) # We key the policy",
"requests to the API. token: Authorization token to pass to the PoE API.",
"def __aexit__( self, exc_type: Optional[Type[BaseException]], exc_val: Optional[BaseException], exc_tb: Optional[TracebackType], ) -> Optional[bool]: \"\"\"Runs",
"query[\"realm\"] = realm.value return await self._get( path=\"pvp-match/{0}\", path_format_args=(match,), model=PvPMatch, result_field=\"match\", query=query, ) async",
"int = 50, ) -> List[League]: \"\"\"Get a list of all leagues based",
"raise ValueError(\"season cannot be empty if league_type is season.\") if match_type == PvPMatchType.league",
"CURRENTLY UNTESTED. HAS NOT BEEN USED IN PRODUCTION. \"\"\" async def get_profile( self,",
"HAS NOT BEEN USED IN PRODUCTION. \"\"\" async def list_leagues( # noqa: WPS211",
"belonging to token.\"\"\" return await self._get_list( path=\"stash/{0}\", path_format_args=(league,), model=StashTab, result_field=\"stashes\", ) async def",
"USED IN PRODUCTION. \"\"\" async def get_public_stash_tabs( self, next_change_id: Optional[str] = None, )",
"-> Model: \"\"\"Make a get request and returns the data as an APIType",
"path_format_args=(league,), model=StashTab, result_field=\"stashes\", ) async def get_stash( self, league: str, stash_id: str, substash_id:",
"query_val for key, query_val in query.items() if query_val} return await self._get_list( path=\"pvp-match\", model=PvPMatch,",
"a get request and returns the data as a list of APIType subclass.",
"get_stash( self, league: str, stash_id: str, substash_id: Optional[str], ) -> StashTab: \"\"\"Get a",
"parts of the path are non-static (account ID), those should be encoded as",
"season else None, \"offset\": str(offset) if offset else None, \"limit\": str(limit) if limit",
") async def get_pvp_match( self, match: str, realm: Optional[Realm] = None, ) ->",
"_token: Optional[str] _base_url: URL = URL(\"https://api.pathofexile.com\") _client: aiohttp.ClientSession _user_agent: str _limiter: RateLimiter #",
"\"{0}/{1}\".format(self._base_url, path.format(*path_format_args)), **kwargs, # type: ignore ) as resp: self._path_to_policy_names[ path_with_no_args ] =",
"for args and kwargs, which have unknown types we pass to _get_json async",
"Optional[Realm] = None, ) -> League: \"\"\"Get a league based on league id.\"\"\"",
"class _PublicStashMixin(Client): \"\"\"Public stash tab methods for the POE API. CURRENTLY UNTESTED. HAS",
") class _LeagueMixin(Client): \"\"\"League related methods for the POE API. CURRENTLY UNTESTED. HAS",
"We use multiple to better split up # the different APIs to simplify",
"we pass to _get_json async def _get( # type: ignore self, model: Callable[...,",
"to _get_json async def _get( # type: ignore self, model: Callable[..., Model], result_field:",
"requests to the same endpoints with different specific args use the # same",
"overly complex annotation. logging.info(\"NOT BLOCKING\") kwargs[\"raise_for_status\"] = True # type: ignore else: logging.info(\"BLOCKING\")",
"with different specific args use the # same rate limiting. For example, /characters/moowiz",
"poe_client.schemas.account import Account, Realm from poe_client.schemas.character import Character from poe_client.schemas.filter import ItemFilter from",
"use the same rate limiting policy name. if await self._limiter.get_semaphore(policy_name): # We ignore",
"None, ) -> PvPMatch: \"\"\"Get a pvp match based on id.\"\"\" query =",
"else None, \"realm\": realm.value if realm else None, \"season\": season if season else",
"await self._get_list( path=\"pvp-match\", model=PvPMatch, result_field=\"matches\", query=query, ) async def get_pvp_match( self, match: str,",
"get_item_filters( self, ) -> List[ItemFilter]: \"\"\"Get all item filters.\"\"\" return await self._get_list( path=\"item-filter\",",
"An OAuth user agent. Used when making HTTP requests to the API. token:",
"season: raise ValueError(\"season cannot be empty if league_type is season.\") if match_type ==",
"from poe_client.schemas.pvp import PvPMatch, PvPMatchLadder, PvPMatchType from poe_client.schemas.stash import PublicStash, StashTab Model =",
"unknown types we pass to _get_json async def _get_list( # type: ignore self,",
"async def list_leagues( # noqa: WPS211 self, realm: Optional[Realm] = None, league_type: Optional[LeagueType]",
"yarl import URL from poe_client.rate_limiter import RateLimiter from poe_client.schemas.account import Account, Realm from",
"if league else None, } # Removed unset query params query = {key:",
"so that the linter doesn't complain about # complexity. query = { \"type\":",
"\"generic\" path. _path_to_policy_names: Dict[str, str] def __init__( self, user_agent: str, token: Optional[str] =",
"json_result[result_field] assert isinstance(json_result, list) # noqa: S101 return [model(**objitem) for objitem in json_result]",
"model: Callable[..., Model], result_field: Optional[str] = None, *args, **kwargs, ) -> List[Model]: \"\"\"Make",
"type: ignore ) as resp: self._path_to_policy_names[ path_with_no_args ] = await self._limiter.parse_headers(resp.headers) if resp.status",
"the request, rather than the request itself. See _get_json for other args. Returns:",
"path: str, path_format_args: Optional[List[str]] = None, query: Optional[Dict[str, str]] = None, ): \"\"\"Fetches",
"request: status code {0}, expected 200\".format( resp.status, ), ) return await resp.json() class",
"be empty if league_type is league.\") # We construct this via a dict",
"\"offset\": str(offset) if offset else None, \"limit\": str(limit) if limit else None, }",
"HTTP requests to the API. token: Authorization token to pass to the PoE",
") -> PvPMatch: \"\"\"Get a pvp match based on id.\"\"\" query = {}",
"league_type: Optional[LeagueType] = None, offset: int = 0, season: str = \"\", limit:",
"assert isinstance(json_result, dict) # noqa: S101 json_result = json_result[result_field] assert isinstance(json_result, list) #",
"# noqa: WPS336 path_format_args.append(substash_id) return await self._get( path=path, path_format_args=path_format_args, model=StashTab, result_field=\"stash\", ) class",
"self, ) -> List[Character]: \"\"\"Get all characters belonging to token.\"\"\" return await self._get_list(",
"-> PublicStash: \"\"\"Get the latest public stash tabs. Args: next_change_id: If set, returns",
"dict) # noqa: S101 if result_field: json_result = json_result[result_field] return model(**json_result) # Type",
"= URL(\"https://api.pathofexile.com\") _client: aiohttp.ClientSession _user_agent: str _limiter: RateLimiter # Maps \"generic\" paths to",
"assert headers # noqa: S101 headers[\"Authorization\"] = \"Bearer {0}\".format(self._token) # We key the",
"self, path: str, path_format_args: Optional[List[str]] = None, query: Optional[Dict[str, str]] = None, ):",
"error about too many base classes. We use multiple to better split up",
"use multiple to better split up # the different APIs to simplify reading.",
"If certain parts of the path are non-static (account ID), those should be",
"200: raise ValueError( \"Invalid request: status code {0}, expected 200\".format( resp.status, ), )",
"pass to _get_json async def _get_list( # type: ignore self, model: Callable[..., Model],",
"the token.\"\"\" return await self._get(path=\"league\", model=Account) async def get_characters( self, ) -> List[Character]:",
"IDs or unique numbers. # For example, \"/character/moowiz\" has an account name, so",
"and returns the data as a list of APIType subclass. Args: model: The",
"values for those args should be passed into path_format_args. path_format_args: Values which should",
"account methods for the POE API. CURRENTLY UNTESTED. HAS NOT BEEN USED IN",
"Optional[BaseException], exc_tb: Optional[TracebackType], ) -> Optional[bool]: \"\"\"Runs on exiting `async with`.\"\"\" await self._client.close()",
"\"\", league: str = \"\", ) -> List[PvPMatch]: \"\"\"Get a list of all",
"result of the API request, parsed as JSON. \"\"\" if not path_format_args: path_format_args",
"kwargs isn't a positional arg and won't override a different # positional argument",
"*args, **kwargs, ) -> List[Model]: \"\"\"Make a get request and returns the data",
"API GGG has exposed. None of these APIs have been tested in production,",
"from yarl import URL from poe_client.rate_limiter import RateLimiter from poe_client.schemas.account import Account, Realm",
"model=PvPMatch, result_field=\"matches\", query=query, ) async def get_pvp_match( self, match: str, realm: Optional[Realm] =",
"which have unknown types we pass to _get_json async def _get( # type:",
"this value fetches stash tabs from the beginning of the API's availability which",
"query[\"realm\"] = realm.value return await self._get( path=\"league/{0}/ladder\", path_format_args=(league,), model=Ladder, result_field=\"ladder\", query=query, ) class",
"model(**json_result) # Type ignore is for args and kwargs, which have unknown types",
"request gets made. query: An optional dict of query params to add to",
"The URL path to use. Appended to the POE API base URL. If",
"id.\"\"\" query = {} if realm: query[\"realm\"] = realm.value return await self._get( path=\"league/{0}\",",
"get_public_stash_tabs( self, next_change_id: Optional[str] = None, ) -> PublicStash: \"\"\"Get the latest public",
"to the same endpoints with different specific args use the # same rate",
"token.\"\"\" return await self._get( path=\"character/{0}\", path_format_args=(name,), model=Character, result_field=\"character\", ) async def get_stashes( self,",
"required; not setting this value fetches stash tabs from the beginning of the",
"\"\"\"Get a ItemFilter based on id.\"\"\" return await self._get( path=\"item-filter/{0}\", path_format_args=(filterid,), model=ItemFilter, result_field=\"filter\",",
"model: Callable[..., Model], result_field: Optional[str] = None, *args, **kwargs, ) -> Model: \"\"\"Make",
"If set, returns the next set of stash tabs, starting at this change_id.",
") -> List[Character]: \"\"\"Get all characters belonging to token.\"\"\" return await self._get_list( path=\"character\",",
"await self._get_list( path=\"character\", model=Character, result_field=\"characters\", ) async def get_character( self, name: str, )",
"async def get_pvp_match( self, match: str, realm: Optional[Realm] = None, ) -> PvPMatch:",
"get_pvp_matches( self, realm: Optional[Realm] = None, match_type: Optional[PvPMatchType] = None, season: str =",
"(\"{0}\") in the path, and the values for those args should be passed",
"Exile API.\"\"\" _token: Optional[str] _base_url: URL = URL(\"https://api.pathofexile.com\") _client: aiohttp.ClientSession _user_agent: str _limiter:",
"import PvPMatch, PvPMatchLadder, PvPMatchType from poe_client.schemas.stash import PublicStash, StashTab Model = TypeVar(\"Model\") #",
"# same rate limiting. For example, /characters/moowiz and /characters/chris # presumably use the",
"of the API's availability which is several years in the past. Returns: A",
"flake8 complaining about overly complex annotation. logging.info(\"NOT BLOCKING\") kwargs[\"raise_for_status\"] = True # type:",
"on here. class PoEClient( # noqa: WPS215 _PvPMixin, _LeagueMixin, _AccountMixin, _FilterMixin, _PublicStashMixin, Client,",
"return await self._get_list( path=\"stash/{0}\", path_format_args=(league,), model=StashTab, result_field=\"stashes\", ) async def get_stash( self, league:",
"type. \"\"\" json_result = await self._get_json(*args, **kwargs) if result_field: assert isinstance(json_result, dict) #",
") class _AccountMixin(Client): \"\"\"User account methods for the POE API. CURRENTLY UNTESTED. HAS",
"WPS336 path_format_args.append(substash_id) return await self._get( path=path, path_format_args=path_format_args, model=StashTab, result_field=\"stash\", ) class _FilterMixin(Client): \"\"\"Item",
"\"generic\" paths to rate limiting policy names. # Generic paths are paths with",
"\"\"\"Client for PoE API. This technically has support for every API GGG has",
"id.\"\"\" query = {} if realm: query[\"realm\"] = realm.value return await self._get( path=\"league/{0}/ladder\",",
"league id.\"\"\" query = {} if realm: query[\"realm\"] = realm.value return await self._get(",
"id.\"\"\" query = {} if realm: query[\"realm\"] = realm.value return await self._get( path=\"pvp-match/{0}/ladder\",",
"limit: int = 50, ) -> List[League]: \"\"\"Get a list of all leagues",
"the data as a list of APIType subclass. Args: model: The object which",
"all leagues based on filters.\"\"\" if league_type == LeagueType.season and not season: raise",
"LeagueType.season and not season: raise ValueError(\"season cannot be empty if league_type is season.\")",
"realm.value return await self._get( path=\"pvp-match/{0}/ladder\", path_format_args=(match,), model=PvPMatchLadder, result_field=\"match\", query=query, ) class _LeagueMixin(Client): \"\"\"League",
"season: str = \"\", league: str = \"\", ) -> List[PvPMatch]: \"\"\"Get a",
"Optional[Realm] = None, league_type: Optional[LeagueType] = None, offset: int = 0, season: str",
"\"\"\"Get a pvp match based on id.\"\"\" query = {} if realm: query[\"realm\"]",
"exposed. None of these APIs have been tested in production, so use at",
"of Exile API.\"\"\" _token: Optional[str] _base_url: URL = URL(\"https://api.pathofexile.com\") _client: aiohttp.ClientSession _user_agent: str",
"= self._path_to_policy_names.get(path_with_no_args, \"\") kwargs = { \"headers\": { \"User-Agent\": self._user_agent, }, \"params\": query,",
"encoded as format args (\"{0}\") in the path, and the values for those",
"query[\"realm\"] = realm.value return await self._get( path=\"league/{0}\", path_format_args=(league,), model=League, result_field=\"league\", query=query, ) async",
"def get_profile( self, ) -> Account: \"\"\"Get the account beloning to the token.\"\"\"",
"return [model(**objitem) for objitem in json_result] async def _get_json( self, path: str, path_format_args:",
"OAuth user agent. Used when making HTTP requests to the API. token: Authorization",
"poe_client.schemas.league import Ladder, League, LeagueType from poe_client.schemas.pvp import PvPMatch, PvPMatchLadder, PvPMatchType from poe_client.schemas.stash",
"season if season else None, \"league\": league if league else None, } #",
") async def get_pvp_match_ladder( self, match: str, realm: Optional[Realm] = None, ) ->",
"technically optional, in practice this is required; not setting this value fetches stash",
"return await self._get( path=\"character/{0}\", path_format_args=(name,), model=Character, result_field=\"character\", ) async def get_stashes( self, league:",
"# noqa: S101 headers[\"Authorization\"] = \"Bearer {0}\".format(self._token) # We key the policy name",
"filterid: str, ) -> ItemFilter: \"\"\"Get a ItemFilter based on id.\"\"\" return await",
"= \"stash/{0}/{1}\".format(league, stash_id) path_format_args = [league, stash_id] if substash_id: path += \"/{2}\" #",
"async def get_profile( self, ) -> Account: \"\"\"Get the account beloning to the",
"def __aenter__(self) -> \"Client\": \"\"\"Runs on entering `async with`.\"\"\" self._client = aiohttp.ClientSession(raise_for_status=True) return",
"doesn't complain about # complexity. query = { \"realm\": realm.value if realm else",
"passed into path_format_args. path_format_args: Values which should be encoded in the path when",
"self._client.close() if exc_val: raise exc_val return True # Type ignore is for args",
"_get_json( self, path: str, path_format_args: Optional[List[str]] = None, query: Optional[Dict[str, str]] = None,",
"Optional[Realm] = None, ) -> PvPMatch: \"\"\"Get a pvp match based on id.\"\"\"",
"-> List[PvPMatch]: \"\"\"Get a list of all pvp matches based on filters.\"\"\" if",
") -> Account: \"\"\"Get the account beloning to the token.\"\"\" return await self._get(path=\"league\",",
"query = {} if realm: query[\"realm\"] = realm.value return await self._get( path=\"league/{0}\", path_format_args=(league,),",
"query_val in query.items() if query_val} return await self._get_list( path=\"league\", model=League, result_field=\"leagues\", query=query, )",
"unset, no auth token is used. \"\"\" self._token = token self._user_agent = user_agent",
"# type: ignore ) as resp: self._path_to_policy_names[ path_with_no_args ] = await self._limiter.parse_headers(resp.headers) if",
") -> List[StashTab]: \"\"\"Get all stash tabs belonging to token.\"\"\" return await self._get_list(",
"base classes. We use multiple to better split up # the different APIs",
"\"Client\": \"\"\"Runs on entering `async with`.\"\"\" self._client = aiohttp.ClientSession(raise_for_status=True) return self async def",
"path_format_args = [] path_with_no_args = path.format((\"\" for _ in range(len(path_format_args)))) policy_name = self._path_to_policy_names.get(path_with_no_args,",
"from the API. Must be a sublclass of APIType. result_field: If present, returns",
"_FilterMixin, _PublicStashMixin, Client, ): \"\"\"Client for PoE API. This technically has support for",
"{} if realm: query[\"realm\"] = realm.value return await self._get( path=\"pvp-match/{0}\", path_format_args=(match,), model=PvPMatch, result_field=\"match\",",
"{} if realm: query[\"realm\"] = realm.value return await self._get( path=\"pvp-match/{0}/ladder\", path_format_args=(match,), model=PvPMatchLadder, result_field=\"match\",",
"def get_pvp_match_ladder( self, match: str, realm: Optional[Realm] = None, ) -> PvPMatchLadder: \"\"\"Get",
"model=ItemFilter, result_field=\"filters\", ) async def get_item_filter( self, filterid: str, ) -> ItemFilter: \"\"\"Get",
"typing in the dict assignment. kwargs only has dicts as values, # but",
"Removed unset query params query = {key: query_val for key, query_val in query.items()",
"change. \"\"\" query = {} if next_change_id: query[\"id\"] = next_change_id return await self._get_json(",
"and account of token.\"\"\" return await self._get( path=\"character/{0}\", path_format_args=(name,), model=Character, result_field=\"character\", ) async",
"Args: path: The URL path to use. Appended to the POE API base",
"result_field=\"matches\", query=query, ) async def get_pvp_match( self, match: str, realm: Optional[Realm] = None,",
"league_type == LeagueType.season and not season: raise ValueError(\"season cannot be empty if league_type",
"for other args. Returns: The result, parsed into a list of the `model`",
"every API GGG has exposed. None of these APIs have been tested in",
"the path when the HTTP request gets made. query: An optional dict of",
"tabs, starting at this change_id. While this is technically optional, in practice this",
") return await resp.json() class _PvPMixin(Client): \"\"\"PVP related methods for the POE API.",
"self._user_agent = user_agent self._limiter = RateLimiter() self._path_to_policy_names = {} async def __aenter__(self) ->",
"we pass to _get_json async def _get_list( # type: ignore self, model: Callable[...,",
"Character from poe_client.schemas.filter import ItemFilter from poe_client.schemas.league import Ladder, League, LeagueType from poe_client.schemas.pvp",
"token self._user_agent = user_agent self._limiter = RateLimiter() self._path_to_policy_names = {} async def __aenter__(self)",
"isinstance(json_result, dict) # noqa: S101 json_result = json_result[result_field] assert isinstance(json_result, list) # noqa:",
"match: str, realm: Optional[Realm] = None, ) -> PvPMatch: \"\"\"Get a pvp match",
"to rate limiting policy names. # Generic paths are paths with no IDs",
"class _FilterMixin(Client): \"\"\"Item Filter methods for the POE API. CURRENTLY UNTESTED. HAS NOT",
"# different requests to the same endpoints with different specific args use the",
"dicts as values, # but we're assigning booleans here. We can't set the",
"Optional, Type, TypeVar import aiohttp from yarl import URL from poe_client.rate_limiter import RateLimiter",
"to token.\"\"\" return await self._get_list( path=\"character\", model=Character, result_field=\"characters\", ) async def get_character( self,",
"def get_pvp_match( self, match: str, realm: Optional[Realm] = None, ) -> PvPMatch: \"\"\"Get",
"None, season: str = \"\", league: str = \"\", ) -> List[PvPMatch]: \"\"\"Get",
"UNTESTED. HAS NOT BEEN USED IN PRODUCTION. \"\"\" async def get_item_filters( self, )",
"if league_type is league.\") # We construct this via a dict so that",
"UNTESTED. HAS NOT BEEN USED IN PRODUCTION. \"\"\" async def list_leagues( # noqa:",
") async def get_league_ladder( self, league: str, realm: Optional[Realm] = None, ) ->",
"path_format_args. path_format_args: Values which should be encoded in the path when the HTTP",
"paths to rate limiting policy names. # Generic paths are paths with no",
"_client: aiohttp.ClientSession _user_agent: str _limiter: RateLimiter # Maps \"generic\" paths to rate limiting",
"\"User-Agent\": self._user_agent, }, \"params\": query, } if self._token: headers = kwargs[\"headers\"] assert headers",
"made. query: An optional dict of query params to add to the HTTP",
"\"type\": match_type.value if match_type else None, \"realm\": realm.value if realm else None, \"season\":",
"= None, ) -> None: \"\"\"Initialize a new PoE client. Args: user_agent: An",
"_get_list( # type: ignore self, model: Callable[..., Model], result_field: Optional[str] = None, *args,",
"self._get( path=\"pvp-match/{0}\", path_format_args=(match,), model=PvPMatch, result_field=\"match\", query=query, ) async def get_pvp_match_ladder( self, match: str,",
"next_change_id return await self._get_json( path=\"public-stash-tabs\", query=query, ) # Ignore WPS215, error about too",
"self._get_list( path=\"character\", model=Character, result_field=\"characters\", ) async def get_character( self, name: str, ) ->",
"no IDs or unique numbers. # For example, \"/character/moowiz\" has an account name,",
"policy names. # Generic paths are paths with no IDs or unique numbers.",
"_AccountMixin, _FilterMixin, _PublicStashMixin, Client, ): \"\"\"Client for PoE API. This technically has support",
"_PvPMixin, _LeagueMixin, _AccountMixin, _FilterMixin, _PublicStashMixin, Client, ): \"\"\"Client for PoE API. This technically",
"if substash_id: path += \"/{2}\" # noqa: WPS336 path_format_args.append(substash_id) return await self._get( path=path,",
"the `model` type. \"\"\" json_result = await self._get_json(*args, **kwargs) if result_field: assert isinstance(json_result,",
"await self._get_list( path=\"league\", model=League, result_field=\"leagues\", query=query, ) async def get_league( self, league: str,",
"None, ) -> Ladder: \"\"\"Get the ladder of a league based on id.\"\"\"",
"self._get(path=\"league\", model=Account) async def get_characters( self, ) -> List[Character]: \"\"\"Get all characters belonging",
"of the path are non-static (account ID), those should be encoded as format",
"class PoEClient( # noqa: WPS215 _PvPMixin, _LeagueMixin, _AccountMixin, _FilterMixin, _PublicStashMixin, Client, ): \"\"\"Client",
"a list of APIType subclass. Args: model: The object which contains data retrieved",
"match_type == PvPMatchType.league and not league: raise ValueError(\"league cannot be empty if league_type",
"self, league: str, ) -> List[StashTab]: \"\"\"Get all stash tabs belonging to token.\"\"\"",
"of all pvp matches based on filters.\"\"\" if match_type == PvPMatchType.season and not",
"# The types are ignored because for some reason it can't understand #",
"realm: Optional[Realm] = None, ) -> PvPMatchLadder: \"\"\"Get a pvp match based on",
"def _get_json( self, path: str, path_format_args: Optional[List[str]] = None, query: Optional[Dict[str, str]] =",
"self._token = token self._user_agent = user_agent self._limiter = RateLimiter() self._path_to_policy_names = {} async",
"NOT BEEN USED IN PRODUCTION. \"\"\" async def get_public_stash_tabs( self, next_change_id: Optional[str] =",
"PvPMatch: \"\"\"Get a pvp match based on id.\"\"\" query = {} if realm:",
"the request itself. See _get_json for other args. Returns: The result, parsed into",
"raise ValueError(\"season cannot be empty if league_type is season.\") # We construct this",
"request and returns the data as a list of APIType subclass. Args: model:",
"self._path_to_policy_names = {} async def __aenter__(self) -> \"Client\": \"\"\"Runs on entering `async with`.\"\"\"",
"result_field=\"match\", query=query, ) async def get_pvp_match_ladder( self, match: str, realm: Optional[Realm] = None,",
"str, ) -> ItemFilter: \"\"\"Get a ItemFilter based on id.\"\"\" return await self._get(",
"\"\"\" query = {} if next_change_id: query[\"id\"] = next_change_id return await self._get_json( path=\"public-stash-tabs\",",
"query = { \"type\": match_type.value if match_type else None, \"realm\": realm.value if realm",
"next_change_id: If set, returns the next set of stash tabs, starting at this",
"query_val for key, query_val in query.items() if query_val} return await self._get_list( path=\"league\", model=League,",
"the same rate limiting policy name. if await self._limiter.get_semaphore(policy_name): # We ignore typing",
"= {} if realm: query[\"realm\"] = realm.value return await self._get( path=\"pvp-match/{0}\", path_format_args=(match,), model=PvPMatch,",
"optional, in practice this is required; not setting this value fetches stash tabs",
"get request and returns the data as an APIType subclass. Args: model: The",
"data retrieved from the API. Must be a sublclass of APIType. result_field: If",
"return await self._get_list( path=\"league\", model=League, result_field=\"leagues\", query=query, ) async def get_league( self, league:",
"PvPMatchLadder, PvPMatchType from poe_client.schemas.stash import PublicStash, StashTab Model = TypeVar(\"Model\") # the variable",
"def get_stash( self, league: str, stash_id: str, substash_id: Optional[str], ) -> StashTab: \"\"\"Get",
"\"\"\" if not path_format_args: path_format_args = [] path_with_no_args = path.format((\"\" for _ in",
"this via a dict so that the linter doesn't complain about # complexity.",
"exc_val: Optional[BaseException], exc_tb: Optional[TracebackType], ) -> Optional[bool]: \"\"\"Runs on exiting `async with`.\"\"\" await",
"a new PoE client. Args: user_agent: An OAuth user agent. Used when making",
"StashTab Model = TypeVar(\"Model\") # the variable return type class Client(object): \"\"\"Aiohttp class",
"class _PvPMixin(Client): \"\"\"PVP related methods for the POE API. CURRENTLY UNTESTED. HAS NOT",
"league_type is league.\") # We construct this via a dict so that the",
"-> League: \"\"\"Get a league based on league id.\"\"\" query = {} if",
"class _LeagueMixin(Client): \"\"\"League related methods for the POE API. CURRENTLY UNTESTED. HAS NOT",
"to the POE API base URL. If certain parts of the path are",
"API. CURRENTLY UNTESTED. HAS NOT BEEN USED IN PRODUCTION. \"\"\" async def get_profile(",
"practice this is required; not setting this value fetches stash tabs from the",
"of these APIs have been tested in production, so use at your own",
"model=ItemFilter, result_field=\"filter\", ) class _PublicStashMixin(Client): \"\"\"Public stash tab methods for the POE API.",
"API. token: Authorization token to pass to the PoE API. If unset, no",
"the POE API. CURRENTLY UNTESTED. HAS NOT BEEN USED IN PRODUCTION. \"\"\" async",
"\"\"\"Get a list of all pvp matches based on filters.\"\"\" if match_type ==",
"league: raise ValueError(\"league cannot be empty if league_type is league.\") # We construct",
"in json_result] async def _get_json( self, path: str, path_format_args: Optional[List[str]] = None, query:",
"query=query, ) async def get_pvp_match_ladder( self, match: str, realm: Optional[Realm] = None, )",
"realm: Optional[Realm] = None, league_type: Optional[LeagueType] = None, offset: int = 0, season:",
"\"realm\": realm.value if realm else None, \"season\": season if season else None, \"league\":",
"self, realm: Optional[Realm] = None, league_type: Optional[LeagueType] = None, offset: int = 0,",
"] = await self._limiter.parse_headers(resp.headers) if resp.status != 200: raise ValueError( \"Invalid request: status",
"= None, ) -> PublicStash: \"\"\"Get the latest public stash tabs. Args: next_change_id:",
"for objitem in json_result] async def _get_json( self, path: str, path_format_args: Optional[List[str]] =",
"same endpoints with different specific args use the # same rate limiting. For",
"model=League, result_field=\"league\", query=query, ) async def get_league_ladder( self, league: str, realm: Optional[Realm] =",
"with`.\"\"\" self._client = aiohttp.ClientSession(raise_for_status=True) return self async def __aexit__( self, exc_type: Optional[Type[BaseException]], exc_val:",
"than the request itself. See _get_json for other args. Returns: The result, parsed",
"HTTP request. Returns: The result of the API request, parsed as JSON. \"\"\"",
"The object which contains data retrieved from the API. Must be a sublclass",
"path=\"item-filter\", model=ItemFilter, result_field=\"filters\", ) async def get_item_filter( self, filterid: str, ) -> ItemFilter:",
"all pvp matches based on filters.\"\"\" if match_type == PvPMatchType.season and not season:",
"args and kwargs, which have unknown types we pass to _get_json async def",
"return await self._get( path=\"item-filter/{0}\", path_format_args=(filterid,), model=ItemFilter, result_field=\"filter\", ) class _PublicStashMixin(Client): \"\"\"Public stash tab",
"Account, Realm from poe_client.schemas.character import Character from poe_client.schemas.filter import ItemFilter from poe_client.schemas.league import",
"path_format_args: path_format_args = [] path_with_no_args = path.format((\"\" for _ in range(len(path_format_args)))) policy_name =",
"based on id.\"\"\" return await self._get( path=\"item-filter/{0}\", path_format_args=(filterid,), model=ItemFilter, result_field=\"filter\", ) class _PublicStashMixin(Client):",
"filters.\"\"\" if match_type == PvPMatchType.season and not season: raise ValueError(\"season cannot be empty",
"name, so it's not a base path. # \"/character/\" is the equivalent \"generic\"",
"PvPMatchLadder: \"\"\"Get a pvp match based on id.\"\"\" query = {} if realm:",
"stash tab based on id.\"\"\" path = \"stash/{0}/{1}\".format(league, stash_id) path_format_args = [league, stash_id]",
"which have unknown types we pass to _get_json async def _get_list( # type:",
"result_field=\"filter\", ) class _PublicStashMixin(Client): \"\"\"Public stash tab methods for the POE API. CURRENTLY",
"booleans here. We can't set the typing inline without # flake8 complaining about",
"not setting this value fetches stash tabs from the beginning of the API's",
"Optional[str] = None, ) -> None: \"\"\"Initialize a new PoE client. Args: user_agent:",
"returns the data as an APIType subclass. Args: model: The object which contains",
"None, ) -> League: \"\"\"Get a league based on league id.\"\"\" query =",
"Optional[TracebackType], ) -> Optional[bool]: \"\"\"Runs on exiting `async with`.\"\"\" await self._client.close() if exc_val:",
"limiting. For example, /characters/moowiz and /characters/chris # presumably use the same rate limiting",
"\"\"\"Get a stash tab based on id.\"\"\" path = \"stash/{0}/{1}\".format(league, stash_id) path_format_args =",
"`async with`.\"\"\" self._client = aiohttp.ClientSession(raise_for_status=True) return self async def __aexit__( self, exc_type: Optional[Type[BaseException]],",
"= json_result[result_field] return model(**json_result) # Type ignore is for args and kwargs, which",
"self, league: str, stash_id: str, substash_id: Optional[str], ) -> StashTab: \"\"\"Get a stash",
"subclass. Args: model: The object which contains data retrieved from the API. Must",
"BEEN USED IN PRODUCTION. \"\"\" async def get_public_stash_tabs( self, next_change_id: Optional[str] = None,",
"), ) return await resp.json() class _PvPMixin(Client): \"\"\"PVP related methods for the POE",
"ignore typing in the dict assignment. kwargs only has dicts as values, #",
"into an instance of the `model` type. \"\"\" json_result = await self._get_json(*args, **kwargs)",
"a list of all leagues based on filters.\"\"\" if league_type == LeagueType.season and",
"path=\"pvp-match\", model=PvPMatch, result_field=\"matches\", query=query, ) async def get_pvp_match( self, match: str, realm: Optional[Realm]",
"field from the request, rather than the request itself. See _get_json for other",
"PRODUCTION. \"\"\" async def get_pvp_matches( self, realm: Optional[Realm] = None, match_type: Optional[PvPMatchType] =",
"# complexity. query = { \"realm\": realm.value if realm else None, \"type\": league_type.value",
"PvPMatch, PvPMatchLadder, PvPMatchType from poe_client.schemas.stash import PublicStash, StashTab Model = TypeVar(\"Model\") # the",
"API. CURRENTLY UNTESTED. HAS NOT BEEN USED IN PRODUCTION. \"\"\" async def get_pvp_matches(",
"class for interacting with the Path of Exile API.\"\"\" _token: Optional[str] _base_url: URL",
"poe_client.schemas.pvp import PvPMatch, PvPMatchLadder, PvPMatchType from poe_client.schemas.stash import PublicStash, StashTab Model = TypeVar(\"Model\")",
"_get_json for other args. Returns: The result, parsed into a list of the",
"\"\", ) -> List[PvPMatch]: \"\"\"Get a list of all pvp matches based on",
"None, } # Removed unset query params query = {key: query_val for key,",
"TypeVar(\"Model\") # the variable return type class Client(object): \"\"\"Aiohttp class for interacting with",
"WPS215 _PvPMixin, _LeagueMixin, _AccountMixin, _FilterMixin, _PublicStashMixin, Client, ): \"\"\"Client for PoE API. This",
"Account: \"\"\"Get the account beloning to the token.\"\"\" return await self._get(path=\"league\", model=Account) async",
"aiohttp.ClientSession _user_agent: str _limiter: RateLimiter # Maps \"generic\" paths to rate limiting policy",
"from poe_client.schemas.stash import PublicStash, StashTab Model = TypeVar(\"Model\") # the variable return type",
"data as a list of APIType subclass. Args: model: The object which contains",
"True # Type ignore is for args and kwargs, which have unknown types",
"get_league_ladder( self, league: str, realm: Optional[Realm] = None, ) -> Ladder: \"\"\"Get the",
"{} if realm: query[\"realm\"] = realm.value return await self._get( path=\"league/{0}\", path_format_args=(league,), model=League, result_field=\"league\",",
"or unique numbers. # For example, \"/character/moowiz\" has an account name, so it's",
"HAS NOT BEEN USED IN PRODUCTION. \"\"\" async def get_public_stash_tabs( self, next_change_id: Optional[str]",
"of APIType. result_field: If present, returns the data in this field from the",
"is required; not setting this value fetches stash tabs from the beginning of",
"is season.\") # We construct this via a dict so that the linter",
"model=PvPMatch, result_field=\"match\", query=query, ) async def get_pvp_match_ladder( self, match: str, realm: Optional[Realm] =",
"result_field=\"stash\", ) class _FilterMixin(Client): \"\"\"Item Filter methods for the POE API. CURRENTLY UNTESTED.",
"match_type == PvPMatchType.season and not season: raise ValueError(\"season cannot be empty if league_type",
"None, ): \"\"\"Fetches data from the POE API. Args: path: The URL path",
"= kwargs[\"headers\"] assert headers # noqa: S101 headers[\"Authorization\"] = \"Bearer {0}\".format(self._token) # We",
"from typing import Callable, Dict, List, Optional, Type, TypeVar import aiohttp from yarl",
"unset query params query = {key: query_val for key, query_val in query.items() if",
"league else None, } # Removed unset query params query = {key: query_val",
"different specific args use the # same rate limiting. For example, /characters/moowiz and",
"won't override a different # positional argument in the function. async with await",
"should be passed into path_format_args. path_format_args: Values which should be encoded in the",
"stash_id: str, substash_id: Optional[str], ) -> StashTab: \"\"\"Get a stash tab based on",
"a pvp match based on id.\"\"\" query = {} if realm: query[\"realm\"] =",
"from poe_client.schemas.league import Ladder, League, LeagueType from poe_client.schemas.pvp import PvPMatch, PvPMatchLadder, PvPMatchType from",
"`model` type. \"\"\" json_result = await self._get_json(*args, **kwargs) assert isinstance(json_result, dict) # noqa:",
"model=Ladder, result_field=\"ladder\", query=query, ) class _AccountMixin(Client): \"\"\"User account methods for the POE API.",
"to the token.\"\"\" return await self._get(path=\"league\", model=Account) async def get_characters( self, ) ->",
"# going on here. class PoEClient( # noqa: WPS215 _PvPMixin, _LeagueMixin, _AccountMixin, _FilterMixin,",
"matches based on filters.\"\"\" if match_type == PvPMatchType.season and not season: raise ValueError(\"season",
"_LeagueMixin(Client): \"\"\"League related methods for the POE API. CURRENTLY UNTESTED. HAS NOT BEEN",
"user_agent self._limiter = RateLimiter() self._path_to_policy_names = {} async def __aenter__(self) -> \"Client\": \"\"\"Runs",
"json_result[result_field] return model(**json_result) # Type ignore is for args and kwargs, which have",
"the `model` type. \"\"\" json_result = await self._get_json(*args, **kwargs) assert isinstance(json_result, dict) #",
"unknown types we pass to _get_json async def _get( # type: ignore self,",
"# flake8 complaining about overly complex annotation. logging.info(\"NOT BLOCKING\") kwargs[\"raise_for_status\"] = True #",
"return await self._get_list( path=\"item-filter\", model=ItemFilter, result_field=\"filters\", ) async def get_item_filter( self, filterid: str,",
"{} async def __aenter__(self) -> \"Client\": \"\"\"Runs on entering `async with`.\"\"\" self._client =",
"all item filters.\"\"\" return await self._get_list( path=\"item-filter\", model=ItemFilter, result_field=\"filters\", ) async def get_item_filter(",
"technically has support for every API GGG has exposed. None of these APIs",
"Model = TypeVar(\"Model\") # the variable return type class Client(object): \"\"\"Aiohttp class for",
"pass to the PoE API. If unset, no auth token is used. \"\"\"",
"Ignore WPS215, error about too many base classes. We use multiple to better",
"better split up # the different APIs to simplify reading. There isn't any",
"the policy name off the path with no format args. This presumes that",
"presumably use the same rate limiting policy name. if await self._limiter.get_semaphore(policy_name): # We",
"that the linter doesn't complain about # complexity. query = { \"realm\": realm.value",
"query.items() if query_val} return await self._get_list( path=\"league\", model=League, result_field=\"leagues\", query=query, ) async def",
"API. This technically has support for every API GGG has exposed. None of",
"client. Args: user_agent: An OAuth user agent. Used when making HTTP requests to",
"self._path_to_policy_names.get(path_with_no_args, \"\") kwargs = { \"headers\": { \"User-Agent\": self._user_agent, }, \"params\": query, }",
"making HTTP requests to the API. token: Authorization token to pass to the",
"dict so that the linter doesn't complain about # complexity. query = {",
"\"\"\"Get the latest public stash tabs. Args: next_change_id: If set, returns the next",
"for other args. Returns: The result, parsed into an instance of the `model`",
"type: ignore # The types are ignored because for some reason it can't",
"from the POE API. Args: path: The URL path to use. Appended to",
"_PublicStashMixin, Client, ): \"\"\"Client for PoE API. This technically has support for every",
"path_format_args.append(substash_id) return await self._get( path=path, path_format_args=path_format_args, model=StashTab, result_field=\"stash\", ) class _FilterMixin(Client): \"\"\"Item Filter",
"the PoE API. If unset, no auth token is used. \"\"\" self._token =",
"= path.format((\"\" for _ in range(len(path_format_args)))) policy_name = self._path_to_policy_names.get(path_with_no_args, \"\") kwargs = {",
"self._get( path=\"item-filter/{0}\", path_format_args=(filterid,), model=ItemFilter, result_field=\"filter\", ) class _PublicStashMixin(Client): \"\"\"Public stash tab methods for",
"if realm: query[\"realm\"] = realm.value return await self._get( path=\"league/{0}/ladder\", path_format_args=(league,), model=Ladder, result_field=\"ladder\", query=query,",
"path=path, path_format_args=path_format_args, model=StashTab, result_field=\"stash\", ) class _FilterMixin(Client): \"\"\"Item Filter methods for the POE",
"self._token: headers = kwargs[\"headers\"] assert headers # noqa: S101 headers[\"Authorization\"] = \"Bearer {0}\".format(self._token)",
"result_field=\"filters\", ) async def get_item_filter( self, filterid: str, ) -> ItemFilter: \"\"\"Get a",
"itself. See _get_json for other args. Returns: The result, parsed into a list",
"the path, and the values for those args should be passed into path_format_args.",
"assignment. kwargs only has dicts as values, # but we're assigning booleans here.",
"realm: Optional[Realm] = None, ) -> League: \"\"\"Get a league based on league",
"If unset, no auth token is used. \"\"\" self._token = token self._user_agent =",
"\"\"\" json_result = await self._get_json(*args, **kwargs) assert isinstance(json_result, dict) # noqa: S101 if",
"if realm: query[\"realm\"] = realm.value return await self._get( path=\"pvp-match/{0}\", path_format_args=(match,), model=PvPMatch, result_field=\"match\", query=query,",
"IN PRODUCTION. \"\"\" async def get_public_stash_tabs( self, next_change_id: Optional[str] = None, ) ->",
"to better split up # the different APIs to simplify reading. There isn't",
"API base URL. If certain parts of the path are non-static (account ID),",
"kwargs[\"raise_for_status\"] = True # type: ignore else: logging.info(\"BLOCKING\") kwargs[\"raise_for_status\"] = False # type:",
"_base_url: URL = URL(\"https://api.pathofexile.com\") _client: aiohttp.ClientSession _user_agent: str _limiter: RateLimiter # Maps \"generic\"",
"should be encoded in the path when the HTTP request gets made. query:",
"complex annotation. logging.info(\"NOT BLOCKING\") kwargs[\"raise_for_status\"] = True # type: ignore else: logging.info(\"BLOCKING\") kwargs[\"raise_for_status\"]",
") -> List[ItemFilter]: \"\"\"Get all item filters.\"\"\" return await self._get_list( path=\"item-filter\", model=ItemFilter, result_field=\"filters\",",
"cannot be empty if league_type is league.\") # We construct this via a",
"has an account name, so it's not a base path. # \"/character/\" is",
"async def _get( # type: ignore self, model: Callable[..., Model], result_field: Optional[str] =",
"query = { \"realm\": realm.value if realm else None, \"type\": league_type.value if league_type",
"await resp.json() class _PvPMixin(Client): \"\"\"PVP related methods for the POE API. CURRENTLY UNTESTED.",
"if offset else None, \"limit\": str(limit) if limit else None, } # Remove",
"self._get_json(*args, **kwargs) assert isinstance(json_result, dict) # noqa: S101 if result_field: json_result = json_result[result_field]",
"The result of the API request, parsed as JSON. \"\"\" if not path_format_args:",
"for PoE API. This technically has support for every API GGG has exposed.",
"= await self._get_json(*args, **kwargs) if result_field: assert isinstance(json_result, dict) # noqa: S101 json_result",
"query = {} if realm: query[\"realm\"] = realm.value return await self._get( path=\"pvp-match/{0}\", path_format_args=(match,),",
"query[\"realm\"] = realm.value return await self._get( path=\"pvp-match/{0}/ladder\", path_format_args=(match,), model=PvPMatchLadder, result_field=\"match\", query=query, ) class",
"# complexity. query = { \"type\": match_type.value if match_type else None, \"realm\": realm.value",
"Callable[..., Model], result_field: Optional[str] = None, *args, **kwargs, ) -> Model: \"\"\"Make a",
"\"\"\"Initialize a new PoE client. Args: user_agent: An OAuth user agent. Used when",
"aiohttp from yarl import URL from poe_client.rate_limiter import RateLimiter from poe_client.schemas.account import Account,",
"of APIType subclass. Args: model: The object which contains data retrieved from the",
"stash tabs. Args: next_change_id: If set, returns the next set of stash tabs,",
"ValueError( \"Invalid request: status code {0}, expected 200\".format( resp.status, ), ) return await",
"/characters/moowiz and /characters/chris # presumably use the same rate limiting policy name. if",
"and returns the data as an APIType subclass. Args: model: The object which",
"logging.info(\"BLOCKING\") kwargs[\"raise_for_status\"] = False # type: ignore # The types are ignored because",
"# noqa: S101 json_result = json_result[result_field] assert isinstance(json_result, list) # noqa: S101 return",
"public stash change. \"\"\" query = {} if next_change_id: query[\"id\"] = next_change_id return",
"beginning of the API's availability which is several years in the past. Returns:",
"query=query, ) async def get_league( self, league: str, realm: Optional[Realm] = None, )",
"List[ItemFilter]: \"\"\"Get all item filters.\"\"\" return await self._get_list( path=\"item-filter\", model=ItemFilter, result_field=\"filters\", ) async",
"self, next_change_id: Optional[str] = None, ) -> PublicStash: \"\"\"Get the latest public stash",
"== PvPMatchType.season and not season: raise ValueError(\"season cannot be empty if league_type is",
"query.items() if query_val} return await self._get_list( path=\"pvp-match\", model=PvPMatch, result_field=\"matches\", query=query, ) async def",
"type: ignore self, model: Callable[..., Model], result_field: Optional[str] = None, *args, **kwargs, )",
"{key: query_val for key, query_val in query.items() if query_val} return await self._get_list( path=\"league\",",
"league: str = \"\", ) -> List[PvPMatch]: \"\"\"Get a list of all pvp",
"RateLimiter from poe_client.schemas.account import Account, Realm from poe_client.schemas.character import Character from poe_client.schemas.filter import",
"positional arg and won't override a different # positional argument in the function.",
"path=\"character/{0}\", path_format_args=(name,), model=Character, result_field=\"character\", ) async def get_stashes( self, league: str, ) ->",
"async def get_public_stash_tabs( self, next_change_id: Optional[str] = None, ) -> PublicStash: \"\"\"Get the",
"realm else None, \"season\": season if season else None, \"league\": league if league",
"\"\"\"Get a list of all leagues based on filters.\"\"\" if league_type == LeagueType.season",
"= None, *args, **kwargs, ) -> List[Model]: \"\"\"Make a get request and returns",
"Returns: The result, parsed into an instance of the `model` type. \"\"\" json_result",
"return await resp.json() class _PvPMixin(Client): \"\"\"PVP related methods for the POE API. CURRENTLY",
"{0}, expected 200\".format( resp.status, ), ) return await resp.json() class _PvPMixin(Client): \"\"\"PVP related",
"\"\"\"PVP related methods for the POE API. CURRENTLY UNTESTED. HAS NOT BEEN USED",
"if league_type is season.\") # We construct this via a dict so that",
"result_field=\"character\", ) async def get_stashes( self, league: str, ) -> List[StashTab]: \"\"\"Get all",
"path = \"stash/{0}/{1}\".format(league, stash_id) path_format_args = [league, stash_id] if substash_id: path += \"/{2}\"",
"self._get( path=\"league/{0}/ladder\", path_format_args=(league,), model=Ladder, result_field=\"ladder\", query=query, ) class _AccountMixin(Client): \"\"\"User account methods for",
"path_format_args=(match,), model=PvPMatch, result_field=\"match\", query=query, ) async def get_pvp_match_ladder( self, match: str, realm: Optional[Realm]",
"await self._get( path=\"league/{0}/ladder\", path_format_args=(league,), model=Ladder, result_field=\"ladder\", query=query, ) class _AccountMixin(Client): \"\"\"User account methods",
"Ladder: \"\"\"Get the ladder of a league based on id.\"\"\" query = {}",
"path_format_args=(filterid,), model=ItemFilter, result_field=\"filter\", ) class _PublicStashMixin(Client): \"\"\"Public stash tab methods for the POE",
"that # different requests to the same endpoints with different specific args use",
"season: raise ValueError(\"season cannot be empty if league_type is season.\") # We construct",
"the POE API. Args: path: The URL path to use. Appended to the",
"from the request, rather than the request itself. See _get_json for other args.",
"`async with`.\"\"\" await self._client.close() if exc_val: raise exc_val return True # Type ignore",
"return self async def __aexit__( self, exc_type: Optional[Type[BaseException]], exc_val: Optional[BaseException], exc_tb: Optional[TracebackType], )",
"self, model: Callable[..., Model], result_field: Optional[str] = None, *args, **kwargs, ) -> List[Model]:",
"league_type is season.\") # We construct this via a dict so that the",
"= RateLimiter() self._path_to_policy_names = {} async def __aenter__(self) -> \"Client\": \"\"\"Runs on entering",
"request, parsed as JSON. \"\"\" if not path_format_args: path_format_args = [] path_with_no_args =",
"= { \"type\": match_type.value if match_type else None, \"realm\": realm.value if realm else",
"other args. Returns: The result, parsed into a list of the `model` type.",
"is used. \"\"\" self._token = token self._user_agent = user_agent self._limiter = RateLimiter() self._path_to_policy_names",
"so it's not a base path. # \"/character/\" is the equivalent \"generic\" path.",
"IN PRODUCTION. \"\"\" async def get_item_filters( self, ) -> List[ItemFilter]: \"\"\"Get all item",
"API.\"\"\" _token: Optional[str] _base_url: URL = URL(\"https://api.pathofexile.com\") _client: aiohttp.ClientSession _user_agent: str _limiter: RateLimiter",
"str, realm: Optional[Realm] = None, ) -> PvPMatch: \"\"\"Get a pvp match based",
"different APIs to simplify reading. There isn't any complicated inheritance # going on",
"None, match_type: Optional[PvPMatchType] = None, season: str = \"\", league: str = \"\",",
"JSON. \"\"\" if not path_format_args: path_format_args = [] path_with_no_args = path.format((\"\" for _",
"exc_tb: Optional[TracebackType], ) -> Optional[bool]: \"\"\"Runs on exiting `async with`.\"\"\" await self._client.close() if",
"str, realm: Optional[Realm] = None, ) -> League: \"\"\"Get a league based on",
"are non-static (account ID), those should be encoded as format args (\"{0}\") in",
"non-static (account ID), those should be encoded as format args (\"{0}\") in the",
"the dict assignment. kwargs only has dicts as values, # but we're assigning",
"stash_id] if substash_id: path += \"/{2}\" # noqa: WPS336 path_format_args.append(substash_id) return await self._get(",
"\"\"\" async def get_profile( self, ) -> Account: \"\"\"Get the account beloning to",
"query[\"id\"] = next_change_id return await self._get_json( path=\"public-stash-tabs\", query=query, ) # Ignore WPS215, error",
"# Type ignore is for args and kwargs, which have unknown types we",
"endpoints with different specific args use the # same rate limiting. For example,",
"): \"\"\"Client for PoE API. This technically has support for every API GGG",
"optional dict of query params to add to the HTTP request. Returns: The",
"user_agent: str, token: Optional[str] = None, ) -> None: \"\"\"Initialize a new PoE",
"if limit else None, } # Remove unset values query = {key: query_val",
"value fetches stash tabs from the beginning of the API's availability which is",
"PoEClient( # noqa: WPS215 _PvPMixin, _LeagueMixin, _AccountMixin, _FilterMixin, _PublicStashMixin, Client, ): \"\"\"Client for",
"if season else None, \"offset\": str(offset) if offset else None, \"limit\": str(limit) if",
"an instance of the `model` type. \"\"\" json_result = await self._get_json(*args, **kwargs) assert",
"the API. Must be a sublclass of APIType. result_field: If present, returns the",
"as format args (\"{0}\") in the path, and the values for those args",
"Appended to the POE API base URL. If certain parts of the path",
"\"headers\": { \"User-Agent\": self._user_agent, }, \"params\": query, } if self._token: headers = kwargs[\"headers\"]",
"We can't set the typing inline without # flake8 complaining about overly complex",
"= None, league_type: Optional[LeagueType] = None, offset: int = 0, season: str =",
"gets made. query: An optional dict of query params to add to the",
"self, match: str, realm: Optional[Realm] = None, ) -> PvPMatch: \"\"\"Get a pvp",
"BEEN USED IN PRODUCTION. \"\"\" async def list_leagues( # noqa: WPS211 self, realm:",
"should be encoded as format args (\"{0}\") in the path, and the values",
"Returns: A dict representing a public stash change. \"\"\" query = {} if",
"league: str, realm: Optional[Realm] = None, ) -> League: \"\"\"Get a league based",
"are paths with no IDs or unique numbers. # For example, \"/character/moowiz\" has",
"args. Returns: The result, parsed into an instance of the `model` type. \"\"\"",
"IN PRODUCTION. \"\"\" async def list_leagues( # noqa: WPS211 self, realm: Optional[Realm] =",
"substash_id: path += \"/{2}\" # noqa: WPS336 path_format_args.append(substash_id) return await self._get( path=path, path_format_args=path_format_args,",
"be passed into path_format_args. path_format_args: Values which should be encoded in the path",
"the next set of stash tabs, starting at this change_id. While this is",
"result_field: assert isinstance(json_result, dict) # noqa: S101 json_result = json_result[result_field] assert isinstance(json_result, list)",
"of stash tabs, starting at this change_id. While this is technically optional, in",
"unique numbers. # For example, \"/character/moowiz\" has an account name, so it's not",
"Type ignore is for args and kwargs, which have unknown types we pass",
"Maps \"generic\" paths to rate limiting policy names. # Generic paths are paths",
"if match_type == PvPMatchType.league and not league: raise ValueError(\"league cannot be empty if",
"While this is technically optional, in practice this is required; not setting this",
"setting this value fetches stash tabs from the beginning of the API's availability",
"self._get( path=\"character/{0}\", path_format_args=(name,), model=Character, result_field=\"character\", ) async def get_stashes( self, league: str, )",
"when the HTTP request gets made. query: An optional dict of query params",
"path_format_args=path_format_args, model=StashTab, result_field=\"stash\", ) class _FilterMixin(Client): \"\"\"Item Filter methods for the POE API.",
"ValueError(\"season cannot be empty if league_type is season.\") # We construct this via",
"if exc_val: raise exc_val return True # Type ignore is for args and",
"kwargs = { \"headers\": { \"User-Agent\": self._user_agent, }, \"params\": query, } if self._token:",
"empty if league_type is season.\") # We construct this via a dict so",
"pass to _get_json async def _get( # type: ignore self, model: Callable[..., Model],",
"kwargs, which have unknown types we pass to _get_json async def _get( #",
"logging from types import TracebackType from typing import Callable, Dict, List, Optional, Type,",
"raise ValueError(\"league cannot be empty if league_type is league.\") # We construct this",
"the API. token: Authorization token to pass to the PoE API. If unset,",
"List[PvPMatch]: \"\"\"Get a list of all pvp matches based on filters.\"\"\" if match_type",
"from poe_client.schemas.filter import ItemFilter from poe_client.schemas.league import Ladder, League, LeagueType from poe_client.schemas.pvp import",
"\"\"\"User account methods for the POE API. CURRENTLY UNTESTED. HAS NOT BEEN USED",
"query = {key: query_val for key, query_val in query.items() if query_val} return await",
"encoded in the path when the HTTP request gets made. query: An optional",
"to token.\"\"\" return await self._get_list( path=\"stash/{0}\", path_format_args=(league,), model=StashTab, result_field=\"stashes\", ) async def get_stash(",
"\"season\": season if season else None, \"league\": league if league else None, }",
"self._get( path=\"pvp-match/{0}/ladder\", path_format_args=(match,), model=PvPMatchLadder, result_field=\"match\", query=query, ) class _LeagueMixin(Client): \"\"\"League related methods for",
"leagues based on filters.\"\"\" if league_type == LeagueType.season and not season: raise ValueError(\"season",
"pvp match based on id.\"\"\" query = {} if realm: query[\"realm\"] = realm.value",
"URL. If certain parts of the path are non-static (account ID), those should",
"token.\"\"\" return await self._get_list( path=\"character\", model=Character, result_field=\"characters\", ) async def get_character( self, name:",
"List[League]: \"\"\"Get a list of all leagues based on filters.\"\"\" if league_type ==",
"ignored because for some reason it can't understand # that kwargs isn't a",
"query=query, ) class _LeagueMixin(Client): \"\"\"League related methods for the POE API. CURRENTLY UNTESTED.",
"get_pvp_match( self, match: str, realm: Optional[Realm] = None, ) -> PvPMatch: \"\"\"Get a",
"self._limiter.get_semaphore(policy_name): # We ignore typing in the dict assignment. kwargs only has dicts",
"Callable, Dict, List, Optional, Type, TypeVar import aiohttp from yarl import URL from",
"with await self._client.get( \"{0}/{1}\".format(self._base_url, path.format(*path_format_args)), **kwargs, # type: ignore ) as resp: self._path_to_policy_names[",
"CURRENTLY UNTESTED. HAS NOT BEEN USED IN PRODUCTION. \"\"\" async def get_pvp_matches( self,",
"return model(**json_result) # Type ignore is for args and kwargs, which have unknown",
"# Removed unset query params query = {key: query_val for key, query_val in",
"methods for the POE API. CURRENTLY UNTESTED. HAS NOT BEEN USED IN PRODUCTION.",
"= None, ) -> PvPMatch: \"\"\"Get a pvp match based on id.\"\"\" query",
"kwargs only has dicts as values, # but we're assigning booleans here. We",
"if query_val} return await self._get_list( path=\"league\", model=League, result_field=\"leagues\", query=query, ) async def get_league(",
"\"realm\": realm.value if realm else None, \"type\": league_type.value if league_type else None, \"season\":",
"this field from the request, rather than the request itself. See _get_json for",
"ignore # The types are ignored because for some reason it can't understand",
"from types import TracebackType from typing import Callable, Dict, List, Optional, Type, TypeVar",
"has dicts as values, # but we're assigning booleans here. We can't set",
"with`.\"\"\" await self._client.close() if exc_val: raise exc_val return True # Type ignore is",
"types are ignored because for some reason it can't understand # that kwargs",
"path=\"league/{0}/ladder\", path_format_args=(league,), model=Ladder, result_field=\"ladder\", query=query, ) class _AccountMixin(Client): \"\"\"User account methods for the",
"this change_id. While this is technically optional, in practice this is required; not",
"Model], result_field: Optional[str] = None, *args, **kwargs, ) -> List[Model]: \"\"\"Make a get",
"json_result = await self._get_json(*args, **kwargs) assert isinstance(json_result, dict) # noqa: S101 if result_field:",
"{} if next_change_id: query[\"id\"] = next_change_id return await self._get_json( path=\"public-stash-tabs\", query=query, ) #",
"all stash tabs belonging to token.\"\"\" return await self._get_list( path=\"stash/{0}\", path_format_args=(league,), model=StashTab, result_field=\"stashes\",",
"= {key: query_val for key, query_val in query.items() if query_val} return await self._get_list(",
"Optional[str] = None, ) -> PublicStash: \"\"\"Get the latest public stash tabs. Args:",
") async def get_item_filter( self, filterid: str, ) -> ItemFilter: \"\"\"Get a ItemFilter",
"policy_name = self._path_to_policy_names.get(path_with_no_args, \"\") kwargs = { \"headers\": { \"User-Agent\": self._user_agent, }, \"params\":",
"if not path_format_args: path_format_args = [] path_with_no_args = path.format((\"\" for _ in range(len(path_format_args))))",
"add to the HTTP request. Returns: The result of the API request, parsed",
"Dict, List, Optional, Type, TypeVar import aiohttp from yarl import URL from poe_client.rate_limiter",
"RateLimiter() self._path_to_policy_names = {} async def __aenter__(self) -> \"Client\": \"\"\"Runs on entering `async",
"else: logging.info(\"BLOCKING\") kwargs[\"raise_for_status\"] = False # type: ignore # The types are ignored",
"instance of the `model` type. \"\"\" json_result = await self._get_json(*args, **kwargs) assert isinstance(json_result,",
"for interacting with the Path of Exile API.\"\"\" _token: Optional[str] _base_url: URL =",
"poe_client.schemas.stash import PublicStash, StashTab Model = TypeVar(\"Model\") # the variable return type class",
"str(offset) if offset else None, \"limit\": str(limit) if limit else None, } #",
"and /characters/chris # presumably use the same rate limiting policy name. if await",
"path += \"/{2}\" # noqa: WPS336 path_format_args.append(substash_id) return await self._get( path=path, path_format_args=path_format_args, model=StashTab,",
"path: The URL path to use. Appended to the POE API base URL.",
"await self._client.close() if exc_val: raise exc_val return True # Type ignore is for",
"BLOCKING\") kwargs[\"raise_for_status\"] = True # type: ignore else: logging.info(\"BLOCKING\") kwargs[\"raise_for_status\"] = False #",
"is season.\") if match_type == PvPMatchType.league and not league: raise ValueError(\"league cannot be",
"query = {} if next_change_id: query[\"id\"] = next_change_id return await self._get_json( path=\"public-stash-tabs\", query=query,",
"return await self._get_list( path=\"character\", model=Character, result_field=\"characters\", ) async def get_character( self, name: str,",
"list of all pvp matches based on filters.\"\"\" if match_type == PvPMatchType.season and",
") -> League: \"\"\"Get a league based on league id.\"\"\" query = {}",
"return type class Client(object): \"\"\"Aiohttp class for interacting with the Path of Exile",
"set the typing inline without # flake8 complaining about overly complex annotation. logging.info(\"NOT",
"# that kwargs isn't a positional arg and won't override a different #",
"-> List[Model]: \"\"\"Make a get request and returns the data as a list",
"not path_format_args: path_format_args = [] path_with_no_args = path.format((\"\" for _ in range(len(path_format_args)))) policy_name",
"the beginning of the API's availability which is several years in the past.",
"and won't override a different # positional argument in the function. async with",
"as values, # but we're assigning booleans here. We can't set the typing",
"See _get_json for other args. Returns: The result, parsed into an instance of",
") -> List[League]: \"\"\"Get a list of all leagues based on filters.\"\"\" if",
"sublclass of APIType. result_field: If present, returns the data in this field from",
"agent. Used when making HTTP requests to the API. token: Authorization token to",
"async def __aexit__( self, exc_type: Optional[Type[BaseException]], exc_val: Optional[BaseException], exc_tb: Optional[TracebackType], ) -> Optional[bool]:",
"We construct this via a dict so that the linter doesn't complain about",
"USED IN PRODUCTION. \"\"\" async def get_item_filters( self, ) -> List[ItemFilter]: \"\"\"Get all",
"list of all leagues based on filters.\"\"\" if league_type == LeagueType.season and not",
"format args (\"{0}\") in the path, and the values for those args should",
"the API's availability which is several years in the past. Returns: A dict",
"offset else None, \"limit\": str(limit) if limit else None, } # Remove unset",
"import Account, Realm from poe_client.schemas.character import Character from poe_client.schemas.filter import ItemFilter from poe_client.schemas.league",
"None, } # Remove unset values query = {key: query_val for key, query_val",
"assert isinstance(json_result, list) # noqa: S101 return [model(**objitem) for objitem in json_result] async",
"logging.info(\"NOT BLOCKING\") kwargs[\"raise_for_status\"] = True # type: ignore else: logging.info(\"BLOCKING\") kwargs[\"raise_for_status\"] = False",
"league: str, ) -> List[StashTab]: \"\"\"Get all stash tabs belonging to token.\"\"\" return",
"# We ignore typing in the dict assignment. kwargs only has dicts as",
"in the path when the HTTP request gets made. query: An optional dict",
"data as an APIType subclass. Args: model: The object which contains data retrieved",
"path to use. Appended to the POE API base URL. If certain parts",
"id and account of token.\"\"\" return await self._get( path=\"character/{0}\", path_format_args=(name,), model=Character, result_field=\"character\", )",
"Optional[str], ) -> StashTab: \"\"\"Get a stash tab based on id.\"\"\" path =",
"str, ) -> Character: \"\"\"Get a character based on id and account of",
"type. \"\"\" json_result = await self._get_json(*args, **kwargs) assert isinstance(json_result, dict) # noqa: S101",
"the ladder of a league based on id.\"\"\" query = {} if realm:",
"args. This presumes that # different requests to the same endpoints with different",
"path=\"stash/{0}\", path_format_args=(league,), model=StashTab, result_field=\"stashes\", ) async def get_stash( self, league: str, stash_id: str,",
"\"\"\"League related methods for the POE API. CURRENTLY UNTESTED. HAS NOT BEEN USED",
"here. We can't set the typing inline without # flake8 complaining about overly",
"__init__( self, user_agent: str, token: Optional[str] = None, ) -> None: \"\"\"Initialize a",
"\"\"\"Make a get request and returns the data as an APIType subclass. Args:",
"dict) # noqa: S101 json_result = json_result[result_field] assert isinstance(json_result, list) # noqa: S101",
"realm: query[\"realm\"] = realm.value return await self._get( path=\"pvp-match/{0}/ladder\", path_format_args=(match,), model=PvPMatchLadder, result_field=\"match\", query=query, )",
"a stash tab based on id.\"\"\" path = \"stash/{0}/{1}\".format(league, stash_id) path_format_args = [league,",
"}, \"params\": query, } if self._token: headers = kwargs[\"headers\"] assert headers # noqa:",
"\"\"\"Make a get request and returns the data as a list of APIType",
"PvPMatchType.league and not league: raise ValueError(\"league cannot be empty if league_type is league.\")",
"APIs to simplify reading. There isn't any complicated inheritance # going on here.",
"path with no format args. This presumes that # different requests to the",
") -> StashTab: \"\"\"Get a stash tab based on id.\"\"\" path = \"stash/{0}/{1}\".format(league,",
"and not league: raise ValueError(\"league cannot be empty if league_type is league.\") #",
"League, LeagueType from poe_client.schemas.pvp import PvPMatch, PvPMatchLadder, PvPMatchType from poe_client.schemas.stash import PublicStash, StashTab",
"str = \"\", league: str = \"\", ) -> List[PvPMatch]: \"\"\"Get a list",
"str, token: Optional[str] = None, ) -> None: \"\"\"Initialize a new PoE client.",
"cannot be empty if league_type is season.\") if match_type == PvPMatchType.league and not",
"def get_league_ladder( self, league: str, realm: Optional[Realm] = None, ) -> Ladder: \"\"\"Get",
"auth token is used. \"\"\" self._token = token self._user_agent = user_agent self._limiter =",
"StashTab: \"\"\"Get a stash tab based on id.\"\"\" path = \"stash/{0}/{1}\".format(league, stash_id) path_format_args",
"present, returns the data in this field from the request, rather than the",
"await self._get( path=\"item-filter/{0}\", path_format_args=(filterid,), model=ItemFilter, result_field=\"filter\", ) class _PublicStashMixin(Client): \"\"\"Public stash tab methods",
"poe_client.schemas.character import Character from poe_client.schemas.filter import ItemFilter from poe_client.schemas.league import Ladder, League, LeagueType",
"numbers. # For example, \"/character/moowiz\" has an account name, so it's not a",
"characters belonging to token.\"\"\" return await self._get_list( path=\"character\", model=Character, result_field=\"characters\", ) async def",
"headers[\"Authorization\"] = \"Bearer {0}\".format(self._token) # We key the policy name off the path",
"the linter doesn't complain about # complexity. query = { \"realm\": realm.value if",
"realm else None, \"type\": league_type.value if league_type else None, \"season\": season if season",
"has support for every API GGG has exposed. None of these APIs have",
"-> Optional[bool]: \"\"\"Runs on exiting `async with`.\"\"\" await self._client.close() if exc_val: raise exc_val",
"= {} if realm: query[\"realm\"] = realm.value return await self._get( path=\"league/{0}\", path_format_args=(league,), model=League,",
"empty if league_type is season.\") if match_type == PvPMatchType.league and not league: raise",
"USED IN PRODUCTION. \"\"\" async def list_leagues( # noqa: WPS211 self, realm: Optional[Realm]",
"# We key the policy name off the path with no format args.",
"else None, \"offset\": str(offset) if offset else None, \"limit\": str(limit) if limit else",
"key, query_val in query.items() if query_val} return await self._get_list( path=\"pvp-match\", model=PvPMatch, result_field=\"matches\", query=query,",
"contains data retrieved from the API. Must be a sublclass of APIType. result_field:",
"{ \"User-Agent\": self._user_agent, }, \"params\": query, } if self._token: headers = kwargs[\"headers\"] assert",
"`model` type. \"\"\" json_result = await self._get_json(*args, **kwargs) if result_field: assert isinstance(json_result, dict)",
"path_with_no_args = path.format((\"\" for _ in range(len(path_format_args)))) policy_name = self._path_to_policy_names.get(path_with_no_args, \"\") kwargs =",
"API's availability which is several years in the past. Returns: A dict representing",
"await self._client.get( \"{0}/{1}\".format(self._base_url, path.format(*path_format_args)), **kwargs, # type: ignore ) as resp: self._path_to_policy_names[ path_with_no_args",
"await self._get_json( path=\"public-stash-tabs\", query=query, ) # Ignore WPS215, error about too many base",
"rather than the request itself. See _get_json for other args. Returns: The result,",
"related methods for the POE API. CURRENTLY UNTESTED. HAS NOT BEEN USED IN",
"are ignored because for some reason it can't understand # that kwargs isn't",
"on id.\"\"\" return await self._get( path=\"item-filter/{0}\", path_format_args=(filterid,), model=ItemFilter, result_field=\"filter\", ) class _PublicStashMixin(Client): \"\"\"Public",
"import Callable, Dict, List, Optional, Type, TypeVar import aiohttp from yarl import URL",
"The result, parsed into a list of the `model` type. \"\"\" json_result =",
"of the API request, parsed as JSON. \"\"\" if not path_format_args: path_format_args =",
"= None, season: str = \"\", league: str = \"\", ) -> List[PvPMatch]:",
"Optional[str] = None, *args, **kwargs, ) -> Model: \"\"\"Make a get request and",
"None, ) -> PublicStash: \"\"\"Get the latest public stash tabs. Args: next_change_id: If",
"cannot be empty if league_type is season.\") # We construct this via a",
"league_type.value if league_type else None, \"season\": season if season else None, \"offset\": str(offset)",
"query, } if self._token: headers = kwargs[\"headers\"] assert headers # noqa: S101 headers[\"Authorization\"]",
"if season else None, \"league\": league if league else None, } # Removed",
"beloning to the token.\"\"\" return await self._get(path=\"league\", model=Account) async def get_characters( self, )",
"\"/{2}\" # noqa: WPS336 path_format_args.append(substash_id) return await self._get( path=path, path_format_args=path_format_args, model=StashTab, result_field=\"stash\", )",
"if resp.status != 200: raise ValueError( \"Invalid request: status code {0}, expected 200\".format(",
"on filters.\"\"\" if league_type == LeagueType.season and not season: raise ValueError(\"season cannot be",
"S101 headers[\"Authorization\"] = \"Bearer {0}\".format(self._token) # We key the policy name off the",
"Optional[Type[BaseException]], exc_val: Optional[BaseException], exc_tb: Optional[TracebackType], ) -> Optional[bool]: \"\"\"Runs on exiting `async with`.\"\"\"",
"async def _get_list( # type: ignore self, model: Callable[..., Model], result_field: Optional[str] =",
"# presumably use the same rate limiting policy name. if await self._limiter.get_semaphore(policy_name): #",
"-> StashTab: \"\"\"Get a stash tab based on id.\"\"\" path = \"stash/{0}/{1}\".format(league, stash_id)",
"return await self._get(path=\"league\", model=Account) async def get_characters( self, ) -> List[Character]: \"\"\"Get all",
"inline without # flake8 complaining about overly complex annotation. logging.info(\"NOT BLOCKING\") kwargs[\"raise_for_status\"] =",
"CURRENTLY UNTESTED. HAS NOT BEEN USED IN PRODUCTION. \"\"\" async def get_item_filters( self,",
"\"\"\"Aiohttp class for interacting with the Path of Exile API.\"\"\" _token: Optional[str] _base_url:",
"get request and returns the data as a list of APIType subclass. Args:",
"\"season\": season if season else None, \"offset\": str(offset) if offset else None, \"limit\":",
"For example, /characters/moowiz and /characters/chris # presumably use the same rate limiting policy",
"\"\") kwargs = { \"headers\": { \"User-Agent\": self._user_agent, }, \"params\": query, } if",
"realm.value if realm else None, \"type\": league_type.value if league_type else None, \"season\": season",
"self, ) -> List[ItemFilter]: \"\"\"Get all item filters.\"\"\" return await self._get_list( path=\"item-filter\", model=ItemFilter,",
"result_field: If present, returns the data in this field from the request, rather",
"on entering `async with`.\"\"\" self._client = aiohttp.ClientSession(raise_for_status=True) return self async def __aexit__( self,",
"} # Removed unset query params query = {key: query_val for key, query_val",
"json_result] async def _get_json( self, path: str, path_format_args: Optional[List[str]] = None, query: Optional[Dict[str,",
"not season: raise ValueError(\"season cannot be empty if league_type is season.\") if match_type",
"def list_leagues( # noqa: WPS211 self, realm: Optional[Realm] = None, league_type: Optional[LeagueType] =",
"of a league based on id.\"\"\" query = {} if realm: query[\"realm\"] =",
"= None, ) -> League: \"\"\"Get a league based on league id.\"\"\" query",
"is several years in the past. Returns: A dict representing a public stash",
"name: str, ) -> Character: \"\"\"Get a character based on id and account",
") async def get_stash( self, league: str, stash_id: str, substash_id: Optional[str], ) ->",
"**kwargs, ) -> Model: \"\"\"Make a get request and returns the data as",
"different # positional argument in the function. async with await self._client.get( \"{0}/{1}\".format(self._base_url, path.format(*path_format_args)),",
"self._get_list( path=\"stash/{0}\", path_format_args=(league,), model=StashTab, result_field=\"stashes\", ) async def get_stash( self, league: str, stash_id:",
"result_field: Optional[str] = None, *args, **kwargs, ) -> Model: \"\"\"Make a get request",
"in practice this is required; not setting this value fetches stash tabs from",
"path. # \"/character/\" is the equivalent \"generic\" path. _path_to_policy_names: Dict[str, str] def __init__(",
"the path are non-static (account ID), those should be encoded as format args",
"realm.value return await self._get( path=\"league/{0}/ladder\", path_format_args=(league,), model=Ladder, result_field=\"ladder\", query=query, ) class _AccountMixin(Client): \"\"\"User",
"POE API. Args: path: The URL path to use. Appended to the POE",
"API. CURRENTLY UNTESTED. HAS NOT BEEN USED IN PRODUCTION. \"\"\" async def list_leagues(",
"from the beginning of the API's availability which is several years in the",
"positional argument in the function. async with await self._client.get( \"{0}/{1}\".format(self._base_url, path.format(*path_format_args)), **kwargs, #",
"linter doesn't complain about # complexity. query = { \"realm\": realm.value if realm",
"async def get_stashes( self, league: str, ) -> List[StashTab]: \"\"\"Get all stash tabs",
"match_type.value if match_type else None, \"realm\": realm.value if realm else None, \"season\": season",
"else None, } # Remove unset values query = {key: query_val for key,",
"def get_stashes( self, league: str, ) -> List[StashTab]: \"\"\"Get all stash tabs belonging",
"return await self._get( path=\"league/{0}/ladder\", path_format_args=(league,), model=Ladder, result_field=\"ladder\", query=query, ) class _AccountMixin(Client): \"\"\"User account",
"here. class PoEClient( # noqa: WPS215 _PvPMixin, _LeagueMixin, _AccountMixin, _FilterMixin, _PublicStashMixin, Client, ):",
"API. If unset, no auth token is used. \"\"\" self._token = token self._user_agent",
"all characters belonging to token.\"\"\" return await self._get_list( path=\"character\", model=Character, result_field=\"characters\", ) async",
"names. # Generic paths are paths with no IDs or unique numbers. #",
"query params query = {key: query_val for key, query_val in query.items() if query_val}",
"season if season else None, \"offset\": str(offset) if offset else None, \"limit\": str(limit)",
"A dict representing a public stash change. \"\"\" query = {} if next_change_id:",
"{ \"headers\": { \"User-Agent\": self._user_agent, }, \"params\": query, } if self._token: headers =",
"if self._token: headers = kwargs[\"headers\"] assert headers # noqa: S101 headers[\"Authorization\"] = \"Bearer",
"await self._get( path=path, path_format_args=path_format_args, model=StashTab, result_field=\"stash\", ) class _FilterMixin(Client): \"\"\"Item Filter methods for",
"We ignore typing in the dict assignment. kwargs only has dicts as values,",
"Ladder, League, LeagueType from poe_client.schemas.pvp import PvPMatch, PvPMatchLadder, PvPMatchType from poe_client.schemas.stash import PublicStash,",
"ItemFilter from poe_client.schemas.league import Ladder, League, LeagueType from poe_client.schemas.pvp import PvPMatch, PvPMatchLadder, PvPMatchType",
") async def get_league( self, league: str, realm: Optional[Realm] = None, ) ->",
"_get_json async def _get_list( # type: ignore self, model: Callable[..., Model], result_field: Optional[str]",
"isn't any complicated inheritance # going on here. class PoEClient( # noqa: WPS215",
"the values for those args should be passed into path_format_args. path_format_args: Values which",
"past. Returns: A dict representing a public stash change. \"\"\" query = {}",
"types import TracebackType from typing import Callable, Dict, List, Optional, Type, TypeVar import",
"exiting `async with`.\"\"\" await self._client.close() if exc_val: raise exc_val return True # Type",
"league based on league id.\"\"\" query = {} if realm: query[\"realm\"] = realm.value",
"self async def __aexit__( self, exc_type: Optional[Type[BaseException]], exc_val: Optional[BaseException], exc_tb: Optional[TracebackType], ) ->",
"The types are ignored because for some reason it can't understand # that",
"\"Invalid request: status code {0}, expected 200\".format( resp.status, ), ) return await resp.json()",
"tabs. Args: next_change_id: If set, returns the next set of stash tabs, starting",
"_AccountMixin(Client): \"\"\"User account methods for the POE API. CURRENTLY UNTESTED. HAS NOT BEEN",
"self._get_json( path=\"public-stash-tabs\", query=query, ) # Ignore WPS215, error about too many base classes.",
"parsed into a list of the `model` type. \"\"\" json_result = await self._get_json(*args,",
"equivalent \"generic\" path. _path_to_policy_names: Dict[str, str] def __init__( self, user_agent: str, token: Optional[str]",
"-> List[StashTab]: \"\"\"Get all stash tabs belonging to token.\"\"\" return await self._get_list( path=\"stash/{0}\",",
"league_type else None, \"season\": season if season else None, \"offset\": str(offset) if offset",
"path.format((\"\" for _ in range(len(path_format_args)))) policy_name = self._path_to_policy_names.get(path_with_no_args, \"\") kwargs = { \"headers\":",
"-> ItemFilter: \"\"\"Get a ItemFilter based on id.\"\"\" return await self._get( path=\"item-filter/{0}\", path_format_args=(filterid,),",
"self._user_agent, }, \"params\": query, } if self._token: headers = kwargs[\"headers\"] assert headers #",
"APIs have been tested in production, so use at your own risk. \"\"\"",
"object which contains data retrieved from the API. Must be a sublclass of",
"await self._limiter.get_semaphore(policy_name): # We ignore typing in the dict assignment. kwargs only has",
"-> PvPMatch: \"\"\"Get a pvp match based on id.\"\"\" query = {} if",
"-> Account: \"\"\"Get the account beloning to the token.\"\"\" return await self._get(path=\"league\", model=Account)",
"argument in the function. async with await self._client.get( \"{0}/{1}\".format(self._base_url, path.format(*path_format_args)), **kwargs, # type:",
"[] path_with_no_args = path.format((\"\" for _ in range(len(path_format_args)))) policy_name = self._path_to_policy_names.get(path_with_no_args, \"\") kwargs",
"# noqa: S101 if result_field: json_result = json_result[result_field] return model(**json_result) # Type ignore",
"def __init__( self, user_agent: str, token: Optional[str] = None, ) -> None: \"\"\"Initialize",
"self._get_json(*args, **kwargs) if result_field: assert isinstance(json_result, dict) # noqa: S101 json_result = json_result[result_field]",
"it's not a base path. # \"/character/\" is the equivalent \"generic\" path. _path_to_policy_names:",
"can't set the typing inline without # flake8 complaining about overly complex annotation.",
") -> Ladder: \"\"\"Get the ladder of a league based on id.\"\"\" query",
"with the Path of Exile API.\"\"\" _token: Optional[str] _base_url: URL = URL(\"https://api.pathofexile.com\") _client:",
"None, \"type\": league_type.value if league_type else None, \"season\": season if season else None,",
"None, \"league\": league if league else None, } # Removed unset query params",
"fetches stash tabs from the beginning of the API's availability which is several",
"ignore ) as resp: self._path_to_policy_names[ path_with_no_args ] = await self._limiter.parse_headers(resp.headers) if resp.status !=",
"query params to add to the HTTP request. Returns: The result of the",
"at this change_id. While this is technically optional, in practice this is required;",
"Must be a sublclass of APIType. result_field: If present, returns the data in",
"so that the linter doesn't complain about # complexity. query = { \"realm\":",
"inheritance # going on here. class PoEClient( # noqa: WPS215 _PvPMixin, _LeagueMixin, _AccountMixin,",
"noqa: WPS211 self, realm: Optional[Realm] = None, league_type: Optional[LeagueType] = None, offset: int",
"result_field=\"leagues\", query=query, ) async def get_league( self, league: str, realm: Optional[Realm] = None,",
"if result_field: json_result = json_result[result_field] return model(**json_result) # Type ignore is for args",
"to the API. token: Authorization token to pass to the PoE API. If",
"HAS NOT BEEN USED IN PRODUCTION. \"\"\" async def get_item_filters( self, ) ->",
"typing inline without # flake8 complaining about overly complex annotation. logging.info(\"NOT BLOCKING\") kwargs[\"raise_for_status\"]",
"self, user_agent: str, token: Optional[str] = None, ) -> None: \"\"\"Initialize a new",
"query=query, ) async def get_league_ladder( self, league: str, realm: Optional[Realm] = None, )",
"complexity. query = { \"type\": match_type.value if match_type else None, \"realm\": realm.value if",
"example, /characters/moowiz and /characters/chris # presumably use the same rate limiting policy name.",
"See _get_json for other args. Returns: The result, parsed into a list of",
"a league based on league id.\"\"\" query = {} if realm: query[\"realm\"] =",
"result_field=\"characters\", ) async def get_character( self, name: str, ) -> Character: \"\"\"Get a",
"used. \"\"\" self._token = token self._user_agent = user_agent self._limiter = RateLimiter() self._path_to_policy_names =",
"= {} if next_change_id: query[\"id\"] = next_change_id return await self._get_json( path=\"public-stash-tabs\", query=query, )",
"USED IN PRODUCTION. \"\"\" async def get_profile( self, ) -> Account: \"\"\"Get the",
"we're assigning booleans here. We can't set the typing inline without # flake8",
"a ItemFilter based on id.\"\"\" return await self._get( path=\"item-filter/{0}\", path_format_args=(filterid,), model=ItemFilter, result_field=\"filter\", )",
"availability which is several years in the past. Returns: A dict representing a",
"in query.items() if query_val} return await self._get_list( path=\"league\", model=League, result_field=\"leagues\", query=query, ) async",
") async def get_stashes( self, league: str, ) -> List[StashTab]: \"\"\"Get all stash",
"APIType subclass. Args: model: The object which contains data retrieved from the API.",
"construct this via a dict so that the linter doesn't complain about #",
"those should be encoded as format args (\"{0}\") in the path, and the",
"a positional arg and won't override a different # positional argument in the",
") -> ItemFilter: \"\"\"Get a ItemFilter based on id.\"\"\" return await self._get( path=\"item-filter/{0}\",",
"-> PvPMatchLadder: \"\"\"Get a pvp match based on id.\"\"\" query = {} if",
"these APIs have been tested in production, so use at your own risk.",
"WPS211 self, realm: Optional[Realm] = None, league_type: Optional[LeagueType] = None, offset: int =",
"self._client.get( \"{0}/{1}\".format(self._base_url, path.format(*path_format_args)), **kwargs, # type: ignore ) as resp: self._path_to_policy_names[ path_with_no_args ]",
"= None, offset: int = 0, season: str = \"\", limit: int =",
"S101 return [model(**objitem) for objitem in json_result] async def _get_json( self, path: str,",
"None, league_type: Optional[LeagueType] = None, offset: int = 0, season: str = \"\",",
"= aiohttp.ClientSession(raise_for_status=True) return self async def __aexit__( self, exc_type: Optional[Type[BaseException]], exc_val: Optional[BaseException], exc_tb:",
"with no format args. This presumes that # different requests to the same",
"path_format_args = [league, stash_id] if substash_id: path += \"/{2}\" # noqa: WPS336 path_format_args.append(substash_id)",
"based on filters.\"\"\" if league_type == LeagueType.season and not season: raise ValueError(\"season cannot",
"= realm.value return await self._get( path=\"pvp-match/{0}\", path_format_args=(match,), model=PvPMatch, result_field=\"match\", query=query, ) async def",
"in this field from the request, rather than the request itself. See _get_json",
"query_val in query.items() if query_val} return await self._get_list( path=\"pvp-match\", model=PvPMatch, result_field=\"matches\", query=query, )",
"params to add to the HTTP request. Returns: The result of the API",
"result_field=\"ladder\", query=query, ) class _AccountMixin(Client): \"\"\"User account methods for the POE API. CURRENTLY",
"the different APIs to simplify reading. There isn't any complicated inheritance # going",
"request itself. See _get_json for other args. Returns: The result, parsed into a",
"= None, ): \"\"\"Fetches data from the POE API. Args: path: The URL",
"IN PRODUCTION. \"\"\" async def get_profile( self, ) -> Account: \"\"\"Get the account",
"-> Ladder: \"\"\"Get the ladder of a league based on id.\"\"\" query =",
"classes. We use multiple to better split up # the different APIs to",
"parsed into an instance of the `model` type. \"\"\" json_result = await self._get_json(*args,",
"raise ValueError( \"Invalid request: status code {0}, expected 200\".format( resp.status, ), ) return",
"\"\"\"Public stash tab methods for the POE API. CURRENTLY UNTESTED. HAS NOT BEEN",
"filters.\"\"\" if league_type == LeagueType.season and not season: raise ValueError(\"season cannot be empty",
"with no IDs or unique numbers. # For example, \"/character/moowiz\" has an account",
"query: Optional[Dict[str, str]] = None, ): \"\"\"Fetches data from the POE API. Args:",
"offset: int = 0, season: str = \"\", limit: int = 50, )",
"the past. Returns: A dict representing a public stash change. \"\"\" query =",
"user_agent: An OAuth user agent. Used when making HTTP requests to the API.",
"Realm from poe_client.schemas.character import Character from poe_client.schemas.filter import ItemFilter from poe_client.schemas.league import Ladder,",
"be a sublclass of APIType. result_field: If present, returns the data in this",
"stash tabs, starting at this change_id. While this is technically optional, in practice",
"This technically has support for every API GGG has exposed. None of these",
"self._get_list( path=\"item-filter\", model=ItemFilter, result_field=\"filters\", ) async def get_item_filter( self, filterid: str, ) ->",
"path_format_args=(league,), model=Ladder, result_field=\"ladder\", query=query, ) class _AccountMixin(Client): \"\"\"User account methods for the POE",
"noqa: S101 headers[\"Authorization\"] = \"Bearer {0}\".format(self._token) # We key the policy name off",
"= None, query: Optional[Dict[str, str]] = None, ): \"\"\"Fetches data from the POE",
"\"\"\"Get a league based on league id.\"\"\" query = {} if realm: query[\"realm\"]",
"if match_type else None, \"realm\": realm.value if realm else None, \"season\": season if",
") as resp: self._path_to_policy_names[ path_with_no_args ] = await self._limiter.parse_headers(resp.headers) if resp.status != 200:",
"str, stash_id: str, substash_id: Optional[str], ) -> StashTab: \"\"\"Get a stash tab based",
"50, ) -> List[League]: \"\"\"Get a list of all leagues based on filters.\"\"\"",
"await self._get( path=\"pvp-match/{0}/ladder\", path_format_args=(match,), model=PvPMatchLadder, result_field=\"match\", query=query, ) class _LeagueMixin(Client): \"\"\"League related methods",
"League: \"\"\"Get a league based on league id.\"\"\" query = {} if realm:",
"IN PRODUCTION. \"\"\" async def get_pvp_matches( self, realm: Optional[Realm] = None, match_type: Optional[PvPMatchType]",
"return await self._get_json( path=\"public-stash-tabs\", query=query, ) # Ignore WPS215, error about too many",
"path when the HTTP request gets made. query: An optional dict of query",
"ValueError(\"season cannot be empty if league_type is season.\") if match_type == PvPMatchType.league and",
"to simplify reading. There isn't any complicated inheritance # going on here. class",
"import URL from poe_client.rate_limiter import RateLimiter from poe_client.schemas.account import Account, Realm from poe_client.schemas.character",
"query = {} if realm: query[\"realm\"] = realm.value return await self._get( path=\"pvp-match/{0}/ladder\", path_format_args=(match,),",
"= [] path_with_no_args = path.format((\"\" for _ in range(len(path_format_args)))) policy_name = self._path_to_policy_names.get(path_with_no_args, \"\")",
"self._get( path=path, path_format_args=path_format_args, model=StashTab, result_field=\"stash\", ) class _FilterMixin(Client): \"\"\"Item Filter methods for the",
"without # flake8 complaining about overly complex annotation. logging.info(\"NOT BLOCKING\") kwargs[\"raise_for_status\"] = True",
"NOT BEEN USED IN PRODUCTION. \"\"\" async def get_pvp_matches( self, realm: Optional[Realm] =",
"a dict so that the linter doesn't complain about # complexity. query =",
"List[Model]: \"\"\"Make a get request and returns the data as a list of",
"query_val} return await self._get_list( path=\"league\", model=League, result_field=\"leagues\", query=query, ) async def get_league( self,",
"isn't a positional arg and won't override a different # positional argument in",
"TracebackType from typing import Callable, Dict, List, Optional, Type, TypeVar import aiohttp from",
"Authorization token to pass to the PoE API. If unset, no auth token",
"Type, TypeVar import aiohttp from yarl import URL from poe_client.rate_limiter import RateLimiter from",
"} # Remove unset values query = {key: query_val for key, query_val in",
"based on filters.\"\"\" if match_type == PvPMatchType.season and not season: raise ValueError(\"season cannot",
"if realm else None, \"season\": season if season else None, \"league\": league if",
"if league_type is season.\") if match_type == PvPMatchType.league and not league: raise ValueError(\"league",
"# noqa: WPS215 _PvPMixin, _LeagueMixin, _AccountMixin, _FilterMixin, _PublicStashMixin, Client, ): \"\"\"Client for PoE",
"because for some reason it can't understand # that kwargs isn't a positional",
"None, \"realm\": realm.value if realm else None, \"season\": season if season else None,",
"Args: next_change_id: If set, returns the next set of stash tabs, starting at",
"season.\") if match_type == PvPMatchType.league and not league: raise ValueError(\"league cannot be empty",
"API request, parsed as JSON. \"\"\" if not path_format_args: path_format_args = [] path_with_no_args",
") -> List[PvPMatch]: \"\"\"Get a list of all pvp matches based on filters.\"\"\"",
"item filters.\"\"\" return await self._get_list( path=\"item-filter\", model=ItemFilter, result_field=\"filters\", ) async def get_item_filter( self,",
"annotation. logging.info(\"NOT BLOCKING\") kwargs[\"raise_for_status\"] = True # type: ignore else: logging.info(\"BLOCKING\") kwargs[\"raise_for_status\"] =",
"data in this field from the request, rather than the request itself. See",
"Client(object): \"\"\"Aiohttp class for interacting with the Path of Exile API.\"\"\" _token: Optional[str]",
"self._path_to_policy_names[ path_with_no_args ] = await self._limiter.parse_headers(resp.headers) if resp.status != 200: raise ValueError( \"Invalid",
") -> PvPMatchLadder: \"\"\"Get a pvp match based on id.\"\"\" query = {}",
"stash tabs from the beginning of the API's availability which is several years",
"realm.value return await self._get( path=\"pvp-match/{0}\", path_format_args=(match,), model=PvPMatch, result_field=\"match\", query=query, ) async def get_pvp_match_ladder(",
"def get_character( self, name: str, ) -> Character: \"\"\"Get a character based on",
"return True # Type ignore is for args and kwargs, which have unknown",
"not season: raise ValueError(\"season cannot be empty if league_type is season.\") # We",
"True # type: ignore else: logging.info(\"BLOCKING\") kwargs[\"raise_for_status\"] = False # type: ignore #",
"-> None: \"\"\"Initialize a new PoE client. Args: user_agent: An OAuth user agent.",
"async def get_pvp_match_ladder( self, match: str, realm: Optional[Realm] = None, ) -> PvPMatchLadder:",
"list of the `model` type. \"\"\" json_result = await self._get_json(*args, **kwargs) if result_field:",
"reading. There isn't any complicated inheritance # going on here. class PoEClient( #",
"Filter methods for the POE API. CURRENTLY UNTESTED. HAS NOT BEEN USED IN",
"as an APIType subclass. Args: model: The object which contains data retrieved from",
"stash_id) path_format_args = [league, stash_id] if substash_id: path += \"/{2}\" # noqa: WPS336",
"get_item_filter( self, filterid: str, ) -> ItemFilter: \"\"\"Get a ItemFilter based on id.\"\"\"",
"kwargs, which have unknown types we pass to _get_json async def _get_list( #",
"path=\"league\", model=League, result_field=\"leagues\", query=query, ) async def get_league( self, league: str, realm: Optional[Realm]",
"latest public stash tabs. Args: next_change_id: If set, returns the next set of",
"\"type\": league_type.value if league_type else None, \"season\": season if season else None, \"offset\":",
"can't understand # that kwargs isn't a positional arg and won't override a",
"id.\"\"\" query = {} if realm: query[\"realm\"] = realm.value return await self._get( path=\"pvp-match/{0}\",",
"be encoded in the path when the HTTP request gets made. query: An",
"simplify reading. There isn't any complicated inheritance # going on here. class PoEClient(",
"use. Appended to the POE API base URL. If certain parts of the",
"retrieved from the API. Must be a sublclass of APIType. result_field: If present,",
"base path. # \"/character/\" is the equivalent \"generic\" path. _path_to_policy_names: Dict[str, str] def",
"self, league: str, realm: Optional[Realm] = None, ) -> League: \"\"\"Get a league",
"model=StashTab, result_field=\"stash\", ) class _FilterMixin(Client): \"\"\"Item Filter methods for the POE API. CURRENTLY",
"aiohttp.ClientSession(raise_for_status=True) return self async def __aexit__( self, exc_type: Optional[Type[BaseException]], exc_val: Optional[BaseException], exc_tb: Optional[TracebackType],",
"0, season: str = \"\", limit: int = 50, ) -> List[League]: \"\"\"Get",
"**kwargs) assert isinstance(json_result, dict) # noqa: S101 if result_field: json_result = json_result[result_field] return",
"\"\"\"Get all stash tabs belonging to token.\"\"\" return await self._get_list( path=\"stash/{0}\", path_format_args=(league,), model=StashTab,",
"which contains data retrieved from the API. Must be a sublclass of APIType.",
"This presumes that # different requests to the same endpoints with different specific",
"result_field: json_result = json_result[result_field] return model(**json_result) # Type ignore is for args and",
"None, ) -> PvPMatchLadder: \"\"\"Get a pvp match based on id.\"\"\" query =",
"in the function. async with await self._client.get( \"{0}/{1}\".format(self._base_url, path.format(*path_format_args)), **kwargs, # type: ignore",
"= \"\", league: str = \"\", ) -> List[PvPMatch]: \"\"\"Get a list of",
"= next_change_id return await self._get_json( path=\"public-stash-tabs\", query=query, ) # Ignore WPS215, error about",
"which is several years in the past. Returns: A dict representing a public",
"season.\") # We construct this via a dict so that the linter doesn't",
"for those args should be passed into path_format_args. path_format_args: Values which should be",
"int = 0, season: str = \"\", limit: int = 50, ) ->",
"is league.\") # We construct this via a dict so that the linter",
"specific args use the # same rate limiting. For example, /characters/moowiz and /characters/chris",
"tabs belonging to token.\"\"\" return await self._get_list( path=\"stash/{0}\", path_format_args=(league,), model=StashTab, result_field=\"stashes\", ) async",
"= \"\", limit: int = 50, ) -> List[League]: \"\"\"Get a list of",
") # Ignore WPS215, error about too many base classes. We use multiple",
"the account beloning to the token.\"\"\" return await self._get(path=\"league\", model=Account) async def get_characters(",
"when making HTTP requests to the API. token: Authorization token to pass to",
"# positional argument in the function. async with await self._client.get( \"{0}/{1}\".format(self._base_url, path.format(*path_format_args)), **kwargs,",
"[model(**objitem) for objitem in json_result] async def _get_json( self, path: str, path_format_args: Optional[List[str]]",
"character based on id and account of token.\"\"\" return await self._get( path=\"character/{0}\", path_format_args=(name,),",
"query = {} if realm: query[\"realm\"] = realm.value return await self._get( path=\"league/{0}/ladder\", path_format_args=(league,),",
"Character: \"\"\"Get a character based on id and account of token.\"\"\" return await",
"S101 json_result = json_result[result_field] assert isinstance(json_result, list) # noqa: S101 return [model(**objitem) for",
"unset values query = {key: query_val for key, query_val in query.items() if query_val}",
"BEEN USED IN PRODUCTION. \"\"\" async def get_item_filters( self, ) -> List[ItemFilter]: \"\"\"Get",
"_FilterMixin(Client): \"\"\"Item Filter methods for the POE API. CURRENTLY UNTESTED. HAS NOT BEEN",
"other args. Returns: The result, parsed into an instance of the `model` type.",
"await self._limiter.parse_headers(resp.headers) if resp.status != 200: raise ValueError( \"Invalid request: status code {0},",
"the variable return type class Client(object): \"\"\"Aiohttp class for interacting with the Path",
"# Ignore WPS215, error about too many base classes. We use multiple to",
"as JSON. \"\"\" if not path_format_args: path_format_args = [] path_with_no_args = path.format((\"\" for",
"\"Bearer {0}\".format(self._token) # We key the policy name off the path with no",
"path=\"league/{0}\", path_format_args=(league,), model=League, result_field=\"league\", query=query, ) async def get_league_ladder( self, league: str, realm:",
"based on id and account of token.\"\"\" return await self._get( path=\"character/{0}\", path_format_args=(name,), model=Character,",
"match based on id.\"\"\" query = {} if realm: query[\"realm\"] = realm.value return",
"params query = {key: query_val for key, query_val in query.items() if query_val} return",
"Callable[..., Model], result_field: Optional[str] = None, *args, **kwargs, ) -> List[Model]: \"\"\"Make a",
"else None, \"type\": league_type.value if league_type else None, \"season\": season if season else",
"league: str, realm: Optional[Realm] = None, ) -> Ladder: \"\"\"Get the ladder of",
") async def get_character( self, name: str, ) -> Character: \"\"\"Get a character",
"Dict[str, str] def __init__( self, user_agent: str, token: Optional[str] = None, ) ->",
") class _PublicStashMixin(Client): \"\"\"Public stash tab methods for the POE API. CURRENTLY UNTESTED.",
"= \"Bearer {0}\".format(self._token) # We key the policy name off the path with",
"of token.\"\"\" return await self._get( path=\"character/{0}\", path_format_args=(name,), model=Character, result_field=\"character\", ) async def get_stashes(",
"going on here. class PoEClient( # noqa: WPS215 _PvPMixin, _LeagueMixin, _AccountMixin, _FilterMixin, _PublicStashMixin,",
"range(len(path_format_args)))) policy_name = self._path_to_policy_names.get(path_with_no_args, \"\") kwargs = { \"headers\": { \"User-Agent\": self._user_agent, },",
"_get( # type: ignore self, model: Callable[..., Model], result_field: Optional[str] = None, *args,",
"presumes that # different requests to the same endpoints with different specific args",
"result, parsed into an instance of the `model` type. \"\"\" json_result = await",
"of query params to add to the HTTP request. Returns: The result of",
"based on id.\"\"\" query = {} if realm: query[\"realm\"] = realm.value return await",
"If present, returns the data in this field from the request, rather than",
"a base path. # \"/character/\" is the equivalent \"generic\" path. _path_to_policy_names: Dict[str, str]",
"Optional[str] = None, *args, **kwargs, ) -> List[Model]: \"\"\"Make a get request and",
"None of these APIs have been tested in production, so use at your",
"import Character from poe_client.schemas.filter import ItemFilter from poe_client.schemas.league import Ladder, League, LeagueType from",
"get_character( self, name: str, ) -> Character: \"\"\"Get a character based on id",
"[league, stash_id] if substash_id: path += \"/{2}\" # noqa: WPS336 path_format_args.append(substash_id) return await",
"API. Args: path: The URL path to use. Appended to the POE API",
"else None, \"season\": season if season else None, \"offset\": str(offset) if offset else",
"on filters.\"\"\" if match_type == PvPMatchType.season and not season: raise ValueError(\"season cannot be",
"def get_characters( self, ) -> List[Character]: \"\"\"Get all characters belonging to token.\"\"\" return",
"\"\"\" json_result = await self._get_json(*args, **kwargs) if result_field: assert isinstance(json_result, dict) # noqa:",
"# noqa: S101 return [model(**objitem) for objitem in json_result] async def _get_json( self,",
"based on league id.\"\"\" query = {} if realm: query[\"realm\"] = realm.value return",
"realm: query[\"realm\"] = realm.value return await self._get( path=\"league/{0}/ladder\", path_format_args=(league,), model=Ladder, result_field=\"ladder\", query=query, )",
"is technically optional, in practice this is required; not setting this value fetches",
"None, query: Optional[Dict[str, str]] = None, ): \"\"\"Fetches data from the POE API.",
"There isn't any complicated inheritance # going on here. class PoEClient( # noqa:",
"def get_item_filter( self, filterid: str, ) -> ItemFilter: \"\"\"Get a ItemFilter based on",
"async def get_stash( self, league: str, stash_id: str, substash_id: Optional[str], ) -> StashTab:",
"return await self._get( path=\"pvp-match/{0}\", path_format_args=(match,), model=PvPMatch, result_field=\"match\", query=query, ) async def get_pvp_match_ladder( self,",
"= 0, season: str = \"\", limit: int = 50, ) -> List[League]:",
"API. CURRENTLY UNTESTED. HAS NOT BEEN USED IN PRODUCTION. \"\"\" async def get_public_stash_tabs(",
"on exiting `async with`.\"\"\" await self._client.close() if exc_val: raise exc_val return True #",
"about # complexity. query = { \"realm\": realm.value if realm else None, \"type\":",
"str] def __init__( self, user_agent: str, token: Optional[str] = None, ) -> None:",
"List[Character]: \"\"\"Get all characters belonging to token.\"\"\" return await self._get_list( path=\"character\", model=Character, result_field=\"characters\",",
"policy name. if await self._limiter.get_semaphore(policy_name): # We ignore typing in the dict assignment.",
"Args: user_agent: An OAuth user agent. Used when making HTTP requests to the",
"= None, ) -> Ladder: \"\"\"Get the ladder of a league based on",
"result, parsed into a list of the `model` type. \"\"\" json_result = await",
"if realm: query[\"realm\"] = realm.value return await self._get( path=\"league/{0}\", path_format_args=(league,), model=League, result_field=\"league\", query=query,",
"None, *args, **kwargs, ) -> List[Model]: \"\"\"Make a get request and returns the",
"self, realm: Optional[Realm] = None, match_type: Optional[PvPMatchType] = None, season: str = \"\",",
"\"\"\" async def get_pvp_matches( self, realm: Optional[Realm] = None, match_type: Optional[PvPMatchType] = None,",
"of the `model` type. \"\"\" json_result = await self._get_json(*args, **kwargs) assert isinstance(json_result, dict)",
"poe_client.rate_limiter import RateLimiter from poe_client.schemas.account import Account, Realm from poe_client.schemas.character import Character from",
"\"\"\"Runs on exiting `async with`.\"\"\" await self._client.close() if exc_val: raise exc_val return True",
"async def get_character( self, name: str, ) -> Character: \"\"\"Get a character based",
"await self._get( path=\"league/{0}\", path_format_args=(league,), model=League, result_field=\"league\", query=query, ) async def get_league_ladder( self, league:",
"# but we're assigning booleans here. We can't set the typing inline without",
"GGG has exposed. None of these APIs have been tested in production, so",
"= {} async def __aenter__(self) -> \"Client\": \"\"\"Runs on entering `async with`.\"\"\" self._client",
"# type: ignore self, model: Callable[..., Model], result_field: Optional[str] = None, *args, **kwargs,",
"from poe_client.schemas.account import Account, Realm from poe_client.schemas.character import Character from poe_client.schemas.filter import ItemFilter",
") -> None: \"\"\"Initialize a new PoE client. Args: user_agent: An OAuth user",
"be empty if league_type is season.\") if match_type == PvPMatchType.league and not league:",
"async def _get_json( self, path: str, path_format_args: Optional[List[str]] = None, query: Optional[Dict[str, str]]",
"RateLimiter # Maps \"generic\" paths to rate limiting policy names. # Generic paths",
"= \"\", ) -> List[PvPMatch]: \"\"\"Get a list of all pvp matches based",
"ignore self, model: Callable[..., Model], result_field: Optional[str] = None, *args, **kwargs, ) ->",
"None, \"season\": season if season else None, \"league\": league if league else None,",
"list) # noqa: S101 return [model(**objitem) for objitem in json_result] async def _get_json(",
"List, Optional, Type, TypeVar import aiohttp from yarl import URL from poe_client.rate_limiter import",
"account beloning to the token.\"\"\" return await self._get(path=\"league\", model=Account) async def get_characters( self,",
"if query_val} return await self._get_list( path=\"pvp-match\", model=PvPMatch, result_field=\"matches\", query=query, ) async def get_pvp_match(",
"} if self._token: headers = kwargs[\"headers\"] assert headers # noqa: S101 headers[\"Authorization\"] =",
"def get_public_stash_tabs( self, next_change_id: Optional[str] = None, ) -> PublicStash: \"\"\"Get the latest",
"realm: Optional[Realm] = None, ) -> Ladder: \"\"\"Get the ladder of a league",
"# For example, \"/character/moowiz\" has an account name, so it's not a base",
"values query = {key: query_val for key, query_val in query.items() if query_val} return",
"and not season: raise ValueError(\"season cannot be empty if league_type is season.\") if",
"same rate limiting policy name. if await self._limiter.get_semaphore(policy_name): # We ignore typing in",
"exc_val: raise exc_val return True # Type ignore is for args and kwargs,",
"UNTESTED. HAS NOT BEEN USED IN PRODUCTION. \"\"\" async def get_profile( self, )",
"name. if await self._limiter.get_semaphore(policy_name): # We ignore typing in the dict assignment. kwargs",
"complain about # complexity. query = { \"realm\": realm.value if realm else None,",
"None, \"limit\": str(limit) if limit else None, } # Remove unset values query",
"a sublclass of APIType. result_field: If present, returns the data in this field",
"account of token.\"\"\" return await self._get( path=\"character/{0}\", path_format_args=(name,), model=Character, result_field=\"character\", ) async def",
"_PublicStashMixin(Client): \"\"\"Public stash tab methods for the POE API. CURRENTLY UNTESTED. HAS NOT",
"the path with no format args. This presumes that # different requests to",
"to add to the HTTP request. Returns: The result of the API request,",
"self._client = aiohttp.ClientSession(raise_for_status=True) return self async def __aexit__( self, exc_type: Optional[Type[BaseException]], exc_val: Optional[BaseException],",
"parsed as JSON. \"\"\" if not path_format_args: path_format_args = [] path_with_no_args = path.format((\"\"",
"about # complexity. query = { \"type\": match_type.value if match_type else None, \"realm\":",
"split up # the different APIs to simplify reading. There isn't any complicated",
"ID), those should be encoded as format args (\"{0}\") in the path, and",
"and kwargs, which have unknown types we pass to _get_json async def _get_list(",
"in the past. Returns: A dict representing a public stash change. \"\"\" query",
"self._get_list( path=\"pvp-match\", model=PvPMatch, result_field=\"matches\", query=query, ) async def get_pvp_match( self, match: str, realm:",
"model: The object which contains data retrieved from the API. Must be a",
"is for args and kwargs, which have unknown types we pass to _get_json",
"# Maps \"generic\" paths to rate limiting policy names. # Generic paths are",
"async with await self._client.get( \"{0}/{1}\".format(self._base_url, path.format(*path_format_args)), **kwargs, # type: ignore ) as resp:",
"def get_pvp_matches( self, realm: Optional[Realm] = None, match_type: Optional[PvPMatchType] = None, season: str",
"if realm: query[\"realm\"] = realm.value return await self._get( path=\"pvp-match/{0}/ladder\", path_format_args=(match,), model=PvPMatchLadder, result_field=\"match\", query=query,",
"kwargs[\"headers\"] assert headers # noqa: S101 headers[\"Authorization\"] = \"Bearer {0}\".format(self._token) # We key",
"Optional[LeagueType] = None, offset: int = 0, season: str = \"\", limit: int",
"stash tab methods for the POE API. CURRENTLY UNTESTED. HAS NOT BEEN USED",
"import RateLimiter from poe_client.schemas.account import Account, Realm from poe_client.schemas.character import Character from poe_client.schemas.filter",
"match_type else None, \"realm\": realm.value if realm else None, \"season\": season if season",
"rate limiting. For example, /characters/moowiz and /characters/chris # presumably use the same rate",
"For example, \"/character/moowiz\" has an account name, so it's not a base path.",
"list_leagues( # noqa: WPS211 self, realm: Optional[Realm] = None, league_type: Optional[LeagueType] = None,",
"URL(\"https://api.pathofexile.com\") _client: aiohttp.ClientSession _user_agent: str _limiter: RateLimiter # Maps \"generic\" paths to rate",
"\"\"\"Runs on entering `async with`.\"\"\" self._client = aiohttp.ClientSession(raise_for_status=True) return self async def __aexit__(",
") -> List[Model]: \"\"\"Make a get request and returns the data as a",
"import ItemFilter from poe_client.schemas.league import Ladder, League, LeagueType from poe_client.schemas.pvp import PvPMatch, PvPMatchLadder,",
"the typing inline without # flake8 complaining about overly complex annotation. logging.info(\"NOT BLOCKING\")",
"complicated inheritance # going on here. class PoEClient( # noqa: WPS215 _PvPMixin, _LeagueMixin,",
"if realm else None, \"type\": league_type.value if league_type else None, \"season\": season if",
"\"\"\" self._token = token self._user_agent = user_agent self._limiter = RateLimiter() self._path_to_policy_names = {}",
"resp.json() class _PvPMixin(Client): \"\"\"PVP related methods for the POE API. CURRENTLY UNTESTED. HAS",
"types we pass to _get_json async def _get_list( # type: ignore self, model:",
"realm: query[\"realm\"] = realm.value return await self._get( path=\"league/{0}\", path_format_args=(league,), model=League, result_field=\"league\", query=query, )",
"-> \"Client\": \"\"\"Runs on entering `async with`.\"\"\" self._client = aiohttp.ClientSession(raise_for_status=True) return self async",
"-> List[League]: \"\"\"Get a list of all leagues based on filters.\"\"\" if league_type",
"a different # positional argument in the function. async with await self._client.get( \"{0}/{1}\".format(self._base_url,",
"path_with_no_args ] = await self._limiter.parse_headers(resp.headers) if resp.status != 200: raise ValueError( \"Invalid request:",
"raise exc_val return True # Type ignore is for args and kwargs, which",
"returns the data in this field from the request, rather than the request",
"async def __aenter__(self) -> \"Client\": \"\"\"Runs on entering `async with`.\"\"\" self._client = aiohttp.ClientSession(raise_for_status=True)",
"import TracebackType from typing import Callable, Dict, List, Optional, Type, TypeVar import aiohttp",
"\"\"\" async def list_leagues( # noqa: WPS211 self, realm: Optional[Realm] = None, league_type:",
"APIType. result_field: If present, returns the data in this field from the request,",
"function. async with await self._client.get( \"{0}/{1}\".format(self._base_url, path.format(*path_format_args)), **kwargs, # type: ignore ) as",
"_PvPMixin(Client): \"\"\"PVP related methods for the POE API. CURRENTLY UNTESTED. HAS NOT BEEN",
"args use the # same rate limiting. For example, /characters/moowiz and /characters/chris #",
"WPS215, error about too many base classes. We use multiple to better split",
"expected 200\".format( resp.status, ), ) return await resp.json() class _PvPMixin(Client): \"\"\"PVP related methods",
"not league: raise ValueError(\"league cannot be empty if league_type is league.\") # We",
"URL path to use. Appended to the POE API base URL. If certain",
"on id and account of token.\"\"\" return await self._get( path=\"character/{0}\", path_format_args=(name,), model=Character, result_field=\"character\",",
"self, filterid: str, ) -> ItemFilter: \"\"\"Get a ItemFilter based on id.\"\"\" return",
"for _ in range(len(path_format_args)))) policy_name = self._path_to_policy_names.get(path_with_no_args, \"\") kwargs = { \"headers\": {",
"in query.items() if query_val} return await self._get_list( path=\"pvp-match\", model=PvPMatch, result_field=\"matches\", query=query, ) async",
"from poe_client.rate_limiter import RateLimiter from poe_client.schemas.account import Account, Realm from poe_client.schemas.character import Character",
"path=\"item-filter/{0}\", path_format_args=(filterid,), model=ItemFilter, result_field=\"filter\", ) class _PublicStashMixin(Client): \"\"\"Public stash tab methods for the",
"None, ) -> None: \"\"\"Initialize a new PoE client. Args: user_agent: An OAuth",
"limiting policy names. # Generic paths are paths with no IDs or unique",
"based on id.\"\"\" path = \"stash/{0}/{1}\".format(league, stash_id) path_format_args = [league, stash_id] if substash_id:",
"await self._get_list( path=\"item-filter\", model=ItemFilter, result_field=\"filters\", ) async def get_item_filter( self, filterid: str, )",
"pvp matches based on filters.\"\"\" if match_type == PvPMatchType.season and not season: raise",
"Optional[List[str]] = None, query: Optional[Dict[str, str]] = None, ): \"\"\"Fetches data from the",
"this is required; not setting this value fetches stash tabs from the beginning",
"!= 200: raise ValueError( \"Invalid request: status code {0}, expected 200\".format( resp.status, ),",
"season: str = \"\", limit: int = 50, ) -> List[League]: \"\"\"Get a",
"= [league, stash_id] if substash_id: path += \"/{2}\" # noqa: WPS336 path_format_args.append(substash_id) return",
"= False # type: ignore # The types are ignored because for some",
"**kwargs) if result_field: assert isinstance(json_result, dict) # noqa: S101 json_result = json_result[result_field] assert",
"dict assignment. kwargs only has dicts as values, # but we're assigning booleans",
"# the variable return type class Client(object): \"\"\"Aiohttp class for interacting with the",
"isinstance(json_result, dict) # noqa: S101 if result_field: json_result = json_result[result_field] return model(**json_result) #",
"realm.value if realm else None, \"season\": season if season else None, \"league\": league",
"\"/character/\" is the equivalent \"generic\" path. _path_to_policy_names: Dict[str, str] def __init__( self, user_agent:",
"match: str, realm: Optional[Realm] = None, ) -> PvPMatchLadder: \"\"\"Get a pvp match",
"Optional[str] _base_url: URL = URL(\"https://api.pathofexile.com\") _client: aiohttp.ClientSession _user_agent: str _limiter: RateLimiter # Maps",
"and the values for those args should be passed into path_format_args. path_format_args: Values",
"NOT BEEN USED IN PRODUCTION. \"\"\" async def list_leagues( # noqa: WPS211 self,",
"path_format_args: Optional[List[str]] = None, query: Optional[Dict[str, str]] = None, ): \"\"\"Fetches data from",
"\"\"\"Get the ladder of a league based on id.\"\"\" query = {} if",
"self._limiter = RateLimiter() self._path_to_policy_names = {} async def __aenter__(self) -> \"Client\": \"\"\"Runs on",
"too many base classes. We use multiple to better split up # the",
"league: str, stash_id: str, substash_id: Optional[str], ) -> StashTab: \"\"\"Get a stash tab",
"format args. This presumes that # different requests to the same endpoints with",
"self._get_list( path=\"league\", model=League, result_field=\"leagues\", query=query, ) async def get_league( self, league: str, realm:",
"base URL. If certain parts of the path are non-static (account ID), those",
"__aenter__(self) -> \"Client\": \"\"\"Runs on entering `async with`.\"\"\" self._client = aiohttp.ClientSession(raise_for_status=True) return self",
"PoE API. This technically has support for every API GGG has exposed. None",
"several years in the past. Returns: A dict representing a public stash change.",
"the HTTP request gets made. query: An optional dict of query params to",
"Returns: The result, parsed into a list of the `model` type. \"\"\" json_result",
"List[StashTab]: \"\"\"Get all stash tabs belonging to token.\"\"\" return await self._get_list( path=\"stash/{0}\", path_format_args=(league,),",
"about too many base classes. We use multiple to better split up #",
"the API request, parsed as JSON. \"\"\" if not path_format_args: path_format_args = []",
"status code {0}, expected 200\".format( resp.status, ), ) return await resp.json() class _PvPMixin(Client):",
"CURRENTLY UNTESTED. HAS NOT BEEN USED IN PRODUCTION. \"\"\" async def get_public_stash_tabs( self,",
"as a list of APIType subclass. Args: model: The object which contains data",
"league_type is season.\") if match_type == PvPMatchType.league and not league: raise ValueError(\"league cannot",
"token to pass to the PoE API. If unset, no auth token is",
"the POE API base URL. If certain parts of the path are non-static",
"PRODUCTION. \"\"\" async def list_leagues( # noqa: WPS211 self, realm: Optional[Realm] = None,",
"kwargs[\"raise_for_status\"] = False # type: ignore # The types are ignored because for",
"import aiohttp from yarl import URL from poe_client.rate_limiter import RateLimiter from poe_client.schemas.account import",
"NOT BEEN USED IN PRODUCTION. \"\"\" async def get_item_filters( self, ) -> List[ItemFilter]:",
"json_result = await self._get_json(*args, **kwargs) if result_field: assert isinstance(json_result, dict) # noqa: S101",
"async def get_league_ladder( self, league: str, realm: Optional[Realm] = None, ) -> Ladder:",
"model=Character, result_field=\"characters\", ) async def get_character( self, name: str, ) -> Character: \"\"\"Get",
"path are non-static (account ID), those should be encoded as format args (\"{0}\")",
"an APIType subclass. Args: model: The object which contains data retrieved from the",
"await self._get( path=\"pvp-match/{0}\", path_format_args=(match,), model=PvPMatch, result_field=\"match\", query=query, ) async def get_pvp_match_ladder( self, match:",
"substash_id: Optional[str], ) -> StashTab: \"\"\"Get a stash tab based on id.\"\"\" path",
"type class Client(object): \"\"\"Aiohttp class for interacting with the Path of Exile API.\"\"\"",
"USED IN PRODUCTION. \"\"\" async def get_pvp_matches( self, realm: Optional[Realm] = None, match_type:",
"a get request and returns the data as an APIType subclass. Args: model:",
"which should be encoded in the path when the HTTP request gets made.",
"_get_json async def _get( # type: ignore self, model: Callable[..., Model], result_field: Optional[str]",
"query_val} return await self._get_list( path=\"pvp-match\", model=PvPMatch, result_field=\"matches\", query=query, ) async def get_pvp_match( self,",
"if next_change_id: query[\"id\"] = next_change_id return await self._get_json( path=\"public-stash-tabs\", query=query, ) # Ignore",
"class Client(object): \"\"\"Aiohttp class for interacting with the Path of Exile API.\"\"\" _token:",
"resp.status != 200: raise ValueError( \"Invalid request: status code {0}, expected 200\".format( resp.status,",
"path=\"pvp-match/{0}\", path_format_args=(match,), model=PvPMatch, result_field=\"match\", query=query, ) async def get_pvp_match_ladder( self, match: str, realm:",
"CURRENTLY UNTESTED. HAS NOT BEEN USED IN PRODUCTION. \"\"\" async def list_leagues( #",
"== PvPMatchType.league and not league: raise ValueError(\"league cannot be empty if league_type is",
"next_change_id: Optional[str] = None, ) -> PublicStash: \"\"\"Get the latest public stash tabs.",
"rate limiting policy name. if await self._limiter.get_semaphore(policy_name): # We ignore typing in the",
"_user_agent: str _limiter: RateLimiter # Maps \"generic\" paths to rate limiting policy names.",
"to pass to the PoE API. If unset, no auth token is used.",
"season else None, \"league\": league if league else None, } # Removed unset",
"(account ID), those should be encoded as format args (\"{0}\") in the path,",
"result_field=\"stashes\", ) async def get_stash( self, league: str, stash_id: str, substash_id: Optional[str], )",
"str, substash_id: Optional[str], ) -> StashTab: \"\"\"Get a stash tab based on id.\"\"\"",
"= True # type: ignore else: logging.info(\"BLOCKING\") kwargs[\"raise_for_status\"] = False # type: ignore",
"ValueError(\"league cannot be empty if league_type is league.\") # We construct this via",
"that the linter doesn't complain about # complexity. query = { \"type\": match_type.value",
"\"params\": query, } if self._token: headers = kwargs[\"headers\"] assert headers # noqa: S101",
"be encoded as format args (\"{0}\") in the path, and the values for",
"result_field=\"league\", query=query, ) async def get_league_ladder( self, league: str, realm: Optional[Realm] = None,",
"in the path, and the values for those args should be passed into",
"ItemFilter based on id.\"\"\" return await self._get( path=\"item-filter/{0}\", path_format_args=(filterid,), model=ItemFilter, result_field=\"filter\", ) class",
"and not season: raise ValueError(\"season cannot be empty if league_type is season.\") #",
"HAS NOT BEEN USED IN PRODUCTION. \"\"\" async def get_profile( self, ) ->",
"\"/character/moowiz\" has an account name, so it's not a base path. # \"/character/\"",
"the same endpoints with different specific args use the # same rate limiting.",
"{0}\".format(self._token) # We key the policy name off the path with no format",
"objitem in json_result] async def _get_json( self, path: str, path_format_args: Optional[List[str]] = None,",
"token: Authorization token to pass to the PoE API. If unset, no auth",
"None: \"\"\"Initialize a new PoE client. Args: user_agent: An OAuth user agent. Used",
"on id.\"\"\" query = {} if realm: query[\"realm\"] = realm.value return await self._get(",
"query: An optional dict of query params to add to the HTTP request.",
"None, \"offset\": str(offset) if offset else None, \"limit\": str(limit) if limit else None,",
"values, # but we're assigning booleans here. We can't set the typing inline",
"TypeVar import aiohttp from yarl import URL from poe_client.rate_limiter import RateLimiter from poe_client.schemas.account",
"async def get_pvp_matches( self, realm: Optional[Realm] = None, match_type: Optional[PvPMatchType] = None, season:",
"types we pass to _get_json async def _get( # type: ignore self, model:",
"\"\", limit: int = 50, ) -> List[League]: \"\"\"Get a list of all",
"stash tabs belonging to token.\"\"\" return await self._get_list( path=\"stash/{0}\", path_format_args=(league,), model=StashTab, result_field=\"stashes\", )",
"different requests to the same endpoints with different specific args use the #",
"a public stash change. \"\"\" query = {} if next_change_id: query[\"id\"] = next_change_id",
") -> Model: \"\"\"Make a get request and returns the data as an",
"Model: \"\"\"Make a get request and returns the data as an APIType subclass.",
"str = \"\", limit: int = 50, ) -> List[League]: \"\"\"Get a list",
"doesn't complain about # complexity. query = { \"type\": match_type.value if match_type else",
"ItemFilter: \"\"\"Get a ItemFilter based on id.\"\"\" return await self._get( path=\"item-filter/{0}\", path_format_args=(filterid,), model=ItemFilter,",
"to the PoE API. If unset, no auth token is used. \"\"\" self._token",
") class _FilterMixin(Client): \"\"\"Item Filter methods for the POE API. CURRENTLY UNTESTED. HAS",
"paths are paths with no IDs or unique numbers. # For example, \"/character/moowiz\"",
"set of stash tabs, starting at this change_id. While this is technically optional,",
"str _limiter: RateLimiter # Maps \"generic\" paths to rate limiting policy names. #",
"into path_format_args. path_format_args: Values which should be encoded in the path when the",
"Optional[Dict[str, str]] = None, ): \"\"\"Fetches data from the POE API. Args: path:",
"assert isinstance(json_result, dict) # noqa: S101 if result_field: json_result = json_result[result_field] return model(**json_result)",
"limit else None, } # Remove unset values query = {key: query_val for",
"some reason it can't understand # that kwargs isn't a positional arg and",
"model=League, result_field=\"leagues\", query=query, ) async def get_league( self, league: str, realm: Optional[Realm] =",
"path=\"public-stash-tabs\", query=query, ) # Ignore WPS215, error about too many base classes. We",
"path_format_args=(name,), model=Character, result_field=\"character\", ) async def get_stashes( self, league: str, ) -> List[StashTab]:",
"async def get_item_filter( self, filterid: str, ) -> ItemFilter: \"\"\"Get a ItemFilter based"
] |
[
"#Exercícios Numpy-15 #******************* import numpy as np arr=np.ones((10,10)) arr[1:-1,1:-1]=0 print(arr) print() arr_zero=np.zeros((8,8)) arr_zero=np.pad(arr_zero,pad_width=1,mode='constant',constant_values=1)",
"Numpy-15 #******************* import numpy as np arr=np.ones((10,10)) arr[1:-1,1:-1]=0 print(arr) print() arr_zero=np.zeros((8,8)) arr_zero=np.pad(arr_zero,pad_width=1,mode='constant',constant_values=1) print(arr_zero)"
] |
[
"struct # Get the stories as json response = requests.get(config['get-stories']) df = pd.DataFrame(response.json())",
"i in sp.ents if i.label_ == 'PER') people = [i.strip() for i in",
"change the ratio (from inMin to inMax) to an angle (from outMin to",
"struct.pack('i', remapped) response = client.publish(config['mqtt-topic'], x, qos=0, retain=True) print(\"MQTT message published:\", response.is_published()) ts",
"for compound nouns like François-Xavier: we use the “first” first name if firstname.count('-')",
"{}, angle: {}'.format(mean, remapped)) x = struct.pack('i', remapped) response = client.publish(config['mqtt-topic'], x, qos=0,",
"# let’s remap the ratio, from percentange to servomotor angle remapped = remap(mean,",
"x: \", \".join(x['female_names'])) df['unknown_names'] = df['score'].apply(lambda x: \", \".join(x['unknown_names'])) df['ratio'] = df['ratio'].apply(lambda x:",
"unknown_names = [] males = 0 females = 0 unknown = 0 doc",
"as pd import re from math import nan # config from define import",
"try: r = requests.post(_url, json=_json) except requests.exceptions.RequestException as e: # This is the",
"r payload = { 'records': df[['id', 'section', 'auteur_uni', 'dte_publication', 'titre', 'male', 'female', 'unknown',",
"x) def sendJson(_url, _json): r = False counter = 1 while counter <",
"i)] people = list(set(people)) for personne in people: ## TODO # here we",
"sp.ents if i.label_ == 'PER') people = [i.strip() for i in people] people",
"json=_json) except requests.exceptions.RequestException as e: # This is the correct syntax print ('Attempt',",
"and if we get a result, check the “gender” property, P21 firstname =",
"result, check the “gender” property, P21 firstname = personne.split()[0] # Dirty fix for",
"\", \".join(x['male_names'])) df['female_names'] = df['score'].apply(lambda x: \", \".join(x['female_names'])) df['unknown_names'] = df['score'].apply(lambda x: \",",
"ratio, from percentange to servomotor angle remapped = remap(mean, 0, 100, 12, 181)",
"def computeRatio(counts): if counts['total'] > 0: return counts['female'] / counts['total'] else: return nan",
"correct syntax print ('Attempt', counter, '>', e) if r == True: if r.status_code",
"female_names.append(personne) females += 1 elif result.find('male') >= 0: male_names.append(personne) males += 1 else:",
"inMax, outMin, outMax ): portion = (x-inMin)*(outMax-outMin)/(inMax-inMin) result = portion + outMin #",
"x = struct.pack('i', remapped) response = client.publish(config['mqtt-topic'], x, qos=0, retain=True) print(\"MQTT message published:\",",
"## TODO # here we could query wikidata # and if we get",
"get a result, check the “gender” property, P21 firstname = personne.split()[0] # Dirty",
"x: \", \".join(x['unknown_names'])) df['ratio'] = df['ratio'].apply(lambda x: 'NULL' if x != x else",
"# to send MQTT message import paho.mqtt.client as mqtt import struct # Get",
"nlp(ptext) for p in paragraphs: sp = nlp(p) people.extend('{}'.format(i) for i in sp.ents",
"= firstname.split('-')[0] result = d.get_gender(firstname) if result.find('female') >= 0: female_names.append(personne) females += 1",
"import config # NLP import spacy import gender_guesser.detector as gender # time import",
"countGenders: # searches for people names with spacy (as nlp) # count genders",
"# sp = nlp(ptext) for p in paragraphs: sp = nlp(p) people.extend('{}'.format(i) for",
"could query wikidata # and if we get a result, check the “gender”",
"'total': males + females, 'unknown': unknown, 'male_names': male_names, 'female_names': female_names, 'unknown_names': unknown_names} df['score']",
"# countGenders: # searches for people names with spacy (as nlp) # count",
"not re.search('Monsieur|Madame', i)] people = list(set(people)) for personne in people: ## TODO #",
"'html.parser') paragraphs = doc.find_all('p') paragraphs = [p.text for p in paragraphs] # or",
"!= x else x) def sendJson(_url, _json): r = False counter = 1",
"+= 1 elif result.find('male') >= 0: male_names.append(personne) males += 1 else: unknown_names.append(personne) unknown",
"): portion = (x-inMin)*(outMax-outMin)/(inMax-inMin) result = portion + outMin # add the new",
"response.is_published()) ts = datetime.datetime.now().strftime('%Y-%m-%dT%H:%M:%SZ') data = {'mean': mean, 'update': ts} print(data) ################ #",
"= df['score'].apply(lambda x: x['female']) df['unknown'] = df['score'].apply(lambda x: x['unknown']) df['id'] = df['guid'].apply(lambda x:",
"if row['auteur_int'] != '' else row['auteur_seul'], axis=1) df['male_names'] = df['score'].apply(lambda x: \", \".join(x['male_names']))",
"as json response = requests.get(config['get-stories']) df = pd.DataFrame(response.json()) nlp = spacy.load('fr') d =",
"x: \", \".join(x['male_names'])) df['female_names'] = df['score'].apply(lambda x: \", \".join(x['female_names'])) df['unknown_names'] = df['score'].apply(lambda x:",
"qos=0, retain=True) print(\"MQTT message published:\", response.is_published()) ts = datetime.datetime.now().strftime('%Y-%m-%dT%H:%M:%SZ') data = {'mean': mean,",
"df['id'] = df['guid'].apply(lambda x: int(x.split('/')[-1])) df['auteur_seul'] = df['auteur'].apply(lambda x: x.split(',')[0]) df['auteur_uni'] = df.apply(lambda",
"if x != x else x) def sendJson(_url, _json): r = False counter",
"print ('Attempt', counter, '>', e) if r == True: if r.status_code == 200:",
"df = pd.DataFrame(response.json()) nlp = spacy.load('fr') d = gender.Detector() # countGenders: # searches",
"as gender # time import datetime import time # to send MQTT message",
"\"{0:.2f}%\".format(x*100) if x == x else 'n/a') ################ # MQTT # # on",
"people = list(set(people)) for personne in people: ## TODO # here we could",
"== True: if r.status_code == 200: print('JSON sent at attempt', counter) break else:",
"import time # to send MQTT message import paho.mqtt.client as mqtt import struct",
"1 while counter < 4: try: r = requests.post(_url, json=_json) except requests.exceptions.RequestException as",
"database # df['male'] = df['score'].apply(lambda x: x['male']) df['female'] = df['score'].apply(lambda x: x['female']) df['unknown']",
"to send MQTT message import paho.mqtt.client as mqtt import struct # Get the",
"# ptext = \"\\n\".join(paragraphs) # sp = nlp(ptext) for p in paragraphs: sp",
"pd.DataFrame(response.json()) nlp = spacy.load('fr') d = gender.Detector() # countGenders: # searches for people",
"import gender_guesser.detector as gender # time import datetime import time # to send",
"data? def countGenders(text): people = [] male_names = [] female_names = [] unknown_names",
"print('JSON sent at attempt', counter) break else: print('Attempt', counter, '>', r.status_code) counter +=",
"# or everything at once: # ptext = \"\\n\".join(paragraphs) # sp = nlp(ptext)",
"x: x['male']) df['female'] = df['score'].apply(lambda x: x['female']) df['unknown'] = df['score'].apply(lambda x: x['unknown']) df['id']",
"if we get a result, check the “gender” property, P21 firstname = personne.split()[0]",
"inMin to inMax) to an angle (from outMin to outMax) def remap( x,",
"requests.post(_url, json=_json) except requests.exceptions.RequestException as e: # This is the correct syntax print",
"+= 1 return r payload = { 'records': df[['id', 'section', 'auteur_uni', 'dte_publication', 'titre',",
"paragraphs = [p.text for p in paragraphs] # or everything at once: #",
"= df['score'].apply(lambda x: \", \".join(x['unknown_names'])) df['ratio'] = df['ratio'].apply(lambda x: 'NULL' if x !=",
"df['score'].apply(lambda x: \", \".join(x['male_names'])) df['female_names'] = df['score'].apply(lambda x: \", \".join(x['female_names'])) df['unknown_names'] = df['score'].apply(lambda",
"names with spacy (as nlp) # count genders with gender.Detector (as d) #",
"x['male']) df['female'] = df['score'].apply(lambda x: x['female']) df['unknown'] = df['score'].apply(lambda x: x['unknown']) df['id'] =",
"e: # This is the correct syntax print ('Attempt', counter, '>', e) if",
"# time import datetime import time # to send MQTT message import paho.mqtt.client",
"= [] male_names = [] female_names = [] unknown_names = [] males =",
"df['score'].apply(lambda x: x['female']) df['unknown'] = df['score'].apply(lambda x: x['unknown']) df['id'] = df['guid'].apply(lambda x: int(x.split('/')[-1]))",
"re.search('Monsieur|Madame', i)] people = list(set(people)) for personne in people: ## TODO # here",
"return counts['female'] / counts['total'] else: return nan df['ratio'] = df['score'].apply(computeRatio) df['percentage'] = df['ratio'].apply(lambda",
"def remap( x, inMin, inMax, outMin, outMax ): portion = (x-inMin)*(outMax-outMin)/(inMax-inMin) result =",
"if r.status_code == 200: print('JSON sent at attempt', counter) break else: print('Attempt', counter,",
"{ 'records': df[['id', 'section', 'auteur_uni', 'dte_publication', 'titre', 'male', 'female', 'unknown', 'male_names', 'female_names', 'unknown_names',",
"df['percentage'] = df['ratio'].apply(lambda x: \"{0:.2f}%\".format(x*100) if x == x else 'n/a') ################ #",
"male_names = [] female_names = [] unknown_names = [] males = 0 females",
"people = [i for i in people if re.search('[A-Z].*[A-Z]', i)] people = [i",
"= [i for i in people if not re.search('Monsieur|Madame', i)] people = list(set(people))",
"import pandas as pd import re from math import nan # config from",
"males += 1 else: unknown_names.append(personne) unknown += 1 return {'male': males, 'female': females,",
"# Get the stories as json response = requests.get(config['get-stories']) df = pd.DataFrame(response.json()) nlp",
"# NLP import spacy import gender_guesser.detector as gender # time import datetime import",
"Get the stories as json response = requests.get(config['get-stories']) df = pd.DataFrame(response.json()) nlp =",
"row['auteur_seul'], axis=1) df['male_names'] = df['score'].apply(lambda x: \", \".join(x['male_names'])) df['female_names'] = df['score'].apply(lambda x: \",",
"print(\"MQTT message published:\", response.is_published()) ts = datetime.datetime.now().strftime('%Y-%m-%dT%H:%M:%SZ') data = {'mean': mean, 'update': ts}",
"df[['id', 'section', 'auteur_uni', 'dte_publication', 'titre', 'male', 'female', 'unknown', 'male_names', 'female_names', 'unknown_names', 'ratio']].to_dict(orient='records'), }",
"once: # ptext = \"\\n\".join(paragraphs) # sp = nlp(ptext) for p in paragraphs:",
"mqtt.Client(\"xoxox\") client.connect(config['mqtt-broker'], port=1883) # change the ratio (from inMin to inMax) to an",
"males = 0 females = 0 unknown = 0 doc = BeautifulSoup(text, 'html.parser')",
"retain=True) print(\"MQTT message published:\", response.is_published()) ts = datetime.datetime.now().strftime('%Y-%m-%dT%H:%M:%SZ') data = {'mean': mean, 'update':",
"people = [i for i in people if not re.search('Monsieur|Madame', i)] people =",
"prend les 25 derniers mean = df[25:]['ratio'].mean() * 100 client = mqtt.Client(\"xoxox\") client.connect(config['mqtt-broker'],",
"i in people if not re.search('Monsieur|Madame', i)] people = list(set(people)) for personne in",
"> 0: return counts['female'] / counts['total'] else: return nan df['ratio'] = df['score'].apply(computeRatio) df['percentage']",
"as e: # This is the correct syntax print ('Attempt', counter, '>', e)",
"re from math import nan # config from define import config # NLP",
"send MQTT message import paho.mqtt.client as mqtt import struct # Get the stories",
"result = d.get_gender(firstname) if result.find('female') >= 0: female_names.append(personne) females += 1 elif result.find('male')",
"p in paragraphs] # or everything at once: # ptext = \"\\n\".join(paragraphs) #",
"countGenders(text): people = [] male_names = [] female_names = [] unknown_names = []",
"'male_names', 'female_names', 'unknown_names', 'ratio']].to_dict(orient='records'), } response = sendJson(config['send-sql-stories'], payload) print('Resultat SQLite:', response.text) print('End')",
"# TODO get wikidata gender data? def countGenders(text): people = [] male_names =",
"people if re.search('[A-Z].*[A-Z]', i)] people = [i for i in people if not",
"in paragraphs: sp = nlp(p) people.extend('{}'.format(i) for i in sp.ents if i.label_ ==",
"'female_names': female_names, 'unknown_names': unknown_names} df['score'] = df['contenu'].apply(countGenders) def computeRatio(counts): if counts['total'] > 0:",
"return nan df['ratio'] = df['score'].apply(computeRatio) df['percentage'] = df['ratio'].apply(lambda x: \"{0:.2f}%\".format(x*100) if x ==",
"doc.find_all('p') paragraphs = [p.text for p in paragraphs] # or everything at once:",
"wikidata gender data? def countGenders(text): people = [] male_names = [] female_names =",
"derniers mean = df[25:]['ratio'].mean() * 100 client = mqtt.Client(\"xoxox\") client.connect(config['mqtt-broker'], port=1883) # change",
"return int(round(result)) # let’s remap the ratio, from percentange to servomotor angle remapped",
"message import paho.mqtt.client as mqtt import struct # Get the stories as json",
"for i in people] people = [i for i in people if re.search('[A-Z].*[A-Z]',",
"people.extend('{}'.format(i) for i in sp.ents if i.label_ == 'PER') people = [i.strip() for",
"= [] males = 0 females = 0 unknown = 0 doc =",
"minimal value return int(round(result)) # let’s remap the ratio, from percentange to servomotor",
"counter, '>', e) if r == True: if r.status_code == 200: print('JSON sent",
"for i in sp.ents if i.label_ == 'PER') people = [i.strip() for i",
"181) print('Mean: {}, angle: {}'.format(mean, remapped)) x = struct.pack('i', remapped) response = client.publish(config['mqtt-topic'],",
"df[25:]['ratio'].mean() * 100 client = mqtt.Client(\"xoxox\") client.connect(config['mqtt-broker'], port=1883) # change the ratio (from",
"bs4 import BeautifulSoup import pandas as pd import re from math import nan",
"for p in paragraphs] # or everything at once: # ptext = \"\\n\".join(paragraphs)",
"row['auteur_int'] if row['auteur_int'] != '' else row['auteur_seul'], axis=1) df['male_names'] = df['score'].apply(lambda x: \",",
"0 unknown = 0 doc = BeautifulSoup(text, 'html.parser') paragraphs = doc.find_all('p') paragraphs =",
"\", \".join(x['unknown_names'])) df['ratio'] = df['ratio'].apply(lambda x: 'NULL' if x != x else x)",
"[i for i in people if re.search('[A-Z].*[A-Z]', i)] people = [i for i",
"if firstname.count('-') > 0: firstname = firstname.split('-')[0] result = d.get_gender(firstname) if result.find('female') >=",
"> 0: firstname = firstname.split('-')[0] result = d.get_gender(firstname) if result.find('female') >= 0: female_names.append(personne)",
"'n/a') ################ # MQTT # # on prend les 25 derniers mean =",
"\".join(x['unknown_names'])) df['ratio'] = df['ratio'].apply(lambda x: 'NULL' if x != x else x) def",
"gender.Detector() # countGenders: # searches for people names with spacy (as nlp) #",
"x else 'n/a') ################ # MQTT # # on prend les 25 derniers",
"unknown = 0 doc = BeautifulSoup(text, 'html.parser') paragraphs = doc.find_all('p') paragraphs = [p.text",
"payload = { 'records': df[['id', 'section', 'auteur_uni', 'dte_publication', 'titre', 'male', 'female', 'unknown', 'male_names',",
"= {'mean': mean, 'update': ts} print(data) ################ # Send data to SQLITE database",
"females, 'total': males + females, 'unknown': unknown, 'male_names': male_names, 'female_names': female_names, 'unknown_names': unknown_names}",
"the ratio (from inMin to inMax) to an angle (from outMin to outMax)",
"'records': df[['id', 'section', 'auteur_uni', 'dte_publication', 'titre', 'male', 'female', 'unknown', 'male_names', 'female_names', 'unknown_names', 'ratio']].to_dict(orient='records'),",
"0: male_names.append(personne) males += 1 else: unknown_names.append(personne) unknown += 1 return {'male': males,",
"'unknown', 'male_names', 'female_names', 'unknown_names', 'ratio']].to_dict(orient='records'), } response = sendJson(config['send-sql-stories'], payload) print('Resultat SQLite:', response.text)",
"= [] female_names = [] unknown_names = [] males = 0 females =",
"here we could query wikidata # and if we get a result, check",
"100 client = mqtt.Client(\"xoxox\") client.connect(config['mqtt-broker'], port=1883) # change the ratio (from inMin to",
"df['auteur'].apply(lambda x: x.split(',')[0]) df['auteur_uni'] = df.apply(lambda row: row['auteur_int'] if row['auteur_int'] != '' else",
"a result, check the “gender” property, P21 firstname = personne.split()[0] # Dirty fix",
"to an angle (from outMin to outMax) def remap( x, inMin, inMax, outMin,",
"(as d) # TODO get wikidata gender data? def countGenders(text): people = []",
"df['ratio'] = df['ratio'].apply(lambda x: 'NULL' if x != x else x) def sendJson(_url,",
"requests from bs4 import BeautifulSoup import pandas as pd import re from math",
"name if firstname.count('-') > 0: firstname = firstname.split('-')[0] result = d.get_gender(firstname) if result.find('female')",
"################ # Send data to SQLITE database # df['male'] = df['score'].apply(lambda x: x['male'])",
"for personne in people: ## TODO # here we could query wikidata #",
"1 return {'male': males, 'female': females, 'total': males + females, 'unknown': unknown, 'male_names':",
"datetime.datetime.now().strftime('%Y-%m-%dT%H:%M:%SZ') data = {'mean': mean, 'update': ts} print(data) ################ # Send data to",
"df['auteur_seul'] = df['auteur'].apply(lambda x: x.split(',')[0]) df['auteur_uni'] = df.apply(lambda row: row['auteur_int'] if row['auteur_int'] !=",
"= df['contenu'].apply(countGenders) def computeRatio(counts): if counts['total'] > 0: return counts['female'] / counts['total'] else:",
"r == True: if r.status_code == 200: print('JSON sent at attempt', counter) break",
"= [i.strip() for i in people] people = [i for i in people",
"'NULL' if x != x else x) def sendJson(_url, _json): r = False",
"les 25 derniers mean = df[25:]['ratio'].mean() * 100 client = mqtt.Client(\"xoxox\") client.connect(config['mqtt-broker'], port=1883)",
"time import datetime import time # to send MQTT message import paho.mqtt.client as",
"= spacy.load('fr') d = gender.Detector() # countGenders: # searches for people names with",
"'auteur_uni', 'dte_publication', 'titre', 'male', 'female', 'unknown', 'male_names', 'female_names', 'unknown_names', 'ratio']].to_dict(orient='records'), } response =",
"Dirty fix for compound nouns like François-Xavier: we use the “first” first name",
"data to SQLITE database # df['male'] = df['score'].apply(lambda x: x['male']) df['female'] = df['score'].apply(lambda",
"= [] unknown_names = [] males = 0 females = 0 unknown =",
"from define import config # NLP import spacy import gender_guesser.detector as gender #",
"in people: ## TODO # here we could query wikidata # and if",
"firstname = personne.split()[0] # Dirty fix for compound nouns like François-Xavier: we use",
"# Send data to SQLITE database # df['male'] = df['score'].apply(lambda x: x['male']) df['female']",
"else x) def sendJson(_url, _json): r = False counter = 1 while counter",
"remap the ratio, from percentange to servomotor angle remapped = remap(mean, 0, 100,",
"= struct.pack('i', remapped) response = client.publish(config['mqtt-topic'], x, qos=0, retain=True) print(\"MQTT message published:\", response.is_published())",
"the ratio, from percentange to servomotor angle remapped = remap(mean, 0, 100, 12,",
"= df['auteur'].apply(lambda x: x.split(',')[0]) df['auteur_uni'] = df.apply(lambda row: row['auteur_int'] if row['auteur_int'] != ''",
"message published:\", response.is_published()) ts = datetime.datetime.now().strftime('%Y-%m-%dT%H:%M:%SZ') data = {'mean': mean, 'update': ts} print(data)",
"data = {'mean': mean, 'update': ts} print(data) ################ # Send data to SQLITE",
"the new minimal value return int(round(result)) # let’s remap the ratio, from percentange",
"else: unknown_names.append(personne) unknown += 1 return {'male': males, 'female': females, 'total': males +",
"mean, 'update': ts} print(data) ################ # Send data to SQLITE database # df['male']",
"# count genders with gender.Detector (as d) # TODO get wikidata gender data?",
"= [p.text for p in paragraphs] # or everything at once: # ptext",
"import paho.mqtt.client as mqtt import struct # Get the stories as json response",
"from bs4 import BeautifulSoup import pandas as pd import re from math import",
"for i in people if re.search('[A-Z].*[A-Z]', i)] people = [i for i in",
"<filename>parser-stories.py # coding: utf-8 import requests from bs4 import BeautifulSoup import pandas as",
"for p in paragraphs: sp = nlp(p) people.extend('{}'.format(i) for i in sp.ents if",
"fix for compound nouns like François-Xavier: we use the “first” first name if",
"MQTT message import paho.mqtt.client as mqtt import struct # Get the stories as",
"= df['score'].apply(lambda x: \", \".join(x['female_names'])) df['unknown_names'] = df['score'].apply(lambda x: \", \".join(x['unknown_names'])) df['ratio'] =",
"= nlp(ptext) for p in paragraphs: sp = nlp(p) people.extend('{}'.format(i) for i in",
"else 'n/a') ################ # MQTT # # on prend les 25 derniers mean",
"12, 181) print('Mean: {}, angle: {}'.format(mean, remapped)) x = struct.pack('i', remapped) response =",
"spacy import gender_guesser.detector as gender # time import datetime import time # to",
"sp = nlp(ptext) for p in paragraphs: sp = nlp(p) people.extend('{}'.format(i) for i",
"ts} print(data) ################ # Send data to SQLITE database # df['male'] = df['score'].apply(lambda",
"= \"\\n\".join(paragraphs) # sp = nlp(ptext) for p in paragraphs: sp = nlp(p)",
"remapped)) x = struct.pack('i', remapped) response = client.publish(config['mqtt-topic'], x, qos=0, retain=True) print(\"MQTT message",
"counter, '>', r.status_code) counter += 1 return r payload = { 'records': df[['id',",
"percentange to servomotor angle remapped = remap(mean, 0, 100, 12, 181) print('Mean: {},",
"mqtt import struct # Get the stories as json response = requests.get(config['get-stories']) df",
"\", \".join(x['female_names'])) df['unknown_names'] = df['score'].apply(lambda x: \", \".join(x['unknown_names'])) df['ratio'] = df['ratio'].apply(lambda x: 'NULL'",
"i in people] people = [i for i in people if re.search('[A-Z].*[A-Z]', i)]",
"= portion + outMin # add the new minimal value return int(round(result)) #",
"nan # config from define import config # NLP import spacy import gender_guesser.detector",
"0 doc = BeautifulSoup(text, 'html.parser') paragraphs = doc.find_all('p') paragraphs = [p.text for p",
"df['ratio'].apply(lambda x: \"{0:.2f}%\".format(x*100) if x == x else 'n/a') ################ # MQTT #",
"!= '' else row['auteur_seul'], axis=1) df['male_names'] = df['score'].apply(lambda x: \", \".join(x['male_names'])) df['female_names'] =",
"personne in people: ## TODO # here we could query wikidata # and",
"= BeautifulSoup(text, 'html.parser') paragraphs = doc.find_all('p') paragraphs = [p.text for p in paragraphs]",
"\"\\n\".join(paragraphs) # sp = nlp(ptext) for p in paragraphs: sp = nlp(p) people.extend('{}'.format(i)",
"'>', r.status_code) counter += 1 return r payload = { 'records': df[['id', 'section',",
"remapped = remap(mean, 0, 100, 12, 181) print('Mean: {}, angle: {}'.format(mean, remapped)) x",
"the correct syntax print ('Attempt', counter, '>', e) if r == True: if",
"# coding: utf-8 import requests from bs4 import BeautifulSoup import pandas as pd",
"Send data to SQLITE database # df['male'] = df['score'].apply(lambda x: x['male']) df['female'] =",
"paragraphs] # or everything at once: # ptext = \"\\n\".join(paragraphs) # sp =",
"TODO # here we could query wikidata # and if we get a",
"'>', e) if r == True: if r.status_code == 200: print('JSON sent at",
"paho.mqtt.client as mqtt import struct # Get the stories as json response =",
"paragraphs: sp = nlp(p) people.extend('{}'.format(i) for i in sp.ents if i.label_ == 'PER')",
"df['score'].apply(lambda x: \", \".join(x['female_names'])) df['unknown_names'] = df['score'].apply(lambda x: \", \".join(x['unknown_names'])) df['ratio'] = df['ratio'].apply(lambda",
"define import config # NLP import spacy import gender_guesser.detector as gender # time",
"x: 'NULL' if x != x else x) def sendJson(_url, _json): r =",
"while counter < 4: try: r = requests.post(_url, json=_json) except requests.exceptions.RequestException as e:",
"= client.publish(config['mqtt-topic'], x, qos=0, retain=True) print(\"MQTT message published:\", response.is_published()) ts = datetime.datetime.now().strftime('%Y-%m-%dT%H:%M:%SZ') data",
"= df['score'].apply(lambda x: \", \".join(x['male_names'])) df['female_names'] = df['score'].apply(lambda x: \", \".join(x['female_names'])) df['unknown_names'] =",
"port=1883) # change the ratio (from inMin to inMax) to an angle (from",
"# and if we get a result, check the “gender” property, P21 firstname",
">= 0: female_names.append(personne) females += 1 elif result.find('male') >= 0: male_names.append(personne) males +=",
"if not re.search('Monsieur|Madame', i)] people = list(set(people)) for personne in people: ## TODO",
"'male_names': male_names, 'female_names': female_names, 'unknown_names': unknown_names} df['score'] = df['contenu'].apply(countGenders) def computeRatio(counts): if counts['total']",
"_json): r = False counter = 1 while counter < 4: try: r",
"math import nan # config from define import config # NLP import spacy",
"angle (from outMin to outMax) def remap( x, inMin, inMax, outMin, outMax ):",
"P21 firstname = personne.split()[0] # Dirty fix for compound nouns like François-Xavier: we",
"re.search('[A-Z].*[A-Z]', i)] people = [i for i in people if not re.search('Monsieur|Madame', i)]",
"# change the ratio (from inMin to inMax) to an angle (from outMin",
"ts = datetime.datetime.now().strftime('%Y-%m-%dT%H:%M:%SZ') data = {'mean': mean, 'update': ts} print(data) ################ # Send",
"TODO get wikidata gender data? def countGenders(text): people = [] male_names = []",
"result = portion + outMin # add the new minimal value return int(round(result))",
"200: print('JSON sent at attempt', counter) break else: print('Attempt', counter, '>', r.status_code) counter",
"[] female_names = [] unknown_names = [] males = 0 females = 0",
"MQTT # # on prend les 25 derniers mean = df[25:]['ratio'].mean() * 100",
"“first” first name if firstname.count('-') > 0: firstname = firstname.split('-')[0] result = d.get_gender(firstname)",
"nlp(p) people.extend('{}'.format(i) for i in sp.ents if i.label_ == 'PER') people = [i.strip()",
"(x-inMin)*(outMax-outMin)/(inMax-inMin) result = portion + outMin # add the new minimal value return",
"female_names, 'unknown_names': unknown_names} df['score'] = df['contenu'].apply(countGenders) def computeRatio(counts): if counts['total'] > 0: return",
"people = [] male_names = [] female_names = [] unknown_names = [] males",
"requests.exceptions.RequestException as e: # This is the correct syntax print ('Attempt', counter, '>',",
"gender data? def countGenders(text): people = [] male_names = [] female_names = []",
"i in people if re.search('[A-Z].*[A-Z]', i)] people = [i for i in people",
"François-Xavier: we use the “first” first name if firstname.count('-') > 0: firstname =",
"if counts['total'] > 0: return counts['female'] / counts['total'] else: return nan df['ratio'] =",
"new minimal value return int(round(result)) # let’s remap the ratio, from percentange to",
"1 return r payload = { 'records': df[['id', 'section', 'auteur_uni', 'dte_publication', 'titre', 'male',",
"import nan # config from define import config # NLP import spacy import",
"in people if not re.search('Monsieur|Madame', i)] people = list(set(people)) for personne in people:",
"# on prend les 25 derniers mean = df[25:]['ratio'].mean() * 100 client =",
"'titre', 'male', 'female', 'unknown', 'male_names', 'female_names', 'unknown_names', 'ratio']].to_dict(orient='records'), } response = sendJson(config['send-sql-stories'], payload)",
"female_names = [] unknown_names = [] males = 0 females = 0 unknown",
"everything at once: # ptext = \"\\n\".join(paragraphs) # sp = nlp(ptext) for p",
"[i.strip() for i in people] people = [i for i in people if",
"personne.split()[0] # Dirty fix for compound nouns like François-Xavier: we use the “first”",
"coding: utf-8 import requests from bs4 import BeautifulSoup import pandas as pd import",
"BeautifulSoup import pandas as pd import re from math import nan # config",
"remap( x, inMin, inMax, outMin, outMax ): portion = (x-inMin)*(outMax-outMin)/(inMax-inMin) result = portion",
"'dte_publication', 'titre', 'male', 'female', 'unknown', 'male_names', 'female_names', 'unknown_names', 'ratio']].to_dict(orient='records'), } response = sendJson(config['send-sql-stories'],",
"import re from math import nan # config from define import config #",
"the stories as json response = requests.get(config['get-stories']) df = pd.DataFrame(response.json()) nlp = spacy.load('fr')",
"1 elif result.find('male') >= 0: male_names.append(personne) males += 1 else: unknown_names.append(personne) unknown +=",
"df['score'] = df['contenu'].apply(countGenders) def computeRatio(counts): if counts['total'] > 0: return counts['female'] / counts['total']",
"inMax) to an angle (from outMin to outMax) def remap( x, inMin, inMax,",
"to inMax) to an angle (from outMin to outMax) def remap( x, inMin,",
"angle remapped = remap(mean, 0, 100, 12, 181) print('Mean: {}, angle: {}'.format(mean, remapped))",
"response = client.publish(config['mqtt-topic'], x, qos=0, retain=True) print(\"MQTT message published:\", response.is_published()) ts = datetime.datetime.now().strftime('%Y-%m-%dT%H:%M:%SZ')",
"client.publish(config['mqtt-topic'], x, qos=0, retain=True) print(\"MQTT message published:\", response.is_published()) ts = datetime.datetime.now().strftime('%Y-%m-%dT%H:%M:%SZ') data =",
"datetime import time # to send MQTT message import paho.mqtt.client as mqtt import",
"break else: print('Attempt', counter, '>', r.status_code) counter += 1 return r payload =",
"0: firstname = firstname.split('-')[0] result = d.get_gender(firstname) if result.find('female') >= 0: female_names.append(personne) females",
"('Attempt', counter, '>', e) if r == True: if r.status_code == 200: print('JSON",
"# config from define import config # NLP import spacy import gender_guesser.detector as",
"import BeautifulSoup import pandas as pd import re from math import nan #",
"'PER') people = [i.strip() for i in people] people = [i for i",
"servomotor angle remapped = remap(mean, 0, 100, 12, 181) print('Mean: {}, angle: {}'.format(mean,",
"= False counter = 1 while counter < 4: try: r = requests.post(_url,",
"25 derniers mean = df[25:]['ratio'].mean() * 100 client = mqtt.Client(\"xoxox\") client.connect(config['mqtt-broker'], port=1883) #",
"axis=1) df['male_names'] = df['score'].apply(lambda x: \", \".join(x['male_names'])) df['female_names'] = df['score'].apply(lambda x: \", \".join(x['female_names']))",
"time # to send MQTT message import paho.mqtt.client as mqtt import struct #",
"'male', 'female', 'unknown', 'male_names', 'female_names', 'unknown_names', 'ratio']].to_dict(orient='records'), } response = sendJson(config['send-sql-stories'], payload) print('Resultat",
"we could query wikidata # and if we get a result, check the",
"NLP import spacy import gender_guesser.detector as gender # time import datetime import time",
"= d.get_gender(firstname) if result.find('female') >= 0: female_names.append(personne) females += 1 elif result.find('male') >=",
"This is the correct syntax print ('Attempt', counter, '>', e) if r ==",
"firstname = firstname.split('-')[0] result = d.get_gender(firstname) if result.find('female') >= 0: female_names.append(personne) females +=",
"attempt', counter) break else: print('Attempt', counter, '>', r.status_code) counter += 1 return r",
"# MQTT # # on prend les 25 derniers mean = df[25:]['ratio'].mean() *",
"= df['score'].apply(computeRatio) df['percentage'] = df['ratio'].apply(lambda x: \"{0:.2f}%\".format(x*100) if x == x else 'n/a')",
"stories as json response = requests.get(config['get-stories']) df = pd.DataFrame(response.json()) nlp = spacy.load('fr') d",
"portion = (x-inMin)*(outMax-outMin)/(inMax-inMin) result = portion + outMin # add the new minimal",
"= 0 females = 0 unknown = 0 doc = BeautifulSoup(text, 'html.parser') paragraphs",
"client = mqtt.Client(\"xoxox\") client.connect(config['mqtt-broker'], port=1883) # change the ratio (from inMin to inMax)",
"print('Mean: {}, angle: {}'.format(mean, remapped)) x = struct.pack('i', remapped) response = client.publish(config['mqtt-topic'], x,",
"“gender” property, P21 firstname = personne.split()[0] # Dirty fix for compound nouns like",
"def countGenders(text): people = [] male_names = [] female_names = [] unknown_names =",
"= df.apply(lambda row: row['auteur_int'] if row['auteur_int'] != '' else row['auteur_seul'], axis=1) df['male_names'] =",
"+ outMin # add the new minimal value return int(round(result)) # let’s remap",
"else: return nan df['ratio'] = df['score'].apply(computeRatio) df['percentage'] = df['ratio'].apply(lambda x: \"{0:.2f}%\".format(x*100) if x",
"females = 0 unknown = 0 doc = BeautifulSoup(text, 'html.parser') paragraphs = doc.find_all('p')",
"def sendJson(_url, _json): r = False counter = 1 while counter < 4:",
"= list(set(people)) for personne in people: ## TODO # here we could query",
"as mqtt import struct # Get the stories as json response = requests.get(config['get-stories'])",
"x.split(',')[0]) df['auteur_uni'] = df.apply(lambda row: row['auteur_int'] if row['auteur_int'] != '' else row['auteur_seul'], axis=1)",
"= (x-inMin)*(outMax-outMin)/(inMax-inMin) result = portion + outMin # add the new minimal value",
"print(data) ################ # Send data to SQLITE database # df['male'] = df['score'].apply(lambda x:",
"requests.get(config['get-stories']) df = pd.DataFrame(response.json()) nlp = spacy.load('fr') d = gender.Detector() # countGenders: #",
"x: \"{0:.2f}%\".format(x*100) if x == x else 'n/a') ################ # MQTT # #",
"x, inMin, inMax, outMin, outMax ): portion = (x-inMin)*(outMax-outMin)/(inMax-inMin) result = portion +",
"doc = BeautifulSoup(text, 'html.parser') paragraphs = doc.find_all('p') paragraphs = [p.text for p in",
"firstname.count('-') > 0: firstname = firstname.split('-')[0] result = d.get_gender(firstname) if result.find('female') >= 0:",
"get wikidata gender data? def countGenders(text): people = [] male_names = [] female_names",
"people: ## TODO # here we could query wikidata # and if we",
"= 1 while counter < 4: try: r = requests.post(_url, json=_json) except requests.exceptions.RequestException",
"'female': females, 'total': males + females, 'unknown': unknown, 'male_names': male_names, 'female_names': female_names, 'unknown_names':",
"for i in people if not re.search('Monsieur|Madame', i)] people = list(set(people)) for personne",
"r.status_code) counter += 1 return r payload = { 'records': df[['id', 'section', 'auteur_uni',",
"angle: {}'.format(mean, remapped)) x = struct.pack('i', remapped) response = client.publish(config['mqtt-topic'], x, qos=0, retain=True)",
"{'male': males, 'female': females, 'total': males + females, 'unknown': unknown, 'male_names': male_names, 'female_names':",
"firstname.split('-')[0] result = d.get_gender(firstname) if result.find('female') >= 0: female_names.append(personne) females += 1 elif",
"x: x['female']) df['unknown'] = df['score'].apply(lambda x: x['unknown']) df['id'] = df['guid'].apply(lambda x: int(x.split('/')[-1])) df['auteur_seul']",
"df['unknown_names'] = df['score'].apply(lambda x: \", \".join(x['unknown_names'])) df['ratio'] = df['ratio'].apply(lambda x: 'NULL' if x",
"in paragraphs] # or everything at once: # ptext = \"\\n\".join(paragraphs) # sp",
"= df[25:]['ratio'].mean() * 100 client = mqtt.Client(\"xoxox\") client.connect(config['mqtt-broker'], port=1883) # change the ratio",
"outMin # add the new minimal value return int(round(result)) # let’s remap the",
"genders with gender.Detector (as d) # TODO get wikidata gender data? def countGenders(text):",
"i.label_ == 'PER') people = [i.strip() for i in people] people = [i",
"import requests from bs4 import BeautifulSoup import pandas as pd import re from",
"value return int(round(result)) # let’s remap the ratio, from percentange to servomotor angle",
"unknown_names.append(personne) unknown += 1 return {'male': males, 'female': females, 'total': males + females,",
"counts['total'] > 0: return counts['female'] / counts['total'] else: return nan df['ratio'] = df['score'].apply(computeRatio)",
"unknown, 'male_names': male_names, 'female_names': female_names, 'unknown_names': unknown_names} df['score'] = df['contenu'].apply(countGenders) def computeRatio(counts): if",
"[p.text for p in paragraphs] # or everything at once: # ptext =",
"################ # MQTT # # on prend les 25 derniers mean = df[25:]['ratio'].mean()",
"(from outMin to outMax) def remap( x, inMin, inMax, outMin, outMax ): portion",
"result.find('female') >= 0: female_names.append(personne) females += 1 elif result.find('male') >= 0: male_names.append(personne) males",
"[] male_names = [] female_names = [] unknown_names = [] males = 0",
"[] unknown_names = [] males = 0 females = 0 unknown = 0",
"counts['total'] else: return nan df['ratio'] = df['score'].apply(computeRatio) df['percentage'] = df['ratio'].apply(lambda x: \"{0:.2f}%\".format(x*100) if",
"'section', 'auteur_uni', 'dte_publication', 'titre', 'male', 'female', 'unknown', 'male_names', 'female_names', 'unknown_names', 'ratio']].to_dict(orient='records'), } response",
"outMin to outMax) def remap( x, inMin, inMax, outMin, outMax ): portion =",
"= df['ratio'].apply(lambda x: 'NULL' if x != x else x) def sendJson(_url, _json):",
"compound nouns like François-Xavier: we use the “first” first name if firstname.count('-') >",
"df['score'].apply(lambda x: \", \".join(x['unknown_names'])) df['ratio'] = df['ratio'].apply(lambda x: 'NULL' if x != x",
"an angle (from outMin to outMax) def remap( x, inMin, inMax, outMin, outMax",
"females, 'unknown': unknown, 'male_names': male_names, 'female_names': female_names, 'unknown_names': unknown_names} df['score'] = df['contenu'].apply(countGenders) def",
"remapped) response = client.publish(config['mqtt-topic'], x, qos=0, retain=True) print(\"MQTT message published:\", response.is_published()) ts =",
"return {'male': males, 'female': females, 'total': males + females, 'unknown': unknown, 'male_names': male_names,",
"# searches for people names with spacy (as nlp) # count genders with",
"# This is the correct syntax print ('Attempt', counter, '>', e) if r",
"nlp) # count genders with gender.Detector (as d) # TODO get wikidata gender",
"counter = 1 while counter < 4: try: r = requests.post(_url, json=_json) except",
"nouns like François-Xavier: we use the “first” first name if firstname.count('-') > 0:",
"'unknown_names': unknown_names} df['score'] = df['contenu'].apply(countGenders) def computeRatio(counts): if counts['total'] > 0: return counts['female']",
"if x == x else 'n/a') ################ # MQTT # # on prend",
"portion + outMin # add the new minimal value return int(round(result)) # let’s",
"= remap(mean, 0, 100, 12, 181) print('Mean: {}, angle: {}'.format(mean, remapped)) x =",
"True: if r.status_code == 200: print('JSON sent at attempt', counter) break else: print('Attempt',",
"df['male'] = df['score'].apply(lambda x: x['male']) df['female'] = df['score'].apply(lambda x: x['female']) df['unknown'] = df['score'].apply(lambda",
"published:\", response.is_published()) ts = datetime.datetime.now().strftime('%Y-%m-%dT%H:%M:%SZ') data = {'mean': mean, 'update': ts} print(data) ################",
"gender.Detector (as d) # TODO get wikidata gender data? def countGenders(text): people =",
"x != x else x) def sendJson(_url, _json): r = False counter =",
"count genders with gender.Detector (as d) # TODO get wikidata gender data? def",
"nan df['ratio'] = df['score'].apply(computeRatio) df['percentage'] = df['ratio'].apply(lambda x: \"{0:.2f}%\".format(x*100) if x == x",
"# # on prend les 25 derniers mean = df[25:]['ratio'].mean() * 100 client",
"gender_guesser.detector as gender # time import datetime import time # to send MQTT",
"[] males = 0 females = 0 unknown = 0 doc = BeautifulSoup(text,",
"x: x['unknown']) df['id'] = df['guid'].apply(lambda x: int(x.split('/')[-1])) df['auteur_seul'] = df['auteur'].apply(lambda x: x.split(',')[0]) df['auteur_uni']",
"= df['guid'].apply(lambda x: int(x.split('/')[-1])) df['auteur_seul'] = df['auteur'].apply(lambda x: x.split(',')[0]) df['auteur_uni'] = df.apply(lambda row:",
"in people if re.search('[A-Z].*[A-Z]', i)] people = [i for i in people if",
"= mqtt.Client(\"xoxox\") client.connect(config['mqtt-broker'], port=1883) # change the ratio (from inMin to inMax) to",
"# add the new minimal value return int(round(result)) # let’s remap the ratio,",
"x, qos=0, retain=True) print(\"MQTT message published:\", response.is_published()) ts = datetime.datetime.now().strftime('%Y-%m-%dT%H:%M:%SZ') data = {'mean':",
"{}'.format(mean, remapped)) x = struct.pack('i', remapped) response = client.publish(config['mqtt-topic'], x, qos=0, retain=True) print(\"MQTT",
"counter += 1 return r payload = { 'records': df[['id', 'section', 'auteur_uni', 'dte_publication',",
"syntax print ('Attempt', counter, '>', e) if r == True: if r.status_code ==",
"r = requests.post(_url, json=_json) except requests.exceptions.RequestException as e: # This is the correct",
"pandas as pd import re from math import nan # config from define",
"spacy.load('fr') d = gender.Detector() # countGenders: # searches for people names with spacy",
"wikidata # and if we get a result, check the “gender” property, P21",
"config from define import config # NLP import spacy import gender_guesser.detector as gender",
"like François-Xavier: we use the “first” first name if firstname.count('-') > 0: firstname",
"r = False counter = 1 while counter < 4: try: r =",
"df['ratio'].apply(lambda x: 'NULL' if x != x else x) def sendJson(_url, _json): r",
"< 4: try: r = requests.post(_url, json=_json) except requests.exceptions.RequestException as e: # This",
"check the “gender” property, P21 firstname = personne.split()[0] # Dirty fix for compound",
"we use the “first” first name if firstname.count('-') > 0: firstname = firstname.split('-')[0]",
"4: try: r = requests.post(_url, json=_json) except requests.exceptions.RequestException as e: # This is",
"'unknown': unknown, 'male_names': male_names, 'female_names': female_names, 'unknown_names': unknown_names} df['score'] = df['contenu'].apply(countGenders) def computeRatio(counts):",
"to SQLITE database # df['male'] = df['score'].apply(lambda x: x['male']) df['female'] = df['score'].apply(lambda x:",
"int(round(result)) # let’s remap the ratio, from percentange to servomotor angle remapped =",
"let’s remap the ratio, from percentange to servomotor angle remapped = remap(mean, 0,",
"100, 12, 181) print('Mean: {}, angle: {}'.format(mean, remapped)) x = struct.pack('i', remapped) response",
"at attempt', counter) break else: print('Attempt', counter, '>', r.status_code) counter += 1 return",
"= 0 unknown = 0 doc = BeautifulSoup(text, 'html.parser') paragraphs = doc.find_all('p') paragraphs",
"male_names, 'female_names': female_names, 'unknown_names': unknown_names} df['score'] = df['contenu'].apply(countGenders) def computeRatio(counts): if counts['total'] >",
"df['male_names'] = df['score'].apply(lambda x: \", \".join(x['male_names'])) df['female_names'] = df['score'].apply(lambda x: \", \".join(x['female_names'])) df['unknown_names']",
"x['unknown']) df['id'] = df['guid'].apply(lambda x: int(x.split('/')[-1])) df['auteur_seul'] = df['auteur'].apply(lambda x: x.split(',')[0]) df['auteur_uni'] =",
"in people] people = [i for i in people if re.search('[A-Z].*[A-Z]', i)] people",
"df['score'].apply(lambda x: x['unknown']) df['id'] = df['guid'].apply(lambda x: int(x.split('/')[-1])) df['auteur_seul'] = df['auteur'].apply(lambda x: x.split(',')[0])",
"add the new minimal value return int(round(result)) # let’s remap the ratio, from",
"== x else 'n/a') ################ # MQTT # # on prend les 25",
"= df['score'].apply(lambda x: x['male']) df['female'] = df['score'].apply(lambda x: x['female']) df['unknown'] = df['score'].apply(lambda x:",
"= { 'records': df[['id', 'section', 'auteur_uni', 'dte_publication', 'titre', 'male', 'female', 'unknown', 'male_names', 'female_names',",
"use the “first” first name if firstname.count('-') > 0: firstname = firstname.split('-')[0] result",
"r.status_code == 200: print('JSON sent at attempt', counter) break else: print('Attempt', counter, '>',",
"result.find('male') >= 0: male_names.append(personne) males += 1 else: unknown_names.append(personne) unknown += 1 return",
"* 100 client = mqtt.Client(\"xoxox\") client.connect(config['mqtt-broker'], port=1883) # change the ratio (from inMin",
"to servomotor angle remapped = remap(mean, 0, 100, 12, 181) print('Mean: {}, angle:",
"the “gender” property, P21 firstname = personne.split()[0] # Dirty fix for compound nouns",
"x else x) def sendJson(_url, _json): r = False counter = 1 while",
"= pd.DataFrame(response.json()) nlp = spacy.load('fr') d = gender.Detector() # countGenders: # searches for",
"x: x.split(',')[0]) df['auteur_uni'] = df.apply(lambda row: row['auteur_int'] if row['auteur_int'] != '' else row['auteur_seul'],",
"d) # TODO get wikidata gender data? def countGenders(text): people = [] male_names",
"[i for i in people if not re.search('Monsieur|Madame', i)] people = list(set(people)) for",
"row: row['auteur_int'] if row['auteur_int'] != '' else row['auteur_seul'], axis=1) df['male_names'] = df['score'].apply(lambda x:",
"0: female_names.append(personne) females += 1 elif result.find('male') >= 0: male_names.append(personne) males += 1",
"sendJson(_url, _json): r = False counter = 1 while counter < 4: try:",
"df['score'].apply(lambda x: x['male']) df['female'] = df['score'].apply(lambda x: x['female']) df['unknown'] = df['score'].apply(lambda x: x['unknown'])",
"df['female_names'] = df['score'].apply(lambda x: \", \".join(x['female_names'])) df['unknown_names'] = df['score'].apply(lambda x: \", \".join(x['unknown_names'])) df['ratio']",
"list(set(people)) for personne in people: ## TODO # here we could query wikidata",
"utf-8 import requests from bs4 import BeautifulSoup import pandas as pd import re",
"== 'PER') people = [i.strip() for i in people] people = [i for",
"= 0 doc = BeautifulSoup(text, 'html.parser') paragraphs = doc.find_all('p') paragraphs = [p.text for",
"SQLITE database # df['male'] = df['score'].apply(lambda x: x['male']) df['female'] = df['score'].apply(lambda x: x['female'])",
"df['unknown'] = df['score'].apply(lambda x: x['unknown']) df['id'] = df['guid'].apply(lambda x: int(x.split('/')[-1])) df['auteur_seul'] = df['auteur'].apply(lambda",
"else row['auteur_seul'], axis=1) df['male_names'] = df['score'].apply(lambda x: \", \".join(x['male_names'])) df['female_names'] = df['score'].apply(lambda x:",
"male_names.append(personne) males += 1 else: unknown_names.append(personne) unknown += 1 return {'male': males, 'female':",
"counter) break else: print('Attempt', counter, '>', r.status_code) counter += 1 return r payload",
"= datetime.datetime.now().strftime('%Y-%m-%dT%H:%M:%SZ') data = {'mean': mean, 'update': ts} print(data) ################ # Send data",
"print('Attempt', counter, '>', r.status_code) counter += 1 return r payload = { 'records':",
"people names with spacy (as nlp) # count genders with gender.Detector (as d)",
"outMax ): portion = (x-inMin)*(outMax-outMin)/(inMax-inMin) result = portion + outMin # add the",
"'' else row['auteur_seul'], axis=1) df['male_names'] = df['score'].apply(lambda x: \", \".join(x['male_names'])) df['female_names'] = df['score'].apply(lambda",
"spacy (as nlp) # count genders with gender.Detector (as d) # TODO get",
"== 200: print('JSON sent at attempt', counter) break else: print('Attempt', counter, '>', r.status_code)",
"is the correct syntax print ('Attempt', counter, '>', e) if r == True:",
"property, P21 firstname = personne.split()[0] # Dirty fix for compound nouns like François-Xavier:",
"'female', 'unknown', 'male_names', 'female_names', 'unknown_names', 'ratio']].to_dict(orient='records'), } response = sendJson(config['send-sql-stories'], payload) print('Resultat SQLite:',",
"int(x.split('/')[-1])) df['auteur_seul'] = df['auteur'].apply(lambda x: x.split(',')[0]) df['auteur_uni'] = df.apply(lambda row: row['auteur_int'] if row['auteur_int']",
"computeRatio(counts): if counts['total'] > 0: return counts['female'] / counts['total'] else: return nan df['ratio']",
"i)] people = [i for i in people if not re.search('Monsieur|Madame', i)] people",
"elif result.find('male') >= 0: male_names.append(personne) males += 1 else: unknown_names.append(personne) unknown += 1",
"response = requests.get(config['get-stories']) df = pd.DataFrame(response.json()) nlp = spacy.load('fr') d = gender.Detector() #",
"to outMax) def remap( x, inMin, inMax, outMin, outMax ): portion = (x-inMin)*(outMax-outMin)/(inMax-inMin)",
"x: int(x.split('/')[-1])) df['auteur_seul'] = df['auteur'].apply(lambda x: x.split(',')[0]) df['auteur_uni'] = df.apply(lambda row: row['auteur_int'] if",
"= requests.get(config['get-stories']) df = pd.DataFrame(response.json()) nlp = spacy.load('fr') d = gender.Detector() # countGenders:",
"+= 1 else: unknown_names.append(personne) unknown += 1 return {'male': males, 'female': females, 'total':",
"= gender.Detector() # countGenders: # searches for people names with spacy (as nlp)",
"0, 100, 12, 181) print('Mean: {}, angle: {}'.format(mean, remapped)) x = struct.pack('i', remapped)",
"BeautifulSoup(text, 'html.parser') paragraphs = doc.find_all('p') paragraphs = [p.text for p in paragraphs] #",
"with gender.Detector (as d) # TODO get wikidata gender data? def countGenders(text): people",
"df['guid'].apply(lambda x: int(x.split('/')[-1])) df['auteur_seul'] = df['auteur'].apply(lambda x: x.split(',')[0]) df['auteur_uni'] = df.apply(lambda row: row['auteur_int']",
"False counter = 1 while counter < 4: try: r = requests.post(_url, json=_json)",
"males + females, 'unknown': unknown, 'male_names': male_names, 'female_names': female_names, 'unknown_names': unknown_names} df['score'] =",
"1 else: unknown_names.append(personne) unknown += 1 return {'male': males, 'female': females, 'total': males",
"import struct # Get the stories as json response = requests.get(config['get-stories']) df =",
"people if not re.search('Monsieur|Madame', i)] people = list(set(people)) for personne in people: ##",
"sp = nlp(p) people.extend('{}'.format(i) for i in sp.ents if i.label_ == 'PER') people",
"query wikidata # and if we get a result, check the “gender” property,",
"paragraphs = doc.find_all('p') paragraphs = [p.text for p in paragraphs] # or everything",
"df['ratio'] = df['score'].apply(computeRatio) df['percentage'] = df['ratio'].apply(lambda x: \"{0:.2f}%\".format(x*100) if x == x else",
"from math import nan # config from define import config # NLP import",
"= [i for i in people if re.search('[A-Z].*[A-Z]', i)] people = [i for",
"client.connect(config['mqtt-broker'], port=1883) # change the ratio (from inMin to inMax) to an angle",
"df['score'].apply(computeRatio) df['percentage'] = df['ratio'].apply(lambda x: \"{0:.2f}%\".format(x*100) if x == x else 'n/a') ################",
"import spacy import gender_guesser.detector as gender # time import datetime import time #",
"people = [i.strip() for i in people] people = [i for i in",
"if r == True: if r.status_code == 200: print('JSON sent at attempt', counter)",
"= personne.split()[0] # Dirty fix for compound nouns like François-Xavier: we use the",
"df['auteur_uni'] = df.apply(lambda row: row['auteur_int'] if row['auteur_int'] != '' else row['auteur_seul'], axis=1) df['male_names']",
"= requests.post(_url, json=_json) except requests.exceptions.RequestException as e: # This is the correct syntax",
"unknown += 1 return {'male': males, 'female': females, 'total': males + females, 'unknown':",
"/ counts['total'] else: return nan df['ratio'] = df['score'].apply(computeRatio) df['percentage'] = df['ratio'].apply(lambda x: \"{0:.2f}%\".format(x*100)",
"outMax) def remap( x, inMin, inMax, outMin, outMax ): portion = (x-inMin)*(outMax-outMin)/(inMax-inMin) result",
"with spacy (as nlp) # count genders with gender.Detector (as d) # TODO",
">= 0: male_names.append(personne) males += 1 else: unknown_names.append(personne) unknown += 1 return {'male':",
"mean = df[25:]['ratio'].mean() * 100 client = mqtt.Client(\"xoxox\") client.connect(config['mqtt-broker'], port=1883) # change the",
"'update': ts} print(data) ################ # Send data to SQLITE database # df['male'] =",
"on prend les 25 derniers mean = df[25:]['ratio'].mean() * 100 client = mqtt.Client(\"xoxox\")",
"first name if firstname.count('-') > 0: firstname = firstname.split('-')[0] result = d.get_gender(firstname) if",
"if re.search('[A-Z].*[A-Z]', i)] people = [i for i in people if not re.search('Monsieur|Madame',",
"e) if r == True: if r.status_code == 200: print('JSON sent at attempt',",
"config # NLP import spacy import gender_guesser.detector as gender # time import datetime",
"# Dirty fix for compound nouns like François-Xavier: we use the “first” first",
"or everything at once: # ptext = \"\\n\".join(paragraphs) # sp = nlp(ptext) for",
"json response = requests.get(config['get-stories']) df = pd.DataFrame(response.json()) nlp = spacy.load('fr') d = gender.Detector()",
"in sp.ents if i.label_ == 'PER') people = [i.strip() for i in people]",
"people] people = [i for i in people if re.search('[A-Z].*[A-Z]', i)] people =",
"df.apply(lambda row: row['auteur_int'] if row['auteur_int'] != '' else row['auteur_seul'], axis=1) df['male_names'] = df['score'].apply(lambda",
"unknown_names} df['score'] = df['contenu'].apply(countGenders) def computeRatio(counts): if counts['total'] > 0: return counts['female'] /",
"nlp = spacy.load('fr') d = gender.Detector() # countGenders: # searches for people names",
"females += 1 elif result.find('male') >= 0: male_names.append(personne) males += 1 else: unknown_names.append(personne)",
"= df['ratio'].apply(lambda x: \"{0:.2f}%\".format(x*100) if x == x else 'n/a') ################ # MQTT",
"x == x else 'n/a') ################ # MQTT # # on prend les",
"0: return counts['female'] / counts['total'] else: return nan df['ratio'] = df['score'].apply(computeRatio) df['percentage'] =",
"= df['score'].apply(lambda x: x['unknown']) df['id'] = df['guid'].apply(lambda x: int(x.split('/')[-1])) df['auteur_seul'] = df['auteur'].apply(lambda x:",
"at once: # ptext = \"\\n\".join(paragraphs) # sp = nlp(ptext) for p in",
"return r payload = { 'records': df[['id', 'section', 'auteur_uni', 'dte_publication', 'titre', 'male', 'female',",
"# here we could query wikidata # and if we get a result,",
"for people names with spacy (as nlp) # count genders with gender.Detector (as",
"df['contenu'].apply(countGenders) def computeRatio(counts): if counts['total'] > 0: return counts['female'] / counts['total'] else: return",
"\".join(x['male_names'])) df['female_names'] = df['score'].apply(lambda x: \", \".join(x['female_names'])) df['unknown_names'] = df['score'].apply(lambda x: \", \".join(x['unknown_names']))",
"we get a result, check the “gender” property, P21 firstname = personne.split()[0] #",
"searches for people names with spacy (as nlp) # count genders with gender.Detector",
"ptext = \"\\n\".join(paragraphs) # sp = nlp(ptext) for p in paragraphs: sp =",
"x['female']) df['unknown'] = df['score'].apply(lambda x: x['unknown']) df['id'] = df['guid'].apply(lambda x: int(x.split('/')[-1])) df['auteur_seul'] =",
"if i.label_ == 'PER') people = [i.strip() for i in people] people =",
"row['auteur_int'] != '' else row['auteur_seul'], axis=1) df['male_names'] = df['score'].apply(lambda x: \", \".join(x['male_names'])) df['female_names']",
"= doc.find_all('p') paragraphs = [p.text for p in paragraphs] # or everything at",
"pd import re from math import nan # config from define import config",
"the “first” first name if firstname.count('-') > 0: firstname = firstname.split('-')[0] result =",
"counts['female'] / counts['total'] else: return nan df['ratio'] = df['score'].apply(computeRatio) df['percentage'] = df['ratio'].apply(lambda x:",
"ratio (from inMin to inMax) to an angle (from outMin to outMax) def",
"d = gender.Detector() # countGenders: # searches for people names with spacy (as",
"except requests.exceptions.RequestException as e: # This is the correct syntax print ('Attempt', counter,",
"+ females, 'unknown': unknown, 'male_names': male_names, 'female_names': female_names, 'unknown_names': unknown_names} df['score'] = df['contenu'].apply(countGenders)",
"else: print('Attempt', counter, '>', r.status_code) counter += 1 return r payload = {",
"import datetime import time # to send MQTT message import paho.mqtt.client as mqtt",
"df['female'] = df['score'].apply(lambda x: x['female']) df['unknown'] = df['score'].apply(lambda x: x['unknown']) df['id'] = df['guid'].apply(lambda",
"p in paragraphs: sp = nlp(p) people.extend('{}'.format(i) for i in sp.ents if i.label_",
"sent at attempt', counter) break else: print('Attempt', counter, '>', r.status_code) counter += 1",
"d.get_gender(firstname) if result.find('female') >= 0: female_names.append(personne) females += 1 elif result.find('male') >= 0:",
"gender # time import datetime import time # to send MQTT message import",
"inMin, inMax, outMin, outMax ): portion = (x-inMin)*(outMax-outMin)/(inMax-inMin) result = portion + outMin",
"outMin, outMax ): portion = (x-inMin)*(outMax-outMin)/(inMax-inMin) result = portion + outMin # add",
"0 females = 0 unknown = 0 doc = BeautifulSoup(text, 'html.parser') paragraphs =",
"counter < 4: try: r = requests.post(_url, json=_json) except requests.exceptions.RequestException as e: #",
"(from inMin to inMax) to an angle (from outMin to outMax) def remap(",
"= nlp(p) people.extend('{}'.format(i) for i in sp.ents if i.label_ == 'PER') people =",
"# df['male'] = df['score'].apply(lambda x: x['male']) df['female'] = df['score'].apply(lambda x: x['female']) df['unknown'] =",
"males, 'female': females, 'total': males + females, 'unknown': unknown, 'male_names': male_names, 'female_names': female_names,",
"from percentange to servomotor angle remapped = remap(mean, 0, 100, 12, 181) print('Mean:",
"{'mean': mean, 'update': ts} print(data) ################ # Send data to SQLITE database #",
"remap(mean, 0, 100, 12, 181) print('Mean: {}, angle: {}'.format(mean, remapped)) x = struct.pack('i',",
"\".join(x['female_names'])) df['unknown_names'] = df['score'].apply(lambda x: \", \".join(x['unknown_names'])) df['ratio'] = df['ratio'].apply(lambda x: 'NULL' if",
"(as nlp) # count genders with gender.Detector (as d) # TODO get wikidata",
"+= 1 return {'male': males, 'female': females, 'total': males + females, 'unknown': unknown,",
"if result.find('female') >= 0: female_names.append(personne) females += 1 elif result.find('male') >= 0: male_names.append(personne)"
] |
[
"= cf.position() if (cfPosition.position.x > wandPosition.position.x): cf.goTo(goal = [wandPosition.position.x + 0.2, wandPosition.position.y, wandPosition.position.z],",
"<filename>crazyflie_driver/src/test_follower.py #!/usr/bin/env python import rospy import crazyflie import time import uav_trajectory if __name__",
"0.2, wandPosition.position.y, wandPosition.position.z], yaw=0.2, duration = 2.0, relative = False) else: cf.goTo(goal =",
"crazyflie.Crazyflie(\"wand\", \"wand\") cf.setParam(\"commander/enHighLevel\", 1) wand.setParam(\"commander/enHighLevel\", 2) cf1.takeoff(targetHeight = 1.0, duration = 2.0) time.sleep(5.0)",
"cf.goTo(goal = [wandPosition.position.x + 0.2, wandPosition.position.y, wandPosition.position.z], yaw=0.2, duration = 2.0, relative =",
"wandPosition = wand.wandPosition() cfPosition = cf.position() if (cfPosition.position.x > wandPosition.position.x): cf.goTo(goal = [wandPosition.position.x",
"crazyflie.Crazyflie(\"crazyflie\", \"crazyflie\") wand = crazyflie.Crazyflie(\"wand\", \"wand\") cf.setParam(\"commander/enHighLevel\", 1) wand.setParam(\"commander/enHighLevel\", 2) cf1.takeoff(targetHeight = 1.0,",
"cfPosition = cf.position() if (cfPosition.position.x > wandPosition.position.x): cf.goTo(goal = [wandPosition.position.x + 0.2, wandPosition.position.y,",
"= [wandPosition.position.x - 0.2, wandPosition.position.y, wandPosition.position.z], yaw=0.2, duration = 2.0, relative = False)",
"cf.setParam(\"commander/enHighLevel\", 1) wand.setParam(\"commander/enHighLevel\", 2) cf1.takeoff(targetHeight = 1.0, duration = 2.0) time.sleep(5.0) try: while",
"import rospy import crazyflie import time import uav_trajectory if __name__ == '__main__': rospy.init_node('test_high_level')",
"wand.setParam(\"commander/enHighLevel\", 2) cf1.takeoff(targetHeight = 1.0, duration = 2.0) time.sleep(5.0) try: while True: wandPosition",
"rospy import crazyflie import time import uav_trajectory if __name__ == '__main__': rospy.init_node('test_high_level') cf",
"import crazyflie import time import uav_trajectory if __name__ == '__main__': rospy.init_node('test_high_level') cf =",
"crazyflie import time import uav_trajectory if __name__ == '__main__': rospy.init_node('test_high_level') cf = crazyflie.Crazyflie(\"crazyflie\",",
"\"crazyflie\") wand = crazyflie.Crazyflie(\"wand\", \"wand\") cf.setParam(\"commander/enHighLevel\", 1) wand.setParam(\"commander/enHighLevel\", 2) cf1.takeoff(targetHeight = 1.0, duration",
"- 0.2, wandPosition.position.y, wandPosition.position.z], yaw=0.2, duration = 2.0, relative = False) finally: cf1.land(targetHeight",
"wandPosition.position.z], yaw=0.2, duration = 2.0, relative = False) finally: cf1.land(targetHeight = 0.0, duration",
"[wandPosition.position.x + 0.2, wandPosition.position.y, wandPosition.position.z], yaw=0.2, duration = 2.0, relative = False) else:",
"2) cf1.takeoff(targetHeight = 1.0, duration = 2.0) time.sleep(5.0) try: while True: wandPosition =",
"while True: wandPosition = wand.wandPosition() cfPosition = cf.position() if (cfPosition.position.x > wandPosition.position.x): cf.goTo(goal",
"[wandPosition.position.x - 0.2, wandPosition.position.y, wandPosition.position.z], yaw=0.2, duration = 2.0, relative = False) finally:",
"1.0, duration = 2.0) time.sleep(5.0) try: while True: wandPosition = wand.wandPosition() cfPosition =",
"wand = crazyflie.Crazyflie(\"wand\", \"wand\") cf.setParam(\"commander/enHighLevel\", 1) wand.setParam(\"commander/enHighLevel\", 2) cf1.takeoff(targetHeight = 1.0, duration =",
"= 2.0) time.sleep(5.0) try: while True: wandPosition = wand.wandPosition() cfPosition = cf.position() if",
"+ 0.2, wandPosition.position.y, wandPosition.position.z], yaw=0.2, duration = 2.0, relative = False) else: cf.goTo(goal",
"relative = False) else: cf.goTo(goal = [wandPosition.position.x - 0.2, wandPosition.position.y, wandPosition.position.z], yaw=0.2, duration",
"if (cfPosition.position.x > wandPosition.position.x): cf.goTo(goal = [wandPosition.position.x + 0.2, wandPosition.position.y, wandPosition.position.z], yaw=0.2, duration",
"= [wandPosition.position.x + 0.2, wandPosition.position.y, wandPosition.position.z], yaw=0.2, duration = 2.0, relative = False)",
"#!/usr/bin/env python import rospy import crazyflie import time import uav_trajectory if __name__ ==",
"= crazyflie.Crazyflie(\"crazyflie\", \"crazyflie\") wand = crazyflie.Crazyflie(\"wand\", \"wand\") cf.setParam(\"commander/enHighLevel\", 1) wand.setParam(\"commander/enHighLevel\", 2) cf1.takeoff(targetHeight =",
"= wand.wandPosition() cfPosition = cf.position() if (cfPosition.position.x > wandPosition.position.x): cf.goTo(goal = [wandPosition.position.x +",
"wandPosition.position.y, wandPosition.position.z], yaw=0.2, duration = 2.0, relative = False) else: cf.goTo(goal = [wandPosition.position.x",
"'__main__': rospy.init_node('test_high_level') cf = crazyflie.Crazyflie(\"crazyflie\", \"crazyflie\") wand = crazyflie.Crazyflie(\"wand\", \"wand\") cf.setParam(\"commander/enHighLevel\", 1) wand.setParam(\"commander/enHighLevel\",",
"else: cf.goTo(goal = [wandPosition.position.x - 0.2, wandPosition.position.y, wandPosition.position.z], yaw=0.2, duration = 2.0, relative",
"__name__ == '__main__': rospy.init_node('test_high_level') cf = crazyflie.Crazyflie(\"crazyflie\", \"crazyflie\") wand = crazyflie.Crazyflie(\"wand\", \"wand\") cf.setParam(\"commander/enHighLevel\",",
"cf = crazyflie.Crazyflie(\"crazyflie\", \"crazyflie\") wand = crazyflie.Crazyflie(\"wand\", \"wand\") cf.setParam(\"commander/enHighLevel\", 1) wand.setParam(\"commander/enHighLevel\", 2) cf1.takeoff(targetHeight",
"1) wand.setParam(\"commander/enHighLevel\", 2) cf1.takeoff(targetHeight = 1.0, duration = 2.0) time.sleep(5.0) try: while True:",
"2.0) time.sleep(5.0) try: while True: wandPosition = wand.wandPosition() cfPosition = cf.position() if (cfPosition.position.x",
"(cfPosition.position.x > wandPosition.position.x): cf.goTo(goal = [wandPosition.position.x + 0.2, wandPosition.position.y, wandPosition.position.z], yaw=0.2, duration =",
"> wandPosition.position.x): cf.goTo(goal = [wandPosition.position.x + 0.2, wandPosition.position.y, wandPosition.position.z], yaw=0.2, duration = 2.0,",
"False) else: cf.goTo(goal = [wandPosition.position.x - 0.2, wandPosition.position.y, wandPosition.position.z], yaw=0.2, duration = 2.0,",
"= 2.0, relative = False) finally: cf1.land(targetHeight = 0.0, duration = 2.0) time.sleep(5.0)",
"time import uav_trajectory if __name__ == '__main__': rospy.init_node('test_high_level') cf = crazyflie.Crazyflie(\"crazyflie\", \"crazyflie\") wand",
"wandPosition.position.x): cf.goTo(goal = [wandPosition.position.x + 0.2, wandPosition.position.y, wandPosition.position.z], yaw=0.2, duration = 2.0, relative",
"yaw=0.2, duration = 2.0, relative = False) else: cf.goTo(goal = [wandPosition.position.x - 0.2,",
"= 2.0, relative = False) else: cf.goTo(goal = [wandPosition.position.x - 0.2, wandPosition.position.y, wandPosition.position.z],",
"duration = 2.0, relative = False) finally: cf1.land(targetHeight = 0.0, duration = 2.0)",
"import uav_trajectory if __name__ == '__main__': rospy.init_node('test_high_level') cf = crazyflie.Crazyflie(\"crazyflie\", \"crazyflie\") wand =",
"import time import uav_trajectory if __name__ == '__main__': rospy.init_node('test_high_level') cf = crazyflie.Crazyflie(\"crazyflie\", \"crazyflie\")",
"= crazyflie.Crazyflie(\"wand\", \"wand\") cf.setParam(\"commander/enHighLevel\", 1) wand.setParam(\"commander/enHighLevel\", 2) cf1.takeoff(targetHeight = 1.0, duration = 2.0)",
"True: wandPosition = wand.wandPosition() cfPosition = cf.position() if (cfPosition.position.x > wandPosition.position.x): cf.goTo(goal =",
"cf.position() if (cfPosition.position.x > wandPosition.position.x): cf.goTo(goal = [wandPosition.position.x + 0.2, wandPosition.position.y, wandPosition.position.z], yaw=0.2,",
"if __name__ == '__main__': rospy.init_node('test_high_level') cf = crazyflie.Crazyflie(\"crazyflie\", \"crazyflie\") wand = crazyflie.Crazyflie(\"wand\", \"wand\")",
"duration = 2.0, relative = False) else: cf.goTo(goal = [wandPosition.position.x - 0.2, wandPosition.position.y,",
"try: while True: wandPosition = wand.wandPosition() cfPosition = cf.position() if (cfPosition.position.x > wandPosition.position.x):",
"== '__main__': rospy.init_node('test_high_level') cf = crazyflie.Crazyflie(\"crazyflie\", \"crazyflie\") wand = crazyflie.Crazyflie(\"wand\", \"wand\") cf.setParam(\"commander/enHighLevel\", 1)",
"= 1.0, duration = 2.0) time.sleep(5.0) try: while True: wandPosition = wand.wandPosition() cfPosition",
"0.2, wandPosition.position.y, wandPosition.position.z], yaw=0.2, duration = 2.0, relative = False) finally: cf1.land(targetHeight =",
"duration = 2.0) time.sleep(5.0) try: while True: wandPosition = wand.wandPosition() cfPosition = cf.position()",
"2.0, relative = False) else: cf.goTo(goal = [wandPosition.position.x - 0.2, wandPosition.position.y, wandPosition.position.z], yaw=0.2,",
"= False) else: cf.goTo(goal = [wandPosition.position.x - 0.2, wandPosition.position.y, wandPosition.position.z], yaw=0.2, duration =",
"\"wand\") cf.setParam(\"commander/enHighLevel\", 1) wand.setParam(\"commander/enHighLevel\", 2) cf1.takeoff(targetHeight = 1.0, duration = 2.0) time.sleep(5.0) try:",
"wandPosition.position.z], yaw=0.2, duration = 2.0, relative = False) else: cf.goTo(goal = [wandPosition.position.x -",
"cf.goTo(goal = [wandPosition.position.x - 0.2, wandPosition.position.y, wandPosition.position.z], yaw=0.2, duration = 2.0, relative =",
"yaw=0.2, duration = 2.0, relative = False) finally: cf1.land(targetHeight = 0.0, duration =",
"2.0, relative = False) finally: cf1.land(targetHeight = 0.0, duration = 2.0) time.sleep(5.0) cf1.stop()",
"python import rospy import crazyflie import time import uav_trajectory if __name__ == '__main__':",
"cf1.takeoff(targetHeight = 1.0, duration = 2.0) time.sleep(5.0) try: while True: wandPosition = wand.wandPosition()",
"time.sleep(5.0) try: while True: wandPosition = wand.wandPosition() cfPosition = cf.position() if (cfPosition.position.x >",
"wand.wandPosition() cfPosition = cf.position() if (cfPosition.position.x > wandPosition.position.x): cf.goTo(goal = [wandPosition.position.x + 0.2,",
"rospy.init_node('test_high_level') cf = crazyflie.Crazyflie(\"crazyflie\", \"crazyflie\") wand = crazyflie.Crazyflie(\"wand\", \"wand\") cf.setParam(\"commander/enHighLevel\", 1) wand.setParam(\"commander/enHighLevel\", 2)",
"wandPosition.position.y, wandPosition.position.z], yaw=0.2, duration = 2.0, relative = False) finally: cf1.land(targetHeight = 0.0,",
"uav_trajectory if __name__ == '__main__': rospy.init_node('test_high_level') cf = crazyflie.Crazyflie(\"crazyflie\", \"crazyflie\") wand = crazyflie.Crazyflie(\"wand\","
] |
[
"AccelerationSensor: def __init__(self, measurement_covariance): self.R_meas = measurement_covariance def getMeasurements(self, true_accel): return np.random.multivariate_normal(true_accel, self.R_meas)",
"numpy as np class AccelerationSensor: def __init__(self, measurement_covariance): self.R_meas = measurement_covariance def getMeasurements(self,",
"import numpy as np class AccelerationSensor: def __init__(self, measurement_covariance): self.R_meas = measurement_covariance def",
"np class AccelerationSensor: def __init__(self, measurement_covariance): self.R_meas = measurement_covariance def getMeasurements(self, true_accel): return",
"as np class AccelerationSensor: def __init__(self, measurement_covariance): self.R_meas = measurement_covariance def getMeasurements(self, true_accel):",
"class AccelerationSensor: def __init__(self, measurement_covariance): self.R_meas = measurement_covariance def getMeasurements(self, true_accel): return np.random.multivariate_normal(true_accel,"
] |
[
"client import IntentClient class IntentError(Exception): pass # def sendIntent(self, context, action, issuer): #",
"IntentClient class IntentError(Exception): pass # def sendIntent(self, context, action, issuer): # client =",
"import IntentClient class IntentError(Exception): pass # def sendIntent(self, context, action, issuer): # client",
"#from client import IntentClient class IntentError(Exception): pass # def sendIntent(self, context, action, issuer):",
"IntentError(Exception): pass # def sendIntent(self, context, action, issuer): # client = IntentClient(action, issuer)",
"<reponame>piyush82/elastest-device-emulator-service<filename>eds/openmtc-gevent/server/openmtc-server/src/openmtc_server/plugins/transport_android_intent/IntentError.py #from client import IntentClient class IntentError(Exception): pass # def sendIntent(self, context, action,",
"class IntentError(Exception): pass # def sendIntent(self, context, action, issuer): # client = IntentClient(action,"
] |
[
"if isinstance(queryset, QuerySet) is False: raise TypeError('\"queryset\" must be Queryset') if isinstance(page, int)",
"TypeError('\"queryset\" must be Queryset') if isinstance(page, int) is False: raise TypeError('\"page\" must be",
"= json.loads(data) _d = [] for x in data: id = x.pop('pk') field_data",
"serialize( 'json', queryset ) data = json.loads(data) _d = [] for x in",
"from django.core.serializers import serialize from django.db.models.query import QuerySet ALLOWED_FORMATS = [ 'dict', 'json',",
"= queryset self.total = total self.pydantic_model = pydantic_model @property def data(self): return {",
"if count != '__all__': pages = math.ceil(total/count) start_index = (page - 1) *",
"'json', queryset ) data = json.loads(data) _d = [] for x in data:",
"'__all__': pages = math.ceil(total/count) start_index = (page - 1) * count end_index =",
"= total self.pydantic_model = pydantic_model @property def data(self): return { 'page': self.page, 'pages':",
"int') if isinstance(count, int) is False: raise TypeError('\"count\" must be int') total =",
"page=1, pages=1, queryset=QuerySet(), total=0, pydantic_model=None, ): self.page = page self.pages = pages self.queryset",
"def __init__( self, page=1, pages=1, queryset=QuerySet(), total=0, pydantic_model=None, ): self.page = page self.pages",
"self.pydantic_model.from_django(results, many=True): _results.append(x.dict()) data['results'] = _results return data @property def json(self): return json.dumps(self.dict)",
"for x in data: id = x.pop('pk') field_data = x.pop('fields') field_data['id'] = id",
"count, pydantic_model=None): if isinstance(queryset, QuerySet) is False: raise TypeError('\"queryset\" must be Queryset') if",
"1 if count != '__all__': pages = math.ceil(total/count) start_index = (page - 1)",
"json.loads(data) _d = [] for x in data: id = x.pop('pk') field_data =",
"pydantic_model @property def data(self): return { 'page': self.page, 'pages': self.pages, 'results': self.queryset, 'total':",
"[ 'dict', 'json', 'queryset' ] class Pagination: def __init__( self, page=1, pages=1, queryset=QuerySet(),",
"data['results'] = self.queryset_to_dict(results) else: _results = [] for x in self.pydantic_model.from_django(results, many=True): _results.append(x.dict())",
"is None: data['results'] = self.queryset_to_dict(results) else: _results = [] for x in self.pydantic_model.from_django(results,",
"_results = [] for x in self.pydantic_model.from_django(results, many=True): _results.append(x.dict()) data['results'] = _results return",
"def dict(self): data = self.data results = data['results'] if self.pydantic_model is None: data['results']",
"def pagination(queryset, page, count, pydantic_model=None): if isinstance(queryset, QuerySet) is False: raise TypeError('\"queryset\" must",
"raise TypeError('\"count\" must be int') total = queryset.count() pages = 1 if count",
"@property def data(self): return { 'page': self.page, 'pages': self.pages, 'results': self.queryset, 'total': self.total",
"return _d def pagination(queryset, page, count, pydantic_model=None): if isinstance(queryset, QuerySet) is False: raise",
"page self.pages = pages self.queryset = queryset self.total = total self.pydantic_model = pydantic_model",
"many=True): _results.append(x.dict()) data['results'] = _results return data @property def json(self): return json.dumps(self.dict) def",
"def queryset_to_dict(self, queryset): data = serialize( 'json', queryset ) data = json.loads(data) _d",
"total=0, pydantic_model=None, ): self.page = page self.pages = pages self.queryset = queryset self.total",
"django.core.serializers import serialize from django.db.models.query import QuerySet ALLOWED_FORMATS = [ 'dict', 'json', 'queryset'",
"x in self.pydantic_model.from_django(results, many=True): _results.append(x.dict()) data['results'] = _results return data @property def json(self):",
"= [] for x in self.pydantic_model.from_django(results, many=True): _results.append(x.dict()) data['results'] = _results return data",
"count queryset = queryset[start_index : end_index] return Pagination( page=page, pages=pages, queryset=queryset, total=total, pydantic_model=pydantic_model",
"in self.pydantic_model.from_django(results, many=True): _results.append(x.dict()) data['results'] = _results return data @property def json(self): return",
"pages=1, queryset=QuerySet(), total=0, pydantic_model=None, ): self.page = page self.pages = pages self.queryset =",
"False: raise TypeError('\"queryset\" must be Queryset') if isinstance(page, int) is False: raise TypeError('\"page\"",
"be int') total = queryset.count() pages = 1 if count != '__all__': pages",
"math from django.core.serializers import serialize from django.db.models.query import QuerySet ALLOWED_FORMATS = [ 'dict',",
"else: _results = [] for x in self.pydantic_model.from_django(results, many=True): _results.append(x.dict()) data['results'] = _results",
"from django.db.models.query import QuerySet ALLOWED_FORMATS = [ 'dict', 'json', 'queryset' ] class Pagination:",
"data['results'] = _results return data @property def json(self): return json.dumps(self.dict) def queryset_to_dict(self, queryset):",
"data = json.loads(data) _d = [] for x in data: id = x.pop('pk')",
"int) is False: raise TypeError('\"page\" must be int') if isinstance(count, int) is False:",
"'queryset' ] class Pagination: def __init__( self, page=1, pages=1, queryset=QuerySet(), total=0, pydantic_model=None, ):",
"'pages': self.pages, 'results': self.queryset, 'total': self.total } @property def dict(self): data = self.data",
"total self.pydantic_model = pydantic_model @property def data(self): return { 'page': self.page, 'pages': self.pages,",
"(page - 1) * count end_index = start_index + count queryset = queryset[start_index",
"data(self): return { 'page': self.page, 'pages': self.pages, 'results': self.queryset, 'total': self.total } @property",
"= 1 if count != '__all__': pages = math.ceil(total/count) start_index = (page -",
"= (page - 1) * count end_index = start_index + count queryset =",
"is False: raise TypeError('\"page\" must be int') if isinstance(count, int) is False: raise",
"pages = 1 if count != '__all__': pages = math.ceil(total/count) start_index = (page",
"total = queryset.count() pages = 1 if count != '__all__': pages = math.ceil(total/count)",
"json import math from django.core.serializers import serialize from django.db.models.query import QuerySet ALLOWED_FORMATS =",
"data = serialize( 'json', queryset ) data = json.loads(data) _d = [] for",
"raise TypeError('\"queryset\" must be Queryset') if isinstance(page, int) is False: raise TypeError('\"page\" must",
"self.pydantic_model = pydantic_model @property def data(self): return { 'page': self.page, 'pages': self.pages, 'results':",
"= _results return data @property def json(self): return json.dumps(self.dict) def queryset_to_dict(self, queryset): data",
"'page': self.page, 'pages': self.pages, 'results': self.queryset, 'total': self.total } @property def dict(self): data",
"raise TypeError('\"page\" must be int') if isinstance(count, int) is False: raise TypeError('\"count\" must",
"dict(self): data = self.data results = data['results'] if self.pydantic_model is None: data['results'] =",
"'total': self.total } @property def dict(self): data = self.data results = data['results'] if",
"= pages self.queryset = queryset self.total = total self.pydantic_model = pydantic_model @property def",
"False: raise TypeError('\"count\" must be int') total = queryset.count() pages = 1 if",
"= pydantic_model @property def data(self): return { 'page': self.page, 'pages': self.pages, 'results': self.queryset,",
"x.pop('pk') field_data = x.pop('fields') field_data['id'] = id _d.append(field_data) return _d def pagination(queryset, page,",
"must be int') total = queryset.count() pages = 1 if count != '__all__':",
"import json import math from django.core.serializers import serialize from django.db.models.query import QuerySet ALLOWED_FORMATS",
"queryset = queryset[start_index : end_index] return Pagination( page=page, pages=pages, queryset=queryset, total=total, pydantic_model=pydantic_model )",
"if isinstance(page, int) is False: raise TypeError('\"page\" must be int') if isinstance(count, int)",
"self.page, 'pages': self.pages, 'results': self.queryset, 'total': self.total } @property def dict(self): data =",
"be int') if isinstance(count, int) is False: raise TypeError('\"count\" must be int') total",
"+ count queryset = queryset[start_index : end_index] return Pagination( page=page, pages=pages, queryset=queryset, total=total,",
"serialize from django.db.models.query import QuerySet ALLOWED_FORMATS = [ 'dict', 'json', 'queryset' ] class",
"be Queryset') if isinstance(page, int) is False: raise TypeError('\"page\" must be int') if",
"QuerySet) is False: raise TypeError('\"queryset\" must be Queryset') if isinstance(page, int) is False:",
"queryset.count() pages = 1 if count != '__all__': pages = math.ceil(total/count) start_index =",
"__init__( self, page=1, pages=1, queryset=QuerySet(), total=0, pydantic_model=None, ): self.page = page self.pages =",
"} @property def dict(self): data = self.data results = data['results'] if self.pydantic_model is",
"1) * count end_index = start_index + count queryset = queryset[start_index : end_index]",
"must be Queryset') if isinstance(page, int) is False: raise TypeError('\"page\" must be int')",
"_d def pagination(queryset, page, count, pydantic_model=None): if isinstance(queryset, QuerySet) is False: raise TypeError('\"queryset\"",
"'dict', 'json', 'queryset' ] class Pagination: def __init__( self, page=1, pages=1, queryset=QuerySet(), total=0,",
"queryset): data = serialize( 'json', queryset ) data = json.loads(data) _d = []",
"TypeError('\"count\" must be int') total = queryset.count() pages = 1 if count !=",
"return json.dumps(self.dict) def queryset_to_dict(self, queryset): data = serialize( 'json', queryset ) data =",
"= page self.pages = pages self.queryset = queryset self.total = total self.pydantic_model =",
"self.queryset = queryset self.total = total self.pydantic_model = pydantic_model @property def data(self): return",
"= self.queryset_to_dict(results) else: _results = [] for x in self.pydantic_model.from_django(results, many=True): _results.append(x.dict()) data['results']",
"self.page = page self.pages = pages self.queryset = queryset self.total = total self.pydantic_model",
"= self.data results = data['results'] if self.pydantic_model is None: data['results'] = self.queryset_to_dict(results) else:",
"{ 'page': self.page, 'pages': self.pages, 'results': self.queryset, 'total': self.total } @property def dict(self):",
"_d = [] for x in data: id = x.pop('pk') field_data = x.pop('fields')",
"id = x.pop('pk') field_data = x.pop('fields') field_data['id'] = id _d.append(field_data) return _d def",
"'json', 'queryset' ] class Pagination: def __init__( self, page=1, pages=1, queryset=QuerySet(), total=0, pydantic_model=None,",
"pagination(queryset, page, count, pydantic_model=None): if isinstance(queryset, QuerySet) is False: raise TypeError('\"queryset\" must be",
"int') total = queryset.count() pages = 1 if count != '__all__': pages =",
"count != '__all__': pages = math.ceil(total/count) start_index = (page - 1) * count",
"= serialize( 'json', queryset ) data = json.loads(data) _d = [] for x",
"is False: raise TypeError('\"count\" must be int') total = queryset.count() pages = 1",
"- 1) * count end_index = start_index + count queryset = queryset[start_index :",
"ALLOWED_FORMATS = [ 'dict', 'json', 'queryset' ] class Pagination: def __init__( self, page=1,",
"pydantic_model=None, ): self.page = page self.pages = pages self.queryset = queryset self.total =",
"pages = math.ceil(total/count) start_index = (page - 1) * count end_index = start_index",
"[] for x in data: id = x.pop('pk') field_data = x.pop('fields') field_data['id'] =",
"x.pop('fields') field_data['id'] = id _d.append(field_data) return _d def pagination(queryset, page, count, pydantic_model=None): if",
"@property def dict(self): data = self.data results = data['results'] if self.pydantic_model is None:",
"return { 'page': self.page, 'pages': self.pages, 'results': self.queryset, 'total': self.total } @property def",
"): self.page = page self.pages = pages self.queryset = queryset self.total = total",
"import QuerySet ALLOWED_FORMATS = [ 'dict', 'json', 'queryset' ] class Pagination: def __init__(",
"self.queryset_to_dict(results) else: _results = [] for x in self.pydantic_model.from_django(results, many=True): _results.append(x.dict()) data['results'] =",
"data @property def json(self): return json.dumps(self.dict) def queryset_to_dict(self, queryset): data = serialize( 'json',",
"queryset ) data = json.loads(data) _d = [] for x in data: id",
"self.total } @property def dict(self): data = self.data results = data['results'] if self.pydantic_model",
"self.pages = pages self.queryset = queryset self.total = total self.pydantic_model = pydantic_model @property",
"must be int') if isinstance(count, int) is False: raise TypeError('\"count\" must be int')",
"= data['results'] if self.pydantic_model is None: data['results'] = self.queryset_to_dict(results) else: _results = []",
"class Pagination: def __init__( self, page=1, pages=1, queryset=QuerySet(), total=0, pydantic_model=None, ): self.page =",
"self.pydantic_model is None: data['results'] = self.queryset_to_dict(results) else: _results = [] for x in",
"QuerySet ALLOWED_FORMATS = [ 'dict', 'json', 'queryset' ] class Pagination: def __init__( self,",
"in data: id = x.pop('pk') field_data = x.pop('fields') field_data['id'] = id _d.append(field_data) return",
"Queryset') if isinstance(page, int) is False: raise TypeError('\"page\" must be int') if isinstance(count,",
"import math from django.core.serializers import serialize from django.db.models.query import QuerySet ALLOWED_FORMATS = [",
"False: raise TypeError('\"page\" must be int') if isinstance(count, int) is False: raise TypeError('\"count\"",
"_results.append(x.dict()) data['results'] = _results return data @property def json(self): return json.dumps(self.dict) def queryset_to_dict(self,",
"def data(self): return { 'page': self.page, 'pages': self.pages, 'results': self.queryset, 'total': self.total }",
"_results return data @property def json(self): return json.dumps(self.dict) def queryset_to_dict(self, queryset): data =",
"self.data results = data['results'] if self.pydantic_model is None: data['results'] = self.queryset_to_dict(results) else: _results",
"import serialize from django.db.models.query import QuerySet ALLOWED_FORMATS = [ 'dict', 'json', 'queryset' ]",
"count end_index = start_index + count queryset = queryset[start_index : end_index] return Pagination(",
"field_data = x.pop('fields') field_data['id'] = id _d.append(field_data) return _d def pagination(queryset, page, count,",
"_d.append(field_data) return _d def pagination(queryset, page, count, pydantic_model=None): if isinstance(queryset, QuerySet) is False:",
"field_data['id'] = id _d.append(field_data) return _d def pagination(queryset, page, count, pydantic_model=None): if isinstance(queryset,",
"] class Pagination: def __init__( self, page=1, pages=1, queryset=QuerySet(), total=0, pydantic_model=None, ): self.page",
"isinstance(queryset, QuerySet) is False: raise TypeError('\"queryset\" must be Queryset') if isinstance(page, int) is",
"= x.pop('pk') field_data = x.pop('fields') field_data['id'] = id _d.append(field_data) return _d def pagination(queryset,",
"None: data['results'] = self.queryset_to_dict(results) else: _results = [] for x in self.pydantic_model.from_django(results, many=True):",
"if isinstance(count, int) is False: raise TypeError('\"count\" must be int') total = queryset.count()",
"end_index = start_index + count queryset = queryset[start_index : end_index] return Pagination( page=page,",
"results = data['results'] if self.pydantic_model is None: data['results'] = self.queryset_to_dict(results) else: _results =",
"int) is False: raise TypeError('\"count\" must be int') total = queryset.count() pages =",
"= start_index + count queryset = queryset[start_index : end_index] return Pagination( page=page, pages=pages,",
"math.ceil(total/count) start_index = (page - 1) * count end_index = start_index + count",
"self.queryset, 'total': self.total } @property def dict(self): data = self.data results = data['results']",
"id _d.append(field_data) return _d def pagination(queryset, page, count, pydantic_model=None): if isinstance(queryset, QuerySet) is",
"isinstance(page, int) is False: raise TypeError('\"page\" must be int') if isinstance(count, int) is",
"is False: raise TypeError('\"queryset\" must be Queryset') if isinstance(page, int) is False: raise",
"self.total = total self.pydantic_model = pydantic_model @property def data(self): return { 'page': self.page,",
"self.pages, 'results': self.queryset, 'total': self.total } @property def dict(self): data = self.data results",
"queryset_to_dict(self, queryset): data = serialize( 'json', queryset ) data = json.loads(data) _d =",
"TypeError('\"page\" must be int') if isinstance(count, int) is False: raise TypeError('\"count\" must be",
"!= '__all__': pages = math.ceil(total/count) start_index = (page - 1) * count end_index",
"data: id = x.pop('pk') field_data = x.pop('fields') field_data['id'] = id _d.append(field_data) return _d",
"'results': self.queryset, 'total': self.total } @property def dict(self): data = self.data results =",
"= id _d.append(field_data) return _d def pagination(queryset, page, count, pydantic_model=None): if isinstance(queryset, QuerySet)",
"pydantic_model=None): if isinstance(queryset, QuerySet) is False: raise TypeError('\"queryset\" must be Queryset') if isinstance(page,",
"queryset self.total = total self.pydantic_model = pydantic_model @property def data(self): return { 'page':",
"isinstance(count, int) is False: raise TypeError('\"count\" must be int') total = queryset.count() pages",
"= [] for x in data: id = x.pop('pk') field_data = x.pop('fields') field_data['id']",
"start_index + count queryset = queryset[start_index : end_index] return Pagination( page=page, pages=pages, queryset=queryset,",
"Pagination: def __init__( self, page=1, pages=1, queryset=QuerySet(), total=0, pydantic_model=None, ): self.page = page",
"* count end_index = start_index + count queryset = queryset[start_index : end_index] return",
"= [ 'dict', 'json', 'queryset' ] class Pagination: def __init__( self, page=1, pages=1,",
") data = json.loads(data) _d = [] for x in data: id =",
"@property def json(self): return json.dumps(self.dict) def queryset_to_dict(self, queryset): data = serialize( 'json', queryset",
"json(self): return json.dumps(self.dict) def queryset_to_dict(self, queryset): data = serialize( 'json', queryset ) data",
"if self.pydantic_model is None: data['results'] = self.queryset_to_dict(results) else: _results = [] for x",
"json.dumps(self.dict) def queryset_to_dict(self, queryset): data = serialize( 'json', queryset ) data = json.loads(data)",
"= math.ceil(total/count) start_index = (page - 1) * count end_index = start_index +",
"queryset=QuerySet(), total=0, pydantic_model=None, ): self.page = page self.pages = pages self.queryset = queryset",
"[] for x in self.pydantic_model.from_django(results, many=True): _results.append(x.dict()) data['results'] = _results return data @property",
"data = self.data results = data['results'] if self.pydantic_model is None: data['results'] = self.queryset_to_dict(results)",
"def json(self): return json.dumps(self.dict) def queryset_to_dict(self, queryset): data = serialize( 'json', queryset )",
"start_index = (page - 1) * count end_index = start_index + count queryset",
"= x.pop('fields') field_data['id'] = id _d.append(field_data) return _d def pagination(queryset, page, count, pydantic_model=None):",
"data['results'] if self.pydantic_model is None: data['results'] = self.queryset_to_dict(results) else: _results = [] for",
"= queryset.count() pages = 1 if count != '__all__': pages = math.ceil(total/count) start_index",
"self, page=1, pages=1, queryset=QuerySet(), total=0, pydantic_model=None, ): self.page = page self.pages = pages",
"for x in self.pydantic_model.from_django(results, many=True): _results.append(x.dict()) data['results'] = _results return data @property def",
"pages self.queryset = queryset self.total = total self.pydantic_model = pydantic_model @property def data(self):",
"x in data: id = x.pop('pk') field_data = x.pop('fields') field_data['id'] = id _d.append(field_data)",
"django.db.models.query import QuerySet ALLOWED_FORMATS = [ 'dict', 'json', 'queryset' ] class Pagination: def",
"return data @property def json(self): return json.dumps(self.dict) def queryset_to_dict(self, queryset): data = serialize(",
"page, count, pydantic_model=None): if isinstance(queryset, QuerySet) is False: raise TypeError('\"queryset\" must be Queryset')"
] |
[
"should, but that would mean asking for a translation would need to go",
"\"\"\" Information regarding the current user locale. TODO should this be its own",
"be its own extension? It seems like it should, but that would mean",
"should this be its own extension? It seems like it should, but that",
"for a translation would need to go through the event bus, and that",
"regarding the current user locale. TODO should this be its own extension? It",
"this be its own extension? It seems like it should, but that would",
"like it should, but that would mean asking for a translation would need",
"It seems like it should, but that would mean asking for a translation",
"a translation would need to go through the event bus, and that doesn't",
"its own extension? It seems like it should, but that would mean asking",
"extension? It seems like it should, but that would mean asking for a",
"seems like it should, but that would mean asking for a translation would",
"that would mean asking for a translation would need to go through the",
"the current user locale. TODO should this be its own extension? It seems",
"TODO should this be its own extension? It seems like it should, but",
"asking for a translation would need to go through the event bus, and",
"own extension? It seems like it should, but that would mean asking for",
"it should, but that would mean asking for a translation would need to",
"<filename>src/petronia/core/platform/api/locale/__init__.py \"\"\" Information regarding the current user locale. TODO should this be its",
"locale. TODO should this be its own extension? It seems like it should,",
"but that would mean asking for a translation would need to go through",
"user locale. TODO should this be its own extension? It seems like it",
"current user locale. TODO should this be its own extension? It seems like",
"mean asking for a translation would need to go through the event bus,",
"would need to go through the event bus, and that doesn't seem right.",
"need to go through the event bus, and that doesn't seem right. \"\"\"",
"Information regarding the current user locale. TODO should this be its own extension?",
"translation would need to go through the event bus, and that doesn't seem",
"would mean asking for a translation would need to go through the event"
] |
[
"%s\", jobs[0]) response = batch.describe_jobs(jobs=[jobs[0]]) logger.info(\"Job %s state is %s\", jobs[0], response['jobs'][0]['status']) if",
"readSamples(args.bamsheet) if samples is False: return -1 # We don't need the last",
"to the cache directory (because each job will need to determine what samples",
"x x x s5 x x x x Instead of visiting every cell,",
"O(n^2) comparisons, but really, we can do this in O(n log(n)). For example,",
"for sample in samples: meltedResults = \"%s/%s.meltedResults.txt\" % (args.s3_cache_folder, sample['name']) if meltedResults not",
"..., sample 5: s1 s2 s3 s4 s5 s1 s2 x s3 x",
"time import subprocess import sys from common import find_bucket_key, listFiles, readSamples, uploadFile __appname__",
"'--dry-run', default=False, action=\"store_true\", help=\"Simulate job submission\") required_args = parser.add_argument_group(\"Required\") required_args.add_argument('-b', '--bamsheet', required=True, help=\"Bamsheet\")",
"required_args.add_argument(\"-CD\", \"--s3_cache_folder\", required=True, help=\"Specify S3 path for cached VCF/TSV files\") job_args = parser.add_argument_group(\"AWS",
"= parseArguments(argv) logging.basicConfig(level=args.log_level) logger.info(\"%s v%s\" % (__appname__, __version__)) logger.info(args) batch = boto3.client('batch') samples",
"Script to compare genotypes Not every sample is going to have a meltedResults.txt.",
"\"--s3_cache_folder\", required=True, help=\"Specify S3 path for cached VCF/TSV files\") job_args = parser.add_argument_group(\"AWS Batch",
"--s3_cache_folder %s\", sample['name'], args.s3_cache_folder) else: response = batch.submit_job(jobName='compareGenotypes-%s' % sample['name'], jobQueue=args.job_queue, jobDefinition=args.job_definition, containerOverrides={'vcpus':",
"in AWS Batch\") job_args.add_argument('-q', \"--job-queue\", action=\"store\", default=\"ngs-job-queue\", help=\"AWS Batch Job Queue\") job_args.add_argument('-j', '--job-definition',",
"a set of samples') parser.add_argument('-l', '--log-level', help=\"Prints warnings to console by default\", default=\"INFO\",",
"help=\"AWS Batch Job Queue\") job_args.add_argument('-j', '--job-definition', action=\"store\", default=\"cohort-matcher:2\", help=\"AWS Batch Job Definition\") args",
"(because each job will need to determine what samples #to compare against based",
"containerOverrides={'vcpus': 1, 'command': ['/compareGenotypes.py', '-s', sample['name'], '--s3_cache_folder', args.s3_cache_folder]}) jobId = response['jobId'] jobs.append(jobId) logger.debug(response)",
"really, we can do this in O(n log(n)). For example, 5 samples, sample1,",
"cell, we only need to visit the ones with a X because the",
"job submission\") required_args = parser.add_argument_group(\"Required\") required_args.add_argument('-b', '--bamsheet', required=True, help=\"Bamsheet\") required_args.add_argument(\"-CD\", \"--s3_cache_folder\", required=True, help=\"Specify",
"the bamsheet) if not args.dry_run: uploadFile(args.bamsheet, \"%s/bamsheet.txt\" % args.s3_cache_folder) jobs = [] for",
"__version__)) logger.info(args) batch = boto3.client('batch') samples = readSamples(args.bamsheet) if samples is False: return",
"meltedResults not in meltedResultsFiles: logger.info(\"Comparing genotype of %s to other samples\", sample['name']) if",
"= parser.add_argument_group(\"Required\") required_args.add_argument('-b', '--bamsheet', required=True, help=\"Bamsheet\") required_args.add_argument(\"-CD\", \"--s3_cache_folder\", required=True, help=\"Specify S3 path for",
"suffix='.meltedResults.txt') # Upload the bamsheet to the cache directory (because each job will",
"sample is going to have a meltedResults.txt. For a list of samples (sample1,",
"AWS Batch\") job_args.add_argument('-q', \"--job-queue\", action=\"store\", default=\"ngs-job-queue\", help=\"AWS Batch Job Queue\") job_args.add_argument('-j', '--job-definition', action=\"store\",",
"meltedResultsFiles: logger.info(\"Comparing genotype of %s to other samples\", sample['name']) if args.local: cmd =",
"of samples') parser.add_argument('-l', '--log-level', help=\"Prints warnings to console by default\", default=\"INFO\", choices=[\"DEBUG\", \"INFO\",",
"parseArguments(argv): ''' Parse arguments ''' parser = argparse.ArgumentParser(description='Compare a set of samples') parser.add_argument('-l',",
"if args.local: cmd = [\"%s/compareGenotypes.py\" % os.path.dirname(__file__), \"-s\", sample['name'], \"--s3_cache_folder\", args.s3_cache_folder] if args.dry_run:",
"main(argv): ''' Main Entry Point ''' args = parseArguments(argv) logging.basicConfig(level=args.log_level) logger.info(\"%s v%s\" %",
"parser.add_argument('-l', '--log-level', help=\"Prints warnings to console by default\", default=\"INFO\", choices=[\"DEBUG\", \"INFO\", \"WARNING\", \"ERROR\"])",
"% (args.s3_cache_folder, sample['name']) if meltedResults not in meltedResultsFiles: logger.info(\"Comparing genotype of %s to",
"else: response = _run(cmd) else: if args.dry_run: logger.info(\"Would call batch.submit_job: compareGenotypes.py -s %s",
"samples') parser.add_argument('-l', '--log-level', help=\"Prints warnings to console by default\", default=\"INFO\", choices=[\"DEBUG\", \"INFO\", \"WARNING\",",
"need to visit the ones with a X because the matrix is symmetrical",
"directory (because each job will need to determine what samples #to compare against",
"logging.getLogger(__appname__) def _run(cmd): p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) out, err = p.communicate() p.wait()",
"= \"0.2\" logger = logging.getLogger(__appname__) def _run(cmd): p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) out,",
"''' Script to compare genotypes Not every sample is going to have a",
"secs\") time.sleep(60) logger.info(\"Checking job %s\", jobs[0]) response = batch.describe_jobs(jobs=[jobs[0]]) logger.info(\"Job %s state is",
"argparse.ArgumentParser(description='Compare a set of samples') parser.add_argument('-l', '--log-level', help=\"Prints warnings to console by default\",",
"return out def main(argv): ''' Main Entry Point ''' args = parseArguments(argv) logging.basicConfig(level=args.log_level)",
"default=\"cohort-matcher:2\", help=\"AWS Batch Job Definition\") args = parser.parse_args(argv) return args if __name__ ==",
"required=True, help=\"Specify S3 path for cached VCF/TSV files\") job_args = parser.add_argument_group(\"AWS Batch Job",
"parseArguments(argv) logging.basicConfig(level=args.log_level) logger.info(\"%s v%s\" % (__appname__, __version__)) logger.info(args) batch = boto3.client('batch') samples =",
"\"0.2\" logger = logging.getLogger(__appname__) def _run(cmd): p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) out, err",
"batch = boto3.client('batch') samples = readSamples(args.bamsheet) if samples is False: return -1 #",
"logger.info(\"Sleeping 60 secs\") time.sleep(60) logger.info(\"Checking job %s\", jobs[0]) response = batch.describe_jobs(jobs=[jobs[0]]) logger.info(\"Job %s",
"if meltedResults not in meltedResultsFiles: logger.info(\"Comparing genotype of %s to other samples\", sample['name'])",
"logging.basicConfig(level=args.log_level) logger.info(\"%s v%s\" % (__appname__, __version__)) logger.info(args) batch = boto3.client('batch') samples = readSamples(args.bamsheet)",
"genotype of %s to other samples\", sample['name']) if args.local: cmd = [\"%s/compareGenotypes.py\" %",
"default=False, action=\"store_true\", help=\"Simulate job submission\") required_args = parser.add_argument_group(\"Required\") required_args.add_argument('-b', '--bamsheet', required=True, help=\"Bamsheet\") required_args.add_argument(\"-CD\",",
"a list of samples (sample1, ..., sampleN), an all v all nieve approach",
"help=\"AWS Batch Job Definition\") args = parser.parse_args(argv) return args if __name__ == '__main__':",
"= listFiles(args.s3_cache_folder, suffix='.meltedResults.txt') # Upload the bamsheet to the cache directory (because each",
"in the list so let's remove it samples.pop() # Get a list of",
"logger.info(\"Would call batch.submit_job: compareGenotypes.py -s %s --s3_cache_folder %s\", sample['name'], args.s3_cache_folder) else: response =",
"failed_jobs = [] while jobs: logger.info(\"Sleeping 60 secs\") time.sleep(60) logger.info(\"Checking job %s\", jobs[0])",
"sample['name']) if meltedResults not in meltedResultsFiles: logger.info(\"Comparing genotype of %s to other samples\",",
"going to have a meltedResults.txt. For a list of samples (sample1, ..., sampleN),",
"logger.info(args) batch = boto3.client('batch') samples = readSamples(args.bamsheet) if samples is False: return -1",
"call %s\", cmd) else: response = _run(cmd) else: if args.dry_run: logger.info(\"Would call batch.submit_job:",
"= argparse.ArgumentParser(description='Compare a set of samples') parser.add_argument('-l', '--log-level', help=\"Prints warnings to console by",
"symmetrical about the axis ''' import argparse import boto3 import logging import os",
"len(failed_jobs)) def parseArguments(argv): ''' Parse arguments ''' parser = argparse.ArgumentParser(description='Compare a set of",
"boto3.client('batch') samples = readSamples(args.bamsheet) if samples is False: return -1 # We don't",
"s1 s2 s3 s4 s5 s1 s2 x s3 x x s4 x",
"readSamples, uploadFile __appname__ = 'compareSamples' __version__ = \"0.2\" logger = logging.getLogger(__appname__) def _run(cmd):",
"of in AWS Batch\") job_args.add_argument('-q', \"--job-queue\", action=\"store\", default=\"ngs-job-queue\", help=\"AWS Batch Job Queue\") job_args.add_argument('-j',",
"len(completed_jobs)) logger.info(\"Failed: %s\", len(failed_jobs)) def parseArguments(argv): ''' Parse arguments ''' parser = argparse.ArgumentParser(description='Compare",
"cache directory (because each job will need to determine what samples #to compare",
"help=\"Simulate job submission\") required_args = parser.add_argument_group(\"Required\") required_args.add_argument('-b', '--bamsheet', required=True, help=\"Bamsheet\") required_args.add_argument(\"-CD\", \"--s3_cache_folder\", required=True,",
"= [] failed_jobs = [] while jobs: logger.info(\"Sleeping 60 secs\") time.sleep(60) logger.info(\"Checking job",
"x Instead of visiting every cell, we only need to visit the ones",
"0: return err return out def main(argv): ''' Main Entry Point ''' args",
"all nieve approach would require O(n^2) comparisons, but really, we can do this",
"not in meltedResultsFiles: logger.info(\"Comparing genotype of %s to other samples\", sample['name']) if args.local:",
"import argparse import boto3 import logging import os import time import subprocess import",
"call batch.submit_job: compareGenotypes.py -s %s --s3_cache_folder %s\", sample['name'], args.s3_cache_folder) else: response = batch.submit_job(jobName='compareGenotypes-%s'",
"os.path.dirname(__file__), \"-s\", sample['name'], \"--s3_cache_folder\", args.s3_cache_folder] if args.dry_run: logger.info(\"Would call %s\", cmd) else: response",
"samples (sample1, ..., sampleN), an all v all nieve approach would require O(n^2)",
"= [] while jobs: logger.info(\"Sleeping 60 secs\") time.sleep(60) logger.info(\"Checking job %s\", jobs[0]) response",
"sample1, ..., sample 5: s1 s2 s3 s4 s5 s1 s2 x s3",
"to visit the ones with a X because the matrix is symmetrical about",
"all v all nieve approach would require O(n^2) comparisons, but really, we can",
"from common import find_bucket_key, listFiles, readSamples, uploadFile __appname__ = 'compareSamples' __version__ = \"0.2\"",
"'--s3_cache_folder', args.s3_cache_folder]}) jobId = response['jobId'] jobs.append(jobId) logger.debug(response) logger.info(\"Submitted %s jobs\", len(jobs)) completed_jobs =",
"remove it samples.pop() # Get a list of meltedResults files meltedResultsFiles = listFiles(args.s3_cache_folder,",
"based on its order in the bamsheet) if not args.dry_run: uploadFile(args.bamsheet, \"%s/bamsheet.txt\" %",
"parser.add_argument_group(\"AWS Batch Job Settings\") job_args.add_argument('--local', action=\"store_true\", default=False, help=\"Run locally instead of in AWS",
"argparse import boto3 import logging import os import time import subprocess import sys",
"v all nieve approach would require O(n^2) comparisons, but really, we can do",
"it samples.pop() # Get a list of meltedResults files meltedResultsFiles = listFiles(args.s3_cache_folder, suffix='.meltedResults.txt')",
"Settings\") job_args.add_argument('--local', action=\"store_true\", default=False, help=\"Run locally instead of in AWS Batch\") job_args.add_argument('-q', \"--job-queue\",",
"#!/usr/bin/env python ''' Script to compare genotypes Not every sample is going to",
"parser.add_argument_group(\"Required\") required_args.add_argument('-b', '--bamsheet', required=True, help=\"Bamsheet\") required_args.add_argument(\"-CD\", \"--s3_cache_folder\", required=True, help=\"Specify S3 path for cached",
"'compareSamples' __version__ = \"0.2\" logger = logging.getLogger(__appname__) def _run(cmd): p = subprocess.Popen(cmd, stdout=subprocess.PIPE,",
"determine what samples #to compare against based on its order in the bamsheet)",
"an all v all nieve approach would require O(n^2) comparisons, but really, we",
"do this in O(n log(n)). For example, 5 samples, sample1, ..., sample 5:",
"would require O(n^2) comparisons, but really, we can do this in O(n log(n)).",
"= readSamples(args.bamsheet) if samples is False: return -1 # We don't need the",
"other samples\", sample['name']) if args.local: cmd = [\"%s/compareGenotypes.py\" % os.path.dirname(__file__), \"-s\", sample['name'], \"--s3_cache_folder\",",
"instead of in AWS Batch\") job_args.add_argument('-q', \"--job-queue\", action=\"store\", default=\"ngs-job-queue\", help=\"AWS Batch Job Queue\")",
"x x x Instead of visiting every cell, we only need to visit",
"def main(argv): ''' Main Entry Point ''' args = parseArguments(argv) logging.basicConfig(level=args.log_level) logger.info(\"%s v%s\"",
"%s\", len(completed_jobs)) logger.info(\"Failed: %s\", len(failed_jobs)) def parseArguments(argv): ''' Parse arguments ''' parser =",
"%s to other samples\", sample['name']) if args.local: cmd = [\"%s/compareGenotypes.py\" % os.path.dirname(__file__), \"-s\",",
"help=\"Bamsheet\") required_args.add_argument(\"-CD\", \"--s3_cache_folder\", required=True, help=\"Specify S3 path for cached VCF/TSV files\") job_args =",
"import sys from common import find_bucket_key, listFiles, readSamples, uploadFile __appname__ = 'compareSamples' __version__",
"import logging import os import time import subprocess import sys from common import",
"= p.communicate() p.wait() if p.returncode != 0: return err return out def main(argv):",
"listFiles, readSamples, uploadFile __appname__ = 'compareSamples' __version__ = \"0.2\" logger = logging.getLogger(__appname__) def",
"\"WARNING\", \"ERROR\"]) parser.add_argument('-d', '--dry-run', default=False, action=\"store_true\", help=\"Simulate job submission\") required_args = parser.add_argument_group(\"Required\") required_args.add_argument('-b',",
"logger.info(\"Successed: %s\", len(completed_jobs)) logger.info(\"Failed: %s\", len(failed_jobs)) def parseArguments(argv): ''' Parse arguments ''' parser",
"logger.info(\"Checking job %s\", jobs[0]) response = batch.describe_jobs(jobs=[jobs[0]]) logger.info(\"Job %s state is %s\", jobs[0],",
"but really, we can do this in O(n log(n)). For example, 5 samples,",
"help=\"Prints warnings to console by default\", default=\"INFO\", choices=[\"DEBUG\", \"INFO\", \"WARNING\", \"ERROR\"]) parser.add_argument('-d', '--dry-run',",
"last sample in the list so let's remove it samples.pop() # Get a",
"= [] for sample in samples: meltedResults = \"%s/%s.meltedResults.txt\" % (args.s3_cache_folder, sample['name']) if",
"VCF/TSV files\") job_args = parser.add_argument_group(\"AWS Batch Job Settings\") job_args.add_argument('--local', action=\"store_true\", default=False, help=\"Run locally",
"jobs.append(jobId) logger.debug(response) logger.info(\"Submitted %s jobs\", len(jobs)) completed_jobs = [] failed_jobs = [] while",
"Job Settings\") job_args.add_argument('--local', action=\"store_true\", default=False, help=\"Run locally instead of in AWS Batch\") job_args.add_argument('-q',",
"sample['name']) if args.local: cmd = [\"%s/compareGenotypes.py\" % os.path.dirname(__file__), \"-s\", sample['name'], \"--s3_cache_folder\", args.s3_cache_folder] if",
"% os.path.dirname(__file__), \"-s\", sample['name'], \"--s3_cache_folder\", args.s3_cache_folder] if args.dry_run: logger.info(\"Would call %s\", cmd) else:",
"60 secs\") time.sleep(60) logger.info(\"Checking job %s\", jobs[0]) response = batch.describe_jobs(jobs=[jobs[0]]) logger.info(\"Job %s state",
"logger.info(\"Would call %s\", cmd) else: response = _run(cmd) else: if args.dry_run: logger.info(\"Would call",
"elif response['jobs'][0]['status'] == 'FAILED': failed_jobs.append(jobs.pop()) logger.info(\"Successed: %s\", len(completed_jobs)) logger.info(\"Failed: %s\", len(failed_jobs)) def parseArguments(argv):",
"listFiles(args.s3_cache_folder, suffix='.meltedResults.txt') # Upload the bamsheet to the cache directory (because each job",
"args.dry_run: logger.info(\"Would call batch.submit_job: compareGenotypes.py -s %s --s3_cache_folder %s\", sample['name'], args.s3_cache_folder) else: response",
"is going to have a meltedResults.txt. For a list of samples (sample1, ...,",
"stderr=subprocess.PIPE) out, err = p.communicate() p.wait() if p.returncode != 0: return err return",
"logger.info(\"%s v%s\" % (__appname__, __version__)) logger.info(args) batch = boto3.client('batch') samples = readSamples(args.bamsheet) if",
"meltedResults files meltedResultsFiles = listFiles(args.s3_cache_folder, suffix='.meltedResults.txt') # Upload the bamsheet to the cache",
"jobs\", len(jobs)) completed_jobs = [] failed_jobs = [] while jobs: logger.info(\"Sleeping 60 secs\")",
"''' import argparse import boto3 import logging import os import time import subprocess",
"%s\", len(failed_jobs)) def parseArguments(argv): ''' Parse arguments ''' parser = argparse.ArgumentParser(description='Compare a set",
"stdout=subprocess.PIPE, stderr=subprocess.PIPE) out, err = p.communicate() p.wait() if p.returncode != 0: return err",
"return err return out def main(argv): ''' Main Entry Point ''' args =",
"jobs: logger.info(\"Sleeping 60 secs\") time.sleep(60) logger.info(\"Checking job %s\", jobs[0]) response = batch.describe_jobs(jobs=[jobs[0]]) logger.info(\"Job",
"to other samples\", sample['name']) if args.local: cmd = [\"%s/compareGenotypes.py\" % os.path.dirname(__file__), \"-s\", sample['name'],",
"[\"%s/compareGenotypes.py\" % os.path.dirname(__file__), \"-s\", sample['name'], \"--s3_cache_folder\", args.s3_cache_folder] if args.dry_run: logger.info(\"Would call %s\", cmd)",
"response['jobs'][0]['status']) if response['jobs'][0]['status'] == 'SUCCEEDED': completed_jobs.append(jobs.pop()) elif response['jobs'][0]['status'] == 'FAILED': failed_jobs.append(jobs.pop()) logger.info(\"Successed: %s\",",
"= subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) out, err = p.communicate() p.wait() if p.returncode != 0:",
"the list so let's remove it samples.pop() # Get a list of meltedResults",
"O(n log(n)). For example, 5 samples, sample1, ..., sample 5: s1 s2 s3",
"if p.returncode != 0: return err return out def main(argv): ''' Main Entry",
"err return out def main(argv): ''' Main Entry Point ''' args = parseArguments(argv)",
"\"ERROR\"]) parser.add_argument('-d', '--dry-run', default=False, action=\"store_true\", help=\"Simulate job submission\") required_args = parser.add_argument_group(\"Required\") required_args.add_argument('-b', '--bamsheet',",
"[] failed_jobs = [] while jobs: logger.info(\"Sleeping 60 secs\") time.sleep(60) logger.info(\"Checking job %s\",",
"_run(cmd): p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) out, err = p.communicate() p.wait() if p.returncode",
"= [\"%s/compareGenotypes.py\" % os.path.dirname(__file__), \"-s\", sample['name'], \"--s3_cache_folder\", args.s3_cache_folder] if args.dry_run: logger.info(\"Would call %s\",",
"so let's remove it samples.pop() # Get a list of meltedResults files meltedResultsFiles",
"completed_jobs = [] failed_jobs = [] while jobs: logger.info(\"Sleeping 60 secs\") time.sleep(60) logger.info(\"Checking",
"meltedResultsFiles = listFiles(args.s3_cache_folder, suffix='.meltedResults.txt') # Upload the bamsheet to the cache directory (because",
"<reponame>golharam/bam-matcher #!/usr/bin/env python ''' Script to compare genotypes Not every sample is going",
"out def main(argv): ''' Main Entry Point ''' args = parseArguments(argv) logging.basicConfig(level=args.log_level) logger.info(\"%s",
"job %s\", jobs[0]) response = batch.describe_jobs(jobs=[jobs[0]]) logger.info(\"Job %s state is %s\", jobs[0], response['jobs'][0]['status'])",
"Get a list of meltedResults files meltedResultsFiles = listFiles(args.s3_cache_folder, suffix='.meltedResults.txt') # Upload the",
"else: response = batch.submit_job(jobName='compareGenotypes-%s' % sample['name'], jobQueue=args.job_queue, jobDefinition=args.job_definition, containerOverrides={'vcpus': 1, 'command': ['/compareGenotypes.py', '-s',",
"action=\"store\", default=\"cohort-matcher:2\", help=\"AWS Batch Job Definition\") args = parser.parse_args(argv) return args if __name__",
"args.s3_cache_folder) else: response = batch.submit_job(jobName='compareGenotypes-%s' % sample['name'], jobQueue=args.job_queue, jobDefinition=args.job_definition, containerOverrides={'vcpus': 1, 'command': ['/compareGenotypes.py',",
"if samples is False: return -1 # We don't need the last sample",
"bamsheet) if not args.dry_run: uploadFile(args.bamsheet, \"%s/bamsheet.txt\" % args.s3_cache_folder) jobs = [] for sample",
"For a list of samples (sample1, ..., sampleN), an all v all nieve",
"log(n)). For example, 5 samples, sample1, ..., sample 5: s1 s2 s3 s4",
"need to determine what samples #to compare against based on its order in",
"'--log-level', help=\"Prints warnings to console by default\", default=\"INFO\", choices=[\"DEBUG\", \"INFO\", \"WARNING\", \"ERROR\"]) parser.add_argument('-d',",
"import subprocess import sys from common import find_bucket_key, listFiles, readSamples, uploadFile __appname__ =",
"boto3 import logging import os import time import subprocess import sys from common",
"we only need to visit the ones with a X because the matrix",
"= parser.add_argument_group(\"AWS Batch Job Settings\") job_args.add_argument('--local', action=\"store_true\", default=False, help=\"Run locally instead of in",
"samples is False: return -1 # We don't need the last sample in",
"to determine what samples #to compare against based on its order in the",
"sample['name'], jobQueue=args.job_queue, jobDefinition=args.job_definition, containerOverrides={'vcpus': 1, 'command': ['/compareGenotypes.py', '-s', sample['name'], '--s3_cache_folder', args.s3_cache_folder]}) jobId =",
"have a meltedResults.txt. For a list of samples (sample1, ..., sampleN), an all",
"5: s1 s2 s3 s4 s5 s1 s2 x s3 x x s4",
"this in O(n log(n)). For example, 5 samples, sample1, ..., sample 5: s1",
"p.communicate() p.wait() if p.returncode != 0: return err return out def main(argv): '''",
"uploadFile(args.bamsheet, \"%s/bamsheet.txt\" % args.s3_cache_folder) jobs = [] for sample in samples: meltedResults =",
"args = parseArguments(argv) logging.basicConfig(level=args.log_level) logger.info(\"%s v%s\" % (__appname__, __version__)) logger.info(args) batch = boto3.client('batch')",
"choices=[\"DEBUG\", \"INFO\", \"WARNING\", \"ERROR\"]) parser.add_argument('-d', '--dry-run', default=False, action=\"store_true\", help=\"Simulate job submission\") required_args =",
"subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) out, err = p.communicate() p.wait() if p.returncode != 0: return",
"sample in the list so let's remove it samples.pop() # Get a list",
"time.sleep(60) logger.info(\"Checking job %s\", jobs[0]) response = batch.describe_jobs(jobs=[jobs[0]]) logger.info(\"Job %s state is %s\",",
"about the axis ''' import argparse import boto3 import logging import os import",
"sample in samples: meltedResults = \"%s/%s.meltedResults.txt\" % (args.s3_cache_folder, sample['name']) if meltedResults not in",
"cmd = [\"%s/compareGenotypes.py\" % os.path.dirname(__file__), \"-s\", sample['name'], \"--s3_cache_folder\", args.s3_cache_folder] if args.dry_run: logger.info(\"Would call",
"__appname__ = 'compareSamples' __version__ = \"0.2\" logger = logging.getLogger(__appname__) def _run(cmd): p =",
"For example, 5 samples, sample1, ..., sample 5: s1 s2 s3 s4 s5",
"X because the matrix is symmetrical about the axis ''' import argparse import",
"jobs = [] for sample in samples: meltedResults = \"%s/%s.meltedResults.txt\" % (args.s3_cache_folder, sample['name'])",
"= logging.getLogger(__appname__) def _run(cmd): p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) out, err = p.communicate()",
"!= 0: return err return out def main(argv): ''' Main Entry Point '''",
"compare genotypes Not every sample is going to have a meltedResults.txt. For a",
"jobQueue=args.job_queue, jobDefinition=args.job_definition, containerOverrides={'vcpus': 1, 'command': ['/compareGenotypes.py', '-s', sample['name'], '--s3_cache_folder', args.s3_cache_folder]}) jobId = response['jobId']",
"s3 x x s4 x x x s5 x x x x Instead",
"# Upload the bamsheet to the cache directory (because each job will need",
"of samples (sample1, ..., sampleN), an all v all nieve approach would require",
"is %s\", jobs[0], response['jobs'][0]['status']) if response['jobs'][0]['status'] == 'SUCCEEDED': completed_jobs.append(jobs.pop()) elif response['jobs'][0]['status'] == 'FAILED':",
"s5 x x x x Instead of visiting every cell, we only need",
"import find_bucket_key, listFiles, readSamples, uploadFile __appname__ = 'compareSamples' __version__ = \"0.2\" logger =",
"jobs[0]) response = batch.describe_jobs(jobs=[jobs[0]]) logger.info(\"Job %s state is %s\", jobs[0], response['jobs'][0]['status']) if response['jobs'][0]['status']",
"logger.info(\"Submitted %s jobs\", len(jobs)) completed_jobs = [] failed_jobs = [] while jobs: logger.info(\"Sleeping",
"'SUCCEEDED': completed_jobs.append(jobs.pop()) elif response['jobs'][0]['status'] == 'FAILED': failed_jobs.append(jobs.pop()) logger.info(\"Successed: %s\", len(completed_jobs)) logger.info(\"Failed: %s\", len(failed_jobs))",
"Point ''' args = parseArguments(argv) logging.basicConfig(level=args.log_level) logger.info(\"%s v%s\" % (__appname__, __version__)) logger.info(args) batch",
"logger = logging.getLogger(__appname__) def _run(cmd): p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) out, err =",
"visiting every cell, we only need to visit the ones with a X",
"#to compare against based on its order in the bamsheet) if not args.dry_run:",
"ones with a X because the matrix is symmetrical about the axis '''",
"required_args = parser.add_argument_group(\"Required\") required_args.add_argument('-b', '--bamsheet', required=True, help=\"Bamsheet\") required_args.add_argument(\"-CD\", \"--s3_cache_folder\", required=True, help=\"Specify S3 path",
"..., sampleN), an all v all nieve approach would require O(n^2) comparisons, but",
"Entry Point ''' args = parseArguments(argv) logging.basicConfig(level=args.log_level) logger.info(\"%s v%s\" % (__appname__, __version__)) logger.info(args)",
"%s\", jobs[0], response['jobs'][0]['status']) if response['jobs'][0]['status'] == 'SUCCEEDED': completed_jobs.append(jobs.pop()) elif response['jobs'][0]['status'] == 'FAILED': failed_jobs.append(jobs.pop())",
"'-s', sample['name'], '--s3_cache_folder', args.s3_cache_folder]}) jobId = response['jobId'] jobs.append(jobId) logger.debug(response) logger.info(\"Submitted %s jobs\", len(jobs))",
"p.wait() if p.returncode != 0: return err return out def main(argv): ''' Main",
"s3 s4 s5 s1 s2 x s3 x x s4 x x x",
"We don't need the last sample in the list so let's remove it",
"job_args.add_argument('-q', \"--job-queue\", action=\"store\", default=\"ngs-job-queue\", help=\"AWS Batch Job Queue\") job_args.add_argument('-j', '--job-definition', action=\"store\", default=\"cohort-matcher:2\", help=\"AWS",
"len(jobs)) completed_jobs = [] failed_jobs = [] while jobs: logger.info(\"Sleeping 60 secs\") time.sleep(60)",
"because the matrix is symmetrical about the axis ''' import argparse import boto3",
"args.local: cmd = [\"%s/compareGenotypes.py\" % os.path.dirname(__file__), \"-s\", sample['name'], \"--s3_cache_folder\", args.s3_cache_folder] if args.dry_run: logger.info(\"Would",
"-1 # We don't need the last sample in the list so let's",
"required_args.add_argument('-b', '--bamsheet', required=True, help=\"Bamsheet\") required_args.add_argument(\"-CD\", \"--s3_cache_folder\", required=True, help=\"Specify S3 path for cached VCF/TSV",
"with a X because the matrix is symmetrical about the axis ''' import",
"files\") job_args = parser.add_argument_group(\"AWS Batch Job Settings\") job_args.add_argument('--local', action=\"store_true\", default=False, help=\"Run locally instead",
"genotypes Not every sample is going to have a meltedResults.txt. For a list",
"''' parser = argparse.ArgumentParser(description='Compare a set of samples') parser.add_argument('-l', '--log-level', help=\"Prints warnings to",
"bamsheet to the cache directory (because each job will need to determine what",
"parser = argparse.ArgumentParser(description='Compare a set of samples') parser.add_argument('-l', '--log-level', help=\"Prints warnings to console",
"the matrix is symmetrical about the axis ''' import argparse import boto3 import",
"by default\", default=\"INFO\", choices=[\"DEBUG\", \"INFO\", \"WARNING\", \"ERROR\"]) parser.add_argument('-d', '--dry-run', default=False, action=\"store_true\", help=\"Simulate job",
"only need to visit the ones with a X because the matrix is",
"= 'compareSamples' __version__ = \"0.2\" logger = logging.getLogger(__appname__) def _run(cmd): p = subprocess.Popen(cmd,",
"(__appname__, __version__)) logger.info(args) batch = boto3.client('batch') samples = readSamples(args.bamsheet) if samples is False:",
"console by default\", default=\"INFO\", choices=[\"DEBUG\", \"INFO\", \"WARNING\", \"ERROR\"]) parser.add_argument('-d', '--dry-run', default=False, action=\"store_true\", help=\"Simulate",
"find_bucket_key, listFiles, readSamples, uploadFile __appname__ = 'compareSamples' __version__ = \"0.2\" logger = logging.getLogger(__appname__)",
"args.s3_cache_folder]}) jobId = response['jobId'] jobs.append(jobId) logger.debug(response) logger.info(\"Submitted %s jobs\", len(jobs)) completed_jobs = []",
"the cache directory (because each job will need to determine what samples #to",
"samples, sample1, ..., sample 5: s1 s2 s3 s4 s5 s1 s2 x",
"response = batch.describe_jobs(jobs=[jobs[0]]) logger.info(\"Job %s state is %s\", jobs[0], response['jobs'][0]['status']) if response['jobs'][0]['status'] ==",
"comparisons, but really, we can do this in O(n log(n)). For example, 5",
"response = _run(cmd) else: if args.dry_run: logger.info(\"Would call batch.submit_job: compareGenotypes.py -s %s --s3_cache_folder",
"\"INFO\", \"WARNING\", \"ERROR\"]) parser.add_argument('-d', '--dry-run', default=False, action=\"store_true\", help=\"Simulate job submission\") required_args = parser.add_argument_group(\"Required\")",
"meltedResults.txt. For a list of samples (sample1, ..., sampleN), an all v all",
"for cached VCF/TSV files\") job_args = parser.add_argument_group(\"AWS Batch Job Settings\") job_args.add_argument('--local', action=\"store_true\", default=False,",
"required=True, help=\"Bamsheet\") required_args.add_argument(\"-CD\", \"--s3_cache_folder\", required=True, help=\"Specify S3 path for cached VCF/TSV files\") job_args",
"batch.submit_job(jobName='compareGenotypes-%s' % sample['name'], jobQueue=args.job_queue, jobDefinition=args.job_definition, containerOverrides={'vcpus': 1, 'command': ['/compareGenotypes.py', '-s', sample['name'], '--s3_cache_folder', args.s3_cache_folder]})",
"action=\"store_true\", help=\"Simulate job submission\") required_args = parser.add_argument_group(\"Required\") required_args.add_argument('-b', '--bamsheet', required=True, help=\"Bamsheet\") required_args.add_argument(\"-CD\", \"--s3_cache_folder\",",
"sys from common import find_bucket_key, listFiles, readSamples, uploadFile __appname__ = 'compareSamples' __version__ =",
"to have a meltedResults.txt. For a list of samples (sample1, ..., sampleN), an",
"a X because the matrix is symmetrical about the axis ''' import argparse",
"logging import os import time import subprocess import sys from common import find_bucket_key,",
"state is %s\", jobs[0], response['jobs'][0]['status']) if response['jobs'][0]['status'] == 'SUCCEEDED': completed_jobs.append(jobs.pop()) elif response['jobs'][0]['status'] ==",
"compareGenotypes.py -s %s --s3_cache_folder %s\", sample['name'], args.s3_cache_folder) else: response = batch.submit_job(jobName='compareGenotypes-%s' % sample['name'],",
"failed_jobs.append(jobs.pop()) logger.info(\"Successed: %s\", len(completed_jobs)) logger.info(\"Failed: %s\", len(failed_jobs)) def parseArguments(argv): ''' Parse arguments '''",
"if args.dry_run: logger.info(\"Would call batch.submit_job: compareGenotypes.py -s %s --s3_cache_folder %s\", sample['name'], args.s3_cache_folder) else:",
"s4 s5 s1 s2 x s3 x x s4 x x x s5",
"= \"%s/%s.meltedResults.txt\" % (args.s3_cache_folder, sample['name']) if meltedResults not in meltedResultsFiles: logger.info(\"Comparing genotype of",
"in samples: meltedResults = \"%s/%s.meltedResults.txt\" % (args.s3_cache_folder, sample['name']) if meltedResults not in meltedResultsFiles:",
"def _run(cmd): p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) out, err = p.communicate() p.wait() if",
"\"-s\", sample['name'], \"--s3_cache_folder\", args.s3_cache_folder] if args.dry_run: logger.info(\"Would call %s\", cmd) else: response =",
"if args.dry_run: logger.info(\"Would call %s\", cmd) else: response = _run(cmd) else: if args.dry_run:",
"approach would require O(n^2) comparisons, but really, we can do this in O(n",
"v%s\" % (__appname__, __version__)) logger.info(args) batch = boto3.client('batch') samples = readSamples(args.bamsheet) if samples",
"Main Entry Point ''' args = parseArguments(argv) logging.basicConfig(level=args.log_level) logger.info(\"%s v%s\" % (__appname__, __version__))",
"list of meltedResults files meltedResultsFiles = listFiles(args.s3_cache_folder, suffix='.meltedResults.txt') # Upload the bamsheet to",
"to compare genotypes Not every sample is going to have a meltedResults.txt. For",
"args.dry_run: uploadFile(args.bamsheet, \"%s/bamsheet.txt\" % args.s3_cache_folder) jobs = [] for sample in samples: meltedResults",
"Parse arguments ''' parser = argparse.ArgumentParser(description='Compare a set of samples') parser.add_argument('-l', '--log-level', help=\"Prints",
"the last sample in the list so let's remove it samples.pop() # Get",
"%s jobs\", len(jobs)) completed_jobs = [] failed_jobs = [] while jobs: logger.info(\"Sleeping 60",
"common import find_bucket_key, listFiles, readSamples, uploadFile __appname__ = 'compareSamples' __version__ = \"0.2\" logger",
"is False: return -1 # We don't need the last sample in the",
"# We don't need the last sample in the list so let's remove",
"every sample is going to have a meltedResults.txt. For a list of samples",
"default=\"ngs-job-queue\", help=\"AWS Batch Job Queue\") job_args.add_argument('-j', '--job-definition', action=\"store\", default=\"cohort-matcher:2\", help=\"AWS Batch Job Definition\")",
"= response['jobId'] jobs.append(jobId) logger.debug(response) logger.info(\"Submitted %s jobs\", len(jobs)) completed_jobs = [] failed_jobs =",
"p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) out, err = p.communicate() p.wait() if p.returncode !=",
"is symmetrical about the axis ''' import argparse import boto3 import logging import",
"axis ''' import argparse import boto3 import logging import os import time import",
"__version__ = \"0.2\" logger = logging.getLogger(__appname__) def _run(cmd): p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)",
"job_args.add_argument('--local', action=\"store_true\", default=False, help=\"Run locally instead of in AWS Batch\") job_args.add_argument('-q', \"--job-queue\", action=\"store\",",
"batch.describe_jobs(jobs=[jobs[0]]) logger.info(\"Job %s state is %s\", jobs[0], response['jobs'][0]['status']) if response['jobs'][0]['status'] == 'SUCCEEDED': completed_jobs.append(jobs.pop())",
"['/compareGenotypes.py', '-s', sample['name'], '--s3_cache_folder', args.s3_cache_folder]}) jobId = response['jobId'] jobs.append(jobId) logger.debug(response) logger.info(\"Submitted %s jobs\",",
"let's remove it samples.pop() # Get a list of meltedResults files meltedResultsFiles =",
"(args.s3_cache_folder, sample['name']) if meltedResults not in meltedResultsFiles: logger.info(\"Comparing genotype of %s to other",
"logger.debug(response) logger.info(\"Submitted %s jobs\", len(jobs)) completed_jobs = [] failed_jobs = [] while jobs:",
"submission\") required_args = parser.add_argument_group(\"Required\") required_args.add_argument('-b', '--bamsheet', required=True, help=\"Bamsheet\") required_args.add_argument(\"-CD\", \"--s3_cache_folder\", required=True, help=\"Specify S3",
"action=\"store\", default=\"ngs-job-queue\", help=\"AWS Batch Job Queue\") job_args.add_argument('-j', '--job-definition', action=\"store\", default=\"cohort-matcher:2\", help=\"AWS Batch Job",
"Not every sample is going to have a meltedResults.txt. For a list of",
"uploadFile __appname__ = 'compareSamples' __version__ = \"0.2\" logger = logging.getLogger(__appname__) def _run(cmd): p",
"S3 path for cached VCF/TSV files\") job_args = parser.add_argument_group(\"AWS Batch Job Settings\") job_args.add_argument('--local',",
"each job will need to determine what samples #to compare against based on",
"s4 x x x s5 x x x x Instead of visiting every",
"= boto3.client('batch') samples = readSamples(args.bamsheet) if samples is False: return -1 # We",
"while jobs: logger.info(\"Sleeping 60 secs\") time.sleep(60) logger.info(\"Checking job %s\", jobs[0]) response = batch.describe_jobs(jobs=[jobs[0]])",
"args.s3_cache_folder) jobs = [] for sample in samples: meltedResults = \"%s/%s.meltedResults.txt\" % (args.s3_cache_folder,",
"samples #to compare against based on its order in the bamsheet) if not",
"against based on its order in the bamsheet) if not args.dry_run: uploadFile(args.bamsheet, \"%s/bamsheet.txt\"",
"of %s to other samples\", sample['name']) if args.local: cmd = [\"%s/compareGenotypes.py\" % os.path.dirname(__file__),",
"== 'SUCCEEDED': completed_jobs.append(jobs.pop()) elif response['jobs'][0]['status'] == 'FAILED': failed_jobs.append(jobs.pop()) logger.info(\"Successed: %s\", len(completed_jobs)) logger.info(\"Failed: %s\",",
"\"--s3_cache_folder\", args.s3_cache_folder] if args.dry_run: logger.info(\"Would call %s\", cmd) else: response = _run(cmd) else:",
"list so let's remove it samples.pop() # Get a list of meltedResults files",
"compare against based on its order in the bamsheet) if not args.dry_run: uploadFile(args.bamsheet,",
"response['jobId'] jobs.append(jobId) logger.debug(response) logger.info(\"Submitted %s jobs\", len(jobs)) completed_jobs = [] failed_jobs = []",
"response['jobs'][0]['status'] == 'FAILED': failed_jobs.append(jobs.pop()) logger.info(\"Successed: %s\", len(completed_jobs)) logger.info(\"Failed: %s\", len(failed_jobs)) def parseArguments(argv): '''",
"subprocess import sys from common import find_bucket_key, listFiles, readSamples, uploadFile __appname__ = 'compareSamples'",
"s5 s1 s2 x s3 x x s4 x x x s5 x",
"every cell, we only need to visit the ones with a X because",
"logger.info(\"Failed: %s\", len(failed_jobs)) def parseArguments(argv): ''' Parse arguments ''' parser = argparse.ArgumentParser(description='Compare a",
"Batch\") job_args.add_argument('-q', \"--job-queue\", action=\"store\", default=\"ngs-job-queue\", help=\"AWS Batch Job Queue\") job_args.add_argument('-j', '--job-definition', action=\"store\", default=\"cohort-matcher:2\",",
"require O(n^2) comparisons, but really, we can do this in O(n log(n)). For",
"Job Queue\") job_args.add_argument('-j', '--job-definition', action=\"store\", default=\"cohort-matcher:2\", help=\"AWS Batch Job Definition\") args = parser.parse_args(argv)",
"path for cached VCF/TSV files\") job_args = parser.add_argument_group(\"AWS Batch Job Settings\") job_args.add_argument('--local', action=\"store_true\",",
"Queue\") job_args.add_argument('-j', '--job-definition', action=\"store\", default=\"cohort-matcher:2\", help=\"AWS Batch Job Definition\") args = parser.parse_args(argv) return",
"if not args.dry_run: uploadFile(args.bamsheet, \"%s/bamsheet.txt\" % args.s3_cache_folder) jobs = [] for sample in",
"x x Instead of visiting every cell, we only need to visit the",
"x s5 x x x x Instead of visiting every cell, we only",
"-s %s --s3_cache_folder %s\", sample['name'], args.s3_cache_folder) else: response = batch.submit_job(jobName='compareGenotypes-%s' % sample['name'], jobQueue=args.job_queue,",
"job will need to determine what samples #to compare against based on its",
"response = batch.submit_job(jobName='compareGenotypes-%s' % sample['name'], jobQueue=args.job_queue, jobDefinition=args.job_definition, containerOverrides={'vcpus': 1, 'command': ['/compareGenotypes.py', '-s', sample['name'],",
"s1 s2 x s3 x x s4 x x x s5 x x",
"default=False, help=\"Run locally instead of in AWS Batch\") job_args.add_argument('-q', \"--job-queue\", action=\"store\", default=\"ngs-job-queue\", help=\"AWS",
"the ones with a X because the matrix is symmetrical about the axis",
"import boto3 import logging import os import time import subprocess import sys from",
"of visiting every cell, we only need to visit the ones with a",
"1, 'command': ['/compareGenotypes.py', '-s', sample['name'], '--s3_cache_folder', args.s3_cache_folder]}) jobId = response['jobId'] jobs.append(jobId) logger.debug(response) logger.info(\"Submitted",
"visit the ones with a X because the matrix is symmetrical about the",
"default\", default=\"INFO\", choices=[\"DEBUG\", \"INFO\", \"WARNING\", \"ERROR\"]) parser.add_argument('-d', '--dry-run', default=False, action=\"store_true\", help=\"Simulate job submission\")",
"parser.add_argument('-d', '--dry-run', default=False, action=\"store_true\", help=\"Simulate job submission\") required_args = parser.add_argument_group(\"Required\") required_args.add_argument('-b', '--bamsheet', required=True,",
"x x x x Instead of visiting every cell, we only need to",
"out, err = p.communicate() p.wait() if p.returncode != 0: return err return out",
"response['jobs'][0]['status'] == 'SUCCEEDED': completed_jobs.append(jobs.pop()) elif response['jobs'][0]['status'] == 'FAILED': failed_jobs.append(jobs.pop()) logger.info(\"Successed: %s\", len(completed_jobs)) logger.info(\"Failed:",
"err = p.communicate() p.wait() if p.returncode != 0: return err return out def",
"job_args = parser.add_argument_group(\"AWS Batch Job Settings\") job_args.add_argument('--local', action=\"store_true\", default=False, help=\"Run locally instead of",
"logger.info(\"Job %s state is %s\", jobs[0], response['jobs'][0]['status']) if response['jobs'][0]['status'] == 'SUCCEEDED': completed_jobs.append(jobs.pop()) elif",
"in meltedResultsFiles: logger.info(\"Comparing genotype of %s to other samples\", sample['name']) if args.local: cmd",
"x s4 x x x s5 x x x x Instead of visiting",
"Batch Job Queue\") job_args.add_argument('-j', '--job-definition', action=\"store\", default=\"cohort-matcher:2\", help=\"AWS Batch Job Definition\") args =",
"x x s4 x x x s5 x x x x Instead of",
"return -1 # We don't need the last sample in the list so",
"on its order in the bamsheet) if not args.dry_run: uploadFile(args.bamsheet, \"%s/bamsheet.txt\" % args.s3_cache_folder)",
"don't need the last sample in the list so let's remove it samples.pop()",
"arguments ''' parser = argparse.ArgumentParser(description='Compare a set of samples') parser.add_argument('-l', '--log-level', help=\"Prints warnings",
"\"%s/bamsheet.txt\" % args.s3_cache_folder) jobs = [] for sample in samples: meltedResults = \"%s/%s.meltedResults.txt\"",
"(sample1, ..., sampleN), an all v all nieve approach would require O(n^2) comparisons,",
"5 samples, sample1, ..., sample 5: s1 s2 s3 s4 s5 s1 s2",
"p.returncode != 0: return err return out def main(argv): ''' Main Entry Point",
"s2 s3 s4 s5 s1 s2 x s3 x x s4 x x",
"samples = readSamples(args.bamsheet) if samples is False: return -1 # We don't need",
"logger.info(\"Comparing genotype of %s to other samples\", sample['name']) if args.local: cmd = [\"%s/compareGenotypes.py\"",
"[] while jobs: logger.info(\"Sleeping 60 secs\") time.sleep(60) logger.info(\"Checking job %s\", jobs[0]) response =",
"help=\"Run locally instead of in AWS Batch\") job_args.add_argument('-q', \"--job-queue\", action=\"store\", default=\"ngs-job-queue\", help=\"AWS Batch",
"% args.s3_cache_folder) jobs = [] for sample in samples: meltedResults = \"%s/%s.meltedResults.txt\" %",
"\"--job-queue\", action=\"store\", default=\"ngs-job-queue\", help=\"AWS Batch Job Queue\") job_args.add_argument('-j', '--job-definition', action=\"store\", default=\"cohort-matcher:2\", help=\"AWS Batch",
"the axis ''' import argparse import boto3 import logging import os import time",
"files meltedResultsFiles = listFiles(args.s3_cache_folder, suffix='.meltedResults.txt') # Upload the bamsheet to the cache directory",
"= batch.submit_job(jobName='compareGenotypes-%s' % sample['name'], jobQueue=args.job_queue, jobDefinition=args.job_definition, containerOverrides={'vcpus': 1, 'command': ['/compareGenotypes.py', '-s', sample['name'], '--s3_cache_folder',",
"sample 5: s1 s2 s3 s4 s5 s1 s2 x s3 x x",
"to console by default\", default=\"INFO\", choices=[\"DEBUG\", \"INFO\", \"WARNING\", \"ERROR\"]) parser.add_argument('-d', '--dry-run', default=False, action=\"store_true\",",
"s2 x s3 x x s4 x x x s5 x x x",
"list of samples (sample1, ..., sampleN), an all v all nieve approach would",
"default=\"INFO\", choices=[\"DEBUG\", \"INFO\", \"WARNING\", \"ERROR\"]) parser.add_argument('-d', '--dry-run', default=False, action=\"store_true\", help=\"Simulate job submission\") required_args",
"can do this in O(n log(n)). For example, 5 samples, sample1, ..., sample",
"os import time import subprocess import sys from common import find_bucket_key, listFiles, readSamples,",
"jobs[0], response['jobs'][0]['status']) if response['jobs'][0]['status'] == 'SUCCEEDED': completed_jobs.append(jobs.pop()) elif response['jobs'][0]['status'] == 'FAILED': failed_jobs.append(jobs.pop()) logger.info(\"Successed:",
"jobId = response['jobId'] jobs.append(jobId) logger.debug(response) logger.info(\"Submitted %s jobs\", len(jobs)) completed_jobs = [] failed_jobs",
"set of samples') parser.add_argument('-l', '--log-level', help=\"Prints warnings to console by default\", default=\"INFO\", choices=[\"DEBUG\",",
"\"%s/%s.meltedResults.txt\" % (args.s3_cache_folder, sample['name']) if meltedResults not in meltedResultsFiles: logger.info(\"Comparing genotype of %s",
"x s3 x x s4 x x x s5 x x x x",
"args.s3_cache_folder] if args.dry_run: logger.info(\"Would call %s\", cmd) else: response = _run(cmd) else: if",
"args.dry_run: logger.info(\"Would call %s\", cmd) else: response = _run(cmd) else: if args.dry_run: logger.info(\"Would",
"in the bamsheet) if not args.dry_run: uploadFile(args.bamsheet, \"%s/bamsheet.txt\" % args.s3_cache_folder) jobs = []",
"== 'FAILED': failed_jobs.append(jobs.pop()) logger.info(\"Successed: %s\", len(completed_jobs)) logger.info(\"Failed: %s\", len(failed_jobs)) def parseArguments(argv): ''' Parse",
"matrix is symmetrical about the axis ''' import argparse import boto3 import logging",
"samples.pop() # Get a list of meltedResults files meltedResultsFiles = listFiles(args.s3_cache_folder, suffix='.meltedResults.txt') #",
"the bamsheet to the cache directory (because each job will need to determine",
"will need to determine what samples #to compare against based on its order",
"cmd) else: response = _run(cmd) else: if args.dry_run: logger.info(\"Would call batch.submit_job: compareGenotypes.py -s",
"of meltedResults files meltedResultsFiles = listFiles(args.s3_cache_folder, suffix='.meltedResults.txt') # Upload the bamsheet to the",
"= _run(cmd) else: if args.dry_run: logger.info(\"Would call batch.submit_job: compareGenotypes.py -s %s --s3_cache_folder %s\",",
"in O(n log(n)). For example, 5 samples, sample1, ..., sample 5: s1 s2",
"''' args = parseArguments(argv) logging.basicConfig(level=args.log_level) logger.info(\"%s v%s\" % (__appname__, __version__)) logger.info(args) batch =",
"warnings to console by default\", default=\"INFO\", choices=[\"DEBUG\", \"INFO\", \"WARNING\", \"ERROR\"]) parser.add_argument('-d', '--dry-run', default=False,",
"'FAILED': failed_jobs.append(jobs.pop()) logger.info(\"Successed: %s\", len(completed_jobs)) logger.info(\"Failed: %s\", len(failed_jobs)) def parseArguments(argv): ''' Parse arguments",
"# Get a list of meltedResults files meltedResultsFiles = listFiles(args.s3_cache_folder, suffix='.meltedResults.txt') # Upload",
"%s\", cmd) else: response = _run(cmd) else: if args.dry_run: logger.info(\"Would call batch.submit_job: compareGenotypes.py",
"% (__appname__, __version__)) logger.info(args) batch = boto3.client('batch') samples = readSamples(args.bamsheet) if samples is",
"sample['name'], args.s3_cache_folder) else: response = batch.submit_job(jobName='compareGenotypes-%s' % sample['name'], jobQueue=args.job_queue, jobDefinition=args.job_definition, containerOverrides={'vcpus': 1, 'command':",
"'command': ['/compareGenotypes.py', '-s', sample['name'], '--s3_cache_folder', args.s3_cache_folder]}) jobId = response['jobId'] jobs.append(jobId) logger.debug(response) logger.info(\"Submitted %s",
"Instead of visiting every cell, we only need to visit the ones with",
"need the last sample in the list so let's remove it samples.pop() #",
"= batch.describe_jobs(jobs=[jobs[0]]) logger.info(\"Job %s state is %s\", jobs[0], response['jobs'][0]['status']) if response['jobs'][0]['status'] == 'SUCCEEDED':",
"Batch Job Settings\") job_args.add_argument('--local', action=\"store_true\", default=False, help=\"Run locally instead of in AWS Batch\")",
"not args.dry_run: uploadFile(args.bamsheet, \"%s/bamsheet.txt\" % args.s3_cache_folder) jobs = [] for sample in samples:",
"locally instead of in AWS Batch\") job_args.add_argument('-q', \"--job-queue\", action=\"store\", default=\"ngs-job-queue\", help=\"AWS Batch Job",
"nieve approach would require O(n^2) comparisons, but really, we can do this in",
"''' Main Entry Point ''' args = parseArguments(argv) logging.basicConfig(level=args.log_level) logger.info(\"%s v%s\" % (__appname__,",
"samples: meltedResults = \"%s/%s.meltedResults.txt\" % (args.s3_cache_folder, sample['name']) if meltedResults not in meltedResultsFiles: logger.info(\"Comparing",
"action=\"store_true\", default=False, help=\"Run locally instead of in AWS Batch\") job_args.add_argument('-q', \"--job-queue\", action=\"store\", default=\"ngs-job-queue\",",
"import os import time import subprocess import sys from common import find_bucket_key, listFiles,",
"'--bamsheet', required=True, help=\"Bamsheet\") required_args.add_argument(\"-CD\", \"--s3_cache_folder\", required=True, help=\"Specify S3 path for cached VCF/TSV files\")",
"help=\"Specify S3 path for cached VCF/TSV files\") job_args = parser.add_argument_group(\"AWS Batch Job Settings\")",
"we can do this in O(n log(n)). For example, 5 samples, sample1, ...,",
"batch.submit_job: compareGenotypes.py -s %s --s3_cache_folder %s\", sample['name'], args.s3_cache_folder) else: response = batch.submit_job(jobName='compareGenotypes-%s' %",
"sample['name'], '--s3_cache_folder', args.s3_cache_folder]}) jobId = response['jobId'] jobs.append(jobId) logger.debug(response) logger.info(\"Submitted %s jobs\", len(jobs)) completed_jobs",
"def parseArguments(argv): ''' Parse arguments ''' parser = argparse.ArgumentParser(description='Compare a set of samples')",
"sampleN), an all v all nieve approach would require O(n^2) comparisons, but really,",
"[] for sample in samples: meltedResults = \"%s/%s.meltedResults.txt\" % (args.s3_cache_folder, sample['name']) if meltedResults",
"Upload the bamsheet to the cache directory (because each job will need to",
"completed_jobs.append(jobs.pop()) elif response['jobs'][0]['status'] == 'FAILED': failed_jobs.append(jobs.pop()) logger.info(\"Successed: %s\", len(completed_jobs)) logger.info(\"Failed: %s\", len(failed_jobs)) def",
"%s --s3_cache_folder %s\", sample['name'], args.s3_cache_folder) else: response = batch.submit_job(jobName='compareGenotypes-%s' % sample['name'], jobQueue=args.job_queue, jobDefinition=args.job_definition,",
"cached VCF/TSV files\") job_args = parser.add_argument_group(\"AWS Batch Job Settings\") job_args.add_argument('--local', action=\"store_true\", default=False, help=\"Run",
"jobDefinition=args.job_definition, containerOverrides={'vcpus': 1, 'command': ['/compareGenotypes.py', '-s', sample['name'], '--s3_cache_folder', args.s3_cache_folder]}) jobId = response['jobId'] jobs.append(jobId)",
"Batch Job Definition\") args = parser.parse_args(argv) return args if __name__ == '__main__': main(sys.argv[1:])",
"a list of meltedResults files meltedResultsFiles = listFiles(args.s3_cache_folder, suffix='.meltedResults.txt') # Upload the bamsheet",
"import time import subprocess import sys from common import find_bucket_key, listFiles, readSamples, uploadFile",
"'--job-definition', action=\"store\", default=\"cohort-matcher:2\", help=\"AWS Batch Job Definition\") args = parser.parse_args(argv) return args if",
"%s\", sample['name'], args.s3_cache_folder) else: response = batch.submit_job(jobName='compareGenotypes-%s' % sample['name'], jobQueue=args.job_queue, jobDefinition=args.job_definition, containerOverrides={'vcpus': 1,",
"its order in the bamsheet) if not args.dry_run: uploadFile(args.bamsheet, \"%s/bamsheet.txt\" % args.s3_cache_folder) jobs",
"''' Parse arguments ''' parser = argparse.ArgumentParser(description='Compare a set of samples') parser.add_argument('-l', '--log-level',",
"samples\", sample['name']) if args.local: cmd = [\"%s/compareGenotypes.py\" % os.path.dirname(__file__), \"-s\", sample['name'], \"--s3_cache_folder\", args.s3_cache_folder]",
"if response['jobs'][0]['status'] == 'SUCCEEDED': completed_jobs.append(jobs.pop()) elif response['jobs'][0]['status'] == 'FAILED': failed_jobs.append(jobs.pop()) logger.info(\"Successed: %s\", len(completed_jobs))",
"%s state is %s\", jobs[0], response['jobs'][0]['status']) if response['jobs'][0]['status'] == 'SUCCEEDED': completed_jobs.append(jobs.pop()) elif response['jobs'][0]['status']",
"order in the bamsheet) if not args.dry_run: uploadFile(args.bamsheet, \"%s/bamsheet.txt\" % args.s3_cache_folder) jobs =",
"sample['name'], \"--s3_cache_folder\", args.s3_cache_folder] if args.dry_run: logger.info(\"Would call %s\", cmd) else: response = _run(cmd)",
"a meltedResults.txt. For a list of samples (sample1, ..., sampleN), an all v",
"what samples #to compare against based on its order in the bamsheet) if",
"False: return -1 # We don't need the last sample in the list",
"x x s5 x x x x Instead of visiting every cell, we",
"python ''' Script to compare genotypes Not every sample is going to have",
"meltedResults = \"%s/%s.meltedResults.txt\" % (args.s3_cache_folder, sample['name']) if meltedResults not in meltedResultsFiles: logger.info(\"Comparing genotype",
"_run(cmd) else: if args.dry_run: logger.info(\"Would call batch.submit_job: compareGenotypes.py -s %s --s3_cache_folder %s\", sample['name'],",
"example, 5 samples, sample1, ..., sample 5: s1 s2 s3 s4 s5 s1",
"job_args.add_argument('-j', '--job-definition', action=\"store\", default=\"cohort-matcher:2\", help=\"AWS Batch Job Definition\") args = parser.parse_args(argv) return args",
"else: if args.dry_run: logger.info(\"Would call batch.submit_job: compareGenotypes.py -s %s --s3_cache_folder %s\", sample['name'], args.s3_cache_folder)",
"% sample['name'], jobQueue=args.job_queue, jobDefinition=args.job_definition, containerOverrides={'vcpus': 1, 'command': ['/compareGenotypes.py', '-s', sample['name'], '--s3_cache_folder', args.s3_cache_folder]}) jobId"
] |
[
"notice and full license details. # \"\"\" WSGI config for pkpdapp project. It",
"file, see https://docs.djangoproject.com/en/3.0/howto/deployment/wsgi/ \"\"\" import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'pkpdapp.settings') application",
"part of PKPDApp (https://github.com/pkpdapp-team/pkpdapp) which # is released under the BSD 3-clause license.",
"# copyright notice and full license details. # \"\"\" WSGI config for pkpdapp",
"see https://docs.djangoproject.com/en/3.0/howto/deployment/wsgi/ \"\"\" import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'pkpdapp.settings') application =",
"file is part of PKPDApp (https://github.com/pkpdapp-team/pkpdapp) which # is released under the BSD",
"is released under the BSD 3-clause license. See accompanying LICENSE.md for # copyright",
"and full license details. # \"\"\" WSGI config for pkpdapp project. It exposes",
"a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/3.0/howto/deployment/wsgi/",
"variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/3.0/howto/deployment/wsgi/ \"\"\" import",
"``application``. For more information on this file, see https://docs.djangoproject.com/en/3.0/howto/deployment/wsgi/ \"\"\" import os from",
"pkpdapp project. It exposes the WSGI callable as a module-level variable named ``application``.",
"as a module-level variable named ``application``. For more information on this file, see",
"\"\"\" WSGI config for pkpdapp project. It exposes the WSGI callable as a",
"this file, see https://docs.djangoproject.com/en/3.0/howto/deployment/wsgi/ \"\"\" import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'pkpdapp.settings')",
"(https://github.com/pkpdapp-team/pkpdapp) which # is released under the BSD 3-clause license. See accompanying LICENSE.md",
"released under the BSD 3-clause license. See accompanying LICENSE.md for # copyright notice",
"For more information on this file, see https://docs.djangoproject.com/en/3.0/howto/deployment/wsgi/ \"\"\" import os from django.core.wsgi",
"This file is part of PKPDApp (https://github.com/pkpdapp-team/pkpdapp) which # is released under the",
"more information on this file, see https://docs.djangoproject.com/en/3.0/howto/deployment/wsgi/ \"\"\" import os from django.core.wsgi import",
"project. It exposes the WSGI callable as a module-level variable named ``application``. For",
"information on this file, see https://docs.djangoproject.com/en/3.0/howto/deployment/wsgi/ \"\"\" import os from django.core.wsgi import get_wsgi_application",
"PKPDApp (https://github.com/pkpdapp-team/pkpdapp) which # is released under the BSD 3-clause license. See accompanying",
"full license details. # \"\"\" WSGI config for pkpdapp project. It exposes the",
"module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/3.0/howto/deployment/wsgi/ \"\"\"",
"See accompanying LICENSE.md for # copyright notice and full license details. # \"\"\"",
"It exposes the WSGI callable as a module-level variable named ``application``. For more",
"https://docs.djangoproject.com/en/3.0/howto/deployment/wsgi/ \"\"\" import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'pkpdapp.settings') application = get_wsgi_application()",
"which # is released under the BSD 3-clause license. See accompanying LICENSE.md for",
"the BSD 3-clause license. See accompanying LICENSE.md for # copyright notice and full",
"under the BSD 3-clause license. See accompanying LICENSE.md for # copyright notice and",
"exposes the WSGI callable as a module-level variable named ``application``. For more information",
"3-clause license. See accompanying LICENSE.md for # copyright notice and full license details.",
"of PKPDApp (https://github.com/pkpdapp-team/pkpdapp) which # is released under the BSD 3-clause license. See",
"for # copyright notice and full license details. # \"\"\" WSGI config for",
"the WSGI callable as a module-level variable named ``application``. For more information on",
"license. See accompanying LICENSE.md for # copyright notice and full license details. #",
"callable as a module-level variable named ``application``. For more information on this file,",
"WSGI callable as a module-level variable named ``application``. For more information on this",
"# \"\"\" WSGI config for pkpdapp project. It exposes the WSGI callable as",
"on this file, see https://docs.djangoproject.com/en/3.0/howto/deployment/wsgi/ \"\"\" import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE',",
"# is released under the BSD 3-clause license. See accompanying LICENSE.md for #",
"for pkpdapp project. It exposes the WSGI callable as a module-level variable named",
"named ``application``. For more information on this file, see https://docs.djangoproject.com/en/3.0/howto/deployment/wsgi/ \"\"\" import os",
"WSGI config for pkpdapp project. It exposes the WSGI callable as a module-level",
"config for pkpdapp project. It exposes the WSGI callable as a module-level variable",
"is part of PKPDApp (https://github.com/pkpdapp-team/pkpdapp) which # is released under the BSD 3-clause",
"license details. # \"\"\" WSGI config for pkpdapp project. It exposes the WSGI",
"copyright notice and full license details. # \"\"\" WSGI config for pkpdapp project.",
"LICENSE.md for # copyright notice and full license details. # \"\"\" WSGI config",
"# This file is part of PKPDApp (https://github.com/pkpdapp-team/pkpdapp) which # is released under",
"# # This file is part of PKPDApp (https://github.com/pkpdapp-team/pkpdapp) which # is released",
"BSD 3-clause license. See accompanying LICENSE.md for # copyright notice and full license",
"accompanying LICENSE.md for # copyright notice and full license details. # \"\"\" WSGI",
"details. # \"\"\" WSGI config for pkpdapp project. It exposes the WSGI callable"
] |
[
"not cnn: model = [nn.Linear(in_features=100, out_features=512), act, nn.Dropout(p=0.5)] model += [nn.Linear(in_features=512, out_features=256), act,",
"# 28x28 self.model = nn.Sequential(*model) def forward(self, x): return self.model(x) class Identity(nn.Module): def",
"x): return x.view(x.shape[0], *self.output_shape) def weights_init(module): if isinstance(module, nn.Conv2d) or isinstance(module, nn.ConvTranspose2d): module.weight.detach().normal_(mean=0.,",
"if not cnn: model = [nn.Linear(in_features=100, out_features=512), act, nn.Dropout(p=0.5)] model += [nn.Linear(in_features=512, out_features=256),",
"[nn.Linear(in_features=100, out_features=512), act, nn.Dropout(p=0.5)] model += [nn.Linear(in_features=512, out_features=256), act, nn.Dropout(p=0.5)] model += [nn.Linear(in_features=256,",
"nn.Tanh()] else: norm = nn.BatchNorm2d model = [nn.Linear(100, 512 * 4 * 4),",
"[nn.Linear(100, 512 * 4 * 4), View([512, 4, 4]), norm(512), act] # 4x4",
"AuxiliaryClassifier(nn.Module): def __init__(self, in_features, n_classes, kernel_size=1, stride=1, padding=0, bias=False, softmax=False, cnn=False): super(AuxiliaryClassifier, self).__init__()",
"self).__init__() self.output_shape = output_shape def forward(self, x): return x.view(x.shape[0], *self.output_shape) def weights_init(module): if",
"128, 5, stride=2, padding=2, output_padding=1), norm(128), act] # 14x14 model += [nn.ConvTranspose2d(128, 1,",
"def weights_init(module): if isinstance(module, nn.Conv2d) or isinstance(module, nn.ConvTranspose2d): module.weight.detach().normal_(mean=0., std=0.02) elif isinstance(module, nn.BatchNorm2d):",
"1), nn.Sigmoid()] self.classes = nn.Sequential(*classes, nn.Softmax if softmax else Identity()) self.validity = nn.Sequential(*validity)",
"softmax=False, cnn=False): super(AuxiliaryClassifier, self).__init__() if cnn: classes = [nn.Conv2d(in_features, n_classes, kernel_size, stride, padding,",
"4]), norm(512), act] # 4x4 model += [nn.ConvTranspose2d(512, 256, 5, stride=2, padding=2), norm(256),",
"torch.nn as nn class AuxiliaryClassifier(nn.Module): def __init__(self, in_features, n_classes, kernel_size=1, stride=1, padding=0, bias=False,",
"model += [nn.Conv2d(256, 512, 5, stride=2, padding=2, bias=False), norm(512), act] # 4x4 model",
"forward(self, x): return self.model(x) class View(nn.Module): def __init__(self, output_shape): super(View, self).__init__() self.output_shape =",
"norm(128), act] # 14x14 model += [nn.ConvTranspose2d(128, 1, 5, stride=2, padding=2, output_padding=1), nn.Tanh()]",
"cnn=False): super(Discriminator, self).__init__() act = nn.LeakyReLU(inplace=True, negative_slope=0.2) if not cnn: model = [nn.Linear(in_features=28",
"nn.Dropout(p=0.5)] model += [nn.Linear(in_features=256, out_features=28 * 28), nn.Tanh()] else: norm = nn.BatchNorm2d model",
"n_classes, kernel_size=1, stride=1, padding=0, bias=False, softmax=False, cnn=False): super(AuxiliaryClassifier, self).__init__() if cnn: classes =",
"14x14 model += [nn.ConvTranspose2d(128, 1, 5, stride=2, padding=2, output_padding=1), nn.Tanh()] # 28x28 self.model",
"View(nn.Module): def __init__(self, output_shape): super(View, self).__init__() self.output_shape = output_shape def forward(self, x): return",
"return self.model(x) class Identity(nn.Module): def __init__(self): super(Identity, self).__init__() def forward(self, x): return x",
"act] # 7x7 model += [nn.ConvTranspose2d(256, 128, 5, stride=2, padding=2, output_padding=1), norm(128), act]",
"nn.ReLU(inplace=True) if not cnn: model = [nn.Linear(in_features=100, out_features=512), act, nn.Dropout(p=0.5)] model += [nn.Linear(in_features=512,",
"model = [nn.Conv2d(1, 128, 5, stride=2, padding=2, bias=False), act] # 14x14 model +=",
"else: classes = [nn.Linear(in_features, n_classes)] validity = [nn.Linear(in_features, 1), nn.Sigmoid()] self.classes = nn.Sequential(*classes,",
"padding, bias=bias)] validity = [nn.Conv2d(in_features, n_classes, kernel_size, stride, padding, bias=bias), nn.Sigmoid()] else: classes",
"bias=False), norm(512), act] # 4x4 model += [AuxiliaryClassifier(512, 10, kernel_size=4, bias=False, cnn=True)] self.model",
"norm(256), act] # 7x7 model += [nn.ConvTranspose2d(256, 128, 5, stride=2, padding=2, output_padding=1), norm(128),",
"nn.Softmax if softmax else Identity()) self.validity = nn.Sequential(*validity) def forward(self, x): return self.classes(x),",
"= [nn.Linear(100, 512 * 4 * 4), View([512, 4, 4]), norm(512), act] #",
"nn.LeakyReLU(inplace=True, negative_slope=0.2) if not cnn: model = [nn.Linear(in_features=28 * 28, out_features=512), act] model",
"[nn.Linear(in_features=512, out_features=256), act] model += [AuxiliaryClassifier(256, 10)] else: norm = nn.BatchNorm2d model =",
"padding=2, bias=False), norm(256), act] # 7x7 model += [nn.Conv2d(256, 512, 5, stride=2, padding=2,",
"out_features=28 * 28), nn.Tanh()] else: norm = nn.BatchNorm2d model = [nn.Linear(100, 512 *",
"model += [nn.Linear(in_features=256, out_features=28 * 28), nn.Tanh()] else: norm = nn.BatchNorm2d model =",
"= [nn.Linear(in_features=100, out_features=512), act, nn.Dropout(p=0.5)] model += [nn.Linear(in_features=512, out_features=256), act, nn.Dropout(p=0.5)] model +=",
"class Discriminator(nn.Module): def __init__(self, cnn=False): super(Discriminator, self).__init__() act = nn.LeakyReLU(inplace=True, negative_slope=0.2) if not",
"= [nn.Conv2d(1, 128, 5, stride=2, padding=2, bias=False), act] # 14x14 model += [nn.Conv2d(128,",
"self).__init__() act = nn.ReLU(inplace=True) if not cnn: model = [nn.Linear(in_features=100, out_features=512), act, nn.Dropout(p=0.5)]",
"def forward(self, x): return x.view(x.shape[0], *self.output_shape) def weights_init(module): if isinstance(module, nn.Conv2d) or isinstance(module,",
"4x4 model += [nn.ConvTranspose2d(512, 256, 5, stride=2, padding=2), norm(256), act] # 7x7 model",
"isinstance(module, nn.Conv2d) or isinstance(module, nn.ConvTranspose2d): module.weight.detach().normal_(mean=0., std=0.02) elif isinstance(module, nn.BatchNorm2d): module.weight.detach().normal_(1., 0.02) module.bias.detach().zero_()",
"[nn.Conv2d(in_features, n_classes, kernel_size, stride, padding, bias=bias)] validity = [nn.Conv2d(in_features, n_classes, kernel_size, stride, padding,",
"= output_shape def forward(self, x): return x.view(x.shape[0], *self.output_shape) def weights_init(module): if isinstance(module, nn.Conv2d)",
"nn class AuxiliaryClassifier(nn.Module): def __init__(self, in_features, n_classes, kernel_size=1, stride=1, padding=0, bias=False, softmax=False, cnn=False):",
"10)] else: norm = nn.BatchNorm2d model = [nn.Conv2d(1, 128, 5, stride=2, padding=2, bias=False),",
"nn.Sequential(*classes, nn.Softmax if softmax else Identity()) self.validity = nn.Sequential(*validity) def forward(self, x): return",
"4), View([512, 4, 4]), norm(512), act] # 4x4 model += [nn.ConvTranspose2d(512, 256, 5,",
"padding, bias=bias), nn.Sigmoid()] else: classes = [nn.Linear(in_features, n_classes)] validity = [nn.Linear(in_features, 1), nn.Sigmoid()]",
"if softmax else Identity()) self.validity = nn.Sequential(*validity) def forward(self, x): return self.classes(x), self.validity(x)",
"stride=2, padding=2, output_padding=1), norm(128), act] # 14x14 model += [nn.ConvTranspose2d(128, 1, 5, stride=2,",
"Discriminator(nn.Module): def __init__(self, cnn=False): super(Discriminator, self).__init__() act = nn.LeakyReLU(inplace=True, negative_slope=0.2) if not cnn:",
"not cnn: model = [nn.Linear(in_features=28 * 28, out_features=512), act] model += [nn.Linear(in_features=512, out_features=256),",
"x): return self.model(x) class Identity(nn.Module): def __init__(self): super(Identity, self).__init__() def forward(self, x): return",
"28x28 self.model = nn.Sequential(*model) def forward(self, x): return self.model(x) class Identity(nn.Module): def __init__(self):",
"out_features=512), act] model += [nn.Linear(in_features=512, out_features=256), act] model += [AuxiliaryClassifier(256, 10)] else: norm",
"512 * 4 * 4), View([512, 4, 4]), norm(512), act] # 4x4 model",
"return self.model(x) class View(nn.Module): def __init__(self, output_shape): super(View, self).__init__() self.output_shape = output_shape def",
"stride=2, padding=2), norm(256), act] # 7x7 model += [nn.ConvTranspose2d(256, 128, 5, stride=2, padding=2,",
"validity = [nn.Conv2d(in_features, n_classes, kernel_size, stride, padding, bias=bias), nn.Sigmoid()] else: classes = [nn.Linear(in_features,",
"negative_slope=0.2) if not cnn: model = [nn.Linear(in_features=28 * 28, out_features=512), act] model +=",
"model += [nn.ConvTranspose2d(256, 128, 5, stride=2, padding=2, output_padding=1), norm(128), act] # 14x14 model",
"x): return x class Discriminator(nn.Module): def __init__(self, cnn=False): super(Discriminator, self).__init__() act = nn.LeakyReLU(inplace=True,",
"super(Identity, self).__init__() def forward(self, x): return x class Discriminator(nn.Module): def __init__(self, cnn=False): super(Discriminator,",
"bias=bias)] validity = [nn.Conv2d(in_features, n_classes, kernel_size, stride, padding, bias=bias), nn.Sigmoid()] else: classes =",
"+= [nn.ConvTranspose2d(256, 128, 5, stride=2, padding=2, output_padding=1), norm(128), act] # 14x14 model +=",
"def __init__(self, output_shape): super(View, self).__init__() self.output_shape = output_shape def forward(self, x): return x.view(x.shape[0],",
"+= [nn.ConvTranspose2d(128, 1, 5, stride=2, padding=2, output_padding=1), nn.Tanh()] # 28x28 self.model = nn.Sequential(*model)",
"+= [nn.Linear(in_features=512, out_features=256), act] model += [AuxiliaryClassifier(256, 10)] else: norm = nn.BatchNorm2d model",
"# 14x14 model += [nn.Conv2d(128, 256, 5, stride=2, padding=2, bias=False), norm(256), act] #",
"10, kernel_size=4, bias=False, cnn=True)] self.model = nn.Sequential(*model) def forward(self, x): return self.model(x) class",
"* 4), View([512, 4, 4]), norm(512), act] # 4x4 model += [nn.ConvTranspose2d(512, 256,",
"* 28, out_features=512), act] model += [nn.Linear(in_features=512, out_features=256), act] model += [AuxiliaryClassifier(256, 10)]",
"Identity(nn.Module): def __init__(self): super(Identity, self).__init__() def forward(self, x): return x class Discriminator(nn.Module): def",
"return self.classes(x), self.validity(x) class Generator(nn.Module): def __init__(self, cnn=False): super(Generator, self).__init__() act = nn.ReLU(inplace=True)",
"+= [nn.Linear(in_features=512, out_features=256), act, nn.Dropout(p=0.5)] model += [nn.Linear(in_features=256, out_features=28 * 28), nn.Tanh()] else:",
"# 4x4 model += [nn.ConvTranspose2d(512, 256, 5, stride=2, padding=2), norm(256), act] # 7x7",
"nn.Tanh()] # 28x28 self.model = nn.Sequential(*model) def forward(self, x): return self.model(x) class Identity(nn.Module):",
"self.model(x) class View(nn.Module): def __init__(self, output_shape): super(View, self).__init__() self.output_shape = output_shape def forward(self,",
"model += [nn.Linear(in_features=512, out_features=256), act, nn.Dropout(p=0.5)] model += [nn.Linear(in_features=256, out_features=28 * 28), nn.Tanh()]",
"* 4 * 4), View([512, 4, 4]), norm(512), act] # 4x4 model +=",
"return x class Discriminator(nn.Module): def __init__(self, cnn=False): super(Discriminator, self).__init__() act = nn.LeakyReLU(inplace=True, negative_slope=0.2)",
"__init__(self, in_features, n_classes, kernel_size=1, stride=1, padding=0, bias=False, softmax=False, cnn=False): super(AuxiliaryClassifier, self).__init__() if cnn:",
"def forward(self, x): return self.classes(x), self.validity(x) class Generator(nn.Module): def __init__(self, cnn=False): super(Generator, self).__init__()",
"self.classes = nn.Sequential(*classes, nn.Softmax if softmax else Identity()) self.validity = nn.Sequential(*validity) def forward(self,",
"[nn.Conv2d(256, 512, 5, stride=2, padding=2, bias=False), norm(512), act] # 4x4 model += [AuxiliaryClassifier(512,",
"norm(512), act] # 4x4 model += [AuxiliaryClassifier(512, 10, kernel_size=4, bias=False, cnn=True)] self.model =",
"nn.Sequential(*model) def forward(self, x): return self.model(x) class Identity(nn.Module): def __init__(self): super(Identity, self).__init__() def",
"nn.Dropout(p=0.5)] model += [nn.Linear(in_features=512, out_features=256), act, nn.Dropout(p=0.5)] model += [nn.Linear(in_features=256, out_features=28 * 28),",
"self.model(x) class Identity(nn.Module): def __init__(self): super(Identity, self).__init__() def forward(self, x): return x class",
"class Identity(nn.Module): def __init__(self): super(Identity, self).__init__() def forward(self, x): return x class Discriminator(nn.Module):",
"n_classes, kernel_size, stride, padding, bias=bias)] validity = [nn.Conv2d(in_features, n_classes, kernel_size, stride, padding, bias=bias),",
"= [nn.Linear(in_features=28 * 28, out_features=512), act] model += [nn.Linear(in_features=512, out_features=256), act] model +=",
"[AuxiliaryClassifier(256, 10)] else: norm = nn.BatchNorm2d model = [nn.Conv2d(1, 128, 5, stride=2, padding=2,",
"def __init__(self, cnn=False): super(Generator, self).__init__() act = nn.ReLU(inplace=True) if not cnn: model =",
"as nn class AuxiliaryClassifier(nn.Module): def __init__(self, in_features, n_classes, kernel_size=1, stride=1, padding=0, bias=False, softmax=False,",
"self.model = nn.Sequential(*model) def forward(self, x): return self.model(x) class View(nn.Module): def __init__(self, output_shape):",
"nn.Sequential(*model) def forward(self, x): return self.model(x) class View(nn.Module): def __init__(self, output_shape): super(View, self).__init__()",
"super(View, self).__init__() self.output_shape = output_shape def forward(self, x): return x.view(x.shape[0], *self.output_shape) def weights_init(module):",
"norm(512), act] # 4x4 model += [nn.ConvTranspose2d(512, 256, 5, stride=2, padding=2), norm(256), act]",
"+= [AuxiliaryClassifier(512, 10, kernel_size=4, bias=False, cnn=True)] self.model = nn.Sequential(*model) def forward(self, x): return",
"nn.Sigmoid()] else: classes = [nn.Linear(in_features, n_classes)] validity = [nn.Linear(in_features, 1), nn.Sigmoid()] self.classes =",
"nn.Sigmoid()] self.classes = nn.Sequential(*classes, nn.Softmax if softmax else Identity()) self.validity = nn.Sequential(*validity) def",
"act = nn.ReLU(inplace=True) if not cnn: model = [nn.Linear(in_features=100, out_features=512), act, nn.Dropout(p=0.5)] model",
"act] # 14x14 model += [nn.ConvTranspose2d(128, 1, 5, stride=2, padding=2, output_padding=1), nn.Tanh()] #",
"5, stride=2, padding=2, output_padding=1), nn.Tanh()] # 28x28 self.model = nn.Sequential(*model) def forward(self, x):",
"model += [nn.ConvTranspose2d(128, 1, 5, stride=2, padding=2, output_padding=1), nn.Tanh()] # 28x28 self.model =",
"else: norm = nn.BatchNorm2d model = [nn.Linear(100, 512 * 4 * 4), View([512,",
"model = [nn.Linear(in_features=28 * 28, out_features=512), act] model += [nn.Linear(in_features=512, out_features=256), act] model",
"= nn.Sequential(*model) def forward(self, x): return self.model(x) class View(nn.Module): def __init__(self, output_shape): super(View,",
"self.validity(x) class Generator(nn.Module): def __init__(self, cnn=False): super(Generator, self).__init__() act = nn.ReLU(inplace=True) if not",
"5, stride=2, padding=2), norm(256), act] # 7x7 model += [nn.ConvTranspose2d(256, 128, 5, stride=2,",
"[nn.ConvTranspose2d(256, 128, 5, stride=2, padding=2, output_padding=1), norm(128), act] # 14x14 model += [nn.ConvTranspose2d(128,",
"= [nn.Conv2d(in_features, n_classes, kernel_size, stride, padding, bias=bias), nn.Sigmoid()] else: classes = [nn.Linear(in_features, n_classes)]",
"forward(self, x): return x class Discriminator(nn.Module): def __init__(self, cnn=False): super(Discriminator, self).__init__() act =",
"x.view(x.shape[0], *self.output_shape) def weights_init(module): if isinstance(module, nn.Conv2d) or isinstance(module, nn.ConvTranspose2d): module.weight.detach().normal_(mean=0., std=0.02) elif",
"self.validity = nn.Sequential(*validity) def forward(self, x): return self.classes(x), self.validity(x) class Generator(nn.Module): def __init__(self,",
"# 4x4 model += [AuxiliaryClassifier(512, 10, kernel_size=4, bias=False, cnn=True)] self.model = nn.Sequential(*model) def",
"bias=False), act] # 14x14 model += [nn.Conv2d(128, 256, 5, stride=2, padding=2, bias=False), norm(256),",
"cnn=False): super(AuxiliaryClassifier, self).__init__() if cnn: classes = [nn.Conv2d(in_features, n_classes, kernel_size, stride, padding, bias=bias)]",
"model += [nn.Linear(in_features=512, out_features=256), act] model += [AuxiliaryClassifier(256, 10)] else: norm = nn.BatchNorm2d",
"[nn.Linear(in_features=256, out_features=28 * 28), nn.Tanh()] else: norm = nn.BatchNorm2d model = [nn.Linear(100, 512",
"Identity()) self.validity = nn.Sequential(*validity) def forward(self, x): return self.classes(x), self.validity(x) class Generator(nn.Module): def",
"x): return self.model(x) class View(nn.Module): def __init__(self, output_shape): super(View, self).__init__() self.output_shape = output_shape",
"5, stride=2, padding=2, bias=False), act] # 14x14 model += [nn.Conv2d(128, 256, 5, stride=2,",
"def forward(self, x): return x class Discriminator(nn.Module): def __init__(self, cnn=False): super(Discriminator, self).__init__() act",
"= nn.Sequential(*classes, nn.Softmax if softmax else Identity()) self.validity = nn.Sequential(*validity) def forward(self, x):",
"5, stride=2, padding=2, bias=False), norm(512), act] # 4x4 model += [AuxiliaryClassifier(512, 10, kernel_size=4,",
"+= [nn.Conv2d(256, 512, 5, stride=2, padding=2, bias=False), norm(512), act] # 4x4 model +=",
"stride, padding, bias=bias)] validity = [nn.Conv2d(in_features, n_classes, kernel_size, stride, padding, bias=bias), nn.Sigmoid()] else:",
"padding=2, bias=False), act] # 14x14 model += [nn.Conv2d(128, 256, 5, stride=2, padding=2, bias=False),",
"cnn: model = [nn.Linear(in_features=28 * 28, out_features=512), act] model += [nn.Linear(in_features=512, out_features=256), act]",
"[nn.Linear(in_features, n_classes)] validity = [nn.Linear(in_features, 1), nn.Sigmoid()] self.classes = nn.Sequential(*classes, nn.Softmax if softmax",
"kernel_size, stride, padding, bias=bias), nn.Sigmoid()] else: classes = [nn.Linear(in_features, n_classes)] validity = [nn.Linear(in_features,",
"__init__(self, cnn=False): super(Discriminator, self).__init__() act = nn.LeakyReLU(inplace=True, negative_slope=0.2) if not cnn: model =",
"act] model += [AuxiliaryClassifier(256, 10)] else: norm = nn.BatchNorm2d model = [nn.Conv2d(1, 128,",
"act = nn.LeakyReLU(inplace=True, negative_slope=0.2) if not cnn: model = [nn.Linear(in_features=28 * 28, out_features=512),",
"softmax else Identity()) self.validity = nn.Sequential(*validity) def forward(self, x): return self.classes(x), self.validity(x) class",
"stride=2, padding=2, bias=False), norm(512), act] # 4x4 model += [AuxiliaryClassifier(512, 10, kernel_size=4, bias=False,",
"= [nn.Conv2d(in_features, n_classes, kernel_size, stride, padding, bias=bias)] validity = [nn.Conv2d(in_features, n_classes, kernel_size, stride,",
"model = [nn.Linear(100, 512 * 4 * 4), View([512, 4, 4]), norm(512), act]",
"View([512, 4, 4]), norm(512), act] # 4x4 model += [nn.ConvTranspose2d(512, 256, 5, stride=2,",
"output_shape def forward(self, x): return x.view(x.shape[0], *self.output_shape) def weights_init(module): if isinstance(module, nn.Conv2d) or",
"or isinstance(module, nn.ConvTranspose2d): module.weight.detach().normal_(mean=0., std=0.02) elif isinstance(module, nn.BatchNorm2d): module.weight.detach().normal_(1., 0.02) module.bias.detach().zero_() else: pass",
"512, 5, stride=2, padding=2, bias=False), norm(512), act] # 4x4 model += [AuxiliaryClassifier(512, 10,",
"5, stride=2, padding=2, output_padding=1), norm(128), act] # 14x14 model += [nn.ConvTranspose2d(128, 1, 5,",
"model = [nn.Linear(in_features=100, out_features=512), act, nn.Dropout(p=0.5)] model += [nn.Linear(in_features=512, out_features=256), act, nn.Dropout(p=0.5)] model",
"bias=False, cnn=True)] self.model = nn.Sequential(*model) def forward(self, x): return self.model(x) class View(nn.Module): def",
"super(Generator, self).__init__() act = nn.ReLU(inplace=True) if not cnn: model = [nn.Linear(in_features=100, out_features=512), act,",
"model += [nn.ConvTranspose2d(512, 256, 5, stride=2, padding=2), norm(256), act] # 7x7 model +=",
"nn.Sequential(*validity) def forward(self, x): return self.classes(x), self.validity(x) class Generator(nn.Module): def __init__(self, cnn=False): super(Generator,",
"stride=2, padding=2, bias=False), act] # 14x14 model += [nn.Conv2d(128, 256, 5, stride=2, padding=2,",
"4x4 model += [AuxiliaryClassifier(512, 10, kernel_size=4, bias=False, cnn=True)] self.model = nn.Sequential(*model) def forward(self,",
"28, out_features=512), act] model += [nn.Linear(in_features=512, out_features=256), act] model += [AuxiliaryClassifier(256, 10)] else:",
"stride, padding, bias=bias), nn.Sigmoid()] else: classes = [nn.Linear(in_features, n_classes)] validity = [nn.Linear(in_features, 1),",
"classes = [nn.Linear(in_features, n_classes)] validity = [nn.Linear(in_features, 1), nn.Sigmoid()] self.classes = nn.Sequential(*classes, nn.Softmax",
"norm = nn.BatchNorm2d model = [nn.Linear(100, 512 * 4 * 4), View([512, 4,",
"act] # 4x4 model += [AuxiliaryClassifier(512, 10, kernel_size=4, bias=False, cnn=True)] self.model = nn.Sequential(*model)",
"if isinstance(module, nn.Conv2d) or isinstance(module, nn.ConvTranspose2d): module.weight.detach().normal_(mean=0., std=0.02) elif isinstance(module, nn.BatchNorm2d): module.weight.detach().normal_(1., 0.02)",
"# 14x14 model += [nn.ConvTranspose2d(128, 1, 5, stride=2, padding=2, output_padding=1), nn.Tanh()] # 28x28",
"__init__(self, cnn=False): super(Generator, self).__init__() act = nn.ReLU(inplace=True) if not cnn: model = [nn.Linear(in_features=100,",
"7x7 model += [nn.ConvTranspose2d(256, 128, 5, stride=2, padding=2, output_padding=1), norm(128), act] # 14x14",
"weights_init(module): if isinstance(module, nn.Conv2d) or isinstance(module, nn.ConvTranspose2d): module.weight.detach().normal_(mean=0., std=0.02) elif isinstance(module, nn.BatchNorm2d): module.weight.detach().normal_(1.,",
"act, nn.Dropout(p=0.5)] model += [nn.Linear(in_features=256, out_features=28 * 28), nn.Tanh()] else: norm = nn.BatchNorm2d",
"norm = nn.BatchNorm2d model = [nn.Conv2d(1, 128, 5, stride=2, padding=2, bias=False), act] #",
"forward(self, x): return self.model(x) class Identity(nn.Module): def __init__(self): super(Identity, self).__init__() def forward(self, x):",
"padding=2, output_padding=1), norm(128), act] # 14x14 model += [nn.ConvTranspose2d(128, 1, 5, stride=2, padding=2,",
"128, 5, stride=2, padding=2, bias=False), act] # 14x14 model += [nn.Conv2d(128, 256, 5,",
"model += [AuxiliaryClassifier(512, 10, kernel_size=4, bias=False, cnn=True)] self.model = nn.Sequential(*model) def forward(self, x):",
"else: norm = nn.BatchNorm2d model = [nn.Conv2d(1, 128, 5, stride=2, padding=2, bias=False), act]",
"act] # 4x4 model += [nn.ConvTranspose2d(512, 256, 5, stride=2, padding=2), norm(256), act] #",
"stride=2, padding=2, bias=False), norm(256), act] # 7x7 model += [nn.Conv2d(256, 512, 5, stride=2,",
"28), nn.Tanh()] else: norm = nn.BatchNorm2d model = [nn.Linear(100, 512 * 4 *",
"act] # 7x7 model += [nn.Conv2d(256, 512, 5, stride=2, padding=2, bias=False), norm(512), act]",
"self).__init__() if cnn: classes = [nn.Conv2d(in_features, n_classes, kernel_size, stride, padding, bias=bias)] validity =",
"kernel_size=1, stride=1, padding=0, bias=False, softmax=False, cnn=False): super(AuxiliaryClassifier, self).__init__() if cnn: classes = [nn.Conv2d(in_features,",
"cnn: classes = [nn.Conv2d(in_features, n_classes, kernel_size, stride, padding, bias=bias)] validity = [nn.Conv2d(in_features, n_classes,",
"kernel_size, stride, padding, bias=bias)] validity = [nn.Conv2d(in_features, n_classes, kernel_size, stride, padding, bias=bias), nn.Sigmoid()]",
"stride=2, padding=2, output_padding=1), nn.Tanh()] # 28x28 self.model = nn.Sequential(*model) def forward(self, x): return",
"__init__(self): super(Identity, self).__init__() def forward(self, x): return x class Discriminator(nn.Module): def __init__(self, cnn=False):",
"class View(nn.Module): def __init__(self, output_shape): super(View, self).__init__() self.output_shape = output_shape def forward(self, x):",
"x): return self.classes(x), self.validity(x) class Generator(nn.Module): def __init__(self, cnn=False): super(Generator, self).__init__() act =",
"x class Discriminator(nn.Module): def __init__(self, cnn=False): super(Discriminator, self).__init__() act = nn.LeakyReLU(inplace=True, negative_slope=0.2) if",
"cnn=True)] self.model = nn.Sequential(*model) def forward(self, x): return self.model(x) class View(nn.Module): def __init__(self,",
"class AuxiliaryClassifier(nn.Module): def __init__(self, in_features, n_classes, kernel_size=1, stride=1, padding=0, bias=False, softmax=False, cnn=False): super(AuxiliaryClassifier,",
"+= [nn.Linear(in_features=256, out_features=28 * 28), nn.Tanh()] else: norm = nn.BatchNorm2d model = [nn.Linear(100,",
"forward(self, x): return x.view(x.shape[0], *self.output_shape) def weights_init(module): if isinstance(module, nn.Conv2d) or isinstance(module, nn.ConvTranspose2d):",
"def forward(self, x): return self.model(x) class Identity(nn.Module): def __init__(self): super(Identity, self).__init__() def forward(self,",
"[nn.Conv2d(128, 256, 5, stride=2, padding=2, bias=False), norm(256), act] # 7x7 model += [nn.Conv2d(256,",
"self.output_shape = output_shape def forward(self, x): return x.view(x.shape[0], *self.output_shape) def weights_init(module): if isinstance(module,",
"Generator(nn.Module): def __init__(self, cnn=False): super(Generator, self).__init__() act = nn.ReLU(inplace=True) if not cnn: model",
"padding=0, bias=False, softmax=False, cnn=False): super(AuxiliaryClassifier, self).__init__() if cnn: classes = [nn.Conv2d(in_features, n_classes, kernel_size,",
"= nn.BatchNorm2d model = [nn.Linear(100, 512 * 4 * 4), View([512, 4, 4]),",
"cnn=False): super(Generator, self).__init__() act = nn.ReLU(inplace=True) if not cnn: model = [nn.Linear(in_features=100, out_features=512),",
"[nn.ConvTranspose2d(512, 256, 5, stride=2, padding=2), norm(256), act] # 7x7 model += [nn.ConvTranspose2d(256, 128,",
"5, stride=2, padding=2, bias=False), norm(256), act] # 7x7 model += [nn.Conv2d(256, 512, 5,",
"[nn.Linear(in_features=512, out_features=256), act, nn.Dropout(p=0.5)] model += [nn.Linear(in_features=256, out_features=28 * 28), nn.Tanh()] else: norm",
"if not cnn: model = [nn.Linear(in_features=28 * 28, out_features=512), act] model += [nn.Linear(in_features=512,",
"= nn.ReLU(inplace=True) if not cnn: model = [nn.Linear(in_features=100, out_features=512), act, nn.Dropout(p=0.5)] model +=",
"self.model = nn.Sequential(*model) def forward(self, x): return self.model(x) class Identity(nn.Module): def __init__(self): super(Identity,",
"self.classes(x), self.validity(x) class Generator(nn.Module): def __init__(self, cnn=False): super(Generator, self).__init__() act = nn.ReLU(inplace=True) if",
"256, 5, stride=2, padding=2), norm(256), act] # 7x7 model += [nn.ConvTranspose2d(256, 128, 5,",
"out_features=256), act, nn.Dropout(p=0.5)] model += [nn.Linear(in_features=256, out_features=28 * 28), nn.Tanh()] else: norm =",
"= nn.BatchNorm2d model = [nn.Conv2d(1, 128, 5, stride=2, padding=2, bias=False), act] # 14x14",
"act] # 14x14 model += [nn.Conv2d(128, 256, 5, stride=2, padding=2, bias=False), norm(256), act]",
"[nn.Conv2d(in_features, n_classes, kernel_size, stride, padding, bias=bias), nn.Sigmoid()] else: classes = [nn.Linear(in_features, n_classes)] validity",
"+= [nn.Conv2d(128, 256, 5, stride=2, padding=2, bias=False), norm(256), act] # 7x7 model +=",
"return x.view(x.shape[0], *self.output_shape) def weights_init(module): if isinstance(module, nn.Conv2d) or isinstance(module, nn.ConvTranspose2d): module.weight.detach().normal_(mean=0., std=0.02)",
"bias=False), norm(256), act] # 7x7 model += [nn.Conv2d(256, 512, 5, stride=2, padding=2, bias=False),",
"14x14 model += [nn.Conv2d(128, 256, 5, stride=2, padding=2, bias=False), norm(256), act] # 7x7",
"= nn.LeakyReLU(inplace=True, negative_slope=0.2) if not cnn: model = [nn.Linear(in_features=28 * 28, out_features=512), act]",
"n_classes)] validity = [nn.Linear(in_features, 1), nn.Sigmoid()] self.classes = nn.Sequential(*classes, nn.Softmax if softmax else",
"padding=2, bias=False), norm(512), act] # 4x4 model += [AuxiliaryClassifier(512, 10, kernel_size=4, bias=False, cnn=True)]",
"output_shape): super(View, self).__init__() self.output_shape = output_shape def forward(self, x): return x.view(x.shape[0], *self.output_shape) def",
"__init__(self, output_shape): super(View, self).__init__() self.output_shape = output_shape def forward(self, x): return x.view(x.shape[0], *self.output_shape)",
"out_features=256), act] model += [AuxiliaryClassifier(256, 10)] else: norm = nn.BatchNorm2d model = [nn.Conv2d(1,",
"[nn.Conv2d(1, 128, 5, stride=2, padding=2, bias=False), act] # 14x14 model += [nn.Conv2d(128, 256,",
"n_classes, kernel_size, stride, padding, bias=bias), nn.Sigmoid()] else: classes = [nn.Linear(in_features, n_classes)] validity =",
"cnn: model = [nn.Linear(in_features=100, out_features=512), act, nn.Dropout(p=0.5)] model += [nn.Linear(in_features=512, out_features=256), act, nn.Dropout(p=0.5)]",
"= nn.Sequential(*model) def forward(self, x): return self.model(x) class Identity(nn.Module): def __init__(self): super(Identity, self).__init__()",
"nn.BatchNorm2d model = [nn.Conv2d(1, 128, 5, stride=2, padding=2, bias=False), act] # 14x14 model",
"model += [AuxiliaryClassifier(256, 10)] else: norm = nn.BatchNorm2d model = [nn.Conv2d(1, 128, 5,",
"stride=1, padding=0, bias=False, softmax=False, cnn=False): super(AuxiliaryClassifier, self).__init__() if cnn: classes = [nn.Conv2d(in_features, n_classes,",
"[nn.ConvTranspose2d(128, 1, 5, stride=2, padding=2, output_padding=1), nn.Tanh()] # 28x28 self.model = nn.Sequential(*model) def",
"+= [AuxiliaryClassifier(256, 10)] else: norm = nn.BatchNorm2d model = [nn.Conv2d(1, 128, 5, stride=2,",
"super(Discriminator, self).__init__() act = nn.LeakyReLU(inplace=True, negative_slope=0.2) if not cnn: model = [nn.Linear(in_features=28 *",
"model += [nn.Conv2d(128, 256, 5, stride=2, padding=2, bias=False), norm(256), act] # 7x7 model",
"norm(256), act] # 7x7 model += [nn.Conv2d(256, 512, 5, stride=2, padding=2, bias=False), norm(512),",
"kernel_size=4, bias=False, cnn=True)] self.model = nn.Sequential(*model) def forward(self, x): return self.model(x) class View(nn.Module):",
"nn.BatchNorm2d model = [nn.Linear(100, 512 * 4 * 4), View([512, 4, 4]), norm(512),",
"# 7x7 model += [nn.Conv2d(256, 512, 5, stride=2, padding=2, bias=False), norm(512), act] #",
"else Identity()) self.validity = nn.Sequential(*validity) def forward(self, x): return self.classes(x), self.validity(x) class Generator(nn.Module):",
"padding=2), norm(256), act] # 7x7 model += [nn.ConvTranspose2d(256, 128, 5, stride=2, padding=2, output_padding=1),",
"bias=bias), nn.Sigmoid()] else: classes = [nn.Linear(in_features, n_classes)] validity = [nn.Linear(in_features, 1), nn.Sigmoid()] self.classes",
"def forward(self, x): return self.model(x) class View(nn.Module): def __init__(self, output_shape): super(View, self).__init__() self.output_shape",
"4, 4]), norm(512), act] # 4x4 model += [nn.ConvTranspose2d(512, 256, 5, stride=2, padding=2),",
"super(AuxiliaryClassifier, self).__init__() if cnn: classes = [nn.Conv2d(in_features, n_classes, kernel_size, stride, padding, bias=bias)] validity",
"self).__init__() def forward(self, x): return x class Discriminator(nn.Module): def __init__(self, cnn=False): super(Discriminator, self).__init__()",
"def __init__(self, in_features, n_classes, kernel_size=1, stride=1, padding=0, bias=False, softmax=False, cnn=False): super(AuxiliaryClassifier, self).__init__() if",
"validity = [nn.Linear(in_features, 1), nn.Sigmoid()] self.classes = nn.Sequential(*classes, nn.Softmax if softmax else Identity())",
"out_features=512), act, nn.Dropout(p=0.5)] model += [nn.Linear(in_features=512, out_features=256), act, nn.Dropout(p=0.5)] model += [nn.Linear(in_features=256, out_features=28",
"self).__init__() act = nn.LeakyReLU(inplace=True, negative_slope=0.2) if not cnn: model = [nn.Linear(in_features=28 * 28,",
"padding=2, output_padding=1), nn.Tanh()] # 28x28 self.model = nn.Sequential(*model) def forward(self, x): return self.model(x)",
"[nn.Linear(in_features=28 * 28, out_features=512), act] model += [nn.Linear(in_features=512, out_features=256), act] model += [AuxiliaryClassifier(256,",
"import torch.nn as nn class AuxiliaryClassifier(nn.Module): def __init__(self, in_features, n_classes, kernel_size=1, stride=1, padding=0,",
"*self.output_shape) def weights_init(module): if isinstance(module, nn.Conv2d) or isinstance(module, nn.ConvTranspose2d): module.weight.detach().normal_(mean=0., std=0.02) elif isinstance(module,",
"nn.Conv2d) or isinstance(module, nn.ConvTranspose2d): module.weight.detach().normal_(mean=0., std=0.02) elif isinstance(module, nn.BatchNorm2d): module.weight.detach().normal_(1., 0.02) module.bias.detach().zero_() else:",
"def __init__(self, cnn=False): super(Discriminator, self).__init__() act = nn.LeakyReLU(inplace=True, negative_slope=0.2) if not cnn: model",
"<filename>generation/SGAN/models.py import torch.nn as nn class AuxiliaryClassifier(nn.Module): def __init__(self, in_features, n_classes, kernel_size=1, stride=1,",
"256, 5, stride=2, padding=2, bias=False), norm(256), act] # 7x7 model += [nn.Conv2d(256, 512,",
"* 28), nn.Tanh()] else: norm = nn.BatchNorm2d model = [nn.Linear(100, 512 * 4",
"output_padding=1), norm(128), act] # 14x14 model += [nn.ConvTranspose2d(128, 1, 5, stride=2, padding=2, output_padding=1),",
"def __init__(self): super(Identity, self).__init__() def forward(self, x): return x class Discriminator(nn.Module): def __init__(self,",
"act] model += [nn.Linear(in_features=512, out_features=256), act] model += [AuxiliaryClassifier(256, 10)] else: norm =",
"7x7 model += [nn.Conv2d(256, 512, 5, stride=2, padding=2, bias=False), norm(512), act] # 4x4",
"4 * 4), View([512, 4, 4]), norm(512), act] # 4x4 model += [nn.ConvTranspose2d(512,",
"[AuxiliaryClassifier(512, 10, kernel_size=4, bias=False, cnn=True)] self.model = nn.Sequential(*model) def forward(self, x): return self.model(x)",
"if cnn: classes = [nn.Conv2d(in_features, n_classes, kernel_size, stride, padding, bias=bias)] validity = [nn.Conv2d(in_features,",
"1, 5, stride=2, padding=2, output_padding=1), nn.Tanh()] # 28x28 self.model = nn.Sequential(*model) def forward(self,",
"output_padding=1), nn.Tanh()] # 28x28 self.model = nn.Sequential(*model) def forward(self, x): return self.model(x) class",
"# 7x7 model += [nn.ConvTranspose2d(256, 128, 5, stride=2, padding=2, output_padding=1), norm(128), act] #",
"in_features, n_classes, kernel_size=1, stride=1, padding=0, bias=False, softmax=False, cnn=False): super(AuxiliaryClassifier, self).__init__() if cnn: classes",
"bias=False, softmax=False, cnn=False): super(AuxiliaryClassifier, self).__init__() if cnn: classes = [nn.Conv2d(in_features, n_classes, kernel_size, stride,",
"= [nn.Linear(in_features, 1), nn.Sigmoid()] self.classes = nn.Sequential(*classes, nn.Softmax if softmax else Identity()) self.validity",
"= nn.Sequential(*validity) def forward(self, x): return self.classes(x), self.validity(x) class Generator(nn.Module): def __init__(self, cnn=False):",
"classes = [nn.Conv2d(in_features, n_classes, kernel_size, stride, padding, bias=bias)] validity = [nn.Conv2d(in_features, n_classes, kernel_size,",
"= [nn.Linear(in_features, n_classes)] validity = [nn.Linear(in_features, 1), nn.Sigmoid()] self.classes = nn.Sequential(*classes, nn.Softmax if",
"act, nn.Dropout(p=0.5)] model += [nn.Linear(in_features=512, out_features=256), act, nn.Dropout(p=0.5)] model += [nn.Linear(in_features=256, out_features=28 *",
"[nn.Linear(in_features, 1), nn.Sigmoid()] self.classes = nn.Sequential(*classes, nn.Softmax if softmax else Identity()) self.validity =",
"+= [nn.ConvTranspose2d(512, 256, 5, stride=2, padding=2), norm(256), act] # 7x7 model += [nn.ConvTranspose2d(256,",
"forward(self, x): return self.classes(x), self.validity(x) class Generator(nn.Module): def __init__(self, cnn=False): super(Generator, self).__init__() act",
"class Generator(nn.Module): def __init__(self, cnn=False): super(Generator, self).__init__() act = nn.ReLU(inplace=True) if not cnn:"
] |
[
"= readImageSet(collection, collection, rootpath) self.nr_of_images = len(self.imset) self.knndir = os.path.join(collection, '%s,%sknn,uu,1500' % (feature,",
"dist) in neighbors: (userid,tags) = self.textstore.get(name, (None, None)) if tags is None: skip",
"in neighbors: (userid,tags) = self.textstore.get(name, (None, None)) if tags is None: skip +=",
"collection, rootpath) self.nr_of_images = len(self.imset) self.knndir = os.path.join(collection, '%s,%sknn,uu,1500' % (feature, distance)) self.k",
"self.concepts] # vote only on the given concept list voted = 0 skip",
"collection, annotationName, feature, distance, tpp=DEFAULT_TPP, rootpath=ROOT_PATH): self.rootpath = rootpath self.concepts = readConcepts(collection, annotationName,",
"self.searcher.search_knn(content, max_hits=max(3000,self.k*3)) def _compute(self, content, context=None): users_voted = set() vote = [0-self.tagprior(c) for",
"0 skip = 0 neighbors = self._get_neighbors(content, context) for (name, dist) in neighbors:",
"distance, self.k)) def _compute(self, content, context=None): vote = [0] * self.nr_of_concepts # vote",
"rootpath self.concepts = readConcepts(collection, annotationName, rootpath) self.nr_of_concepts = len(self.concepts) self.concept2index = dict(zip(self.concepts, range(self.nr_of_concepts)))",
"c_idx >= 0: vote[c_idx] += 1 voted += 1 if voted >= self.k:",
"continue tagset = set(tags.split()) for tag in tagset: c_idx = self.concept2index.get(tag, -1) if",
"'pqtagvote':PqTagVoteTagger} if __name__ == '__main__': feature = 'vgg-verydeep-16-fc7relu' tagger = TagVoteTagger('train10k', 'concepts81.txt', feature,",
"return vote class PqTagVoteTagger (TagVoteTagger): def __init__(self, collection, annotationName, feature, distance, tpp=DEFAULT_TPP, rootpath=ROOT_PATH):",
"testCollection,testid = context.split(',') knnfile = os.path.join(self.rootpath, testCollection, 'SimilarityIndex', testCollection, self.knndir, testid[-2:], '%s.txt' %",
"= os.path.join(featuredir, \"id.txt\") shape_file = os.path.join(feat_dir, 'shape.txt') self.nr_of_images, feat_dim = map(int, open(shape_file).readline().split()) self.searcher",
"'cosine') tagger = PreTagVoteTagger('train10k', 'concepts81.txt', feature, 'cosine') tagger = PreKnnTagger('train10k', 'conceptsmir14.txt', feature, 'cosine')",
"for c in self.concepts] # vote only on the given concept list voted",
"continue users_voted.add(userid) tagset = set(tags.split()) for tag in tagset: c_idx = self.concept2index.get(tag, -1)",
"users_voted: skip += 1 continue users_voted.add(userid) tagset = set(tags.split()) for tag in tagset:",
"rootpath) self.nr_of_concepts = len(self.concepts) self.concept2index = dict(zip(self.concepts, range(self.nr_of_concepts))) self.imset = readImageSet(collection, collection, rootpath)",
"1 continue users_voted.add(userid) tagset = set(tags.split()) for tag in tagset: c_idx = self.concept2index.get(tag,",
"'shape.txt') self.nr_of_images, feat_dim = map(int, open(shape_file).readline().split()) self.searcher = simpleknn.load_model(os.path.join(feat_dir, 'feature.bin'), feat_dim, self.nr_of_images, id_file)",
"v:v[1], reverse=True) class PreTagVoteTagger (TagVoteTagger): def __init__(self, collection, annotationName, feature, distance, tpp=DEFAULT_TPP, rootpath=ROOT_PATH):",
"tpp=DEFAULT_TPP, rootpath=ROOT_PATH): self.concepts = readConcepts(collection, annotationName, rootpath) self.nr_of_concepts = len(self.concepts) self.concept2index = dict(zip(self.concepts,",
"(%d) in %d neighbors' % (skip, len(neighbors)) return vote class PqTagVoteTagger (TagVoteTagger): def",
"= (userid, tags) tagset = set(tags.split()) for tag in tagset: self.tag2freq[tag] = self.tag2freq.get(tag,0)",
"in %d neighbors' % (skip, len(neighbors)) return vote def predict(self, content, context=None): scores",
"\"id.txt\") shape_file = os.path.join(feat_dir, 'shape.txt') self.nr_of_images, feat_dim = map(int, open(shape_file).readline().split()) self.searcher = load_model(featuredir,",
"= map(int, open(shape_file).readline().split()) self.searcher = simpleknn.load_model(os.path.join(feat_dir, 'feature.bin'), feat_dim, self.nr_of_images, id_file) self.searcher.set_distance(distance) self.k =",
"distance, self.k)) def _load_tag_data(self, collection, tpp, rootpath): tagfile = os.path.join(rootpath, collection, \"TextData\", \"id.userid.%stags.txt\"",
"testid[-2:], '%s.txt' % testid) knn = readRankingResults(knnfile) knn = knn[:self.k] if self.noise >",
"1 if voted >= self.k: break #assert(voted >= self.k), 'too many skips (%d)",
"self.noise > 1e-3: n = int(len(knn) * self.noise) hits = random.sample(xrange(len(knn)), n) random_set",
"0: vote[c_idx] += 1 voted += 1 if voted >= self.k: break #assert(voted",
"feat_dim = map(int, open(shape_file).readline().split()) self.searcher = load_model(featuredir, self.nr_of_images, feat_dim,nr_of_segments=512,segmentk=256,coarsek=4096) self.k = DEFAULT_K self._load_tag_data(collection,",
"set(tags.split()) for tag in tagset: c_idx = self.concept2index.get(tag, -1) if c_idx >= 0:",
"reverse=True) class PreTagVoteTagger (TagVoteTagger): def __init__(self, collection, annotationName, feature, distance, tpp=DEFAULT_TPP, rootpath=ROOT_PATH): self.rootpath",
"noise): self.noise = noise def _get_neighbors(self, content, context): testCollection,testid = context.split(',') knnfile =",
"_compute(self, content, context=None): vote = [0] * self.nr_of_concepts # vote only on the",
"sandbox.pquan.pqsearch import load_model INFO = __file__ DEFAULT_K=1000 DEFAULT_TPP = 'lemm' DEFAULT_DISTANCE = 'l1'",
"DEFAULT_TPP = 'lemm' DEFAULT_DISTANCE = 'l1' DEFAULT_BLOCK_SIZE = 1000 DEFAULT_TAGGER = 'tagvote' class",
"self.noise) hits = random.sample(xrange(len(knn)), n) random_set = random.sample(self.imset, n) for i in range(n):",
"basic.common import printStatus, readRankingResults from basic.util import readImageSet from basic.annotationtable import readConcepts from",
"__init__(self, collection, annotationName, feature, distance, tpp=DEFAULT_TPP, rootpath=ROOT_PATH, k = DEFAULT_K): self.rootpath = rootpath",
"feature, distance, tpp=DEFAULT_TPP, rootpath=ROOT_PATH): self.rootpath = rootpath self.concepts = readConcepts(collection, annotationName, rootpath) self.nr_of_concepts",
"for voting\" % (self.__class__.__name__, self.nr_of_images, len(self.tag2freq), distance, self.k)) def _get_neighbors(self, content, context): return",
"readImageSet(collection, collection, rootpath) self.nr_of_images = len(self.imset) self.knndir = os.path.join(collection, '%s,%sknn,uu,1500' % (feature, distance))",
"self.noise = 0 self._load_tag_data(collection, tpp, rootpath) printStatus(INFO, \"%s, %d images, %d unique tags,",
"self.concept2index.get(tag, -1) if c_idx >= 0: vote[c_idx] += 1 voted += 1 if",
"(skip, len(neighbors)) return vote class PqTagVoteTagger (TagVoteTagger): def __init__(self, collection, annotationName, feature, distance,",
"if tags is None or userid in users_voted: skip += 1 continue users_voted.add(userid)",
"if voted >= self.k: break #assert(voted >= self.k), 'too many skips (%d) in",
"tags = tags.lower() self.textstore[imageid] = (userid, tags) tagset = set(tags.split()) for tag in",
"neighbors = self._get_neighbors(content, context) for (name, dist) in neighbors: (userid,tags) = self.textstore.get(name, (None,",
"userid in users_voted: skip += 1 continue users_voted.add(userid) tagset = set(tags.split()) for tag",
"_load_tag_data(self, collection, tpp, rootpath): tagfile = os.path.join(rootpath, collection, \"TextData\", \"id.userid.%stags.txt\" % tpp) self.textstore",
"os.path.join(rootpath, collection, \"FeatureData\", feature) id_file = os.path.join(feat_dir, 'id.txt') shape_file = os.path.join(feat_dir, 'shape.txt') self.nr_of_images,",
"= readConcepts(collection, annotationName, rootpath) self.nr_of_concepts = len(self.concepts) self.concept2index = dict(zip(self.concepts, range(self.nr_of_concepts))) self.imset =",
"rootpath) printStatus(INFO, \"%s, %d images, %d unique tags, %s %d neighbours for voting\"",
"= len(self.imset) self.knndir = os.path.join(collection, '%s,%sknn,uu,1500' % (feature, distance)) self.k = DEFAULT_K self.noise",
"scores = self._compute(content, context) return sorted(zip(self.concepts, scores), key=lambda v:v[1], reverse=True) class PreTagVoteTagger (TagVoteTagger):",
"basic.util import readImageSet from basic.annotationtable import readConcepts from util.simpleknn import simpleknn #from sandbox.pquan.pqsearch",
"(userid, tags) tagset = set(tags.split()) for tag in tagset: self.tag2freq[tag] = self.tag2freq.get(tag,0) +",
"%s %d neighbours for voting\" % (self.__class__.__name__, self.nr_of_images, len(self.tag2freq), distance, self.k)) def _compute(self,",
"= 0 self._load_tag_data(collection, tpp, rootpath) printStatus(INFO, \"%s, %d images, %d unique tags, %s",
"self.nr_of_images, len(self.tag2freq), distance, self.k)) def set_noise(self, noise): self.noise = noise def _get_neighbors(self, content,",
"(feature, distance)) self.k = k self.noise = 0 self._load_tag_data(collection, tpp, rootpath) printStatus(INFO, \"%s,",
"'id.txt') shape_file = os.path.join(feat_dir, 'shape.txt') self.nr_of_images, feat_dim = map(int, open(shape_file).readline().split()) self.searcher = simpleknn.load_model(os.path.join(feat_dir,",
"self.searcher = load_model(featuredir, self.nr_of_images, feat_dim,nr_of_segments=512,segmentk=256,coarsek=4096) self.k = DEFAULT_K self._load_tag_data(collection, tpp, rootpath) printStatus(INFO, \"%s,",
"+ 1 def tagprior(self, tag): return float(self.k) * self.tag2freq.get(tag,0) / self.nr_of_images def _get_neighbors(self,",
"(name, dist) in neighbors: (userid,tags) = self.textstore.get(name, (None, None)) if tags is None",
"len(self.tag2freq), distance, self.k)) def set_noise(self, noise): self.noise = noise def _get_neighbors(self, content, context):",
"self.noise = noise def _get_neighbors(self, content, context): testCollection,testid = context.split(',') knnfile = os.path.join(self.rootpath,",
"== '__main__': feature = 'vgg-verydeep-16-fc7relu' tagger = TagVoteTagger('train10k', 'concepts81.txt', feature, 'cosine') tagger =",
"self.tag2freq.get(tag,0) / self.nr_of_images def _get_neighbors(self, content, context): return self.searcher.search_knn(content, max_hits=max(3000,self.k*3)) def _compute(self, content,",
"= 'l1' DEFAULT_BLOCK_SIZE = 1000 DEFAULT_TAGGER = 'tagvote' class TagVoteTagger: def __init__(self, collection,",
"set_noise(self, noise): self.noise = noise def _get_neighbors(self, content, context): testCollection,testid = context.split(',') knnfile",
"feature, distance, tpp=DEFAULT_TPP, rootpath=ROOT_PATH, k = DEFAULT_K): self.rootpath = rootpath self.concepts = readConcepts(collection,",
"= self.tag2freq.get(tag,0) + 1 def tagprior(self, tag): return float(self.k) * self.tag2freq.get(tag,0) / self.nr_of_images",
"context=None): vote = [0] * self.nr_of_concepts # vote only on the given concept",
"content, context): return self.searcher.search_knn(content, requested=max(3000, self.k*3)) NAME_TO_TAGGER = {'tagvote':TagVoteTagger, 'pretagvote':PreTagVoteTagger, 'preknn':PreKnnTagger, 'pqtagvote':PqTagVoteTagger} if",
"os.path.join(collection, '%s,%sknn,1500' % (feature, distance)) self.k = k self.noise = 0 self._load_tag_data(collection, tpp,",
"annotationName, feature, distance, tpp=DEFAULT_TPP, rootpath=ROOT_PATH): self.rootpath = rootpath self.concepts = readConcepts(collection, annotationName, rootpath)",
"self.nr_of_images, id_file) self.searcher.set_distance(distance) self.k = DEFAULT_K self._load_tag_data(collection, tpp, rootpath) printStatus(INFO, \"%s, %d images,",
"self.tag2freq[tag] = self.tag2freq.get(tag,0) + 1 def tagprior(self, tag): return float(self.k) * self.tag2freq.get(tag,0) /",
"self.k = k self.noise = 0 self._load_tag_data(collection, tpp, rootpath) printStatus(INFO, \"%s, %d images,",
"'shape.txt') self.nr_of_images, feat_dim = map(int, open(shape_file).readline().split()) self.searcher = load_model(featuredir, self.nr_of_images, feat_dim,nr_of_segments=512,segmentk=256,coarsek=4096) self.k =",
"if tags is None: skip += 1 continue tagset = set(tags.split()) for tag",
"context): return self.searcher.search_knn(content, requested=max(3000, self.k*3)) NAME_TO_TAGGER = {'tagvote':TagVoteTagger, 'pretagvote':PreTagVoteTagger, 'preknn':PreKnnTagger, 'pqtagvote':PqTagVoteTagger} if __name__",
"len(self.concepts) self.concept2index = dict(zip(self.concepts, range(self.nr_of_concepts))) self.imset = readImageSet(collection, collection, rootpath) self.nr_of_images = len(self.imset)",
"def __init__(self, collection, annotationName, feature, distance, tpp=DEFAULT_TPP, rootpath=ROOT_PATH): self.rootpath = rootpath self.concepts =",
"'%s,%sknn,1500' % (feature, distance)) self.k = k self.noise = 0 self._load_tag_data(collection, tpp, rootpath)",
"0 neighbors = self._get_neighbors(content, context) for (name, dist) in neighbors: (userid,tags) = self.textstore.get(name,",
"len(self.tag2freq), distance, self.k)) def _load_tag_data(self, collection, tpp, rootpath): tagfile = os.path.join(rootpath, collection, \"TextData\",",
"os.path.join(self.rootpath, testCollection, 'SimilarityIndex', testCollection, self.knndir, testid[-2:], '%s.txt' % testid) knn = readRankingResults(knnfile) knn",
"+= 1 continue users_voted.add(userid) tagset = set(tags.split()) for tag in tagset: c_idx =",
"0 self._load_tag_data(collection, tpp, rootpath) printStatus(INFO, \"%s, %d images, %d unique tags, %s %d",
"self._get_neighbors(content, context) for (name, dist) in neighbors: (userid,tags) = self.textstore.get(name, (None, None)) if",
"<reponame>vohoaiviet/tag-image-retrieval import sys, os, time, random from basic.constant import ROOT_PATH from basic.common import",
"self.nr_of_images, feat_dim,nr_of_segments=512,segmentk=256,coarsek=4096) self.k = DEFAULT_K self._load_tag_data(collection, tpp, rootpath) printStatus(INFO, \"%s, %d images, %d",
"random.sample(xrange(len(knn)), n) random_set = random.sample(self.imset, n) for i in range(n): idx = hits[i]",
"tpp, rootpath): tagfile = os.path.join(rootpath, collection, \"TextData\", \"id.userid.%stags.txt\" % tpp) self.textstore = {}",
"scores), key=lambda v:v[1], reverse=True) class PreTagVoteTagger (TagVoteTagger): def __init__(self, collection, annotationName, feature, distance,",
"in users_voted: skip += 1 continue users_voted.add(userid) tagset = set(tags.split()) for tag in",
"rootpath=ROOT_PATH): self.concepts = readConcepts(collection, annotationName, rootpath) self.nr_of_concepts = len(self.concepts) self.concept2index = dict(zip(self.concepts, range(self.nr_of_concepts)))",
"readImageSet from basic.annotationtable import readConcepts from util.simpleknn import simpleknn #from sandbox.pquan.pqsearch import load_model",
"for voting\" % (self.__class__.__name__, self.nr_of_images, len(self.tag2freq), distance, self.k)) def _load_tag_data(self, collection, tpp, rootpath):",
"len(self.imset) self.knndir = os.path.join(collection, '%s,%sknn,uu,1500' % (feature, distance)) self.k = DEFAULT_K self.noise =",
"n = int(len(knn) * self.noise) hits = random.sample(xrange(len(knn)), n) random_set = random.sample(self.imset, n)",
"self.nr_of_images, len(self.tag2freq), distance, self.k)) def _compute(self, content, context=None): vote = [0] * self.nr_of_concepts",
"= context.split(',') knnfile = os.path.join(self.rootpath, testCollection, 'SimilarityIndex', testCollection, self.knndir, testid[-2:], '%s.txt' % testid)",
"n) for i in range(n): idx = hits[i] knn[idx] = (random_set[i], 1000) return",
"1000 DEFAULT_TAGGER = 'tagvote' class TagVoteTagger: def __init__(self, collection, annotationName, feature, distance, tpp=DEFAULT_TPP,",
"= 0 skip = 0 neighbors = self._get_neighbors(content, context) for (name, dist) in",
"= hits[i] knn[idx] = (random_set[i], 1000) return knn class PreKnnTagger (PreTagVoteTagger): def __init__(self,",
"DEFAULT_TAGGER = 'tagvote' class TagVoteTagger: def __init__(self, collection, annotationName, feature, distance, tpp=DEFAULT_TPP, rootpath=ROOT_PATH):",
"import printStatus, readRankingResults from basic.util import readImageSet from basic.annotationtable import readConcepts from util.simpleknn",
"load_model INFO = __file__ DEFAULT_K=1000 DEFAULT_TPP = 'lemm' DEFAULT_DISTANCE = 'l1' DEFAULT_BLOCK_SIZE =",
"the given concept list voted = 0 skip = 0 neighbors = self._get_neighbors(content,",
"neighbours for voting\" % (self.__class__.__name__, self.nr_of_images, len(self.tag2freq), distance, self.k)) def _compute(self, content, context=None):",
"if self.noise > 1e-3: n = int(len(knn) * self.noise) hits = random.sample(xrange(len(knn)), n)",
"+= 1 voted += 1 if voted >= self.k: break #assert(voted >= self.k),",
"\"TextData\", \"id.userid.%stags.txt\" % tpp) self.textstore = {} self.tag2freq = {} for line in",
"len(neighbors)) return vote def predict(self, content, context=None): scores = self._compute(content, context) return sorted(zip(self.concepts,",
"% (self.__class__.__name__, self.nr_of_images, len(self.tag2freq), distance, self.k)) def set_noise(self, noise): self.noise = noise def",
"+= 1 if voted >= self.k: break #assert(voted >= self.k), 'too many skips",
"neighbours for voting\" % (self.__class__.__name__, self.nr_of_images, len(self.tag2freq), distance, self.k)) def set_noise(self, noise): self.noise",
"(self.__class__.__name__, self.nr_of_images, len(self.tag2freq), distance, self.k)) def _load_tag_data(self, collection, tpp, rootpath): tagfile = os.path.join(rootpath,",
"sorted(zip(self.concepts, scores), key=lambda v:v[1], reverse=True) class PreTagVoteTagger (TagVoteTagger): def __init__(self, collection, annotationName, feature,",
"1000) return knn class PreKnnTagger (PreTagVoteTagger): def __init__(self, collection, annotationName, feature, distance, tpp=DEFAULT_TPP,",
"#assert(voted >= self.k), 'too many skips (%d) in %d neighbors' % (skip, len(neighbors))",
"annotationName, rootpath) self.nr_of_concepts = len(self.concepts) self.concept2index = dict(zip(self.concepts, range(self.nr_of_concepts))) featuredir = os.path.join(rootpath,collection,'FeatureData',feature) id_file",
"readConcepts(collection, annotationName, rootpath) self.nr_of_concepts = len(self.concepts) self.concept2index = dict(zip(self.concepts, range(self.nr_of_concepts))) feat_dir = os.path.join(rootpath,",
"= random.sample(self.imset, n) for i in range(n): idx = hits[i] knn[idx] = (random_set[i],",
"open(tagfile): imageid, userid, tags = line.split('\\t') tags = tags.lower() self.textstore[imageid] = (userid, tags)",
"simpleknn #from sandbox.pquan.pqsearch import load_model INFO = __file__ DEFAULT_K=1000 DEFAULT_TPP = 'lemm' DEFAULT_DISTANCE",
"= 1000 DEFAULT_TAGGER = 'tagvote' class TagVoteTagger: def __init__(self, collection, annotationName, feature, distance,",
"os.path.join(feat_dir, 'shape.txt') self.nr_of_images, feat_dim = map(int, open(shape_file).readline().split()) self.searcher = simpleknn.load_model(os.path.join(feat_dir, 'feature.bin'), feat_dim, self.nr_of_images,",
"self.k)) def _compute(self, content, context=None): vote = [0] * self.nr_of_concepts # vote only",
"collection, rootpath) self.nr_of_images = len(self.imset) self.knndir = os.path.join(collection, '%s,%sknn,1500' % (feature, distance)) self.k",
"range(self.nr_of_concepts))) feat_dir = os.path.join(rootpath, collection, \"FeatureData\", feature) id_file = os.path.join(feat_dir, 'id.txt') shape_file =",
"len(self.tag2freq), distance, self.k)) def _get_neighbors(self, content, context): return self.searcher.search_knn(content, requested=max(3000, self.k*3)) NAME_TO_TAGGER =",
"neighbors' % (skip, len(neighbors)) return vote def predict(self, content, context=None): scores = self._compute(content,",
"DEFAULT_BLOCK_SIZE = 1000 DEFAULT_TAGGER = 'tagvote' class TagVoteTagger: def __init__(self, collection, annotationName, feature,",
"self.searcher = simpleknn.load_model(os.path.join(feat_dir, 'feature.bin'), feat_dim, self.nr_of_images, id_file) self.searcher.set_distance(distance) self.k = DEFAULT_K self._load_tag_data(collection, tpp,",
"# vote only on the given concept list voted = 0 skip =",
"'preknn':PreKnnTagger, 'pqtagvote':PqTagVoteTagger} if __name__ == '__main__': feature = 'vgg-verydeep-16-fc7relu' tagger = TagVoteTagger('train10k', 'concepts81.txt',",
"'tagvote' class TagVoteTagger: def __init__(self, collection, annotationName, feature, distance, tpp=DEFAULT_TPP, rootpath=ROOT_PATH): self.concepts =",
"[0] * self.nr_of_concepts # vote only on the given concept list voted =",
"annotationName, rootpath) self.nr_of_concepts = len(self.concepts) self.concept2index = dict(zip(self.concepts, range(self.nr_of_concepts))) self.imset = readImageSet(collection, collection,",
"DEFAULT_DISTANCE = 'l1' DEFAULT_BLOCK_SIZE = 1000 DEFAULT_TAGGER = 'tagvote' class TagVoteTagger: def __init__(self,",
"users_voted.add(userid) tagset = set(tags.split()) for tag in tagset: c_idx = self.concept2index.get(tag, -1) if",
"% (skip, len(neighbors)) return vote def predict(self, content, context=None): scores = self._compute(content, context)",
"from basic.annotationtable import readConcepts from util.simpleknn import simpleknn #from sandbox.pquan.pqsearch import load_model INFO",
"self.nr_of_images, feat_dim = map(int, open(shape_file).readline().split()) self.searcher = simpleknn.load_model(os.path.join(feat_dir, 'feature.bin'), feat_dim, self.nr_of_images, id_file) self.searcher.set_distance(distance)",
"(userid,tags) = self.textstore.get(name, (None, None)) if tags is None: skip += 1 continue",
"distance)) self.k = DEFAULT_K self.noise = 0 self._load_tag_data(collection, tpp, rootpath) printStatus(INFO, \"%s, %d",
"dist) in neighbors: (userid,tags) = self.textstore.get(name, (None, None)) if tags is None or",
"neighbours for voting\" % (self.__class__.__name__, self.nr_of_images, len(self.tag2freq), distance, self.k)) def _get_neighbors(self, content, context):",
"= k self.noise = 0 self._load_tag_data(collection, tpp, rootpath) printStatus(INFO, \"%s, %d images, %d",
"= noise def _get_neighbors(self, content, context): testCollection,testid = context.split(',') knnfile = os.path.join(self.rootpath, testCollection,",
"(%d) in %d neighbors' % (skip, len(neighbors)) return vote def predict(self, content, context=None):",
"len(neighbors)) return vote class PqTagVoteTagger (TagVoteTagger): def __init__(self, collection, annotationName, feature, distance, tpp=DEFAULT_TPP,",
"self.concept2index = dict(zip(self.concepts, range(self.nr_of_concepts))) featuredir = os.path.join(rootpath,collection,'FeatureData',feature) id_file = os.path.join(featuredir, \"id.txt\") shape_file =",
"float(self.k) * self.tag2freq.get(tag,0) / self.nr_of_images def _get_neighbors(self, content, context): return self.searcher.search_knn(content, max_hits=max(3000,self.k*3)) def",
"self.nr_of_images, len(self.tag2freq), distance, self.k)) def _get_neighbors(self, content, context): return self.searcher.search_knn(content, requested=max(3000, self.k*3)) NAME_TO_TAGGER",
"line in open(tagfile): imageid, userid, tags = line.split('\\t') tags = tags.lower() self.textstore[imageid] =",
"tag in tagset: c_idx = self.concept2index.get(tag, -1) if c_idx >= 0: vote[c_idx] +=",
"NAME_TO_TAGGER = {'tagvote':TagVoteTagger, 'pretagvote':PreTagVoteTagger, 'preknn':PreKnnTagger, 'pqtagvote':PqTagVoteTagger} if __name__ == '__main__': feature = 'vgg-verydeep-16-fc7relu'",
"n) random_set = random.sample(self.imset, n) for i in range(n): idx = hits[i] knn[idx]",
"import load_model INFO = __file__ DEFAULT_K=1000 DEFAULT_TPP = 'lemm' DEFAULT_DISTANCE = 'l1' DEFAULT_BLOCK_SIZE",
"featuredir = os.path.join(rootpath,collection,'FeatureData',feature) id_file = os.path.join(featuredir, \"id.txt\") shape_file = os.path.join(feat_dir, 'shape.txt') self.nr_of_images, feat_dim",
"class PreKnnTagger (PreTagVoteTagger): def __init__(self, collection, annotationName, feature, distance, tpp=DEFAULT_TPP, rootpath=ROOT_PATH, k =",
"userid, tags = line.split('\\t') tags = tags.lower() self.textstore[imageid] = (userid, tags) tagset =",
"tagprior(self, tag): return float(self.k) * self.tag2freq.get(tag,0) / self.nr_of_images def _get_neighbors(self, content, context): return",
"= DEFAULT_K self._load_tag_data(collection, tpp, rootpath) printStatus(INFO, \"%s, %d images, %d unique tags, %s",
"set() vote = [0-self.tagprior(c) for c in self.concepts] # vote only on the",
"tpp=DEFAULT_TPP, rootpath=ROOT_PATH, k = DEFAULT_K): self.rootpath = rootpath self.concepts = readConcepts(collection, annotationName, rootpath)",
"import simpleknn #from sandbox.pquan.pqsearch import load_model INFO = __file__ DEFAULT_K=1000 DEFAULT_TPP = 'lemm'",
"in %d neighbors' % (skip, len(neighbors)) return vote class PqTagVoteTagger (TagVoteTagger): def __init__(self,",
"if __name__ == '__main__': feature = 'vgg-verydeep-16-fc7relu' tagger = TagVoteTagger('train10k', 'concepts81.txt', feature, 'cosine')",
"__name__ == '__main__': feature = 'vgg-verydeep-16-fc7relu' tagger = TagVoteTagger('train10k', 'concepts81.txt', feature, 'cosine') tagger",
"readConcepts from util.simpleknn import simpleknn #from sandbox.pquan.pqsearch import load_model INFO = __file__ DEFAULT_K=1000",
"#from sandbox.pquan.pqsearch import load_model INFO = __file__ DEFAULT_K=1000 DEFAULT_TPP = 'lemm' DEFAULT_DISTANCE =",
"from basic.constant import ROOT_PATH from basic.common import printStatus, readRankingResults from basic.util import readImageSet",
"in tagset: self.tag2freq[tag] = self.tag2freq.get(tag,0) + 1 def tagprior(self, tag): return float(self.k) *",
"TagVoteTagger('train10k', 'concepts81.txt', feature, 'cosine') tagger = PreTagVoteTagger('train10k', 'concepts81.txt', feature, 'cosine') tagger = PreKnnTagger('train10k',",
"knn = knn[:self.k] if self.noise > 1e-3: n = int(len(knn) * self.noise) hits",
"context): return self.searcher.search_knn(content, max_hits=max(3000,self.k*3)) def _compute(self, content, context=None): users_voted = set() vote =",
"= TagVoteTagger('train10k', 'concepts81.txt', feature, 'cosine') tagger = PreTagVoteTagger('train10k', 'concepts81.txt', feature, 'cosine') tagger =",
"__file__ DEFAULT_K=1000 DEFAULT_TPP = 'lemm' DEFAULT_DISTANCE = 'l1' DEFAULT_BLOCK_SIZE = 1000 DEFAULT_TAGGER =",
">= 0: vote[c_idx] += 1 voted += 1 if voted >= self.k: break",
"_get_neighbors(self, content, context): return self.searcher.search_knn(content, requested=max(3000, self.k*3)) NAME_TO_TAGGER = {'tagvote':TagVoteTagger, 'pretagvote':PreTagVoteTagger, 'preknn':PreKnnTagger, 'pqtagvote':PqTagVoteTagger}",
"from util.simpleknn import simpleknn #from sandbox.pquan.pqsearch import load_model INFO = __file__ DEFAULT_K=1000 DEFAULT_TPP",
"context): testCollection,testid = context.split(',') knnfile = os.path.join(self.rootpath, testCollection, 'SimilarityIndex', testCollection, self.knndir, testid[-2:], '%s.txt'",
"\"%s, %d images, %d unique tags, %s %d neighbours for voting\" % (self.__class__.__name__,",
"self.k)) def _get_neighbors(self, content, context): return self.searcher.search_knn(content, requested=max(3000, self.k*3)) NAME_TO_TAGGER = {'tagvote':TagVoteTagger, 'pretagvote':PreTagVoteTagger,",
"DEFAULT_K self.noise = 0 self._load_tag_data(collection, tpp, rootpath) printStatus(INFO, \"%s, %d images, %d unique",
"feature, 'cosine') tagger = PreTagVoteTagger('train10k', 'concepts81.txt', feature, 'cosine') tagger = PreKnnTagger('train10k', 'conceptsmir14.txt', feature,",
"ROOT_PATH from basic.common import printStatus, readRankingResults from basic.util import readImageSet from basic.annotationtable import",
"knn[:self.k] if self.noise > 1e-3: n = int(len(knn) * self.noise) hits = random.sample(xrange(len(knn)),",
"len(self.tag2freq), distance, self.k)) def _compute(self, content, context=None): vote = [0] * self.nr_of_concepts #",
"knn[idx] = (random_set[i], 1000) return knn class PreKnnTagger (PreTagVoteTagger): def __init__(self, collection, annotationName,",
"self.knndir = os.path.join(collection, '%s,%sknn,1500' % (feature, distance)) self.k = k self.noise = 0",
"+= 1 continue tagset = set(tags.split()) for tag in tagset: c_idx = self.concept2index.get(tag,",
"import readImageSet from basic.annotationtable import readConcepts from util.simpleknn import simpleknn #from sandbox.pquan.pqsearch import",
"'SimilarityIndex', testCollection, self.knndir, testid[-2:], '%s.txt' % testid) knn = readRankingResults(knnfile) knn = knn[:self.k]",
"_get_neighbors(self, content, context): testCollection,testid = context.split(',') knnfile = os.path.join(self.rootpath, testCollection, 'SimilarityIndex', testCollection, self.knndir,",
"PreKnnTagger (PreTagVoteTagger): def __init__(self, collection, annotationName, feature, distance, tpp=DEFAULT_TPP, rootpath=ROOT_PATH, k = DEFAULT_K):",
"PreTagVoteTagger (TagVoteTagger): def __init__(self, collection, annotationName, feature, distance, tpp=DEFAULT_TPP, rootpath=ROOT_PATH): self.rootpath = rootpath",
"self.concepts = readConcepts(collection, annotationName, rootpath) self.nr_of_concepts = len(self.concepts) self.concept2index = dict(zip(self.concepts, range(self.nr_of_concepts))) self.imset",
"import sys, os, time, random from basic.constant import ROOT_PATH from basic.common import printStatus,",
"%s %d neighbours for voting\" % (self.__class__.__name__, self.nr_of_images, len(self.tag2freq), distance, self.k)) def _get_neighbors(self,",
"voted >= self.k: break #assert(voted >= self.k), 'too many skips (%d) in %d",
"[0-self.tagprior(c) for c in self.concepts] # vote only on the given concept list",
"(TagVoteTagger): def __init__(self, collection, annotationName, feature, distance, tpp=DEFAULT_TPP, rootpath=ROOT_PATH): self.rootpath = rootpath self.concepts",
"self.nr_of_concepts = len(self.concepts) self.concept2index = dict(zip(self.concepts, range(self.nr_of_concepts))) feat_dir = os.path.join(rootpath, collection, \"FeatureData\", feature)",
"readRankingResults(knnfile) knn = knn[:self.k] if self.noise > 1e-3: n = int(len(knn) * self.noise)",
"(feature, distance)) self.k = DEFAULT_K self.noise = 0 self._load_tag_data(collection, tpp, rootpath) printStatus(INFO, \"%s,",
"class TagVoteTagger: def __init__(self, collection, annotationName, feature, distance, tpp=DEFAULT_TPP, rootpath=ROOT_PATH): self.concepts = readConcepts(collection,",
"skips (%d) in %d neighbors' % (skip, len(neighbors)) return vote def predict(self, content,",
"voted += 1 if voted >= self.k: break #assert(voted >= self.k), 'too many",
"tagset = set(tags.split()) for tag in tagset: c_idx = self.concept2index.get(tag, -1) if c_idx",
"= [0-self.tagprior(c) for c in self.concepts] # vote only on the given concept",
"tags is None or userid in users_voted: skip += 1 continue users_voted.add(userid) tagset",
"tpp, rootpath) printStatus(INFO, \"%s, %d images, %d unique tags, %s %d neighbours for",
"'vgg-verydeep-16-fc7relu' tagger = TagVoteTagger('train10k', 'concepts81.txt', feature, 'cosine') tagger = PreTagVoteTagger('train10k', 'concepts81.txt', feature, 'cosine')",
"\"FeatureData\", feature) id_file = os.path.join(feat_dir, 'id.txt') shape_file = os.path.join(feat_dir, 'shape.txt') self.nr_of_images, feat_dim =",
"'feature.bin'), feat_dim, self.nr_of_images, id_file) self.searcher.set_distance(distance) self.k = DEFAULT_K self._load_tag_data(collection, tpp, rootpath) printStatus(INFO, \"%s,",
"> 1e-3: n = int(len(knn) * self.noise) hits = random.sample(xrange(len(knn)), n) random_set =",
"for i in range(n): idx = hits[i] knn[idx] = (random_set[i], 1000) return knn",
"content, context=None): scores = self._compute(content, context) return sorted(zip(self.concepts, scores), key=lambda v:v[1], reverse=True) class",
"unique tags, %s %d neighbours for voting\" % (self.__class__.__name__, self.nr_of_images, len(self.tag2freq), distance, self.k))",
"self.nr_of_images = len(self.imset) self.knndir = os.path.join(collection, '%s,%sknn,uu,1500' % (feature, distance)) self.k = DEFAULT_K",
"content, context): testCollection,testid = context.split(',') knnfile = os.path.join(self.rootpath, testCollection, 'SimilarityIndex', testCollection, self.knndir, testid[-2:],",
"= 'vgg-verydeep-16-fc7relu' tagger = TagVoteTagger('train10k', 'concepts81.txt', feature, 'cosine') tagger = PreTagVoteTagger('train10k', 'concepts81.txt', feature,",
"os.path.join(feat_dir, 'shape.txt') self.nr_of_images, feat_dim = map(int, open(shape_file).readline().split()) self.searcher = load_model(featuredir, self.nr_of_images, feat_dim,nr_of_segments=512,segmentk=256,coarsek=4096) self.k",
"%d neighbours for voting\" % (self.__class__.__name__, self.nr_of_images, len(self.tag2freq), distance, self.k)) def set_noise(self, noise):",
"rootpath=ROOT_PATH, k = DEFAULT_K): self.rootpath = rootpath self.concepts = readConcepts(collection, annotationName, rootpath) self.nr_of_concepts",
"skip += 1 continue users_voted.add(userid) tagset = set(tags.split()) for tag in tagset: c_idx",
"= set(tags.split()) for tag in tagset: c_idx = self.concept2index.get(tag, -1) if c_idx >=",
"% (self.__class__.__name__, self.nr_of_images, len(self.tag2freq), distance, self.k)) def _compute(self, content, context=None): vote = [0]",
"distance, tpp=DEFAULT_TPP, rootpath=ROOT_PATH): self.concepts = readConcepts(collection, annotationName, rootpath) self.nr_of_concepts = len(self.concepts) self.concept2index =",
"neighbours for voting\" % (self.__class__.__name__, self.nr_of_images, len(self.tag2freq), distance, self.k)) def _load_tag_data(self, collection, tpp,",
"= os.path.join(feat_dir, 'id.txt') shape_file = os.path.join(feat_dir, 'shape.txt') self.nr_of_images, feat_dim = map(int, open(shape_file).readline().split()) self.searcher",
"_get_neighbors(self, content, context): return self.searcher.search_knn(content, max_hits=max(3000,self.k*3)) def _compute(self, content, context=None): users_voted = set()",
"def _compute(self, content, context=None): users_voted = set() vote = [0-self.tagprior(c) for c in",
">= self.k), 'too many skips (%d) in %d neighbors' % (skip, len(neighbors)) return",
"key=lambda v:v[1], reverse=True) class PreTagVoteTagger (TagVoteTagger): def __init__(self, collection, annotationName, feature, distance, tpp=DEFAULT_TPP,",
"= self._compute(content, context) return sorted(zip(self.concepts, scores), key=lambda v:v[1], reverse=True) class PreTagVoteTagger (TagVoteTagger): def",
"return sorted(zip(self.concepts, scores), key=lambda v:v[1], reverse=True) class PreTagVoteTagger (TagVoteTagger): def __init__(self, collection, annotationName,",
"= DEFAULT_K): self.rootpath = rootpath self.concepts = readConcepts(collection, annotationName, rootpath) self.nr_of_concepts = len(self.concepts)",
"random from basic.constant import ROOT_PATH from basic.common import printStatus, readRankingResults from basic.util import",
"voting\" % (self.__class__.__name__, self.nr_of_images, len(self.tag2freq), distance, self.k)) def _load_tag_data(self, collection, tpp, rootpath): tagfile",
"len(self.concepts) self.concept2index = dict(zip(self.concepts, range(self.nr_of_concepts))) feat_dir = os.path.join(rootpath, collection, \"FeatureData\", feature) id_file =",
"None)) if tags is None or userid in users_voted: skip += 1 continue",
"basic.annotationtable import readConcepts from util.simpleknn import simpleknn #from sandbox.pquan.pqsearch import load_model INFO =",
"dict(zip(self.concepts, range(self.nr_of_concepts))) feat_dir = os.path.join(rootpath, collection, \"FeatureData\", feature) id_file = os.path.join(feat_dir, 'id.txt') shape_file",
"{} for line in open(tagfile): imageid, userid, tags = line.split('\\t') tags = tags.lower()",
"context) return sorted(zip(self.concepts, scores), key=lambda v:v[1], reverse=True) class PreTagVoteTagger (TagVoteTagger): def __init__(self, collection,",
"len(self.concepts) self.concept2index = dict(zip(self.concepts, range(self.nr_of_concepts))) featuredir = os.path.join(rootpath,collection,'FeatureData',feature) id_file = os.path.join(featuredir, \"id.txt\") shape_file",
"%d neighbors' % (skip, len(neighbors)) return vote class PqTagVoteTagger (TagVoteTagger): def __init__(self, collection,",
"range(n): idx = hits[i] knn[idx] = (random_set[i], 1000) return knn class PreKnnTagger (PreTagVoteTagger):",
"for tag in tagset: self.tag2freq[tag] = self.tag2freq.get(tag,0) + 1 def tagprior(self, tag): return",
"readImageSet(collection, collection, rootpath) self.nr_of_images = len(self.imset) self.knndir = os.path.join(collection, '%s,%sknn,1500' % (feature, distance))",
"* self.tag2freq.get(tag,0) / self.nr_of_images def _get_neighbors(self, content, context): return self.searcher.search_knn(content, max_hits=max(3000,self.k*3)) def _compute(self,",
"testCollection, self.knndir, testid[-2:], '%s.txt' % testid) knn = readRankingResults(knnfile) knn = knn[:self.k] if",
"'%s,%sknn,uu,1500' % (feature, distance)) self.k = DEFAULT_K self.noise = 0 self._load_tag_data(collection, tpp, rootpath)",
"%s %d neighbours for voting\" % (self.__class__.__name__, self.nr_of_images, len(self.tag2freq), distance, self.k)) def _load_tag_data(self,",
"'%s.txt' % testid) knn = readRankingResults(knnfile) knn = knn[:self.k] if self.noise > 1e-3:",
"self.nr_of_images = len(self.imset) self.knndir = os.path.join(collection, '%s,%sknn,1500' % (feature, distance)) self.k = k",
"for (name, dist) in neighbors: (userid,tags) = self.textstore.get(name, (None, None)) if tags is",
"(None, None)) if tags is None or userid in users_voted: skip += 1",
"voting\" % (self.__class__.__name__, self.nr_of_images, len(self.tag2freq), distance, self.k)) def _get_neighbors(self, content, context): return self.searcher.search_knn(content,",
"in neighbors: (userid,tags) = self.textstore.get(name, (None, None)) if tags is None or userid",
"for voting\" % (self.__class__.__name__, self.nr_of_images, len(self.tag2freq), distance, self.k)) def _compute(self, content, context=None): vote",
"'__main__': feature = 'vgg-verydeep-16-fc7relu' tagger = TagVoteTagger('train10k', 'concepts81.txt', feature, 'cosine') tagger = PreTagVoteTagger('train10k',",
"'lemm' DEFAULT_DISTANCE = 'l1' DEFAULT_BLOCK_SIZE = 1000 DEFAULT_TAGGER = 'tagvote' class TagVoteTagger: def",
"os.path.join(feat_dir, 'id.txt') shape_file = os.path.join(feat_dir, 'shape.txt') self.nr_of_images, feat_dim = map(int, open(shape_file).readline().split()) self.searcher =",
"1 continue tagset = set(tags.split()) for tag in tagset: c_idx = self.concept2index.get(tag, -1)",
"self.nr_of_images, len(self.tag2freq), distance, self.k)) def _load_tag_data(self, collection, tpp, rootpath): tagfile = os.path.join(rootpath, collection,",
"printStatus, readRankingResults from basic.util import readImageSet from basic.annotationtable import readConcepts from util.simpleknn import",
"vote def predict(self, content, context=None): scores = self._compute(content, context) return sorted(zip(self.concepts, scores), key=lambda",
"range(self.nr_of_concepts))) self.imset = readImageSet(collection, collection, rootpath) self.nr_of_images = len(self.imset) self.knndir = os.path.join(collection, '%s,%sknn,uu,1500'",
"range(self.nr_of_concepts))) featuredir = os.path.join(rootpath,collection,'FeatureData',feature) id_file = os.path.join(featuredir, \"id.txt\") shape_file = os.path.join(feat_dir, 'shape.txt') self.nr_of_images,",
"len(self.imset) self.knndir = os.path.join(collection, '%s,%sknn,1500' % (feature, distance)) self.k = k self.noise =",
"map(int, open(shape_file).readline().split()) self.searcher = simpleknn.load_model(os.path.join(feat_dir, 'feature.bin'), feat_dim, self.nr_of_images, id_file) self.searcher.set_distance(distance) self.k = DEFAULT_K",
"in self.concepts] # vote only on the given concept list voted = 0",
"basic.constant import ROOT_PATH from basic.common import printStatus, readRankingResults from basic.util import readImageSet from",
"rootpath) self.nr_of_concepts = len(self.concepts) self.concept2index = dict(zip(self.concepts, range(self.nr_of_concepts))) feat_dir = os.path.join(rootpath, collection, \"FeatureData\",",
"readConcepts(collection, annotationName, rootpath) self.nr_of_concepts = len(self.concepts) self.concept2index = dict(zip(self.concepts, range(self.nr_of_concepts))) self.imset = readImageSet(collection,",
"rootpath) self.nr_of_images = len(self.imset) self.knndir = os.path.join(collection, '%s,%sknn,1500' % (feature, distance)) self.k =",
"'too many skips (%d) in %d neighbors' % (skip, len(neighbors)) return vote class",
"tpp) self.textstore = {} self.tag2freq = {} for line in open(tagfile): imageid, userid,",
"= os.path.join(self.rootpath, testCollection, 'SimilarityIndex', testCollection, self.knndir, testid[-2:], '%s.txt' % testid) knn = readRankingResults(knnfile)",
"dict(zip(self.concepts, range(self.nr_of_concepts))) featuredir = os.path.join(rootpath,collection,'FeatureData',feature) id_file = os.path.join(featuredir, \"id.txt\") shape_file = os.path.join(feat_dir, 'shape.txt')",
"tagfile = os.path.join(rootpath, collection, \"TextData\", \"id.userid.%stags.txt\" % tpp) self.textstore = {} self.tag2freq =",
"voted = 0 skip = 0 neighbors = self._get_neighbors(content, context) for (name, dist)",
"= __file__ DEFAULT_K=1000 DEFAULT_TPP = 'lemm' DEFAULT_DISTANCE = 'l1' DEFAULT_BLOCK_SIZE = 1000 DEFAULT_TAGGER",
"__init__(self, collection, annotationName, feature, distance, tpp=DEFAULT_TPP, rootpath=ROOT_PATH): self.concepts = readConcepts(collection, annotationName, rootpath) self.nr_of_concepts",
"testid) knn = readRankingResults(knnfile) knn = knn[:self.k] if self.noise > 1e-3: n =",
"printStatus(INFO, \"%s, %d images, %d unique tags, %s %d neighbours for voting\" %",
"= 'tagvote' class TagVoteTagger: def __init__(self, collection, annotationName, feature, distance, tpp=DEFAULT_TPP, rootpath=ROOT_PATH): self.concepts",
"self.concept2index = dict(zip(self.concepts, range(self.nr_of_concepts))) feat_dir = os.path.join(rootpath, collection, \"FeatureData\", feature) id_file = os.path.join(feat_dir,",
"set(tags.split()) for tag in tagset: self.tag2freq[tag] = self.tag2freq.get(tag,0) + 1 def tagprior(self, tag):",
"= load_model(featuredir, self.nr_of_images, feat_dim,nr_of_segments=512,segmentk=256,coarsek=4096) self.k = DEFAULT_K self._load_tag_data(collection, tpp, rootpath) printStatus(INFO, \"%s, %d",
"class PqTagVoteTagger (TagVoteTagger): def __init__(self, collection, annotationName, feature, distance, tpp=DEFAULT_TPP, rootpath=ROOT_PATH): self.rootpath =",
"collection, tpp, rootpath): tagfile = os.path.join(rootpath, collection, \"TextData\", \"id.userid.%stags.txt\" % tpp) self.textstore =",
"self.knndir = os.path.join(collection, '%s,%sknn,uu,1500' % (feature, distance)) self.k = DEFAULT_K self.noise = 0",
"tpp=DEFAULT_TPP, rootpath=ROOT_PATH): self.rootpath = rootpath self.concepts = readConcepts(collection, annotationName, rootpath) self.nr_of_concepts = len(self.concepts)",
"tag in tagset: self.tag2freq[tag] = self.tag2freq.get(tag,0) + 1 def tagprior(self, tag): return float(self.k)",
"rootpath=ROOT_PATH): self.rootpath = rootpath self.concepts = readConcepts(collection, annotationName, rootpath) self.nr_of_concepts = len(self.concepts) self.concept2index",
"collection, \"TextData\", \"id.userid.%stags.txt\" % tpp) self.textstore = {} self.tag2freq = {} for line",
"hits = random.sample(xrange(len(knn)), n) random_set = random.sample(self.imset, n) for i in range(n): idx",
"feat_dir = os.path.join(rootpath, collection, \"FeatureData\", feature) id_file = os.path.join(feat_dir, 'id.txt') shape_file = os.path.join(feat_dir,",
"distance, tpp=DEFAULT_TPP, rootpath=ROOT_PATH): self.rootpath = rootpath self.concepts = readConcepts(collection, annotationName, rootpath) self.nr_of_concepts =",
"util.simpleknn import simpleknn #from sandbox.pquan.pqsearch import load_model INFO = __file__ DEFAULT_K=1000 DEFAULT_TPP =",
"self.imset = readImageSet(collection, collection, rootpath) self.nr_of_images = len(self.imset) self.knndir = os.path.join(collection, '%s,%sknn,uu,1500' %",
"neighbors: (userid,tags) = self.textstore.get(name, (None, None)) if tags is None or userid in",
"vote only on the given concept list voted = 0 skip = 0",
"= self.concept2index.get(tag, -1) if c_idx >= 0: vote[c_idx] += 1 voted += 1",
"os.path.join(collection, '%s,%sknn,uu,1500' % (feature, distance)) self.k = DEFAULT_K self.noise = 0 self._load_tag_data(collection, tpp,",
"self.concepts = readConcepts(collection, annotationName, rootpath) self.nr_of_concepts = len(self.concepts) self.concept2index = dict(zip(self.concepts, range(self.nr_of_concepts))) featuredir",
"for line in open(tagfile): imageid, userid, tags = line.split('\\t') tags = tags.lower() self.textstore[imageid]",
"self.textstore.get(name, (None, None)) if tags is None or userid in users_voted: skip +=",
"os, time, random from basic.constant import ROOT_PATH from basic.common import printStatus, readRankingResults from",
"distance)) self.k = k self.noise = 0 self._load_tag_data(collection, tpp, rootpath) printStatus(INFO, \"%s, %d",
"id_file = os.path.join(feat_dir, 'id.txt') shape_file = os.path.join(feat_dir, 'shape.txt') self.nr_of_images, feat_dim = map(int, open(shape_file).readline().split())",
"tags = line.split('\\t') tags = tags.lower() self.textstore[imageid] = (userid, tags) tagset = set(tags.split())",
"= dict(zip(self.concepts, range(self.nr_of_concepts))) self.imset = readImageSet(collection, collection, rootpath) self.nr_of_images = len(self.imset) self.knndir =",
"tags is None: skip += 1 continue tagset = set(tags.split()) for tag in",
"= (random_set[i], 1000) return knn class PreKnnTagger (PreTagVoteTagger): def __init__(self, collection, annotationName, feature,",
"% (skip, len(neighbors)) return vote class PqTagVoteTagger (TagVoteTagger): def __init__(self, collection, annotationName, feature,",
"tagset: c_idx = self.concept2index.get(tag, -1) if c_idx >= 0: vote[c_idx] += 1 voted",
"(name, dist) in neighbors: (userid,tags) = self.textstore.get(name, (None, None)) if tags is None:",
"self.textstore = {} self.tag2freq = {} for line in open(tagfile): imageid, userid, tags",
"= dict(zip(self.concepts, range(self.nr_of_concepts))) feat_dir = os.path.join(rootpath, collection, \"FeatureData\", feature) id_file = os.path.join(feat_dir, 'id.txt')",
"self.imset = readImageSet(collection, collection, rootpath) self.nr_of_images = len(self.imset) self.knndir = os.path.join(collection, '%s,%sknn,1500' %",
"many skips (%d) in %d neighbors' % (skip, len(neighbors)) return vote def predict(self,",
"load_model(featuredir, self.nr_of_images, feat_dim,nr_of_segments=512,segmentk=256,coarsek=4096) self.k = DEFAULT_K self._load_tag_data(collection, tpp, rootpath) printStatus(INFO, \"%s, %d images,",
"= [0] * self.nr_of_concepts # vote only on the given concept list voted",
"% (self.__class__.__name__, self.nr_of_images, len(self.tag2freq), distance, self.k)) def _load_tag_data(self, collection, tpp, rootpath): tagfile =",
"self.textstore.get(name, (None, None)) if tags is None: skip += 1 continue tagset =",
"distance, self.k)) def _get_neighbors(self, content, context): return self.searcher.search_knn(content, requested=max(3000, self.k*3)) NAME_TO_TAGGER = {'tagvote':TagVoteTagger,",
"feature) id_file = os.path.join(feat_dir, 'id.txt') shape_file = os.path.join(feat_dir, 'shape.txt') self.nr_of_images, feat_dim = map(int,",
"1e-3: n = int(len(knn) * self.noise) hits = random.sample(xrange(len(knn)), n) random_set = random.sample(self.imset,",
">= self.k: break #assert(voted >= self.k), 'too many skips (%d) in %d neighbors'",
"context=None): scores = self._compute(content, context) return sorted(zip(self.concepts, scores), key=lambda v:v[1], reverse=True) class PreTagVoteTagger",
"testCollection, 'SimilarityIndex', testCollection, self.knndir, testid[-2:], '%s.txt' % testid) knn = readRankingResults(knnfile) knn =",
"_compute(self, content, context=None): users_voted = set() vote = [0-self.tagprior(c) for c in self.concepts]",
"DEFAULT_K): self.rootpath = rootpath self.concepts = readConcepts(collection, annotationName, rootpath) self.nr_of_concepts = len(self.concepts) self.concept2index",
"distance, tpp=DEFAULT_TPP, rootpath=ROOT_PATH, k = DEFAULT_K): self.rootpath = rootpath self.concepts = readConcepts(collection, annotationName,",
"self.tag2freq.get(tag,0) + 1 def tagprior(self, tag): return float(self.k) * self.tag2freq.get(tag,0) / self.nr_of_images def",
"= len(self.concepts) self.concept2index = dict(zip(self.concepts, range(self.nr_of_concepts))) featuredir = os.path.join(rootpath,collection,'FeatureData',feature) id_file = os.path.join(featuredir, \"id.txt\")",
"= readImageSet(collection, collection, rootpath) self.nr_of_images = len(self.imset) self.knndir = os.path.join(collection, '%s,%sknn,1500' % (feature,",
"= map(int, open(shape_file).readline().split()) self.searcher = load_model(featuredir, self.nr_of_images, feat_dim,nr_of_segments=512,segmentk=256,coarsek=4096) self.k = DEFAULT_K self._load_tag_data(collection, tpp,",
"-1) if c_idx >= 0: vote[c_idx] += 1 voted += 1 if voted",
"= self._get_neighbors(content, context) for (name, dist) in neighbors: (userid,tags) = self.textstore.get(name, (None, None))",
"tagger = TagVoteTagger('train10k', 'concepts81.txt', feature, 'cosine') tagger = PreTagVoteTagger('train10k', 'concepts81.txt', feature, 'cosine') tagger",
"imageid, userid, tags = line.split('\\t') tags = tags.lower() self.textstore[imageid] = (userid, tags) tagset",
"= {} self.tag2freq = {} for line in open(tagfile): imageid, userid, tags =",
"concept list voted = 0 skip = 0 neighbors = self._get_neighbors(content, context) for",
"def _get_neighbors(self, content, context): testCollection,testid = context.split(',') knnfile = os.path.join(self.rootpath, testCollection, 'SimilarityIndex', testCollection,",
"time, random from basic.constant import ROOT_PATH from basic.common import printStatus, readRankingResults from basic.util",
"%d neighbours for voting\" % (self.__class__.__name__, self.nr_of_images, len(self.tag2freq), distance, self.k)) def _get_neighbors(self, content,",
"k self.noise = 0 self._load_tag_data(collection, tpp, rootpath) printStatus(INFO, \"%s, %d images, %d unique",
"content, context=None): vote = [0] * self.nr_of_concepts # vote only on the given",
"= rootpath self.concepts = readConcepts(collection, annotationName, rootpath) self.nr_of_concepts = len(self.concepts) self.concept2index = dict(zip(self.concepts,",
"1 def tagprior(self, tag): return float(self.k) * self.tag2freq.get(tag,0) / self.nr_of_images def _get_neighbors(self, content,",
"images, %d unique tags, %s %d neighbours for voting\" % (self.__class__.__name__, self.nr_of_images, len(self.tag2freq),",
"= self.textstore.get(name, (None, None)) if tags is None: skip += 1 continue tagset",
"\"id.userid.%stags.txt\" % tpp) self.textstore = {} self.tag2freq = {} for line in open(tagfile):",
"self.nr_of_concepts = len(self.concepts) self.concept2index = dict(zip(self.concepts, range(self.nr_of_concepts))) featuredir = os.path.join(rootpath,collection,'FeatureData',feature) id_file = os.path.join(featuredir,",
"shape_file = os.path.join(feat_dir, 'shape.txt') self.nr_of_images, feat_dim = map(int, open(shape_file).readline().split()) self.searcher = simpleknn.load_model(os.path.join(feat_dir, 'feature.bin'),",
"in open(tagfile): imageid, userid, tags = line.split('\\t') tags = tags.lower() self.textstore[imageid] = (userid,",
"context.split(',') knnfile = os.path.join(self.rootpath, testCollection, 'SimilarityIndex', testCollection, self.knndir, testid[-2:], '%s.txt' % testid) knn",
"readConcepts(collection, annotationName, rootpath) self.nr_of_concepts = len(self.concepts) self.concept2index = dict(zip(self.concepts, range(self.nr_of_concepts))) featuredir = os.path.join(rootpath,collection,'FeatureData',feature)",
"os.path.join(rootpath, collection, \"TextData\", \"id.userid.%stags.txt\" % tpp) self.textstore = {} self.tag2freq = {} for",
"def _load_tag_data(self, collection, tpp, rootpath): tagfile = os.path.join(rootpath, collection, \"TextData\", \"id.userid.%stags.txt\" % tpp)",
"distance, self.k)) def set_noise(self, noise): self.noise = noise def _get_neighbors(self, content, context): testCollection,testid",
"id_file = os.path.join(featuredir, \"id.txt\") shape_file = os.path.join(feat_dir, 'shape.txt') self.nr_of_images, feat_dim = map(int, open(shape_file).readline().split())",
"def set_noise(self, noise): self.noise = noise def _get_neighbors(self, content, context): testCollection,testid = context.split(',')",
"in range(n): idx = hits[i] knn[idx] = (random_set[i], 1000) return knn class PreKnnTagger",
"(self.__class__.__name__, self.nr_of_images, len(self.tag2freq), distance, self.k)) def _get_neighbors(self, content, context): return self.searcher.search_knn(content, requested=max(3000, self.k*3))",
"users_voted = set() vote = [0-self.tagprior(c) for c in self.concepts] # vote only",
"for voting\" % (self.__class__.__name__, self.nr_of_images, len(self.tag2freq), distance, self.k)) def set_noise(self, noise): self.noise =",
"self.concept2index = dict(zip(self.concepts, range(self.nr_of_concepts))) self.imset = readImageSet(collection, collection, rootpath) self.nr_of_images = len(self.imset) self.knndir",
"k = DEFAULT_K): self.rootpath = rootpath self.concepts = readConcepts(collection, annotationName, rootpath) self.nr_of_concepts =",
"annotationName, feature, distance, tpp=DEFAULT_TPP, rootpath=ROOT_PATH): self.concepts = readConcepts(collection, annotationName, rootpath) self.nr_of_concepts = len(self.concepts)",
"1 voted += 1 if voted >= self.k: break #assert(voted >= self.k), 'too",
"= tags.lower() self.textstore[imageid] = (userid, tags) tagset = set(tags.split()) for tag in tagset:",
"self.rootpath = rootpath self.concepts = readConcepts(collection, annotationName, rootpath) self.nr_of_concepts = len(self.concepts) self.concept2index =",
"= readConcepts(collection, annotationName, rootpath) self.nr_of_concepts = len(self.concepts) self.concept2index = dict(zip(self.concepts, range(self.nr_of_concepts))) feat_dir =",
"tags, %s %d neighbours for voting\" % (self.__class__.__name__, self.nr_of_images, len(self.tag2freq), distance, self.k)) def",
"readRankingResults from basic.util import readImageSet from basic.annotationtable import readConcepts from util.simpleknn import simpleknn",
"'concepts81.txt', feature, 'cosine') tagger = PreTagVoteTagger('train10k', 'concepts81.txt', feature, 'cosine') tagger = PreKnnTagger('train10k', 'conceptsmir14.txt',",
"def _get_neighbors(self, content, context): return self.searcher.search_knn(content, max_hits=max(3000,self.k*3)) def _compute(self, content, context=None): users_voted =",
"noise def _get_neighbors(self, content, context): testCollection,testid = context.split(',') knnfile = os.path.join(self.rootpath, testCollection, 'SimilarityIndex',",
"import ROOT_PATH from basic.common import printStatus, readRankingResults from basic.util import readImageSet from basic.annotationtable",
"= simpleknn.load_model(os.path.join(feat_dir, 'feature.bin'), feat_dim, self.nr_of_images, id_file) self.searcher.set_distance(distance) self.k = DEFAULT_K self._load_tag_data(collection, tpp, rootpath)",
"self.k)) def _load_tag_data(self, collection, tpp, rootpath): tagfile = os.path.join(rootpath, collection, \"TextData\", \"id.userid.%stags.txt\" %",
"break #assert(voted >= self.k), 'too many skips (%d) in %d neighbors' % (skip,",
"given concept list voted = 0 skip = 0 neighbors = self._get_neighbors(content, context)",
"feat_dim,nr_of_segments=512,segmentk=256,coarsek=4096) self.k = DEFAULT_K self._load_tag_data(collection, tpp, rootpath) printStatus(INFO, \"%s, %d images, %d unique",
"= os.path.join(collection, '%s,%sknn,uu,1500' % (feature, distance)) self.k = DEFAULT_K self.noise = 0 self._load_tag_data(collection,",
"self.nr_of_concepts = len(self.concepts) self.concept2index = dict(zip(self.concepts, range(self.nr_of_concepts))) self.imset = readImageSet(collection, collection, rootpath) self.nr_of_images",
"return vote def predict(self, content, context=None): scores = self._compute(content, context) return sorted(zip(self.concepts, scores),",
"os.path.join(rootpath,collection,'FeatureData',feature) id_file = os.path.join(featuredir, \"id.txt\") shape_file = os.path.join(feat_dir, 'shape.txt') self.nr_of_images, feat_dim = map(int,",
"feat_dim, self.nr_of_images, id_file) self.searcher.set_distance(distance) self.k = DEFAULT_K self._load_tag_data(collection, tpp, rootpath) printStatus(INFO, \"%s, %d",
"'l1' DEFAULT_BLOCK_SIZE = 1000 DEFAULT_TAGGER = 'tagvote' class TagVoteTagger: def __init__(self, collection, annotationName,",
"%d neighbours for voting\" % (self.__class__.__name__, self.nr_of_images, len(self.tag2freq), distance, self.k)) def _load_tag_data(self, collection,",
"feature = 'vgg-verydeep-16-fc7relu' tagger = TagVoteTagger('train10k', 'concepts81.txt', feature, 'cosine') tagger = PreTagVoteTagger('train10k', 'concepts81.txt',",
"= knn[:self.k] if self.noise > 1e-3: n = int(len(knn) * self.noise) hits =",
"int(len(knn) * self.noise) hits = random.sample(xrange(len(knn)), n) random_set = random.sample(self.imset, n) for i",
"self._load_tag_data(collection, tpp, rootpath) printStatus(INFO, \"%s, %d images, %d unique tags, %s %d neighbours",
"return knn class PreKnnTagger (PreTagVoteTagger): def __init__(self, collection, annotationName, feature, distance, tpp=DEFAULT_TPP, rootpath=ROOT_PATH,",
"sys, os, time, random from basic.constant import ROOT_PATH from basic.common import printStatus, readRankingResults",
"(userid,tags) = self.textstore.get(name, (None, None)) if tags is None or userid in users_voted:",
"many skips (%d) in %d neighbors' % (skip, len(neighbors)) return vote class PqTagVoteTagger",
"context) for (name, dist) in neighbors: (userid,tags) = self.textstore.get(name, (None, None)) if tags",
"% (self.__class__.__name__, self.nr_of_images, len(self.tag2freq), distance, self.k)) def _get_neighbors(self, content, context): return self.searcher.search_knn(content, requested=max(3000,",
"rootpath): tagfile = os.path.join(rootpath, collection, \"TextData\", \"id.userid.%stags.txt\" % tpp) self.textstore = {} self.tag2freq",
"idx = hits[i] knn[idx] = (random_set[i], 1000) return knn class PreKnnTagger (PreTagVoteTagger): def",
"self.k = DEFAULT_K self.noise = 0 self._load_tag_data(collection, tpp, rootpath) printStatus(INFO, \"%s, %d images,",
"* self.nr_of_concepts # vote only on the given concept list voted = 0",
"(skip, len(neighbors)) return vote def predict(self, content, context=None): scores = self._compute(content, context) return",
"DEFAULT_K self._load_tag_data(collection, tpp, rootpath) printStatus(INFO, \"%s, %d images, %d unique tags, %s %d",
"%d neighbours for voting\" % (self.__class__.__name__, self.nr_of_images, len(self.tag2freq), distance, self.k)) def _compute(self, content,",
"only on the given concept list voted = 0 skip = 0 neighbors",
"self.tag2freq = {} for line in open(tagfile): imageid, userid, tags = line.split('\\t') tags",
"% (feature, distance)) self.k = DEFAULT_K self.noise = 0 self._load_tag_data(collection, tpp, rootpath) printStatus(INFO,",
"tagset: self.tag2freq[tag] = self.tag2freq.get(tag,0) + 1 def tagprior(self, tag): return float(self.k) * self.tag2freq.get(tag,0)",
"requested=max(3000, self.k*3)) NAME_TO_TAGGER = {'tagvote':TagVoteTagger, 'pretagvote':PreTagVoteTagger, 'preknn':PreKnnTagger, 'pqtagvote':PqTagVoteTagger} if __name__ == '__main__': feature",
"= 'lemm' DEFAULT_DISTANCE = 'l1' DEFAULT_BLOCK_SIZE = 1000 DEFAULT_TAGGER = 'tagvote' class TagVoteTagger:",
"= line.split('\\t') tags = tags.lower() self.textstore[imageid] = (userid, tags) tagset = set(tags.split()) for",
"or userid in users_voted: skip += 1 continue users_voted.add(userid) tagset = set(tags.split()) for",
"self.knndir, testid[-2:], '%s.txt' % testid) knn = readRankingResults(knnfile) knn = knn[:self.k] if self.noise",
"if c_idx >= 0: vote[c_idx] += 1 voted += 1 if voted >=",
"voting\" % (self.__class__.__name__, self.nr_of_images, len(self.tag2freq), distance, self.k)) def _compute(self, content, context=None): vote =",
"knn = readRankingResults(knnfile) knn = knn[:self.k] if self.noise > 1e-3: n = int(len(knn)",
"os.path.join(featuredir, \"id.txt\") shape_file = os.path.join(feat_dir, 'shape.txt') self.nr_of_images, feat_dim = map(int, open(shape_file).readline().split()) self.searcher =",
"None or userid in users_voted: skip += 1 continue users_voted.add(userid) tagset = set(tags.split())",
"open(shape_file).readline().split()) self.searcher = load_model(featuredir, self.nr_of_images, feat_dim,nr_of_segments=512,segmentk=256,coarsek=4096) self.k = DEFAULT_K self._load_tag_data(collection, tpp, rootpath) printStatus(INFO,",
"for tag in tagset: c_idx = self.concept2index.get(tag, -1) if c_idx >= 0: vote[c_idx]",
"in tagset: c_idx = self.concept2index.get(tag, -1) if c_idx >= 0: vote[c_idx] += 1",
"def tagprior(self, tag): return float(self.k) * self.tag2freq.get(tag,0) / self.nr_of_images def _get_neighbors(self, content, context):",
"def _compute(self, content, context=None): vote = [0] * self.nr_of_concepts # vote only on",
"hits[i] knn[idx] = (random_set[i], 1000) return knn class PreKnnTagger (PreTagVoteTagger): def __init__(self, collection,",
"self.nr_of_concepts # vote only on the given concept list voted = 0 skip",
"%d images, %d unique tags, %s %d neighbours for voting\" % (self.__class__.__name__, self.nr_of_images,",
"skip += 1 continue tagset = set(tags.split()) for tag in tagset: c_idx =",
"content, context=None): users_voted = set() vote = [0-self.tagprior(c) for c in self.concepts] #",
"annotationName, rootpath) self.nr_of_concepts = len(self.concepts) self.concept2index = dict(zip(self.concepts, range(self.nr_of_concepts))) feat_dir = os.path.join(rootpath, collection,",
"tags) tagset = set(tags.split()) for tag in tagset: self.tag2freq[tag] = self.tag2freq.get(tag,0) + 1",
"None: skip += 1 continue tagset = set(tags.split()) for tag in tagset: c_idx",
"%d unique tags, %s %d neighbours for voting\" % (self.__class__.__name__, self.nr_of_images, len(self.tag2freq), distance,",
"= {'tagvote':TagVoteTagger, 'pretagvote':PreTagVoteTagger, 'preknn':PreKnnTagger, 'pqtagvote':PqTagVoteTagger} if __name__ == '__main__': feature = 'vgg-verydeep-16-fc7relu' tagger",
"def __init__(self, collection, annotationName, feature, distance, tpp=DEFAULT_TPP, rootpath=ROOT_PATH): self.concepts = readConcepts(collection, annotationName, rootpath)",
"vote = [0] * self.nr_of_concepts # vote only on the given concept list",
"collection, annotationName, feature, distance, tpp=DEFAULT_TPP, rootpath=ROOT_PATH): self.concepts = readConcepts(collection, annotationName, rootpath) self.nr_of_concepts =",
"self.concepts = readConcepts(collection, annotationName, rootpath) self.nr_of_concepts = len(self.concepts) self.concept2index = dict(zip(self.concepts, range(self.nr_of_concepts))) feat_dir",
"= dict(zip(self.concepts, range(self.nr_of_concepts))) featuredir = os.path.join(rootpath,collection,'FeatureData',feature) id_file = os.path.join(featuredir, \"id.txt\") shape_file = os.path.join(feat_dir,",
"= DEFAULT_K self.noise = 0 self._load_tag_data(collection, tpp, rootpath) printStatus(INFO, \"%s, %d images, %d",
"return self.searcher.search_knn(content, max_hits=max(3000,self.k*3)) def _compute(self, content, context=None): users_voted = set() vote = [0-self.tagprior(c)",
"= os.path.join(rootpath, collection, \"FeatureData\", feature) id_file = os.path.join(feat_dir, 'id.txt') shape_file = os.path.join(feat_dir, 'shape.txt')",
"self.nr_of_images def _get_neighbors(self, content, context): return self.searcher.search_knn(content, max_hits=max(3000,self.k*3)) def _compute(self, content, context=None): users_voted",
"= readConcepts(collection, annotationName, rootpath) self.nr_of_concepts = len(self.concepts) self.concept2index = dict(zip(self.concepts, range(self.nr_of_concepts))) featuredir =",
"on the given concept list voted = 0 skip = 0 neighbors =",
"list voted = 0 skip = 0 neighbors = self._get_neighbors(content, context) for (name,",
"rootpath) self.nr_of_images = len(self.imset) self.knndir = os.path.join(collection, '%s,%sknn,uu,1500' % (feature, distance)) self.k =",
"vote = [0-self.tagprior(c) for c in self.concepts] # vote only on the given",
"self.k*3)) NAME_TO_TAGGER = {'tagvote':TagVoteTagger, 'pretagvote':PreTagVoteTagger, 'preknn':PreKnnTagger, 'pqtagvote':PqTagVoteTagger} if __name__ == '__main__': feature =",
"= os.path.join(feat_dir, 'shape.txt') self.nr_of_images, feat_dim = map(int, open(shape_file).readline().split()) self.searcher = simpleknn.load_model(os.path.join(feat_dir, 'feature.bin'), feat_dim,",
"return float(self.k) * self.tag2freq.get(tag,0) / self.nr_of_images def _get_neighbors(self, content, context): return self.searcher.search_knn(content, max_hits=max(3000,self.k*3))",
"line.split('\\t') tags = tags.lower() self.textstore[imageid] = (userid, tags) tagset = set(tags.split()) for tag",
"random.sample(self.imset, n) for i in range(n): idx = hits[i] knn[idx] = (random_set[i], 1000)",
"%s %d neighbours for voting\" % (self.__class__.__name__, self.nr_of_images, len(self.tag2freq), distance, self.k)) def set_noise(self,",
"self.k)) def set_noise(self, noise): self.noise = noise def _get_neighbors(self, content, context): testCollection,testid =",
"open(shape_file).readline().split()) self.searcher = simpleknn.load_model(os.path.join(feat_dir, 'feature.bin'), feat_dim, self.nr_of_images, id_file) self.searcher.set_distance(distance) self.k = DEFAULT_K self._load_tag_data(collection,",
"from basic.common import printStatus, readRankingResults from basic.util import readImageSet from basic.annotationtable import readConcepts",
"= len(self.imset) self.knndir = os.path.join(collection, '%s,%sknn,1500' % (feature, distance)) self.k = k self.noise",
"= os.path.join(collection, '%s,%sknn,1500' % (feature, distance)) self.k = k self.noise = 0 self._load_tag_data(collection,",
"is None: skip += 1 continue tagset = set(tags.split()) for tag in tagset:",
"context=None): users_voted = set() vote = [0-self.tagprior(c) for c in self.concepts] # vote",
"class PreTagVoteTagger (TagVoteTagger): def __init__(self, collection, annotationName, feature, distance, tpp=DEFAULT_TPP, rootpath=ROOT_PATH): self.rootpath =",
"neighbors: (userid,tags) = self.textstore.get(name, (None, None)) if tags is None: skip += 1",
"feature, distance, tpp=DEFAULT_TPP, rootpath=ROOT_PATH): self.concepts = readConcepts(collection, annotationName, rootpath) self.nr_of_concepts = len(self.concepts) self.concept2index",
"__init__(self, collection, annotationName, feature, distance, tpp=DEFAULT_TPP, rootpath=ROOT_PATH): self.rootpath = rootpath self.concepts = readConcepts(collection,",
"def _get_neighbors(self, content, context): return self.searcher.search_knn(content, requested=max(3000, self.k*3)) NAME_TO_TAGGER = {'tagvote':TagVoteTagger, 'pretagvote':PreTagVoteTagger, 'preknn':PreKnnTagger,",
"* self.noise) hits = random.sample(xrange(len(knn)), n) random_set = random.sample(self.imset, n) for i in",
"(self.__class__.__name__, self.nr_of_images, len(self.tag2freq), distance, self.k)) def set_noise(self, noise): self.noise = noise def _get_neighbors(self,",
"from basic.util import readImageSet from basic.annotationtable import readConcepts from util.simpleknn import simpleknn #from",
"self.k = DEFAULT_K self._load_tag_data(collection, tpp, rootpath) printStatus(INFO, \"%s, %d images, %d unique tags,",
"skips (%d) in %d neighbors' % (skip, len(neighbors)) return vote class PqTagVoteTagger (TagVoteTagger):",
"predict(self, content, context=None): scores = self._compute(content, context) return sorted(zip(self.concepts, scores), key=lambda v:v[1], reverse=True)",
"rootpath) self.nr_of_concepts = len(self.concepts) self.concept2index = dict(zip(self.concepts, range(self.nr_of_concepts))) featuredir = os.path.join(rootpath,collection,'FeatureData',feature) id_file =",
"(PreTagVoteTagger): def __init__(self, collection, annotationName, feature, distance, tpp=DEFAULT_TPP, rootpath=ROOT_PATH, k = DEFAULT_K): self.rootpath",
"shape_file = os.path.join(feat_dir, 'shape.txt') self.nr_of_images, feat_dim = map(int, open(shape_file).readline().split()) self.searcher = load_model(featuredir, self.nr_of_images,",
"voting\" % (self.__class__.__name__, self.nr_of_images, len(self.tag2freq), distance, self.k)) def set_noise(self, noise): self.noise = noise",
"range(self.nr_of_concepts))) self.imset = readImageSet(collection, collection, rootpath) self.nr_of_images = len(self.imset) self.knndir = os.path.join(collection, '%s,%sknn,1500'",
"knn class PreKnnTagger (PreTagVoteTagger): def __init__(self, collection, annotationName, feature, distance, tpp=DEFAULT_TPP, rootpath=ROOT_PATH, k",
"= 0 neighbors = self._get_neighbors(content, context) for (name, dist) in neighbors: (userid,tags) =",
"id_file) self.searcher.set_distance(distance) self.k = DEFAULT_K self._load_tag_data(collection, tpp, rootpath) printStatus(INFO, \"%s, %d images, %d",
"(self.__class__.__name__, self.nr_of_images, len(self.tag2freq), distance, self.k)) def _compute(self, content, context=None): vote = [0] *",
"DEFAULT_K=1000 DEFAULT_TPP = 'lemm' DEFAULT_DISTANCE = 'l1' DEFAULT_BLOCK_SIZE = 1000 DEFAULT_TAGGER = 'tagvote'",
"= os.path.join(rootpath, collection, \"TextData\", \"id.userid.%stags.txt\" % tpp) self.textstore = {} self.tag2freq = {}",
"random_set = random.sample(self.imset, n) for i in range(n): idx = hits[i] knn[idx] =",
"self.searcher.set_distance(distance) self.k = DEFAULT_K self._load_tag_data(collection, tpp, rootpath) printStatus(INFO, \"%s, %d images, %d unique",
"{'tagvote':TagVoteTagger, 'pretagvote':PreTagVoteTagger, 'preknn':PreKnnTagger, 'pqtagvote':PqTagVoteTagger} if __name__ == '__main__': feature = 'vgg-verydeep-16-fc7relu' tagger =",
"map(int, open(shape_file).readline().split()) self.searcher = load_model(featuredir, self.nr_of_images, feat_dim,nr_of_segments=512,segmentk=256,coarsek=4096) self.k = DEFAULT_K self._load_tag_data(collection, tpp, rootpath)",
"i in range(n): idx = hits[i] knn[idx] = (random_set[i], 1000) return knn class",
"PqTagVoteTagger (TagVoteTagger): def __init__(self, collection, annotationName, feature, distance, tpp=DEFAULT_TPP, rootpath=ROOT_PATH): self.rootpath = rootpath",
"vote class PqTagVoteTagger (TagVoteTagger): def __init__(self, collection, annotationName, feature, distance, tpp=DEFAULT_TPP, rootpath=ROOT_PATH): self.rootpath",
"knnfile = os.path.join(self.rootpath, testCollection, 'SimilarityIndex', testCollection, self.knndir, testid[-2:], '%s.txt' % testid) knn =",
"max_hits=max(3000,self.k*3)) def _compute(self, content, context=None): users_voted = set() vote = [0-self.tagprior(c) for c",
"def predict(self, content, context=None): scores = self._compute(content, context) return sorted(zip(self.concepts, scores), key=lambda v:v[1],",
"def __init__(self, collection, annotationName, feature, distance, tpp=DEFAULT_TPP, rootpath=ROOT_PATH, k = DEFAULT_K): self.rootpath =",
"tagset = set(tags.split()) for tag in tagset: self.tag2freq[tag] = self.tag2freq.get(tag,0) + 1 def",
"self._compute(content, context) return sorted(zip(self.concepts, scores), key=lambda v:v[1], reverse=True) class PreTagVoteTagger (TagVoteTagger): def __init__(self,",
"self.nr_of_images, feat_dim = map(int, open(shape_file).readline().split()) self.searcher = load_model(featuredir, self.nr_of_images, feat_dim,nr_of_segments=512,segmentk=256,coarsek=4096) self.k = DEFAULT_K",
"content, context): return self.searcher.search_knn(content, max_hits=max(3000,self.k*3)) def _compute(self, content, context=None): users_voted = set() vote",
"/ self.nr_of_images def _get_neighbors(self, content, context): return self.searcher.search_knn(content, max_hits=max(3000,self.k*3)) def _compute(self, content, context=None):",
"= set() vote = [0-self.tagprior(c) for c in self.concepts] # vote only on",
"(None, None)) if tags is None: skip += 1 continue tagset = set(tags.split())",
"= self.textstore.get(name, (None, None)) if tags is None or userid in users_voted: skip",
"collection, annotationName, feature, distance, tpp=DEFAULT_TPP, rootpath=ROOT_PATH, k = DEFAULT_K): self.rootpath = rootpath self.concepts",
"% testid) knn = readRankingResults(knnfile) knn = knn[:self.k] if self.noise > 1e-3: n",
"None)) if tags is None: skip += 1 continue tagset = set(tags.split()) for",
"annotationName, feature, distance, tpp=DEFAULT_TPP, rootpath=ROOT_PATH, k = DEFAULT_K): self.rootpath = rootpath self.concepts =",
"c_idx = self.concept2index.get(tag, -1) if c_idx >= 0: vote[c_idx] += 1 voted +=",
"self.searcher.search_knn(content, requested=max(3000, self.k*3)) NAME_TO_TAGGER = {'tagvote':TagVoteTagger, 'pretagvote':PreTagVoteTagger, 'preknn':PreKnnTagger, 'pqtagvote':PqTagVoteTagger} if __name__ == '__main__':",
"% tpp) self.textstore = {} self.tag2freq = {} for line in open(tagfile): imageid,",
"= set(tags.split()) for tag in tagset: self.tag2freq[tag] = self.tag2freq.get(tag,0) + 1 def tagprior(self,",
"= readRankingResults(knnfile) knn = knn[:self.k] if self.noise > 1e-3: n = int(len(knn) *",
"tags.lower() self.textstore[imageid] = (userid, tags) tagset = set(tags.split()) for tag in tagset: self.tag2freq[tag]",
"feat_dim = map(int, open(shape_file).readline().split()) self.searcher = simpleknn.load_model(os.path.join(feat_dir, 'feature.bin'), feat_dim, self.nr_of_images, id_file) self.searcher.set_distance(distance) self.k",
"%d neighbors' % (skip, len(neighbors)) return vote def predict(self, content, context=None): scores =",
"self.k: break #assert(voted >= self.k), 'too many skips (%d) in %d neighbors' %",
"'too many skips (%d) in %d neighbors' % (skip, len(neighbors)) return vote def",
"dict(zip(self.concepts, range(self.nr_of_concepts))) self.imset = readImageSet(collection, collection, rootpath) self.nr_of_images = len(self.imset) self.knndir = os.path.join(collection,",
"vote[c_idx] += 1 voted += 1 if voted >= self.k: break #assert(voted >=",
"= len(self.concepts) self.concept2index = dict(zip(self.concepts, range(self.nr_of_concepts))) feat_dir = os.path.join(rootpath, collection, \"FeatureData\", feature) id_file",
"TagVoteTagger: def __init__(self, collection, annotationName, feature, distance, tpp=DEFAULT_TPP, rootpath=ROOT_PATH): self.concepts = readConcepts(collection, annotationName,",
"simpleknn.load_model(os.path.join(feat_dir, 'feature.bin'), feat_dim, self.nr_of_images, id_file) self.searcher.set_distance(distance) self.k = DEFAULT_K self._load_tag_data(collection, tpp, rootpath) printStatus(INFO,",
"tag): return float(self.k) * self.tag2freq.get(tag,0) / self.nr_of_images def _get_neighbors(self, content, context): return self.searcher.search_knn(content,",
"(random_set[i], 1000) return knn class PreKnnTagger (PreTagVoteTagger): def __init__(self, collection, annotationName, feature, distance,",
"skip = 0 neighbors = self._get_neighbors(content, context) for (name, dist) in neighbors: (userid,tags)",
"= os.path.join(feat_dir, 'shape.txt') self.nr_of_images, feat_dim = map(int, open(shape_file).readline().split()) self.searcher = load_model(featuredir, self.nr_of_images, feat_dim,nr_of_segments=512,segmentk=256,coarsek=4096)",
"neighbors' % (skip, len(neighbors)) return vote class PqTagVoteTagger (TagVoteTagger): def __init__(self, collection, annotationName,",
"= int(len(knn) * self.noise) hits = random.sample(xrange(len(knn)), n) random_set = random.sample(self.imset, n) for",
"is None or userid in users_voted: skip += 1 continue users_voted.add(userid) tagset =",
"INFO = __file__ DEFAULT_K=1000 DEFAULT_TPP = 'lemm' DEFAULT_DISTANCE = 'l1' DEFAULT_BLOCK_SIZE = 1000",
"= os.path.join(rootpath,collection,'FeatureData',feature) id_file = os.path.join(featuredir, \"id.txt\") shape_file = os.path.join(feat_dir, 'shape.txt') self.nr_of_images, feat_dim =",
"{} self.tag2freq = {} for line in open(tagfile): imageid, userid, tags = line.split('\\t')",
"'pretagvote':PreTagVoteTagger, 'preknn':PreKnnTagger, 'pqtagvote':PqTagVoteTagger} if __name__ == '__main__': feature = 'vgg-verydeep-16-fc7relu' tagger = TagVoteTagger('train10k',",
"import readConcepts from util.simpleknn import simpleknn #from sandbox.pquan.pqsearch import load_model INFO = __file__",
"self.textstore[imageid] = (userid, tags) tagset = set(tags.split()) for tag in tagset: self.tag2freq[tag] =",
"= {} for line in open(tagfile): imageid, userid, tags = line.split('\\t') tags =",
"c in self.concepts] # vote only on the given concept list voted =",
"return self.searcher.search_knn(content, requested=max(3000, self.k*3)) NAME_TO_TAGGER = {'tagvote':TagVoteTagger, 'pretagvote':PreTagVoteTagger, 'preknn':PreKnnTagger, 'pqtagvote':PqTagVoteTagger} if __name__ ==",
"= len(self.concepts) self.concept2index = dict(zip(self.concepts, range(self.nr_of_concepts))) self.imset = readImageSet(collection, collection, rootpath) self.nr_of_images =",
"collection, \"FeatureData\", feature) id_file = os.path.join(feat_dir, 'id.txt') shape_file = os.path.join(feat_dir, 'shape.txt') self.nr_of_images, feat_dim",
"= random.sample(xrange(len(knn)), n) random_set = random.sample(self.imset, n) for i in range(n): idx =",
"% (feature, distance)) self.k = k self.noise = 0 self._load_tag_data(collection, tpp, rootpath) printStatus(INFO,",
"self.k), 'too many skips (%d) in %d neighbors' % (skip, len(neighbors)) return vote"
] |
[
"= list(item.items())[0] is_element_value = self._is_intrinsic(value, '_') if is_element_value: value = value['_'] value =",
"if isinstance(item, six.string_types) and not self._is_element_type(item): item = {'Inline': item} else: item =",
"= value or [] if not isinstance(value, list): raise ValueError('Value should be a",
"obj, context): def process(node): if isinstance(node, dict): if self._is_intrinsic(node, '$'): return self._process_input(node, context)",
"elif obj_str in view.builtin_element_types: return view.builtin_element_types[obj_str], {} elif obj_str in self.registry.element_types: return self.registry.element_types[obj_str],",
"context) return {k: process(v) for k, v in node.items()} elif isinstance(node, list): return",
"for item in value: if isinstance(item, six.string_types) and not self._is_element_type(item): item = {'Inline':",
"else: result['kwargs']['props'][key] = value def _parse_str(self, obj_str): assert obj_str if obj_str[0].islower(): return view.Raw,",
"key in self._get_init_args(element_type): result['kwargs'][key] = value if is_element_value: result['kwargs_children'].add(key) elif is_element_value: result['prop_children'][key] =",
"def parse(self, obj, context): obj = _prepare(obj) obj = self._normalize_element(obj) obj = self._process_intrinsic_functions(obj,",
"_init_cache: return _init_cache[element_type] result = set() getargspec_impl = inspect.getargspec if six.PY2 else inspect.getfullargspec",
"if key in SPECIAL_KWARGS_KEYS or key in self._get_init_args(element_type): result['kwargs'][key] = value if is_element_value:",
"result |= set(spec.kwonlyargs) _init_cache[element_type] = result return result def is_parsable(obj): return isinstance(obj, six.string_types",
"= {'id', 'cols', 'updater'} _init_cache = {} class ParserContext(object): def __init__(self, inputs): self.inputs",
"return node return process(obj) @staticmethod def _normalize_element(obj): if isinstance(obj, six.string_types): obj = {obj:",
"input_node = input_node[1:] default_value = None for entry in input_node: assert isinstance(entry, dict)",
"value = value['_'] value = self._normalize_element(value) value = self._parse_dict(value) if key in SPECIAL_KWARGS_KEYS",
"inputs or {} class Parser(object): def __init__(self, registry): self.registry = registry def parse(self,",
"= value['_'] value = self._normalize_element(value) value = self._parse_dict(value) if key in SPECIAL_KWARGS_KEYS or",
"element_configuration def _parse_element_configuration(self, result, element_type, configuration_items): if not configuration_items: return if not isinstance(configuration_items,",
"dict) and len(obj) == 1 and bool(obj.get(key)) def _process_input(self, node, context): input_node =",
"input_node[1:] default_value = None for entry in input_node: assert isinstance(entry, dict) assert len(entry)",
"def _parse_dict(self, obj): assert isinstance(obj, dict) assert len(obj) == 1 element_configuration = {",
"None } key, value = list(obj.items())[0] element_type, additional_kwargs = self._parse_str(key) element_configuration['element_type'] = element_type",
"in self._get_init_args(element_type): result['kwargs'][key] = value if is_element_value: result['kwargs_children'].add(key) elif is_element_value: result['prop_children'][key] = value",
"_normalize_element(obj): if isinstance(obj, six.string_types): obj = {obj: None} elif isinstance(obj, list): obj =",
"default_value = None for entry in input_node: assert isinstance(entry, dict) assert len(entry) ==",
"return obj @staticmethod def _get_init_args(element_type): if element_type in _init_cache: return _init_cache[element_type] result =",
"be a string or a list, got: {}'.format(value)) if value and isinstance(value[0], list):",
"obj_str[0].islower(): return view.Raw, {'tag': obj_str} elif obj_str in view.builtin_element_types: return view.builtin_element_types[obj_str], {} elif",
"= {'div': obj} return obj @staticmethod def _get_init_args(element_type): if element_type in _init_cache: return",
"{} }, 'kwargs_children': set(), 'prop_children': {}, 'children': [], 'field': None } key, value",
"configuration_items): if not configuration_items: return if not isinstance(configuration_items, list): raise ValueError('Element configuration should",
"element_configuration['kwargs']['_awe_arg'] = value value = [] value = value or [] if not",
"should be a string or a list, got: {}'.format(value)) if value and isinstance(value[0],",
"self._process_intrinsic_functions(node['$'], context) if isinstance(input_node, six.string_types): input_node = [input_node] input_name = input_node[0] input_node =",
"list): return [process(item) for item in node] return node return process(obj) @staticmethod def",
"1 and bool(obj.get(key)) def _process_input(self, node, context): input_node = self._process_intrinsic_functions(node['$'], context) if isinstance(input_node,",
"len(obj) == 1 element_configuration = { 'kwargs': { 'props': {} }, 'kwargs_children': set(),",
"= configuration_items[0] configuration_items = configuration_items[1:] for item in configuration_items: assert isinstance(item, dict) assert",
"return view.Raw, {'tag': obj_str} elif obj_str in view.builtin_element_types: return view.builtin_element_types[obj_str], {} elif obj_str",
"process(v) for k, v in node.items()} elif isinstance(node, list): return [process(item) for item",
"six.string_types + (list, dict)) def _prepare(obj): if isinstance(obj, six.string_types): obj = yaml.load(obj) return",
"= {obj: None} elif isinstance(obj, list): obj = {'div': obj} return obj @staticmethod",
"= input_node[1:] default_value = None for entry in input_node: assert isinstance(entry, dict) assert",
"isinstance(node, list): return [process(item) for item in node] return node return process(obj) @staticmethod",
"obj, context): obj = _prepare(obj) obj = self._normalize_element(obj) obj = self._process_intrinsic_functions(obj, context) element_configuration",
"'prop_children': {}, 'children': [], 'field': None } key, value = list(obj.items())[0] element_type, additional_kwargs",
"self._get_init_args(element_type): result['kwargs'][key] = value if is_element_value: result['kwargs_children'].add(key) elif is_element_value: result['prop_children'][key] = value else:",
"elif obj_str in self.registry.element_types: return self.registry.element_types[obj_str], {} raise ValueError('No such element: {}'.format(obj_str)) def",
"result |= set(spec.args) if six.PY3: result |= set(spec.kwonlyargs) _init_cache[element_type] = result return result",
"else: item = self._normalize_element(item) child_element_configuration = self._parse_dict(item) element_configuration['children'].append(child_element_configuration) return element_configuration def _parse_element_configuration(self, result,",
"{}, 'children': [], 'field': None } key, value = list(obj.items())[0] element_type, additional_kwargs =",
"k, v in node.items()} elif isinstance(node, list): return [process(item) for item in node]",
"if is_element_value: result['kwargs_children'].add(key) elif is_element_value: result['prop_children'][key] = value else: result['kwargs']['props'][key] = value def",
"def _parse_element_configuration(self, result, element_type, configuration_items): if not configuration_items: return if not isinstance(configuration_items, list):",
"raise ValueError('Element configuration should be passed as a list, got: {}'.format(configuration_items)) if isinstance(configuration_items[0],",
"def _get_init_args(element_type): if element_type in _init_cache: return _init_cache[element_type] result = set() getargspec_impl =",
"_parse_element_configuration(self, result, element_type, configuration_items): if not configuration_items: return if not isinstance(configuration_items, list): raise",
"or a list, got: {}'.format(value)) if value and isinstance(value[0], list): self._parse_element_configuration(element_configuration, element_type, value[0])",
"return if not isinstance(configuration_items, list): raise ValueError('Element configuration should be passed as a",
"element_type in _init_cache: return _init_cache[element_type] result = set() getargspec_impl = inspect.getargspec if six.PY2",
"element_configuration = { 'kwargs': { 'props': {} }, 'kwargs_children': set(), 'prop_children': {}, 'children':",
"SPECIAL_KWARGS_KEYS or key in self._get_init_args(element_type): result['kwargs'][key] = value if is_element_value: result['kwargs_children'].add(key) elif is_element_value:",
"view SPECIAL_KWARGS_KEYS = {'id', 'cols', 'updater'} _init_cache = {} class ParserContext(object): def __init__(self,",
"+ (list, dict)) def _prepare(obj): if isinstance(obj, six.string_types): obj = yaml.load(obj) return obj",
"_get_init_args(element_type): if element_type in _init_cache: return _init_cache[element_type] result = set() getargspec_impl = inspect.getargspec",
"key, value = list(item.items())[0] is_element_value = self._is_intrinsic(value, '_') if is_element_value: value = value['_']",
"assert isinstance(entry, dict) assert len(entry) == 1 key, value = list(entry.items())[0] if key",
"return ( str_obj in self.registry.element_types or str_obj in view.builtin_element_types ) @staticmethod def _is_intrinsic(obj,",
"inspect import six import yaml from . import view SPECIAL_KWARGS_KEYS = {'id', 'cols',",
"context.inputs.get(input_name, default_value) else: return context.inputs[input_name] def _process_intrinsic_functions(self, obj, context): def process(node): if isinstance(node,",
"_is_element_type(self, str_obj): return ( str_obj in self.registry.element_types or str_obj in view.builtin_element_types ) @staticmethod",
"or key in self._get_init_args(element_type): result['kwargs'][key] = value if is_element_value: result['kwargs_children'].add(key) elif is_element_value: result['prop_children'][key]",
"raise ValueError('No such element: {}'.format(obj_str)) def _is_element_type(self, str_obj): return ( str_obj in self.registry.element_types",
"a string or a list, got: {}'.format(value)) if value and isinstance(value[0], list): self._parse_element_configuration(element_configuration,",
"@staticmethod def _is_intrinsic(obj, key): return isinstance(obj, dict) and len(obj) == 1 and bool(obj.get(key))",
"isinstance(obj, dict) assert len(obj) == 1 element_configuration = { 'kwargs': { 'props': {}",
"key, value = list(obj.items())[0] element_type, additional_kwargs = self._parse_str(key) element_configuration['element_type'] = element_type element_configuration['kwargs'].update(additional_kwargs) if",
"= value value = [] value = value or [] if not isinstance(value,",
"{ 'props': {} }, 'kwargs_children': set(), 'prop_children': {}, 'children': [], 'field': None }",
"in node.items()} elif isinstance(node, list): return [process(item) for item in node] return node",
"should be passed as a list, got: {}'.format(configuration_items)) if isinstance(configuration_items[0], six.string_types): result['field'] =",
"self.registry.element_types or str_obj in view.builtin_element_types ) @staticmethod def _is_intrinsic(obj, key): return isinstance(obj, dict)",
"isinstance(value, list): raise ValueError('Value should be a string or a list, got: {}'.format(value))",
"element_configuration['element_type'] = element_type element_configuration['kwargs'].update(additional_kwargs) if isinstance(value, six.string_types): if issubclass(element_type, view.Raw): value = [{'Inline':",
"return element_configuration def _parse_element_configuration(self, result, element_type, configuration_items): if not configuration_items: return if not",
"if is_element_value: value = value['_'] value = self._normalize_element(value) value = self._parse_dict(value) if key",
"if six.PY3: result |= set(spec.kwonlyargs) _init_cache[element_type] = result return result def is_parsable(obj): return",
"for item in node] return node return process(obj) @staticmethod def _normalize_element(obj): if isinstance(obj,",
"return isinstance(obj, six.string_types + (list, dict)) def _prepare(obj): if isinstance(obj, six.string_types): obj =",
"_init_cache[element_type] result = set() getargspec_impl = inspect.getargspec if six.PY2 else inspect.getfullargspec spec =",
"self.registry.element_types[obj_str], {} raise ValueError('No such element: {}'.format(obj_str)) def _is_element_type(self, str_obj): return ( str_obj",
"value = value[1:] for item in value: if isinstance(item, six.string_types) and not self._is_element_type(item):",
"|= set(spec.args) if six.PY3: result |= set(spec.kwonlyargs) _init_cache[element_type] = result return result def",
"_parse_str(self, obj_str): assert obj_str if obj_str[0].islower(): return view.Raw, {'tag': obj_str} elif obj_str in",
"if not isinstance(value, list): raise ValueError('Value should be a string or a list,",
"import yaml from . import view SPECIAL_KWARGS_KEYS = {'id', 'cols', 'updater'} _init_cache =",
"= self._normalize_element(value) value = self._parse_dict(value) if key in SPECIAL_KWARGS_KEYS or key in self._get_init_args(element_type):",
"passed as a list, got: {}'.format(configuration_items)) if isinstance(configuration_items[0], six.string_types): result['field'] = configuration_items[0] configuration_items",
"or {} class Parser(object): def __init__(self, registry): self.registry = registry def parse(self, obj,",
"default_value = value else: raise ValueError('Unknown config option: {}'.format(key)) if default_value: return context.inputs.get(input_name,",
"obj = self._process_intrinsic_functions(obj, context) element_configuration = self._parse_dict(obj) return element_configuration def _parse_dict(self, obj): assert",
") @staticmethod def _is_intrinsic(obj, key): return isinstance(obj, dict) and len(obj) == 1 and",
"__init__(self, registry): self.registry = registry def parse(self, obj, context): obj = _prepare(obj) obj",
"in _init_cache: return _init_cache[element_type] result = set() getargspec_impl = inspect.getargspec if six.PY2 else",
"in value: if isinstance(item, six.string_types) and not self._is_element_type(item): item = {'Inline': item} else:",
"such element: {}'.format(obj_str)) def _is_element_type(self, str_obj): return ( str_obj in self.registry.element_types or str_obj",
"= result return result def is_parsable(obj): return isinstance(obj, six.string_types + (list, dict)) def",
"list): self._parse_element_configuration(element_configuration, element_type, value[0]) value = value[1:] for item in value: if isinstance(item,",
"@staticmethod def _normalize_element(obj): if isinstance(obj, six.string_types): obj = {obj: None} elif isinstance(obj, list):",
"self._parse_element_configuration(element_configuration, element_type, value[0]) value = value[1:] for item in value: if isinstance(item, six.string_types)",
"def process(node): if isinstance(node, dict): if self._is_intrinsic(node, '$'): return self._process_input(node, context) return {k:",
"bool(obj.get(key)) def _process_input(self, node, context): input_node = self._process_intrinsic_functions(node['$'], context) if isinstance(input_node, six.string_types): input_node",
"context): input_node = self._process_intrinsic_functions(node['$'], context) if isinstance(input_node, six.string_types): input_node = [input_node] input_name =",
"None for entry in input_node: assert isinstance(entry, dict) assert len(entry) == 1 key,",
"for k, v in node.items()} elif isinstance(node, list): return [process(item) for item in",
"inspect.getargspec if six.PY2 else inspect.getfullargspec spec = getargspec_impl(element_type._init) result |= set(spec.args) if six.PY3:",
"{}'.format(configuration_items)) if isinstance(configuration_items[0], six.string_types): result['field'] = configuration_items[0] configuration_items = configuration_items[1:] for item in",
"return context.inputs[input_name] def _process_intrinsic_functions(self, obj, context): def process(node): if isinstance(node, dict): if self._is_intrinsic(node,",
"Parser(object): def __init__(self, registry): self.registry = registry def parse(self, obj, context): obj =",
"input_name = input_node[0] input_node = input_node[1:] default_value = None for entry in input_node:",
"issubclass(element_type, view.Raw): value = [{'Inline': value}] else: element_configuration['kwargs']['_awe_arg'] = value value = []",
"set() getargspec_impl = inspect.getargspec if six.PY2 else inspect.getfullargspec spec = getargspec_impl(element_type._init) result |=",
"result = set() getargspec_impl = inspect.getargspec if six.PY2 else inspect.getfullargspec spec = getargspec_impl(element_type._init)",
"assert len(entry) == 1 key, value = list(entry.items())[0] if key == 'default': default_value",
"[] value = value or [] if not isinstance(value, list): raise ValueError('Value should",
"return result def is_parsable(obj): return isinstance(obj, six.string_types + (list, dict)) def _prepare(obj): if",
"[], 'field': None } key, value = list(obj.items())[0] element_type, additional_kwargs = self._parse_str(key) element_configuration['element_type']",
"= { 'kwargs': { 'props': {} }, 'kwargs_children': set(), 'prop_children': {}, 'children': [],",
"{'tag': obj_str} elif obj_str in view.builtin_element_types: return view.builtin_element_types[obj_str], {} elif obj_str in self.registry.element_types:",
"= value[1:] for item in value: if isinstance(item, six.string_types) and not self._is_element_type(item): item",
"v in node.items()} elif isinstance(node, list): return [process(item) for item in node] return",
"is_element_value: value = value['_'] value = self._normalize_element(value) value = self._parse_dict(value) if key in",
"def __init__(self, registry): self.registry = registry def parse(self, obj, context): obj = _prepare(obj)",
"'kwargs': { 'props': {} }, 'kwargs_children': set(), 'prop_children': {}, 'children': [], 'field': None",
"not self._is_element_type(item): item = {'Inline': item} else: item = self._normalize_element(item) child_element_configuration = self._parse_dict(item)",
"= value if is_element_value: result['kwargs_children'].add(key) elif is_element_value: result['prop_children'][key] = value else: result['kwargs']['props'][key] =",
"else: element_configuration['kwargs']['_awe_arg'] = value value = [] value = value or [] if",
"element_configuration['children'].append(child_element_configuration) return element_configuration def _parse_element_configuration(self, result, element_type, configuration_items): if not configuration_items: return if",
"dict) assert len(entry) == 1 key, value = list(entry.items())[0] if key == 'default':",
"{} class Parser(object): def __init__(self, registry): self.registry = registry def parse(self, obj, context):",
"_process_intrinsic_functions(self, obj, context): def process(node): if isinstance(node, dict): if self._is_intrinsic(node, '$'): return self._process_input(node,",
"be passed as a list, got: {}'.format(configuration_items)) if isinstance(configuration_items[0], six.string_types): result['field'] = configuration_items[0]",
"context): obj = _prepare(obj) obj = self._normalize_element(obj) obj = self._process_intrinsic_functions(obj, context) element_configuration =",
"getargspec_impl = inspect.getargspec if six.PY2 else inspect.getfullargspec spec = getargspec_impl(element_type._init) result |= set(spec.args)",
"raise ValueError('Value should be a string or a list, got: {}'.format(value)) if value",
"== 1 and bool(obj.get(key)) def _process_input(self, node, context): input_node = self._process_intrinsic_functions(node['$'], context) if",
"obj = {obj: None} elif isinstance(obj, list): obj = {'div': obj} return obj",
"and not self._is_element_type(item): item = {'Inline': item} else: item = self._normalize_element(item) child_element_configuration =",
"= value else: raise ValueError('Unknown config option: {}'.format(key)) if default_value: return context.inputs.get(input_name, default_value)",
"str_obj in self.registry.element_types or str_obj in view.builtin_element_types ) @staticmethod def _is_intrinsic(obj, key): return",
"obj_str): assert obj_str if obj_str[0].islower(): return view.Raw, {'tag': obj_str} elif obj_str in view.builtin_element_types:",
"isinstance(obj, six.string_types): obj = {obj: None} elif isinstance(obj, list): obj = {'div': obj}",
"obj_str} elif obj_str in view.builtin_element_types: return view.builtin_element_types[obj_str], {} elif obj_str in self.registry.element_types: return",
"_init_cache[element_type] = result return result def is_parsable(obj): return isinstance(obj, six.string_types + (list, dict))",
"{}'.format(value)) if value and isinstance(value[0], list): self._parse_element_configuration(element_configuration, element_type, value[0]) value = value[1:] for",
"value = list(entry.items())[0] if key == 'default': default_value = value else: raise ValueError('Unknown",
"assert isinstance(item, dict) assert len(item) == 1 key, value = list(item.items())[0] is_element_value =",
"as a list, got: {}'.format(configuration_items)) if isinstance(configuration_items[0], six.string_types): result['field'] = configuration_items[0] configuration_items =",
"isinstance(value[0], list): self._parse_element_configuration(element_configuration, element_type, value[0]) value = value[1:] for item in value: if",
"not isinstance(configuration_items, list): raise ValueError('Element configuration should be passed as a list, got:",
"{} raise ValueError('No such element: {}'.format(obj_str)) def _is_element_type(self, str_obj): return ( str_obj in",
"= value else: result['kwargs']['props'][key] = value def _parse_str(self, obj_str): assert obj_str if obj_str[0].islower():",
"if isinstance(input_node, six.string_types): input_node = [input_node] input_name = input_node[0] input_node = input_node[1:] default_value",
"value}] else: element_configuration['kwargs']['_awe_arg'] = value value = [] value = value or []",
"list): obj = {'div': obj} return obj @staticmethod def _get_init_args(element_type): if element_type in",
"self._process_input(node, context) return {k: process(v) for k, v in node.items()} elif isinstance(node, list):",
"return _init_cache[element_type] result = set() getargspec_impl = inspect.getargspec if six.PY2 else inspect.getfullargspec spec",
"set(), 'prop_children': {}, 'children': [], 'field': None } key, value = list(obj.items())[0] element_type,",
"in self.registry.element_types or str_obj in view.builtin_element_types ) @staticmethod def _is_intrinsic(obj, key): return isinstance(obj,",
"return [process(item) for item in node] return node return process(obj) @staticmethod def _normalize_element(obj):",
"self._is_element_type(item): item = {'Inline': item} else: item = self._normalize_element(item) child_element_configuration = self._parse_dict(item) element_configuration['children'].append(child_element_configuration)",
"= inputs or {} class Parser(object): def __init__(self, registry): self.registry = registry def",
"assert len(item) == 1 key, value = list(item.items())[0] is_element_value = self._is_intrinsic(value, '_') if",
"input_node[0] input_node = input_node[1:] default_value = None for entry in input_node: assert isinstance(entry,",
"assert len(obj) == 1 element_configuration = { 'kwargs': { 'props': {} }, 'kwargs_children':",
"'updater'} _init_cache = {} class ParserContext(object): def __init__(self, inputs): self.inputs = inputs or",
"registry def parse(self, obj, context): obj = _prepare(obj) obj = self._normalize_element(obj) obj =",
"ValueError('No such element: {}'.format(obj_str)) def _is_element_type(self, str_obj): return ( str_obj in self.registry.element_types or",
"def _is_element_type(self, str_obj): return ( str_obj in self.registry.element_types or str_obj in view.builtin_element_types )",
"or [] if not isinstance(value, list): raise ValueError('Value should be a string or",
"item in node] return node return process(obj) @staticmethod def _normalize_element(obj): if isinstance(obj, six.string_types):",
"= {} class ParserContext(object): def __init__(self, inputs): self.inputs = inputs or {} class",
"value and isinstance(value[0], list): self._parse_element_configuration(element_configuration, element_type, value[0]) value = value[1:] for item in",
"}, 'kwargs_children': set(), 'prop_children': {}, 'children': [], 'field': None } key, value =",
"= list(obj.items())[0] element_type, additional_kwargs = self._parse_str(key) element_configuration['element_type'] = element_type element_configuration['kwargs'].update(additional_kwargs) if isinstance(value, six.string_types):",
"value value = [] value = value or [] if not isinstance(value, list):",
"value[1:] for item in value: if isinstance(item, six.string_types) and not self._is_element_type(item): item =",
"if isinstance(node, dict): if self._is_intrinsic(node, '$'): return self._process_input(node, context) return {k: process(v) for",
"isinstance(obj, six.string_types + (list, dict)) def _prepare(obj): if isinstance(obj, six.string_types): obj = yaml.load(obj)",
"return view.builtin_element_types[obj_str], {} elif obj_str in self.registry.element_types: return self.registry.element_types[obj_str], {} raise ValueError('No such",
"[input_node] input_name = input_node[0] input_node = input_node[1:] default_value = None for entry in",
"'field': None } key, value = list(obj.items())[0] element_type, additional_kwargs = self._parse_str(key) element_configuration['element_type'] =",
"element: {}'.format(obj_str)) def _is_element_type(self, str_obj): return ( str_obj in self.registry.element_types or str_obj in",
"configuration should be passed as a list, got: {}'.format(configuration_items)) if isinstance(configuration_items[0], six.string_types): result['field']",
"context.inputs[input_name] def _process_intrinsic_functions(self, obj, context): def process(node): if isinstance(node, dict): if self._is_intrinsic(node, '$'):",
"import inspect import six import yaml from . import view SPECIAL_KWARGS_KEYS = {'id',",
"isinstance(configuration_items[0], six.string_types): result['field'] = configuration_items[0] configuration_items = configuration_items[1:] for item in configuration_items: assert",
"= [] value = value or [] if not isinstance(value, list): raise ValueError('Value",
"'cols', 'updater'} _init_cache = {} class ParserContext(object): def __init__(self, inputs): self.inputs = inputs",
"and isinstance(value[0], list): self._parse_element_configuration(element_configuration, element_type, value[0]) value = value[1:] for item in value:",
"six.PY2 else inspect.getfullargspec spec = getargspec_impl(element_type._init) result |= set(spec.args) if six.PY3: result |=",
"in SPECIAL_KWARGS_KEYS or key in self._get_init_args(element_type): result['kwargs'][key] = value if is_element_value: result['kwargs_children'].add(key) elif",
"obj = _prepare(obj) obj = self._normalize_element(obj) obj = self._process_intrinsic_functions(obj, context) element_configuration = self._parse_dict(obj)",
"self._parse_dict(obj) return element_configuration def _parse_dict(self, obj): assert isinstance(obj, dict) assert len(obj) == 1",
"node, context): input_node = self._process_intrinsic_functions(node['$'], context) if isinstance(input_node, six.string_types): input_node = [input_node] input_name",
"return isinstance(obj, dict) and len(obj) == 1 and bool(obj.get(key)) def _process_input(self, node, context):",
"set(spec.kwonlyargs) _init_cache[element_type] = result return result def is_parsable(obj): return isinstance(obj, six.string_types + (list,",
"six.string_types) and not self._is_element_type(item): item = {'Inline': item} else: item = self._normalize_element(item) child_element_configuration",
"1 element_configuration = { 'kwargs': { 'props': {} }, 'kwargs_children': set(), 'prop_children': {},",
"isinstance(configuration_items, list): raise ValueError('Element configuration should be passed as a list, got: {}'.format(configuration_items))",
"self._is_intrinsic(node, '$'): return self._process_input(node, context) return {k: process(v) for k, v in node.items()}",
"item in configuration_items: assert isinstance(item, dict) assert len(item) == 1 key, value =",
"__init__(self, inputs): self.inputs = inputs or {} class Parser(object): def __init__(self, registry): self.registry",
"if not configuration_items: return if not isinstance(configuration_items, list): raise ValueError('Element configuration should be",
"= self._parse_dict(obj) return element_configuration def _parse_dict(self, obj): assert isinstance(obj, dict) assert len(obj) ==",
"obj): assert isinstance(obj, dict) assert len(obj) == 1 element_configuration = { 'kwargs': {",
"default_value: return context.inputs.get(input_name, default_value) else: return context.inputs[input_name] def _process_intrinsic_functions(self, obj, context): def process(node):",
"import six import yaml from . import view SPECIAL_KWARGS_KEYS = {'id', 'cols', 'updater'}",
"in view.builtin_element_types ) @staticmethod def _is_intrinsic(obj, key): return isinstance(obj, dict) and len(obj) ==",
"element_configuration = self._parse_dict(obj) return element_configuration def _parse_dict(self, obj): assert isinstance(obj, dict) assert len(obj)",
"[process(item) for item in node] return node return process(obj) @staticmethod def _normalize_element(obj): if",
"== 1 key, value = list(item.items())[0] is_element_value = self._is_intrinsic(value, '_') if is_element_value: value",
"dict) assert len(obj) == 1 element_configuration = { 'kwargs': { 'props': {} },",
"{'div': obj} return obj @staticmethod def _get_init_args(element_type): if element_type in _init_cache: return _init_cache[element_type]",
"if self._is_intrinsic(node, '$'): return self._process_input(node, context) return {k: process(v) for k, v in",
"{}'.format(key)) if default_value: return context.inputs.get(input_name, default_value) else: return context.inputs[input_name] def _process_intrinsic_functions(self, obj, context):",
"value else: raise ValueError('Unknown config option: {}'.format(key)) if default_value: return context.inputs.get(input_name, default_value) else:",
"{} elif obj_str in self.registry.element_types: return self.registry.element_types[obj_str], {} raise ValueError('No such element: {}'.format(obj_str))",
"def _normalize_element(obj): if isinstance(obj, six.string_types): obj = {obj: None} elif isinstance(obj, list): obj",
"inputs): self.inputs = inputs or {} class Parser(object): def __init__(self, registry): self.registry =",
"option: {}'.format(key)) if default_value: return context.inputs.get(input_name, default_value) else: return context.inputs[input_name] def _process_intrinsic_functions(self, obj,",
"element_type, value[0]) value = value[1:] for item in value: if isinstance(item, six.string_types) and",
"ValueError('Value should be a string or a list, got: {}'.format(value)) if value and",
"configuration_items[0] configuration_items = configuration_items[1:] for item in configuration_items: assert isinstance(item, dict) assert len(item)",
"class ParserContext(object): def __init__(self, inputs): self.inputs = inputs or {} class Parser(object): def",
"def __init__(self, inputs): self.inputs = inputs or {} class Parser(object): def __init__(self, registry):",
"string or a list, got: {}'.format(value)) if value and isinstance(value[0], list): self._parse_element_configuration(element_configuration, element_type,",
"ValueError('Unknown config option: {}'.format(key)) if default_value: return context.inputs.get(input_name, default_value) else: return context.inputs[input_name] def",
"six.string_types): obj = {obj: None} elif isinstance(obj, list): obj = {'div': obj} return",
"isinstance(item, six.string_types) and not self._is_element_type(item): item = {'Inline': item} else: item = self._normalize_element(item)",
"is_element_value = self._is_intrinsic(value, '_') if is_element_value: value = value['_'] value = self._normalize_element(value) value",
"or str_obj in view.builtin_element_types ) @staticmethod def _is_intrinsic(obj, key): return isinstance(obj, dict) and",
"return self.registry.element_types[obj_str], {} raise ValueError('No such element: {}'.format(obj_str)) def _is_element_type(self, str_obj): return (",
"if default_value: return context.inputs.get(input_name, default_value) else: return context.inputs[input_name] def _process_intrinsic_functions(self, obj, context): def",
"if key == 'default': default_value = value else: raise ValueError('Unknown config option: {}'.format(key))",
"node return process(obj) @staticmethod def _normalize_element(obj): if isinstance(obj, six.string_types): obj = {obj: None}",
"_parse_dict(self, obj): assert isinstance(obj, dict) assert len(obj) == 1 element_configuration = { 'kwargs':",
"self._normalize_element(item) child_element_configuration = self._parse_dict(item) element_configuration['children'].append(child_element_configuration) return element_configuration def _parse_element_configuration(self, result, element_type, configuration_items): if",
"default_value) else: return context.inputs[input_name] def _process_intrinsic_functions(self, obj, context): def process(node): if isinstance(node, dict):",
"None} elif isinstance(obj, list): obj = {'div': obj} return obj @staticmethod def _get_init_args(element_type):",
"value[0]) value = value[1:] for item in value: if isinstance(item, six.string_types) and not",
"obj = self._normalize_element(obj) obj = self._process_intrinsic_functions(obj, context) element_configuration = self._parse_dict(obj) return element_configuration def",
"def _parse_str(self, obj_str): assert obj_str if obj_str[0].islower(): return view.Raw, {'tag': obj_str} elif obj_str",
"self.registry = registry def parse(self, obj, context): obj = _prepare(obj) obj = self._normalize_element(obj)",
"value else: result['kwargs']['props'][key] = value def _parse_str(self, obj_str): assert obj_str if obj_str[0].islower(): return",
"isinstance(node, dict): if self._is_intrinsic(node, '$'): return self._process_input(node, context) return {k: process(v) for k,",
"{'Inline': item} else: item = self._normalize_element(item) child_element_configuration = self._parse_dict(item) element_configuration['children'].append(child_element_configuration) return element_configuration def",
". import view SPECIAL_KWARGS_KEYS = {'id', 'cols', 'updater'} _init_cache = {} class ParserContext(object):",
"str_obj in view.builtin_element_types ) @staticmethod def _is_intrinsic(obj, key): return isinstance(obj, dict) and len(obj)",
"view.builtin_element_types[obj_str], {} elif obj_str in self.registry.element_types: return self.registry.element_types[obj_str], {} raise ValueError('No such element:",
"a list, got: {}'.format(value)) if value and isinstance(value[0], list): self._parse_element_configuration(element_configuration, element_type, value[0]) value",
"entry in input_node: assert isinstance(entry, dict) assert len(entry) == 1 key, value =",
"view.Raw): value = [{'Inline': value}] else: element_configuration['kwargs']['_awe_arg'] = value value = [] value",
"def _process_input(self, node, context): input_node = self._process_intrinsic_functions(node['$'], context) if isinstance(input_node, six.string_types): input_node =",
"= element_type element_configuration['kwargs'].update(additional_kwargs) if isinstance(value, six.string_types): if issubclass(element_type, view.Raw): value = [{'Inline': value}]",
"[] if not isinstance(value, list): raise ValueError('Value should be a string or a",
"if not isinstance(configuration_items, list): raise ValueError('Element configuration should be passed as a list,",
"result['prop_children'][key] = value else: result['kwargs']['props'][key] = value def _parse_str(self, obj_str): assert obj_str if",
"self.inputs = inputs or {} class Parser(object): def __init__(self, registry): self.registry = registry",
"{ 'kwargs': { 'props': {} }, 'kwargs_children': set(), 'prop_children': {}, 'children': [], 'field':",
"got: {}'.format(configuration_items)) if isinstance(configuration_items[0], six.string_types): result['field'] = configuration_items[0] configuration_items = configuration_items[1:] for item",
"value: if isinstance(item, six.string_types) and not self._is_element_type(item): item = {'Inline': item} else: item",
"{k: process(v) for k, v in node.items()} elif isinstance(node, list): return [process(item) for",
"assert isinstance(obj, dict) assert len(obj) == 1 element_configuration = { 'kwargs': { 'props':",
"if obj_str[0].islower(): return view.Raw, {'tag': obj_str} elif obj_str in view.builtin_element_types: return view.builtin_element_types[obj_str], {}",
"self._process_intrinsic_functions(obj, context) element_configuration = self._parse_dict(obj) return element_configuration def _parse_dict(self, obj): assert isinstance(obj, dict)",
"= self._is_intrinsic(value, '_') if is_element_value: value = value['_'] value = self._normalize_element(value) value =",
"node.items()} elif isinstance(node, list): return [process(item) for item in node] return node return",
"context): def process(node): if isinstance(node, dict): if self._is_intrinsic(node, '$'): return self._process_input(node, context) return",
"isinstance(item, dict) assert len(item) == 1 key, value = list(item.items())[0] is_element_value = self._is_intrinsic(value,",
"list, got: {}'.format(configuration_items)) if isinstance(configuration_items[0], six.string_types): result['field'] = configuration_items[0] configuration_items = configuration_items[1:] for",
"not configuration_items: return if not isinstance(configuration_items, list): raise ValueError('Element configuration should be passed",
"configuration_items: return if not isinstance(configuration_items, list): raise ValueError('Element configuration should be passed as",
"_is_intrinsic(obj, key): return isinstance(obj, dict) and len(obj) == 1 and bool(obj.get(key)) def _process_input(self,",
"obj @staticmethod def _get_init_args(element_type): if element_type in _init_cache: return _init_cache[element_type] result = set()",
"input_node: assert isinstance(entry, dict) assert len(entry) == 1 key, value = list(entry.items())[0] if",
"_init_cache = {} class ParserContext(object): def __init__(self, inputs): self.inputs = inputs or {}",
"= self._normalize_element(item) child_element_configuration = self._parse_dict(item) element_configuration['children'].append(child_element_configuration) return element_configuration def _parse_element_configuration(self, result, element_type, configuration_items):",
"obj_str in view.builtin_element_types: return view.builtin_element_types[obj_str], {} elif obj_str in self.registry.element_types: return self.registry.element_types[obj_str], {}",
"value = [] value = value or [] if not isinstance(value, list): raise",
"'children': [], 'field': None } key, value = list(obj.items())[0] element_type, additional_kwargs = self._parse_str(key)",
"{} class ParserContext(object): def __init__(self, inputs): self.inputs = inputs or {} class Parser(object):",
"element_configuration['kwargs'].update(additional_kwargs) if isinstance(value, six.string_types): if issubclass(element_type, view.Raw): value = [{'Inline': value}] else: element_configuration['kwargs']['_awe_arg']",
"input_node = self._process_intrinsic_functions(node['$'], context) if isinstance(input_node, six.string_types): input_node = [input_node] input_name = input_node[0]",
"six.string_types): result['field'] = configuration_items[0] configuration_items = configuration_items[1:] for item in configuration_items: assert isinstance(item,",
"str_obj): return ( str_obj in self.registry.element_types or str_obj in view.builtin_element_types ) @staticmethod def",
"context) element_configuration = self._parse_dict(obj) return element_configuration def _parse_dict(self, obj): assert isinstance(obj, dict) assert",
"return {k: process(v) for k, v in node.items()} elif isinstance(node, list): return [process(item)",
"def _process_intrinsic_functions(self, obj, context): def process(node): if isinstance(node, dict): if self._is_intrinsic(node, '$'): return",
"= getargspec_impl(element_type._init) result |= set(spec.args) if six.PY3: result |= set(spec.kwonlyargs) _init_cache[element_type] = result",
"obj_str if obj_str[0].islower(): return view.Raw, {'tag': obj_str} elif obj_str in view.builtin_element_types: return view.builtin_element_types[obj_str],",
"} key, value = list(obj.items())[0] element_type, additional_kwargs = self._parse_str(key) element_configuration['element_type'] = element_type element_configuration['kwargs'].update(additional_kwargs)",
"element_type, configuration_items): if not configuration_items: return if not isinstance(configuration_items, list): raise ValueError('Element configuration",
"input_node = [input_node] input_name = input_node[0] input_node = input_node[1:] default_value = None for",
"elif isinstance(node, list): return [process(item) for item in node] return node return process(obj)",
"def _is_intrinsic(obj, key): return isinstance(obj, dict) and len(obj) == 1 and bool(obj.get(key)) def",
"'$'): return self._process_input(node, context) return {k: process(v) for k, v in node.items()} elif",
"value if is_element_value: result['kwargs_children'].add(key) elif is_element_value: result['prop_children'][key] = value else: result['kwargs']['props'][key] = value",
"assert obj_str if obj_str[0].islower(): return view.Raw, {'tag': obj_str} elif obj_str in view.builtin_element_types: return",
"class Parser(object): def __init__(self, registry): self.registry = registry def parse(self, obj, context): obj",
"'props': {} }, 'kwargs_children': set(), 'prop_children': {}, 'children': [], 'field': None } key,",
"in node] return node return process(obj) @staticmethod def _normalize_element(obj): if isinstance(obj, six.string_types): obj",
"getargspec_impl(element_type._init) result |= set(spec.args) if six.PY3: result |= set(spec.kwonlyargs) _init_cache[element_type] = result return",
"list): raise ValueError('Element configuration should be passed as a list, got: {}'.format(configuration_items)) if",
"'kwargs_children': set(), 'prop_children': {}, 'children': [], 'field': None } key, value = list(obj.items())[0]",
"[{'Inline': value}] else: element_configuration['kwargs']['_awe_arg'] = value value = [] value = value or",
"= value def _parse_str(self, obj_str): assert obj_str if obj_str[0].islower(): return view.Raw, {'tag': obj_str}",
"if value and isinstance(value[0], list): self._parse_element_configuration(element_configuration, element_type, value[0]) value = value[1:] for item",
"result['kwargs'][key] = value if is_element_value: result['kwargs_children'].add(key) elif is_element_value: result['prop_children'][key] = value else: result['kwargs']['props'][key]",
"for item in configuration_items: assert isinstance(item, dict) assert len(item) == 1 key, value",
"len(obj) == 1 and bool(obj.get(key)) def _process_input(self, node, context): input_node = self._process_intrinsic_functions(node['$'], context)",
"value = [{'Inline': value}] else: element_configuration['kwargs']['_awe_arg'] = value value = [] value =",
"= [{'Inline': value}] else: element_configuration['kwargs']['_awe_arg'] = value value = [] value = value",
"import view SPECIAL_KWARGS_KEYS = {'id', 'cols', 'updater'} _init_cache = {} class ParserContext(object): def",
"if six.PY2 else inspect.getfullargspec spec = getargspec_impl(element_type._init) result |= set(spec.args) if six.PY3: result",
"self._normalize_element(obj) obj = self._process_intrinsic_functions(obj, context) element_configuration = self._parse_dict(obj) return element_configuration def _parse_dict(self, obj):",
"self._is_intrinsic(value, '_') if is_element_value: value = value['_'] value = self._normalize_element(value) value = self._parse_dict(value)",
"element_type element_configuration['kwargs'].update(additional_kwargs) if isinstance(value, six.string_types): if issubclass(element_type, view.Raw): value = [{'Inline': value}] else:",
"configuration_items[1:] for item in configuration_items: assert isinstance(item, dict) assert len(item) == 1 key,",
"if element_type in _init_cache: return _init_cache[element_type] result = set() getargspec_impl = inspect.getargspec if",
"got: {}'.format(value)) if value and isinstance(value[0], list): self._parse_element_configuration(element_configuration, element_type, value[0]) value = value[1:]",
"is_element_value: result['kwargs_children'].add(key) elif is_element_value: result['prop_children'][key] = value else: result['kwargs']['props'][key] = value def _parse_str(self,",
"self._parse_dict(value) if key in SPECIAL_KWARGS_KEYS or key in self._get_init_args(element_type): result['kwargs'][key] = value if",
"result['kwargs']['props'][key] = value def _parse_str(self, obj_str): assert obj_str if obj_str[0].islower(): return view.Raw, {'tag':",
"SPECIAL_KWARGS_KEYS = {'id', 'cols', 'updater'} _init_cache = {} class ParserContext(object): def __init__(self, inputs):",
"1 key, value = list(item.items())[0] is_element_value = self._is_intrinsic(value, '_') if is_element_value: value =",
"len(item) == 1 key, value = list(item.items())[0] is_element_value = self._is_intrinsic(value, '_') if is_element_value:",
"obj} return obj @staticmethod def _get_init_args(element_type): if element_type in _init_cache: return _init_cache[element_type] result",
"context) if isinstance(input_node, six.string_types): input_node = [input_node] input_name = input_node[0] input_node = input_node[1:]",
"list, got: {}'.format(value)) if value and isinstance(value[0], list): self._parse_element_configuration(element_configuration, element_type, value[0]) value =",
"and len(obj) == 1 and bool(obj.get(key)) def _process_input(self, node, context): input_node = self._process_intrinsic_functions(node['$'],",
"if isinstance(value, six.string_types): if issubclass(element_type, view.Raw): value = [{'Inline': value}] else: element_configuration['kwargs']['_awe_arg'] =",
"obj = {'div': obj} return obj @staticmethod def _get_init_args(element_type): if element_type in _init_cache:",
"= configuration_items[1:] for item in configuration_items: assert isinstance(item, dict) assert len(item) == 1",
"list(item.items())[0] is_element_value = self._is_intrinsic(value, '_') if is_element_value: value = value['_'] value = self._normalize_element(value)",
"isinstance(obj, list): obj = {'div': obj} return obj @staticmethod def _get_init_args(element_type): if element_type",
"in self.registry.element_types: return self.registry.element_types[obj_str], {} raise ValueError('No such element: {}'.format(obj_str)) def _is_element_type(self, str_obj):",
"= None for entry in input_node: assert isinstance(entry, dict) assert len(entry) == 1",
"value = self._parse_dict(value) if key in SPECIAL_KWARGS_KEYS or key in self._get_init_args(element_type): result['kwargs'][key] =",
"len(entry) == 1 key, value = list(entry.items())[0] if key == 'default': default_value =",
"element_type, additional_kwargs = self._parse_str(key) element_configuration['element_type'] = element_type element_configuration['kwargs'].update(additional_kwargs) if isinstance(value, six.string_types): if issubclass(element_type,",
"key, value = list(entry.items())[0] if key == 'default': default_value = value else: raise",
"return element_configuration def _parse_dict(self, obj): assert isinstance(obj, dict) assert len(obj) == 1 element_configuration",
"for entry in input_node: assert isinstance(entry, dict) assert len(entry) == 1 key, value",
"six.PY3: result |= set(spec.kwonlyargs) _init_cache[element_type] = result return result def is_parsable(obj): return isinstance(obj,",
"self._normalize_element(value) value = self._parse_dict(value) if key in SPECIAL_KWARGS_KEYS or key in self._get_init_args(element_type): result['kwargs'][key]",
"else: raise ValueError('Unknown config option: {}'.format(key)) if default_value: return context.inputs.get(input_name, default_value) else: return",
"= self._parse_dict(value) if key in SPECIAL_KWARGS_KEYS or key in self._get_init_args(element_type): result['kwargs'][key] = value",
"else: return context.inputs[input_name] def _process_intrinsic_functions(self, obj, context): def process(node): if isinstance(node, dict): if",
"self._parse_str(key) element_configuration['element_type'] = element_type element_configuration['kwargs'].update(additional_kwargs) if isinstance(value, six.string_types): if issubclass(element_type, view.Raw): value =",
"@staticmethod def _get_init_args(element_type): if element_type in _init_cache: return _init_cache[element_type] result = set() getargspec_impl",
"result def is_parsable(obj): return isinstance(obj, six.string_types + (list, dict)) def _prepare(obj): if isinstance(obj,",
"result['field'] = configuration_items[0] configuration_items = configuration_items[1:] for item in configuration_items: assert isinstance(item, dict)",
"elif is_element_value: result['prop_children'][key] = value else: result['kwargs']['props'][key] = value def _parse_str(self, obj_str): assert",
"element_configuration def _parse_dict(self, obj): assert isinstance(obj, dict) assert len(obj) == 1 element_configuration =",
"= self._parse_str(key) element_configuration['element_type'] = element_type element_configuration['kwargs'].update(additional_kwargs) if isinstance(value, six.string_types): if issubclass(element_type, view.Raw): value",
"key == 'default': default_value = value else: raise ValueError('Unknown config option: {}'.format(key)) if",
"= list(entry.items())[0] if key == 'default': default_value = value else: raise ValueError('Unknown config",
"inspect.getfullargspec spec = getargspec_impl(element_type._init) result |= set(spec.args) if six.PY3: result |= set(spec.kwonlyargs) _init_cache[element_type]",
"value = list(obj.items())[0] element_type, additional_kwargs = self._parse_str(key) element_configuration['element_type'] = element_type element_configuration['kwargs'].update(additional_kwargs) if isinstance(value,",
"dict) assert len(item) == 1 key, value = list(item.items())[0] is_element_value = self._is_intrinsic(value, '_')",
"= _prepare(obj) obj = self._normalize_element(obj) obj = self._process_intrinsic_functions(obj, context) element_configuration = self._parse_dict(obj) return",
"= self._process_intrinsic_functions(obj, context) element_configuration = self._parse_dict(obj) return element_configuration def _parse_dict(self, obj): assert isinstance(obj,",
"item = {'Inline': item} else: item = self._normalize_element(item) child_element_configuration = self._parse_dict(item) element_configuration['children'].append(child_element_configuration) return",
"else inspect.getfullargspec spec = getargspec_impl(element_type._init) result |= set(spec.args) if six.PY3: result |= set(spec.kwonlyargs)",
"= self._parse_dict(item) element_configuration['children'].append(child_element_configuration) return element_configuration def _parse_element_configuration(self, result, element_type, configuration_items): if not configuration_items:",
"yaml from . import view SPECIAL_KWARGS_KEYS = {'id', 'cols', 'updater'} _init_cache = {}",
"{}'.format(obj_str)) def _is_element_type(self, str_obj): return ( str_obj in self.registry.element_types or str_obj in view.builtin_element_types",
"{'id', 'cols', 'updater'} _init_cache = {} class ParserContext(object): def __init__(self, inputs): self.inputs =",
"'default': default_value = value else: raise ValueError('Unknown config option: {}'.format(key)) if default_value: return",
"return process(obj) @staticmethod def _normalize_element(obj): if isinstance(obj, six.string_types): obj = {obj: None} elif",
"= registry def parse(self, obj, context): obj = _prepare(obj) obj = self._normalize_element(obj) obj",
"obj_str in self.registry.element_types: return self.registry.element_types[obj_str], {} raise ValueError('No such element: {}'.format(obj_str)) def _is_element_type(self,",
"return self._process_input(node, context) return {k: process(v) for k, v in node.items()} elif isinstance(node,",
"= {'Inline': item} else: item = self._normalize_element(item) child_element_configuration = self._parse_dict(item) element_configuration['children'].append(child_element_configuration) return element_configuration",
"return context.inputs.get(input_name, default_value) else: return context.inputs[input_name] def _process_intrinsic_functions(self, obj, context): def process(node): if",
"= [input_node] input_name = input_node[0] input_node = input_node[1:] default_value = None for entry",
"view.builtin_element_types: return view.builtin_element_types[obj_str], {} elif obj_str in self.registry.element_types: return self.registry.element_types[obj_str], {} raise ValueError('No",
"parse(self, obj, context): obj = _prepare(obj) obj = self._normalize_element(obj) obj = self._process_intrinsic_functions(obj, context)",
"'_') if is_element_value: value = value['_'] value = self._normalize_element(value) value = self._parse_dict(value) if",
"|= set(spec.kwonlyargs) _init_cache[element_type] = result return result def is_parsable(obj): return isinstance(obj, six.string_types +",
"_process_input(self, node, context): input_node = self._process_intrinsic_functions(node['$'], context) if isinstance(input_node, six.string_types): input_node = [input_node]",
"self._parse_dict(item) element_configuration['children'].append(child_element_configuration) return element_configuration def _parse_element_configuration(self, result, element_type, configuration_items): if not configuration_items: return",
"and bool(obj.get(key)) def _process_input(self, node, context): input_node = self._process_intrinsic_functions(node['$'], context) if isinstance(input_node, six.string_types):",
"configuration_items = configuration_items[1:] for item in configuration_items: assert isinstance(item, dict) assert len(item) ==",
"set(spec.args) if six.PY3: result |= set(spec.kwonlyargs) _init_cache[element_type] = result return result def is_parsable(obj):",
"value or [] if not isinstance(value, list): raise ValueError('Value should be a string",
"a list, got: {}'.format(configuration_items)) if isinstance(configuration_items[0], six.string_types): result['field'] = configuration_items[0] configuration_items = configuration_items[1:]",
"= set() getargspec_impl = inspect.getargspec if six.PY2 else inspect.getfullargspec spec = getargspec_impl(element_type._init) result",
"additional_kwargs = self._parse_str(key) element_configuration['element_type'] = element_type element_configuration['kwargs'].update(additional_kwargs) if isinstance(value, six.string_types): if issubclass(element_type, view.Raw):",
"( str_obj in self.registry.element_types or str_obj in view.builtin_element_types ) @staticmethod def _is_intrinsic(obj, key):",
"six.string_types): input_node = [input_node] input_name = input_node[0] input_node = input_node[1:] default_value = None",
"list(obj.items())[0] element_type, additional_kwargs = self._parse_str(key) element_configuration['element_type'] = element_type element_configuration['kwargs'].update(additional_kwargs) if isinstance(value, six.string_types): if",
"spec = getargspec_impl(element_type._init) result |= set(spec.args) if six.PY3: result |= set(spec.kwonlyargs) _init_cache[element_type] =",
"node] return node return process(obj) @staticmethod def _normalize_element(obj): if isinstance(obj, six.string_types): obj =",
"view.builtin_element_types ) @staticmethod def _is_intrinsic(obj, key): return isinstance(obj, dict) and len(obj) == 1",
"list(entry.items())[0] if key == 'default': default_value = value else: raise ValueError('Unknown config option:",
"= inspect.getargspec if six.PY2 else inspect.getfullargspec spec = getargspec_impl(element_type._init) result |= set(spec.args) if",
"in view.builtin_element_types: return view.builtin_element_types[obj_str], {} elif obj_str in self.registry.element_types: return self.registry.element_types[obj_str], {} raise",
"elif isinstance(obj, list): obj = {'div': obj} return obj @staticmethod def _get_init_args(element_type): if",
"item} else: item = self._normalize_element(item) child_element_configuration = self._parse_dict(item) element_configuration['children'].append(child_element_configuration) return element_configuration def _parse_element_configuration(self,",
"dict): if self._is_intrinsic(node, '$'): return self._process_input(node, context) return {k: process(v) for k, v",
"if issubclass(element_type, view.Raw): value = [{'Inline': value}] else: element_configuration['kwargs']['_awe_arg'] = value value =",
"value = list(item.items())[0] is_element_value = self._is_intrinsic(value, '_') if is_element_value: value = value['_'] value",
"result, element_type, configuration_items): if not configuration_items: return if not isinstance(configuration_items, list): raise ValueError('Element",
"= input_node[0] input_node = input_node[1:] default_value = None for entry in input_node: assert",
"process(obj) @staticmethod def _normalize_element(obj): if isinstance(obj, six.string_types): obj = {obj: None} elif isinstance(obj,",
"== 1 element_configuration = { 'kwargs': { 'props': {} }, 'kwargs_children': set(), 'prop_children':",
"raise ValueError('Unknown config option: {}'.format(key)) if default_value: return context.inputs.get(input_name, default_value) else: return context.inputs[input_name]",
"isinstance(value, six.string_types): if issubclass(element_type, view.Raw): value = [{'Inline': value}] else: element_configuration['kwargs']['_awe_arg'] = value",
"if isinstance(obj, six.string_types): obj = {obj: None} elif isinstance(obj, list): obj = {'div':",
"_prepare(obj) obj = self._normalize_element(obj) obj = self._process_intrinsic_functions(obj, context) element_configuration = self._parse_dict(obj) return element_configuration",
"value def _parse_str(self, obj_str): assert obj_str if obj_str[0].islower(): return view.Raw, {'tag': obj_str} elif",
"def is_parsable(obj): return isinstance(obj, six.string_types + (list, dict)) def _prepare(obj): if isinstance(obj, six.string_types):",
"is_element_value: result['prop_children'][key] = value else: result['kwargs']['props'][key] = value def _parse_str(self, obj_str): assert obj_str",
"is_parsable(obj): return isinstance(obj, six.string_types + (list, dict)) def _prepare(obj): if isinstance(obj, six.string_types): obj",
"list): raise ValueError('Value should be a string or a list, got: {}'.format(value)) if",
"result['kwargs_children'].add(key) elif is_element_value: result['prop_children'][key] = value else: result['kwargs']['props'][key] = value def _parse_str(self, obj_str):",
"1 key, value = list(entry.items())[0] if key == 'default': default_value = value else:",
"key): return isinstance(obj, dict) and len(obj) == 1 and bool(obj.get(key)) def _process_input(self, node,",
"item = self._normalize_element(item) child_element_configuration = self._parse_dict(item) element_configuration['children'].append(child_element_configuration) return element_configuration def _parse_element_configuration(self, result, element_type,",
"ValueError('Element configuration should be passed as a list, got: {}'.format(configuration_items)) if isinstance(configuration_items[0], six.string_types):",
"view.Raw, {'tag': obj_str} elif obj_str in view.builtin_element_types: return view.builtin_element_types[obj_str], {} elif obj_str in",
"if isinstance(configuration_items[0], six.string_types): result['field'] = configuration_items[0] configuration_items = configuration_items[1:] for item in configuration_items:",
"self.registry.element_types: return self.registry.element_types[obj_str], {} raise ValueError('No such element: {}'.format(obj_str)) def _is_element_type(self, str_obj): return",
"isinstance(obj, dict) and len(obj) == 1 and bool(obj.get(key)) def _process_input(self, node, context): input_node",
"== 'default': default_value = value else: raise ValueError('Unknown config option: {}'.format(key)) if default_value:",
"= self._normalize_element(obj) obj = self._process_intrinsic_functions(obj, context) element_configuration = self._parse_dict(obj) return element_configuration def _parse_dict(self,",
"value = value or [] if not isinstance(value, list): raise ValueError('Value should be",
"{obj: None} elif isinstance(obj, list): obj = {'div': obj} return obj @staticmethod def",
"from . import view SPECIAL_KWARGS_KEYS = {'id', 'cols', 'updater'} _init_cache = {} class",
"configuration_items: assert isinstance(item, dict) assert len(item) == 1 key, value = list(item.items())[0] is_element_value",
"value['_'] value = self._normalize_element(value) value = self._parse_dict(value) if key in SPECIAL_KWARGS_KEYS or key",
"six import yaml from . import view SPECIAL_KWARGS_KEYS = {'id', 'cols', 'updater'} _init_cache",
"not isinstance(value, list): raise ValueError('Value should be a string or a list, got:",
"config option: {}'.format(key)) if default_value: return context.inputs.get(input_name, default_value) else: return context.inputs[input_name] def _process_intrinsic_functions(self,",
"value = self._normalize_element(value) value = self._parse_dict(value) if key in SPECIAL_KWARGS_KEYS or key in",
"key in SPECIAL_KWARGS_KEYS or key in self._get_init_args(element_type): result['kwargs'][key] = value if is_element_value: result['kwargs_children'].add(key)",
"registry): self.registry = registry def parse(self, obj, context): obj = _prepare(obj) obj =",
"isinstance(input_node, six.string_types): input_node = [input_node] input_name = input_node[0] input_node = input_node[1:] default_value =",
"result return result def is_parsable(obj): return isinstance(obj, six.string_types + (list, dict)) def _prepare(obj):",
"item in value: if isinstance(item, six.string_types) and not self._is_element_type(item): item = {'Inline': item}",
"process(node): if isinstance(node, dict): if self._is_intrinsic(node, '$'): return self._process_input(node, context) return {k: process(v)",
"in configuration_items: assert isinstance(item, dict) assert len(item) == 1 key, value = list(item.items())[0]",
"ParserContext(object): def __init__(self, inputs): self.inputs = inputs or {} class Parser(object): def __init__(self,",
"isinstance(entry, dict) assert len(entry) == 1 key, value = list(entry.items())[0] if key ==",
"== 1 key, value = list(entry.items())[0] if key == 'default': default_value = value",
"in input_node: assert isinstance(entry, dict) assert len(entry) == 1 key, value = list(entry.items())[0]",
"= self._process_intrinsic_functions(node['$'], context) if isinstance(input_node, six.string_types): input_node = [input_node] input_name = input_node[0] input_node",
"six.string_types): if issubclass(element_type, view.Raw): value = [{'Inline': value}] else: element_configuration['kwargs']['_awe_arg'] = value value",
"child_element_configuration = self._parse_dict(item) element_configuration['children'].append(child_element_configuration) return element_configuration def _parse_element_configuration(self, result, element_type, configuration_items): if not"
] |
[] |
[
"inner_table.append(inner) return tabulate(inner_table, tablefmt=\"plain\") @property def _edge_info(self): inner_table = [[\"\", \"Index\", \"Energy\", \"P-ratio\",",
"from monty.json import MSONable from pydefect.defaults import defaults from pydefect.util.coords import pretty_coords from",
"f\"vbm has acceptor phs: {self.has_acceptor_phs} \" \\ f\"({self.vbm_hole_occupation:5.3f} vs. {defaults.state_occupied_threshold})\" cbm_phs = f\"cbm",
"spin. @property def is_shallow(self): return any([i.is_shallow for i in self.states]) @property def has_donor_phs(self):",
"pretty_orbital(orbitals: Dict[str, List[float]]): \"\"\" :param orbitals: An example is {\"Mn\": [0.5, 0.4, 0.01]}",
"kpt_coords: List[Coords] kpt_weights: List[float] lowest_band_index: int fermi_level: float def kpt_idx(self, kpt_coord): for i,",
"EdgeInfo def __str__(self): def show_edge_info(edge_info: EdgeInfo): return [edge_info.band_idx, edge_info.energy, f\"{edge_info.occupation:5.2f}\", pretty_orbital(edge_info.orbital_info.orbitals), pretty_coords(edge_info.kpt_coord)] return",
"from vise.util.typing import Coords, GenCoords printed_orbital_weight_threshold = 0.1 @dataclass class BandEdgeEigenvalues(MSONable, ToJsonFileMixIn): #",
"None @dataclass class BandEdgeOrbitalInfos(MSONable, ToJsonFileMixIn): orbital_infos: List[List[List[\"OrbitalInfo\"]]] # [spin, k-idx, band-idx] kpt_coords: List[Coords]",
"# determine the band_idx where the occupation changes largely. if lower[0].occupation - upper[0].occupation",
"np from monty.json import MSONable from pydefect.defaults import defaults from pydefect.util.coords import pretty_coords",
"has donor phs: {self.has_donor_phs} \" \\ f\"({self.cbm_electron_occupation:5.3f} vs. {defaults.state_occupied_threshold})\" return \"\\n\".join([table, vbm_phs, cbm_phs])",
"+ (2,)) for i, x in enumerate(self.orbital_infos): for j, y in enumerate(x): for",
"vise.util.mix_in import ToJsonFileMixIn from vise.util.typing import Coords, GenCoords printed_orbital_weight_threshold = 0.1 @dataclass class",
"List[List[List[\"OrbitalInfo\"]]] # [spin, k-idx, band-idx] kpt_coords: List[Coords] kpt_weights: List[float] lowest_band_index: int fermi_level: float",
"range(min_idx, max_idx): actual_band_idx = band_idx + self.lowest_band_index + 1 for kpt_idx, orb_info in",
"sorted([i for i in indices_set]) def __str__(self): lines = [\" -- band-edge states",
"ToJsonFileMixIn from vise.util.typing import Coords, GenCoords printed_orbital_weight_threshold = 0.1 @dataclass class BandEdgeEigenvalues(MSONable, ToJsonFileMixIn):",
"Optional[float] = None center: Optional[GenCoords] = None @dataclass class EdgeInfo(MSONable): band_idx: int kpt_coord:",
"> defaults.state_occupied_threshold @property def has_acceptor_phs(self): return self.vbm_hole_occupation > defaults.state_occupied_threshold @property def has_unoccupied_localized_state(self): return",
"lo in self.localized_orbitals: participation_ratio = f\"{lo.participation_ratio:5.2f}\" \\ if lo.participation_ratio else \"None\" inner =",
"= band_idx + 1 break max_idx = min(middle_idx + 3, len(t_orbital_info)) min_idx =",
"version dependent quantities. \"\"\" energy: float # max eigenvalue # {\"Mn\": [0.01, ..],",
"coding: utf-8 -*- # Copyright (c) 2020. Distributed under the terms of the",
"def is_shallow(self): return self.has_donor_phs or self.has_acceptor_phs @property def has_donor_phs(self): return self.cbm_electron_occupation > defaults.state_occupied_threshold",
"(2,)) for i, x in enumerate(self.orbital_infos): for j, y in enumerate(x): for k,",
"return any([lo.occupation < defaults.state_unoccupied_threshold for lo in self.localized_orbitals]) @property def has_occupied_localized_state(self): return any([lo.occupation",
"has_donor_phs(self): return any([i.has_donor_phs for i in self.states]) @property def has_acceptor_phs(self): return any([i.has_acceptor_phs for",
"int def pretty_orbital(orbitals: Dict[str, List[float]]): \"\"\" :param orbitals: An example is {\"Mn\": [0.5,",
"for i in self.states]) @property def has_acceptor_phs(self): return any([i.has_acceptor_phs for i in self.states])",
"min_idx, t_orbital_info @dataclass class LocalizedOrbital(MSONable): band_idx: int ave_energy: float occupation: float orbitals: Dict[str,",
"_band_block(self): band_block = [[\"Index\", \"Kpoint index\", \"Energy\", \"Occupation\", \"P-ratio\", \"Orbital\"]] for orbital_info in",
"kpt_weight) in enumerate( zip(self.kpt_coords, self.kpt_weights), 1): coord = pretty_coords(kpt_coord) weight = f\"{kpt_weight:4.3f}\" kpt_block.append([index,",
"\"Orbitals\", \"K-point coords\"], [\"VBM\"] + show_edge_info(self.vbm_info), [\"CBM\"] + show_edge_info(self.cbm_info)], tablefmt=\"plain\") @dataclass class BandEdgeState(MSONable):",
"# where lists contain s, p, d, (f) orbital components. orbitals: Dict[str, List[float]]",
"def occupation(self): return self.orbital_info.occupation @property def p_ratio(self): return self.orbital_info.participation_ratio @dataclass class PerfectBandEdgeState(MSONable, ToJsonFileMixIn):",
"i, x in enumerate(self.orbital_infos): for j, y in enumerate(x): for k, z in",
"+ self._show_edge_info( self.vbm_info, self.vbm_orbital_diff), [\"CBM\"] + self._show_edge_info( self.cbm_info, self.cbm_orbital_diff)] table = tabulate(inner_table, tablefmt=\"plain\")",
"occupation energies_and_occupations: List[List[List[List[float]]]] kpt_coords: List[Tuple[float, float, float]] lowest_band_index: int def pretty_orbital(orbitals: Dict[str, List[float]]):",
"coord = pretty_coords(kpt_coord) weight = f\"{kpt_weight:4.3f}\" kpt_block.append([index, coord, weight]) return tabulate(kpt_block, tablefmt=\"plain\") @staticmethod",
"has acceptor phs: {self.has_acceptor_phs} \" \\ f\"({self.vbm_hole_occupation:5.3f} vs. {defaults.state_occupied_threshold})\" cbm_phs = f\"cbm has",
"occupation, p_ratio, orbs]) band_block.append([\"--\"]) band_block.append(\"\") return tabulate(band_block, tablefmt=\"plain\") @property def _kpt_block(self): kpt_block =",
"= None @property def is_shallow(self): return self.has_donor_phs or self.has_acceptor_phs @property def has_donor_phs(self): return",
"< defaults.state_unoccupied_threshold for lo in self.localized_orbitals]) @property def has_occupied_localized_state(self): return any([lo.occupation > defaults.state_occupied_threshold",
"any([i.has_donor_phs for i in self.states]) @property def has_acceptor_phs(self): return any([i.has_acceptor_phs for i in",
"\"Band info near band edges\", self._band_block]) @property def _band_block(self): band_block = [[\"Index\", \"Kpoint",
"= set() for state in self.states: indices_set.add(state.vbm_info.band_idx) for lo in state.localized_orbitals: indices_set.add(lo.band_idx) indices_set.add(state.cbm_info.band_idx)",
"indices_set.add(state.cbm_info.band_idx) return sorted([i for i in indices_set]) def __str__(self): lines = [\" --",
"[[\"Index\", \"Kpoint index\", \"Energy\", \"Occupation\", \"P-ratio\", \"Orbital\"]] for orbital_info in self.orbital_infos: max_idx, min_idx,",
"@property def _orbital_info(self): inner_table = [[\"Index\", \"Energy\", \"P-ratio\", \"Occupation\", \"Orbitals\"]] w_radius = self.localized_orbitals",
"f\"{edge_info.energy:7.3f}\", f\"{edge_info.p_ratio:5.2f}\", f\"{edge_info.occupation:5.2f}\", f\"{orb_diff:5.2f}\", pretty_orbital(edge_info.orbital_info.orbitals), pretty_coords(edge_info.kpt_coord)] @dataclass class BandEdgeStates(MSONable, ToJsonFileMixIn): states: List[BandEdgeState] #",
"lines = [\" -- band-edge states info\"] for spin, state in zip([\"up\", \"down\"],",
"\"\", \"Band info near band edges\", self._band_block]) @property def _band_block(self): band_block = [[\"Index\",",
"energy: float # max eigenvalue # {\"Mn\": [0.01, ..], \"O\": [0.03, 0.5]}, #",
"+ 1 break max_idx = min(middle_idx + 3, len(t_orbital_info)) min_idx = max(middle_idx -",
"from dataclasses import dataclass from typing import List, Dict, Tuple, Optional, Set import",
"lower) in enumerate(zip(t_orbital_info[1:], t_orbital_info[:-1])): # determine the band_idx where the occupation changes largely.",
"tabulate import tabulate from vise.util.mix_in import ToJsonFileMixIn from vise.util.typing import Coords, GenCoords printed_orbital_weight_threshold",
"0.1 @dataclass class BandEdgeEigenvalues(MSONable, ToJsonFileMixIn): # [spin, k-idx, band-idx] = energy, occupation energies_and_occupations:",
"def kpt_idx(self, kpt_coord): for i, orig_kpt in enumerate(self.kpt_coords): if sum(abs(k - l) for",
"inner.extend([f\"{lo.radius:5.2f}\", pretty_coords(lo.center)]) inner_table.append(inner) return tabulate(inner_table, tablefmt=\"plain\") @property def _edge_info(self): inner_table = [[\"\", \"Index\",",
"def _show_edge_info(edge_info: EdgeInfo, orb_diff: float): return [edge_info.band_idx + 1, f\"{edge_info.energy:7.3f}\", f\"{edge_info.p_ratio:5.2f}\", f\"{edge_info.occupation:5.2f}\", f\"{orb_diff:5.2f}\",",
"_kpt_block(self): kpt_block = [[\"Index\", \"Coords\", \"Weight\"]] for index, (kpt_coord, kpt_weight) in enumerate( zip(self.kpt_coords,",
"orbital_info: \"OrbitalInfo\" @property def orbitals(self): return self.orbital_info.orbitals @property def energy(self): return self.orbital_info.energy @property",
"= None cbm_electron_occupation: float = None @property def is_shallow(self): return self.has_donor_phs or self.has_acceptor_phs",
"Orbital(s)\", self._orbital_info]) @property def _orbital_info(self): inner_table = [[\"Index\", \"Energy\", \"P-ratio\", \"Occupation\", \"Orbitals\"]] w_radius",
"cbm_info: EdgeInfo def __str__(self): def show_edge_info(edge_info: EdgeInfo): return [edge_info.band_idx, edge_info.energy, f\"{edge_info.occupation:5.2f}\", pretty_orbital(edge_info.orbital_info.orbitals), pretty_coords(edge_info.kpt_coord)]",
"\"Energy\", \"P-ratio\", \"Occupation\", \"Orbitals\"]] w_radius = self.localized_orbitals and self.localized_orbitals[0].radius if w_radius: inner_table[0].extend([\"Radius\", \"Center\"])",
"band_idx where the occupation changes largely. if lower[0].occupation - upper[0].occupation > 0.1: middle_idx",
"np.array(orbital_info).T.tolist() middle_idx = int(len(t_orbital_info) / 2) for band_idx, (upper, lower) in enumerate(zip(t_orbital_info[1:], t_orbital_info[:-1])):",
"int(len(t_orbital_info) / 2) for band_idx, (upper, lower) in enumerate(zip(t_orbital_info[1:], t_orbital_info[:-1])): # determine the",
"self.vbm_orbital_diff), [\"CBM\"] + self._show_edge_info( self.cbm_info, self.cbm_orbital_diff)] table = tabulate(inner_table, tablefmt=\"plain\") vbm_phs = f\"vbm",
"tabulate from vise.util.mix_in import ToJsonFileMixIn from vise.util.typing import Coords, GenCoords printed_orbital_weight_threshold = 0.1",
"class LocalizedOrbital(MSONable): band_idx: int ave_energy: float occupation: float orbitals: Dict[str, List[float]] participation_ratio: Optional[float]",
"> defaults.state_occupied_threshold @property def has_unoccupied_localized_state(self): return any([lo.occupation < defaults.state_unoccupied_threshold for lo in self.localized_orbitals])",
"index\", \"Energy\", \"Occupation\", \"P-ratio\", \"Orbital\"]] for orbital_info in self.orbital_infos: max_idx, min_idx, t_orb_info =",
"any([lo.occupation > defaults.state_occupied_threshold for lo in self.localized_orbitals]) def __str__(self): return \"\\n\".join([self._edge_info, \"---\", \"Localized",
"acceptor phs: {self.has_acceptor_phs} \" \\ f\"({self.vbm_hole_occupation:5.3f} vs. {defaults.state_occupied_threshold})\" cbm_phs = f\"cbm has donor",
"orbital_infos.append(f\"{elem}-{orb_name}: {weight:.2f}\") return \", \".join(orbital_infos) @dataclass class OrbitalInfo(MSONable): \"\"\"Note that this is code",
"@dataclass class BandEdgeOrbitalInfos(MSONable, ToJsonFileMixIn): orbital_infos: List[List[List[\"OrbitalInfo\"]]] # [spin, k-idx, band-idx] kpt_coords: List[Coords] kpt_weights:",
"band_idx + self.lowest_band_index + 1 for kpt_idx, orb_info in enumerate(t_orb_info[band_idx], 1): energy =",
"List[List[OrbitalInfo]] ) -> Tuple[int, int, List[List[OrbitalInfo]]]: # swap [kpt_idx][band_idx] -> [bane_idx][kpt_idx] t_orbital_info =",
"ToJsonFileMixIn): states: List[BandEdgeState] # by spin. @property def is_shallow(self): return any([i.is_shallow for i",
"inner_table = [[\"\", \"Index\", \"Energy\", \"P-ratio\", \"Occupation\", \"OrbDiff\", \"Orbitals\", \"K-point coords\"], [\"VBM\"] +",
"@property def has_occupied_localized_state(self): return any([i.has_occupied_localized_state for i in self.states]) @property def band_indices_from_vbm_to_cbm(self) ->",
"class BandEdgeEigenvalues(MSONable, ToJsonFileMixIn): # [spin, k-idx, band-idx] = energy, occupation energies_and_occupations: List[List[List[List[float]]]] kpt_coords:",
"= None center: Optional[GenCoords] = None @dataclass class EdgeInfo(MSONable): band_idx: int kpt_coord: Coords",
"self.lowest_band_index + 1 for kpt_idx, orb_info in enumerate(t_orb_info[band_idx], 1): energy = f\"{orb_info.energy :5.2f}\"",
"float = None @dataclass class BandEdgeOrbitalInfos(MSONable, ToJsonFileMixIn): orbital_infos: List[List[List[\"OrbitalInfo\"]]] # [spin, k-idx, band-idx]",
"band edges\", self._band_block]) @property def _band_block(self): band_block = [[\"Index\", \"Kpoint index\", \"Energy\", \"Occupation\",",
"p_ratio = f\"{orb_info.participation_ratio:4.1f}\" orbs = pretty_orbital(orb_info.orbitals) band_block.append([actual_band_idx, kpt_idx, energy, occupation, p_ratio, orbs]) band_block.append([\"--\"])",
"\"Occupation\", \"OrbDiff\", \"Orbitals\", \"K-point coords\"], [\"VBM\"] + self._show_edge_info( self.vbm_info, self.vbm_orbital_diff), [\"CBM\"] + self._show_edge_info(",
"= [[\"Index\", \"Kpoint index\", \"Energy\", \"Occupation\", \"P-ratio\", \"Orbital\"]] for orbital_info in self.orbital_infos: max_idx,",
"return tabulate([ [\"\", \"Index\", \"Energy\", \"Occupation\", \"Orbitals\", \"K-point coords\"], [\"VBM\"] + show_edge_info(self.vbm_info), [\"CBM\"]",
"Dict[str, List[float]]): \"\"\" :param orbitals: An example is {\"Mn\": [0.5, 0.4, 0.01]} (no",
"state.localized_orbitals: indices_set.add(lo.band_idx) indices_set.add(state.cbm_info.band_idx) return sorted([i for i in indices_set]) def __str__(self): lines =",
"BandEdgeEigenvalues(MSONable, ToJsonFileMixIn): # [spin, k-idx, band-idx] = energy, occupation energies_and_occupations: List[List[List[List[float]]]] kpt_coords: List[Tuple[float,",
"None center: Optional[GenCoords] = None @dataclass class EdgeInfo(MSONable): band_idx: int kpt_coord: Coords orbital_info:",
"Coords, GenCoords printed_orbital_weight_threshold = 0.1 @dataclass class BandEdgeEigenvalues(MSONable, ToJsonFileMixIn): # [spin, k-idx, band-idx]",
"\" \\ f\"({self.cbm_electron_occupation:5.3f} vs. {defaults.state_occupied_threshold})\" return \"\\n\".join([table, vbm_phs, cbm_phs]) @staticmethod def _show_edge_info(edge_info: EdgeInfo,",
"for i in self.states]) @property def has_unoccupied_localized_state(self): return any([i.has_unoccupied_localized_state for i in self.states])",
"quantities. \"\"\" energy: float # max eigenvalue # {\"Mn\": [0.01, ..], \"O\": [0.03,",
"0.40\" \"\"\" orbital_infos = [] for elem, orbs in orbitals.items(): for orb_name, weight",
"+ 1 for kpt_idx, orb_info in enumerate(t_orb_info[band_idx], 1): energy = f\"{orb_info.energy :5.2f}\" occupation",
"+ 3, len(t_orbital_info)) min_idx = max(middle_idx - 3, 0) return max_idx, min_idx, t_orbital_info",
"def orbitals(self): return self.orbital_info.orbitals @property def energy(self): return self.orbital_info.energy @property def occupation(self): return",
"orbitals(self): return self.orbital_info.orbitals @property def energy(self): return self.orbital_info.energy @property def occupation(self): return self.orbital_info.occupation",
"i, orig_kpt in enumerate(self.kpt_coords): if sum(abs(k - l) for k, l in zip(orig_kpt,",
"has_unoccupied_localized_state(self): return any([i.has_unoccupied_localized_state for i in self.states]) @property def has_occupied_localized_state(self): return any([i.has_occupied_localized_state for",
"tablefmt=\"plain\") @property def _kpt_block(self): kpt_block = [[\"Index\", \"Coords\", \"Weight\"]] for index, (kpt_coord, kpt_weight)",
"not in kpt_coords {self.kpt_coords}.\") @property def energies_and_occupations(self) -> List[List[List[List[float]]]]: result = np.zeros(np.shape(self.orbital_infos) +",
"@dataclass class BandEdgeEigenvalues(MSONable, ToJsonFileMixIn): # [spin, k-idx, band-idx] = energy, occupation energies_and_occupations: List[List[List[List[float]]]]",
"List[List[OrbitalInfo]]]: # swap [kpt_idx][band_idx] -> [bane_idx][kpt_idx] t_orbital_info = np.array(orbital_info).T.tolist() middle_idx = int(len(t_orbital_info) /",
"band-edge states info\"] for spin, state in zip([\"up\", \"down\"], self.states): lines.append(f\"Spin-{spin}\") lines.append(state.__str__()) lines.append(\"\")",
"its version dependent quantities. \"\"\" energy: float # max eigenvalue # {\"Mn\": [0.01,",
"or self.has_acceptor_phs @property def has_donor_phs(self): return self.cbm_electron_occupation > defaults.state_occupied_threshold @property def has_acceptor_phs(self): return",
"f\"{lo.participation_ratio:5.2f}\" \\ if lo.participation_ratio else \"None\" inner = [lo.band_idx + 1, f\"{lo.ave_energy:7.3f}\", participation_ratio,",
"return self.cbm_electron_occupation > defaults.state_occupied_threshold @property def has_acceptor_phs(self): return self.vbm_hole_occupation > defaults.state_occupied_threshold @property def",
"\"P-ratio\", \"Occupation\", \"Orbitals\"]] w_radius = self.localized_orbitals and self.localized_orbitals[0].radius if w_radius: inner_table[0].extend([\"Radius\", \"Center\"]) for",
"inner = [lo.band_idx + 1, f\"{lo.ave_energy:7.3f}\", participation_ratio, f\"{lo.occupation:5.2f}\", pretty_orbital(lo.orbitals)] if w_radius: inner.extend([f\"{lo.radius:5.2f}\", pretty_coords(lo.center)])",
"f\"{edge_info.p_ratio:5.2f}\", f\"{edge_info.occupation:5.2f}\", f\"{orb_diff:5.2f}\", pretty_orbital(edge_info.orbital_info.orbitals), pretty_coords(edge_info.kpt_coord)] @dataclass class BandEdgeStates(MSONable, ToJsonFileMixIn): states: List[BandEdgeState] # by",
"= int(len(t_orbital_info) / 2) for band_idx, (upper, lower) in enumerate(zip(t_orbital_info[1:], t_orbital_info[:-1])): # determine",
"float occupation: float orbitals: Dict[str, List[float]] participation_ratio: Optional[float] = None radius: Optional[float] =",
"EdgeInfo, orb_diff: float): return [edge_info.band_idx + 1, f\"{edge_info.energy:7.3f}\", f\"{edge_info.p_ratio:5.2f}\", f\"{edge_info.occupation:5.2f}\", f\"{orb_diff:5.2f}\", pretty_orbital(edge_info.orbital_info.orbitals), pretty_coords(edge_info.kpt_coord)]",
"in zip([\"s\", \"p\", \"d\", \"f\"], orbs): if weight > printed_orbital_weight_threshold: orbital_infos.append(f\"{elem}-{orb_name}: {weight:.2f}\") return",
":5.2f}\" occupation = f\"{orb_info.occupation:4.1f}\" p_ratio = f\"{orb_info.participation_ratio:4.1f}\" orbs = pretty_orbital(orb_info.orbitals) band_block.append([actual_band_idx, kpt_idx, energy,",
"return \"\\n\".join([table, vbm_phs, cbm_phs]) @staticmethod def _show_edge_info(edge_info: EdgeInfo, orb_diff: float): return [edge_info.band_idx +",
"= [z.energy, z.occupation] return result.tolist() def __str__(self): return \"\\n\".join([\" -- band-edge orbitals info\",",
"the occupation changes largely. if lower[0].occupation - upper[0].occupation > 0.1: middle_idx = band_idx",
"code and its version dependent quantities. \"\"\" energy: float # max eigenvalue #",
"enumerate(self.kpt_coords): if sum(abs(k - l) for k, l in zip(orig_kpt, kpt_coord)) < 1e-5:",
"energy, occupation, p_ratio, orbs]) band_block.append([\"--\"]) band_block.append(\"\") return tabulate(band_block, tablefmt=\"plain\") @property def _kpt_block(self): kpt_block",
"i in self.states]) @property def has_donor_phs(self): return any([i.has_donor_phs for i in self.states]) @property",
"max eigenvalue # {\"Mn\": [0.01, ..], \"O\": [0.03, 0.5]}, # where lists contain",
"from tabulate import tabulate from vise.util.mix_in import ToJsonFileMixIn from vise.util.typing import Coords, GenCoords",
"coords\"], [\"VBM\"] + show_edge_info(self.vbm_info), [\"CBM\"] + show_edge_info(self.cbm_info)], tablefmt=\"plain\") @dataclass class BandEdgeState(MSONable): vbm_info: EdgeInfo",
"= None @dataclass class EdgeInfo(MSONable): band_idx: int kpt_coord: Coords orbital_info: \"OrbitalInfo\" @property def",
"orbitals: An example is {\"Mn\": [0.5, 0.4, 0.01]} (no f-orbital) :return: \"Mn-s: 0.50,",
"@property def band_indices_from_vbm_to_cbm(self) -> List[int]: indices_set = set() for state in self.states: indices_set.add(state.vbm_info.band_idx)",
"if w_radius: inner.extend([f\"{lo.radius:5.2f}\", pretty_coords(lo.center)]) inner_table.append(inner) return tabulate(inner_table, tablefmt=\"plain\") @property def _edge_info(self): inner_table =",
"return i raise ValueError(f\"{kpt_coord} not in kpt_coords {self.kpt_coords}.\") @property def energies_and_occupations(self) -> List[List[List[List[float]]]]:",
"if weight > printed_orbital_weight_threshold: orbital_infos.append(f\"{elem}-{orb_name}: {weight:.2f}\") return \", \".join(orbital_infos) @dataclass class OrbitalInfo(MSONable): \"\"\"Note",
"import dataclass from typing import List, Dict, Tuple, Optional, Set import numpy as",
"__str__(self): def show_edge_info(edge_info: EdgeInfo): return [edge_info.band_idx, edge_info.energy, f\"{edge_info.occupation:5.2f}\", pretty_orbital(edge_info.orbital_info.orbitals), pretty_coords(edge_info.kpt_coord)] return tabulate([ [\"\",",
"where lists contain s, p, d, (f) orbital components. orbitals: Dict[str, List[float]] occupation:",
"for lo in self.localized_orbitals]) def __str__(self): return \"\\n\".join([self._edge_info, \"---\", \"Localized Orbital(s)\", self._orbital_info]) @property",
"self.orbital_infos: max_idx, min_idx, t_orb_info = self._band_idx_range(orbital_info) for band_idx in range(min_idx, max_idx): actual_band_idx =",
"tabulate(kpt_block, tablefmt=\"plain\") @staticmethod def _band_idx_range(orbital_info: List[List[OrbitalInfo]] ) -> Tuple[int, int, List[List[OrbitalInfo]]]: # swap",
"orbitals info\", \"K-points info\", self._kpt_block, \"\", \"Band info near band edges\", self._band_block]) @property",
"pydefect.util.coords import pretty_coords from tabulate import tabulate from vise.util.mix_in import ToJsonFileMixIn from vise.util.typing",
"- upper[0].occupation > 0.1: middle_idx = band_idx + 1 break max_idx = min(middle_idx",
"participation_ratio: float = None @dataclass class BandEdgeOrbitalInfos(MSONable, ToJsonFileMixIn): orbital_infos: List[List[List[\"OrbitalInfo\"]]] # [spin, k-idx,",
"int, List[List[OrbitalInfo]]]: # swap [kpt_idx][band_idx] -> [bane_idx][kpt_idx] t_orbital_info = np.array(orbital_info).T.tolist() middle_idx = int(len(t_orbital_info)",
"self.has_acceptor_phs @property def has_donor_phs(self): return self.cbm_electron_occupation > defaults.state_occupied_threshold @property def has_acceptor_phs(self): return self.vbm_hole_occupation",
"indices_set.add(lo.band_idx) indices_set.add(state.cbm_info.band_idx) return sorted([i for i in indices_set]) def __str__(self): lines = [\"",
"pretty_coords(edge_info.kpt_coord)] return tabulate([ [\"\", \"Index\", \"Energy\", \"Occupation\", \"Orbitals\", \"K-point coords\"], [\"VBM\"] + show_edge_info(self.vbm_info),",
"Distributed under the terms of the MIT License. from dataclasses import dataclass from",
"tabulate([ [\"\", \"Index\", \"Energy\", \"Occupation\", \"Orbitals\", \"K-point coords\"], [\"VBM\"] + show_edge_info(self.vbm_info), [\"CBM\"] +",
"float = None @property def is_shallow(self): return self.has_donor_phs or self.has_acceptor_phs @property def has_donor_phs(self):",
"for k, z in enumerate(y): result[i][j][k] = [z.energy, z.occupation] return result.tolist() def __str__(self):",
"> defaults.state_occupied_threshold for lo in self.localized_orbitals]) def __str__(self): return \"\\n\".join([self._edge_info, \"---\", \"Localized Orbital(s)\",",
"if lower[0].occupation - upper[0].occupation > 0.1: middle_idx = band_idx + 1 break max_idx",
"f\"({self.vbm_hole_occupation:5.3f} vs. {defaults.state_occupied_threshold})\" cbm_phs = f\"cbm has donor phs: {self.has_donor_phs} \" \\ f\"({self.cbm_electron_occupation:5.3f}",
"-> List[int]: indices_set = set() for state in self.states: indices_set.add(state.vbm_info.band_idx) for lo in",
"terms of the MIT License. from dataclasses import dataclass from typing import List,",
"float = None cbm_electron_occupation: float = None @property def is_shallow(self): return self.has_donor_phs or",
"from pydefect.util.coords import pretty_coords from tabulate import tabulate from vise.util.mix_in import ToJsonFileMixIn from",
"self._band_idx_range(orbital_info) for band_idx in range(min_idx, max_idx): actual_band_idx = band_idx + self.lowest_band_index + 1",
"participation_ratio, f\"{lo.occupation:5.2f}\", pretty_orbital(lo.orbitals)] if w_radius: inner.extend([f\"{lo.radius:5.2f}\", pretty_coords(lo.center)]) inner_table.append(inner) return tabulate(inner_table, tablefmt=\"plain\") @property def",
"= self.localized_orbitals and self.localized_orbitals[0].radius if w_radius: inner_table[0].extend([\"Radius\", \"Center\"]) for lo in self.localized_orbitals: participation_ratio",
"# {\"Mn\": [0.01, ..], \"O\": [0.03, 0.5]}, # where lists contain s, p,",
"= [[\"Index\", \"Coords\", \"Weight\"]] for index, (kpt_coord, kpt_weight) in enumerate( zip(self.kpt_coords, self.kpt_weights), 1):",
"import tabulate from vise.util.mix_in import ToJsonFileMixIn from vise.util.typing import Coords, GenCoords printed_orbital_weight_threshold =",
"printed_orbital_weight_threshold = 0.1 @dataclass class BandEdgeEigenvalues(MSONable, ToJsonFileMixIn): # [spin, k-idx, band-idx] = energy,",
"\"Orbitals\", \"K-point coords\"], [\"VBM\"] + self._show_edge_info( self.vbm_info, self.vbm_orbital_diff), [\"CBM\"] + self._show_edge_info( self.cbm_info, self.cbm_orbital_diff)]",
"[\"\", \"Index\", \"Energy\", \"Occupation\", \"Orbitals\", \"K-point coords\"], [\"VBM\"] + show_edge_info(self.vbm_info), [\"CBM\"] + show_edge_info(self.cbm_info)],",
"\"Energy\", \"Occupation\", \"P-ratio\", \"Orbital\"]] for orbital_info in self.orbital_infos: max_idx, min_idx, t_orb_info = self._band_idx_range(orbital_info)",
"utf-8 -*- # Copyright (c) 2020. Distributed under the terms of the MIT",
"contain s, p, d, (f) orbital components. orbitals: Dict[str, List[float]] occupation: float participation_ratio:",
"class BandEdgeStates(MSONable, ToJsonFileMixIn): states: List[BandEdgeState] # by spin. @property def is_shallow(self): return any([i.is_shallow",
"max_idx = min(middle_idx + 3, len(t_orbital_info)) min_idx = max(middle_idx - 3, 0) return",
"in range(min_idx, max_idx): actual_band_idx = band_idx + self.lowest_band_index + 1 for kpt_idx, orb_info",
"None @dataclass class EdgeInfo(MSONable): band_idx: int kpt_coord: Coords orbital_info: \"OrbitalInfo\" @property def orbitals(self):",
"indices_set = set() for state in self.states: indices_set.add(state.vbm_info.band_idx) for lo in state.localized_orbitals: indices_set.add(lo.band_idx)",
"= None @dataclass class BandEdgeOrbitalInfos(MSONable, ToJsonFileMixIn): orbital_infos: List[List[List[\"OrbitalInfo\"]]] # [spin, k-idx, band-idx] kpt_coords:",
"\"P-ratio\", \"Orbital\"]] for orbital_info in self.orbital_infos: max_idx, min_idx, t_orb_info = self._band_idx_range(orbital_info) for band_idx",
"@staticmethod def _band_idx_range(orbital_info: List[List[OrbitalInfo]] ) -> Tuple[int, int, List[List[OrbitalInfo]]]: # swap [kpt_idx][band_idx] ->",
"components. orbitals: Dict[str, List[float]] occupation: float participation_ratio: float = None @dataclass class BandEdgeOrbitalInfos(MSONable,",
"dependent quantities. \"\"\" energy: float # max eigenvalue # {\"Mn\": [0.01, ..], \"O\":",
"@property def has_unoccupied_localized_state(self): return any([lo.occupation < defaults.state_unoccupied_threshold for lo in self.localized_orbitals]) @property def",
"2) for band_idx, (upper, lower) in enumerate(zip(t_orbital_info[1:], t_orbital_info[:-1])): # determine the band_idx where",
"self.vbm_info, self.vbm_orbital_diff), [\"CBM\"] + self._show_edge_info( self.cbm_info, self.cbm_orbital_diff)] table = tabulate(inner_table, tablefmt=\"plain\") vbm_phs =",
"\"Energy\", \"Occupation\", \"Orbitals\", \"K-point coords\"], [\"VBM\"] + show_edge_info(self.vbm_info), [\"CBM\"] + show_edge_info(self.cbm_info)], tablefmt=\"plain\") @dataclass",
"table = tabulate(inner_table, tablefmt=\"plain\") vbm_phs = f\"vbm has acceptor phs: {self.has_acceptor_phs} \" \\",
"{\"Mn\": [0.01, ..], \"O\": [0.03, 0.5]}, # where lists contain s, p, d,",
"else \"None\" inner = [lo.band_idx + 1, f\"{lo.ave_energy:7.3f}\", participation_ratio, f\"{lo.occupation:5.2f}\", pretty_orbital(lo.orbitals)] if w_radius:",
"info near band edges\", self._band_block]) @property def _band_block(self): band_block = [[\"Index\", \"Kpoint index\",",
":return: \"Mn-s: 0.50, Mn-p: 0.40\" \"\"\" orbital_infos = [] for elem, orbs in",
"{self.has_acceptor_phs} \" \\ f\"({self.vbm_hole_occupation:5.3f} vs. {defaults.state_occupied_threshold})\" cbm_phs = f\"cbm has donor phs: {self.has_donor_phs}",
"orbs = pretty_orbital(orb_info.orbitals) band_block.append([actual_band_idx, kpt_idx, energy, occupation, p_ratio, orbs]) band_block.append([\"--\"]) band_block.append(\"\") return tabulate(band_block,",
"[edge_info.band_idx, edge_info.energy, f\"{edge_info.occupation:5.2f}\", pretty_orbital(edge_info.orbital_info.orbitals), pretty_coords(edge_info.kpt_coord)] return tabulate([ [\"\", \"Index\", \"Energy\", \"Occupation\", \"Orbitals\", \"K-point",
"[0.03, 0.5]}, # where lists contain s, p, d, (f) orbital components. orbitals:",
"in enumerate(self.orbital_infos): for j, y in enumerate(x): for k, z in enumerate(y): result[i][j][k]",
"BandEdgeOrbitalInfos(MSONable, ToJsonFileMixIn): orbital_infos: List[List[List[\"OrbitalInfo\"]]] # [spin, k-idx, band-idx] kpt_coords: List[Coords] kpt_weights: List[float] lowest_band_index:",
"= None radius: Optional[float] = None center: Optional[GenCoords] = None @dataclass class EdgeInfo(MSONable):",
"\"OrbitalInfo\" @property def orbitals(self): return self.orbital_info.orbitals @property def energy(self): return self.orbital_info.energy @property def",
"z in enumerate(y): result[i][j][k] = [z.energy, z.occupation] return result.tolist() def __str__(self): return \"\\n\".join([\"",
"int kpt_coord: Coords orbital_info: \"OrbitalInfo\" @property def orbitals(self): return self.orbital_info.orbitals @property def energy(self):",
"\"\"\" orbital_infos = [] for elem, orbs in orbitals.items(): for orb_name, weight in",
"@property def is_shallow(self): return any([i.is_shallow for i in self.states]) @property def has_donor_phs(self): return",
"t_orbital_info[:-1])): # determine the band_idx where the occupation changes largely. if lower[0].occupation -",
"edges\", self._band_block]) @property def _band_block(self): band_block = [[\"Index\", \"Kpoint index\", \"Energy\", \"Occupation\", \"P-ratio\",",
"\"\\n\".join([\" -- band-edge orbitals info\", \"K-points info\", self._kpt_block, \"\", \"Band info near band",
"vbm_info: EdgeInfo cbm_info: EdgeInfo def __str__(self): def show_edge_info(edge_info: EdgeInfo): return [edge_info.band_idx, edge_info.energy, f\"{edge_info.occupation:5.2f}\",",
"energy, occupation energies_and_occupations: List[List[List[List[float]]]] kpt_coords: List[Tuple[float, float, float]] lowest_band_index: int def pretty_orbital(orbitals: Dict[str,",
"cbm_orbital_diff: float localized_orbitals: List[LocalizedOrbital] vbm_hole_occupation: float = None cbm_electron_occupation: float = None @property",
"k, z in enumerate(y): result[i][j][k] = [z.energy, z.occupation] return result.tolist() def __str__(self): return",
"Dict[str, List[float]] participation_ratio: Optional[float] = None radius: Optional[float] = None center: Optional[GenCoords] =",
"+ 1, f\"{edge_info.energy:7.3f}\", f\"{edge_info.p_ratio:5.2f}\", f\"{edge_info.occupation:5.2f}\", f\"{orb_diff:5.2f}\", pretty_orbital(edge_info.orbital_info.orbitals), pretty_coords(edge_info.kpt_coord)] @dataclass class BandEdgeStates(MSONable, ToJsonFileMixIn): states:",
"class PerfectBandEdgeState(MSONable, ToJsonFileMixIn): vbm_info: EdgeInfo cbm_info: EdgeInfo def __str__(self): def show_edge_info(edge_info: EdgeInfo): return",
"= 0.1 @dataclass class BandEdgeEigenvalues(MSONable, ToJsonFileMixIn): # [spin, k-idx, band-idx] = energy, occupation",
"eigenvalue # {\"Mn\": [0.01, ..], \"O\": [0.03, 0.5]}, # where lists contain s,",
"edge_info.energy, f\"{edge_info.occupation:5.2f}\", pretty_orbital(edge_info.orbital_info.orbitals), pretty_coords(edge_info.kpt_coord)] return tabulate([ [\"\", \"Index\", \"Energy\", \"Occupation\", \"Orbitals\", \"K-point coords\"],",
"License. from dataclasses import dataclass from typing import List, Dict, Tuple, Optional, Set",
"orb_name, weight in zip([\"s\", \"p\", \"d\", \"f\"], orbs): if weight > printed_orbital_weight_threshold: orbital_infos.append(f\"{elem}-{orb_name}:",
"band_idx: int ave_energy: float occupation: float orbitals: Dict[str, List[float]] participation_ratio: Optional[float] = None",
"EdgeInfo cbm_info: EdgeInfo vbm_orbital_diff: float cbm_orbital_diff: float localized_orbitals: List[LocalizedOrbital] vbm_hole_occupation: float = None",
"@property def _edge_info(self): inner_table = [[\"\", \"Index\", \"Energy\", \"P-ratio\", \"Occupation\", \"OrbDiff\", \"Orbitals\", \"K-point",
"t_orb_info = self._band_idx_range(orbital_info) for band_idx in range(min_idx, max_idx): actual_band_idx = band_idx + self.lowest_band_index",
"occupation(self): return self.orbital_info.occupation @property def p_ratio(self): return self.orbital_info.participation_ratio @dataclass class PerfectBandEdgeState(MSONable, ToJsonFileMixIn): vbm_info:",
"List[float]] participation_ratio: Optional[float] = None radius: Optional[float] = None center: Optional[GenCoords] = None",
"{\"Mn\": [0.5, 0.4, 0.01]} (no f-orbital) :return: \"Mn-s: 0.50, Mn-p: 0.40\" \"\"\" orbital_infos",
"lo in state.localized_orbitals: indices_set.add(lo.band_idx) indices_set.add(state.cbm_info.band_idx) return sorted([i for i in indices_set]) def __str__(self):",
"[0.01, ..], \"O\": [0.03, 0.5]}, # where lists contain s, p, d, (f)",
"kpt_idx(self, kpt_coord): for i, orig_kpt in enumerate(self.kpt_coords): if sum(abs(k - l) for k,",
"lower[0].occupation - upper[0].occupation > 0.1: middle_idx = band_idx + 1 break max_idx =",
"kpt_weights: List[float] lowest_band_index: int fermi_level: float def kpt_idx(self, kpt_coord): for i, orig_kpt in",
"f\"{edge_info.occupation:5.2f}\", pretty_orbital(edge_info.orbital_info.orbitals), pretty_coords(edge_info.kpt_coord)] return tabulate([ [\"\", \"Index\", \"Energy\", \"Occupation\", \"Orbitals\", \"K-point coords\"], [\"VBM\"]",
"w_radius = self.localized_orbitals and self.localized_orbitals[0].radius if w_radius: inner_table[0].extend([\"Radius\", \"Center\"]) for lo in self.localized_orbitals:",
"return tabulate(inner_table, tablefmt=\"plain\") @property def _edge_info(self): inner_table = [[\"\", \"Index\", \"Energy\", \"P-ratio\", \"Occupation\",",
"-- band-edge states info\"] for spin, state in zip([\"up\", \"down\"], self.states): lines.append(f\"Spin-{spin}\") lines.append(state.__str__())",
"i in self.states]) @property def band_indices_from_vbm_to_cbm(self) -> List[int]: indices_set = set() for state",
"self.orbital_info.occupation @property def p_ratio(self): return self.orbital_info.participation_ratio @dataclass class PerfectBandEdgeState(MSONable, ToJsonFileMixIn): vbm_info: EdgeInfo cbm_info:",
"f\"{orb_info.energy :5.2f}\" occupation = f\"{orb_info.occupation:4.1f}\" p_ratio = f\"{orb_info.participation_ratio:4.1f}\" orbs = pretty_orbital(orb_info.orbitals) band_block.append([actual_band_idx, kpt_idx,",
"states info\"] for spin, state in zip([\"up\", \"down\"], self.states): lines.append(f\"Spin-{spin}\") lines.append(state.__str__()) lines.append(\"\") return",
"\"None\" inner = [lo.band_idx + 1, f\"{lo.ave_energy:7.3f}\", participation_ratio, f\"{lo.occupation:5.2f}\", pretty_orbital(lo.orbitals)] if w_radius: inner.extend([f\"{lo.radius:5.2f}\",",
"p, d, (f) orbital components. orbitals: Dict[str, List[float]] occupation: float participation_ratio: float =",
"orbital_info in self.orbital_infos: max_idx, min_idx, t_orb_info = self._band_idx_range(orbital_info) for band_idx in range(min_idx, max_idx):",
"EdgeInfo vbm_orbital_diff: float cbm_orbital_diff: float localized_orbitals: List[LocalizedOrbital] vbm_hole_occupation: float = None cbm_electron_occupation: float",
"if lo.participation_ratio else \"None\" inner = [lo.band_idx + 1, f\"{lo.ave_energy:7.3f}\", participation_ratio, f\"{lo.occupation:5.2f}\", pretty_orbital(lo.orbitals)]",
"i in self.states]) @property def has_acceptor_phs(self): return any([i.has_acceptor_phs for i in self.states]) @property",
"= np.array(orbital_info).T.tolist() middle_idx = int(len(t_orbital_info) / 2) for band_idx, (upper, lower) in enumerate(zip(t_orbital_info[1:],",
"\\ f\"({self.cbm_electron_occupation:5.3f} vs. {defaults.state_occupied_threshold})\" return \"\\n\".join([table, vbm_phs, cbm_phs]) @staticmethod def _show_edge_info(edge_info: EdgeInfo, orb_diff:",
"orbs in orbitals.items(): for orb_name, weight in zip([\"s\", \"p\", \"d\", \"f\"], orbs): if",
"result[i][j][k] = [z.energy, z.occupation] return result.tolist() def __str__(self): return \"\\n\".join([\" -- band-edge orbitals",
"pretty_coords(kpt_coord) weight = f\"{kpt_weight:4.3f}\" kpt_block.append([index, coord, weight]) return tabulate(kpt_block, tablefmt=\"plain\") @staticmethod def _band_idx_range(orbital_info:",
"-> Tuple[int, int, List[List[OrbitalInfo]]]: # swap [kpt_idx][band_idx] -> [bane_idx][kpt_idx] t_orbital_info = np.array(orbital_info).T.tolist() middle_idx",
"float cbm_orbital_diff: float localized_orbitals: List[LocalizedOrbital] vbm_hole_occupation: float = None cbm_electron_occupation: float = None",
"[edge_info.band_idx + 1, f\"{edge_info.energy:7.3f}\", f\"{edge_info.p_ratio:5.2f}\", f\"{edge_info.occupation:5.2f}\", f\"{orb_diff:5.2f}\", pretty_orbital(edge_info.orbital_info.orbitals), pretty_coords(edge_info.kpt_coord)] @dataclass class BandEdgeStates(MSONable, ToJsonFileMixIn):",
"def has_occupied_localized_state(self): return any([i.has_occupied_localized_state for i in self.states]) @property def band_indices_from_vbm_to_cbm(self) -> List[int]:",
"# by spin. @property def is_shallow(self): return any([i.is_shallow for i in self.states]) @property",
"return self.orbital_info.orbitals @property def energy(self): return self.orbital_info.energy @property def occupation(self): return self.orbital_info.occupation @property",
"@staticmethod def _show_edge_info(edge_info: EdgeInfo, orb_diff: float): return [edge_info.band_idx + 1, f\"{edge_info.energy:7.3f}\", f\"{edge_info.p_ratio:5.2f}\", f\"{edge_info.occupation:5.2f}\",",
"typing import List, Dict, Tuple, Optional, Set import numpy as np from monty.json",
"Optional[float] = None radius: Optional[float] = None center: Optional[GenCoords] = None @dataclass class",
"= f\"{kpt_weight:4.3f}\" kpt_block.append([index, coord, weight]) return tabulate(kpt_block, tablefmt=\"plain\") @staticmethod def _band_idx_range(orbital_info: List[List[OrbitalInfo]] )",
"- 3, 0) return max_idx, min_idx, t_orbital_info @dataclass class LocalizedOrbital(MSONable): band_idx: int ave_energy:",
"return [edge_info.band_idx, edge_info.energy, f\"{edge_info.occupation:5.2f}\", pretty_orbital(edge_info.orbital_info.orbitals), pretty_coords(edge_info.kpt_coord)] return tabulate([ [\"\", \"Index\", \"Energy\", \"Occupation\", \"Orbitals\",",
"occupation: float orbitals: Dict[str, List[float]] participation_ratio: Optional[float] = None radius: Optional[float] = None",
"self.vbm_hole_occupation > defaults.state_occupied_threshold @property def has_unoccupied_localized_state(self): return any([lo.occupation < defaults.state_unoccupied_threshold for lo in",
"[z.energy, z.occupation] return result.tolist() def __str__(self): return \"\\n\".join([\" -- band-edge orbitals info\", \"K-points",
"+ self.lowest_band_index + 1 for kpt_idx, orb_info in enumerate(t_orb_info[band_idx], 1): energy = f\"{orb_info.energy",
"GenCoords printed_orbital_weight_threshold = 0.1 @dataclass class BandEdgeEigenvalues(MSONable, ToJsonFileMixIn): # [spin, k-idx, band-idx] =",
"defaults.state_occupied_threshold for lo in self.localized_orbitals]) def __str__(self): return \"\\n\".join([self._edge_info, \"---\", \"Localized Orbital(s)\", self._orbital_info])",
"@dataclass class PerfectBandEdgeState(MSONable, ToJsonFileMixIn): vbm_info: EdgeInfo cbm_info: EdgeInfo def __str__(self): def show_edge_info(edge_info: EdgeInfo):",
"class BandEdgeOrbitalInfos(MSONable, ToJsonFileMixIn): orbital_infos: List[List[List[\"OrbitalInfo\"]]] # [spin, k-idx, band-idx] kpt_coords: List[Coords] kpt_weights: List[float]",
"f-orbital) :return: \"Mn-s: 0.50, Mn-p: 0.40\" \"\"\" orbital_infos = [] for elem, orbs",
"in self.localized_orbitals: participation_ratio = f\"{lo.participation_ratio:5.2f}\" \\ if lo.participation_ratio else \"None\" inner = [lo.band_idx",
"[bane_idx][kpt_idx] t_orbital_info = np.array(orbital_info).T.tolist() middle_idx = int(len(t_orbital_info) / 2) for band_idx, (upper, lower)",
"EdgeInfo(MSONable): band_idx: int kpt_coord: Coords orbital_info: \"OrbitalInfo\" @property def orbitals(self): return self.orbital_info.orbitals @property",
"@dataclass class EdgeInfo(MSONable): band_idx: int kpt_coord: Coords orbital_info: \"OrbitalInfo\" @property def orbitals(self): return",
"coords\"], [\"VBM\"] + self._show_edge_info( self.vbm_info, self.vbm_orbital_diff), [\"CBM\"] + self._show_edge_info( self.cbm_info, self.cbm_orbital_diff)] table =",
"self.states: indices_set.add(state.vbm_info.band_idx) for lo in state.localized_orbitals: indices_set.add(lo.band_idx) indices_set.add(state.cbm_info.band_idx) return sorted([i for i in",
"EdgeInfo): return [edge_info.band_idx, edge_info.energy, f\"{edge_info.occupation:5.2f}\", pretty_orbital(edge_info.orbital_info.orbitals), pretty_coords(edge_info.kpt_coord)] return tabulate([ [\"\", \"Index\", \"Energy\", \"Occupation\",",
"i in self.states]) @property def has_unoccupied_localized_state(self): return any([i.has_unoccupied_localized_state for i in self.states]) @property",
"band_block.append([actual_band_idx, kpt_idx, energy, occupation, p_ratio, orbs]) band_block.append([\"--\"]) band_block.append(\"\") return tabulate(band_block, tablefmt=\"plain\") @property def",
"middle_idx = int(len(t_orbital_info) / 2) for band_idx, (upper, lower) in enumerate(zip(t_orbital_info[1:], t_orbital_info[:-1])): #",
"center: Optional[GenCoords] = None @dataclass class EdgeInfo(MSONable): band_idx: int kpt_coord: Coords orbital_info: \"OrbitalInfo\"",
"pretty_orbital(edge_info.orbital_info.orbitals), pretty_coords(edge_info.kpt_coord)] @dataclass class BandEdgeStates(MSONable, ToJsonFileMixIn): states: List[BandEdgeState] # by spin. @property def",
"has_occupied_localized_state(self): return any([i.has_occupied_localized_state for i in self.states]) @property def band_indices_from_vbm_to_cbm(self) -> List[int]: indices_set",
"_band_idx_range(orbital_info: List[List[OrbitalInfo]] ) -> Tuple[int, int, List[List[OrbitalInfo]]]: # swap [kpt_idx][band_idx] -> [bane_idx][kpt_idx] t_orbital_info",
"List[int]: indices_set = set() for state in self.states: indices_set.add(state.vbm_info.band_idx) for lo in state.localized_orbitals:",
"List[Tuple[float, float, float]] lowest_band_index: int def pretty_orbital(orbitals: Dict[str, List[float]]): \"\"\" :param orbitals: An",
"determine the band_idx where the occupation changes largely. if lower[0].occupation - upper[0].occupation >",
"[] for elem, orbs in orbitals.items(): for orb_name, weight in zip([\"s\", \"p\", \"d\",",
"{defaults.state_occupied_threshold})\" cbm_phs = f\"cbm has donor phs: {self.has_donor_phs} \" \\ f\"({self.cbm_electron_occupation:5.3f} vs. {defaults.state_occupied_threshold})\"",
"tablefmt=\"plain\") @staticmethod def _band_idx_range(orbital_info: List[List[OrbitalInfo]] ) -> Tuple[int, int, List[List[OrbitalInfo]]]: # swap [kpt_idx][band_idx]",
"return any([i.has_unoccupied_localized_state for i in self.states]) @property def has_occupied_localized_state(self): return any([i.has_occupied_localized_state for i",
"def has_acceptor_phs(self): return any([i.has_acceptor_phs for i in self.states]) @property def has_unoccupied_localized_state(self): return any([i.has_unoccupied_localized_state",
"lo.participation_ratio else \"None\" inner = [lo.band_idx + 1, f\"{lo.ave_energy:7.3f}\", participation_ratio, f\"{lo.occupation:5.2f}\", pretty_orbital(lo.orbitals)] if",
"tablefmt=\"plain\") vbm_phs = f\"vbm has acceptor phs: {self.has_acceptor_phs} \" \\ f\"({self.vbm_hole_occupation:5.3f} vs. {defaults.state_occupied_threshold})\"",
"occupation: float participation_ratio: float = None @dataclass class BandEdgeOrbitalInfos(MSONable, ToJsonFileMixIn): orbital_infos: List[List[List[\"OrbitalInfo\"]]] #",
"def _band_block(self): band_block = [[\"Index\", \"Kpoint index\", \"Energy\", \"Occupation\", \"P-ratio\", \"Orbital\"]] for orbital_info",
"this is code and its version dependent quantities. \"\"\" energy: float # max",
"for i, orig_kpt in enumerate(self.kpt_coords): if sum(abs(k - l) for k, l in",
"zip(orig_kpt, kpt_coord)) < 1e-5: return i raise ValueError(f\"{kpt_coord} not in kpt_coords {self.kpt_coords}.\") @property",
"actual_band_idx = band_idx + self.lowest_band_index + 1 for kpt_idx, orb_info in enumerate(t_orb_info[band_idx], 1):",
"import numpy as np from monty.json import MSONable from pydefect.defaults import defaults from",
"self.localized_orbitals]) def __str__(self): return \"\\n\".join([self._edge_info, \"---\", \"Localized Orbital(s)\", self._orbital_info]) @property def _orbital_info(self): inner_table",
"\" \\ f\"({self.vbm_hole_occupation:5.3f} vs. {defaults.state_occupied_threshold})\" cbm_phs = f\"cbm has donor phs: {self.has_donor_phs} \"",
"t_orbital_info = np.array(orbital_info).T.tolist() middle_idx = int(len(t_orbital_info) / 2) for band_idx, (upper, lower) in",
"class OrbitalInfo(MSONable): \"\"\"Note that this is code and its version dependent quantities. \"\"\"",
"phs: {self.has_donor_phs} \" \\ f\"({self.cbm_electron_occupation:5.3f} vs. {defaults.state_occupied_threshold})\" return \"\\n\".join([table, vbm_phs, cbm_phs]) @staticmethod def",
"weight = f\"{kpt_weight:4.3f}\" kpt_block.append([index, coord, weight]) return tabulate(kpt_block, tablefmt=\"plain\") @staticmethod def _band_idx_range(orbital_info: List[List[OrbitalInfo]]",
"@dataclass class LocalizedOrbital(MSONable): band_idx: int ave_energy: float occupation: float orbitals: Dict[str, List[float]] participation_ratio:",
"middle_idx = band_idx + 1 break max_idx = min(middle_idx + 3, len(t_orbital_info)) min_idx",
"result.tolist() def __str__(self): return \"\\n\".join([\" -- band-edge orbitals info\", \"K-points info\", self._kpt_block, \"\",",
"return any([i.has_occupied_localized_state for i in self.states]) @property def band_indices_from_vbm_to_cbm(self) -> List[int]: indices_set =",
"__str__(self): return \"\\n\".join([\" -- band-edge orbitals info\", \"K-points info\", self._kpt_block, \"\", \"Band info",
"for elem, orbs in orbitals.items(): for orb_name, weight in zip([\"s\", \"p\", \"d\", \"f\"],",
"has_donor_phs(self): return self.cbm_electron_occupation > defaults.state_occupied_threshold @property def has_acceptor_phs(self): return self.vbm_hole_occupation > defaults.state_occupied_threshold @property",
"MIT License. from dataclasses import dataclass from typing import List, Dict, Tuple, Optional,",
"raise ValueError(f\"{kpt_coord} not in kpt_coords {self.kpt_coords}.\") @property def energies_and_occupations(self) -> List[List[List[List[float]]]]: result =",
"x in enumerate(self.orbital_infos): for j, y in enumerate(x): for k, z in enumerate(y):",
"@dataclass class OrbitalInfo(MSONable): \"\"\"Note that this is code and its version dependent quantities.",
"energy(self): return self.orbital_info.energy @property def occupation(self): return self.orbital_info.occupation @property def p_ratio(self): return self.orbital_info.participation_ratio",
"inner_table[0].extend([\"Radius\", \"Center\"]) for lo in self.localized_orbitals: participation_ratio = f\"{lo.participation_ratio:5.2f}\" \\ if lo.participation_ratio else",
"vbm_phs = f\"vbm has acceptor phs: {self.has_acceptor_phs} \" \\ f\"({self.vbm_hole_occupation:5.3f} vs. {defaults.state_occupied_threshold})\" cbm_phs",
"show_edge_info(self.vbm_info), [\"CBM\"] + show_edge_info(self.cbm_info)], tablefmt=\"plain\") @dataclass class BandEdgeState(MSONable): vbm_info: EdgeInfo cbm_info: EdgeInfo vbm_orbital_diff:",
"def has_occupied_localized_state(self): return any([lo.occupation > defaults.state_occupied_threshold for lo in self.localized_orbitals]) def __str__(self): return",
"An example is {\"Mn\": [0.5, 0.4, 0.01]} (no f-orbital) :return: \"Mn-s: 0.50, Mn-p:",
"states: List[BandEdgeState] # by spin. @property def is_shallow(self): return any([i.is_shallow for i in",
"band_block = [[\"Index\", \"Kpoint index\", \"Energy\", \"Occupation\", \"P-ratio\", \"Orbital\"]] for orbital_info in self.orbital_infos:",
"of the MIT License. from dataclasses import dataclass from typing import List, Dict,",
"= f\"{orb_info.occupation:4.1f}\" p_ratio = f\"{orb_info.participation_ratio:4.1f}\" orbs = pretty_orbital(orb_info.orbitals) band_block.append([actual_band_idx, kpt_idx, energy, occupation, p_ratio,",
"self.kpt_weights), 1): coord = pretty_coords(kpt_coord) weight = f\"{kpt_weight:4.3f}\" kpt_block.append([index, coord, weight]) return tabulate(kpt_block,",
"for index, (kpt_coord, kpt_weight) in enumerate( zip(self.kpt_coords, self.kpt_weights), 1): coord = pretty_coords(kpt_coord) weight",
"\"Occupation\", \"Orbitals\", \"K-point coords\"], [\"VBM\"] + show_edge_info(self.vbm_info), [\"CBM\"] + show_edge_info(self.cbm_info)], tablefmt=\"plain\") @dataclass class",
"Copyright (c) 2020. Distributed under the terms of the MIT License. from dataclasses",
"> printed_orbital_weight_threshold: orbital_infos.append(f\"{elem}-{orb_name}: {weight:.2f}\") return \", \".join(orbital_infos) @dataclass class OrbitalInfo(MSONable): \"\"\"Note that this",
"[\" -- band-edge states info\"] for spin, state in zip([\"up\", \"down\"], self.states): lines.append(f\"Spin-{spin}\")",
"j, y in enumerate(x): for k, z in enumerate(y): result[i][j][k] = [z.energy, z.occupation]",
"-> List[List[List[List[float]]]]: result = np.zeros(np.shape(self.orbital_infos) + (2,)) for i, x in enumerate(self.orbital_infos): for",
"0.4, 0.01]} (no f-orbital) :return: \"Mn-s: 0.50, Mn-p: 0.40\" \"\"\" orbital_infos = []",
"band-idx] = energy, occupation energies_and_occupations: List[List[List[List[float]]]] kpt_coords: List[Tuple[float, float, float]] lowest_band_index: int def",
"cbm_electron_occupation: float = None @property def is_shallow(self): return self.has_donor_phs or self.has_acceptor_phs @property def",
"info\"] for spin, state in zip([\"up\", \"down\"], self.states): lines.append(f\"Spin-{spin}\") lines.append(state.__str__()) lines.append(\"\") return \"\\n\".join(lines)",
"= max(middle_idx - 3, 0) return max_idx, min_idx, t_orbital_info @dataclass class LocalizedOrbital(MSONable): band_idx:",
"f\"{lo.ave_energy:7.3f}\", participation_ratio, f\"{lo.occupation:5.2f}\", pretty_orbital(lo.orbitals)] if w_radius: inner.extend([f\"{lo.radius:5.2f}\", pretty_coords(lo.center)]) inner_table.append(inner) return tabulate(inner_table, tablefmt=\"plain\") @property",
"\"Kpoint index\", \"Energy\", \"Occupation\", \"P-ratio\", \"Orbital\"]] for orbital_info in self.orbital_infos: max_idx, min_idx, t_orb_info",
"import MSONable from pydefect.defaults import defaults from pydefect.util.coords import pretty_coords from tabulate import",
"l) for k, l in zip(orig_kpt, kpt_coord)) < 1e-5: return i raise ValueError(f\"{kpt_coord}",
"def has_donor_phs(self): return self.cbm_electron_occupation > defaults.state_occupied_threshold @property def has_acceptor_phs(self): return self.vbm_hole_occupation > defaults.state_occupied_threshold",
"[[\"Index\", \"Coords\", \"Weight\"]] for index, (kpt_coord, kpt_weight) in enumerate( zip(self.kpt_coords, self.kpt_weights), 1): coord",
"# -*- coding: utf-8 -*- # Copyright (c) 2020. Distributed under the terms",
"for k, l in zip(orig_kpt, kpt_coord)) < 1e-5: return i raise ValueError(f\"{kpt_coord} not",
"kpt_coords: List[Tuple[float, float, float]] lowest_band_index: int def pretty_orbital(orbitals: Dict[str, List[float]]): \"\"\" :param orbitals:",
"in enumerate(self.kpt_coords): if sum(abs(k - l) for k, l in zip(orig_kpt, kpt_coord)) <",
"band_indices_from_vbm_to_cbm(self) -> List[int]: indices_set = set() for state in self.states: indices_set.add(state.vbm_info.band_idx) for lo",
"in kpt_coords {self.kpt_coords}.\") @property def energies_and_occupations(self) -> List[List[List[List[float]]]]: result = np.zeros(np.shape(self.orbital_infos) + (2,))",
"in enumerate(y): result[i][j][k] = [z.energy, z.occupation] return result.tolist() def __str__(self): return \"\\n\".join([\" --",
"@property def is_shallow(self): return self.has_donor_phs or self.has_acceptor_phs @property def has_donor_phs(self): return self.cbm_electron_occupation >",
"\\ if lo.participation_ratio else \"None\" inner = [lo.band_idx + 1, f\"{lo.ave_energy:7.3f}\", participation_ratio, f\"{lo.occupation:5.2f}\",",
"in self.orbital_infos: max_idx, min_idx, t_orb_info = self._band_idx_range(orbital_info) for band_idx in range(min_idx, max_idx): actual_band_idx",
"max_idx, min_idx, t_orbital_info @dataclass class LocalizedOrbital(MSONable): band_idx: int ave_energy: float occupation: float orbitals:",
"orig_kpt in enumerate(self.kpt_coords): if sum(abs(k - l) for k, l in zip(orig_kpt, kpt_coord))",
"for kpt_idx, orb_info in enumerate(t_orb_info[band_idx], 1): energy = f\"{orb_info.energy :5.2f}\" occupation = f\"{orb_info.occupation:4.1f}\"",
"def is_shallow(self): return any([i.is_shallow for i in self.states]) @property def has_donor_phs(self): return any([i.has_donor_phs",
"for lo in state.localized_orbitals: indices_set.add(lo.band_idx) indices_set.add(state.cbm_info.band_idx) return sorted([i for i in indices_set]) def",
"@property def has_acceptor_phs(self): return self.vbm_hole_occupation > defaults.state_occupied_threshold @property def has_unoccupied_localized_state(self): return any([lo.occupation <",
"orbitals: Dict[str, List[float]] participation_ratio: Optional[float] = None radius: Optional[float] = None center: Optional[GenCoords]",
"tablefmt=\"plain\") @property def _edge_info(self): inner_table = [[\"\", \"Index\", \"Energy\", \"P-ratio\", \"Occupation\", \"OrbDiff\", \"Orbitals\",",
"None radius: Optional[float] = None center: Optional[GenCoords] = None @dataclass class EdgeInfo(MSONable): band_idx:",
"is code and its version dependent quantities. \"\"\" energy: float # max eigenvalue",
"near band edges\", self._band_block]) @property def _band_block(self): band_block = [[\"Index\", \"Kpoint index\", \"Energy\",",
"List, Dict, Tuple, Optional, Set import numpy as np from monty.json import MSONable",
"for state in self.states: indices_set.add(state.vbm_info.band_idx) for lo in state.localized_orbitals: indices_set.add(lo.band_idx) indices_set.add(state.cbm_info.band_idx) return sorted([i",
"if sum(abs(k - l) for k, l in zip(orig_kpt, kpt_coord)) < 1e-5: return",
"1): coord = pretty_coords(kpt_coord) weight = f\"{kpt_weight:4.3f}\" kpt_block.append([index, coord, weight]) return tabulate(kpt_block, tablefmt=\"plain\")",
"+ show_edge_info(self.cbm_info)], tablefmt=\"plain\") @dataclass class BandEdgeState(MSONable): vbm_info: EdgeInfo cbm_info: EdgeInfo vbm_orbital_diff: float cbm_orbital_diff:",
"return \"\\n\".join([\" -- band-edge orbitals info\", \"K-points info\", self._kpt_block, \"\", \"Band info near",
"show_edge_info(edge_info: EdgeInfo): return [edge_info.band_idx, edge_info.energy, f\"{edge_info.occupation:5.2f}\", pretty_orbital(edge_info.orbital_info.orbitals), pretty_coords(edge_info.kpt_coord)] return tabulate([ [\"\", \"Index\", \"Energy\",",
"List[LocalizedOrbital] vbm_hole_occupation: float = None cbm_electron_occupation: float = None @property def is_shallow(self): return",
"band-edge orbitals info\", \"K-points info\", self._kpt_block, \"\", \"Band info near band edges\", self._band_block])",
"return sorted([i for i in indices_set]) def __str__(self): lines = [\" -- band-edge",
"tabulate(band_block, tablefmt=\"plain\") @property def _kpt_block(self): kpt_block = [[\"Index\", \"Coords\", \"Weight\"]] for index, (kpt_coord,",
"orbitals.items(): for orb_name, weight in zip([\"s\", \"p\", \"d\", \"f\"], orbs): if weight >",
"self.states]) @property def has_occupied_localized_state(self): return any([i.has_occupied_localized_state for i in self.states]) @property def band_indices_from_vbm_to_cbm(self)",
"for lo in self.localized_orbitals: participation_ratio = f\"{lo.participation_ratio:5.2f}\" \\ if lo.participation_ratio else \"None\" inner",
"- l) for k, l in zip(orig_kpt, kpt_coord)) < 1e-5: return i raise",
"ToJsonFileMixIn): orbital_infos: List[List[List[\"OrbitalInfo\"]]] # [spin, k-idx, band-idx] kpt_coords: List[Coords] kpt_weights: List[float] lowest_band_index: int",
"# [spin, k-idx, band-idx] = energy, occupation energies_and_occupations: List[List[List[List[float]]]] kpt_coords: List[Tuple[float, float, float]]",
"has_unoccupied_localized_state(self): return any([lo.occupation < defaults.state_unoccupied_threshold for lo in self.localized_orbitals]) @property def has_occupied_localized_state(self): return",
"in enumerate(x): for k, z in enumerate(y): result[i][j][k] = [z.energy, z.occupation] return result.tolist()",
"def has_donor_phs(self): return any([i.has_donor_phs for i in self.states]) @property def has_acceptor_phs(self): return any([i.has_acceptor_phs",
"float def kpt_idx(self, kpt_coord): for i, orig_kpt in enumerate(self.kpt_coords): if sum(abs(k - l)",
"ToJsonFileMixIn): vbm_info: EdgeInfo cbm_info: EdgeInfo def __str__(self): def show_edge_info(edge_info: EdgeInfo): return [edge_info.band_idx, edge_info.energy,",
"-- band-edge orbitals info\", \"K-points info\", self._kpt_block, \"\", \"Band info near band edges\",",
"3, 0) return max_idx, min_idx, t_orbital_info @dataclass class LocalizedOrbital(MSONable): band_idx: int ave_energy: float",
"in enumerate(zip(t_orbital_info[1:], t_orbital_info[:-1])): # determine the band_idx where the occupation changes largely. if",
"\"d\", \"f\"], orbs): if weight > printed_orbital_weight_threshold: orbital_infos.append(f\"{elem}-{orb_name}: {weight:.2f}\") return \", \".join(orbital_infos) @dataclass",
"f\"{kpt_weight:4.3f}\" kpt_block.append([index, coord, weight]) return tabulate(kpt_block, tablefmt=\"plain\") @staticmethod def _band_idx_range(orbital_info: List[List[OrbitalInfo]] ) ->",
"coord, weight]) return tabulate(kpt_block, tablefmt=\"plain\") @staticmethod def _band_idx_range(orbital_info: List[List[OrbitalInfo]] ) -> Tuple[int, int,",
"Set import numpy as np from monty.json import MSONable from pydefect.defaults import defaults",
"participation_ratio: Optional[float] = None radius: Optional[float] = None center: Optional[GenCoords] = None @dataclass",
"l in zip(orig_kpt, kpt_coord)) < 1e-5: return i raise ValueError(f\"{kpt_coord} not in kpt_coords",
"orbital_infos = [] for elem, orbs in orbitals.items(): for orb_name, weight in zip([\"s\",",
"weight]) return tabulate(kpt_block, tablefmt=\"plain\") @staticmethod def _band_idx_range(orbital_info: List[List[OrbitalInfo]] ) -> Tuple[int, int, List[List[OrbitalInfo]]]:",
"def __str__(self): lines = [\" -- band-edge states info\"] for spin, state in",
"float localized_orbitals: List[LocalizedOrbital] vbm_hole_occupation: float = None cbm_electron_occupation: float = None @property def",
"@property def has_unoccupied_localized_state(self): return any([i.has_unoccupied_localized_state for i in self.states]) @property def has_occupied_localized_state(self): return",
"@property def energies_and_occupations(self) -> List[List[List[List[float]]]]: result = np.zeros(np.shape(self.orbital_infos) + (2,)) for i, x",
"self.cbm_electron_occupation > defaults.state_occupied_threshold @property def has_acceptor_phs(self): return self.vbm_hole_occupation > defaults.state_occupied_threshold @property def has_unoccupied_localized_state(self):",
"in self.localized_orbitals]) def __str__(self): return \"\\n\".join([self._edge_info, \"---\", \"Localized Orbital(s)\", self._orbital_info]) @property def _orbital_info(self):",
"defaults.state_unoccupied_threshold for lo in self.localized_orbitals]) @property def has_occupied_localized_state(self): return any([lo.occupation > defaults.state_occupied_threshold for",
"max(middle_idx - 3, 0) return max_idx, min_idx, t_orbital_info @dataclass class LocalizedOrbital(MSONable): band_idx: int",
"return [edge_info.band_idx + 1, f\"{edge_info.energy:7.3f}\", f\"{edge_info.p_ratio:5.2f}\", f\"{edge_info.occupation:5.2f}\", f\"{orb_diff:5.2f}\", pretty_orbital(edge_info.orbital_info.orbitals), pretty_coords(edge_info.kpt_coord)] @dataclass class BandEdgeStates(MSONable,",
"band_idx, (upper, lower) in enumerate(zip(t_orbital_info[1:], t_orbital_info[:-1])): # determine the band_idx where the occupation",
"= np.zeros(np.shape(self.orbital_infos) + (2,)) for i, x in enumerate(self.orbital_infos): for j, y in",
"any([lo.occupation < defaults.state_unoccupied_threshold for lo in self.localized_orbitals]) @property def has_occupied_localized_state(self): return any([lo.occupation >",
"0.50, Mn-p: 0.40\" \"\"\" orbital_infos = [] for elem, orbs in orbitals.items(): for",
"def energies_and_occupations(self) -> List[List[List[List[float]]]]: result = np.zeros(np.shape(self.orbital_infos) + (2,)) for i, x in",
"PerfectBandEdgeState(MSONable, ToJsonFileMixIn): vbm_info: EdgeInfo cbm_info: EdgeInfo def __str__(self): def show_edge_info(edge_info: EdgeInfo): return [edge_info.band_idx,",
") -> Tuple[int, int, List[List[OrbitalInfo]]]: # swap [kpt_idx][band_idx] -> [bane_idx][kpt_idx] t_orbital_info = np.array(orbital_info).T.tolist()",
"= f\"{orb_info.energy :5.2f}\" occupation = f\"{orb_info.occupation:4.1f}\" p_ratio = f\"{orb_info.participation_ratio:4.1f}\" orbs = pretty_orbital(orb_info.orbitals) band_block.append([actual_band_idx,",
"self._band_block]) @property def _band_block(self): band_block = [[\"Index\", \"Kpoint index\", \"Energy\", \"Occupation\", \"P-ratio\", \"Orbital\"]]",
"return self.vbm_hole_occupation > defaults.state_occupied_threshold @property def has_unoccupied_localized_state(self): return any([lo.occupation < defaults.state_unoccupied_threshold for lo",
"if w_radius: inner_table[0].extend([\"Radius\", \"Center\"]) for lo in self.localized_orbitals: participation_ratio = f\"{lo.participation_ratio:5.2f}\" \\ if",
"(no f-orbital) :return: \"Mn-s: 0.50, Mn-p: 0.40\" \"\"\" orbital_infos = [] for elem,",
"self._kpt_block, \"\", \"Band info near band edges\", self._band_block]) @property def _band_block(self): band_block =",
"{defaults.state_occupied_threshold})\" return \"\\n\".join([table, vbm_phs, cbm_phs]) @staticmethod def _show_edge_info(edge_info: EdgeInfo, orb_diff: float): return [edge_info.band_idx",
"in enumerate( zip(self.kpt_coords, self.kpt_weights), 1): coord = pretty_coords(kpt_coord) weight = f\"{kpt_weight:4.3f}\" kpt_block.append([index, coord,",
"self.cbm_orbital_diff)] table = tabulate(inner_table, tablefmt=\"plain\") vbm_phs = f\"vbm has acceptor phs: {self.has_acceptor_phs} \"",
"donor phs: {self.has_donor_phs} \" \\ f\"({self.cbm_electron_occupation:5.3f} vs. {defaults.state_occupied_threshold})\" return \"\\n\".join([table, vbm_phs, cbm_phs]) @staticmethod",
"int fermi_level: float def kpt_idx(self, kpt_coord): for i, orig_kpt in enumerate(self.kpt_coords): if sum(abs(k",
"enumerate(self.orbital_infos): for j, y in enumerate(x): for k, z in enumerate(y): result[i][j][k] =",
"\"OrbDiff\", \"Orbitals\", \"K-point coords\"], [\"VBM\"] + self._show_edge_info( self.vbm_info, self.vbm_orbital_diff), [\"CBM\"] + self._show_edge_info( self.cbm_info,",
"[spin, k-idx, band-idx] kpt_coords: List[Coords] kpt_weights: List[float] lowest_band_index: int fermi_level: float def kpt_idx(self,",
"vbm_info: EdgeInfo cbm_info: EdgeInfo vbm_orbital_diff: float cbm_orbital_diff: float localized_orbitals: List[LocalizedOrbital] vbm_hole_occupation: float =",
"pretty_coords(edge_info.kpt_coord)] @dataclass class BandEdgeStates(MSONable, ToJsonFileMixIn): states: List[BandEdgeState] # by spin. @property def is_shallow(self):",
"min(middle_idx + 3, len(t_orbital_info)) min_idx = max(middle_idx - 3, 0) return max_idx, min_idx,",
"def pretty_orbital(orbitals: Dict[str, List[float]]): \"\"\" :param orbitals: An example is {\"Mn\": [0.5, 0.4,",
"List[float] lowest_band_index: int fermi_level: float def kpt_idx(self, kpt_coord): for i, orig_kpt in enumerate(self.kpt_coords):",
"(kpt_coord, kpt_weight) in enumerate( zip(self.kpt_coords, self.kpt_weights), 1): coord = pretty_coords(kpt_coord) weight = f\"{kpt_weight:4.3f}\"",
"for orb_name, weight in zip([\"s\", \"p\", \"d\", \"f\"], orbs): if weight > printed_orbital_weight_threshold:",
"info\", \"K-points info\", self._kpt_block, \"\", \"Band info near band edges\", self._band_block]) @property def",
"\"Orbital\"]] for orbital_info in self.orbital_infos: max_idx, min_idx, t_orb_info = self._band_idx_range(orbital_info) for band_idx in",
"kpt_coord: Coords orbital_info: \"OrbitalInfo\" @property def orbitals(self): return self.orbital_info.orbitals @property def energy(self): return",
"self.localized_orbitals]) @property def has_occupied_localized_state(self): return any([lo.occupation > defaults.state_occupied_threshold for lo in self.localized_orbitals]) def",
"return any([i.has_donor_phs for i in self.states]) @property def has_acceptor_phs(self): return any([i.has_acceptor_phs for i",
"f\"{orb_info.occupation:4.1f}\" p_ratio = f\"{orb_info.participation_ratio:4.1f}\" orbs = pretty_orbital(orb_info.orbitals) band_block.append([actual_band_idx, kpt_idx, energy, occupation, p_ratio, orbs])",
"self.cbm_info, self.cbm_orbital_diff)] table = tabulate(inner_table, tablefmt=\"plain\") vbm_phs = f\"vbm has acceptor phs: {self.has_acceptor_phs}",
"max_idx, min_idx, t_orb_info = self._band_idx_range(orbital_info) for band_idx in range(min_idx, max_idx): actual_band_idx = band_idx",
"None cbm_electron_occupation: float = None @property def is_shallow(self): return self.has_donor_phs or self.has_acceptor_phs @property",
"lo in self.localized_orbitals]) @property def has_occupied_localized_state(self): return any([lo.occupation > defaults.state_occupied_threshold for lo in",
"in zip(orig_kpt, kpt_coord)) < 1e-5: return i raise ValueError(f\"{kpt_coord} not in kpt_coords {self.kpt_coords}.\")",
"index, (kpt_coord, kpt_weight) in enumerate( zip(self.kpt_coords, self.kpt_weights), 1): coord = pretty_coords(kpt_coord) weight =",
"indices_set]) def __str__(self): lines = [\" -- band-edge states info\"] for spin, state",
"return self.orbital_info.participation_ratio @dataclass class PerfectBandEdgeState(MSONable, ToJsonFileMixIn): vbm_info: EdgeInfo cbm_info: EdgeInfo def __str__(self): def",
"cbm_info: EdgeInfo vbm_orbital_diff: float cbm_orbital_diff: float localized_orbitals: List[LocalizedOrbital] vbm_hole_occupation: float = None cbm_electron_occupation:",
"swap [kpt_idx][band_idx] -> [bane_idx][kpt_idx] t_orbital_info = np.array(orbital_info).T.tolist() middle_idx = int(len(t_orbital_info) / 2) for",
"self.orbital_info.orbitals @property def energy(self): return self.orbital_info.energy @property def occupation(self): return self.orbital_info.occupation @property def",
"in self.states]) @property def has_acceptor_phs(self): return any([i.has_acceptor_phs for i in self.states]) @property def",
"= [[\"\", \"Index\", \"Energy\", \"P-ratio\", \"Occupation\", \"OrbDiff\", \"Orbitals\", \"K-point coords\"], [\"VBM\"] + self._show_edge_info(",
"kpt_coord)) < 1e-5: return i raise ValueError(f\"{kpt_coord} not in kpt_coords {self.kpt_coords}.\") @property def",
"for i in self.states]) @property def has_occupied_localized_state(self): return any([i.has_occupied_localized_state for i in self.states])",
"kpt_block = [[\"Index\", \"Coords\", \"Weight\"]] for index, (kpt_coord, kpt_weight) in enumerate( zip(self.kpt_coords, self.kpt_weights),",
"def show_edge_info(edge_info: EdgeInfo): return [edge_info.band_idx, edge_info.energy, f\"{edge_info.occupation:5.2f}\", pretty_orbital(edge_info.orbital_info.orbitals), pretty_coords(edge_info.kpt_coord)] return tabulate([ [\"\", \"Index\",",
"0) return max_idx, min_idx, t_orbital_info @dataclass class LocalizedOrbital(MSONable): band_idx: int ave_energy: float occupation:",
"cbm_phs]) @staticmethod def _show_edge_info(edge_info: EdgeInfo, orb_diff: float): return [edge_info.band_idx + 1, f\"{edge_info.energy:7.3f}\", f\"{edge_info.p_ratio:5.2f}\",",
"\"\"\" :param orbitals: An example is {\"Mn\": [0.5, 0.4, 0.01]} (no f-orbital) :return:",
"OrbitalInfo(MSONable): \"\"\"Note that this is code and its version dependent quantities. \"\"\" energy:",
"\"Localized Orbital(s)\", self._orbital_info]) @property def _orbital_info(self): inner_table = [[\"Index\", \"Energy\", \"P-ratio\", \"Occupation\", \"Orbitals\"]]",
"import ToJsonFileMixIn from vise.util.typing import Coords, GenCoords printed_orbital_weight_threshold = 0.1 @dataclass class BandEdgeEigenvalues(MSONable,",
"sum(abs(k - l) for k, l in zip(orig_kpt, kpt_coord)) < 1e-5: return i",
"3, len(t_orbital_info)) min_idx = max(middle_idx - 3, 0) return max_idx, min_idx, t_orbital_info @dataclass",
"@dataclass class BandEdgeState(MSONable): vbm_info: EdgeInfo cbm_info: EdgeInfo vbm_orbital_diff: float cbm_orbital_diff: float localized_orbitals: List[LocalizedOrbital]",
"inner_table = [[\"Index\", \"Energy\", \"P-ratio\", \"Occupation\", \"Orbitals\"]] w_radius = self.localized_orbitals and self.localized_orbitals[0].radius if",
"k, l in zip(orig_kpt, kpt_coord)) < 1e-5: return i raise ValueError(f\"{kpt_coord} not in",
"< 1e-5: return i raise ValueError(f\"{kpt_coord} not in kpt_coords {self.kpt_coords}.\") @property def energies_and_occupations(self)",
"int ave_energy: float occupation: float orbitals: Dict[str, List[float]] participation_ratio: Optional[float] = None radius:",
"self.has_donor_phs or self.has_acceptor_phs @property def has_donor_phs(self): return self.cbm_electron_occupation > defaults.state_occupied_threshold @property def has_acceptor_phs(self):",
"+ 1, f\"{lo.ave_energy:7.3f}\", participation_ratio, f\"{lo.occupation:5.2f}\", pretty_orbital(lo.orbitals)] if w_radius: inner.extend([f\"{lo.radius:5.2f}\", pretty_coords(lo.center)]) inner_table.append(inner) return tabulate(inner_table,",
"cbm_phs = f\"cbm has donor phs: {self.has_donor_phs} \" \\ f\"({self.cbm_electron_occupation:5.3f} vs. {defaults.state_occupied_threshold})\" return",
"= pretty_coords(kpt_coord) weight = f\"{kpt_weight:4.3f}\" kpt_block.append([index, coord, weight]) return tabulate(kpt_block, tablefmt=\"plain\") @staticmethod def",
"has_acceptor_phs(self): return any([i.has_acceptor_phs for i in self.states]) @property def has_unoccupied_localized_state(self): return any([i.has_unoccupied_localized_state for",
"float participation_ratio: float = None @dataclass class BandEdgeOrbitalInfos(MSONable, ToJsonFileMixIn): orbital_infos: List[List[List[\"OrbitalInfo\"]]] # [spin,",
"kpt_block.append([index, coord, weight]) return tabulate(kpt_block, tablefmt=\"plain\") @staticmethod def _band_idx_range(orbital_info: List[List[OrbitalInfo]] ) -> Tuple[int,",
"kpt_idx, energy, occupation, p_ratio, orbs]) band_block.append([\"--\"]) band_block.append(\"\") return tabulate(band_block, tablefmt=\"plain\") @property def _kpt_block(self):",
"for i in indices_set]) def __str__(self): lines = [\" -- band-edge states info\"]",
"@property def has_donor_phs(self): return self.cbm_electron_occupation > defaults.state_occupied_threshold @property def has_acceptor_phs(self): return self.vbm_hole_occupation >",
"import Coords, GenCoords printed_orbital_weight_threshold = 0.1 @dataclass class BandEdgeEigenvalues(MSONable, ToJsonFileMixIn): # [spin, k-idx,",
"0.01]} (no f-orbital) :return: \"Mn-s: 0.50, Mn-p: 0.40\" \"\"\" orbital_infos = [] for",
"List[List[List[List[float]]]] kpt_coords: List[Tuple[float, float, float]] lowest_band_index: int def pretty_orbital(orbitals: Dict[str, List[float]]): \"\"\" :param",
"float): return [edge_info.band_idx + 1, f\"{edge_info.energy:7.3f}\", f\"{edge_info.p_ratio:5.2f}\", f\"{edge_info.occupation:5.2f}\", f\"{orb_diff:5.2f}\", pretty_orbital(edge_info.orbital_info.orbitals), pretty_coords(edge_info.kpt_coord)] @dataclass class",
":param orbitals: An example is {\"Mn\": [0.5, 0.4, 0.01]} (no f-orbital) :return: \"Mn-s:",
"= self._band_idx_range(orbital_info) for band_idx in range(min_idx, max_idx): actual_band_idx = band_idx + self.lowest_band_index +",
"for band_idx, (upper, lower) in enumerate(zip(t_orbital_info[1:], t_orbital_info[:-1])): # determine the band_idx where the",
"class BandEdgeState(MSONable): vbm_info: EdgeInfo cbm_info: EdgeInfo vbm_orbital_diff: float cbm_orbital_diff: float localized_orbitals: List[LocalizedOrbital] vbm_hole_occupation:",
"[\"CBM\"] + show_edge_info(self.cbm_info)], tablefmt=\"plain\") @dataclass class BandEdgeState(MSONable): vbm_info: EdgeInfo cbm_info: EdgeInfo vbm_orbital_diff: float",
"= tabulate(inner_table, tablefmt=\"plain\") vbm_phs = f\"vbm has acceptor phs: {self.has_acceptor_phs} \" \\ f\"({self.vbm_hole_occupation:5.3f}",
"any([i.has_acceptor_phs for i in self.states]) @property def has_unoccupied_localized_state(self): return any([i.has_unoccupied_localized_state for i in",
"return \"\\n\".join([self._edge_info, \"---\", \"Localized Orbital(s)\", self._orbital_info]) @property def _orbital_info(self): inner_table = [[\"Index\", \"Energy\",",
"phs: {self.has_acceptor_phs} \" \\ f\"({self.vbm_hole_occupation:5.3f} vs. {defaults.state_occupied_threshold})\" cbm_phs = f\"cbm has donor phs:",
"state in self.states: indices_set.add(state.vbm_info.band_idx) for lo in state.localized_orbitals: indices_set.add(lo.band_idx) indices_set.add(state.cbm_info.band_idx) return sorted([i for",
"largely. if lower[0].occupation - upper[0].occupation > 0.1: middle_idx = band_idx + 1 break",
"= min(middle_idx + 3, len(t_orbital_info)) min_idx = max(middle_idx - 3, 0) return max_idx,",
"\"Mn-s: 0.50, Mn-p: 0.40\" \"\"\" orbital_infos = [] for elem, orbs in orbitals.items():",
"= f\"{lo.participation_ratio:5.2f}\" \\ if lo.participation_ratio else \"None\" inner = [lo.band_idx + 1, f\"{lo.ave_energy:7.3f}\",",
"\", \".join(orbital_infos) @dataclass class OrbitalInfo(MSONable): \"\"\"Note that this is code and its version",
"occupation changes largely. if lower[0].occupation - upper[0].occupation > 0.1: middle_idx = band_idx +",
"p_ratio(self): return self.orbital_info.participation_ratio @dataclass class PerfectBandEdgeState(MSONable, ToJsonFileMixIn): vbm_info: EdgeInfo cbm_info: EdgeInfo def __str__(self):",
"@property def has_acceptor_phs(self): return any([i.has_acceptor_phs for i in self.states]) @property def has_unoccupied_localized_state(self): return",
"energies_and_occupations: List[List[List[List[float]]]] kpt_coords: List[Tuple[float, float, float]] lowest_band_index: int def pretty_orbital(orbitals: Dict[str, List[float]]): \"\"\"",
"any([i.has_unoccupied_localized_state for i in self.states]) @property def has_occupied_localized_state(self): return any([i.has_occupied_localized_state for i in",
"Tuple, Optional, Set import numpy as np from monty.json import MSONable from pydefect.defaults",
"Optional[GenCoords] = None @dataclass class EdgeInfo(MSONable): band_idx: int kpt_coord: Coords orbital_info: \"OrbitalInfo\" @property",
"_edge_info(self): inner_table = [[\"\", \"Index\", \"Energy\", \"P-ratio\", \"Occupation\", \"OrbDiff\", \"Orbitals\", \"K-point coords\"], [\"VBM\"]",
"defaults.state_occupied_threshold @property def has_unoccupied_localized_state(self): return any([lo.occupation < defaults.state_unoccupied_threshold for lo in self.localized_orbitals]) @property",
"enumerate(y): result[i][j][k] = [z.energy, z.occupation] return result.tolist() def __str__(self): return \"\\n\".join([\" -- band-edge",
"d, (f) orbital components. orbitals: Dict[str, List[float]] occupation: float participation_ratio: float = None",
"y in enumerate(x): for k, z in enumerate(y): result[i][j][k] = [z.energy, z.occupation] return",
"numpy as np from monty.json import MSONable from pydefect.defaults import defaults from pydefect.util.coords",
"= band_idx + self.lowest_band_index + 1 for kpt_idx, orb_info in enumerate(t_orb_info[band_idx], 1): energy",
"dataclass from typing import List, Dict, Tuple, Optional, Set import numpy as np",
"\"Orbitals\"]] w_radius = self.localized_orbitals and self.localized_orbitals[0].radius if w_radius: inner_table[0].extend([\"Radius\", \"Center\"]) for lo in",
"f\"cbm has donor phs: {self.has_donor_phs} \" \\ f\"({self.cbm_electron_occupation:5.3f} vs. {defaults.state_occupied_threshold})\" return \"\\n\".join([table, vbm_phs,",
"break max_idx = min(middle_idx + 3, len(t_orbital_info)) min_idx = max(middle_idx - 3, 0)",
"@property def has_occupied_localized_state(self): return any([lo.occupation > defaults.state_occupied_threshold for lo in self.localized_orbitals]) def __str__(self):",
"1, f\"{lo.ave_energy:7.3f}\", participation_ratio, f\"{lo.occupation:5.2f}\", pretty_orbital(lo.orbitals)] if w_radius: inner.extend([f\"{lo.radius:5.2f}\", pretty_coords(lo.center)]) inner_table.append(inner) return tabulate(inner_table, tablefmt=\"plain\")",
"the terms of the MIT License. from dataclasses import dataclass from typing import",
"lowest_band_index: int fermi_level: float def kpt_idx(self, kpt_coord): for i, orig_kpt in enumerate(self.kpt_coords): if",
"i in self.states]) @property def has_occupied_localized_state(self): return any([i.has_occupied_localized_state for i in self.states]) @property",
"np.zeros(np.shape(self.orbital_infos) + (2,)) for i, x in enumerate(self.orbital_infos): for j, y in enumerate(x):",
"f\"{lo.occupation:5.2f}\", pretty_orbital(lo.orbitals)] if w_radius: inner.extend([f\"{lo.radius:5.2f}\", pretty_coords(lo.center)]) inner_table.append(inner) return tabulate(inner_table, tablefmt=\"plain\") @property def _edge_info(self):",
"f\"{edge_info.occupation:5.2f}\", f\"{orb_diff:5.2f}\", pretty_orbital(edge_info.orbital_info.orbitals), pretty_coords(edge_info.kpt_coord)] @dataclass class BandEdgeStates(MSONable, ToJsonFileMixIn): states: List[BandEdgeState] # by spin.",
"class EdgeInfo(MSONable): band_idx: int kpt_coord: Coords orbital_info: \"OrbitalInfo\" @property def orbitals(self): return self.orbital_info.orbitals",
"from vise.util.mix_in import ToJsonFileMixIn from vise.util.typing import Coords, GenCoords printed_orbital_weight_threshold = 0.1 @dataclass",
"for band_idx in range(min_idx, max_idx): actual_band_idx = band_idx + self.lowest_band_index + 1 for",
"orbs]) band_block.append([\"--\"]) band_block.append(\"\") return tabulate(band_block, tablefmt=\"plain\") @property def _kpt_block(self): kpt_block = [[\"Index\", \"Coords\",",
"pretty_coords(lo.center)]) inner_table.append(inner) return tabulate(inner_table, tablefmt=\"plain\") @property def _edge_info(self): inner_table = [[\"\", \"Index\", \"Energy\",",
"pretty_orbital(edge_info.orbital_info.orbitals), pretty_coords(edge_info.kpt_coord)] return tabulate([ [\"\", \"Index\", \"Energy\", \"Occupation\", \"Orbitals\", \"K-point coords\"], [\"VBM\"] +",
"is_shallow(self): return any([i.is_shallow for i in self.states]) @property def has_donor_phs(self): return any([i.has_donor_phs for",
"kpt_coords {self.kpt_coords}.\") @property def energies_and_occupations(self) -> List[List[List[List[float]]]]: result = np.zeros(np.shape(self.orbital_infos) + (2,)) for",
"f\"{orb_diff:5.2f}\", pretty_orbital(edge_info.orbital_info.orbitals), pretty_coords(edge_info.kpt_coord)] @dataclass class BandEdgeStates(MSONable, ToJsonFileMixIn): states: List[BandEdgeState] # by spin. @property",
"in self.states]) @property def band_indices_from_vbm_to_cbm(self) -> List[int]: indices_set = set() for state in",
"= pretty_orbital(orb_info.orbitals) band_block.append([actual_band_idx, kpt_idx, energy, occupation, p_ratio, orbs]) band_block.append([\"--\"]) band_block.append(\"\") return tabulate(band_block, tablefmt=\"plain\")",
"and its version dependent quantities. \"\"\" energy: float # max eigenvalue # {\"Mn\":",
"\\ f\"({self.vbm_hole_occupation:5.3f} vs. {defaults.state_occupied_threshold})\" cbm_phs = f\"cbm has donor phs: {self.has_donor_phs} \" \\",
"tabulate(inner_table, tablefmt=\"plain\") vbm_phs = f\"vbm has acceptor phs: {self.has_acceptor_phs} \" \\ f\"({self.vbm_hole_occupation:5.3f} vs.",
"return self.orbital_info.energy @property def occupation(self): return self.orbital_info.occupation @property def p_ratio(self): return self.orbital_info.participation_ratio @dataclass",
"= [] for elem, orbs in orbitals.items(): for orb_name, weight in zip([\"s\", \"p\",",
"info\", self._kpt_block, \"\", \"Band info near band edges\", self._band_block]) @property def _band_block(self): band_block",
"= [lo.band_idx + 1, f\"{lo.ave_energy:7.3f}\", participation_ratio, f\"{lo.occupation:5.2f}\", pretty_orbital(lo.orbitals)] if w_radius: inner.extend([f\"{lo.radius:5.2f}\", pretty_coords(lo.center)]) inner_table.append(inner)",
"-> [bane_idx][kpt_idx] t_orbital_info = np.array(orbital_info).T.tolist() middle_idx = int(len(t_orbital_info) / 2) for band_idx, (upper,",
"Dict, Tuple, Optional, Set import numpy as np from monty.json import MSONable from",
"return any([i.is_shallow for i in self.states]) @property def has_donor_phs(self): return any([i.has_donor_phs for i",
"BandEdgeStates(MSONable, ToJsonFileMixIn): states: List[BandEdgeState] # by spin. @property def is_shallow(self): return any([i.is_shallow for",
"k-idx, band-idx] = energy, occupation energies_and_occupations: List[List[List[List[float]]]] kpt_coords: List[Tuple[float, float, float]] lowest_band_index: int",
"lowest_band_index: int def pretty_orbital(orbitals: Dict[str, List[float]]): \"\"\" :param orbitals: An example is {\"Mn\":",
"ValueError(f\"{kpt_coord} not in kpt_coords {self.kpt_coords}.\") @property def energies_and_occupations(self) -> List[List[List[List[float]]]]: result = np.zeros(np.shape(self.orbital_infos)",
"self._show_edge_info( self.vbm_info, self.vbm_orbital_diff), [\"CBM\"] + self._show_edge_info( self.cbm_info, self.cbm_orbital_diff)] table = tabulate(inner_table, tablefmt=\"plain\") vbm_phs",
"def band_indices_from_vbm_to_cbm(self) -> List[int]: indices_set = set() for state in self.states: indices_set.add(state.vbm_info.band_idx) for",
"self._show_edge_info( self.cbm_info, self.cbm_orbital_diff)] table = tabulate(inner_table, tablefmt=\"plain\") vbm_phs = f\"vbm has acceptor phs:",
"for i, x in enumerate(self.orbital_infos): for j, y in enumerate(x): for k, z",
"= f\"{orb_info.participation_ratio:4.1f}\" orbs = pretty_orbital(orb_info.orbitals) band_block.append([actual_band_idx, kpt_idx, energy, occupation, p_ratio, orbs]) band_block.append([\"--\"]) band_block.append(\"\")",
"self.orbital_info.participation_ratio @dataclass class PerfectBandEdgeState(MSONable, ToJsonFileMixIn): vbm_info: EdgeInfo cbm_info: EdgeInfo def __str__(self): def show_edge_info(edge_info:",
"def p_ratio(self): return self.orbital_info.participation_ratio @dataclass class PerfectBandEdgeState(MSONable, ToJsonFileMixIn): vbm_info: EdgeInfo cbm_info: EdgeInfo def",
"\"Index\", \"Energy\", \"Occupation\", \"Orbitals\", \"K-point coords\"], [\"VBM\"] + show_edge_info(self.vbm_info), [\"CBM\"] + show_edge_info(self.cbm_info)], tablefmt=\"plain\")",
"localized_orbitals: List[LocalizedOrbital] vbm_hole_occupation: float = None cbm_electron_occupation: float = None @property def is_shallow(self):",
"\"---\", \"Localized Orbital(s)\", self._orbital_info]) @property def _orbital_info(self): inner_table = [[\"Index\", \"Energy\", \"P-ratio\", \"Occupation\",",
"Optional, Set import numpy as np from monty.json import MSONable from pydefect.defaults import",
"show_edge_info(self.cbm_info)], tablefmt=\"plain\") @dataclass class BandEdgeState(MSONable): vbm_info: EdgeInfo cbm_info: EdgeInfo vbm_orbital_diff: float cbm_orbital_diff: float",
"= [\" -- band-edge states info\"] for spin, state in zip([\"up\", \"down\"], self.states):",
"# Copyright (c) 2020. Distributed under the terms of the MIT License. from",
"dataclasses import dataclass from typing import List, Dict, Tuple, Optional, Set import numpy",
"weight in zip([\"s\", \"p\", \"d\", \"f\"], orbs): if weight > printed_orbital_weight_threshold: orbital_infos.append(f\"{elem}-{orb_name}: {weight:.2f}\")",
"has_acceptor_phs(self): return self.vbm_hole_occupation > defaults.state_occupied_threshold @property def has_unoccupied_localized_state(self): return any([lo.occupation < defaults.state_unoccupied_threshold for",
"Tuple[int, int, List[List[OrbitalInfo]]]: # swap [kpt_idx][band_idx] -> [bane_idx][kpt_idx] t_orbital_info = np.array(orbital_info).T.tolist() middle_idx =",
"\"\"\" energy: float # max eigenvalue # {\"Mn\": [0.01, ..], \"O\": [0.03, 0.5]},",
"0.1: middle_idx = band_idx + 1 break max_idx = min(middle_idx + 3, len(t_orbital_info))",
"self.states]) @property def has_donor_phs(self): return any([i.has_donor_phs for i in self.states]) @property def has_acceptor_phs(self):",
"def energy(self): return self.orbital_info.energy @property def occupation(self): return self.orbital_info.occupation @property def p_ratio(self): return",
"\"Center\"]) for lo in self.localized_orbitals: participation_ratio = f\"{lo.participation_ratio:5.2f}\" \\ if lo.participation_ratio else \"None\"",
"@property def occupation(self): return self.orbital_info.occupation @property def p_ratio(self): return self.orbital_info.participation_ratio @dataclass class PerfectBandEdgeState(MSONable,",
"for lo in self.localized_orbitals]) @property def has_occupied_localized_state(self): return any([lo.occupation > defaults.state_occupied_threshold for lo",
"List[float]]): \"\"\" :param orbitals: An example is {\"Mn\": [0.5, 0.4, 0.01]} (no f-orbital)",
"self.states]) @property def band_indices_from_vbm_to_cbm(self) -> List[int]: indices_set = set() for state in self.states:",
"{weight:.2f}\") return \", \".join(orbital_infos) @dataclass class OrbitalInfo(MSONable): \"\"\"Note that this is code and",
"(f) orbital components. orbitals: Dict[str, List[float]] occupation: float participation_ratio: float = None @dataclass",
"..], \"O\": [0.03, 0.5]}, # where lists contain s, p, d, (f) orbital",
"band_block.append([\"--\"]) band_block.append(\"\") return tabulate(band_block, tablefmt=\"plain\") @property def _kpt_block(self): kpt_block = [[\"Index\", \"Coords\", \"Weight\"]]",
"None @property def is_shallow(self): return self.has_donor_phs or self.has_acceptor_phs @property def has_donor_phs(self): return self.cbm_electron_occupation",
"float # max eigenvalue # {\"Mn\": [0.01, ..], \"O\": [0.03, 0.5]}, # where",
"1 for kpt_idx, orb_info in enumerate(t_orb_info[band_idx], 1): energy = f\"{orb_info.energy :5.2f}\" occupation =",
"[[\"Index\", \"Energy\", \"P-ratio\", \"Occupation\", \"Orbitals\"]] w_radius = self.localized_orbitals and self.localized_orbitals[0].radius if w_radius: inner_table[0].extend([\"Radius\",",
"zip(self.kpt_coords, self.kpt_weights), 1): coord = pretty_coords(kpt_coord) weight = f\"{kpt_weight:4.3f}\" kpt_block.append([index, coord, weight]) return",
"i raise ValueError(f\"{kpt_coord} not in kpt_coords {self.kpt_coords}.\") @property def energies_and_occupations(self) -> List[List[List[List[float]]]]: result",
"(c) 2020. Distributed under the terms of the MIT License. from dataclasses import",
"z.occupation] return result.tolist() def __str__(self): return \"\\n\".join([\" -- band-edge orbitals info\", \"K-points info\",",
"zip([\"s\", \"p\", \"d\", \"f\"], orbs): if weight > printed_orbital_weight_threshold: orbital_infos.append(f\"{elem}-{orb_name}: {weight:.2f}\") return \",",
"def has_acceptor_phs(self): return self.vbm_hole_occupation > defaults.state_occupied_threshold @property def has_unoccupied_localized_state(self): return any([lo.occupation < defaults.state_unoccupied_threshold",
"in indices_set]) def __str__(self): lines = [\" -- band-edge states info\"] for spin,",
"elem, orbs in orbitals.items(): for orb_name, weight in zip([\"s\", \"p\", \"d\", \"f\"], orbs):",
"@property def _band_block(self): band_block = [[\"Index\", \"Kpoint index\", \"Energy\", \"Occupation\", \"P-ratio\", \"Orbital\"]] for",
"p_ratio, orbs]) band_block.append([\"--\"]) band_block.append(\"\") return tabulate(band_block, tablefmt=\"plain\") @property def _kpt_block(self): kpt_block = [[\"Index\",",
"LocalizedOrbital(MSONable): band_idx: int ave_energy: float occupation: float orbitals: Dict[str, List[float]] participation_ratio: Optional[float] =",
"[lo.band_idx + 1, f\"{lo.ave_energy:7.3f}\", participation_ratio, f\"{lo.occupation:5.2f}\", pretty_orbital(lo.orbitals)] if w_radius: inner.extend([f\"{lo.radius:5.2f}\", pretty_coords(lo.center)]) inner_table.append(inner) return",
"# [spin, k-idx, band-idx] kpt_coords: List[Coords] kpt_weights: List[float] lowest_band_index: int fermi_level: float def",
"w_radius: inner.extend([f\"{lo.radius:5.2f}\", pretty_coords(lo.center)]) inner_table.append(inner) return tabulate(inner_table, tablefmt=\"plain\") @property def _edge_info(self): inner_table = [[\"\",",
"in self.states]) @property def has_occupied_localized_state(self): return any([i.has_occupied_localized_state for i in self.states]) @property def",
"Dict[str, List[float]] occupation: float participation_ratio: float = None @dataclass class BandEdgeOrbitalInfos(MSONable, ToJsonFileMixIn): orbital_infos:",
"[0.5, 0.4, 0.01]} (no f-orbital) :return: \"Mn-s: 0.50, Mn-p: 0.40\" \"\"\" orbital_infos =",
"result = np.zeros(np.shape(self.orbital_infos) + (2,)) for i, x in enumerate(self.orbital_infos): for j, y",
"/ 2) for band_idx, (upper, lower) in enumerate(zip(t_orbital_info[1:], t_orbital_info[:-1])): # determine the band_idx",
"in self.localized_orbitals]) @property def has_occupied_localized_state(self): return any([lo.occupation > defaults.state_occupied_threshold for lo in self.localized_orbitals])",
"[[\"\", \"Index\", \"Energy\", \"P-ratio\", \"Occupation\", \"OrbDiff\", \"Orbitals\", \"K-point coords\"], [\"VBM\"] + self._show_edge_info( self.vbm_info,",
"band_block.append(\"\") return tabulate(band_block, tablefmt=\"plain\") @property def _kpt_block(self): kpt_block = [[\"Index\", \"Coords\", \"Weight\"]] for",
"self.states]) @property def has_unoccupied_localized_state(self): return any([i.has_unoccupied_localized_state for i in self.states]) @property def has_occupied_localized_state(self):",
"def has_unoccupied_localized_state(self): return any([i.has_unoccupied_localized_state for i in self.states]) @property def has_occupied_localized_state(self): return any([i.has_occupied_localized_state",
"@property def p_ratio(self): return self.orbital_info.participation_ratio @dataclass class PerfectBandEdgeState(MSONable, ToJsonFileMixIn): vbm_info: EdgeInfo cbm_info: EdgeInfo",
"@property def _kpt_block(self): kpt_block = [[\"Index\", \"Coords\", \"Weight\"]] for index, (kpt_coord, kpt_weight) in",
"def __str__(self): return \"\\n\".join([self._edge_info, \"---\", \"Localized Orbital(s)\", self._orbital_info]) @property def _orbital_info(self): inner_table =",
"\"\"\"Note that this is code and its version dependent quantities. \"\"\" energy: float",
"kpt_idx, orb_info in enumerate(t_orb_info[band_idx], 1): energy = f\"{orb_info.energy :5.2f}\" occupation = f\"{orb_info.occupation:4.1f}\" p_ratio",
"band_idx in range(min_idx, max_idx): actual_band_idx = band_idx + self.lowest_band_index + 1 for kpt_idx,",
"> 0.1: middle_idx = band_idx + 1 break max_idx = min(middle_idx + 3,",
"enumerate(zip(t_orbital_info[1:], t_orbital_info[:-1])): # determine the band_idx where the occupation changes largely. if lower[0].occupation",
"return tabulate(band_block, tablefmt=\"plain\") @property def _kpt_block(self): kpt_block = [[\"Index\", \"Coords\", \"Weight\"]] for index,",
"min_idx = max(middle_idx - 3, 0) return max_idx, min_idx, t_orbital_info @dataclass class LocalizedOrbital(MSONable):",
"@dataclass class BandEdgeStates(MSONable, ToJsonFileMixIn): states: List[BandEdgeState] # by spin. @property def is_shallow(self): return",
"__str__(self): return \"\\n\".join([self._edge_info, \"---\", \"Localized Orbital(s)\", self._orbital_info]) @property def _orbital_info(self): inner_table = [[\"Index\",",
"in orbitals.items(): for orb_name, weight in zip([\"s\", \"p\", \"d\", \"f\"], orbs): if weight",
"self.localized_orbitals: participation_ratio = f\"{lo.participation_ratio:5.2f}\" \\ if lo.participation_ratio else \"None\" inner = [lo.band_idx +",
"return self.has_donor_phs or self.has_acceptor_phs @property def has_donor_phs(self): return self.cbm_electron_occupation > defaults.state_occupied_threshold @property def",
"MSONable from pydefect.defaults import defaults from pydefect.util.coords import pretty_coords from tabulate import tabulate",
"self.states]) @property def has_acceptor_phs(self): return any([i.has_acceptor_phs for i in self.states]) @property def has_unoccupied_localized_state(self):",
"_show_edge_info(edge_info: EdgeInfo, orb_diff: float): return [edge_info.band_idx + 1, f\"{edge_info.energy:7.3f}\", f\"{edge_info.p_ratio:5.2f}\", f\"{edge_info.occupation:5.2f}\", f\"{orb_diff:5.2f}\", pretty_orbital(edge_info.orbital_info.orbitals),",
"pydefect.defaults import defaults from pydefect.util.coords import pretty_coords from tabulate import tabulate from vise.util.mix_in",
"monty.json import MSONable from pydefect.defaults import defaults from pydefect.util.coords import pretty_coords from tabulate",
"\".join(orbital_infos) @dataclass class OrbitalInfo(MSONable): \"\"\"Note that this is code and its version dependent",
"has_occupied_localized_state(self): return any([lo.occupation > defaults.state_occupied_threshold for lo in self.localized_orbitals]) def __str__(self): return \"\\n\".join([self._edge_info,",
"where the occupation changes largely. if lower[0].occupation - upper[0].occupation > 0.1: middle_idx =",
"enumerate( zip(self.kpt_coords, self.kpt_weights), 1): coord = pretty_coords(kpt_coord) weight = f\"{kpt_weight:4.3f}\" kpt_block.append([index, coord, weight])",
"the MIT License. from dataclasses import dataclass from typing import List, Dict, Tuple,",
"= [[\"Index\", \"Energy\", \"P-ratio\", \"Occupation\", \"Orbitals\"]] w_radius = self.localized_orbitals and self.localized_orbitals[0].radius if w_radius:",
"i in indices_set]) def __str__(self): lines = [\" -- band-edge states info\"] for",
"that this is code and its version dependent quantities. \"\"\" energy: float #",
"+ self._show_edge_info( self.cbm_info, self.cbm_orbital_diff)] table = tabulate(inner_table, tablefmt=\"plain\") vbm_phs = f\"vbm has acceptor",
"vbm_orbital_diff: float cbm_orbital_diff: float localized_orbitals: List[LocalizedOrbital] vbm_hole_occupation: float = None cbm_electron_occupation: float =",
"_orbital_info(self): inner_table = [[\"Index\", \"Energy\", \"P-ratio\", \"Occupation\", \"Orbitals\"]] w_radius = self.localized_orbitals and self.localized_orbitals[0].radius",
"tabulate(inner_table, tablefmt=\"plain\") @property def _edge_info(self): inner_table = [[\"\", \"Index\", \"Energy\", \"P-ratio\", \"Occupation\", \"OrbDiff\",",
"by spin. @property def is_shallow(self): return any([i.is_shallow for i in self.states]) @property def",
"= f\"vbm has acceptor phs: {self.has_acceptor_phs} \" \\ f\"({self.vbm_hole_occupation:5.3f} vs. {defaults.state_occupied_threshold})\" cbm_phs =",
"return tabulate(kpt_block, tablefmt=\"plain\") @staticmethod def _band_idx_range(orbital_info: List[List[OrbitalInfo]] ) -> Tuple[int, int, List[List[OrbitalInfo]]]: #",
"\"K-points info\", self._kpt_block, \"\", \"Band info near band edges\", self._band_block]) @property def _band_block(self):",
"in enumerate(t_orb_info[band_idx], 1): energy = f\"{orb_info.energy :5.2f}\" occupation = f\"{orb_info.occupation:4.1f}\" p_ratio = f\"{orb_info.participation_ratio:4.1f}\"",
"vbm_hole_occupation: float = None cbm_electron_occupation: float = None @property def is_shallow(self): return self.has_donor_phs",
"participation_ratio = f\"{lo.participation_ratio:5.2f}\" \\ if lo.participation_ratio else \"None\" inner = [lo.band_idx + 1,",
"[\"VBM\"] + self._show_edge_info( self.vbm_info, self.vbm_orbital_diff), [\"CBM\"] + self._show_edge_info( self.cbm_info, self.cbm_orbital_diff)] table = tabulate(inner_table,",
"fermi_level: float def kpt_idx(self, kpt_coord): for i, orig_kpt in enumerate(self.kpt_coords): if sum(abs(k -",
"1e-5: return i raise ValueError(f\"{kpt_coord} not in kpt_coords {self.kpt_coords}.\") @property def energies_and_occupations(self) ->",
"band-idx] kpt_coords: List[Coords] kpt_weights: List[float] lowest_band_index: int fermi_level: float def kpt_idx(self, kpt_coord): for",
"vs. {defaults.state_occupied_threshold})\" return \"\\n\".join([table, vbm_phs, cbm_phs]) @staticmethod def _show_edge_info(edge_info: EdgeInfo, orb_diff: float): return",
"t_orbital_info @dataclass class LocalizedOrbital(MSONable): band_idx: int ave_energy: float occupation: float orbitals: Dict[str, List[float]]",
"float]] lowest_band_index: int def pretty_orbital(orbitals: Dict[str, List[float]]): \"\"\" :param orbitals: An example is",
"[\"CBM\"] + self._show_edge_info( self.cbm_info, self.cbm_orbital_diff)] table = tabulate(inner_table, tablefmt=\"plain\") vbm_phs = f\"vbm has",
"def __str__(self): def show_edge_info(edge_info: EdgeInfo): return [edge_info.band_idx, edge_info.energy, f\"{edge_info.occupation:5.2f}\", pretty_orbital(edge_info.orbital_info.orbitals), pretty_coords(edge_info.kpt_coord)] return tabulate([",
"max_idx): actual_band_idx = band_idx + self.lowest_band_index + 1 for kpt_idx, orb_info in enumerate(t_orb_info[band_idx],",
"@property def energy(self): return self.orbital_info.energy @property def occupation(self): return self.orbital_info.occupation @property def p_ratio(self):",
"vise.util.typing import Coords, GenCoords printed_orbital_weight_threshold = 0.1 @dataclass class BandEdgeEigenvalues(MSONable, ToJsonFileMixIn): # [spin,",
"from pydefect.defaults import defaults from pydefect.util.coords import pretty_coords from tabulate import tabulate from",
"len(t_orbital_info)) min_idx = max(middle_idx - 3, 0) return max_idx, min_idx, t_orbital_info @dataclass class",
"Mn-p: 0.40\" \"\"\" orbital_infos = [] for elem, orbs in orbitals.items(): for orb_name,",
"self._orbital_info]) @property def _orbital_info(self): inner_table = [[\"Index\", \"Energy\", \"P-ratio\", \"Occupation\", \"Orbitals\"]] w_radius =",
"-*- coding: utf-8 -*- # Copyright (c) 2020. Distributed under the terms of",
"\"Weight\"]] for index, (kpt_coord, kpt_weight) in enumerate( zip(self.kpt_coords, self.kpt_weights), 1): coord = pretty_coords(kpt_coord)",
"ave_energy: float occupation: float orbitals: Dict[str, List[float]] participation_ratio: Optional[float] = None radius: Optional[float]",
"def has_unoccupied_localized_state(self): return any([lo.occupation < defaults.state_unoccupied_threshold for lo in self.localized_orbitals]) @property def has_occupied_localized_state(self):",
"self.localized_orbitals[0].radius if w_radius: inner_table[0].extend([\"Radius\", \"Center\"]) for lo in self.localized_orbitals: participation_ratio = f\"{lo.participation_ratio:5.2f}\" \\",
"def _orbital_info(self): inner_table = [[\"Index\", \"Energy\", \"P-ratio\", \"Occupation\", \"Orbitals\"]] w_radius = self.localized_orbitals and",
"orbitals: Dict[str, List[float]] occupation: float participation_ratio: float = None @dataclass class BandEdgeOrbitalInfos(MSONable, ToJsonFileMixIn):",
"orb_diff: float): return [edge_info.band_idx + 1, f\"{edge_info.energy:7.3f}\", f\"{edge_info.p_ratio:5.2f}\", f\"{edge_info.occupation:5.2f}\", f\"{orb_diff:5.2f}\", pretty_orbital(edge_info.orbital_info.orbitals), pretty_coords(edge_info.kpt_coord)] @dataclass",
"return self.orbital_info.occupation @property def p_ratio(self): return self.orbital_info.participation_ratio @dataclass class PerfectBandEdgeState(MSONable, ToJsonFileMixIn): vbm_info: EdgeInfo",
"band_idx: int kpt_coord: Coords orbital_info: \"OrbitalInfo\" @property def orbitals(self): return self.orbital_info.orbitals @property def",
"the band_idx where the occupation changes largely. if lower[0].occupation - upper[0].occupation > 0.1:",
"orbital_infos: List[List[List[\"OrbitalInfo\"]]] # [spin, k-idx, band-idx] kpt_coords: List[Coords] kpt_weights: List[float] lowest_band_index: int fermi_level:",
"w_radius: inner_table[0].extend([\"Radius\", \"Center\"]) for lo in self.localized_orbitals: participation_ratio = f\"{lo.participation_ratio:5.2f}\" \\ if lo.participation_ratio",
"[\"VBM\"] + show_edge_info(self.vbm_info), [\"CBM\"] + show_edge_info(self.cbm_info)], tablefmt=\"plain\") @dataclass class BandEdgeState(MSONable): vbm_info: EdgeInfo cbm_info:",
"defaults.state_occupied_threshold @property def has_acceptor_phs(self): return self.vbm_hole_occupation > defaults.state_occupied_threshold @property def has_unoccupied_localized_state(self): return any([lo.occupation",
"= energy, occupation energies_and_occupations: List[List[List[List[float]]]] kpt_coords: List[Tuple[float, float, float]] lowest_band_index: int def pretty_orbital(orbitals:",
"{self.has_donor_phs} \" \\ f\"({self.cbm_electron_occupation:5.3f} vs. {defaults.state_occupied_threshold})\" return \"\\n\".join([table, vbm_phs, cbm_phs]) @staticmethod def _show_edge_info(edge_info:",
"@property def has_donor_phs(self): return any([i.has_donor_phs for i in self.states]) @property def has_acceptor_phs(self): return",
"kpt_coord): for i, orig_kpt in enumerate(self.kpt_coords): if sum(abs(k - l) for k, l",
"pretty_orbital(lo.orbitals)] if w_radius: inner.extend([f\"{lo.radius:5.2f}\", pretty_coords(lo.center)]) inner_table.append(inner) return tabulate(inner_table, tablefmt=\"plain\") @property def _edge_info(self): inner_table",
"float, float]] lowest_band_index: int def pretty_orbital(orbitals: Dict[str, List[float]]): \"\"\" :param orbitals: An example",
"example is {\"Mn\": [0.5, 0.4, 0.01]} (no f-orbital) :return: \"Mn-s: 0.50, Mn-p: 0.40\"",
"self.localized_orbitals and self.localized_orbitals[0].radius if w_radius: inner_table[0].extend([\"Radius\", \"Center\"]) for lo in self.localized_orbitals: participation_ratio =",
"weight > printed_orbital_weight_threshold: orbital_infos.append(f\"{elem}-{orb_name}: {weight:.2f}\") return \", \".join(orbital_infos) @dataclass class OrbitalInfo(MSONable): \"\"\"Note that",
"import defaults from pydefect.util.coords import pretty_coords from tabulate import tabulate from vise.util.mix_in import",
"in state.localized_orbitals: indices_set.add(lo.band_idx) indices_set.add(state.cbm_info.band_idx) return sorted([i for i in indices_set]) def __str__(self): lines",
"(upper, lower) in enumerate(zip(t_orbital_info[1:], t_orbital_info[:-1])): # determine the band_idx where the occupation changes",
"return result.tolist() def __str__(self): return \"\\n\".join([\" -- band-edge orbitals info\", \"K-points info\", self._kpt_block,",
"for i in self.states]) @property def has_donor_phs(self): return any([i.has_donor_phs for i in self.states])",
"__str__(self): lines = [\" -- band-edge states info\"] for spin, state in zip([\"up\",",
"orb_info in enumerate(t_orb_info[band_idx], 1): energy = f\"{orb_info.energy :5.2f}\" occupation = f\"{orb_info.occupation:4.1f}\" p_ratio =",
"lists contain s, p, d, (f) orbital components. orbitals: Dict[str, List[float]] occupation: float",
"= f\"cbm has donor phs: {self.has_donor_phs} \" \\ f\"({self.cbm_electron_occupation:5.3f} vs. {defaults.state_occupied_threshold})\" return \"\\n\".join([table,",
"for j, y in enumerate(x): for k, z in enumerate(y): result[i][j][k] = [z.energy,",
"[kpt_idx][band_idx] -> [bane_idx][kpt_idx] t_orbital_info = np.array(orbital_info).T.tolist() middle_idx = int(len(t_orbital_info) / 2) for band_idx,",
"\"K-point coords\"], [\"VBM\"] + show_edge_info(self.vbm_info), [\"CBM\"] + show_edge_info(self.cbm_info)], tablefmt=\"plain\") @dataclass class BandEdgeState(MSONable): vbm_info:",
"in self.states]) @property def has_unoccupied_localized_state(self): return any([i.has_unoccupied_localized_state for i in self.states]) @property def",
"radius: Optional[float] = None center: Optional[GenCoords] = None @dataclass class EdgeInfo(MSONable): band_idx: int",
"any([i.is_shallow for i in self.states]) @property def has_donor_phs(self): return any([i.has_donor_phs for i in",
"energies_and_occupations(self) -> List[List[List[List[float]]]]: result = np.zeros(np.shape(self.orbital_infos) + (2,)) for i, x in enumerate(self.orbital_infos):",
"\"Occupation\", \"Orbitals\"]] w_radius = self.localized_orbitals and self.localized_orbitals[0].radius if w_radius: inner_table[0].extend([\"Radius\", \"Center\"]) for lo",
"enumerate(x): for k, z in enumerate(y): result[i][j][k] = [z.energy, z.occupation] return result.tolist() def",
"enumerate(t_orb_info[band_idx], 1): energy = f\"{orb_info.energy :5.2f}\" occupation = f\"{orb_info.occupation:4.1f}\" p_ratio = f\"{orb_info.participation_ratio:4.1f}\" orbs",
"+ show_edge_info(self.vbm_info), [\"CBM\"] + show_edge_info(self.cbm_info)], tablefmt=\"plain\") @dataclass class BandEdgeState(MSONable): vbm_info: EdgeInfo cbm_info: EdgeInfo",
"BandEdgeState(MSONable): vbm_info: EdgeInfo cbm_info: EdgeInfo vbm_orbital_diff: float cbm_orbital_diff: float localized_orbitals: List[LocalizedOrbital] vbm_hole_occupation: float",
"k-idx, band-idx] kpt_coords: List[Coords] kpt_weights: List[float] lowest_band_index: int fermi_level: float def kpt_idx(self, kpt_coord):",
"lo in self.localized_orbitals]) def __str__(self): return \"\\n\".join([self._edge_info, \"---\", \"Localized Orbital(s)\", self._orbital_info]) @property def",
"List[BandEdgeState] # by spin. @property def is_shallow(self): return any([i.is_shallow for i in self.states])",
"in self.states]) @property def has_donor_phs(self): return any([i.has_donor_phs for i in self.states]) @property def",
"-*- # Copyright (c) 2020. Distributed under the terms of the MIT License.",
"upper[0].occupation > 0.1: middle_idx = band_idx + 1 break max_idx = min(middle_idx +",
"as np from monty.json import MSONable from pydefect.defaults import defaults from pydefect.util.coords import",
"def __str__(self): return \"\\n\".join([\" -- band-edge orbitals info\", \"K-points info\", self._kpt_block, \"\", \"Band",
"\"\\n\".join([table, vbm_phs, cbm_phs]) @staticmethod def _show_edge_info(edge_info: EdgeInfo, orb_diff: float): return [edge_info.band_idx + 1,",
"def _kpt_block(self): kpt_block = [[\"Index\", \"Coords\", \"Weight\"]] for index, (kpt_coord, kpt_weight) in enumerate(",
"is {\"Mn\": [0.5, 0.4, 0.01]} (no f-orbital) :return: \"Mn-s: 0.50, Mn-p: 0.40\" \"\"\"",
"List[float]] occupation: float participation_ratio: float = None @dataclass class BandEdgeOrbitalInfos(MSONable, ToJsonFileMixIn): orbital_infos: List[List[List[\"OrbitalInfo\"]]]",
"self.orbital_info.energy @property def occupation(self): return self.orbital_info.occupation @property def p_ratio(self): return self.orbital_info.participation_ratio @dataclass class",
"1, f\"{edge_info.energy:7.3f}\", f\"{edge_info.p_ratio:5.2f}\", f\"{edge_info.occupation:5.2f}\", f\"{orb_diff:5.2f}\", pretty_orbital(edge_info.orbital_info.orbitals), pretty_coords(edge_info.kpt_coord)] @dataclass class BandEdgeStates(MSONable, ToJsonFileMixIn): states: List[BandEdgeState]",
"Coords orbital_info: \"OrbitalInfo\" @property def orbitals(self): return self.orbital_info.orbitals @property def energy(self): return self.orbital_info.energy",
"in self.states: indices_set.add(state.vbm_info.band_idx) for lo in state.localized_orbitals: indices_set.add(lo.band_idx) indices_set.add(state.cbm_info.band_idx) return sorted([i for i",
"float orbitals: Dict[str, List[float]] participation_ratio: Optional[float] = None radius: Optional[float] = None center:",
"def _edge_info(self): inner_table = [[\"\", \"Index\", \"Energy\", \"P-ratio\", \"Occupation\", \"OrbDiff\", \"Orbitals\", \"K-point coords\"],",
"changes largely. if lower[0].occupation - upper[0].occupation > 0.1: middle_idx = band_idx + 1",
"@property def orbitals(self): return self.orbital_info.orbitals @property def energy(self): return self.orbital_info.energy @property def occupation(self):",
"\"Index\", \"Energy\", \"P-ratio\", \"Occupation\", \"OrbDiff\", \"Orbitals\", \"K-point coords\"], [\"VBM\"] + self._show_edge_info( self.vbm_info, self.vbm_orbital_diff),",
"printed_orbital_weight_threshold: orbital_infos.append(f\"{elem}-{orb_name}: {weight:.2f}\") return \", \".join(orbital_infos) @dataclass class OrbitalInfo(MSONable): \"\"\"Note that this is",
"0.5]}, # where lists contain s, p, d, (f) orbital components. orbitals: Dict[str,",
"pretty_orbital(orb_info.orbitals) band_block.append([actual_band_idx, kpt_idx, energy, occupation, p_ratio, orbs]) band_block.append([\"--\"]) band_block.append(\"\") return tabulate(band_block, tablefmt=\"plain\") @property",
"orbs): if weight > printed_orbital_weight_threshold: orbital_infos.append(f\"{elem}-{orb_name}: {weight:.2f}\") return \", \".join(orbital_infos) @dataclass class OrbitalInfo(MSONable):",
"vs. {defaults.state_occupied_threshold})\" cbm_phs = f\"cbm has donor phs: {self.has_donor_phs} \" \\ f\"({self.cbm_electron_occupation:5.3f} vs.",
"from typing import List, Dict, Tuple, Optional, Set import numpy as np from",
"\"Coords\", \"Weight\"]] for index, (kpt_coord, kpt_weight) in enumerate( zip(self.kpt_coords, self.kpt_weights), 1): coord =",
"\"K-point coords\"], [\"VBM\"] + self._show_edge_info( self.vbm_info, self.vbm_orbital_diff), [\"CBM\"] + self._show_edge_info( self.cbm_info, self.cbm_orbital_diff)] table",
"under the terms of the MIT License. from dataclasses import dataclass from typing",
"occupation = f\"{orb_info.occupation:4.1f}\" p_ratio = f\"{orb_info.participation_ratio:4.1f}\" orbs = pretty_orbital(orb_info.orbitals) band_block.append([actual_band_idx, kpt_idx, energy, occupation,",
"set() for state in self.states: indices_set.add(state.vbm_info.band_idx) for lo in state.localized_orbitals: indices_set.add(lo.band_idx) indices_set.add(state.cbm_info.band_idx) return",
"return any([i.has_acceptor_phs for i in self.states]) @property def has_unoccupied_localized_state(self): return any([i.has_unoccupied_localized_state for i",
"[spin, k-idx, band-idx] = energy, occupation energies_and_occupations: List[List[List[List[float]]]] kpt_coords: List[Tuple[float, float, float]] lowest_band_index:",
"any([i.has_occupied_localized_state for i in self.states]) @property def band_indices_from_vbm_to_cbm(self) -> List[int]: indices_set = set()",
"band_idx + 1 break max_idx = min(middle_idx + 3, len(t_orbital_info)) min_idx = max(middle_idx",
"ToJsonFileMixIn): # [spin, k-idx, band-idx] = energy, occupation energies_and_occupations: List[List[List[List[float]]]] kpt_coords: List[Tuple[float, float,",
"\"\\n\".join([self._edge_info, \"---\", \"Localized Orbital(s)\", self._orbital_info]) @property def _orbital_info(self): inner_table = [[\"Index\", \"Energy\", \"P-ratio\",",
"return any([lo.occupation > defaults.state_occupied_threshold for lo in self.localized_orbitals]) def __str__(self): return \"\\n\".join([self._edge_info, \"---\",",
"\"Energy\", \"P-ratio\", \"Occupation\", \"OrbDiff\", \"Orbitals\", \"K-point coords\"], [\"VBM\"] + self._show_edge_info( self.vbm_info, self.vbm_orbital_diff), [\"CBM\"]",
"for orbital_info in self.orbital_infos: max_idx, min_idx, t_orb_info = self._band_idx_range(orbital_info) for band_idx in range(min_idx,",
"1): energy = f\"{orb_info.energy :5.2f}\" occupation = f\"{orb_info.occupation:4.1f}\" p_ratio = f\"{orb_info.participation_ratio:4.1f}\" orbs =",
"return max_idx, min_idx, t_orbital_info @dataclass class LocalizedOrbital(MSONable): band_idx: int ave_energy: float occupation: float",
"List[Coords] kpt_weights: List[float] lowest_band_index: int fermi_level: float def kpt_idx(self, kpt_coord): for i, orig_kpt",
"and self.localized_orbitals[0].radius if w_radius: inner_table[0].extend([\"Radius\", \"Center\"]) for lo in self.localized_orbitals: participation_ratio = f\"{lo.participation_ratio:5.2f}\"",
"min_idx, t_orb_info = self._band_idx_range(orbital_info) for band_idx in range(min_idx, max_idx): actual_band_idx = band_idx +",
"s, p, d, (f) orbital components. orbitals: Dict[str, List[float]] occupation: float participation_ratio: float",
"List[List[List[List[float]]]]: result = np.zeros(np.shape(self.orbital_infos) + (2,)) for i, x in enumerate(self.orbital_infos): for j,",
"2020. Distributed under the terms of the MIT License. from dataclasses import dataclass",
"\"O\": [0.03, 0.5]}, # where lists contain s, p, d, (f) orbital components.",
"\"f\"], orbs): if weight > printed_orbital_weight_threshold: orbital_infos.append(f\"{elem}-{orb_name}: {weight:.2f}\") return \", \".join(orbital_infos) @dataclass class",
"# swap [kpt_idx][band_idx] -> [bane_idx][kpt_idx] t_orbital_info = np.array(orbital_info).T.tolist() middle_idx = int(len(t_orbital_info) / 2)",
"{self.kpt_coords}.\") @property def energies_and_occupations(self) -> List[List[List[List[float]]]]: result = np.zeros(np.shape(self.orbital_infos) + (2,)) for i,",
"pretty_coords from tabulate import tabulate from vise.util.mix_in import ToJsonFileMixIn from vise.util.typing import Coords,",
"\"Occupation\", \"P-ratio\", \"Orbital\"]] for orbital_info in self.orbital_infos: max_idx, min_idx, t_orb_info = self._band_idx_range(orbital_info) for",
"energy = f\"{orb_info.energy :5.2f}\" occupation = f\"{orb_info.occupation:4.1f}\" p_ratio = f\"{orb_info.participation_ratio:4.1f}\" orbs = pretty_orbital(orb_info.orbitals)",
"is_shallow(self): return self.has_donor_phs or self.has_acceptor_phs @property def has_donor_phs(self): return self.cbm_electron_occupation > defaults.state_occupied_threshold @property",
"\"p\", \"d\", \"f\"], orbs): if weight > printed_orbital_weight_threshold: orbital_infos.append(f\"{elem}-{orb_name}: {weight:.2f}\") return \", \".join(orbital_infos)",
"f\"({self.cbm_electron_occupation:5.3f} vs. {defaults.state_occupied_threshold})\" return \"\\n\".join([table, vbm_phs, cbm_phs]) @staticmethod def _show_edge_info(edge_info: EdgeInfo, orb_diff: float):",
"vbm_phs, cbm_phs]) @staticmethod def _show_edge_info(edge_info: EdgeInfo, orb_diff: float): return [edge_info.band_idx + 1, f\"{edge_info.energy:7.3f}\",",
"indices_set.add(state.vbm_info.band_idx) for lo in state.localized_orbitals: indices_set.add(lo.band_idx) indices_set.add(state.cbm_info.band_idx) return sorted([i for i in indices_set])",
"<filename>pydefect/analyzer/band_edge_states.py<gh_stars>10-100 # -*- coding: utf-8 -*- # Copyright (c) 2020. Distributed under the",
"defaults from pydefect.util.coords import pretty_coords from tabulate import tabulate from vise.util.mix_in import ToJsonFileMixIn",
"def _band_idx_range(orbital_info: List[List[OrbitalInfo]] ) -> Tuple[int, int, List[List[OrbitalInfo]]]: # swap [kpt_idx][band_idx] -> [bane_idx][kpt_idx]",
"1 break max_idx = min(middle_idx + 3, len(t_orbital_info)) min_idx = max(middle_idx - 3,",
"orbital components. orbitals: Dict[str, List[float]] occupation: float participation_ratio: float = None @dataclass class",
"# max eigenvalue # {\"Mn\": [0.01, ..], \"O\": [0.03, 0.5]}, # where lists",
"import List, Dict, Tuple, Optional, Set import numpy as np from monty.json import",
"return \", \".join(orbital_infos) @dataclass class OrbitalInfo(MSONable): \"\"\"Note that this is code and its",
"f\"{orb_info.participation_ratio:4.1f}\" orbs = pretty_orbital(orb_info.orbitals) band_block.append([actual_band_idx, kpt_idx, energy, occupation, p_ratio, orbs]) band_block.append([\"--\"]) band_block.append(\"\") return",
"for i in self.states]) @property def band_indices_from_vbm_to_cbm(self) -> List[int]: indices_set = set() for",
"EdgeInfo cbm_info: EdgeInfo def __str__(self): def show_edge_info(edge_info: EdgeInfo): return [edge_info.band_idx, edge_info.energy, f\"{edge_info.occupation:5.2f}\", pretty_orbital(edge_info.orbital_info.orbitals),",
"\"P-ratio\", \"Occupation\", \"OrbDiff\", \"Orbitals\", \"K-point coords\"], [\"VBM\"] + self._show_edge_info( self.vbm_info, self.vbm_orbital_diff), [\"CBM\"] +",
"import pretty_coords from tabulate import tabulate from vise.util.mix_in import ToJsonFileMixIn from vise.util.typing import",
"tablefmt=\"plain\") @dataclass class BandEdgeState(MSONable): vbm_info: EdgeInfo cbm_info: EdgeInfo vbm_orbital_diff: float cbm_orbital_diff: float localized_orbitals:"
] |
[
"description in self.cursor.description] # gets the column names from nuts table because self.sm.get_cursor().execute()",
"self.comp_names) def test_result(self): self.assertEqual(self.sm.result, \"OK\") def tearDown(self): self.sm.__del__() if __name__ == '__main__': unittest.main()",
"get the cursor from the object, execute a SELECT statement against the table,",
"object compose and execute an SQL statement to create a table in fruit.db,",
"self.comp_names. If they match, the object successfully created the nut table in fruit.db.",
"SELECT statement against the table, then get the name of the columns in",
"gets the column names from nuts table because self.sm.get_cursor().execute() is selecting from nuts",
"\"TEXT\").create_table() self.cursor = self.sm.get_cursor() self.cursor.execute(\"SELECT * FROM nuts\") self.col_names = [description[0] for description",
"create a table in fruit.db, then get the cursor from the object, execute",
"If they match, the object successfully created the nut table in fruit.db. \"\"\"",
"have the SQLiteMgr object compose and execute an SQL statement to create a",
"(in a list), and compare with what should be the same list assigned",
"of the columns in the table (in a list), and compare with what",
"nuts\") self.col_names = [description[0] for description in self.cursor.description] # gets the column names",
"against the table, then get the name of the columns in the table",
"'Called', 'Description'] def test_create_table(self): self.assertEqual(self.col_names, self.comp_names) def test_result(self): self.assertEqual(self.sm.result, \"OK\") def tearDown(self): self.sm.__del__()",
"import unittest import os import sys sys.path.append(\"../sqlitemgr/\") import sqlitemgr as sqm class CreateTableTest(unittest.TestCase):",
"setUp(self): self.sm = sqm.SQLiteMgr(\"../fixtures/fruit.db\") self.sm.new_table(\"nuts\").add_table_column(\"Nmbr\", \"INT\", \"PRIMARY KEY\").add_table_column(\"Called\", \"TEXT\", \"UNIQUE\").add_table_column(\"Description\", \"TEXT\").create_table() self.cursor =",
"table self.comp_names = ['Nmbr', 'Called', 'Description'] def test_create_table(self): self.assertEqual(self.col_names, self.comp_names) def test_result(self): self.assertEqual(self.sm.result,",
"created the nut table in fruit.db. \"\"\" def setUp(self): self.sm = sqm.SQLiteMgr(\"../fixtures/fruit.db\") self.sm.new_table(\"nuts\").add_table_column(\"Nmbr\",",
"self.cursor.description] # gets the column names from nuts table because self.sm.get_cursor().execute() is selecting",
"sys sys.path.append(\"../sqlitemgr/\") import sqlitemgr as sqm class CreateTableTest(unittest.TestCase): \"\"\" The way the create_table",
"from nuts table self.comp_names = ['Nmbr', 'Called', 'Description'] def test_create_table(self): self.assertEqual(self.col_names, self.comp_names) def",
"selecting from nuts table self.comp_names = ['Nmbr', 'Called', 'Description'] def test_create_table(self): self.assertEqual(self.col_names, self.comp_names)",
"= ['Nmbr', 'Called', 'Description'] def test_create_table(self): self.assertEqual(self.col_names, self.comp_names) def test_result(self): self.assertEqual(self.sm.result, \"OK\") def",
"'Description'] def test_create_table(self): self.assertEqual(self.col_names, self.comp_names) def test_result(self): self.assertEqual(self.sm.result, \"OK\") def tearDown(self): self.sm.__del__() if",
"the column names from nuts table because self.sm.get_cursor().execute() is selecting from nuts table",
"table in fruit.db. \"\"\" def setUp(self): self.sm = sqm.SQLiteMgr(\"../fixtures/fruit.db\") self.sm.new_table(\"nuts\").add_table_column(\"Nmbr\", \"INT\", \"PRIMARY KEY\").add_table_column(\"Called\",",
"then get the cursor from the object, execute a SELECT statement against the",
"list), and compare with what should be the same list assigned to self.comp_names.",
"import sqlitemgr as sqm class CreateTableTest(unittest.TestCase): \"\"\" The way the create_table function is",
"KEY\").add_table_column(\"Called\", \"TEXT\", \"UNIQUE\").add_table_column(\"Description\", \"TEXT\").create_table() self.cursor = self.sm.get_cursor() self.cursor.execute(\"SELECT * FROM nuts\") self.col_names =",
"self.comp_names = ['Nmbr', 'Called', 'Description'] def test_create_table(self): self.assertEqual(self.col_names, self.comp_names) def test_result(self): self.assertEqual(self.sm.result, \"OK\")",
"assigned to self.comp_names. If they match, the object successfully created the nut table",
"nuts table self.comp_names = ['Nmbr', 'Called', 'Description'] def test_create_table(self): self.assertEqual(self.col_names, self.comp_names) def test_result(self):",
"table because self.sm.get_cursor().execute() is selecting from nuts table self.comp_names = ['Nmbr', 'Called', 'Description']",
"the SQLiteMgr object compose and execute an SQL statement to create a table",
"from the object, execute a SELECT statement against the table, then get the",
"os import sys sys.path.append(\"../sqlitemgr/\") import sqlitemgr as sqm class CreateTableTest(unittest.TestCase): \"\"\" The way",
"what should be the same list assigned to self.comp_names. If they match, the",
"test_create_table(self): self.assertEqual(self.col_names, self.comp_names) def test_result(self): self.assertEqual(self.sm.result, \"OK\") def tearDown(self): self.sm.__del__() if __name__ ==",
"to have the SQLiteMgr object compose and execute an SQL statement to create",
"in fruit.db, then get the cursor from the object, execute a SELECT statement",
"create_table function is being tested is to have the SQLiteMgr object compose and",
"get the name of the columns in the table (in a list), and",
"an SQL statement to create a table in fruit.db, then get the cursor",
"the nut table in fruit.db. \"\"\" def setUp(self): self.sm = sqm.SQLiteMgr(\"../fixtures/fruit.db\") self.sm.new_table(\"nuts\").add_table_column(\"Nmbr\", \"INT\",",
"\"UNIQUE\").add_table_column(\"Description\", \"TEXT\").create_table() self.cursor = self.sm.get_cursor() self.cursor.execute(\"SELECT * FROM nuts\") self.col_names = [description[0] for",
"def setUp(self): self.sm = sqm.SQLiteMgr(\"../fixtures/fruit.db\") self.sm.new_table(\"nuts\").add_table_column(\"Nmbr\", \"INT\", \"PRIMARY KEY\").add_table_column(\"Called\", \"TEXT\", \"UNIQUE\").add_table_column(\"Description\", \"TEXT\").create_table() self.cursor",
"in fruit.db. \"\"\" def setUp(self): self.sm = sqm.SQLiteMgr(\"../fixtures/fruit.db\") self.sm.new_table(\"nuts\").add_table_column(\"Nmbr\", \"INT\", \"PRIMARY KEY\").add_table_column(\"Called\", \"TEXT\",",
"nuts table because self.sm.get_cursor().execute() is selecting from nuts table self.comp_names = ['Nmbr', 'Called',",
"column names from nuts table because self.sm.get_cursor().execute() is selecting from nuts table self.comp_names",
"self.col_names = [description[0] for description in self.cursor.description] # gets the column names from",
"self.cursor.execute(\"SELECT * FROM nuts\") self.col_names = [description[0] for description in self.cursor.description] # gets",
"to self.comp_names. If they match, the object successfully created the nut table in",
"import sys sys.path.append(\"../sqlitemgr/\") import sqlitemgr as sqm class CreateTableTest(unittest.TestCase): \"\"\" The way the",
"= sqm.SQLiteMgr(\"../fixtures/fruit.db\") self.sm.new_table(\"nuts\").add_table_column(\"Nmbr\", \"INT\", \"PRIMARY KEY\").add_table_column(\"Called\", \"TEXT\", \"UNIQUE\").add_table_column(\"Description\", \"TEXT\").create_table() self.cursor = self.sm.get_cursor() self.cursor.execute(\"SELECT",
"then get the name of the columns in the table (in a list),",
"unittest import os import sys sys.path.append(\"../sqlitemgr/\") import sqlitemgr as sqm class CreateTableTest(unittest.TestCase): \"\"\"",
"should be the same list assigned to self.comp_names. If they match, the object",
"[description[0] for description in self.cursor.description] # gets the column names from nuts table",
"table (in a list), and compare with what should be the same list",
"compare with what should be the same list assigned to self.comp_names. If they",
"def test_create_table(self): self.assertEqual(self.col_names, self.comp_names) def test_result(self): self.assertEqual(self.sm.result, \"OK\") def tearDown(self): self.sm.__del__() if __name__",
"match, the object successfully created the nut table in fruit.db. \"\"\" def setUp(self):",
"successfully created the nut table in fruit.db. \"\"\" def setUp(self): self.sm = sqm.SQLiteMgr(\"../fixtures/fruit.db\")",
"being tested is to have the SQLiteMgr object compose and execute an SQL",
"the table (in a list), and compare with what should be the same",
"cursor from the object, execute a SELECT statement against the table, then get",
"\"\"\" The way the create_table function is being tested is to have the",
"is selecting from nuts table self.comp_names = ['Nmbr', 'Called', 'Description'] def test_create_table(self): self.assertEqual(self.col_names,",
"\"INT\", \"PRIMARY KEY\").add_table_column(\"Called\", \"TEXT\", \"UNIQUE\").add_table_column(\"Description\", \"TEXT\").create_table() self.cursor = self.sm.get_cursor() self.cursor.execute(\"SELECT * FROM nuts\")",
"because self.sm.get_cursor().execute() is selecting from nuts table self.comp_names = ['Nmbr', 'Called', 'Description'] def",
"\"\"\" def setUp(self): self.sm = sqm.SQLiteMgr(\"../fixtures/fruit.db\") self.sm.new_table(\"nuts\").add_table_column(\"Nmbr\", \"INT\", \"PRIMARY KEY\").add_table_column(\"Called\", \"TEXT\", \"UNIQUE\").add_table_column(\"Description\", \"TEXT\").create_table()",
"object successfully created the nut table in fruit.db. \"\"\" def setUp(self): self.sm =",
"compose and execute an SQL statement to create a table in fruit.db, then",
"the name of the columns in the table (in a list), and compare",
"the cursor from the object, execute a SELECT statement against the table, then",
"statement against the table, then get the name of the columns in the",
"import os import sys sys.path.append(\"../sqlitemgr/\") import sqlitemgr as sqm class CreateTableTest(unittest.TestCase): \"\"\" The",
"self.assertEqual(self.col_names, self.comp_names) def test_result(self): self.assertEqual(self.sm.result, \"OK\") def tearDown(self): self.sm.__del__() if __name__ == '__main__':",
"the object successfully created the nut table in fruit.db. \"\"\" def setUp(self): self.sm",
"table in fruit.db, then get the cursor from the object, execute a SELECT",
"nut table in fruit.db. \"\"\" def setUp(self): self.sm = sqm.SQLiteMgr(\"../fixtures/fruit.db\") self.sm.new_table(\"nuts\").add_table_column(\"Nmbr\", \"INT\", \"PRIMARY",
"sqm.SQLiteMgr(\"../fixtures/fruit.db\") self.sm.new_table(\"nuts\").add_table_column(\"Nmbr\", \"INT\", \"PRIMARY KEY\").add_table_column(\"Called\", \"TEXT\", \"UNIQUE\").add_table_column(\"Description\", \"TEXT\").create_table() self.cursor = self.sm.get_cursor() self.cursor.execute(\"SELECT *",
"self.sm.get_cursor() self.cursor.execute(\"SELECT * FROM nuts\") self.col_names = [description[0] for description in self.cursor.description] #",
"and compare with what should be the same list assigned to self.comp_names. If",
"statement to create a table in fruit.db, then get the cursor from the",
"self.sm.get_cursor().execute() is selecting from nuts table self.comp_names = ['Nmbr', 'Called', 'Description'] def test_create_table(self):",
"columns in the table (in a list), and compare with what should be",
"in the table (in a list), and compare with what should be the",
"is to have the SQLiteMgr object compose and execute an SQL statement to",
"a list), and compare with what should be the same list assigned to",
"same list assigned to self.comp_names. If they match, the object successfully created the",
"\"TEXT\", \"UNIQUE\").add_table_column(\"Description\", \"TEXT\").create_table() self.cursor = self.sm.get_cursor() self.cursor.execute(\"SELECT * FROM nuts\") self.col_names = [description[0]",
"with what should be the same list assigned to self.comp_names. If they match,",
"execute a SELECT statement against the table, then get the name of the",
"for description in self.cursor.description] # gets the column names from nuts table because",
"names from nuts table because self.sm.get_cursor().execute() is selecting from nuts table self.comp_names =",
"execute an SQL statement to create a table in fruit.db, then get the",
"The way the create_table function is being tested is to have the SQLiteMgr",
"the columns in the table (in a list), and compare with what should",
"sys.path.append(\"../sqlitemgr/\") import sqlitemgr as sqm class CreateTableTest(unittest.TestCase): \"\"\" The way the create_table function",
"a table in fruit.db, then get the cursor from the object, execute a",
"['Nmbr', 'Called', 'Description'] def test_create_table(self): self.assertEqual(self.col_names, self.comp_names) def test_result(self): self.assertEqual(self.sm.result, \"OK\") def tearDown(self):",
"is being tested is to have the SQLiteMgr object compose and execute an",
"table, then get the name of the columns in the table (in a",
"\"PRIMARY KEY\").add_table_column(\"Called\", \"TEXT\", \"UNIQUE\").add_table_column(\"Description\", \"TEXT\").create_table() self.cursor = self.sm.get_cursor() self.cursor.execute(\"SELECT * FROM nuts\") self.col_names",
"in self.cursor.description] # gets the column names from nuts table because self.sm.get_cursor().execute() is",
"class CreateTableTest(unittest.TestCase): \"\"\" The way the create_table function is being tested is to",
"FROM nuts\") self.col_names = [description[0] for description in self.cursor.description] # gets the column",
"the object, execute a SELECT statement against the table, then get the name",
"list assigned to self.comp_names. If they match, the object successfully created the nut",
"self.sm = sqm.SQLiteMgr(\"../fixtures/fruit.db\") self.sm.new_table(\"nuts\").add_table_column(\"Nmbr\", \"INT\", \"PRIMARY KEY\").add_table_column(\"Called\", \"TEXT\", \"UNIQUE\").add_table_column(\"Description\", \"TEXT\").create_table() self.cursor = self.sm.get_cursor()",
"SQL statement to create a table in fruit.db, then get the cursor from",
"= [description[0] for description in self.cursor.description] # gets the column names from nuts",
"they match, the object successfully created the nut table in fruit.db. \"\"\" def",
"from nuts table because self.sm.get_cursor().execute() is selecting from nuts table self.comp_names = ['Nmbr',",
"self.sm.new_table(\"nuts\").add_table_column(\"Nmbr\", \"INT\", \"PRIMARY KEY\").add_table_column(\"Called\", \"TEXT\", \"UNIQUE\").add_table_column(\"Description\", \"TEXT\").create_table() self.cursor = self.sm.get_cursor() self.cursor.execute(\"SELECT * FROM",
"CreateTableTest(unittest.TestCase): \"\"\" The way the create_table function is being tested is to have",
"tested is to have the SQLiteMgr object compose and execute an SQL statement",
"fruit.db. \"\"\" def setUp(self): self.sm = sqm.SQLiteMgr(\"../fixtures/fruit.db\") self.sm.new_table(\"nuts\").add_table_column(\"Nmbr\", \"INT\", \"PRIMARY KEY\").add_table_column(\"Called\", \"TEXT\", \"UNIQUE\").add_table_column(\"Description\",",
"as sqm class CreateTableTest(unittest.TestCase): \"\"\" The way the create_table function is being tested",
"self.cursor = self.sm.get_cursor() self.cursor.execute(\"SELECT * FROM nuts\") self.col_names = [description[0] for description in",
"SQLiteMgr object compose and execute an SQL statement to create a table in",
"* FROM nuts\") self.col_names = [description[0] for description in self.cursor.description] # gets the",
"<reponame>aescwork/sqlitemgr import unittest import os import sys sys.path.append(\"../sqlitemgr/\") import sqlitemgr as sqm class",
"name of the columns in the table (in a list), and compare with",
"a SELECT statement against the table, then get the name of the columns",
"to create a table in fruit.db, then get the cursor from the object,",
"fruit.db, then get the cursor from the object, execute a SELECT statement against",
"function is being tested is to have the SQLiteMgr object compose and execute",
"= self.sm.get_cursor() self.cursor.execute(\"SELECT * FROM nuts\") self.col_names = [description[0] for description in self.cursor.description]",
"way the create_table function is being tested is to have the SQLiteMgr object",
"sqlitemgr as sqm class CreateTableTest(unittest.TestCase): \"\"\" The way the create_table function is being",
"sqm class CreateTableTest(unittest.TestCase): \"\"\" The way the create_table function is being tested is",
"the create_table function is being tested is to have the SQLiteMgr object compose",
"object, execute a SELECT statement against the table, then get the name of",
"be the same list assigned to self.comp_names. If they match, the object successfully",
"# gets the column names from nuts table because self.sm.get_cursor().execute() is selecting from",
"the table, then get the name of the columns in the table (in",
"the same list assigned to self.comp_names. If they match, the object successfully created",
"and execute an SQL statement to create a table in fruit.db, then get"
] |
[
"<NAME> (<EMAIL>) \"\"\" from scs_core.data.queue_report import QueueReport, ClientStatus # -------------------------------------------------------------------------------------------------------------------- filename = '/tmp/southcoastscience/queue_report.json'",
"QueueReport, ClientStatus # -------------------------------------------------------------------------------------------------------------------- filename = '/tmp/southcoastscience/queue_report.json' report = QueueReport(23, ClientStatus.CONNECTED, True) print(report)",
"#!/usr/bin/env python3 \"\"\" Created on 27 Aug 2019 @author: <NAME> (<EMAIL>) \"\"\" from",
"Created on 27 Aug 2019 @author: <NAME> (<EMAIL>) \"\"\" from scs_core.data.queue_report import QueueReport,",
"= '/tmp/southcoastscience/queue_report.json' report = QueueReport(23, ClientStatus.CONNECTED, True) print(report) print(report.as_json()) report.save(filename) print(\"-\") report =",
"@author: <NAME> (<EMAIL>) \"\"\" from scs_core.data.queue_report import QueueReport, ClientStatus # -------------------------------------------------------------------------------------------------------------------- filename =",
"ClientStatus # -------------------------------------------------------------------------------------------------------------------- filename = '/tmp/southcoastscience/queue_report.json' report = QueueReport(23, ClientStatus.CONNECTED, True) print(report) print(report.as_json())",
"report = QueueReport(23, ClientStatus.CONNECTED, True) print(report) print(report.as_json()) report.save(filename) print(\"-\") report = QueueReport.load(filename) print(report)",
"from scs_core.data.queue_report import QueueReport, ClientStatus # -------------------------------------------------------------------------------------------------------------------- filename = '/tmp/southcoastscience/queue_report.json' report = QueueReport(23,",
"on 27 Aug 2019 @author: <NAME> (<EMAIL>) \"\"\" from scs_core.data.queue_report import QueueReport, ClientStatus",
"filename = '/tmp/southcoastscience/queue_report.json' report = QueueReport(23, ClientStatus.CONNECTED, True) print(report) print(report.as_json()) report.save(filename) print(\"-\") report",
"\"\"\" Created on 27 Aug 2019 @author: <NAME> (<EMAIL>) \"\"\" from scs_core.data.queue_report import",
"27 Aug 2019 @author: <NAME> (<EMAIL>) \"\"\" from scs_core.data.queue_report import QueueReport, ClientStatus #",
"# -------------------------------------------------------------------------------------------------------------------- filename = '/tmp/southcoastscience/queue_report.json' report = QueueReport(23, ClientStatus.CONNECTED, True) print(report) print(report.as_json()) report.save(filename)",
"(<EMAIL>) \"\"\" from scs_core.data.queue_report import QueueReport, ClientStatus # -------------------------------------------------------------------------------------------------------------------- filename = '/tmp/southcoastscience/queue_report.json' report",
"python3 \"\"\" Created on 27 Aug 2019 @author: <NAME> (<EMAIL>) \"\"\" from scs_core.data.queue_report",
"\"\"\" from scs_core.data.queue_report import QueueReport, ClientStatus # -------------------------------------------------------------------------------------------------------------------- filename = '/tmp/southcoastscience/queue_report.json' report =",
"import QueueReport, ClientStatus # -------------------------------------------------------------------------------------------------------------------- filename = '/tmp/southcoastscience/queue_report.json' report = QueueReport(23, ClientStatus.CONNECTED, True)",
"<reponame>seoss/scs_core #!/usr/bin/env python3 \"\"\" Created on 27 Aug 2019 @author: <NAME> (<EMAIL>) \"\"\"",
"Aug 2019 @author: <NAME> (<EMAIL>) \"\"\" from scs_core.data.queue_report import QueueReport, ClientStatus # --------------------------------------------------------------------------------------------------------------------",
"2019 @author: <NAME> (<EMAIL>) \"\"\" from scs_core.data.queue_report import QueueReport, ClientStatus # -------------------------------------------------------------------------------------------------------------------- filename",
"'/tmp/southcoastscience/queue_report.json' report = QueueReport(23, ClientStatus.CONNECTED, True) print(report) print(report.as_json()) report.save(filename) print(\"-\") report = QueueReport.load(filename)",
"-------------------------------------------------------------------------------------------------------------------- filename = '/tmp/southcoastscience/queue_report.json' report = QueueReport(23, ClientStatus.CONNECTED, True) print(report) print(report.as_json()) report.save(filename) print(\"-\")",
"scs_core.data.queue_report import QueueReport, ClientStatus # -------------------------------------------------------------------------------------------------------------------- filename = '/tmp/southcoastscience/queue_report.json' report = QueueReport(23, ClientStatus.CONNECTED,"
] |
[
"# Call preparation callback. if prepare: prepare(p) # Actually parse arguments. arguments =",
"run(handler, server=WSSHTTPServer, prepare=None, postparse=None, premain=None): \"\"\" run(handler, server=WSSHTTPServer, prepare=None, postparse=None, premain=None) -> None",
"is a (host, port) tuple with explicit values. If any of host or",
"not sep: raise ValueError('Invalid key-value pair %r' % (item,)) if key in ret:",
"used to specify additional options. postparse is a callable invoked after parsing arguments",
"default_addr=None): \"\"\" resolve_listen_address(addr, origin, default_addr=None) -> (host, port) Fill in default host and",
"a callable taking two arguments that creates the server instance; the arguments are:",
"the key-value pairs recovered from s. \"\"\" ret = {} for item in",
"key-value pairs recovered from s. \"\"\" ret = {} for item in s.split(','):",
"httpd.serve_forever() except KeyboardInterrupt: # Don't print a noisy stack trace if Ctrl+C'ed. sys.stderr.write('\\n')",
"HTTP request handler combining all the package's functionality. \"\"\" def tls_flags(s): \"\"\" Parse",
"configured using prepare to the server object and the handler class. \"\"\" #",
"= {} for item in s.split(','): if not item: continue key, sep, value",
"if host is None: host = default_addr[0] if port is None: port =",
"argument. It can do things like complex validation, and prevent the creation and",
"%s (origin %s)...\\n' % (address, origin_string)) sys.stderr.flush() # Call final preparation hook. if",
"port) def run(handler, server=WSSHTTPServer, prepare=None, postparse=None, premain=None): \"\"\" run(handler, server=WSSHTTPServer, prepare=None, postparse=None, premain=None)",
"be authenticated by one of the ' 'certificates in this file.') # Call",
"'tls_flags', 'resolve_listen_address', 'run'] DEFAULT_ADDRESS = ('', 8080) class RoutingWebSocketRequestHandler(RoutingRequestHandler, WebSocketMixIn): \"\"\" An HTTP",
"at. addr is a (host, port) tuple with explicit values. If any of",
"if httpd.origin is None else httpd.origin sys.stderr.write('Serving HTTP on %s (origin %s)...\\n' %",
"and the handler class. \"\"\" # Named function for better argparse output. def",
"key %r' % (key,)) ret[key] = value return ret def resolve_listen_address(addr, origin, default_addr=None):",
"(defaults to the port from ' 'the origin, or 8080).') p.add_argument('--host', '-s', metavar='IP',",
"# Run it. try: httpd.serve_forever() except KeyboardInterrupt: # Don't print a noisy stack",
"or all interfaces).') p.add_argument('--origin', '-O', type=origin, help='A SCHEME://HOST[:PORT] string indicating how ' 'clients",
"(host, port) def run(handler, server=WSSHTTPServer, prepare=None, postparse=None, premain=None): \"\"\" run(handler, server=WSSHTTPServer, prepare=None, postparse=None,",
"is called immediately before entering the main loop of the internally created server",
"validation, and prevent the creation and running of a server by raising an",
"ultimately listen at. addr is a (host, port) tuple with explicit values. If",
"p.add_argument('--host', '-s', metavar='IP', help='The network interface to bind to (defaults to the '",
"postparse is a callable invoked after parsing arguments (and resolving complex default values)",
"returned by argparse.ArgumentParser. It can be used to pass on the values of",
"if that fails, this ' 'remains unset.') p.add_argument('--tls', '-T', metavar='PARAM=VALUE[,...]', type=tls_flags, help='Enable (mandatory)",
"' 'used by the server; \"key\": The private key file ' 'belonging to",
"' 'belonging to cert (if omitted, the private key is ' 'taken from",
"header message. # Since the server has bound itself when it was contructed",
"origin_string = 'N/A' if httpd.origin is None else httpd.origin sys.stderr.write('Serving HTTP on %s",
"pairs recovered from s. \"\"\" ret = {} for item in s.split(','): if",
"of the internally created server object with two arguments: httpd : The server",
"for default host/port values (if not None; if this is None, default_addr is",
"tuple containing the address to bind to. Constructed from command-line arguments. handler :",
"Resolve complex defaults. arguments.host, arguments.port = resolve_listen_address( (arguments.host, arguments.port), arguments.origin) # Call next",
"prepare=None, postparse=None, premain=None): \"\"\" run(handler, server=WSSHTTPServer, prepare=None, postparse=None, premain=None) -> None Actually run",
"consulted for default host/port values (if not None; if this is None, default_addr",
"handler class to use. server is a callable taking two arguments that creates",
"resolving complex default values) with the resulting arguments object as the only positional",
"WebSocket server instance. handler is the handler class to use. server is a",
"private key file ' 'belonging to cert (if omitted, the private key is",
"server((arguments.host, arguments.port), handler) if arguments.origin: httpd.origin = arguments.origin if arguments.tls: httpd.setup_ssl(arguments.tls) # Print",
"else httpd.origin sys.stderr.write('Serving HTTP on %s (origin %s)...\\n' % (address, origin_string)) sys.stderr.flush() #",
"invoked with the ArgumentParser (from argparse) instance used to parse options as the",
"(if omitted, the private key is ' 'taken from the certificate file); \"ca\":",
"defined: \"cert\": A file ' 'containing X.509 certificate in PEM format, along '",
"the ' 'certificates in this file.') # Call preparation callback. if prepare: prepare(p)",
"%r' % (item,)) if key in ret: raise ValueError('Duplicate key %r' % (key,))",
"that is invoked with the ArgumentParser (from argparse) instance used to parse options",
"Convenience functions for quick usage. \"\"\" import sys import argparse from .server import",
"help='A SCHEME://HOST[:PORT] string indicating how ' 'clients should access this server. If omitted,",
"Returns a dictionary of the key-value pairs recovered from s. \"\"\" ret =",
"an address an HTTP server should ultimately listen at. addr is a (host,",
"is a callable taking two arguments that creates the server instance; the arguments",
"(host, port) tuple with defaults filled in. \"\"\" if default_addr is None: default_addr",
"<filename>websocket_server/quick.py # websocket_server -- WebSocket/HTTP server/client library # https://github.com/CylonicRaider/websocket-server \"\"\" Convenience functions for",
"DEFAULT_ADDRESS constant, viz. ('', 8080). Returns the (host, port) tuple with defaults filled",
"premain=None): \"\"\" run(handler, server=WSSHTTPServer, prepare=None, postparse=None, premain=None) -> None Actually run a WebSocket",
"attempt is made to guess the value from the ' '--host and --port",
"if postparse: postparse(arguments) # Create server. httpd = server((arguments.host, arguments.port), handler) if arguments.origin:",
"item: continue key, sep, value = item.partition('=') if not sep: raise ValueError('Invalid key-value",
"'-O', type=origin, help='A SCHEME://HOST[:PORT] string indicating how ' 'clients should access this server.",
"and running of a server by raising an exception. premain is called immediately",
"def run(handler, server=WSSHTTPServer, prepare=None, postparse=None, premain=None): \"\"\" run(handler, server=WSSHTTPServer, prepare=None, postparse=None, premain=None) ->",
"postparse(arguments) # Create server. httpd = server((arguments.host, arguments.port), handler) if arguments.origin: httpd.origin =",
"# Call final preparation hook. if premain: premain(httpd, arguments) # Run it. try:",
"origin, default_addr=None) -> (host, port) Fill in default host and port values into",
"with the ArgumentParser (from argparse) instance used to parse options as the only",
"\"\"\" Parse a comma-separated key-value list as used for command-line TLS configuration. Returns",
"= arguments.origin if arguments.tls: httpd.setup_ssl(arguments.tls) # Print header message. # Since the server",
"and defaults to the module-level DEFAULT_ADDRESS constant, viz. ('', 8080). Returns the (host,",
"private key is ' 'taken from the certificate file); \"ca\": Require ' 'clients",
"# Actually parse arguments. arguments = p.parse_args() # Resolve complex defaults. arguments.host, arguments.port",
"use. server is a callable taking two arguments that creates the server instance;",
"file ' 'belonging to cert (if omitted, the private key is ' 'taken",
"quick usage. \"\"\" import sys import argparse from .server import WebSocketMixIn from .httpserver",
"functionality. \"\"\" def tls_flags(s): \"\"\" Parse a comma-separated key-value list as used for",
"before entering the main loop of the internally created server object with two",
"WSSHTTPServer, RoutingRequestHandler from .httpserver import validate_origin, parse_origin __all__ = ['DEFAULT_ADDRESS', 'RoutingWebSocketRequestHandler', 'tls_flags', 'resolve_listen_address',",
"that fails, this ' 'remains unset.') p.add_argument('--tls', '-T', metavar='PARAM=VALUE[,...]', type=tls_flags, help='Enable (mandatory) TLS,",
"import WSSHTTPServer, RoutingRequestHandler from .httpserver import validate_origin, parse_origin __all__ = ['DEFAULT_ADDRESS', 'RoutingWebSocketRequestHandler', 'tls_flags',",
"class. \"\"\" # Named function for better argparse output. def origin(s): return validate_origin(s)",
"arguments: The arguments as returned by argparse.ArgumentParser. It can be used to pass",
"httpd.setup_ssl(arguments.tls) # Print header message. # Since the server has bound itself when",
"default_addr = DEFAULT_ADDRESS host, port = addr if origin: default_addr = parse_origin(origin)[1:] if",
"https://github.com/CylonicRaider/websocket-server \"\"\" Convenience functions for quick usage. \"\"\" import sys import argparse from",
"arguments.tls: httpd.setup_ssl(arguments.tls) # Print header message. # Since the server has bound itself",
"it. try: httpd.serve_forever() except KeyboardInterrupt: # Don't print a noisy stack trace if",
"from command-line arguments. handler : The request handler. Passed through from the same-",
"(item,)) if key in ret: raise ValueError('Duplicate key %r' % (key,)) ret[key] =",
"prepare to the server object and the handler class. \"\"\" # Named function",
"parse arguments. arguments = p.parse_args() # Resolve complex defaults. arguments.host, arguments.port = resolve_listen_address(",
"class RoutingWebSocketRequestHandler(RoutingRequestHandler, WebSocketMixIn): \"\"\" An HTTP request handler combining all the package's functionality.",
"'an attempt is made to guess the value from the ' '--host and",
"try: httpd.serve_forever() except KeyboardInterrupt: # Don't print a noisy stack trace if Ctrl+C'ed.",
"class to use. server is a callable taking two arguments that creates the",
"after parsing arguments (and resolving complex default values) with the resulting arguments object",
"= default_addr[1] return (host, port) def run(handler, server=WSSHTTPServer, prepare=None, postparse=None, premain=None): \"\"\" run(handler,",
"'-s', metavar='IP', help='The network interface to bind to (defaults to the ' 'host",
"network interface to bind to (defaults to the ' 'host from the origin,",
"value from the ' '--host and --port parameters; if that fails, this '",
"None: host = default_addr[0] if port is None: port = default_addr[1] return (host,",
"all the package's functionality. \"\"\" def tls_flags(s): \"\"\" Parse a comma-separated key-value list",
"continue key, sep, value = item.partition('=') if not sep: raise ValueError('Invalid key-value pair",
"If any of host or port is None, a default value is derived",
"% (key,)) ret[key] = value return ret def resolve_listen_address(addr, origin, default_addr=None): \"\"\" resolve_listen_address(addr,",
"(if not None; if this is None, default_addr is used instead). default_addr is",
"default_addr[0] if port is None: port = default_addr[1] return (host, port) def run(handler,",
"callable invoked after parsing arguments (and resolving complex default values) with the resulting",
"things like complex validation, and prevent the creation and running of a server",
"__all__ = ['DEFAULT_ADDRESS', 'RoutingWebSocketRequestHandler', 'tls_flags', 'resolve_listen_address', 'run'] DEFAULT_ADDRESS = ('', 8080) class RoutingWebSocketRequestHandler(RoutingRequestHandler,",
"' 'the origin, or 8080).') p.add_argument('--host', '-s', metavar='IP', help='The network interface to bind",
"s.split(','): if not item: continue key, sep, value = item.partition('=') if not sep:",
"necessary, to be ' 'used by the server; \"key\": The private key file",
"is ' 'taken from the certificate file); \"ca\": Require ' 'clients to be",
"or 8080).') p.add_argument('--host', '-s', metavar='IP', help='The network interface to bind to (defaults to",
"return ret def resolve_listen_address(addr, origin, default_addr=None): \"\"\" resolve_listen_address(addr, origin, default_addr=None) -> (host, port)",
"arguments.port) else: address = '*:%s' % arguments.port origin_string = 'N/A' if httpd.origin is",
"pass on the values of the options configured using prepare to the server",
"default_addr=None) -> (host, port) Fill in default host and port values into an",
"for better argparse output. def origin(s): return validate_origin(s) # Parse command-line arguments. p",
"from the origin, or all interfaces).') p.add_argument('--origin', '-O', type=origin, help='A SCHEME://HOST[:PORT] string indicating",
"function for better argparse output. def origin(s): return validate_origin(s) # Parse command-line arguments.",
"functions for quick usage. \"\"\" import sys import argparse from .server import WebSocketMixIn",
"the ultimate fallback (host, port) tuple, and defaults to the module-level DEFAULT_ADDRESS constant,",
"if arguments.host: address = '%s:%s' % (arguments.host, arguments.port) else: address = '*:%s' %",
"or default_addr. origin is a Web origin that is consulted for default host/port",
"--port parameters; if that fails, this ' 'remains unset.') p.add_argument('--tls', '-T', metavar='PARAM=VALUE[,...]', type=tls_flags,",
"the same- named argument of run(). prepare is a callable that is invoked",
"into an address an HTTP server should ultimately listen at. addr is a",
"explicit values. If any of host or port is None, a default value",
"postparse=None, premain=None): \"\"\" run(handler, server=WSSHTTPServer, prepare=None, postparse=None, premain=None) -> None Actually run a",
"by the server; \"key\": The private key file ' 'belonging to cert (if",
"RoutingWebSocketRequestHandler(RoutingRequestHandler, WebSocketMixIn): \"\"\" An HTTP request handler combining all the package's functionality. \"\"\"",
"that creates the server instance; the arguments are: bindaddr: A (host, port) tuple",
"'certificates in this file.') # Call preparation callback. if prepare: prepare(p) # Actually",
"file.') # Call preparation callback. if prepare: prepare(p) # Actually parse arguments. arguments",
"'-p', metavar='PORT', type=int, help='The TCP port to run on (defaults to the port",
"is None: host = default_addr[0] if port is None: port = default_addr[1] return",
"server instance; the arguments are: bindaddr: A (host, port) tuple containing the address",
"bound itself when it was contructed above, we can # insert the final",
"httpd = server((arguments.host, arguments.port), handler) if arguments.origin: httpd.origin = arguments.origin if arguments.tls: httpd.setup_ssl(arguments.tls)",
"to the server object and the handler class. \"\"\" # Named function for",
"for command-line TLS configuration. Returns a dictionary of the key-value pairs recovered from",
"the only argument. Can be used to specify additional options. postparse is a",
"created; an instance of server. arguments: The arguments as returned by argparse.ArgumentParser. It",
"Require ' 'clients to be authenticated by one of the ' 'certificates in",
"the port from ' 'the origin, or 8080).') p.add_argument('--host', '-s', metavar='IP', help='The network",
"origin, or 8080).') p.add_argument('--host', '-s', metavar='IP', help='The network interface to bind to (defaults",
"s. \"\"\" ret = {} for item in s.split(','): if not item: continue",
"as necessary, to be ' 'used by the server; \"key\": The private key",
"if key in ret: raise ValueError('Duplicate key %r' % (key,)) ret[key] = value",
"it. The ' 'following parameters are defined: \"cert\": A file ' 'containing X.509",
"'N/A' if httpd.origin is None else httpd.origin sys.stderr.write('Serving HTTP on %s (origin %s)...\\n'",
"parsing arguments (and resolving complex default values) with the resulting arguments object as",
"def tls_flags(s): \"\"\" Parse a comma-separated key-value list as used for command-line TLS",
"of run(). prepare is a callable that is invoked with the ArgumentParser (from",
"of host or port is None, a default value is derived for it",
"bindaddr: A (host, port) tuple containing the address to bind to. Constructed from",
"prepare is a callable that is invoked with the ArgumentParser (from argparse) instance",
"default_addr is the ultimate fallback (host, port) tuple, and defaults to the module-level",
"('', 8080). Returns the (host, port) tuple with defaults filled in. \"\"\" if",
"None: default_addr = DEFAULT_ADDRESS host, port = addr if origin: default_addr = parse_origin(origin)[1:]",
"interfaces).') p.add_argument('--origin', '-O', type=origin, help='A SCHEME://HOST[:PORT] string indicating how ' 'clients should access",
"'run'] DEFAULT_ADDRESS = ('', 8080) class RoutingWebSocketRequestHandler(RoutingRequestHandler, WebSocketMixIn): \"\"\" An HTTP request handler",
"to be ' 'used by the server; \"key\": The private key file '",
"of a server by raising an exception. premain is called immediately before entering",
"be used to specify additional options. postparse is a callable invoked after parsing",
"ret = {} for item in s.split(','): if not item: continue key, sep,",
"is None, default_addr is used instead). default_addr is the ultimate fallback (host, port)",
"to cert (if omitted, the private key is ' 'taken from the certificate",
"any of host or port is None, a default value is derived for",
"ret def resolve_listen_address(addr, origin, default_addr=None): \"\"\" resolve_listen_address(addr, origin, default_addr=None) -> (host, port) Fill",
"arguments as returned by argparse.ArgumentParser. It can be used to pass on the",
"made to guess the value from the ' '--host and --port parameters; if",
"key, sep, value = item.partition('=') if not sep: raise ValueError('Invalid key-value pair %r'",
"to. Constructed from command-line arguments. handler : The request handler. Passed through from",
"premain=None) -> None Actually run a WebSocket server instance. handler is the handler",
"authenticated by one of the ' 'certificates in this file.') # Call preparation",
"an exception. premain is called immediately before entering the main loop of the",
"is made to guess the value from the ' '--host and --port parameters;",
"the server; \"key\": The private key file ' 'belonging to cert (if omitted,",
"= item.partition('=') if not sep: raise ValueError('Invalid key-value pair %r' % (item,)) if",
"values. If any of host or port is None, a default value is",
"certificate chain as necessary, to be ' 'used by the server; \"key\": The",
"postparse: postparse(arguments) # Create server. httpd = server((arguments.host, arguments.port), handler) if arguments.origin: httpd.origin",
"as the only argument. Can be used to specify additional options. postparse is",
"is the ultimate fallback (host, port) tuple, and defaults to the module-level DEFAULT_ADDRESS",
"if not item: continue key, sep, value = item.partition('=') if not sep: raise",
"= parse_origin(origin)[1:] if host is None: host = default_addr[0] if port is None:",
"from the certificate file); \"ca\": Require ' 'clients to be authenticated by one",
"fails, this ' 'remains unset.') p.add_argument('--tls', '-T', metavar='PARAM=VALUE[,...]', type=tls_flags, help='Enable (mandatory) TLS, and",
"(mandatory) TLS, and configure it. The ' 'following parameters are defined: \"cert\": A",
"message. # Since the server has bound itself when it was contructed above,",
"ArgumentParser (from argparse) instance used to parse options as the only argument. Can",
"exception. premain is called immediately before entering the main loop of the internally",
"The private key file ' 'belonging to cert (if omitted, the private key",
"creates the server instance; the arguments are: bindaddr: A (host, port) tuple containing",
"is used instead). default_addr is the ultimate fallback (host, port) tuple, and defaults",
"preparation callback. if prepare: prepare(p) # Actually parse arguments. arguments = p.parse_args() #",
"ultimate fallback (host, port) tuple, and defaults to the module-level DEFAULT_ADDRESS constant, viz.",
"argparse) instance used to parse options as the only argument. Can be used",
"(from argparse) instance used to parse options as the only argument. Can be",
"a callable that is invoked with the ArgumentParser (from argparse) instance used to",
"'containing X.509 certificate in PEM format, along ' 'with a CA certificate chain",
"def origin(s): return validate_origin(s) # Parse command-line arguments. p = argparse.ArgumentParser() p.add_argument('--port', '-p',",
"port to run on (defaults to the port from ' 'the origin, or",
"resolve_listen_address(addr, origin, default_addr=None): \"\"\" resolve_listen_address(addr, origin, default_addr=None) -> (host, port) Fill in default",
"arguments.port = resolve_listen_address( (arguments.host, arguments.port), arguments.origin) # Call next preparation callback. if postparse:",
"to pass on the values of the options configured using prepare to the",
"origin: default_addr = parse_origin(origin)[1:] if host is None: host = default_addr[0] if port",
"= '*:%s' % arguments.port origin_string = 'N/A' if httpd.origin is None else httpd.origin",
"from .httpserver import validate_origin, parse_origin __all__ = ['DEFAULT_ADDRESS', 'RoutingWebSocketRequestHandler', 'tls_flags', 'resolve_listen_address', 'run'] DEFAULT_ADDRESS",
"prepare(p) # Actually parse arguments. arguments = p.parse_args() # Resolve complex defaults. arguments.host,",
"sep, value = item.partition('=') if not sep: raise ValueError('Invalid key-value pair %r' %",
"{} for item in s.split(','): if not item: continue key, sep, value =",
"%r' % (key,)) ret[key] = value return ret def resolve_listen_address(addr, origin, default_addr=None): \"\"\"",
"the only positional argument. It can do things like complex validation, and prevent",
"None: port = default_addr[1] return (host, port) def run(handler, server=WSSHTTPServer, prepare=None, postparse=None, premain=None):",
"item.partition('=') if not sep: raise ValueError('Invalid key-value pair %r' % (item,)) if key",
"request handler. Passed through from the same- named argument of run(). prepare is",
"type=origin, help='A SCHEME://HOST[:PORT] string indicating how ' 'clients should access this server. If",
"p.parse_args() # Resolve complex defaults. arguments.host, arguments.port = resolve_listen_address( (arguments.host, arguments.port), arguments.origin) #",
"An HTTP request handler combining all the package's functionality. \"\"\" def tls_flags(s): \"\"\"",
"import argparse from .server import WebSocketMixIn from .httpserver import WSSHTTPServer, RoutingRequestHandler from .httpserver",
"argparse.ArgumentParser. It can be used to pass on the values of the options",
"contructed above, we can # insert the final origin value. if arguments.host: address",
"' 'clients should access this server. If omitted, ' 'an attempt is made",
"to run on (defaults to the port from ' 'the origin, or 8080).')",
"% (address, origin_string)) sys.stderr.flush() # Call final preparation hook. if premain: premain(httpd, arguments)",
"ret: raise ValueError('Duplicate key %r' % (key,)) ret[key] = value return ret def",
"host is None: host = default_addr[0] if port is None: port = default_addr[1]",
"(key,)) ret[key] = value return ret def resolve_listen_address(addr, origin, default_addr=None): \"\"\" resolve_listen_address(addr, origin,",
"import WebSocketMixIn from .httpserver import WSSHTTPServer, RoutingRequestHandler from .httpserver import validate_origin, parse_origin __all__",
"(host, port) tuple with explicit values. If any of host or port is",
"'-T', metavar='PARAM=VALUE[,...]', type=tls_flags, help='Enable (mandatory) TLS, and configure it. The ' 'following parameters",
"if not sep: raise ValueError('Invalid key-value pair %r' % (item,)) if key in",
"Constructed from command-line arguments. handler : The request handler. Passed through from the",
"output. def origin(s): return validate_origin(s) # Parse command-line arguments. p = argparse.ArgumentParser() p.add_argument('--port',",
"' 'clients to be authenticated by one of the ' 'certificates in this",
"parse_origin(origin)[1:] if host is None: host = default_addr[0] if port is None: port",
"address to bind to. Constructed from command-line arguments. handler : The request handler.",
"'*:%s' % arguments.port origin_string = 'N/A' if httpd.origin is None else httpd.origin sys.stderr.write('Serving",
"Parse a comma-separated key-value list as used for command-line TLS configuration. Returns a",
"with the resulting arguments object as the only positional argument. It can do",
"constant, viz. ('', 8080). Returns the (host, port) tuple with defaults filled in.",
"in this file.') # Call preparation callback. if prepare: prepare(p) # Actually parse",
"'host from the origin, or all interfaces).') p.add_argument('--origin', '-O', type=origin, help='A SCHEME://HOST[:PORT] string",
"' 'host from the origin, or all interfaces).') p.add_argument('--origin', '-O', type=origin, help='A SCHEME://HOST[:PORT]",
"' 'remains unset.') p.add_argument('--tls', '-T', metavar='PARAM=VALUE[,...]', type=tls_flags, help='Enable (mandatory) TLS, and configure it.",
"server; \"key\": The private key file ' 'belonging to cert (if omitted, the",
"tls_flags(s): \"\"\" Parse a comma-separated key-value list as used for command-line TLS configuration.",
"omitted, the private key is ' 'taken from the certificate file); \"ca\": Require",
"default_addr is None: default_addr = DEFAULT_ADDRESS host, port = addr if origin: default_addr",
"% (item,)) if key in ret: raise ValueError('Duplicate key %r' % (key,)) ret[key]",
"additional options. postparse is a callable invoked after parsing arguments (and resolving complex",
"insert the final origin value. if arguments.host: address = '%s:%s' % (arguments.host, arguments.port)",
"complex defaults. arguments.host, arguments.port = resolve_listen_address( (arguments.host, arguments.port), arguments.origin) # Call next preparation",
"if arguments.origin: httpd.origin = arguments.origin if arguments.tls: httpd.setup_ssl(arguments.tls) # Print header message. #",
"arguments. handler : The request handler. Passed through from the same- named argument",
"The arguments as returned by argparse.ArgumentParser. It can be used to pass on",
"same- named argument of run(). prepare is a callable that is invoked with",
"the internally created server object with two arguments: httpd : The server object",
"the value from the ' '--host and --port parameters; if that fails, this",
"we can # insert the final origin value. if arguments.host: address = '%s:%s'",
"is None: default_addr = DEFAULT_ADDRESS host, port = addr if origin: default_addr =",
"'%s:%s' % (arguments.host, arguments.port) else: address = '*:%s' % arguments.port origin_string = 'N/A'",
"Call final preparation hook. if premain: premain(httpd, arguments) # Run it. try: httpd.serve_forever()",
"'clients should access this server. If omitted, ' 'an attempt is made to",
"if premain: premain(httpd, arguments) # Run it. try: httpd.serve_forever() except KeyboardInterrupt: # Don't",
"are defined: \"cert\": A file ' 'containing X.509 certificate in PEM format, along",
"The request handler. Passed through from the same- named argument of run(). prepare",
"httpd.origin = arguments.origin if arguments.tls: httpd.setup_ssl(arguments.tls) # Print header message. # Since the",
"port = addr if origin: default_addr = parse_origin(origin)[1:] if host is None: host",
"\"key\": The private key file ' 'belonging to cert (if omitted, the private",
"None Actually run a WebSocket server instance. handler is the handler class to",
"entering the main loop of the internally created server object with two arguments:",
"is a callable that is invoked with the ArgumentParser (from argparse) instance used",
"item in s.split(','): if not item: continue key, sep, value = item.partition('=') if",
"as returned by argparse.ArgumentParser. It can be used to pass on the values",
"tuple with defaults filled in. \"\"\" if default_addr is None: default_addr = DEFAULT_ADDRESS",
"arguments: httpd : The server object created; an instance of server. arguments: The",
"the server instance; the arguments are: bindaddr: A (host, port) tuple containing the",
"'remains unset.') p.add_argument('--tls', '-T', metavar='PARAM=VALUE[,...]', type=tls_flags, help='Enable (mandatory) TLS, and configure it. The",
"(origin %s)...\\n' % (address, origin_string)) sys.stderr.flush() # Call final preparation hook. if premain:",
"server=WSSHTTPServer, prepare=None, postparse=None, premain=None) -> None Actually run a WebSocket server instance. handler",
"-> (host, port) Fill in default host and port values into an address",
"server. If omitted, ' 'an attempt is made to guess the value from",
"to the module-level DEFAULT_ADDRESS constant, viz. ('', 8080). Returns the (host, port) tuple",
"module-level DEFAULT_ADDRESS constant, viz. ('', 8080). Returns the (host, port) tuple with defaults",
"callback. if postparse: postparse(arguments) # Create server. httpd = server((arguments.host, arguments.port), handler) if",
"arguments. arguments = p.parse_args() # Resolve complex defaults. arguments.host, arguments.port = resolve_listen_address( (arguments.host,",
"address = '%s:%s' % (arguments.host, arguments.port) else: address = '*:%s' % arguments.port origin_string",
"premain: premain(httpd, arguments) # Run it. try: httpd.serve_forever() except KeyboardInterrupt: # Don't print",
"\"\"\" def tls_flags(s): \"\"\" Parse a comma-separated key-value list as used for command-line",
"to the port from ' 'the origin, or 8080).') p.add_argument('--host', '-s', metavar='IP', help='The",
"# Named function for better argparse output. def origin(s): return validate_origin(s) # Parse",
"tuple with explicit values. If any of host or port is None, a",
"p.add_argument('--port', '-p', metavar='PORT', type=int, help='The TCP port to run on (defaults to the",
"through from the same- named argument of run(). prepare is a callable that",
"from s. \"\"\" ret = {} for item in s.split(','): if not item:",
"if arguments.tls: httpd.setup_ssl(arguments.tls) # Print header message. # Since the server has bound",
"host and port values into an address an HTTP server should ultimately listen",
"# https://github.com/CylonicRaider/websocket-server \"\"\" Convenience functions for quick usage. \"\"\" import sys import argparse",
"'clients to be authenticated by one of the ' 'certificates in this file.')",
"host/port values (if not None; if this is None, default_addr is used instead).",
"raise ValueError('Invalid key-value pair %r' % (item,)) if key in ret: raise ValueError('Duplicate",
"should access this server. If omitted, ' 'an attempt is made to guess",
"usage. \"\"\" import sys import argparse from .server import WebSocketMixIn from .httpserver import",
"= default_addr[0] if port is None: port = default_addr[1] return (host, port) def",
"two arguments that creates the server instance; the arguments are: bindaddr: A (host,",
"preparation hook. if premain: premain(httpd, arguments) # Run it. try: httpd.serve_forever() except KeyboardInterrupt:",
"arguments.origin: httpd.origin = arguments.origin if arguments.tls: httpd.setup_ssl(arguments.tls) # Print header message. # Since",
"arguments) # Run it. try: httpd.serve_forever() except KeyboardInterrupt: # Don't print a noisy",
"callable taking two arguments that creates the server instance; the arguments are: bindaddr:",
"# Call next preparation callback. if postparse: postparse(arguments) # Create server. httpd =",
"Named function for better argparse output. def origin(s): return validate_origin(s) # Parse command-line",
"default host/port values (if not None; if this is None, default_addr is used",
"all interfaces).') p.add_argument('--origin', '-O', type=origin, help='A SCHEME://HOST[:PORT] string indicating how ' 'clients should",
"sep: raise ValueError('Invalid key-value pair %r' % (item,)) if key in ret: raise",
"can be used to pass on the values of the options configured using",
"file ' 'containing X.509 certificate in PEM format, along ' 'with a CA",
"server=WSSHTTPServer, prepare=None, postparse=None, premain=None): \"\"\" run(handler, server=WSSHTTPServer, prepare=None, postparse=None, premain=None) -> None Actually",
"addr is a (host, port) tuple with explicit values. If any of host",
"command-line arguments. p = argparse.ArgumentParser() p.add_argument('--port', '-p', metavar='PORT', type=int, help='The TCP port to",
"It can do things like complex validation, and prevent the creation and running",
"options. postparse is a callable invoked after parsing arguments (and resolving complex default",
"default_addr. origin is a Web origin that is consulted for default host/port values",
"arguments.port origin_string = 'N/A' if httpd.origin is None else httpd.origin sys.stderr.write('Serving HTTP on",
"derived for it from origin or default_addr. origin is a Web origin that",
"TCP port to run on (defaults to the port from ' 'the origin,",
"final origin value. if arguments.host: address = '%s:%s' % (arguments.host, arguments.port) else: address",
"'--host and --port parameters; if that fails, this ' 'remains unset.') p.add_argument('--tls', '-T',",
"in PEM format, along ' 'with a CA certificate chain as necessary, to",
"internally created server object with two arguments: httpd : The server object created;",
"metavar='PARAM=VALUE[,...]', type=tls_flags, help='Enable (mandatory) TLS, and configure it. The ' 'following parameters are",
"the options configured using prepare to the server object and the handler class.",
"using prepare to the server object and the handler class. \"\"\" # Named",
"the package's functionality. \"\"\" def tls_flags(s): \"\"\" Parse a comma-separated key-value list as",
"WebSocketMixIn from .httpserver import WSSHTTPServer, RoutingRequestHandler from .httpserver import validate_origin, parse_origin __all__ =",
"None; if this is None, default_addr is used instead). default_addr is the ultimate",
"Web origin that is consulted for default host/port values (if not None; if",
"command-line arguments. handler : The request handler. Passed through from the same- named",
"when it was contructed above, we can # insert the final origin value.",
"is a Web origin that is consulted for default host/port values (if not",
"port) tuple containing the address to bind to. Constructed from command-line arguments. handler",
"chain as necessary, to be ' 'used by the server; \"key\": The private",
"containing the address to bind to. Constructed from command-line arguments. handler : The",
"on the values of the options configured using prepare to the server object",
"prevent the creation and running of a server by raising an exception. premain",
"key-value pair %r' % (item,)) if key in ret: raise ValueError('Duplicate key %r'",
"= server((arguments.host, arguments.port), handler) if arguments.origin: httpd.origin = arguments.origin if arguments.tls: httpd.setup_ssl(arguments.tls) #",
"raising an exception. premain is called immediately before entering the main loop of",
"default values) with the resulting arguments object as the only positional argument. It",
"server instance. handler is the handler class to use. server is a callable",
"The server object created; an instance of server. arguments: The arguments as returned",
"values of the options configured using prepare to the server object and the",
"a CA certificate chain as necessary, to be ' 'used by the server;",
"the certificate file); \"ca\": Require ' 'clients to be authenticated by one of",
"instance; the arguments are: bindaddr: A (host, port) tuple containing the address to",
"and port values into an address an HTTP server should ultimately listen at.",
"defaults. arguments.host, arguments.port = resolve_listen_address( (arguments.host, arguments.port), arguments.origin) # Call next preparation callback.",
"like complex validation, and prevent the creation and running of a server by",
"the server object and the handler class. \"\"\" # Named function for better",
"\"\"\" import sys import argparse from .server import WebSocketMixIn from .httpserver import WSSHTTPServer,",
"arguments (and resolving complex default values) with the resulting arguments object as the",
"if prepare: prepare(p) # Actually parse arguments. arguments = p.parse_args() # Resolve complex",
"creation and running of a server by raising an exception. premain is called",
"-> None Actually run a WebSocket server instance. handler is the handler class",
"argparse output. def origin(s): return validate_origin(s) # Parse command-line arguments. p = argparse.ArgumentParser()",
"in. \"\"\" if default_addr is None: default_addr = DEFAULT_ADDRESS host, port = addr",
"if port is None: port = default_addr[1] return (host, port) def run(handler, server=WSSHTTPServer,",
"(host, port) Fill in default host and port values into an address an",
"host, port = addr if origin: default_addr = parse_origin(origin)[1:] if host is None:",
"the handler class. \"\"\" # Named function for better argparse output. def origin(s):",
"arguments.origin if arguments.tls: httpd.setup_ssl(arguments.tls) # Print header message. # Since the server has",
"(and resolving complex default values) with the resulting arguments object as the only",
"None else httpd.origin sys.stderr.write('Serving HTTP on %s (origin %s)...\\n' % (address, origin_string)) sys.stderr.flush()",
"taking two arguments that creates the server instance; the arguments are: bindaddr: A",
"be ' 'used by the server; \"key\": The private key file ' 'belonging",
"port) tuple with defaults filled in. \"\"\" if default_addr is None: default_addr =",
"is None, a default value is derived for it from origin or default_addr.",
"instance of server. arguments: The arguments as returned by argparse.ArgumentParser. It can be",
"['DEFAULT_ADDRESS', 'RoutingWebSocketRequestHandler', 'tls_flags', 'resolve_listen_address', 'run'] DEFAULT_ADDRESS = ('', 8080) class RoutingWebSocketRequestHandler(RoutingRequestHandler, WebSocketMixIn): \"\"\"",
"the ArgumentParser (from argparse) instance used to parse options as the only argument.",
"the final origin value. if arguments.host: address = '%s:%s' % (arguments.host, arguments.port) else:",
"\"\"\" resolve_listen_address(addr, origin, default_addr=None) -> (host, port) Fill in default host and port",
"request handler combining all the package's functionality. \"\"\" def tls_flags(s): \"\"\" Parse a",
"a callable invoked after parsing arguments (and resolving complex default values) with the",
"bind to (defaults to the ' 'host from the origin, or all interfaces).')",
"loop of the internally created server object with two arguments: httpd : The",
"It can be used to pass on the values of the options configured",
"if origin: default_addr = parse_origin(origin)[1:] if host is None: host = default_addr[0] if",
"# websocket_server -- WebSocket/HTTP server/client library # https://github.com/CylonicRaider/websocket-server \"\"\" Convenience functions for quick",
"the address to bind to. Constructed from command-line arguments. handler : The request",
"parameters; if that fails, this ' 'remains unset.') p.add_argument('--tls', '-T', metavar='PARAM=VALUE[,...]', type=tls_flags, help='Enable",
"viz. ('', 8080). Returns the (host, port) tuple with defaults filled in. \"\"\"",
"RoutingRequestHandler from .httpserver import validate_origin, parse_origin __all__ = ['DEFAULT_ADDRESS', 'RoutingWebSocketRequestHandler', 'tls_flags', 'resolve_listen_address', 'run']",
"by one of the ' 'certificates in this file.') # Call preparation callback.",
"= value return ret def resolve_listen_address(addr, origin, default_addr=None): \"\"\" resolve_listen_address(addr, origin, default_addr=None) ->",
"If omitted, ' 'an attempt is made to guess the value from the",
"# Resolve complex defaults. arguments.host, arguments.port = resolve_listen_address( (arguments.host, arguments.port), arguments.origin) # Call",
"with defaults filled in. \"\"\" if default_addr is None: default_addr = DEFAULT_ADDRESS host,",
"arguments. p = argparse.ArgumentParser() p.add_argument('--port', '-p', metavar='PORT', type=int, help='The TCP port to run",
"Can be used to specify additional options. postparse is a callable invoked after",
"library # https://github.com/CylonicRaider/websocket-server \"\"\" Convenience functions for quick usage. \"\"\" import sys import",
"resolve_listen_address(addr, origin, default_addr=None) -> (host, port) Fill in default host and port values",
"and configure it. The ' 'following parameters are defined: \"cert\": A file '",
"specify additional options. postparse is a callable invoked after parsing arguments (and resolving",
"8080).') p.add_argument('--host', '-s', metavar='IP', help='The network interface to bind to (defaults to the",
"\"ca\": Require ' 'clients to be authenticated by one of the ' 'certificates",
"origin_string)) sys.stderr.flush() # Call final preparation hook. if premain: premain(httpd, arguments) # Run",
"' 'taken from the certificate file); \"ca\": Require ' 'clients to be authenticated",
"list as used for command-line TLS configuration. Returns a dictionary of the key-value",
"from the same- named argument of run(). prepare is a callable that is",
"positional argument. It can do things like complex validation, and prevent the creation",
"premain(httpd, arguments) # Run it. try: httpd.serve_forever() except KeyboardInterrupt: # Don't print a",
"origin, default_addr=None): \"\"\" resolve_listen_address(addr, origin, default_addr=None) -> (host, port) Fill in default host",
"of the ' 'certificates in this file.') # Call preparation callback. if prepare:",
"prepare: prepare(p) # Actually parse arguments. arguments = p.parse_args() # Resolve complex defaults.",
"final preparation hook. if premain: premain(httpd, arguments) # Run it. try: httpd.serve_forever() except",
"port from ' 'the origin, or 8080).') p.add_argument('--host', '-s', metavar='IP', help='The network interface",
"return validate_origin(s) # Parse command-line arguments. p = argparse.ArgumentParser() p.add_argument('--port', '-p', metavar='PORT', type=int,",
"in default host and port values into an address an HTTP server should",
"import validate_origin, parse_origin __all__ = ['DEFAULT_ADDRESS', 'RoutingWebSocketRequestHandler', 'tls_flags', 'resolve_listen_address', 'run'] DEFAULT_ADDRESS = ('',",
"object as the only positional argument. It can do things like complex validation,",
"values into an address an HTTP server should ultimately listen at. addr is",
"values) with the resulting arguments object as the only positional argument. It can",
"None, a default value is derived for it from origin or default_addr. origin",
"the resulting arguments object as the only positional argument. It can do things",
"has bound itself when it was contructed above, we can # insert the",
"of the key-value pairs recovered from s. \"\"\" ret = {} for item",
"complex validation, and prevent the creation and running of a server by raising",
"(arguments.host, arguments.port) else: address = '*:%s' % arguments.port origin_string = 'N/A' if httpd.origin",
"Returns the (host, port) tuple with defaults filled in. \"\"\" if default_addr is",
"the ' 'host from the origin, or all interfaces).') p.add_argument('--origin', '-O', type=origin, help='A",
"for quick usage. \"\"\" import sys import argparse from .server import WebSocketMixIn from",
"(defaults to the ' 'host from the origin, or all interfaces).') p.add_argument('--origin', '-O',",
"prepare=None, postparse=None, premain=None) -> None Actually run a WebSocket server instance. handler is",
"immediately before entering the main loop of the internally created server object with",
"callable that is invoked with the ArgumentParser (from argparse) instance used to parse",
"file); \"ca\": Require ' 'clients to be authenticated by one of the '",
"= addr if origin: default_addr = parse_origin(origin)[1:] if host is None: host =",
"in ret: raise ValueError('Duplicate key %r' % (key,)) ret[key] = value return ret",
"main loop of the internally created server object with two arguments: httpd :",
"instance. handler is the handler class to use. server is a callable taking",
"sys import argparse from .server import WebSocketMixIn from .httpserver import WSSHTTPServer, RoutingRequestHandler from",
"default_addr is used instead). default_addr is the ultimate fallback (host, port) tuple, and",
"from .httpserver import WSSHTTPServer, RoutingRequestHandler from .httpserver import validate_origin, parse_origin __all__ = ['DEFAULT_ADDRESS',",
"handler : The request handler. Passed through from the same- named argument of",
"handler combining all the package's functionality. \"\"\" def tls_flags(s): \"\"\" Parse a comma-separated",
"Passed through from the same- named argument of run(). prepare is a callable",
"run a WebSocket server instance. handler is the handler class to use. server",
"format, along ' 'with a CA certificate chain as necessary, to be '",
"options as the only argument. Can be used to specify additional options. postparse",
"parameters are defined: \"cert\": A file ' 'containing X.509 certificate in PEM format,",
"of the options configured using prepare to the server object and the handler",
"\"\"\" if default_addr is None: default_addr = DEFAULT_ADDRESS host, port = addr if",
"a WebSocket server instance. handler is the handler class to use. server is",
"used to parse options as the only argument. Can be used to specify",
"# Since the server has bound itself when it was contructed above, we",
"p.add_argument('--tls', '-T', metavar='PARAM=VALUE[,...]', type=tls_flags, help='Enable (mandatory) TLS, and configure it. The ' 'following",
"a default value is derived for it from origin or default_addr. origin is",
"is invoked with the ArgumentParser (from argparse) instance used to parse options as",
"above, we can # insert the final origin value. if arguments.host: address =",
"%s)...\\n' % (address, origin_string)) sys.stderr.flush() # Call final preparation hook. if premain: premain(httpd,",
"TLS configuration. Returns a dictionary of the key-value pairs recovered from s. \"\"\"",
"a server by raising an exception. premain is called immediately before entering the",
"certificate file); \"ca\": Require ' 'clients to be authenticated by one of the",
"'belonging to cert (if omitted, the private key is ' 'taken from the",
"not None; if this is None, default_addr is used instead). default_addr is the",
"arguments.port), arguments.origin) # Call next preparation callback. if postparse: postparse(arguments) # Create server.",
"from the ' '--host and --port parameters; if that fails, this ' 'remains",
"8080) class RoutingWebSocketRequestHandler(RoutingRequestHandler, WebSocketMixIn): \"\"\" An HTTP request handler combining all the package's",
"better argparse output. def origin(s): return validate_origin(s) # Parse command-line arguments. p =",
"return (host, port) def run(handler, server=WSSHTTPServer, prepare=None, postparse=None, premain=None): \"\"\" run(handler, server=WSSHTTPServer, prepare=None,",
"command-line TLS configuration. Returns a dictionary of the key-value pairs recovered from s.",
"key is ' 'taken from the certificate file); \"ca\": Require ' 'clients to",
"help='Enable (mandatory) TLS, and configure it. The ' 'following parameters are defined: \"cert\":",
"origin(s): return validate_origin(s) # Parse command-line arguments. p = argparse.ArgumentParser() p.add_argument('--port', '-p', metavar='PORT',",
"help='The network interface to bind to (defaults to the ' 'host from the",
"with two arguments: httpd : The server object created; an instance of server.",
"Call next preparation callback. if postparse: postparse(arguments) # Create server. httpd = server((arguments.host,",
"SCHEME://HOST[:PORT] string indicating how ' 'clients should access this server. If omitted, '",
"metavar='PORT', type=int, help='The TCP port to run on (defaults to the port from",
"resulting arguments object as the only positional argument. It can do things like",
"# Create server. httpd = server((arguments.host, arguments.port), handler) if arguments.origin: httpd.origin = arguments.origin",
"(arguments.host, arguments.port), arguments.origin) # Call next preparation callback. if postparse: postparse(arguments) # Create",
"defaults to the module-level DEFAULT_ADDRESS constant, viz. ('', 8080). Returns the (host, port)",
"value return ret def resolve_listen_address(addr, origin, default_addr=None): \"\"\" resolve_listen_address(addr, origin, default_addr=None) -> (host,",
"handler. Passed through from the same- named argument of run(). prepare is a",
"created server object with two arguments: httpd : The server object created; an",
"listen at. addr is a (host, port) tuple with explicit values. If any",
"are: bindaddr: A (host, port) tuple containing the address to bind to. Constructed",
"for it from origin or default_addr. origin is a Web origin that is",
"is None: port = default_addr[1] return (host, port) def run(handler, server=WSSHTTPServer, prepare=None, postparse=None,",
"\"\"\" # Named function for better argparse output. def origin(s): return validate_origin(s) #",
"arguments.host, arguments.port = resolve_listen_address( (arguments.host, arguments.port), arguments.origin) # Call next preparation callback. if",
"'following parameters are defined: \"cert\": A file ' 'containing X.509 certificate in PEM",
"configure it. The ' 'following parameters are defined: \"cert\": A file ' 'containing",
"Fill in default host and port values into an address an HTTP server",
"arguments are: bindaddr: A (host, port) tuple containing the address to bind to.",
"from origin or default_addr. origin is a Web origin that is consulted for",
"address an HTTP server should ultimately listen at. addr is a (host, port)",
"defaults filled in. \"\"\" if default_addr is None: default_addr = DEFAULT_ADDRESS host, port",
"unset.') p.add_argument('--tls', '-T', metavar='PARAM=VALUE[,...]', type=tls_flags, help='Enable (mandatory) TLS, and configure it. The '",
"filled in. \"\"\" if default_addr is None: default_addr = DEFAULT_ADDRESS host, port =",
"is derived for it from origin or default_addr. origin is a Web origin",
"the handler class to use. server is a callable taking two arguments that",
"server object created; an instance of server. arguments: The arguments as returned by",
"HTTP on %s (origin %s)...\\n' % (address, origin_string)) sys.stderr.flush() # Call final preparation",
"WebSocketMixIn): \"\"\" An HTTP request handler combining all the package's functionality. \"\"\" def",
"address = '*:%s' % arguments.port origin_string = 'N/A' if httpd.origin is None else",
".httpserver import validate_origin, parse_origin __all__ = ['DEFAULT_ADDRESS', 'RoutingWebSocketRequestHandler', 'tls_flags', 'resolve_listen_address', 'run'] DEFAULT_ADDRESS =",
"\"\"\" run(handler, server=WSSHTTPServer, prepare=None, postparse=None, premain=None) -> None Actually run a WebSocket server",
"on (defaults to the port from ' 'the origin, or 8080).') p.add_argument('--host', '-s',",
"fallback (host, port) tuple, and defaults to the module-level DEFAULT_ADDRESS constant, viz. ('',",
"default host and port values into an address an HTTP server should ultimately",
"for item in s.split(','): if not item: continue key, sep, value = item.partition('=')",
"(host, port) tuple containing the address to bind to. Constructed from command-line arguments.",
"('', 8080) class RoutingWebSocketRequestHandler(RoutingRequestHandler, WebSocketMixIn): \"\"\" An HTTP request handler combining all the",
"server object with two arguments: httpd : The server object created; an instance",
"run(handler, server=WSSHTTPServer, prepare=None, postparse=None, premain=None) -> None Actually run a WebSocket server instance.",
"along ' 'with a CA certificate chain as necessary, to be ' 'used",
"Print header message. # Since the server has bound itself when it was",
"from ' 'the origin, or 8080).') p.add_argument('--host', '-s', metavar='IP', help='The network interface to",
"can # insert the final origin value. if arguments.host: address = '%s:%s' %",
"is the handler class to use. server is a callable taking two arguments",
"an instance of server. arguments: The arguments as returned by argparse.ArgumentParser. It can",
"type=tls_flags, help='Enable (mandatory) TLS, and configure it. The ' 'following parameters are defined:",
"argument of run(). prepare is a callable that is invoked with the ArgumentParser",
"server. arguments: The arguments as returned by argparse.ArgumentParser. It can be used to",
"-- WebSocket/HTTP server/client library # https://github.com/CylonicRaider/websocket-server \"\"\" Convenience functions for quick usage. \"\"\"",
"cert (if omitted, the private key is ' 'taken from the certificate file);",
"server should ultimately listen at. addr is a (host, port) tuple with explicit",
"sys.stderr.write('Serving HTTP on %s (origin %s)...\\n' % (address, origin_string)) sys.stderr.flush() # Call final",
"named argument of run(). prepare is a callable that is invoked with the",
".httpserver import WSSHTTPServer, RoutingRequestHandler from .httpserver import validate_origin, parse_origin __all__ = ['DEFAULT_ADDRESS', 'RoutingWebSocketRequestHandler',",
"value is derived for it from origin or default_addr. origin is a Web",
"handler is the handler class to use. server is a callable taking two",
"Call preparation callback. if prepare: prepare(p) # Actually parse arguments. arguments = p.parse_args()",
"port = default_addr[1] return (host, port) def run(handler, server=WSSHTTPServer, prepare=None, postparse=None, premain=None): \"\"\"",
"server object and the handler class. \"\"\" # Named function for better argparse",
"if default_addr is None: default_addr = DEFAULT_ADDRESS host, port = addr if origin:",
"else: address = '*:%s' % arguments.port origin_string = 'N/A' if httpd.origin is None",
"host = default_addr[0] if port is None: port = default_addr[1] return (host, port)",
"arguments.port), handler) if arguments.origin: httpd.origin = arguments.origin if arguments.tls: httpd.setup_ssl(arguments.tls) # Print header",
"(host, port) tuple, and defaults to the module-level DEFAULT_ADDRESS constant, viz. ('', 8080).",
"' 'an attempt is made to guess the value from the ' '--host",
"port) Fill in default host and port values into an address an HTTP",
"to parse options as the only argument. Can be used to specify additional",
"ret[key] = value return ret def resolve_listen_address(addr, origin, default_addr=None): \"\"\" resolve_listen_address(addr, origin, default_addr=None)",
"Create server. httpd = server((arguments.host, arguments.port), handler) if arguments.origin: httpd.origin = arguments.origin if",
"arguments = p.parse_args() # Resolve complex defaults. arguments.host, arguments.port = resolve_listen_address( (arguments.host, arguments.port),",
"to bind to (defaults to the ' 'host from the origin, or all",
"TLS, and configure it. The ' 'following parameters are defined: \"cert\": A file",
"run(). prepare is a callable that is invoked with the ArgumentParser (from argparse)",
"the private key is ' 'taken from the certificate file); \"ca\": Require '",
"arguments object as the only positional argument. It can do things like complex",
"server has bound itself when it was contructed above, we can # insert",
"' 'with a CA certificate chain as necessary, to be ' 'used by",
"= p.parse_args() # Resolve complex defaults. arguments.host, arguments.port = resolve_listen_address( (arguments.host, arguments.port), arguments.origin)",
"metavar='IP', help='The network interface to bind to (defaults to the ' 'host from",
"HTTP server should ultimately listen at. addr is a (host, port) tuple with",
"8080). Returns the (host, port) tuple with defaults filled in. \"\"\" if default_addr",
"indicating how ' 'clients should access this server. If omitted, ' 'an attempt",
"A (host, port) tuple containing the address to bind to. Constructed from command-line",
"bind to. Constructed from command-line arguments. handler : The request handler. Passed through",
"httpd.origin is None else httpd.origin sys.stderr.write('Serving HTTP on %s (origin %s)...\\n' % (address,",
"access this server. If omitted, ' 'an attempt is made to guess the",
"configuration. Returns a dictionary of the key-value pairs recovered from s. \"\"\" ret",
"Actually parse arguments. arguments = p.parse_args() # Resolve complex defaults. arguments.host, arguments.port =",
"callback. if prepare: prepare(p) # Actually parse arguments. arguments = p.parse_args() # Resolve",
"package's functionality. \"\"\" def tls_flags(s): \"\"\" Parse a comma-separated key-value list as used",
"is None else httpd.origin sys.stderr.write('Serving HTTP on %s (origin %s)...\\n' % (address, origin_string))",
"origin that is consulted for default host/port values (if not None; if this",
"dictionary of the key-value pairs recovered from s. \"\"\" ret = {} for",
"DEFAULT_ADDRESS host, port = addr if origin: default_addr = parse_origin(origin)[1:] if host is",
"be used to pass on the values of the options configured using prepare",
"key in ret: raise ValueError('Duplicate key %r' % (key,)) ret[key] = value return",
"WebSocket/HTTP server/client library # https://github.com/CylonicRaider/websocket-server \"\"\" Convenience functions for quick usage. \"\"\" import",
"only argument. Can be used to specify additional options. postparse is a callable",
"default_addr[1] return (host, port) def run(handler, server=WSSHTTPServer, prepare=None, postparse=None, premain=None): \"\"\" run(handler, server=WSSHTTPServer,",
"'with a CA certificate chain as necessary, to be ' 'used by the",
"used for command-line TLS configuration. Returns a dictionary of the key-value pairs recovered",
"certificate in PEM format, along ' 'with a CA certificate chain as necessary,",
"'used by the server; \"key\": The private key file ' 'belonging to cert",
"instance used to parse options as the only argument. Can be used to",
"and prevent the creation and running of a server by raising an exception.",
"port is None: port = default_addr[1] return (host, port) def run(handler, server=WSSHTTPServer, prepare=None,",
"\"cert\": A file ' 'containing X.509 certificate in PEM format, along ' 'with",
"is consulted for default host/port values (if not None; if this is None,",
"not item: continue key, sep, value = item.partition('=') if not sep: raise ValueError('Invalid",
"premain is called immediately before entering the main loop of the internally created",
"object created; an instance of server. arguments: The arguments as returned by argparse.ArgumentParser.",
"arguments.origin) # Call next preparation callback. if postparse: postparse(arguments) # Create server. httpd",
"running of a server by raising an exception. premain is called immediately before",
"server by raising an exception. premain is called immediately before entering the main",
"postparse=None, premain=None) -> None Actually run a WebSocket server instance. handler is the",
"recovered from s. \"\"\" ret = {} for item in s.split(','): if not",
"= ('', 8080) class RoutingWebSocketRequestHandler(RoutingRequestHandler, WebSocketMixIn): \"\"\" An HTTP request handler combining all",
"this server. If omitted, ' 'an attempt is made to guess the value",
"instead). default_addr is the ultimate fallback (host, port) tuple, and defaults to the",
"import sys import argparse from .server import WebSocketMixIn from .httpserver import WSSHTTPServer, RoutingRequestHandler",
"that is consulted for default host/port values (if not None; if this is",
"to use. server is a callable taking two arguments that creates the server",
"origin, or all interfaces).') p.add_argument('--origin', '-O', type=origin, help='A SCHEME://HOST[:PORT] string indicating how '",
"websocket_server -- WebSocket/HTTP server/client library # https://github.com/CylonicRaider/websocket-server \"\"\" Convenience functions for quick usage.",
"# Parse command-line arguments. p = argparse.ArgumentParser() p.add_argument('--port', '-p', metavar='PORT', type=int, help='The TCP",
"key file ' 'belonging to cert (if omitted, the private key is '",
"handler) if arguments.origin: httpd.origin = arguments.origin if arguments.tls: httpd.setup_ssl(arguments.tls) # Print header message.",
"the values of the options configured using prepare to the server object and",
"' 'certificates in this file.') # Call preparation callback. if prepare: prepare(p) #",
"key-value list as used for command-line TLS configuration. Returns a dictionary of the",
"with explicit values. If any of host or port is None, a default",
"' 'following parameters are defined: \"cert\": A file ' 'containing X.509 certificate in",
"% arguments.port origin_string = 'N/A' if httpd.origin is None else httpd.origin sys.stderr.write('Serving HTTP",
"PEM format, along ' 'with a CA certificate chain as necessary, to be",
"'taken from the certificate file); \"ca\": Require ' 'clients to be authenticated by",
"\"\"\" ret = {} for item in s.split(','): if not item: continue key,",
"p.add_argument('--origin', '-O', type=origin, help='A SCHEME://HOST[:PORT] string indicating how ' 'clients should access this",
"None, default_addr is used instead). default_addr is the ultimate fallback (host, port) tuple,",
"preparation callback. if postparse: postparse(arguments) # Create server. httpd = server((arguments.host, arguments.port), handler)",
"only positional argument. It can do things like complex validation, and prevent the",
"can do things like complex validation, and prevent the creation and running of",
"to the ' 'host from the origin, or all interfaces).') p.add_argument('--origin', '-O', type=origin,",
"# Print header message. # Since the server has bound itself when it",
"a Web origin that is consulted for default host/port values (if not None;",
"one of the ' 'certificates in this file.') # Call preparation callback. if",
"it from origin or default_addr. origin is a Web origin that is consulted",
"of server. arguments: The arguments as returned by argparse.ArgumentParser. It can be used",
"CA certificate chain as necessary, to be ' 'used by the server; \"key\":",
"default_addr = parse_origin(origin)[1:] if host is None: host = default_addr[0] if port is",
"do things like complex validation, and prevent the creation and running of a",
"to specify additional options. postparse is a callable invoked after parsing arguments (and",
"# insert the final origin value. if arguments.host: address = '%s:%s' % (arguments.host,",
"the module-level DEFAULT_ADDRESS constant, viz. ('', 8080). Returns the (host, port) tuple with",
"argparse.ArgumentParser() p.add_argument('--port', '-p', metavar='PORT', type=int, help='The TCP port to run on (defaults to",
"in s.split(','): if not item: continue key, sep, value = item.partition('=') if not",
"to bind to. Constructed from command-line arguments. handler : The request handler. Passed",
"a dictionary of the key-value pairs recovered from s. \"\"\" ret = {}",
"'RoutingWebSocketRequestHandler', 'tls_flags', 'resolve_listen_address', 'run'] DEFAULT_ADDRESS = ('', 8080) class RoutingWebSocketRequestHandler(RoutingRequestHandler, WebSocketMixIn): \"\"\" An",
"called immediately before entering the main loop of the internally created server object",
"X.509 certificate in PEM format, along ' 'with a CA certificate chain as",
"by argparse.ArgumentParser. It can be used to pass on the values of the",
"port values into an address an HTTP server should ultimately listen at. addr",
"addr if origin: default_addr = parse_origin(origin)[1:] if host is None: host = default_addr[0]",
"a comma-separated key-value list as used for command-line TLS configuration. Returns a dictionary",
"the (host, port) tuple with defaults filled in. \"\"\" if default_addr is None:",
"Run it. try: httpd.serve_forever() except KeyboardInterrupt: # Don't print a noisy stack trace",
"as the only positional argument. It can do things like complex validation, and",
"used to pass on the values of the options configured using prepare to",
"validate_origin(s) # Parse command-line arguments. p = argparse.ArgumentParser() p.add_argument('--port', '-p', metavar='PORT', type=int, help='The",
"tuple, and defaults to the module-level DEFAULT_ADDRESS constant, viz. ('', 8080). Returns the",
"raise ValueError('Duplicate key %r' % (key,)) ret[key] = value return ret def resolve_listen_address(addr,",
"% (arguments.host, arguments.port) else: address = '*:%s' % arguments.port origin_string = 'N/A' if",
"itself when it was contructed above, we can # insert the final origin",
"server/client library # https://github.com/CylonicRaider/websocket-server \"\"\" Convenience functions for quick usage. \"\"\" import sys",
"ValueError('Duplicate key %r' % (key,)) ret[key] = value return ret def resolve_listen_address(addr, origin,",
"port) tuple with explicit values. If any of host or port is None,",
"object and the handler class. \"\"\" # Named function for better argparse output.",
"resolve_listen_address( (arguments.host, arguments.port), arguments.origin) # Call next preparation callback. if postparse: postparse(arguments) #",
"and --port parameters; if that fails, this ' 'remains unset.') p.add_argument('--tls', '-T', metavar='PARAM=VALUE[,...]',",
"type=int, help='The TCP port to run on (defaults to the port from '",
"arguments.host: address = '%s:%s' % (arguments.host, arguments.port) else: address = '*:%s' % arguments.port",
"the creation and running of a server by raising an exception. premain is",
"\"\"\" An HTTP request handler combining all the package's functionality. \"\"\" def tls_flags(s):",
"ValueError('Invalid key-value pair %r' % (item,)) if key in ret: raise ValueError('Duplicate key",
"this is None, default_addr is used instead). default_addr is the ultimate fallback (host,",
"p = argparse.ArgumentParser() p.add_argument('--port', '-p', metavar='PORT', type=int, help='The TCP port to run on",
"string indicating how ' 'clients should access this server. If omitted, ' 'an",
"the server has bound itself when it was contructed above, we can #",
"two arguments: httpd : The server object created; an instance of server. arguments:",
"as used for command-line TLS configuration. Returns a dictionary of the key-value pairs",
"= argparse.ArgumentParser() p.add_argument('--port', '-p', metavar='PORT', type=int, help='The TCP port to run on (defaults",
"omitted, ' 'an attempt is made to guess the value from the '",
"origin is a Web origin that is consulted for default host/port values (if",
"argparse from .server import WebSocketMixIn from .httpserver import WSSHTTPServer, RoutingRequestHandler from .httpserver import",
"help='The TCP port to run on (defaults to the port from ' 'the",
"validate_origin, parse_origin __all__ = ['DEFAULT_ADDRESS', 'RoutingWebSocketRequestHandler', 'tls_flags', 'resolve_listen_address', 'run'] DEFAULT_ADDRESS = ('', 8080)",
".server import WebSocketMixIn from .httpserver import WSSHTTPServer, RoutingRequestHandler from .httpserver import validate_origin, parse_origin",
"parse options as the only argument. Can be used to specify additional options.",
"combining all the package's functionality. \"\"\" def tls_flags(s): \"\"\" Parse a comma-separated key-value",
"port) tuple, and defaults to the module-level DEFAULT_ADDRESS constant, viz. ('', 8080). Returns",
"= DEFAULT_ADDRESS host, port = addr if origin: default_addr = parse_origin(origin)[1:] if host",
"this file.') # Call preparation callback. if prepare: prepare(p) # Actually parse arguments.",
"from .server import WebSocketMixIn from .httpserver import WSSHTTPServer, RoutingRequestHandler from .httpserver import validate_origin,",
"values (if not None; if this is None, default_addr is used instead). default_addr",
"' '--host and --port parameters; if that fails, this ' 'remains unset.') p.add_argument('--tls',",
"to (defaults to the ' 'host from the origin, or all interfaces).') p.add_argument('--origin',",
": The server object created; an instance of server. arguments: The arguments as",
"options configured using prepare to the server object and the handler class. \"\"\"",
"the ' '--host and --port parameters; if that fails, this ' 'remains unset.')",
"guess the value from the ' '--host and --port parameters; if that fails,",
"sys.stderr.flush() # Call final preparation hook. if premain: premain(httpd, arguments) # Run it.",
"by raising an exception. premain is called immediately before entering the main loop",
"value. if arguments.host: address = '%s:%s' % (arguments.host, arguments.port) else: address = '*:%s'",
"default value is derived for it from origin or default_addr. origin is a",
"the origin, or all interfaces).') p.add_argument('--origin', '-O', type=origin, help='A SCHEME://HOST[:PORT] string indicating how",
"is a callable invoked after parsing arguments (and resolving complex default values) with",
"if this is None, default_addr is used instead). default_addr is the ultimate fallback",
"used instead). default_addr is the ultimate fallback (host, port) tuple, and defaults to",
"this ' 'remains unset.') p.add_argument('--tls', '-T', metavar='PARAM=VALUE[,...]', type=tls_flags, help='Enable (mandatory) TLS, and configure",
"'the origin, or 8080).') p.add_argument('--host', '-s', metavar='IP', help='The network interface to bind to",
"host or port is None, a default value is derived for it from",
"pair %r' % (item,)) if key in ret: raise ValueError('Duplicate key %r' %",
"Actually run a WebSocket server instance. handler is the handler class to use.",
"comma-separated key-value list as used for command-line TLS configuration. Returns a dictionary of",
"run on (defaults to the port from ' 'the origin, or 8080).') p.add_argument('--host',",
"origin or default_addr. origin is a Web origin that is consulted for default",
"server. httpd = server((arguments.host, arguments.port), handler) if arguments.origin: httpd.origin = arguments.origin if arguments.tls:",
"invoked after parsing arguments (and resolving complex default values) with the resulting arguments",
"to be authenticated by one of the ' 'certificates in this file.') #",
"DEFAULT_ADDRESS = ('', 8080) class RoutingWebSocketRequestHandler(RoutingRequestHandler, WebSocketMixIn): \"\"\" An HTTP request handler combining",
"server is a callable taking two arguments that creates the server instance; the",
"an HTTP server should ultimately listen at. addr is a (host, port) tuple",
"port is None, a default value is derived for it from origin or",
"origin value. if arguments.host: address = '%s:%s' % (arguments.host, arguments.port) else: address =",
"hook. if premain: premain(httpd, arguments) # Run it. try: httpd.serve_forever() except KeyboardInterrupt: #",
"arguments that creates the server instance; the arguments are: bindaddr: A (host, port)",
"Parse command-line arguments. p = argparse.ArgumentParser() p.add_argument('--port', '-p', metavar='PORT', type=int, help='The TCP port",
"A file ' 'containing X.509 certificate in PEM format, along ' 'with a",
"it was contructed above, we can # insert the final origin value. if",
"complex default values) with the resulting arguments object as the only positional argument.",
"value = item.partition('=') if not sep: raise ValueError('Invalid key-value pair %r' % (item,))",
"Since the server has bound itself when it was contructed above, we can",
"The ' 'following parameters are defined: \"cert\": A file ' 'containing X.509 certificate",
"or port is None, a default value is derived for it from origin",
"= resolve_listen_address( (arguments.host, arguments.port), arguments.origin) # Call next preparation callback. if postparse: postparse(arguments)",
"how ' 'clients should access this server. If omitted, ' 'an attempt is",
"next preparation callback. if postparse: postparse(arguments) # Create server. httpd = server((arguments.host, arguments.port),",
"the arguments are: bindaddr: A (host, port) tuple containing the address to bind",
"= ['DEFAULT_ADDRESS', 'RoutingWebSocketRequestHandler', 'tls_flags', 'resolve_listen_address', 'run'] DEFAULT_ADDRESS = ('', 8080) class RoutingWebSocketRequestHandler(RoutingRequestHandler, WebSocketMixIn):",
"a (host, port) tuple with explicit values. If any of host or port",
"= 'N/A' if httpd.origin is None else httpd.origin sys.stderr.write('Serving HTTP on %s (origin",
"was contructed above, we can # insert the final origin value. if arguments.host:",
"'resolve_listen_address', 'run'] DEFAULT_ADDRESS = ('', 8080) class RoutingWebSocketRequestHandler(RoutingRequestHandler, WebSocketMixIn): \"\"\" An HTTP request",
"interface to bind to (defaults to the ' 'host from the origin, or",
"on %s (origin %s)...\\n' % (address, origin_string)) sys.stderr.flush() # Call final preparation hook.",
"object with two arguments: httpd : The server object created; an instance of",
"\"\"\" Convenience functions for quick usage. \"\"\" import sys import argparse from .server",
"httpd : The server object created; an instance of server. arguments: The arguments",
"should ultimately listen at. addr is a (host, port) tuple with explicit values.",
"to guess the value from the ' '--host and --port parameters; if that",
"parse_origin __all__ = ['DEFAULT_ADDRESS', 'RoutingWebSocketRequestHandler', 'tls_flags', 'resolve_listen_address', 'run'] DEFAULT_ADDRESS = ('', 8080) class",
"argument. Can be used to specify additional options. postparse is a callable invoked",
"' 'containing X.509 certificate in PEM format, along ' 'with a CA certificate",
"(address, origin_string)) sys.stderr.flush() # Call final preparation hook. if premain: premain(httpd, arguments) #",
"def resolve_listen_address(addr, origin, default_addr=None): \"\"\" resolve_listen_address(addr, origin, default_addr=None) -> (host, port) Fill in",
": The request handler. Passed through from the same- named argument of run().",
"= '%s:%s' % (arguments.host, arguments.port) else: address = '*:%s' % arguments.port origin_string =",
"the main loop of the internally created server object with two arguments: httpd",
"handler class. \"\"\" # Named function for better argparse output. def origin(s): return",
"httpd.origin sys.stderr.write('Serving HTTP on %s (origin %s)...\\n' % (address, origin_string)) sys.stderr.flush() # Call"
] |
[
"sorted(old_contacts, key=Contact.id_or_max) == sorted(new_contacts, key=Contact.id_or_max) if check_ui: # tune db contact data to",
"db.get_contact_list() contact = random.choice(old_contacts) app.contact.delete_contact_by_id(contact.id) new_contacts = db.get_contact_list() assert len(old_contacts) - 1 ==",
"random.choice(old_contacts) app.contact.delete_contact_by_id(contact.id) new_contacts = db.get_contact_list() assert len(old_contacts) - 1 == len(new_contacts) old_contacts.remove(contact) assert",
"= random.choice(old_contacts) app.contact.delete_contact_by_id(contact.id) new_contacts = db.get_contact_list() assert len(old_contacts) - 1 == len(new_contacts) old_contacts.remove(contact)",
"app.contact.create(Contact(firstname=\"Tester\", middlename=\"Something\", lastname=\"Trump\", photo=\"picture.jpg\", nickname=\"super nickname\", title=\"QA engineer\", company=\"Google\", address=\"Kremlin\", homephone=\"1111111\", mobilephone=\"2222222\", workphone=\"3333333\",",
"Contact import random def test_delete_first_contact(app, db, check_ui): if len(db.get_contact_list()) == 0: app.contact.create(Contact(firstname=\"Tester\", middlename=\"Something\",",
"byear=\"1991\", aday=\"22\", amonth=\"August\", ayear=\"2015\", address_2=\"Moscow\", secondaryphone=\"5555555\", notes=\"Cool guy\")) old_contacts = db.get_contact_list() contact =",
"db.get_contact_list() assert len(old_contacts) - 1 == len(new_contacts) old_contacts.remove(contact) assert sorted(old_contacts, key=Contact.id_or_max) == sorted(new_contacts,",
"appropriate for the homepage representation old_contacts = app.contact.make_contacts_like_on_homepage(old_contacts) assert sorted(old_contacts, key=Contact.id_or_max) == sorted(app.contact.get_contacts_list(),",
"photo=\"picture.jpg\", nickname=\"super nickname\", title=\"QA engineer\", company=\"Google\", address=\"Kremlin\", homephone=\"1111111\", mobilephone=\"2222222\", workphone=\"3333333\", fax=\"4444444\", email=\"<EMAIL>\", email2=\"<EMAIL>\",",
"sorted(new_contacts, key=Contact.id_or_max) if check_ui: # tune db contact data to be appropriate for",
"assert sorted(old_contacts, key=Contact.id_or_max) == sorted(new_contacts, key=Contact.id_or_max) if check_ui: # tune db contact data",
"= db.get_contact_list() contact = random.choice(old_contacts) app.contact.delete_contact_by_id(contact.id) new_contacts = db.get_contact_list() assert len(old_contacts) - 1",
"contact = random.choice(old_contacts) app.contact.delete_contact_by_id(contact.id) new_contacts = db.get_contact_list() assert len(old_contacts) - 1 == len(new_contacts)",
"fax=\"4444444\", email=\"<EMAIL>\", email2=\"<EMAIL>\", email3=\"<EMAIL>\", homepage=\"google.com\", bday=\"29\", bmonth=\"April\", byear=\"1991\", aday=\"22\", amonth=\"August\", ayear=\"2015\", address_2=\"Moscow\", secondaryphone=\"5555555\",",
"amonth=\"August\", ayear=\"2015\", address_2=\"Moscow\", secondaryphone=\"5555555\", notes=\"Cool guy\")) old_contacts = db.get_contact_list() contact = random.choice(old_contacts) app.contact.delete_contact_by_id(contact.id)",
"workphone=\"3333333\", fax=\"4444444\", email=\"<EMAIL>\", email2=\"<EMAIL>\", email3=\"<EMAIL>\", homepage=\"google.com\", bday=\"29\", bmonth=\"April\", byear=\"1991\", aday=\"22\", amonth=\"August\", ayear=\"2015\", address_2=\"Moscow\",",
"len(db.get_contact_list()) == 0: app.contact.create(Contact(firstname=\"Tester\", middlename=\"Something\", lastname=\"Trump\", photo=\"picture.jpg\", nickname=\"super nickname\", title=\"QA engineer\", company=\"Google\", address=\"Kremlin\",",
"lastname=\"Trump\", photo=\"picture.jpg\", nickname=\"super nickname\", title=\"QA engineer\", company=\"Google\", address=\"Kremlin\", homephone=\"1111111\", mobilephone=\"2222222\", workphone=\"3333333\", fax=\"4444444\", email=\"<EMAIL>\",",
"be appropriate for the homepage representation old_contacts = app.contact.make_contacts_like_on_homepage(old_contacts) assert sorted(old_contacts, key=Contact.id_or_max) ==",
"title=\"QA engineer\", company=\"Google\", address=\"Kremlin\", homephone=\"1111111\", mobilephone=\"2222222\", workphone=\"3333333\", fax=\"4444444\", email=\"<EMAIL>\", email2=\"<EMAIL>\", email3=\"<EMAIL>\", homepage=\"google.com\", bday=\"29\",",
"key=Contact.id_or_max) if check_ui: # tune db contact data to be appropriate for the",
"email2=\"<EMAIL>\", email3=\"<EMAIL>\", homepage=\"google.com\", bday=\"29\", bmonth=\"April\", byear=\"1991\", aday=\"22\", amonth=\"August\", ayear=\"2015\", address_2=\"Moscow\", secondaryphone=\"5555555\", notes=\"Cool guy\"))",
"check_ui): if len(db.get_contact_list()) == 0: app.contact.create(Contact(firstname=\"Tester\", middlename=\"Something\", lastname=\"Trump\", photo=\"picture.jpg\", nickname=\"super nickname\", title=\"QA engineer\",",
"bmonth=\"April\", byear=\"1991\", aday=\"22\", amonth=\"August\", ayear=\"2015\", address_2=\"Moscow\", secondaryphone=\"5555555\", notes=\"Cool guy\")) old_contacts = db.get_contact_list() contact",
"key=Contact.id_or_max) == sorted(new_contacts, key=Contact.id_or_max) if check_ui: # tune db contact data to be",
"for the homepage representation old_contacts = app.contact.make_contacts_like_on_homepage(old_contacts) assert sorted(old_contacts, key=Contact.id_or_max) == sorted(app.contact.get_contacts_list(), key=Contact.id_or_max)",
"homephone=\"1111111\", mobilephone=\"2222222\", workphone=\"3333333\", fax=\"4444444\", email=\"<EMAIL>\", email2=\"<EMAIL>\", email3=\"<EMAIL>\", homepage=\"google.com\", bday=\"29\", bmonth=\"April\", byear=\"1991\", aday=\"22\", amonth=\"August\",",
"model.contact import Contact import random def test_delete_first_contact(app, db, check_ui): if len(db.get_contact_list()) == 0:",
"db contact data to be appropriate for the homepage representation old_contacts = app.contact.make_contacts_like_on_homepage(old_contacts)",
"import random def test_delete_first_contact(app, db, check_ui): if len(db.get_contact_list()) == 0: app.contact.create(Contact(firstname=\"Tester\", middlename=\"Something\", lastname=\"Trump\",",
"if len(db.get_contact_list()) == 0: app.contact.create(Contact(firstname=\"Tester\", middlename=\"Something\", lastname=\"Trump\", photo=\"picture.jpg\", nickname=\"super nickname\", title=\"QA engineer\", company=\"Google\",",
"contact data to be appropriate for the homepage representation old_contacts = app.contact.make_contacts_like_on_homepage(old_contacts) assert",
"len(old_contacts) - 1 == len(new_contacts) old_contacts.remove(contact) assert sorted(old_contacts, key=Contact.id_or_max) == sorted(new_contacts, key=Contact.id_or_max) if",
"- 1 == len(new_contacts) old_contacts.remove(contact) assert sorted(old_contacts, key=Contact.id_or_max) == sorted(new_contacts, key=Contact.id_or_max) if check_ui:",
"app.contact.delete_contact_by_id(contact.id) new_contacts = db.get_contact_list() assert len(old_contacts) - 1 == len(new_contacts) old_contacts.remove(contact) assert sorted(old_contacts,",
"# tune db contact data to be appropriate for the homepage representation old_contacts",
"old_contacts = db.get_contact_list() contact = random.choice(old_contacts) app.contact.delete_contact_by_id(contact.id) new_contacts = db.get_contact_list() assert len(old_contacts) -",
"<gh_stars>0 from model.contact import Contact import random def test_delete_first_contact(app, db, check_ui): if len(db.get_contact_list())",
"test_delete_first_contact(app, db, check_ui): if len(db.get_contact_list()) == 0: app.contact.create(Contact(firstname=\"Tester\", middlename=\"Something\", lastname=\"Trump\", photo=\"picture.jpg\", nickname=\"super nickname\",",
"import Contact import random def test_delete_first_contact(app, db, check_ui): if len(db.get_contact_list()) == 0: app.contact.create(Contact(firstname=\"Tester\",",
"nickname=\"super nickname\", title=\"QA engineer\", company=\"Google\", address=\"Kremlin\", homephone=\"1111111\", mobilephone=\"2222222\", workphone=\"3333333\", fax=\"4444444\", email=\"<EMAIL>\", email2=\"<EMAIL>\", email3=\"<EMAIL>\",",
"0: app.contact.create(Contact(firstname=\"Tester\", middlename=\"Something\", lastname=\"Trump\", photo=\"picture.jpg\", nickname=\"super nickname\", title=\"QA engineer\", company=\"Google\", address=\"Kremlin\", homephone=\"1111111\", mobilephone=\"2222222\",",
"company=\"Google\", address=\"Kremlin\", homephone=\"1111111\", mobilephone=\"2222222\", workphone=\"3333333\", fax=\"4444444\", email=\"<EMAIL>\", email2=\"<EMAIL>\", email3=\"<EMAIL>\", homepage=\"google.com\", bday=\"29\", bmonth=\"April\", byear=\"1991\",",
"homepage=\"google.com\", bday=\"29\", bmonth=\"April\", byear=\"1991\", aday=\"22\", amonth=\"August\", ayear=\"2015\", address_2=\"Moscow\", secondaryphone=\"5555555\", notes=\"Cool guy\")) old_contacts =",
"aday=\"22\", amonth=\"August\", ayear=\"2015\", address_2=\"Moscow\", secondaryphone=\"5555555\", notes=\"Cool guy\")) old_contacts = db.get_contact_list() contact = random.choice(old_contacts)",
"check_ui: # tune db contact data to be appropriate for the homepage representation",
"tune db contact data to be appropriate for the homepage representation old_contacts =",
"middlename=\"Something\", lastname=\"Trump\", photo=\"picture.jpg\", nickname=\"super nickname\", title=\"QA engineer\", company=\"Google\", address=\"Kremlin\", homephone=\"1111111\", mobilephone=\"2222222\", workphone=\"3333333\", fax=\"4444444\",",
"engineer\", company=\"Google\", address=\"Kremlin\", homephone=\"1111111\", mobilephone=\"2222222\", workphone=\"3333333\", fax=\"4444444\", email=\"<EMAIL>\", email2=\"<EMAIL>\", email3=\"<EMAIL>\", homepage=\"google.com\", bday=\"29\", bmonth=\"April\",",
"if check_ui: # tune db contact data to be appropriate for the homepage",
"to be appropriate for the homepage representation old_contacts = app.contact.make_contacts_like_on_homepage(old_contacts) assert sorted(old_contacts, key=Contact.id_or_max)",
"notes=\"Cool guy\")) old_contacts = db.get_contact_list() contact = random.choice(old_contacts) app.contact.delete_contact_by_id(contact.id) new_contacts = db.get_contact_list() assert",
"address_2=\"Moscow\", secondaryphone=\"5555555\", notes=\"Cool guy\")) old_contacts = db.get_contact_list() contact = random.choice(old_contacts) app.contact.delete_contact_by_id(contact.id) new_contacts =",
"= db.get_contact_list() assert len(old_contacts) - 1 == len(new_contacts) old_contacts.remove(contact) assert sorted(old_contacts, key=Contact.id_or_max) ==",
"ayear=\"2015\", address_2=\"Moscow\", secondaryphone=\"5555555\", notes=\"Cool guy\")) old_contacts = db.get_contact_list() contact = random.choice(old_contacts) app.contact.delete_contact_by_id(contact.id) new_contacts",
"db, check_ui): if len(db.get_contact_list()) == 0: app.contact.create(Contact(firstname=\"Tester\", middlename=\"Something\", lastname=\"Trump\", photo=\"picture.jpg\", nickname=\"super nickname\", title=\"QA",
"assert len(old_contacts) - 1 == len(new_contacts) old_contacts.remove(contact) assert sorted(old_contacts, key=Contact.id_or_max) == sorted(new_contacts, key=Contact.id_or_max)",
"nickname\", title=\"QA engineer\", company=\"Google\", address=\"Kremlin\", homephone=\"1111111\", mobilephone=\"2222222\", workphone=\"3333333\", fax=\"4444444\", email=\"<EMAIL>\", email2=\"<EMAIL>\", email3=\"<EMAIL>\", homepage=\"google.com\",",
"def test_delete_first_contact(app, db, check_ui): if len(db.get_contact_list()) == 0: app.contact.create(Contact(firstname=\"Tester\", middlename=\"Something\", lastname=\"Trump\", photo=\"picture.jpg\", nickname=\"super",
"address=\"Kremlin\", homephone=\"1111111\", mobilephone=\"2222222\", workphone=\"3333333\", fax=\"4444444\", email=\"<EMAIL>\", email2=\"<EMAIL>\", email3=\"<EMAIL>\", homepage=\"google.com\", bday=\"29\", bmonth=\"April\", byear=\"1991\", aday=\"22\",",
"mobilephone=\"2222222\", workphone=\"3333333\", fax=\"4444444\", email=\"<EMAIL>\", email2=\"<EMAIL>\", email3=\"<EMAIL>\", homepage=\"google.com\", bday=\"29\", bmonth=\"April\", byear=\"1991\", aday=\"22\", amonth=\"August\", ayear=\"2015\",",
"data to be appropriate for the homepage representation old_contacts = app.contact.make_contacts_like_on_homepage(old_contacts) assert sorted(old_contacts,",
"secondaryphone=\"5555555\", notes=\"Cool guy\")) old_contacts = db.get_contact_list() contact = random.choice(old_contacts) app.contact.delete_contact_by_id(contact.id) new_contacts = db.get_contact_list()",
"email=\"<EMAIL>\", email2=\"<EMAIL>\", email3=\"<EMAIL>\", homepage=\"google.com\", bday=\"29\", bmonth=\"April\", byear=\"1991\", aday=\"22\", amonth=\"August\", ayear=\"2015\", address_2=\"Moscow\", secondaryphone=\"5555555\", notes=\"Cool",
"bday=\"29\", bmonth=\"April\", byear=\"1991\", aday=\"22\", amonth=\"August\", ayear=\"2015\", address_2=\"Moscow\", secondaryphone=\"5555555\", notes=\"Cool guy\")) old_contacts = db.get_contact_list()",
"1 == len(new_contacts) old_contacts.remove(contact) assert sorted(old_contacts, key=Contact.id_or_max) == sorted(new_contacts, key=Contact.id_or_max) if check_ui: #",
"== sorted(new_contacts, key=Contact.id_or_max) if check_ui: # tune db contact data to be appropriate",
"random def test_delete_first_contact(app, db, check_ui): if len(db.get_contact_list()) == 0: app.contact.create(Contact(firstname=\"Tester\", middlename=\"Something\", lastname=\"Trump\", photo=\"picture.jpg\",",
"== 0: app.contact.create(Contact(firstname=\"Tester\", middlename=\"Something\", lastname=\"Trump\", photo=\"picture.jpg\", nickname=\"super nickname\", title=\"QA engineer\", company=\"Google\", address=\"Kremlin\", homephone=\"1111111\",",
"old_contacts.remove(contact) assert sorted(old_contacts, key=Contact.id_or_max) == sorted(new_contacts, key=Contact.id_or_max) if check_ui: # tune db contact",
"new_contacts = db.get_contact_list() assert len(old_contacts) - 1 == len(new_contacts) old_contacts.remove(contact) assert sorted(old_contacts, key=Contact.id_or_max)",
"email3=\"<EMAIL>\", homepage=\"google.com\", bday=\"29\", bmonth=\"April\", byear=\"1991\", aday=\"22\", amonth=\"August\", ayear=\"2015\", address_2=\"Moscow\", secondaryphone=\"5555555\", notes=\"Cool guy\")) old_contacts",
"guy\")) old_contacts = db.get_contact_list() contact = random.choice(old_contacts) app.contact.delete_contact_by_id(contact.id) new_contacts = db.get_contact_list() assert len(old_contacts)",
"== len(new_contacts) old_contacts.remove(contact) assert sorted(old_contacts, key=Contact.id_or_max) == sorted(new_contacts, key=Contact.id_or_max) if check_ui: # tune",
"from model.contact import Contact import random def test_delete_first_contact(app, db, check_ui): if len(db.get_contact_list()) ==",
"len(new_contacts) old_contacts.remove(contact) assert sorted(old_contacts, key=Contact.id_or_max) == sorted(new_contacts, key=Contact.id_or_max) if check_ui: # tune db"
] |
[
"* np.exp(-y * self.weights_[i] * y_pred) self.D_ = self.D_ / np.sum(self.D_) def _predict(self,",
"the current dataset according to sample_weights \"\"\" new_indices = np.random.choice(cur_y.size, size=cur_y.size, p=sample_weights) return",
"X: np.ndarray, y: np.ndarray, T: int) -> float: \"\"\" Evaluate performance under misclassification",
"fitted along the boosting iterations \"\"\" def __init__(self, wl: Callable[[], BaseEstimator], iterations: int):",
"self.weights_[i] = 1 self.iterations_ = i + 1 break self.weights_[i] = np.log(1 /",
"= np.where(y_true != y_pred, 1, 0) return np.sum(misses * sample_weights) def _fit(self, X:",
"iterations: int Number of boosting iterations to perform \"\"\" super().__init__() self.wl_ = wl",
"y : ndarray of shape (n_samples, ) True labels of test samples Returns",
"loss function \"\"\" return misclassification_error(y, self._predict(X), normalize=True) def partial_predict(self, X: np.ndarray, T: int)",
"iterations to perform self.models_: List[BaseEstimator] List of fitted estimators, fitted along the boosting",
"Evaluate performance under misclassification loss function Parameters ---------- X : ndarray of shape",
"1 self.iterations_ = i + 1 break self.weights_[i] = np.log(1 / epsilon -",
"0 else 1 self.D_ = self.D_ * np.exp(-y * self.weights_[i] * y_pred) self.D_",
"self.models_[i].predict(X) epsilon = self.weighted_loss(y, y_pred, self.D_) # if loss is 0, then we",
"for obtaining an instance of type BaseEstimator iterations: int Number of boosting iterations",
"Predict responses for given samples using fitted estimators Parameters ---------- X : ndarray",
"of test samples T: int The number of classifiers (from 1,...,T) to be",
"iterations \"\"\" def __init__(self, wl: Callable[[], BaseEstimator], iterations: int): \"\"\" Instantiate an AdaBoost",
"* self.D_) y_pred = self.models_[i].predict(X) epsilon = self.weighted_loss(y, y_pred, self.D_) # if loss",
"Callable[[], BaseEstimator] Callable for obtaining an instance of type BaseEstimator self.iterations_: int Number",
"of boosting iterations to perform \"\"\" super().__init__() self.wl_ = wl self.iterations_ = iterations",
"labels of test samples Returns ------- loss : float Performance under missclassification loss",
"selected_models = self.models_[:T] all_learners_pred = np.array([m.predict(X) for m in selected_models]).T weighted_pred = all_learners_pred",
": ndarray of shape (n_samples, n_features) Test samples y : ndarray of shape",
"---------- X : ndarray of shape (n_samples, n_features) Input data to predict responses",
"= self.D_ / np.sum(self.D_) def _predict(self, X): \"\"\" Predict responses for given samples",
"shape (n_samples, n_features) Test samples y : ndarray of shape (n_samples, ) True",
"BaseEstimator] Callable for obtaining an instance of type BaseEstimator iterations: int Number of",
"_fit(self, X: np.ndarray, y: np.ndarray) -> NoReturn: \"\"\" Fit an AdaBoost classifier over",
"boosting iterations to perform self.models_: List[BaseEstimator] List of fitted estimators, fitted along the",
"samples y : ndarray of shape (n_samples, ) True labels of test samples",
"perform \"\"\" super().__init__() self.wl_ = wl self.iterations_ = iterations self.models_, self.weights_, self.D_ =",
"a given set of predictions \"\"\" misses = np.where(y_true != y_pred, 1, 0)",
"classifier if epsilon == 0: self.weights_ = np.zeros(self.iterations_) self.weights_[i] = 1 self.iterations_ =",
"X: np.ndarray, y: np.ndarray) -> NoReturn: \"\"\" Fit an AdaBoost classifier over given",
"int) -> np.ndarray: \"\"\" Predict responses for given samples using fitted estimators Parameters",
"np.array([m.predict(X) for m in selected_models]).T weighted_pred = all_learners_pred @ self.weights_[:T] if len(weighted_pred.shape) ==",
"of shape (n_samples, n_features) Input data to predict responses for T: int The",
"1: X = X.reshape((-1, 1)) n_samples = X.shape[0] self.models_ = [self.wl_() for _",
"iterations to perform \"\"\" super().__init__() self.wl_ = wl self.iterations_ = iterations self.models_, self.weights_,",
"= 1 self.iterations_ = i + 1 break self.weights_[i] = np.log(1 / epsilon",
"List[BaseEstimator] List of fitted estimators, fitted along the boosting iterations \"\"\" def __init__(self,",
"Performance under missclassification loss function \"\"\" return misclassification_error(y, self._predict(X), normalize=True) def partial_predict(self, X:",
"given samples \"\"\" T = min(T, self.iterations_) selected_models = self.models_[:T] all_learners_pred = np.array([m.predict(X)",
"from IMLearn.base import BaseEstimator from typing import Callable, NoReturn from IMLearn.metrics import misclassification_error",
"super().__init__() self.wl_ = wl self.iterations_ = iterations self.models_, self.weights_, self.D_ = None, None,",
"---------- wl: Callable[[], BaseEstimator] Callable for obtaining an instance of type BaseEstimator iterations:",
"/ 2 # if cur_loss > 0 else 1 self.D_ = self.D_ *",
"ndarray of shape (n_samples, ) True labels of test samples Returns ------- loss",
"sample_weights) def _fit(self, X: np.ndarray, y: np.ndarray) -> NoReturn: \"\"\" Fit an AdaBoost",
"= np.zeros(self.iterations_) self.weights_[i] = 1 self.iterations_ = i + 1 break self.weights_[i] =",
"/ n_samples) self.weights_ = np.zeros(self.iterations_) for i in range(self.iterations_): self.models_[i].fit(X, y * self.D_)",
"BaseEstimator iterations: int Number of boosting iterations to perform \"\"\" super().__init__() self.wl_ =",
"import BaseEstimator from typing import Callable, NoReturn from IMLearn.metrics import misclassification_error class AdaBoost(BaseEstimator):",
"self.D_ * np.exp(-y * self.weights_[i] * y_pred) self.D_ = self.D_ / np.sum(self.D_) def",
"\"\"\" return misclassification_error(y, self._predict(X), normalize=True) def partial_predict(self, X: np.ndarray, T: int) -> np.ndarray:",
"partial_loss(self, X: np.ndarray, y: np.ndarray, T: int) -> float: \"\"\" Evaluate performance under",
"\"\"\" return self.partial_predict(X, self.iterations_) def _loss(self, X: np.ndarray, y: np.ndarray) -> float: \"\"\"",
"True labels of test samples T: int The number of classifiers (from 1,...,T)",
"of shape (n_samples, ) True labels of test samples Returns ------- loss :",
"Performance under missclassification loss function \"\"\" y_pred = self.partial_predict(X, T) return misclassification_error(y, y_pred,",
"self.D_ = np.full(n_samples, 1 / n_samples) self.weights_ = np.zeros(self.iterations_) for i in range(self.iterations_):",
"import numpy as np # from ...base import BaseEstimator from IMLearn.base import BaseEstimator",
"instance of type BaseEstimator self.iterations_: int Number of boosting iterations to perform self.models_:",
"n_features) Test samples y : ndarray of shape (n_samples, ) True labels of",
"current dataset according to sample_weights \"\"\" new_indices = np.random.choice(cur_y.size, size=cur_y.size, p=sample_weights) return cur_X[new_indices,",
"AdaBoost class over the specified base estimator Parameters ---------- wl: Callable[[], BaseEstimator] Callable",
"for T: int The number of classifiers (from 1,...,T) to be used for",
"_loss(self, X: np.ndarray, y: np.ndarray) -> float: \"\"\" Evaluate performance under misclassification loss",
"AdaBoost classifier over given samples Parameters ---------- X : ndarray of shape (n_samples,",
"= np.full(n_samples, 1 / n_samples) self.weights_ = np.zeros(self.iterations_) for i in range(self.iterations_): self.models_[i].fit(X,",
"given samples using fitted estimator Parameters ---------- X : ndarray of shape (n_samples,",
"boosting iterations to perform \"\"\" super().__init__() self.wl_ = wl self.iterations_ = iterations self.models_,",
"\"\"\" Predict responses for given samples using fitted estimator Parameters ---------- X :",
"\"\"\" misses = np.where(y_true != y_pred, 1, 0) return np.sum(misses * sample_weights) def",
"1) / 2 # if cur_loss > 0 else 1 self.D_ = self.D_",
"misclassification_error(y, self._predict(X), normalize=True) def partial_predict(self, X: np.ndarray, T: int) -> np.ndarray: \"\"\" Predict",
"def _loss(self, X: np.ndarray, y: np.ndarray) -> float: \"\"\" Evaluate performance under misclassification",
"self.models_ = [self.wl_() for _ in range(self.iterations_)] self.D_ = np.full(n_samples, 1 / n_samples)",
"loss for a given set of predictions \"\"\" misses = np.where(y_true != y_pred,",
": ndarray of shape (n_samples, ) True labels of test samples Returns -------",
"cur_y[new_indices] @staticmethod def weighted_loss(y_true, y_pred, sample_weights): \"\"\" Calculate the weighted loss for a",
"shape (n_samples, n_features) Input data to predict responses for T: int The number",
"data to predict responses for T: int The number of classifiers (from 1,...,T)",
"IMLearn.base import BaseEstimator from typing import Callable, NoReturn from IMLearn.metrics import misclassification_error class",
"* y_pred) self.D_ = self.D_ / np.sum(self.D_) def _predict(self, X): \"\"\" Predict responses",
"of type BaseEstimator self.iterations_: int Number of boosting iterations to perform self.models_: List[BaseEstimator]",
"= X.reshape((-1, 1)) n_samples = X.shape[0] self.models_ = [self.wl_() for _ in range(self.iterations_)]",
"of input data to fit to \"\"\" if len(X.shape) == 1: X =",
"Returns ------- loss : float Performance under missclassification loss function \"\"\" y_pred =",
"set of predictions \"\"\" misses = np.where(y_true != y_pred, 1, 0) return np.sum(misses",
"* sample_weights) def _fit(self, X: np.ndarray, y: np.ndarray) -> NoReturn: \"\"\" Fit an",
"np.random.choice(cur_y.size, size=cur_y.size, p=sample_weights) return cur_X[new_indices, :], cur_y[new_indices] @staticmethod def weighted_loss(y_true, y_pred, sample_weights): \"\"\"",
"samples \"\"\" T = min(T, self.iterations_) selected_models = self.models_[:T] all_learners_pred = np.array([m.predict(X) for",
"if epsilon == 0: self.weights_ = np.zeros(self.iterations_) self.weights_[i] = 1 self.iterations_ = i",
"responses for given samples using fitted estimators Parameters ---------- X : ndarray of",
"under missclassification loss function \"\"\" return misclassification_error(y, self._predict(X), normalize=True) def partial_predict(self, X: np.ndarray,",
"an instance of type BaseEstimator self.iterations_: int Number of boosting iterations to perform",
"of boosting iterations to perform self.models_: List[BaseEstimator] List of fitted estimators, fitted along",
"= self.weighted_loss(y, y_pred, self.D_) # if loss is 0, then we have a",
"all_learners_pred = np.array([m.predict(X) for m in selected_models]).T weighted_pred = all_learners_pred @ self.weights_[:T] if",
"over the specified base estimator Parameters ---------- wl: Callable[[], BaseEstimator] Callable for obtaining",
"def __resample(cur_X, cur_y, sample_weights): \"\"\" Resample the current dataset according to sample_weights \"\"\"",
"List of fitted estimators, fitted along the boosting iterations \"\"\" def __init__(self, wl:",
"int) -> float: \"\"\" Evaluate performance under misclassification loss function Parameters ---------- X",
"return misclassification_error(y, self._predict(X), normalize=True) def partial_predict(self, X: np.ndarray, T: int) -> np.ndarray: \"\"\"",
"samples Returns ------- loss : float Performance under missclassification loss function \"\"\" return",
"\"\"\" Evaluate performance under misclassification loss function Parameters ---------- X : ndarray of",
"== 0: self.weights_ = np.zeros(self.iterations_) self.weights_[i] = 1 self.iterations_ = i + 1",
"predict responses for T: int The number of classifiers (from 1,...,T) to be",
"ndarray of shape (n_samples, ) Predicted responses of given samples \"\"\" T =",
"None, None @staticmethod def __resample(cur_X, cur_y, sample_weights): \"\"\" Resample the current dataset according",
"the weighted loss for a given set of predictions \"\"\" misses = np.where(y_true",
"weak learner Attributes ---------- self.wl_: Callable[[], BaseEstimator] Callable for obtaining an instance of",
"(n_samples, ) True labels of test samples T: int The number of classifiers",
"numpy as np # from ...base import BaseEstimator from IMLearn.base import BaseEstimator from",
"X : ndarray of shape (n_samples, n_features) Test samples y : ndarray of",
"= min(T, self.iterations_) selected_models = self.models_[:T] all_learners_pred = np.array([m.predict(X) for m in selected_models]).T",
"estimators Parameters ---------- X : ndarray of shape (n_samples, n_features) Input data to",
"= np.log(1 / epsilon - 1) / 2 # if cur_loss > 0",
"p=sample_weights) return cur_X[new_indices, :], cur_y[new_indices] @staticmethod def weighted_loss(y_true, y_pred, sample_weights): \"\"\" Calculate the",
"self.wl_: Callable[[], BaseEstimator] Callable for obtaining an instance of type BaseEstimator self.iterations_: int",
"input data to fit to \"\"\" if len(X.shape) == 1: X = X.reshape((-1,",
"break self.weights_[i] = np.log(1 / epsilon - 1) / 2 # if cur_loss",
"= self.models_[i].predict(X) epsilon = self.weighted_loss(y, y_pred, self.D_) # if loss is 0, then",
"new_indices = np.random.choice(cur_y.size, size=cur_y.size, p=sample_weights) return cur_X[new_indices, :], cur_y[new_indices] @staticmethod def weighted_loss(y_true, y_pred,",
"\"\"\" if len(X.shape) == 1: X = X.reshape((-1, 1)) n_samples = X.shape[0] self.models_",
"epsilon = self.weighted_loss(y, y_pred, self.D_) # if loss is 0, then we have",
"np.ndarray) -> NoReturn: \"\"\" Fit an AdaBoost classifier over given samples Parameters ----------",
"from typing import Callable, NoReturn from IMLearn.metrics import misclassification_error class AdaBoost(BaseEstimator): \"\"\" AdaBoost",
"self.weights_, self.D_ = None, None, None @staticmethod def __resample(cur_X, cur_y, sample_weights): \"\"\" Resample",
"samples using fitted estimator Parameters ---------- X : ndarray of shape (n_samples, n_features)",
"for _ in range(self.iterations_)] self.D_ = np.full(n_samples, 1 / n_samples) self.weights_ = np.zeros(self.iterations_)",
"shape (n_samples, ) Responses of input data to fit to \"\"\" if len(X.shape)",
"(n_samples, n_features) Input data to fit an estimator for y : ndarray of",
"y_pred) self.D_ = self.D_ / np.sum(self.D_) def _predict(self, X): \"\"\" Predict responses for",
"Attributes ---------- self.wl_: Callable[[], BaseEstimator] Callable for obtaining an instance of type BaseEstimator",
"data to fit an estimator for y : ndarray of shape (n_samples, )",
"for m in selected_models]).T weighted_pred = all_learners_pred @ self.weights_[:T] if len(weighted_pred.shape) == 1:",
"__init__(self, wl: Callable[[], BaseEstimator], iterations: int): \"\"\" Instantiate an AdaBoost class over the",
"to sample_weights \"\"\" new_indices = np.random.choice(cur_y.size, size=cur_y.size, p=sample_weights) return cur_X[new_indices, :], cur_y[new_indices] @staticmethod",
"X.shape[0] self.models_ = [self.wl_() for _ in range(self.iterations_)] self.D_ = np.full(n_samples, 1 /",
"Parameters ---------- X : ndarray of shape (n_samples, n_features) Test samples y :",
"self.iterations_ = iterations self.models_, self.weights_, self.D_ = None, None, None @staticmethod def __resample(cur_X,",
"= np.random.choice(cur_y.size, size=cur_y.size, p=sample_weights) return cur_X[new_indices, :], cur_y[new_indices] @staticmethod def weighted_loss(y_true, y_pred, sample_weights):",
"np.ndarray, y: np.ndarray) -> float: \"\"\" Evaluate performance under misclassification loss function Parameters",
"weighted_pred = all_learners_pred @ self.weights_[:T] if len(weighted_pred.shape) == 1: return np.sign(weighted_pred) else: return",
"import Callable, NoReturn from IMLearn.metrics import misclassification_error class AdaBoost(BaseEstimator): \"\"\" AdaBoost class for",
"y : ndarray of shape (n_samples, ) Responses of input data to fit",
"def _predict(self, X): \"\"\" Predict responses for given samples using fitted estimator Parameters",
"boosting iterations \"\"\" def __init__(self, wl: Callable[[], BaseEstimator], iterations: int): \"\"\" Instantiate an",
"samples Parameters ---------- X : ndarray of shape (n_samples, n_features) Input data to",
"def partial_loss(self, X: np.ndarray, y: np.ndarray, T: int) -> float: \"\"\" Evaluate performance",
"self.weights_ = np.zeros(self.iterations_) for i in range(self.iterations_): self.models_[i].fit(X, y * self.D_) y_pred =",
"= np.zeros(self.iterations_) for i in range(self.iterations_): self.models_[i].fit(X, y * self.D_) y_pred = self.models_[i].predict(X)",
"= wl self.iterations_ = iterations self.models_, self.weights_, self.D_ = None, None, None @staticmethod",
"self.iterations_) def _loss(self, X: np.ndarray, y: np.ndarray) -> float: \"\"\" Evaluate performance under",
"BaseEstimator] Callable for obtaining an instance of type BaseEstimator self.iterations_: int Number of",
"int): \"\"\" Instantiate an AdaBoost class over the specified base estimator Parameters ----------",
"self.D_ = None, None, None @staticmethod def __resample(cur_X, cur_y, sample_weights): \"\"\" Resample the",
"in range(self.iterations_): self.models_[i].fit(X, y * self.D_) y_pred = self.models_[i].predict(X) epsilon = self.weighted_loss(y, y_pred,",
"Number of boosting iterations to perform \"\"\" super().__init__() self.wl_ = wl self.iterations_ =",
"typing import Callable, NoReturn from IMLearn.metrics import misclassification_error class AdaBoost(BaseEstimator): \"\"\" AdaBoost class",
"cur_X[new_indices, :], cur_y[new_indices] @staticmethod def weighted_loss(y_true, y_pred, sample_weights): \"\"\" Calculate the weighted loss",
"self.models_: List[BaseEstimator] List of fitted estimators, fitted along the boosting iterations \"\"\" def",
"perfect classifier if epsilon == 0: self.weights_ = np.zeros(self.iterations_) self.weights_[i] = 1 self.iterations_",
"= i + 1 break self.weights_[i] = np.log(1 / epsilon - 1) /",
"an estimator for y : ndarray of shape (n_samples, ) Responses of input",
"X): \"\"\" Predict responses for given samples using fitted estimator Parameters ---------- X",
"int The number of classifiers (from 1,...,T) to be used for prediction Returns",
"for a given set of predictions \"\"\" misses = np.where(y_true != y_pred, 1,",
"len(X.shape) == 1: X = X.reshape((-1, 1)) n_samples = X.shape[0] self.models_ = [self.wl_()",
") Predicted responses of given samples \"\"\" T = min(T, self.iterations_) selected_models =",
"0) return np.sum(misses * sample_weights) def _fit(self, X: np.ndarray, y: np.ndarray) -> NoReturn:",
"of classifiers (from 1,...,T) to be used for prediction Returns ------- responses :",
"self.wl_ = wl self.iterations_ = iterations self.models_, self.weights_, self.D_ = None, None, None",
"be used for prediction Returns ------- responses : ndarray of shape (n_samples, )",
"responses for Returns ------- responses : ndarray of shape (n_samples, ) Predicted responses",
") True labels of test samples Returns ------- loss : float Performance under",
"\"\"\" Calculate the weighted loss for a given set of predictions \"\"\" misses",
"to fit to \"\"\" if len(X.shape) == 1: X = X.reshape((-1, 1)) n_samples",
"len(weighted_pred.shape) == 1: return np.sign(weighted_pred) else: return np.sign(weighted_pred.sum(axis=1)) def partial_loss(self, X: np.ndarray, y:",
"return np.sign(weighted_pred) else: return np.sign(weighted_pred.sum(axis=1)) def partial_loss(self, X: np.ndarray, y: np.ndarray, T: int)",
"samples using fitted estimators Parameters ---------- X : ndarray of shape (n_samples, n_features)",
"Callable[[], BaseEstimator], iterations: int): \"\"\" Instantiate an AdaBoost class over the specified base",
"an AdaBoost classifier over given samples Parameters ---------- X : ndarray of shape",
": ndarray of shape (n_samples, ) Predicted responses of given samples \"\"\" return",
"of predictions \"\"\" misses = np.where(y_true != y_pred, 1, 0) return np.sum(misses *",
"self.D_ = self.D_ * np.exp(-y * self.weights_[i] * y_pred) self.D_ = self.D_ /",
"def partial_predict(self, X: np.ndarray, T: int) -> np.ndarray: \"\"\" Predict responses for given",
"- 1) / 2 # if cur_loss > 0 else 1 self.D_ =",
"(n_samples, ) True labels of test samples Returns ------- loss : float Performance",
"is 0, then we have a perfect classifier if epsilon == 0: self.weights_",
"y_pred, 1, 0) return np.sum(misses * sample_weights) def _fit(self, X: np.ndarray, y: np.ndarray)",
"function \"\"\" return misclassification_error(y, self._predict(X), normalize=True) def partial_predict(self, X: np.ndarray, T: int) ->",
"normalize=True) def partial_predict(self, X: np.ndarray, T: int) -> np.ndarray: \"\"\" Predict responses for",
"X : ndarray of shape (n_samples, n_features) Input data to predict responses for",
"number of classifiers (from 1,...,T) to be used for prediction Returns ------- loss",
"Parameters ---------- wl: Callable[[], BaseEstimator] Callable for obtaining an instance of type BaseEstimator",
"Number of boosting iterations to perform self.models_: List[BaseEstimator] List of fitted estimators, fitted",
"NoReturn: \"\"\" Fit an AdaBoost classifier over given samples Parameters ---------- X :",
"@staticmethod def weighted_loss(y_true, y_pred, sample_weights): \"\"\" Calculate the weighted loss for a given",
"-> NoReturn: \"\"\" Fit an AdaBoost classifier over given samples Parameters ---------- X",
"if cur_loss > 0 else 1 self.D_ = self.D_ * np.exp(-y * self.weights_[i]",
"Callable[[], BaseEstimator] Callable for obtaining an instance of type BaseEstimator iterations: int Number",
"ndarray of shape (n_samples, ) True labels of test samples T: int The",
"iterations self.models_, self.weights_, self.D_ = None, None, None @staticmethod def __resample(cur_X, cur_y, sample_weights):",
"1: return np.sign(weighted_pred) else: return np.sign(weighted_pred.sum(axis=1)) def partial_loss(self, X: np.ndarray, y: np.ndarray, T:",
"we have a perfect classifier if epsilon == 0: self.weights_ = np.zeros(self.iterations_) self.weights_[i]",
"Resample the current dataset according to sample_weights \"\"\" new_indices = np.random.choice(cur_y.size, size=cur_y.size, p=sample_weights)",
"return np.sum(misses * sample_weights) def _fit(self, X: np.ndarray, y: np.ndarray) -> NoReturn: \"\"\"",
"over given samples Parameters ---------- X : ndarray of shape (n_samples, n_features) Input",
"self.partial_predict(X, self.iterations_) def _loss(self, X: np.ndarray, y: np.ndarray) -> float: \"\"\" Evaluate performance",
") Predicted responses of given samples \"\"\" return self.partial_predict(X, self.iterations_) def _loss(self, X:",
"n_features) Input data to predict responses for Returns ------- responses : ndarray of",
"\"\"\" Predict responses for given samples using fitted estimators Parameters ---------- X :",
"used for prediction Returns ------- loss : float Performance under missclassification loss function",
"self.iterations_: int Number of boosting iterations to perform self.models_: List[BaseEstimator] List of fitted",
"else 1 self.D_ = self.D_ * np.exp(-y * self.weights_[i] * y_pred) self.D_ =",
"Returns ------- loss : float Performance under missclassification loss function \"\"\" return misclassification_error(y,",
"Input data to predict responses for Returns ------- responses : ndarray of shape",
"BaseEstimator from IMLearn.base import BaseEstimator from typing import Callable, NoReturn from IMLearn.metrics import",
"learner Attributes ---------- self.wl_: Callable[[], BaseEstimator] Callable for obtaining an instance of type",
"if len(X.shape) == 1: X = X.reshape((-1, 1)) n_samples = X.shape[0] self.models_ =",
"_predict(self, X): \"\"\" Predict responses for given samples using fitted estimator Parameters ----------",
"samples T: int The number of classifiers (from 1,...,T) to be used for",
"Instantiate an AdaBoost class over the specified base estimator Parameters ---------- wl: Callable[[],",
"== 1: X = X.reshape((-1, 1)) n_samples = X.shape[0] self.models_ = [self.wl_() for",
": ndarray of shape (n_samples, ) True labels of test samples T: int",
"of shape (n_samples, ) Predicted responses of given samples \"\"\" T = min(T,",
"ndarray of shape (n_samples, ) Responses of input data to fit to \"\"\"",
"# if cur_loss > 0 else 1 self.D_ = self.D_ * np.exp(-y *",
"fit an estimator for y : ndarray of shape (n_samples, ) Responses of",
"Predicted responses of given samples \"\"\" return self.partial_predict(X, self.iterations_) def _loss(self, X: np.ndarray,",
"for y : ndarray of shape (n_samples, ) Responses of input data to",
"weighted loss for a given set of predictions \"\"\" misses = np.where(y_true !=",
"for given samples using fitted estimator Parameters ---------- X : ndarray of shape",
"a perfect classifier if epsilon == 0: self.weights_ = np.zeros(self.iterations_) self.weights_[i] = 1",
"(n_samples, n_features) Input data to predict responses for Returns ------- responses : ndarray",
"np.ndarray: \"\"\" Predict responses for given samples using fitted estimators Parameters ---------- X",
"m in selected_models]).T weighted_pred = all_learners_pred @ self.weights_[:T] if len(weighted_pred.shape) == 1: return",
"y_pred = self.models_[i].predict(X) epsilon = self.weighted_loss(y, y_pred, self.D_) # if loss is 0,",
"dataset according to sample_weights \"\"\" new_indices = np.random.choice(cur_y.size, size=cur_y.size, p=sample_weights) return cur_X[new_indices, :],",
"X: np.ndarray, T: int) -> np.ndarray: \"\"\" Predict responses for given samples using",
"== 1: return np.sign(weighted_pred) else: return np.sign(weighted_pred.sum(axis=1)) def partial_loss(self, X: np.ndarray, y: np.ndarray,",
"/ epsilon - 1) / 2 # if cur_loss > 0 else 1",
"data to fit to \"\"\" if len(X.shape) == 1: X = X.reshape((-1, 1))",
"import misclassification_error class AdaBoost(BaseEstimator): \"\"\" AdaBoost class for boosting a specified weak learner",
"performance under misclassification loss function Parameters ---------- X : ndarray of shape (n_samples,",
"Responses of input data to fit to \"\"\" if len(X.shape) == 1: X",
"type BaseEstimator self.iterations_: int Number of boosting iterations to perform self.models_: List[BaseEstimator] List",
"y_pred, sample_weights): \"\"\" Calculate the weighted loss for a given set of predictions",
"def __init__(self, wl: Callable[[], BaseEstimator], iterations: int): \"\"\" Instantiate an AdaBoost class over",
"cur_y, sample_weights): \"\"\" Resample the current dataset according to sample_weights \"\"\" new_indices =",
"def _fit(self, X: np.ndarray, y: np.ndarray) -> NoReturn: \"\"\" Fit an AdaBoost classifier",
"def weighted_loss(y_true, y_pred, sample_weights): \"\"\" Calculate the weighted loss for a given set",
"* self.weights_[i] * y_pred) self.D_ = self.D_ / np.sum(self.D_) def _predict(self, X): \"\"\"",
"float Performance under missclassification loss function \"\"\" return misclassification_error(y, self._predict(X), normalize=True) def partial_predict(self,",
"iterations: int): \"\"\" Instantiate an AdaBoost class over the specified base estimator Parameters",
"------- loss : float Performance under missclassification loss function \"\"\" return misclassification_error(y, self._predict(X),",
"# if loss is 0, then we have a perfect classifier if epsilon",
"partial_predict(self, X: np.ndarray, T: int) -> np.ndarray: \"\"\" Predict responses for given samples",
"Input data to fit an estimator for y : ndarray of shape (n_samples,",
"Predict responses for given samples using fitted estimator Parameters ---------- X : ndarray",
"= np.array([m.predict(X) for m in selected_models]).T weighted_pred = all_learners_pred @ self.weights_[:T] if len(weighted_pred.shape)",
"class over the specified base estimator Parameters ---------- wl: Callable[[], BaseEstimator] Callable for",
"data to predict responses for Returns ------- responses : ndarray of shape (n_samples,",
"prediction Returns ------- loss : float Performance under missclassification loss function \"\"\" y_pred",
"np.full(n_samples, 1 / n_samples) self.weights_ = np.zeros(self.iterations_) for i in range(self.iterations_): self.models_[i].fit(X, y",
"specified weak learner Attributes ---------- self.wl_: Callable[[], BaseEstimator] Callable for obtaining an instance",
"y: np.ndarray, T: int) -> float: \"\"\" Evaluate performance under misclassification loss function",
": float Performance under missclassification loss function \"\"\" return misclassification_error(y, self._predict(X), normalize=True) def",
"@ self.weights_[:T] if len(weighted_pred.shape) == 1: return np.sign(weighted_pred) else: return np.sign(weighted_pred.sum(axis=1)) def partial_loss(self,",
"obtaining an instance of type BaseEstimator self.iterations_: int Number of boosting iterations to",
"range(self.iterations_)] self.D_ = np.full(n_samples, 1 / n_samples) self.weights_ = np.zeros(self.iterations_) for i in",
"self.weights_ = np.zeros(self.iterations_) self.weights_[i] = 1 self.iterations_ = i + 1 break self.weights_[i]",
"__resample(cur_X, cur_y, sample_weights): \"\"\" Resample the current dataset according to sample_weights \"\"\" new_indices",
"1)) n_samples = X.shape[0] self.models_ = [self.wl_() for _ in range(self.iterations_)] self.D_ =",
"float Performance under missclassification loss function \"\"\" y_pred = self.partial_predict(X, T) return misclassification_error(y,",
"np.where(y_true != y_pred, 1, 0) return np.sum(misses * sample_weights) def _fit(self, X: np.ndarray,",
"given samples using fitted estimators Parameters ---------- X : ndarray of shape (n_samples,",
"if len(weighted_pred.shape) == 1: return np.sign(weighted_pred) else: return np.sign(weighted_pred.sum(axis=1)) def partial_loss(self, X: np.ndarray,",
"an instance of type BaseEstimator iterations: int Number of boosting iterations to perform",
": ndarray of shape (n_samples, n_features) Input data to predict responses for T:",
"responses for T: int The number of classifiers (from 1,...,T) to be used",
"\"\"\" super().__init__() self.wl_ = wl self.iterations_ = iterations self.models_, self.weights_, self.D_ = None,",
"base estimator Parameters ---------- wl: Callable[[], BaseEstimator] Callable for obtaining an instance of",
"[self.wl_() for _ in range(self.iterations_)] self.D_ = np.full(n_samples, 1 / n_samples) self.weights_ =",
"fitted estimator Parameters ---------- X : ndarray of shape (n_samples, n_features) Input data",
"estimator Parameters ---------- wl: Callable[[], BaseEstimator] Callable for obtaining an instance of type",
"weighted_loss(y_true, y_pred, sample_weights): \"\"\" Calculate the weighted loss for a given set of",
"y_pred, self.D_) # if loss is 0, then we have a perfect classifier",
"of shape (n_samples, ) Predicted responses of given samples \"\"\" return self.partial_predict(X, self.iterations_)",
"shape (n_samples, n_features) Input data to predict responses for Returns ------- responses :",
"Input data to predict responses for T: int The number of classifiers (from",
"obtaining an instance of type BaseEstimator iterations: int Number of boosting iterations to",
"sample_weights): \"\"\" Calculate the weighted loss for a given set of predictions \"\"\"",
"to perform self.models_: List[BaseEstimator] List of fitted estimators, fitted along the boosting iterations",
"IMLearn.metrics import misclassification_error class AdaBoost(BaseEstimator): \"\"\" AdaBoost class for boosting a specified weak",
"the boosting iterations \"\"\" def __init__(self, wl: Callable[[], BaseEstimator], iterations: int): \"\"\" Instantiate",
"test samples T: int The number of classifiers (from 1,...,T) to be used",
"import BaseEstimator from IMLearn.base import BaseEstimator from typing import Callable, NoReturn from IMLearn.metrics",
"BaseEstimator self.iterations_: int Number of boosting iterations to perform self.models_: List[BaseEstimator] List of",
"using fitted estimators Parameters ---------- X : ndarray of shape (n_samples, n_features) Input",
"(from 1,...,T) to be used for prediction Returns ------- responses : ndarray of",
"specified base estimator Parameters ---------- wl: Callable[[], BaseEstimator] Callable for obtaining an instance",
"X : ndarray of shape (n_samples, n_features) Input data to fit an estimator",
"if loss is 0, then we have a perfect classifier if epsilon ==",
"to predict responses for Returns ------- responses : ndarray of shape (n_samples, )",
"---------- self.wl_: Callable[[], BaseEstimator] Callable for obtaining an instance of type BaseEstimator self.iterations_:",
"under missclassification loss function \"\"\" y_pred = self.partial_predict(X, T) return misclassification_error(y, y_pred, normalize=True)",
"float: \"\"\" Evaluate performance under misclassification loss function Parameters ---------- X : ndarray",
"shape (n_samples, ) True labels of test samples Returns ------- loss : float",
"(from 1,...,T) to be used for prediction Returns ------- loss : float Performance",
"!= y_pred, 1, 0) return np.sum(misses * sample_weights) def _fit(self, X: np.ndarray, y:",
"1,...,T) to be used for prediction Returns ------- loss : float Performance under",
"sample_weights): \"\"\" Resample the current dataset according to sample_weights \"\"\" new_indices = np.random.choice(cur_y.size,",
") True labels of test samples T: int The number of classifiers (from",
"under misclassification loss function Parameters ---------- X : ndarray of shape (n_samples, n_features)",
"misses = np.where(y_true != y_pred, 1, 0) return np.sum(misses * sample_weights) def _fit(self,",
"@staticmethod def __resample(cur_X, cur_y, sample_weights): \"\"\" Resample the current dataset according to sample_weights",
"ndarray of shape (n_samples, n_features) Input data to predict responses for T: int",
"missclassification loss function \"\"\" return misclassification_error(y, self._predict(X), normalize=True) def partial_predict(self, X: np.ndarray, T:",
"fitted estimators, fitted along the boosting iterations \"\"\" def __init__(self, wl: Callable[[], BaseEstimator],",
"estimators, fitted along the boosting iterations \"\"\" def __init__(self, wl: Callable[[], BaseEstimator], iterations:",
"return self.partial_predict(X, self.iterations_) def _loss(self, X: np.ndarray, y: np.ndarray) -> float: \"\"\" Evaluate",
"n_samples = X.shape[0] self.models_ = [self.wl_() for _ in range(self.iterations_)] self.D_ = np.full(n_samples,",
"(n_samples, ) Predicted responses of given samples \"\"\" T = min(T, self.iterations_) selected_models",
"= iterations self.models_, self.weights_, self.D_ = None, None, None @staticmethod def __resample(cur_X, cur_y,",
"np.sum(self.D_) def _predict(self, X): \"\"\" Predict responses for given samples using fitted estimator",
"classifiers (from 1,...,T) to be used for prediction Returns ------- loss : float",
"-> float: \"\"\" Evaluate performance under misclassification loss function Parameters ---------- X :",
": ndarray of shape (n_samples, ) Responses of input data to fit to",
"X.reshape((-1, 1)) n_samples = X.shape[0] self.models_ = [self.wl_() for _ in range(self.iterations_)] self.D_",
"# from ...base import BaseEstimator from IMLearn.base import BaseEstimator from typing import Callable,",
"class for boosting a specified weak learner Attributes ---------- self.wl_: Callable[[], BaseEstimator] Callable",
"Fit an AdaBoost classifier over given samples Parameters ---------- X : ndarray of",
"to predict responses for T: int The number of classifiers (from 1,...,T) to",
"self.D_ / np.sum(self.D_) def _predict(self, X): \"\"\" Predict responses for given samples using",
"test samples Returns ------- loss : float Performance under missclassification loss function \"\"\"",
"np.zeros(self.iterations_) for i in range(self.iterations_): self.models_[i].fit(X, y * self.D_) y_pred = self.models_[i].predict(X) epsilon",
"classifiers (from 1,...,T) to be used for prediction Returns ------- responses : ndarray",
"to be used for prediction Returns ------- responses : ndarray of shape (n_samples,",
"labels of test samples T: int The number of classifiers (from 1,...,T) to",
"responses of given samples \"\"\" return self.partial_predict(X, self.iterations_) def _loss(self, X: np.ndarray, y:",
"y * self.D_) y_pred = self.models_[i].predict(X) epsilon = self.weighted_loss(y, y_pred, self.D_) # if",
"np # from ...base import BaseEstimator from IMLearn.base import BaseEstimator from typing import",
"AdaBoost class for boosting a specified weak learner Attributes ---------- self.wl_: Callable[[], BaseEstimator]",
": ndarray of shape (n_samples, n_features) Input data to predict responses for Returns",
"misclassification loss function Parameters ---------- X : ndarray of shape (n_samples, n_features) Test",
"size=cur_y.size, p=sample_weights) return cur_X[new_indices, :], cur_y[new_indices] @staticmethod def weighted_loss(y_true, y_pred, sample_weights): \"\"\" Calculate",
"---------- X : ndarray of shape (n_samples, n_features) Input data to fit an",
"a specified weak learner Attributes ---------- self.wl_: Callable[[], BaseEstimator] Callable for obtaining an",
"None @staticmethod def __resample(cur_X, cur_y, sample_weights): \"\"\" Resample the current dataset according to",
"= self.models_[:T] all_learners_pred = np.array([m.predict(X) for m in selected_models]).T weighted_pred = all_learners_pred @",
"of given samples \"\"\" return self.partial_predict(X, self.iterations_) def _loss(self, X: np.ndarray, y: np.ndarray)",
"to be used for prediction Returns ------- loss : float Performance under missclassification",
"self.models_, self.weights_, self.D_ = None, None, None @staticmethod def __resample(cur_X, cur_y, sample_weights): \"\"\"",
"predictions \"\"\" misses = np.where(y_true != y_pred, 1, 0) return np.sum(misses * sample_weights)",
"self._predict(X), normalize=True) def partial_predict(self, X: np.ndarray, T: int) -> np.ndarray: \"\"\" Predict responses",
"given samples \"\"\" return self.partial_predict(X, self.iterations_) def _loss(self, X: np.ndarray, y: np.ndarray) ->",
"self.weights_[i] = np.log(1 / epsilon - 1) / 2 # if cur_loss >",
"of shape (n_samples, n_features) Test samples y : ndarray of shape (n_samples, )",
"for prediction Returns ------- responses : ndarray of shape (n_samples, ) Predicted responses",
"0, then we have a perfect classifier if epsilon == 0: self.weights_ =",
"i + 1 break self.weights_[i] = np.log(1 / epsilon - 1) / 2",
"self.weighted_loss(y, y_pred, self.D_) # if loss is 0, then we have a perfect",
"loss function Parameters ---------- X : ndarray of shape (n_samples, n_features) Test samples",
"given set of predictions \"\"\" misses = np.where(y_true != y_pred, 1, 0) return",
"of classifiers (from 1,...,T) to be used for prediction Returns ------- loss :",
"for Returns ------- responses : ndarray of shape (n_samples, ) Predicted responses of",
"i in range(self.iterations_): self.models_[i].fit(X, y * self.D_) y_pred = self.models_[i].predict(X) epsilon = self.weighted_loss(y,",
"(n_samples, n_features) Test samples y : ndarray of shape (n_samples, ) True labels",
"---------- X : ndarray of shape (n_samples, n_features) Test samples y : ndarray",
"int Number of boosting iterations to perform self.models_: List[BaseEstimator] List of fitted estimators,",
"wl: Callable[[], BaseEstimator] Callable for obtaining an instance of type BaseEstimator iterations: int",
"loss : float Performance under missclassification loss function \"\"\" y_pred = self.partial_predict(X, T)",
"for boosting a specified weak learner Attributes ---------- self.wl_: Callable[[], BaseEstimator] Callable for",
"an AdaBoost class over the specified base estimator Parameters ---------- wl: Callable[[], BaseEstimator]",
"Parameters ---------- X : ndarray of shape (n_samples, n_features) Input data to fit",
") Responses of input data to fit to \"\"\" if len(X.shape) == 1:",
"function Parameters ---------- X : ndarray of shape (n_samples, n_features) Test samples y",
"(n_samples, ) Predicted responses of given samples \"\"\" return self.partial_predict(X, self.iterations_) def _loss(self,",
"2 # if cur_loss > 0 else 1 self.D_ = self.D_ * np.exp(-y",
"of type BaseEstimator iterations: int Number of boosting iterations to perform \"\"\" super().__init__()",
"+ 1 break self.weights_[i] = np.log(1 / epsilon - 1) / 2 #",
"to perform \"\"\" super().__init__() self.wl_ = wl self.iterations_ = iterations self.models_, self.weights_, self.D_",
"np.ndarray, y: np.ndarray) -> NoReturn: \"\"\" Fit an AdaBoost classifier over given samples",
": ndarray of shape (n_samples, n_features) Input data to fit an estimator for",
"np.log(1 / epsilon - 1) / 2 # if cur_loss > 0 else",
"as np # from ...base import BaseEstimator from IMLearn.base import BaseEstimator from typing",
"------- loss : float Performance under missclassification loss function \"\"\" y_pred = self.partial_predict(X,",
"misclassification_error class AdaBoost(BaseEstimator): \"\"\" AdaBoost class for boosting a specified weak learner Attributes",
"ndarray of shape (n_samples, n_features) Input data to fit an estimator for y",
"Predicted responses of given samples \"\"\" T = min(T, self.iterations_) selected_models = self.models_[:T]",
"instance of type BaseEstimator iterations: int Number of boosting iterations to perform \"\"\"",
"for obtaining an instance of type BaseEstimator self.iterations_: int Number of boosting iterations",
"-> np.ndarray: \"\"\" Predict responses for given samples using fitted estimators Parameters ----------",
"sample_weights \"\"\" new_indices = np.random.choice(cur_y.size, size=cur_y.size, p=sample_weights) return cur_X[new_indices, :], cur_y[new_indices] @staticmethod def",
"<reponame>dani3lwinter/IML.HUJI<filename>IMLearn/metalearners/adaboost.py import numpy as np # from ...base import BaseEstimator from IMLearn.base import",
"predict responses for Returns ------- responses : ndarray of shape (n_samples, ) Predicted",
"np.zeros(self.iterations_) self.weights_[i] = 1 self.iterations_ = i + 1 break self.weights_[i] = np.log(1",
"= all_learners_pred @ self.weights_[:T] if len(weighted_pred.shape) == 1: return np.sign(weighted_pred) else: return np.sign(weighted_pred.sum(axis=1))",
"in range(self.iterations_)] self.D_ = np.full(n_samples, 1 / n_samples) self.weights_ = np.zeros(self.iterations_) for i",
"epsilon - 1) / 2 # if cur_loss > 0 else 1 self.D_",
"/ np.sum(self.D_) def _predict(self, X): \"\"\" Predict responses for given samples using fitted",
"n_features) Input data to fit an estimator for y : ndarray of shape",
"\"\"\" AdaBoost class for boosting a specified weak learner Attributes ---------- self.wl_: Callable[[],",
"the specified base estimator Parameters ---------- wl: Callable[[], BaseEstimator] Callable for obtaining an",
"given samples Parameters ---------- X : ndarray of shape (n_samples, n_features) Input data",
"for prediction Returns ------- loss : float Performance under missclassification loss function \"\"\"",
"np.ndarray, T: int) -> float: \"\"\" Evaluate performance under misclassification loss function Parameters",
"(n_samples, n_features) Input data to predict responses for T: int The number of",
"responses of given samples \"\"\" T = min(T, self.iterations_) selected_models = self.models_[:T] all_learners_pred",
"self.models_[i].fit(X, y * self.D_) y_pred = self.models_[i].predict(X) epsilon = self.weighted_loss(y, y_pred, self.D_) #",
"to \"\"\" if len(X.shape) == 1: X = X.reshape((-1, 1)) n_samples = X.shape[0]",
"for given samples using fitted estimators Parameters ---------- X : ndarray of shape",
"number of classifiers (from 1,...,T) to be used for prediction Returns ------- responses",
"Callable for obtaining an instance of type BaseEstimator iterations: int Number of boosting",
"= self.D_ * np.exp(-y * self.weights_[i] * y_pred) self.D_ = self.D_ / np.sum(self.D_)",
"ndarray of shape (n_samples, n_features) Test samples y : ndarray of shape (n_samples,",
"Returns ------- responses : ndarray of shape (n_samples, ) Predicted responses of given",
"in selected_models]).T weighted_pred = all_learners_pred @ self.weights_[:T] if len(weighted_pred.shape) == 1: return np.sign(weighted_pred)",
"T = min(T, self.iterations_) selected_models = self.models_[:T] all_learners_pred = np.array([m.predict(X) for m in",
"int Number of boosting iterations to perform \"\"\" super().__init__() self.wl_ = wl self.iterations_",
"self.weights_[i] * y_pred) self.D_ = self.D_ / np.sum(self.D_) def _predict(self, X): \"\"\" Predict",
"for i in range(self.iterations_): self.models_[i].fit(X, y * self.D_) y_pred = self.models_[i].predict(X) epsilon =",
"\"\"\" def __init__(self, wl: Callable[[], BaseEstimator], iterations: int): \"\"\" Instantiate an AdaBoost class",
"_ in range(self.iterations_)] self.D_ = np.full(n_samples, 1 / n_samples) self.weights_ = np.zeros(self.iterations_) for",
"self.weights_[:T] if len(weighted_pred.shape) == 1: return np.sign(weighted_pred) else: return np.sign(weighted_pred.sum(axis=1)) def partial_loss(self, X:",
"fit to \"\"\" if len(X.shape) == 1: X = X.reshape((-1, 1)) n_samples =",
"self.D_) y_pred = self.models_[i].predict(X) epsilon = self.weighted_loss(y, y_pred, self.D_) # if loss is",
"= None, None, None @staticmethod def __resample(cur_X, cur_y, sample_weights): \"\"\" Resample the current",
"------- responses : ndarray of shape (n_samples, ) Predicted responses of given samples",
"NoReturn from IMLearn.metrics import misclassification_error class AdaBoost(BaseEstimator): \"\"\" AdaBoost class for boosting a",
"\"\"\" Fit an AdaBoost classifier over given samples Parameters ---------- X : ndarray",
"Calculate the weighted loss for a given set of predictions \"\"\" misses =",
"Test samples y : ndarray of shape (n_samples, ) True labels of test",
"np.sign(weighted_pred.sum(axis=1)) def partial_loss(self, X: np.ndarray, y: np.ndarray, T: int) -> float: \"\"\" Evaluate",
"self.iterations_) selected_models = self.models_[:T] all_learners_pred = np.array([m.predict(X) for m in selected_models]).T weighted_pred =",
": ndarray of shape (n_samples, ) Predicted responses of given samples \"\"\" T",
"return cur_X[new_indices, :], cur_y[new_indices] @staticmethod def weighted_loss(y_true, y_pred, sample_weights): \"\"\" Calculate the weighted",
"= [self.wl_() for _ in range(self.iterations_)] self.D_ = np.full(n_samples, 1 / n_samples) self.weights_",
"ndarray of shape (n_samples, ) Predicted responses of given samples \"\"\" return self.partial_predict(X,",
"wl self.iterations_ = iterations self.models_, self.weights_, self.D_ = None, None, None @staticmethod def",
"selected_models]).T weighted_pred = all_learners_pred @ self.weights_[:T] if len(weighted_pred.shape) == 1: return np.sign(weighted_pred) else:",
"y: np.ndarray) -> NoReturn: \"\"\" Fit an AdaBoost classifier over given samples Parameters",
"of shape (n_samples, ) True labels of test samples T: int The number",
"all_learners_pred @ self.weights_[:T] if len(weighted_pred.shape) == 1: return np.sign(weighted_pred) else: return np.sign(weighted_pred.sum(axis=1)) def",
"np.ndarray) -> float: \"\"\" Evaluate performance under misclassification loss function Parameters ---------- X",
"y: np.ndarray) -> float: \"\"\" Evaluate performance under misclassification loss function Parameters ----------",
"self.models_[:T] all_learners_pred = np.array([m.predict(X) for m in selected_models]).T weighted_pred = all_learners_pred @ self.weights_[:T]",
"...base import BaseEstimator from IMLearn.base import BaseEstimator from typing import Callable, NoReturn from",
"have a perfect classifier if epsilon == 0: self.weights_ = np.zeros(self.iterations_) self.weights_[i] =",
"return np.sign(weighted_pred.sum(axis=1)) def partial_loss(self, X: np.ndarray, y: np.ndarray, T: int) -> float: \"\"\"",
"Callable for obtaining an instance of type BaseEstimator self.iterations_: int Number of boosting",
"estimator for y : ndarray of shape (n_samples, ) Responses of input data",
"along the boosting iterations \"\"\" def __init__(self, wl: Callable[[], BaseEstimator], iterations: int): \"\"\"",
"epsilon == 0: self.weights_ = np.zeros(self.iterations_) self.weights_[i] = 1 self.iterations_ = i +",
"\"\"\" Resample the current dataset according to sample_weights \"\"\" new_indices = np.random.choice(cur_y.size, size=cur_y.size,",
"\"\"\" T = min(T, self.iterations_) selected_models = self.models_[:T] all_learners_pred = np.array([m.predict(X) for m",
"of shape (n_samples, n_features) Input data to fit an estimator for y :",
"= X.shape[0] self.models_ = [self.wl_() for _ in range(self.iterations_)] self.D_ = np.full(n_samples, 1",
"self.iterations_ = i + 1 break self.weights_[i] = np.log(1 / epsilon - 1)",
"classifier over given samples Parameters ---------- X : ndarray of shape (n_samples, n_features)",
"shape (n_samples, ) Predicted responses of given samples \"\"\" return self.partial_predict(X, self.iterations_) def",
"estimator Parameters ---------- X : ndarray of shape (n_samples, n_features) Input data to",
"1 / n_samples) self.weights_ = np.zeros(self.iterations_) for i in range(self.iterations_): self.models_[i].fit(X, y *",
"T: int) -> np.ndarray: \"\"\" Predict responses for given samples using fitted estimators",
"AdaBoost(BaseEstimator): \"\"\" AdaBoost class for boosting a specified weak learner Attributes ---------- self.wl_:",
"BaseEstimator from typing import Callable, NoReturn from IMLearn.metrics import misclassification_error class AdaBoost(BaseEstimator): \"\"\"",
"from ...base import BaseEstimator from IMLearn.base import BaseEstimator from typing import Callable, NoReturn",
"samples \"\"\" return self.partial_predict(X, self.iterations_) def _loss(self, X: np.ndarray, y: np.ndarray) -> float:",
"min(T, self.iterations_) selected_models = self.models_[:T] all_learners_pred = np.array([m.predict(X) for m in selected_models]).T weighted_pred",
"wl: Callable[[], BaseEstimator], iterations: int): \"\"\" Instantiate an AdaBoost class over the specified",
"X: np.ndarray, y: np.ndarray) -> float: \"\"\" Evaluate performance under misclassification loss function",
"range(self.iterations_): self.models_[i].fit(X, y * self.D_) y_pred = self.models_[i].predict(X) epsilon = self.weighted_loss(y, y_pred, self.D_)",
"\"\"\" new_indices = np.random.choice(cur_y.size, size=cur_y.size, p=sample_weights) return cur_X[new_indices, :], cur_y[new_indices] @staticmethod def weighted_loss(y_true,",
"be used for prediction Returns ------- loss : float Performance under missclassification loss",
"Parameters ---------- X : ndarray of shape (n_samples, n_features) Input data to predict",
"shape (n_samples, n_features) Input data to fit an estimator for y : ndarray",
"1 self.D_ = self.D_ * np.exp(-y * self.weights_[i] * y_pred) self.D_ = self.D_",
"of shape (n_samples, n_features) Input data to predict responses for Returns ------- responses",
"T: int) -> float: \"\"\" Evaluate performance under misclassification loss function Parameters ----------",
"np.ndarray, T: int) -> np.ndarray: \"\"\" Predict responses for given samples using fitted",
"of shape (n_samples, ) Responses of input data to fit to \"\"\" if",
"y : ndarray of shape (n_samples, ) True labels of test samples T:",
"The number of classifiers (from 1,...,T) to be used for prediction Returns -------",
"shape (n_samples, ) Predicted responses of given samples \"\"\" T = min(T, self.iterations_)",
"fitted estimators Parameters ---------- X : ndarray of shape (n_samples, n_features) Input data",
"prediction Returns ------- responses : ndarray of shape (n_samples, ) Predicted responses of",
": float Performance under missclassification loss function \"\"\" y_pred = self.partial_predict(X, T) return",
"None, None, None @staticmethod def __resample(cur_X, cur_y, sample_weights): \"\"\" Resample the current dataset",
"X = X.reshape((-1, 1)) n_samples = X.shape[0] self.models_ = [self.wl_() for _ in",
"shape (n_samples, ) True labels of test samples T: int The number of",
"BaseEstimator], iterations: int): \"\"\" Instantiate an AdaBoost class over the specified base estimator",
"loss is 0, then we have a perfect classifier if epsilon == 0:",
"Callable, NoReturn from IMLearn.metrics import misclassification_error class AdaBoost(BaseEstimator): \"\"\" AdaBoost class for boosting",
"True labels of test samples Returns ------- loss : float Performance under missclassification",
"to fit an estimator for y : ndarray of shape (n_samples, ) Responses",
"perform self.models_: List[BaseEstimator] List of fitted estimators, fitted along the boosting iterations \"\"\"",
"np.sign(weighted_pred) else: return np.sign(weighted_pred.sum(axis=1)) def partial_loss(self, X: np.ndarray, y: np.ndarray, T: int) ->",
"np.sum(misses * sample_weights) def _fit(self, X: np.ndarray, y: np.ndarray) -> NoReturn: \"\"\" Fit",
"n_samples) self.weights_ = np.zeros(self.iterations_) for i in range(self.iterations_): self.models_[i].fit(X, y * self.D_) y_pred",
"responses for given samples using fitted estimator Parameters ---------- X : ndarray of",
"responses : ndarray of shape (n_samples, ) Predicted responses of given samples \"\"\"",
"1,...,T) to be used for prediction Returns ------- responses : ndarray of shape",
"type BaseEstimator iterations: int Number of boosting iterations to perform \"\"\" super().__init__() self.wl_",
"class AdaBoost(BaseEstimator): \"\"\" AdaBoost class for boosting a specified weak learner Attributes ----------",
"boosting a specified weak learner Attributes ---------- self.wl_: Callable[[], BaseEstimator] Callable for obtaining",
"T: int The number of classifiers (from 1,...,T) to be used for prediction",
"then we have a perfect classifier if epsilon == 0: self.weights_ = np.zeros(self.iterations_)",
"np.exp(-y * self.weights_[i] * y_pred) self.D_ = self.D_ / np.sum(self.D_) def _predict(self, X):",
":], cur_y[new_indices] @staticmethod def weighted_loss(y_true, y_pred, sample_weights): \"\"\" Calculate the weighted loss for",
"else: return np.sign(weighted_pred.sum(axis=1)) def partial_loss(self, X: np.ndarray, y: np.ndarray, T: int) -> float:",
"used for prediction Returns ------- responses : ndarray of shape (n_samples, ) Predicted",
"np.ndarray, y: np.ndarray, T: int) -> float: \"\"\" Evaluate performance under misclassification loss",
"self.D_) # if loss is 0, then we have a perfect classifier if",
"> 0 else 1 self.D_ = self.D_ * np.exp(-y * self.weights_[i] * y_pred)",
"ndarray of shape (n_samples, n_features) Input data to predict responses for Returns -------",
"of test samples Returns ------- loss : float Performance under missclassification loss function",
"of fitted estimators, fitted along the boosting iterations \"\"\" def __init__(self, wl: Callable[[],",
"n_features) Input data to predict responses for T: int The number of classifiers",
"according to sample_weights \"\"\" new_indices = np.random.choice(cur_y.size, size=cur_y.size, p=sample_weights) return cur_X[new_indices, :], cur_y[new_indices]",
"(n_samples, ) Responses of input data to fit to \"\"\" if len(X.shape) ==",
"from IMLearn.metrics import misclassification_error class AdaBoost(BaseEstimator): \"\"\" AdaBoost class for boosting a specified",
"1, 0) return np.sum(misses * sample_weights) def _fit(self, X: np.ndarray, y: np.ndarray) ->",
"of given samples \"\"\" T = min(T, self.iterations_) selected_models = self.models_[:T] all_learners_pred =",
"self.D_ = self.D_ / np.sum(self.D_) def _predict(self, X): \"\"\" Predict responses for given",
"loss : float Performance under missclassification loss function \"\"\" return misclassification_error(y, self._predict(X), normalize=True)",
"0: self.weights_ = np.zeros(self.iterations_) self.weights_[i] = 1 self.iterations_ = i + 1 break",
"1 break self.weights_[i] = np.log(1 / epsilon - 1) / 2 # if",
"cur_loss > 0 else 1 self.D_ = self.D_ * np.exp(-y * self.weights_[i] *",
"using fitted estimator Parameters ---------- X : ndarray of shape (n_samples, n_features) Input",
"\"\"\" Instantiate an AdaBoost class over the specified base estimator Parameters ---------- wl:"
] |
[
"_decimal128_INF, _decimal128_NaN_ls, ) __all__ = [ \"FieldWalker\", \"FieldWriteError\", \"_no_val\", \"Weighted\", \"gravity\", \"_cmp_decimal\", \"_decimal128_INF\",",
".field_walker import ( FieldWalker, FieldWriteError, _no_val, ) from .weighted import ( Weighted, gravity,",
"( FieldWalker, FieldWriteError, _no_val, ) from .weighted import ( Weighted, gravity, _cmp_decimal, _decimal128_INF,",
".weighted import ( Weighted, gravity, _cmp_decimal, _decimal128_INF, _decimal128_NaN_ls, ) __all__ = [ \"FieldWalker\",",
"<gh_stars>0 from .field_walker import ( FieldWalker, FieldWriteError, _no_val, ) from .weighted import (",
"( Weighted, gravity, _cmp_decimal, _decimal128_INF, _decimal128_NaN_ls, ) __all__ = [ \"FieldWalker\", \"FieldWriteError\", \"_no_val\",",
"_cmp_decimal, _decimal128_INF, _decimal128_NaN_ls, ) __all__ = [ \"FieldWalker\", \"FieldWriteError\", \"_no_val\", \"Weighted\", \"gravity\", \"_cmp_decimal\",",
"FieldWriteError, _no_val, ) from .weighted import ( Weighted, gravity, _cmp_decimal, _decimal128_INF, _decimal128_NaN_ls, )",
"Weighted, gravity, _cmp_decimal, _decimal128_INF, _decimal128_NaN_ls, ) __all__ = [ \"FieldWalker\", \"FieldWriteError\", \"_no_val\", \"Weighted\",",
"_no_val, ) from .weighted import ( Weighted, gravity, _cmp_decimal, _decimal128_INF, _decimal128_NaN_ls, ) __all__",
") __all__ = [ \"FieldWalker\", \"FieldWriteError\", \"_no_val\", \"Weighted\", \"gravity\", \"_cmp_decimal\", \"_decimal128_INF\", \"_decimal128_NaN_ls\", ]",
"FieldWalker, FieldWriteError, _no_val, ) from .weighted import ( Weighted, gravity, _cmp_decimal, _decimal128_INF, _decimal128_NaN_ls,",
") from .weighted import ( Weighted, gravity, _cmp_decimal, _decimal128_INF, _decimal128_NaN_ls, ) __all__ =",
"import ( FieldWalker, FieldWriteError, _no_val, ) from .weighted import ( Weighted, gravity, _cmp_decimal,",
"import ( Weighted, gravity, _cmp_decimal, _decimal128_INF, _decimal128_NaN_ls, ) __all__ = [ \"FieldWalker\", \"FieldWriteError\",",
"_decimal128_NaN_ls, ) __all__ = [ \"FieldWalker\", \"FieldWriteError\", \"_no_val\", \"Weighted\", \"gravity\", \"_cmp_decimal\", \"_decimal128_INF\", \"_decimal128_NaN_ls\",",
"gravity, _cmp_decimal, _decimal128_INF, _decimal128_NaN_ls, ) __all__ = [ \"FieldWalker\", \"FieldWriteError\", \"_no_val\", \"Weighted\", \"gravity\",",
"from .field_walker import ( FieldWalker, FieldWriteError, _no_val, ) from .weighted import ( Weighted,",
"from .weighted import ( Weighted, gravity, _cmp_decimal, _decimal128_INF, _decimal128_NaN_ls, ) __all__ = ["
] |
[
"common_ancestors, kinship # Reading and writing files import pydigree.io # Population growth models",
"from pydigree.ibs import ibs from pydigree.rand import set_seed # Functions for navigating pedigree",
"Functions and classes for doing statistics import pydigree.stats # Functions for identifying shared",
"Population growth models from pydigree.population import exponential_growth, logistic_growth # Classes from pydigree.genotypes import",
"import Population from pydigree.pedigreecollection import PedigreeCollection from pydigree.pedigree import Pedigree from pydigree.individual import",
"pydigree.pedigree import Pedigree from pydigree.individual import Individual # Functions and classes for doing",
"ImportError('pydigree requires Python 3') # Common functions (cumsum, table, etc) import pydigree.common from",
"Classes from pydigree.genotypes import ChromosomeTemplate from pydigree.population import Population from pydigree.pedigreecollection import PedigreeCollection",
"#!/usr/bin/env python import sys if sys.version_info < (3,3): raise ImportError('pydigree requires Python 3')",
"# Functions for navigating pedigree structures from pydigree.paths import path_downward, paths, paths_through_ancestor from",
"import common_ancestors, kinship # Reading and writing files import pydigree.io # Population growth",
"from pydigree.paths import common_ancestors, kinship # Reading and writing files import pydigree.io #",
"writing files import pydigree.io # Population growth models from pydigree.population import exponential_growth, logistic_growth",
"if sys.version_info < (3,3): raise ImportError('pydigree requires Python 3') # Common functions (cumsum,",
"and classes for doing statistics import pydigree.stats # Functions for identifying shared genomic",
"growth models from pydigree.population import exponential_growth, logistic_growth # Classes from pydigree.genotypes import ChromosomeTemplate",
"from pydigree.genotypes import ChromosomeTemplate from pydigree.population import Population from pydigree.pedigreecollection import PedigreeCollection from",
"statistics import pydigree.stats # Functions for identifying shared genomic segments (SGS) import pydigree.sgs",
"sys if sys.version_info < (3,3): raise ImportError('pydigree requires Python 3') # Common functions",
"# Classes from pydigree.genotypes import ChromosomeTemplate from pydigree.population import Population from pydigree.pedigreecollection import",
"import Individual # Functions and classes for doing statistics import pydigree.stats # Functions",
"models from pydigree.population import exponential_growth, logistic_growth # Classes from pydigree.genotypes import ChromosomeTemplate from",
"from pydigree.population import Population from pydigree.pedigreecollection import PedigreeCollection from pydigree.pedigree import Pedigree from",
"pydigree.paths import common_ancestors, kinship # Reading and writing files import pydigree.io # Population",
"structures from pydigree.paths import path_downward, paths, paths_through_ancestor from pydigree.paths import common_ancestors, kinship #",
"import Pedigree from pydigree.individual import Individual # Functions and classes for doing statistics",
"functions (cumsum, table, etc) import pydigree.common from pydigree.ibs import ibs from pydigree.rand import",
"classes for doing statistics import pydigree.stats # Functions for identifying shared genomic segments",
"from pydigree.individual import Individual # Functions and classes for doing statistics import pydigree.stats",
"Common functions (cumsum, table, etc) import pydigree.common from pydigree.ibs import ibs from pydigree.rand",
"kinship # Reading and writing files import pydigree.io # Population growth models from",
"(3,3): raise ImportError('pydigree requires Python 3') # Common functions (cumsum, table, etc) import",
"import pydigree.common from pydigree.ibs import ibs from pydigree.rand import set_seed # Functions for",
"import sys if sys.version_info < (3,3): raise ImportError('pydigree requires Python 3') # Common",
"path_downward, paths, paths_through_ancestor from pydigree.paths import common_ancestors, kinship # Reading and writing files",
"for doing statistics import pydigree.stats # Functions for identifying shared genomic segments (SGS)",
"from pydigree.rand import set_seed # Functions for navigating pedigree structures from pydigree.paths import",
"requires Python 3') # Common functions (cumsum, table, etc) import pydigree.common from pydigree.ibs",
"Population from pydigree.pedigreecollection import PedigreeCollection from pydigree.pedigree import Pedigree from pydigree.individual import Individual",
"pydigree.common from pydigree.ibs import ibs from pydigree.rand import set_seed # Functions for navigating",
"files import pydigree.io # Population growth models from pydigree.population import exponential_growth, logistic_growth #",
"pydigree.paths import path_downward, paths, paths_through_ancestor from pydigree.paths import common_ancestors, kinship # Reading and",
"sys.version_info < (3,3): raise ImportError('pydigree requires Python 3') # Common functions (cumsum, table,",
"# Population growth models from pydigree.population import exponential_growth, logistic_growth # Classes from pydigree.genotypes",
"ChromosomeTemplate from pydigree.population import Population from pydigree.pedigreecollection import PedigreeCollection from pydigree.pedigree import Pedigree",
"3') # Common functions (cumsum, table, etc) import pydigree.common from pydigree.ibs import ibs",
"from pydigree.pedigree import Pedigree from pydigree.individual import Individual # Functions and classes for",
"import exponential_growth, logistic_growth # Classes from pydigree.genotypes import ChromosomeTemplate from pydigree.population import Population",
"pedigree structures from pydigree.paths import path_downward, paths, paths_through_ancestor from pydigree.paths import common_ancestors, kinship",
"logistic_growth # Classes from pydigree.genotypes import ChromosomeTemplate from pydigree.population import Population from pydigree.pedigreecollection",
"raise ImportError('pydigree requires Python 3') # Common functions (cumsum, table, etc) import pydigree.common",
"from pydigree.population import exponential_growth, logistic_growth # Classes from pydigree.genotypes import ChromosomeTemplate from pydigree.population",
"pydigree.pedigreecollection import PedigreeCollection from pydigree.pedigree import Pedigree from pydigree.individual import Individual # Functions",
"from pydigree.pedigreecollection import PedigreeCollection from pydigree.pedigree import Pedigree from pydigree.individual import Individual #",
"# Common functions (cumsum, table, etc) import pydigree.common from pydigree.ibs import ibs from",
"# Reading and writing files import pydigree.io # Population growth models from pydigree.population",
"pydigree.io # Population growth models from pydigree.population import exponential_growth, logistic_growth # Classes from",
"navigating pedigree structures from pydigree.paths import path_downward, paths, paths_through_ancestor from pydigree.paths import common_ancestors,",
"Python 3') # Common functions (cumsum, table, etc) import pydigree.common from pydigree.ibs import",
"paths, paths_through_ancestor from pydigree.paths import common_ancestors, kinship # Reading and writing files import",
"python import sys if sys.version_info < (3,3): raise ImportError('pydigree requires Python 3') #",
"ibs from pydigree.rand import set_seed # Functions for navigating pedigree structures from pydigree.paths",
"import path_downward, paths, paths_through_ancestor from pydigree.paths import common_ancestors, kinship # Reading and writing",
"import ibs from pydigree.rand import set_seed # Functions for navigating pedigree structures from",
"< (3,3): raise ImportError('pydigree requires Python 3') # Common functions (cumsum, table, etc)",
"etc) import pydigree.common from pydigree.ibs import ibs from pydigree.rand import set_seed # Functions",
"Pedigree from pydigree.individual import Individual # Functions and classes for doing statistics import",
"pydigree.individual import Individual # Functions and classes for doing statistics import pydigree.stats #",
"for navigating pedigree structures from pydigree.paths import path_downward, paths, paths_through_ancestor from pydigree.paths import",
"Individual # Functions and classes for doing statistics import pydigree.stats # Functions for",
"table, etc) import pydigree.common from pydigree.ibs import ibs from pydigree.rand import set_seed #",
"pydigree.rand import set_seed # Functions for navigating pedigree structures from pydigree.paths import path_downward,",
"doing statistics import pydigree.stats # Functions for identifying shared genomic segments (SGS) import",
"pydigree.genotypes import ChromosomeTemplate from pydigree.population import Population from pydigree.pedigreecollection import PedigreeCollection from pydigree.pedigree",
"Reading and writing files import pydigree.io # Population growth models from pydigree.population import",
"pydigree.ibs import ibs from pydigree.rand import set_seed # Functions for navigating pedigree structures",
"import PedigreeCollection from pydigree.pedigree import Pedigree from pydigree.individual import Individual # Functions and",
"# Functions and classes for doing statistics import pydigree.stats # Functions for identifying",
"and writing files import pydigree.io # Population growth models from pydigree.population import exponential_growth,",
"PedigreeCollection from pydigree.pedigree import Pedigree from pydigree.individual import Individual # Functions and classes",
"(cumsum, table, etc) import pydigree.common from pydigree.ibs import ibs from pydigree.rand import set_seed",
"Functions for navigating pedigree structures from pydigree.paths import path_downward, paths, paths_through_ancestor from pydigree.paths",
"pydigree.population import Population from pydigree.pedigreecollection import PedigreeCollection from pydigree.pedigree import Pedigree from pydigree.individual",
"paths_through_ancestor from pydigree.paths import common_ancestors, kinship # Reading and writing files import pydigree.io",
"exponential_growth, logistic_growth # Classes from pydigree.genotypes import ChromosomeTemplate from pydigree.population import Population from",
"pydigree.population import exponential_growth, logistic_growth # Classes from pydigree.genotypes import ChromosomeTemplate from pydigree.population import",
"import ChromosomeTemplate from pydigree.population import Population from pydigree.pedigreecollection import PedigreeCollection from pydigree.pedigree import",
"set_seed # Functions for navigating pedigree structures from pydigree.paths import path_downward, paths, paths_through_ancestor",
"import set_seed # Functions for navigating pedigree structures from pydigree.paths import path_downward, paths,",
"import pydigree.io # Population growth models from pydigree.population import exponential_growth, logistic_growth # Classes",
"from pydigree.paths import path_downward, paths, paths_through_ancestor from pydigree.paths import common_ancestors, kinship # Reading"
] |
[
"========================================================= This file is subject to the MIT license copyright notice. ========================================================= Script",
"Script to test speedtest related objects. \"\"\" #imports import pdb from mysql.connector.errors import",
"pdb from mysql.connector.errors import DataError import dbIntfObj import SpeedTestObj if __name__ == \"__main__\":",
"import SpeedTestObj if __name__ == \"__main__\": #create connection to database dbTable = dbIntfObj.networkDataTable()",
"dbIntfObj import SpeedTestObj if __name__ == \"__main__\": #create connection to database dbTable =",
"test = SpeedTestObj.SpeedTest() test.run_bestTest() #get data as formatted dictionary, sanitize, and insert into",
"related objects. \"\"\" #imports import pdb from mysql.connector.errors import DataError import dbIntfObj import",
"subject to the MIT license copyright notice. ========================================================= Script to test speedtest related",
"speedtest related objects. \"\"\" #imports import pdb from mysql.connector.errors import DataError import dbIntfObj",
"\"__main__\": #create connection to database dbTable = dbIntfObj.networkDataTable() #run a speed test test",
"connection to database dbTable = dbIntfObj.networkDataTable() #run a speed test test = SpeedTestObj.SpeedTest()",
"a speed test test = SpeedTestObj.SpeedTest() test.run_bestTest() #get data as formatted dictionary, sanitize,",
"= SpeedTestObj.SpeedTest() test.run_bestTest() #get data as formatted dictionary, sanitize, and insert into db",
"test.run_bestTest() #get data as formatted dictionary, sanitize, and insert into db results =",
"and insert into db results = test.get_testData() try: dbTable.record_newEntry(server=results['server'], ping=results['ping'], upload=results['upload'], download=results['download']) except:",
"mysql.connector.errors import DataError import dbIntfObj import SpeedTestObj if __name__ == \"__main__\": #create connection",
"#run a speed test test = SpeedTestObj.SpeedTest() test.run_bestTest() #get data as formatted dictionary,",
"========================================================= Script to test speedtest related objects. \"\"\" #imports import pdb from mysql.connector.errors",
"objects. \"\"\" #imports import pdb from mysql.connector.errors import DataError import dbIntfObj import SpeedTestObj",
"results = test.get_testData() try: dbTable.record_newEntry(server=results['server'], ping=results['ping'], upload=results['upload'], download=results['download']) except: raise DataError(\"Could not record",
"license copyright notice. ========================================================= Script to test speedtest related objects. \"\"\" #imports import",
"is subject to the MIT license copyright notice. ========================================================= Script to test speedtest",
"copyright notice. ========================================================= Script to test speedtest related objects. \"\"\" #imports import pdb",
"from mysql.connector.errors import DataError import dbIntfObj import SpeedTestObj if __name__ == \"__main__\": #create",
"<NAME> date: 12/30/21 email: <EMAIL> ========================================================= This file is subject to the MIT",
"dictionary, sanitize, and insert into db results = test.get_testData() try: dbTable.record_newEntry(server=results['server'], ping=results['ping'], upload=results['upload'],",
"import dbIntfObj import SpeedTestObj if __name__ == \"__main__\": #create connection to database dbTable",
"database dbTable = dbIntfObj.networkDataTable() #run a speed test test = SpeedTestObj.SpeedTest() test.run_bestTest() #get",
"DataError import dbIntfObj import SpeedTestObj if __name__ == \"__main__\": #create connection to database",
"12/30/21 email: <EMAIL> ========================================================= This file is subject to the MIT license copyright",
"import DataError import dbIntfObj import SpeedTestObj if __name__ == \"__main__\": #create connection to",
"email: <EMAIL> ========================================================= This file is subject to the MIT license copyright notice.",
"formatted dictionary, sanitize, and insert into db results = test.get_testData() try: dbTable.record_newEntry(server=results['server'], ping=results['ping'],",
"= test.get_testData() try: dbTable.record_newEntry(server=results['server'], ping=results['ping'], upload=results['upload'], download=results['download']) except: raise DataError(\"Could not record new",
"SpeedTestObj if __name__ == \"__main__\": #create connection to database dbTable = dbIntfObj.networkDataTable() #run",
"to test speedtest related objects. \"\"\" #imports import pdb from mysql.connector.errors import DataError",
"\"\"\" author(s): <NAME> date: 12/30/21 email: <EMAIL> ========================================================= This file is subject to",
"#get data as formatted dictionary, sanitize, and insert into db results = test.get_testData()",
"to database dbTable = dbIntfObj.networkDataTable() #run a speed test test = SpeedTestObj.SpeedTest() test.run_bestTest()",
"This file is subject to the MIT license copyright notice. ========================================================= Script to",
"== \"__main__\": #create connection to database dbTable = dbIntfObj.networkDataTable() #run a speed test",
"speed test test = SpeedTestObj.SpeedTest() test.run_bestTest() #get data as formatted dictionary, sanitize, and",
"into db results = test.get_testData() try: dbTable.record_newEntry(server=results['server'], ping=results['ping'], upload=results['upload'], download=results['download']) except: raise DataError(\"Could",
"<EMAIL> ========================================================= This file is subject to the MIT license copyright notice. =========================================================",
"dbIntfObj.networkDataTable() #run a speed test test = SpeedTestObj.SpeedTest() test.run_bestTest() #get data as formatted",
"if __name__ == \"__main__\": #create connection to database dbTable = dbIntfObj.networkDataTable() #run a",
"file is subject to the MIT license copyright notice. ========================================================= Script to test",
"__name__ == \"__main__\": #create connection to database dbTable = dbIntfObj.networkDataTable() #run a speed",
"= dbIntfObj.networkDataTable() #run a speed test test = SpeedTestObj.SpeedTest() test.run_bestTest() #get data as",
"SpeedTestObj.SpeedTest() test.run_bestTest() #get data as formatted dictionary, sanitize, and insert into db results",
"as formatted dictionary, sanitize, and insert into db results = test.get_testData() try: dbTable.record_newEntry(server=results['server'],",
"insert into db results = test.get_testData() try: dbTable.record_newEntry(server=results['server'], ping=results['ping'], upload=results['upload'], download=results['download']) except: raise",
"db results = test.get_testData() try: dbTable.record_newEntry(server=results['server'], ping=results['ping'], upload=results['upload'], download=results['download']) except: raise DataError(\"Could not",
"\"\"\" #imports import pdb from mysql.connector.errors import DataError import dbIntfObj import SpeedTestObj if",
"test test = SpeedTestObj.SpeedTest() test.run_bestTest() #get data as formatted dictionary, sanitize, and insert",
"data as formatted dictionary, sanitize, and insert into db results = test.get_testData() try:",
"author(s): <NAME> date: 12/30/21 email: <EMAIL> ========================================================= This file is subject to the",
"<reponame>atabulog/rpi-dashboard<gh_stars>0 \"\"\" author(s): <NAME> date: 12/30/21 email: <EMAIL> ========================================================= This file is subject",
"notice. ========================================================= Script to test speedtest related objects. \"\"\" #imports import pdb from",
"test speedtest related objects. \"\"\" #imports import pdb from mysql.connector.errors import DataError import",
"#imports import pdb from mysql.connector.errors import DataError import dbIntfObj import SpeedTestObj if __name__",
"import pdb from mysql.connector.errors import DataError import dbIntfObj import SpeedTestObj if __name__ ==",
"dbTable = dbIntfObj.networkDataTable() #run a speed test test = SpeedTestObj.SpeedTest() test.run_bestTest() #get data",
"sanitize, and insert into db results = test.get_testData() try: dbTable.record_newEntry(server=results['server'], ping=results['ping'], upload=results['upload'], download=results['download'])",
"to the MIT license copyright notice. ========================================================= Script to test speedtest related objects.",
"#create connection to database dbTable = dbIntfObj.networkDataTable() #run a speed test test =",
"date: 12/30/21 email: <EMAIL> ========================================================= This file is subject to the MIT license",
"MIT license copyright notice. ========================================================= Script to test speedtest related objects. \"\"\" #imports",
"test.get_testData() try: dbTable.record_newEntry(server=results['server'], ping=results['ping'], upload=results['upload'], download=results['download']) except: raise DataError(\"Could not record new entry.\")",
"the MIT license copyright notice. ========================================================= Script to test speedtest related objects. \"\"\""
] |
[
"vec3 color2 = texture(Color2, v_text * 6.0).rgb; vec3 color = color1 * (1.0",
"7.0).rgb; vec3 color2 = texture(Color2, v_text * 6.0).rgb; vec3 color = color1 *",
"uniform sampler2D Cracks; uniform sampler2D Darken; in vec2 v_text; out vec4 f_color; void",
"} '''), ]) img0 = Image.open('data/heightmap.jpg').convert('L').transpose(Image.FLIP_TOP_BOTTOM) img1 = Image.open('data/grass.jpg').convert('RGB').transpose(Image.FLIP_TOP_BOTTOM) img2 = Image.open('data/rock.jpg').convert('RGB').transpose(Image.FLIP_TOP_BOTTOM) img3",
"* texture(Cracks, v_text * 5.0).r; color *= 0.5 + 0.5 * height; f_color",
"= ctx.texture(img2.size, 3, img2.tobytes()) tex3 = ctx.texture(img3.size, 1, img3.tobytes()) tex4 = ctx.texture(img4.size, 1,",
"+= 1 vertices += struct.pack('2f', (i + 1) / 64, j / 64)",
"v_text * 3.0).r; color *= 0.5 + 0.5 * texture(Cracks, v_text * 5.0).r;",
"* 3.0).r; color *= 0.5 + 0.5 * texture(Cracks, v_text * 5.0).r; color",
"= ctx.vertex_array(prog, [(vbo, '2f', ['vert'])], ibo) while wnd.update(): angle = wnd.time * 0.5",
"import Matrix44 wnd = GLWindow.create_window() ctx = ModernGL.create_context() prog = ctx.program([ ctx.vertex_shader(''' #version",
"Darken; in vec2 v_text; out vec4 f_color; void main() { float height =",
"1 prog.uniforms['Color2'].value = 2 prog.uniforms['Cracks'].value = 3 prog.uniforms['Darken'].value = 4 index = 0",
"Matrix44 wnd = GLWindow.create_window() ctx = ModernGL.create_context() prog = ctx.program([ ctx.vertex_shader(''' #version 330",
"64, j / 64) indices += struct.pack('i', index) index += 1 indices +=",
"angle = wnd.time * 0.5 width, height = wnd.size proj = Matrix44.perspective_projection(45.0, width",
"1) / 64, j / 64) indices += struct.pack('i', index) index += 1",
"[(vbo, '2f', ['vert'])], ibo) while wnd.update(): angle = wnd.time * 0.5 width, height",
"0.2, 1.0); gl_Position = Mvp * vertex; v_text = vert; } '''), ctx.fragment_shader('''",
"Color2; uniform sampler2D Cracks; uniform sampler2D Darken; in vec2 v_text; out vec4 f_color;",
"{ vec4 vertex = vec4(vert - 0.5, texture(Heightmap, vert).r * 0.2, 1.0); gl_Position",
"float height = texture(Heightmap, v_text).r; float border = smoothstep(0.5, 0.7, height); vec3 color1",
"vec4(vert - 0.5, texture(Heightmap, vert).r * 0.2, 1.0); gl_Position = Mvp * vertex;",
"0.5 + 0.5 * texture(Cracks, v_text * 5.0).r; color *= 0.5 + 0.5",
"* (1.0 - border) + color2 * border; color *= 0.8 + 0.2",
"tex4 = ctx.texture(img4.size, 1, img4.tobytes()) tex0.build_mipmaps() tex1.build_mipmaps() tex2.build_mipmaps() tex3.build_mipmaps() tex4.build_mipmaps() tex0.use(0) tex1.use(1) tex2.use(2)",
"* 7.0).rgb; vec3 color2 = texture(Color2, v_text * 6.0).rgb; vec3 color = color1",
"border; color *= 0.8 + 0.2 * texture(Darken, v_text * 3.0).r; color *=",
"= Matrix44.perspective_projection(45.0, width / height, 0.01, 10.0) look = Matrix44.look_at((math.cos(angle), math.sin(angle), 0.8), (0.0,",
"ModernGL from PIL import Image from pyrr import Matrix44 wnd = GLWindow.create_window() ctx",
"= 3 prog.uniforms['Darken'].value = 4 index = 0 vertices = bytearray() indices =",
"Image.open('data/checked.jpg').convert('L').transpose(Image.FLIP_TOP_BOTTOM) tex0 = ctx.texture(img0.size, 1, img0.tobytes()) tex1 = ctx.texture(img1.size, 3, img1.tobytes()) tex2 =",
"wnd.time * 0.5 width, height = wnd.size proj = Matrix44.perspective_projection(45.0, width / height,",
"#version 330 uniform sampler2D Heightmap; uniform sampler2D Color1; uniform sampler2D Color2; uniform sampler2D",
"struct.pack('2f', (i + 1) / 64, j / 64) indices += struct.pack('i', index)",
"1, img0.tobytes()) tex1 = ctx.texture(img1.size, 3, img1.tobytes()) tex2 = ctx.texture(img2.size, 3, img2.tobytes()) tex3",
"= ctx.texture(img1.size, 3, img1.tobytes()) tex2 = ctx.texture(img2.size, 3, img2.tobytes()) tex3 = ctx.texture(img3.size, 1,",
"ModernGL.create_context() prog = ctx.program([ ctx.vertex_shader(''' #version 330 uniform mat4 Mvp; uniform sampler2D Heightmap;",
"ctx.buffer(vertices) ibo = ctx.buffer(indices) vao = ctx.vertex_array(prog, [(vbo, '2f', ['vert'])], ibo) while wnd.update():",
"texture(Color1, v_text * 7.0).rgb; vec3 color2 = texture(Color2, v_text * 6.0).rgb; vec3 color",
"range(64 - 1): for j in range(64): vertices += struct.pack('2f', i / 64,",
"ctx.vertex_shader(''' #version 330 uniform mat4 Mvp; uniform sampler2D Heightmap; in vec2 vert; out",
"-1) vbo = ctx.buffer(vertices) ibo = ctx.buffer(indices) vao = ctx.vertex_array(prog, [(vbo, '2f', ['vert'])],",
"+= struct.pack('i', -1) vbo = ctx.buffer(vertices) ibo = ctx.buffer(indices) vao = ctx.vertex_array(prog, [(vbo,",
"64, j / 64) indices += struct.pack('i', index) index += 1 vertices +=",
"j / 64) indices += struct.pack('i', index) index += 1 vertices += struct.pack('2f',",
"0.8), (0.0, 0.0, 0.1), (0.0, 0.0, 1.0)) prog.uniforms['Mvp'].write((proj * look).astype('float32').tobytes()) ctx.enable(ModernGL.DEPTH_TEST) ctx.viewport =",
"1 vertices += struct.pack('2f', (i + 1) / 64, j / 64) indices",
"Image from pyrr import Matrix44 wnd = GLWindow.create_window() ctx = ModernGL.create_context() prog =",
"tex1 = ctx.texture(img1.size, 3, img1.tobytes()) tex2 = ctx.texture(img2.size, 3, img2.tobytes()) tex3 = ctx.texture(img3.size,",
"img1 = Image.open('data/grass.jpg').convert('RGB').transpose(Image.FLIP_TOP_BOTTOM) img2 = Image.open('data/rock.jpg').convert('RGB').transpose(Image.FLIP_TOP_BOTTOM) img3 = Image.open('data/cracks.jpg').convert('L').transpose(Image.FLIP_TOP_BOTTOM) img4 = Image.open('data/checked.jpg').convert('L').transpose(Image.FLIP_TOP_BOTTOM) tex0",
"* height; f_color = vec4(color, 1.0); } '''), ]) img0 = Image.open('data/heightmap.jpg').convert('L').transpose(Image.FLIP_TOP_BOTTOM) img1",
"(0.0, 0.0, 1.0)) prog.uniforms['Mvp'].write((proj * look).astype('float32').tobytes()) ctx.enable(ModernGL.DEPTH_TEST) ctx.viewport = wnd.viewport ctx.clear(1.0, 1.0, 1.0)",
"i / 64, j / 64) indices += struct.pack('i', index) index += 1",
"height = texture(Heightmap, v_text).r; float border = smoothstep(0.5, 0.7, height); vec3 color1 =",
"1, img4.tobytes()) tex0.build_mipmaps() tex1.build_mipmaps() tex2.build_mipmaps() tex3.build_mipmaps() tex4.build_mipmaps() tex0.use(0) tex1.use(1) tex2.use(2) tex3.use(3) tex4.use(4) prog.uniforms['Heightmap'].value",
"* 0.2, 1.0); gl_Position = Mvp * vertex; v_text = vert; } '''),",
"void main() { vec4 vertex = vec4(vert - 0.5, texture(Heightmap, vert).r * 0.2,",
"vertices += struct.pack('2f', (i + 1) / 64, j / 64) indices +=",
"+= struct.pack('2f', i / 64, j / 64) indices += struct.pack('i', index) index",
"indices += struct.pack('i', -1) vbo = ctx.buffer(vertices) ibo = ctx.buffer(indices) vao = ctx.vertex_array(prog,",
"(0.0, 0.0, 0.1), (0.0, 0.0, 1.0)) prog.uniforms['Mvp'].write((proj * look).astype('float32').tobytes()) ctx.enable(ModernGL.DEPTH_TEST) ctx.viewport = wnd.viewport",
"struct.pack('i', index) index += 1 vertices += struct.pack('2f', (i + 1) / 64,",
"texture(Heightmap, vert).r * 0.2, 1.0); gl_Position = Mvp * vertex; v_text = vert;",
"tex3 = ctx.texture(img3.size, 1, img3.tobytes()) tex4 = ctx.texture(img4.size, 1, img4.tobytes()) tex0.build_mipmaps() tex1.build_mipmaps() tex2.build_mipmaps()",
"tex1.build_mipmaps() tex2.build_mipmaps() tex3.build_mipmaps() tex4.build_mipmaps() tex0.use(0) tex1.use(1) tex2.use(2) tex3.use(3) tex4.use(4) prog.uniforms['Heightmap'].value = 0 prog.uniforms['Color1'].value",
"index += 1 vertices += struct.pack('2f', (i + 1) / 64, j /",
"in range(64): vertices += struct.pack('2f', i / 64, j / 64) indices +=",
"i in range(64 - 1): for j in range(64): vertices += struct.pack('2f', i",
"vec4 vertex = vec4(vert - 0.5, texture(Heightmap, vert).r * 0.2, 1.0); gl_Position =",
"vertices += struct.pack('2f', i / 64, j / 64) indices += struct.pack('i', index)",
"img2 = Image.open('data/rock.jpg').convert('RGB').transpose(Image.FLIP_TOP_BOTTOM) img3 = Image.open('data/cracks.jpg').convert('L').transpose(Image.FLIP_TOP_BOTTOM) img4 = Image.open('data/checked.jpg').convert('L').transpose(Image.FLIP_TOP_BOTTOM) tex0 = ctx.texture(img0.size, 1,",
"import struct import GLWindow import ModernGL from PIL import Image from pyrr import",
"struct.pack('i', index) index += 1 indices += struct.pack('i', -1) vbo = ctx.buffer(vertices) ibo",
"vec3 color1 = texture(Color1, v_text * 7.0).rgb; vec3 color2 = texture(Color2, v_text *",
"ctx.texture(img0.size, 1, img0.tobytes()) tex1 = ctx.texture(img1.size, 3, img1.tobytes()) tex2 = ctx.texture(img2.size, 3, img2.tobytes())",
"= ctx.texture(img4.size, 1, img4.tobytes()) tex0.build_mipmaps() tex1.build_mipmaps() tex2.build_mipmaps() tex3.build_mipmaps() tex4.build_mipmaps() tex0.use(0) tex1.use(1) tex2.use(2) tex3.use(3)",
"= vec4(vert - 0.5, texture(Heightmap, vert).r * 0.2, 1.0); gl_Position = Mvp *",
"*= 0.5 + 0.5 * texture(Cracks, v_text * 5.0).r; color *= 0.5 +",
"for i in range(64 - 1): for j in range(64): vertices += struct.pack('2f',",
"= Mvp * vertex; v_text = vert; } '''), ctx.fragment_shader(''' #version 330 uniform",
"* 0.5 width, height = wnd.size proj = Matrix44.perspective_projection(45.0, width / height, 0.01,",
"= bytearray() indices = bytearray() for i in range(64 - 1): for j",
"2 prog.uniforms['Cracks'].value = 3 prog.uniforms['Darken'].value = 4 index = 0 vertices = bytearray()",
"* 6.0).rgb; vec3 color = color1 * (1.0 - border) + color2 *",
"= vec4(color, 1.0); } '''), ]) img0 = Image.open('data/heightmap.jpg').convert('L').transpose(Image.FLIP_TOP_BOTTOM) img1 = Image.open('data/grass.jpg').convert('RGB').transpose(Image.FLIP_TOP_BOTTOM) img2",
"index = 0 vertices = bytearray() indices = bytearray() for i in range(64",
"prog.uniforms['Darken'].value = 4 index = 0 vertices = bytearray() indices = bytearray() for",
"sampler2D Heightmap; in vec2 vert; out vec2 v_text; void main() { vec4 vertex",
"<filename>main.py import math import struct import GLWindow import ModernGL from PIL import Image",
"3 prog.uniforms['Darken'].value = 4 index = 0 vertices = bytearray() indices = bytearray()",
"10.0) look = Matrix44.look_at((math.cos(angle), math.sin(angle), 0.8), (0.0, 0.0, 0.1), (0.0, 0.0, 1.0)) prog.uniforms['Mvp'].write((proj",
"'2f', ['vert'])], ibo) while wnd.update(): angle = wnd.time * 0.5 width, height =",
"- border) + color2 * border; color *= 0.8 + 0.2 * texture(Darken,",
"tex3.build_mipmaps() tex4.build_mipmaps() tex0.use(0) tex1.use(1) tex2.use(2) tex3.use(3) tex4.use(4) prog.uniforms['Heightmap'].value = 0 prog.uniforms['Color1'].value = 1",
"vertex = vec4(vert - 0.5, texture(Heightmap, vert).r * 0.2, 1.0); gl_Position = Mvp",
"img3 = Image.open('data/cracks.jpg').convert('L').transpose(Image.FLIP_TOP_BOTTOM) img4 = Image.open('data/checked.jpg').convert('L').transpose(Image.FLIP_TOP_BOTTOM) tex0 = ctx.texture(img0.size, 1, img0.tobytes()) tex1 =",
"= Image.open('data/heightmap.jpg').convert('L').transpose(Image.FLIP_TOP_BOTTOM) img1 = Image.open('data/grass.jpg').convert('RGB').transpose(Image.FLIP_TOP_BOTTOM) img2 = Image.open('data/rock.jpg').convert('RGB').transpose(Image.FLIP_TOP_BOTTOM) img3 = Image.open('data/cracks.jpg').convert('L').transpose(Image.FLIP_TOP_BOTTOM) img4 =",
"smoothstep(0.5, 0.7, height); vec3 color1 = texture(Color1, v_text * 7.0).rgb; vec3 color2 =",
"= ctx.texture(img3.size, 1, img3.tobytes()) tex4 = ctx.texture(img4.size, 1, img4.tobytes()) tex0.build_mipmaps() tex1.build_mipmaps() tex2.build_mipmaps() tex3.build_mipmaps()",
"main() { vec4 vertex = vec4(vert - 0.5, texture(Heightmap, vert).r * 0.2, 1.0);",
"for j in range(64): vertices += struct.pack('2f', i / 64, j / 64)",
"float border = smoothstep(0.5, 0.7, height); vec3 color1 = texture(Color1, v_text * 7.0).rgb;",
"tex0.use(0) tex1.use(1) tex2.use(2) tex3.use(3) tex4.use(4) prog.uniforms['Heightmap'].value = 0 prog.uniforms['Color1'].value = 1 prog.uniforms['Color2'].value =",
"Mvp; uniform sampler2D Heightmap; in vec2 vert; out vec2 v_text; void main() {",
"texture(Color2, v_text * 6.0).rgb; vec3 color = color1 * (1.0 - border) +",
"tex0.build_mipmaps() tex1.build_mipmaps() tex2.build_mipmaps() tex3.build_mipmaps() tex4.build_mipmaps() tex0.use(0) tex1.use(1) tex2.use(2) tex3.use(3) tex4.use(4) prog.uniforms['Heightmap'].value = 0",
"img0.tobytes()) tex1 = ctx.texture(img1.size, 3, img1.tobytes()) tex2 = ctx.texture(img2.size, 3, img2.tobytes()) tex3 =",
"v_text * 6.0).rgb; vec3 color = color1 * (1.0 - border) + color2",
"Matrix44.look_at((math.cos(angle), math.sin(angle), 0.8), (0.0, 0.0, 0.1), (0.0, 0.0, 1.0)) prog.uniforms['Mvp'].write((proj * look).astype('float32').tobytes()) ctx.enable(ModernGL.DEPTH_TEST)",
"vert; } '''), ctx.fragment_shader(''' #version 330 uniform sampler2D Heightmap; uniform sampler2D Color1; uniform",
"img0 = Image.open('data/heightmap.jpg').convert('L').transpose(Image.FLIP_TOP_BOTTOM) img1 = Image.open('data/grass.jpg').convert('RGB').transpose(Image.FLIP_TOP_BOTTOM) img2 = Image.open('data/rock.jpg').convert('RGB').transpose(Image.FLIP_TOP_BOTTOM) img3 = Image.open('data/cracks.jpg').convert('L').transpose(Image.FLIP_TOP_BOTTOM) img4",
"indices += struct.pack('i', index) index += 1 indices += struct.pack('i', -1) vbo =",
"GLWindow.create_window() ctx = ModernGL.create_context() prog = ctx.program([ ctx.vertex_shader(''' #version 330 uniform mat4 Mvp;",
"vert).r * 0.2, 1.0); gl_Position = Mvp * vertex; v_text = vert; }",
"0.0, 1.0)) prog.uniforms['Mvp'].write((proj * look).astype('float32').tobytes()) ctx.enable(ModernGL.DEPTH_TEST) ctx.viewport = wnd.viewport ctx.clear(1.0, 1.0, 1.0) vao.render(ModernGL.TRIANGLE_STRIP)",
"1.0); } '''), ]) img0 = Image.open('data/heightmap.jpg').convert('L').transpose(Image.FLIP_TOP_BOTTOM) img1 = Image.open('data/grass.jpg').convert('RGB').transpose(Image.FLIP_TOP_BOTTOM) img2 = Image.open('data/rock.jpg').convert('RGB').transpose(Image.FLIP_TOP_BOTTOM)",
"PIL import Image from pyrr import Matrix44 wnd = GLWindow.create_window() ctx = ModernGL.create_context()",
"{ float height = texture(Heightmap, v_text).r; float border = smoothstep(0.5, 0.7, height); vec3",
"* 5.0).r; color *= 0.5 + 0.5 * height; f_color = vec4(color, 1.0);",
"ctx.texture(img4.size, 1, img4.tobytes()) tex0.build_mipmaps() tex1.build_mipmaps() tex2.build_mipmaps() tex3.build_mipmaps() tex4.build_mipmaps() tex0.use(0) tex1.use(1) tex2.use(2) tex3.use(3) tex4.use(4)",
"3, img1.tobytes()) tex2 = ctx.texture(img2.size, 3, img2.tobytes()) tex3 = ctx.texture(img3.size, 1, img3.tobytes()) tex4",
"= color1 * (1.0 - border) + color2 * border; color *= 0.8",
"+ 1) / 64, j / 64) indices += struct.pack('i', index) index +=",
"vec4(color, 1.0); } '''), ]) img0 = Image.open('data/heightmap.jpg').convert('L').transpose(Image.FLIP_TOP_BOTTOM) img1 = Image.open('data/grass.jpg').convert('RGB').transpose(Image.FLIP_TOP_BOTTOM) img2 =",
"ctx.fragment_shader(''' #version 330 uniform sampler2D Heightmap; uniform sampler2D Color1; uniform sampler2D Color2; uniform",
"0.5 + 0.5 * height; f_color = vec4(color, 1.0); } '''), ]) img0",
"texture(Cracks, v_text * 5.0).r; color *= 0.5 + 0.5 * height; f_color =",
"ctx.texture(img1.size, 3, img1.tobytes()) tex2 = ctx.texture(img2.size, 3, img2.tobytes()) tex3 = ctx.texture(img3.size, 1, img3.tobytes())",
"vec4 f_color; void main() { float height = texture(Heightmap, v_text).r; float border =",
"texture(Heightmap, v_text).r; float border = smoothstep(0.5, 0.7, height); vec3 color1 = texture(Color1, v_text",
"uniform sampler2D Darken; in vec2 v_text; out vec4 f_color; void main() { float",
"sampler2D Cracks; uniform sampler2D Darken; in vec2 v_text; out vec4 f_color; void main()",
"main() { float height = texture(Heightmap, v_text).r; float border = smoothstep(0.5, 0.7, height);",
"in vec2 v_text; out vec4 f_color; void main() { float height = texture(Heightmap,",
"= texture(Color1, v_text * 7.0).rgb; vec3 color2 = texture(Color2, v_text * 6.0).rgb; vec3",
"Heightmap; in vec2 vert; out vec2 v_text; void main() { vec4 vertex =",
"330 uniform mat4 Mvp; uniform sampler2D Heightmap; in vec2 vert; out vec2 v_text;",
"tex4.use(4) prog.uniforms['Heightmap'].value = 0 prog.uniforms['Color1'].value = 1 prog.uniforms['Color2'].value = 2 prog.uniforms['Cracks'].value = 3",
"uniform sampler2D Color2; uniform sampler2D Cracks; uniform sampler2D Darken; in vec2 v_text; out",
"vertex; v_text = vert; } '''), ctx.fragment_shader(''' #version 330 uniform sampler2D Heightmap; uniform",
"f_color = vec4(color, 1.0); } '''), ]) img0 = Image.open('data/heightmap.jpg').convert('L').transpose(Image.FLIP_TOP_BOTTOM) img1 = Image.open('data/grass.jpg').convert('RGB').transpose(Image.FLIP_TOP_BOTTOM)",
"bytearray() for i in range(64 - 1): for j in range(64): vertices +=",
"width, height = wnd.size proj = Matrix44.perspective_projection(45.0, width / height, 0.01, 10.0) look",
"ctx.program([ ctx.vertex_shader(''' #version 330 uniform mat4 Mvp; uniform sampler2D Heightmap; in vec2 vert;",
"v_text * 7.0).rgb; vec3 color2 = texture(Color2, v_text * 6.0).rgb; vec3 color =",
"5.0).r; color *= 0.5 + 0.5 * height; f_color = vec4(color, 1.0); }",
"ctx.buffer(indices) vao = ctx.vertex_array(prog, [(vbo, '2f', ['vert'])], ibo) while wnd.update(): angle = wnd.time",
"vertices = bytearray() indices = bytearray() for i in range(64 - 1): for",
"0 prog.uniforms['Color1'].value = 1 prog.uniforms['Color2'].value = 2 prog.uniforms['Cracks'].value = 3 prog.uniforms['Darken'].value = 4",
"img2.tobytes()) tex3 = ctx.texture(img3.size, 1, img3.tobytes()) tex4 = ctx.texture(img4.size, 1, img4.tobytes()) tex0.build_mipmaps() tex1.build_mipmaps()",
"j / 64) indices += struct.pack('i', index) index += 1 indices += struct.pack('i',",
"= GLWindow.create_window() ctx = ModernGL.create_context() prog = ctx.program([ ctx.vertex_shader(''' #version 330 uniform mat4",
"Image.open('data/cracks.jpg').convert('L').transpose(Image.FLIP_TOP_BOTTOM) img4 = Image.open('data/checked.jpg').convert('L').transpose(Image.FLIP_TOP_BOTTOM) tex0 = ctx.texture(img0.size, 1, img0.tobytes()) tex1 = ctx.texture(img1.size, 3,",
"import Image from pyrr import Matrix44 wnd = GLWindow.create_window() ctx = ModernGL.create_context() prog",
"out vec4 f_color; void main() { float height = texture(Heightmap, v_text).r; float border",
"0.7, height); vec3 color1 = texture(Color1, v_text * 7.0).rgb; vec3 color2 = texture(Color2,",
"index) index += 1 vertices += struct.pack('2f', (i + 1) / 64, j",
"sampler2D Color2; uniform sampler2D Cracks; uniform sampler2D Darken; in vec2 v_text; out vec4",
"math.sin(angle), 0.8), (0.0, 0.0, 0.1), (0.0, 0.0, 1.0)) prog.uniforms['Mvp'].write((proj * look).astype('float32').tobytes()) ctx.enable(ModernGL.DEPTH_TEST) ctx.viewport",
"color2 = texture(Color2, v_text * 6.0).rgb; vec3 color = color1 * (1.0 -",
"indices += struct.pack('i', index) index += 1 vertices += struct.pack('2f', (i + 1)",
"/ 64) indices += struct.pack('i', index) index += 1 indices += struct.pack('i', -1)",
"['vert'])], ibo) while wnd.update(): angle = wnd.time * 0.5 width, height = wnd.size",
"prog.uniforms['Color1'].value = 1 prog.uniforms['Color2'].value = 2 prog.uniforms['Cracks'].value = 3 prog.uniforms['Darken'].value = 4 index",
"GLWindow import ModernGL from PIL import Image from pyrr import Matrix44 wnd =",
"import math import struct import GLWindow import ModernGL from PIL import Image from",
"0.5 * texture(Cracks, v_text * 5.0).r; color *= 0.5 + 0.5 * height;",
"from PIL import Image from pyrr import Matrix44 wnd = GLWindow.create_window() ctx =",
"+ 0.2 * texture(Darken, v_text * 3.0).r; color *= 0.5 + 0.5 *",
"gl_Position = Mvp * vertex; v_text = vert; } '''), ctx.fragment_shader(''' #version 330",
"j in range(64): vertices += struct.pack('2f', i / 64, j / 64) indices",
"= ctx.program([ ctx.vertex_shader(''' #version 330 uniform mat4 Mvp; uniform sampler2D Heightmap; in vec2",
"import ModernGL from PIL import Image from pyrr import Matrix44 wnd = GLWindow.create_window()",
"= smoothstep(0.5, 0.7, height); vec3 color1 = texture(Color1, v_text * 7.0).rgb; vec3 color2",
"border = smoothstep(0.5, 0.7, height); vec3 color1 = texture(Color1, v_text * 7.0).rgb; vec3",
"img4 = Image.open('data/checked.jpg').convert('L').transpose(Image.FLIP_TOP_BOTTOM) tex0 = ctx.texture(img0.size, 1, img0.tobytes()) tex1 = ctx.texture(img1.size, 3, img1.tobytes())",
"img1.tobytes()) tex2 = ctx.texture(img2.size, 3, img2.tobytes()) tex3 = ctx.texture(img3.size, 1, img3.tobytes()) tex4 =",
"Mvp * vertex; v_text = vert; } '''), ctx.fragment_shader(''' #version 330 uniform sampler2D",
"v_text * 5.0).r; color *= 0.5 + 0.5 * height; f_color = vec4(color,",
"void main() { float height = texture(Heightmap, v_text).r; float border = smoothstep(0.5, 0.7,",
"tex1.use(1) tex2.use(2) tex3.use(3) tex4.use(4) prog.uniforms['Heightmap'].value = 0 prog.uniforms['Color1'].value = 1 prog.uniforms['Color2'].value = 2",
"0.2 * texture(Darken, v_text * 3.0).r; color *= 0.5 + 0.5 * texture(Cracks,",
"uniform sampler2D Heightmap; uniform sampler2D Color1; uniform sampler2D Color2; uniform sampler2D Cracks; uniform",
"- 1): for j in range(64): vertices += struct.pack('2f', i / 64, j",
"uniform sampler2D Color1; uniform sampler2D Color2; uniform sampler2D Cracks; uniform sampler2D Darken; in",
"- 0.5, texture(Heightmap, vert).r * 0.2, 1.0); gl_Position = Mvp * vertex; v_text",
"= Image.open('data/grass.jpg').convert('RGB').transpose(Image.FLIP_TOP_BOTTOM) img2 = Image.open('data/rock.jpg').convert('RGB').transpose(Image.FLIP_TOP_BOTTOM) img3 = Image.open('data/cracks.jpg').convert('L').transpose(Image.FLIP_TOP_BOTTOM) img4 = Image.open('data/checked.jpg').convert('L').transpose(Image.FLIP_TOP_BOTTOM) tex0 =",
"sampler2D Darken; in vec2 v_text; out vec4 f_color; void main() { float height",
"wnd.size proj = Matrix44.perspective_projection(45.0, width / height, 0.01, 10.0) look = Matrix44.look_at((math.cos(angle), math.sin(angle),",
"330 uniform sampler2D Heightmap; uniform sampler2D Color1; uniform sampler2D Color2; uniform sampler2D Cracks;",
"f_color; void main() { float height = texture(Heightmap, v_text).r; float border = smoothstep(0.5,",
"struct import GLWindow import ModernGL from PIL import Image from pyrr import Matrix44",
"tex2 = ctx.texture(img2.size, 3, img2.tobytes()) tex3 = ctx.texture(img3.size, 1, img3.tobytes()) tex4 = ctx.texture(img4.size,",
"in range(64 - 1): for j in range(64): vertices += struct.pack('2f', i /",
"img3.tobytes()) tex4 = ctx.texture(img4.size, 1, img4.tobytes()) tex0.build_mipmaps() tex1.build_mipmaps() tex2.build_mipmaps() tex3.build_mipmaps() tex4.build_mipmaps() tex0.use(0) tex1.use(1)",
"= texture(Color2, v_text * 6.0).rgb; vec3 color = color1 * (1.0 - border)",
"prog.uniforms['Heightmap'].value = 0 prog.uniforms['Color1'].value = 1 prog.uniforms['Color2'].value = 2 prog.uniforms['Cracks'].value = 3 prog.uniforms['Darken'].value",
"border) + color2 * border; color *= 0.8 + 0.2 * texture(Darken, v_text",
"1, img3.tobytes()) tex4 = ctx.texture(img4.size, 1, img4.tobytes()) tex0.build_mipmaps() tex1.build_mipmaps() tex2.build_mipmaps() tex3.build_mipmaps() tex4.build_mipmaps() tex0.use(0)",
"/ height, 0.01, 10.0) look = Matrix44.look_at((math.cos(angle), math.sin(angle), 0.8), (0.0, 0.0, 0.1), (0.0,",
"(1.0 - border) + color2 * border; color *= 0.8 + 0.2 *",
"= Matrix44.look_at((math.cos(angle), math.sin(angle), 0.8), (0.0, 0.0, 0.1), (0.0, 0.0, 1.0)) prog.uniforms['Mvp'].write((proj * look).astype('float32').tobytes())",
"0.1), (0.0, 0.0, 1.0)) prog.uniforms['Mvp'].write((proj * look).astype('float32').tobytes()) ctx.enable(ModernGL.DEPTH_TEST) ctx.viewport = wnd.viewport ctx.clear(1.0, 1.0,",
"* border; color *= 0.8 + 0.2 * texture(Darken, v_text * 3.0).r; color",
"= ctx.texture(img0.size, 1, img0.tobytes()) tex1 = ctx.texture(img1.size, 3, img1.tobytes()) tex2 = ctx.texture(img2.size, 3,",
"= ctx.buffer(indices) vao = ctx.vertex_array(prog, [(vbo, '2f', ['vert'])], ibo) while wnd.update(): angle =",
"1): for j in range(64): vertices += struct.pack('2f', i / 64, j /",
"4 index = 0 vertices = bytearray() indices = bytearray() for i in",
"+= struct.pack('2f', (i + 1) / 64, j / 64) indices += struct.pack('i',",
"pyrr import Matrix44 wnd = GLWindow.create_window() ctx = ModernGL.create_context() prog = ctx.program([ ctx.vertex_shader('''",
"prog = ctx.program([ ctx.vertex_shader(''' #version 330 uniform mat4 Mvp; uniform sampler2D Heightmap; in",
"ctx.texture(img2.size, 3, img2.tobytes()) tex3 = ctx.texture(img3.size, 1, img3.tobytes()) tex4 = ctx.texture(img4.size, 1, img4.tobytes())",
"= 0 prog.uniforms['Color1'].value = 1 prog.uniforms['Color2'].value = 2 prog.uniforms['Cracks'].value = 3 prog.uniforms['Darken'].value =",
"Image.open('data/heightmap.jpg').convert('L').transpose(Image.FLIP_TOP_BOTTOM) img1 = Image.open('data/grass.jpg').convert('RGB').transpose(Image.FLIP_TOP_BOTTOM) img2 = Image.open('data/rock.jpg').convert('RGB').transpose(Image.FLIP_TOP_BOTTOM) img3 = Image.open('data/cracks.jpg').convert('L').transpose(Image.FLIP_TOP_BOTTOM) img4 = Image.open('data/checked.jpg').convert('L').transpose(Image.FLIP_TOP_BOTTOM)",
"tex2.build_mipmaps() tex3.build_mipmaps() tex4.build_mipmaps() tex0.use(0) tex1.use(1) tex2.use(2) tex3.use(3) tex4.use(4) prog.uniforms['Heightmap'].value = 0 prog.uniforms['Color1'].value =",
"color1 * (1.0 - border) + color2 * border; color *= 0.8 +",
"struct.pack('2f', i / 64, j / 64) indices += struct.pack('i', index) index +=",
"= bytearray() for i in range(64 - 1): for j in range(64): vertices",
"0.8 + 0.2 * texture(Darken, v_text * 3.0).r; color *= 0.5 + 0.5",
"* vertex; v_text = vert; } '''), ctx.fragment_shader(''' #version 330 uniform sampler2D Heightmap;",
"while wnd.update(): angle = wnd.time * 0.5 width, height = wnd.size proj =",
"'''), ]) img0 = Image.open('data/heightmap.jpg').convert('L').transpose(Image.FLIP_TOP_BOTTOM) img1 = Image.open('data/grass.jpg').convert('RGB').transpose(Image.FLIP_TOP_BOTTOM) img2 = Image.open('data/rock.jpg').convert('RGB').transpose(Image.FLIP_TOP_BOTTOM) img3 =",
"vec2 v_text; out vec4 f_color; void main() { float height = texture(Heightmap, v_text).r;",
"/ 64, j / 64) indices += struct.pack('i', index) index += 1 vertices",
"uniform mat4 Mvp; uniform sampler2D Heightmap; in vec2 vert; out vec2 v_text; void",
"/ 64) indices += struct.pack('i', index) index += 1 vertices += struct.pack('2f', (i",
"0.5 * height; f_color = vec4(color, 1.0); } '''), ]) img0 = Image.open('data/heightmap.jpg').convert('L').transpose(Image.FLIP_TOP_BOTTOM)",
"vert; out vec2 v_text; void main() { vec4 vertex = vec4(vert - 0.5,",
"+ color2 * border; color *= 0.8 + 0.2 * texture(Darken, v_text *",
"1.0); gl_Position = Mvp * vertex; v_text = vert; } '''), ctx.fragment_shader(''' #version",
"out vec2 v_text; void main() { vec4 vertex = vec4(vert - 0.5, texture(Heightmap,",
"0.01, 10.0) look = Matrix44.look_at((math.cos(angle), math.sin(angle), 0.8), (0.0, 0.0, 0.1), (0.0, 0.0, 1.0))",
"wnd.update(): angle = wnd.time * 0.5 width, height = wnd.size proj = Matrix44.perspective_projection(45.0,",
"= 0 vertices = bytearray() indices = bytearray() for i in range(64 -",
"mat4 Mvp; uniform sampler2D Heightmap; in vec2 vert; out vec2 v_text; void main()",
"color *= 0.5 + 0.5 * height; f_color = vec4(color, 1.0); } '''),",
"Cracks; uniform sampler2D Darken; in vec2 v_text; out vec4 f_color; void main() {",
"= 1 prog.uniforms['Color2'].value = 2 prog.uniforms['Cracks'].value = 3 prog.uniforms['Darken'].value = 4 index =",
"1 indices += struct.pack('i', -1) vbo = ctx.buffer(vertices) ibo = ctx.buffer(indices) vao =",
"'''), ctx.fragment_shader(''' #version 330 uniform sampler2D Heightmap; uniform sampler2D Color1; uniform sampler2D Color2;",
"color *= 0.5 + 0.5 * texture(Cracks, v_text * 5.0).r; color *= 0.5",
"Image.open('data/rock.jpg').convert('RGB').transpose(Image.FLIP_TOP_BOTTOM) img3 = Image.open('data/cracks.jpg').convert('L').transpose(Image.FLIP_TOP_BOTTOM) img4 = Image.open('data/checked.jpg').convert('L').transpose(Image.FLIP_TOP_BOTTOM) tex0 = ctx.texture(img0.size, 1, img0.tobytes()) tex1",
"+ 0.5 * height; f_color = vec4(color, 1.0); } '''), ]) img0 =",
"height; f_color = vec4(color, 1.0); } '''), ]) img0 = Image.open('data/heightmap.jpg').convert('L').transpose(Image.FLIP_TOP_BOTTOM) img1 =",
"64) indices += struct.pack('i', index) index += 1 indices += struct.pack('i', -1) vbo",
"ibo = ctx.buffer(indices) vao = ctx.vertex_array(prog, [(vbo, '2f', ['vert'])], ibo) while wnd.update(): angle",
"struct.pack('i', -1) vbo = ctx.buffer(vertices) ibo = ctx.buffer(indices) vao = ctx.vertex_array(prog, [(vbo, '2f',",
"0.5 width, height = wnd.size proj = Matrix44.perspective_projection(45.0, width / height, 0.01, 10.0)",
"in vec2 vert; out vec2 v_text; void main() { vec4 vertex = vec4(vert",
"vbo = ctx.buffer(vertices) ibo = ctx.buffer(indices) vao = ctx.vertex_array(prog, [(vbo, '2f', ['vert'])], ibo)",
"vec2 vert; out vec2 v_text; void main() { vec4 vertex = vec4(vert -",
"uniform sampler2D Heightmap; in vec2 vert; out vec2 v_text; void main() { vec4",
"Matrix44.perspective_projection(45.0, width / height, 0.01, 10.0) look = Matrix44.look_at((math.cos(angle), math.sin(angle), 0.8), (0.0, 0.0,",
"= vert; } '''), ctx.fragment_shader(''' #version 330 uniform sampler2D Heightmap; uniform sampler2D Color1;",
"sampler2D Color1; uniform sampler2D Color2; uniform sampler2D Cracks; uniform sampler2D Darken; in vec2",
"3.0).r; color *= 0.5 + 0.5 * texture(Cracks, v_text * 5.0).r; color *=",
"* texture(Darken, v_text * 3.0).r; color *= 0.5 + 0.5 * texture(Cracks, v_text",
"64) indices += struct.pack('i', index) index += 1 vertices += struct.pack('2f', (i +",
"v_text).r; float border = smoothstep(0.5, 0.7, height); vec3 color1 = texture(Color1, v_text *",
"texture(Darken, v_text * 3.0).r; color *= 0.5 + 0.5 * texture(Cracks, v_text *",
"ctx.texture(img3.size, 1, img3.tobytes()) tex4 = ctx.texture(img4.size, 1, img4.tobytes()) tex0.build_mipmaps() tex1.build_mipmaps() tex2.build_mipmaps() tex3.build_mipmaps() tex4.build_mipmaps()",
"prog.uniforms['Cracks'].value = 3 prog.uniforms['Darken'].value = 4 index = 0 vertices = bytearray() indices",
"color = color1 * (1.0 - border) + color2 * border; color *=",
"= Image.open('data/rock.jpg').convert('RGB').transpose(Image.FLIP_TOP_BOTTOM) img3 = Image.open('data/cracks.jpg').convert('L').transpose(Image.FLIP_TOP_BOTTOM) img4 = Image.open('data/checked.jpg').convert('L').transpose(Image.FLIP_TOP_BOTTOM) tex0 = ctx.texture(img0.size, 1, img0.tobytes())",
"Image.open('data/grass.jpg').convert('RGB').transpose(Image.FLIP_TOP_BOTTOM) img2 = Image.open('data/rock.jpg').convert('RGB').transpose(Image.FLIP_TOP_BOTTOM) img3 = Image.open('data/cracks.jpg').convert('L').transpose(Image.FLIP_TOP_BOTTOM) img4 = Image.open('data/checked.jpg').convert('L').transpose(Image.FLIP_TOP_BOTTOM) tex0 = ctx.texture(img0.size,",
"0.0, 0.1), (0.0, 0.0, 1.0)) prog.uniforms['Mvp'].write((proj * look).astype('float32').tobytes()) ctx.enable(ModernGL.DEPTH_TEST) ctx.viewport = wnd.viewport ctx.clear(1.0,",
"math import struct import GLWindow import ModernGL from PIL import Image from pyrr",
"+= struct.pack('i', index) index += 1 indices += struct.pack('i', -1) vbo = ctx.buffer(vertices)",
"import GLWindow import ModernGL from PIL import Image from pyrr import Matrix44 wnd",
"]) img0 = Image.open('data/heightmap.jpg').convert('L').transpose(Image.FLIP_TOP_BOTTOM) img1 = Image.open('data/grass.jpg').convert('RGB').transpose(Image.FLIP_TOP_BOTTOM) img2 = Image.open('data/rock.jpg').convert('RGB').transpose(Image.FLIP_TOP_BOTTOM) img3 = Image.open('data/cracks.jpg').convert('L').transpose(Image.FLIP_TOP_BOTTOM)",
"= ModernGL.create_context() prog = ctx.program([ ctx.vertex_shader(''' #version 330 uniform mat4 Mvp; uniform sampler2D",
"indices = bytearray() for i in range(64 - 1): for j in range(64):",
"*= 0.5 + 0.5 * height; f_color = vec4(color, 1.0); } '''), ])",
"= wnd.time * 0.5 width, height = wnd.size proj = Matrix44.perspective_projection(45.0, width /",
"= Image.open('data/checked.jpg').convert('L').transpose(Image.FLIP_TOP_BOTTOM) tex0 = ctx.texture(img0.size, 1, img0.tobytes()) tex1 = ctx.texture(img1.size, 3, img1.tobytes()) tex2",
"ctx.vertex_array(prog, [(vbo, '2f', ['vert'])], ibo) while wnd.update(): angle = wnd.time * 0.5 width,",
"= texture(Heightmap, v_text).r; float border = smoothstep(0.5, 0.7, height); vec3 color1 = texture(Color1,",
"vec3 color = color1 * (1.0 - border) + color2 * border; color",
"index) index += 1 indices += struct.pack('i', -1) vbo = ctx.buffer(vertices) ibo =",
"= ctx.buffer(vertices) ibo = ctx.buffer(indices) vao = ctx.vertex_array(prog, [(vbo, '2f', ['vert'])], ibo) while",
"#version 330 uniform mat4 Mvp; uniform sampler2D Heightmap; in vec2 vert; out vec2",
"/ 64, j / 64) indices += struct.pack('i', index) index += 1 indices",
"*= 0.8 + 0.2 * texture(Darken, v_text * 3.0).r; color *= 0.5 +",
"index += 1 indices += struct.pack('i', -1) vbo = ctx.buffer(vertices) ibo = ctx.buffer(indices)",
"v_text; out vec4 f_color; void main() { float height = texture(Heightmap, v_text).r; float",
"height); vec3 color1 = texture(Color1, v_text * 7.0).rgb; vec3 color2 = texture(Color2, v_text",
"0 vertices = bytearray() indices = bytearray() for i in range(64 - 1):",
"(i + 1) / 64, j / 64) indices += struct.pack('i', index) index",
"= Image.open('data/cracks.jpg').convert('L').transpose(Image.FLIP_TOP_BOTTOM) img4 = Image.open('data/checked.jpg').convert('L').transpose(Image.FLIP_TOP_BOTTOM) tex0 = ctx.texture(img0.size, 1, img0.tobytes()) tex1 = ctx.texture(img1.size,",
"color2 * border; color *= 0.8 + 0.2 * texture(Darken, v_text * 3.0).r;",
"height, 0.01, 10.0) look = Matrix44.look_at((math.cos(angle), math.sin(angle), 0.8), (0.0, 0.0, 0.1), (0.0, 0.0,",
"} '''), ctx.fragment_shader(''' #version 330 uniform sampler2D Heightmap; uniform sampler2D Color1; uniform sampler2D",
"= wnd.size proj = Matrix44.perspective_projection(45.0, width / height, 0.01, 10.0) look = Matrix44.look_at((math.cos(angle),",
"wnd = GLWindow.create_window() ctx = ModernGL.create_context() prog = ctx.program([ ctx.vertex_shader(''' #version 330 uniform",
"height = wnd.size proj = Matrix44.perspective_projection(45.0, width / height, 0.01, 10.0) look =",
"0.5, texture(Heightmap, vert).r * 0.2, 1.0); gl_Position = Mvp * vertex; v_text =",
"6.0).rgb; vec3 color = color1 * (1.0 - border) + color2 * border;",
"Color1; uniform sampler2D Color2; uniform sampler2D Cracks; uniform sampler2D Darken; in vec2 v_text;",
"ctx = ModernGL.create_context() prog = ctx.program([ ctx.vertex_shader(''' #version 330 uniform mat4 Mvp; uniform",
"tex2.use(2) tex3.use(3) tex4.use(4) prog.uniforms['Heightmap'].value = 0 prog.uniforms['Color1'].value = 1 prog.uniforms['Color2'].value = 2 prog.uniforms['Cracks'].value",
"= 4 index = 0 vertices = bytearray() indices = bytearray() for i",
"+= 1 indices += struct.pack('i', -1) vbo = ctx.buffer(vertices) ibo = ctx.buffer(indices) vao",
"= 2 prog.uniforms['Cracks'].value = 3 prog.uniforms['Darken'].value = 4 index = 0 vertices =",
"Heightmap; uniform sampler2D Color1; uniform sampler2D Color2; uniform sampler2D Cracks; uniform sampler2D Darken;",
"3, img2.tobytes()) tex3 = ctx.texture(img3.size, 1, img3.tobytes()) tex4 = ctx.texture(img4.size, 1, img4.tobytes()) tex0.build_mipmaps()",
"range(64): vertices += struct.pack('2f', i / 64, j / 64) indices += struct.pack('i',",
"tex3.use(3) tex4.use(4) prog.uniforms['Heightmap'].value = 0 prog.uniforms['Color1'].value = 1 prog.uniforms['Color2'].value = 2 prog.uniforms['Cracks'].value =",
"color1 = texture(Color1, v_text * 7.0).rgb; vec3 color2 = texture(Color2, v_text * 6.0).rgb;",
"v_text; void main() { vec4 vertex = vec4(vert - 0.5, texture(Heightmap, vert).r *",
"vao = ctx.vertex_array(prog, [(vbo, '2f', ['vert'])], ibo) while wnd.update(): angle = wnd.time *",
"bytearray() indices = bytearray() for i in range(64 - 1): for j in",
"ibo) while wnd.update(): angle = wnd.time * 0.5 width, height = wnd.size proj",
"proj = Matrix44.perspective_projection(45.0, width / height, 0.01, 10.0) look = Matrix44.look_at((math.cos(angle), math.sin(angle), 0.8),",
"tex4.build_mipmaps() tex0.use(0) tex1.use(1) tex2.use(2) tex3.use(3) tex4.use(4) prog.uniforms['Heightmap'].value = 0 prog.uniforms['Color1'].value = 1 prog.uniforms['Color2'].value",
"look = Matrix44.look_at((math.cos(angle), math.sin(angle), 0.8), (0.0, 0.0, 0.1), (0.0, 0.0, 1.0)) prog.uniforms['Mvp'].write((proj *",
"vec2 v_text; void main() { vec4 vertex = vec4(vert - 0.5, texture(Heightmap, vert).r",
"+ 0.5 * texture(Cracks, v_text * 5.0).r; color *= 0.5 + 0.5 *",
"width / height, 0.01, 10.0) look = Matrix44.look_at((math.cos(angle), math.sin(angle), 0.8), (0.0, 0.0, 0.1),",
"v_text = vert; } '''), ctx.fragment_shader(''' #version 330 uniform sampler2D Heightmap; uniform sampler2D",
"prog.uniforms['Color2'].value = 2 prog.uniforms['Cracks'].value = 3 prog.uniforms['Darken'].value = 4 index = 0 vertices",
"from pyrr import Matrix44 wnd = GLWindow.create_window() ctx = ModernGL.create_context() prog = ctx.program([",
"color *= 0.8 + 0.2 * texture(Darken, v_text * 3.0).r; color *= 0.5",
"img4.tobytes()) tex0.build_mipmaps() tex1.build_mipmaps() tex2.build_mipmaps() tex3.build_mipmaps() tex4.build_mipmaps() tex0.use(0) tex1.use(1) tex2.use(2) tex3.use(3) tex4.use(4) prog.uniforms['Heightmap'].value =",
"tex0 = ctx.texture(img0.size, 1, img0.tobytes()) tex1 = ctx.texture(img1.size, 3, img1.tobytes()) tex2 = ctx.texture(img2.size,",
"sampler2D Heightmap; uniform sampler2D Color1; uniform sampler2D Color2; uniform sampler2D Cracks; uniform sampler2D",
"+= struct.pack('i', index) index += 1 vertices += struct.pack('2f', (i + 1) /"
] |
[
"Column(String(256)) tags = Column(String(256)) key = Column(String(256)) create_dt = Column(DATETIME) def __repr__(self): return",
"= Column(String(256)) create_dt = Column(DATETIME) def __repr__(self): return \"<PubMed(pmid=%s,title=%s)>\" % (self.pmid, self.title) class",
"Column(String(64)) altmetric = Column(FLOAT) create_dt = Column(DATETIME) def __repr__(self): return \"<Metric(pmid=%s, metric=%s)>\" %",
"import dbapi2 as sqlite from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from",
"contextmanager from sqlite3 import dbapi2 as sqlite from sqlalchemy import create_engine from sqlalchemy.orm",
"= Session() try: yield session session.commit() except Exception as ex: logger.error(ex) session.rollback() raise",
"INTEGER, NUMERIC, SMALLINT, TEXT, TIME, TIMESTAMP, VARCHAR) logger = logging.getLogger('db') engine = create_engine(\"sqlite+pysqlite:///pubmed.db\",",
"(self.pmid, self.altmetric) Base.metadata.create_all(engine) if __name__ == '__main__': import datetime as dt Base.metadata.create_all(engine) with",
"as session: pubmed = PubMed( pmid='000000', title='title', authors='authors', create_dt=dt.datetime.now() ) session.merge(pubmed) pubmed =",
"id = Column(Integer, Sequence('user_id_seq'), primary_key=True) pmid = Column(String(64)) altmetric = Column(FLOAT) create_dt =",
"Metric(Base): __tablename__ = 'metric' id = Column(Integer, Sequence('user_id_seq'), primary_key=True) pmid = Column(String(64)) altmetric",
"Sequence('user_id_seq'), primary_key=True) pmid = Column(String(64)) altmetric = Column(FLOAT) create_dt = Column(DATETIME) def __repr__(self):",
"scope around a series of operations.\"\"\" session = Session() try: yield session session.commit()",
"\"<PubMed(pmid=%s,title=%s)>\" % (self.pmid, self.title) class Metric(Base): __tablename__ = 'metric' id = Column(Integer, Sequence('user_id_seq'),",
"declarative_base from sqlalchemy.dialects.sqlite import (BLOB, BOOLEAN, CHAR, DATE, DATETIME, DECIMAL, FLOAT, INTEGER, NUMERIC,",
"Sequence from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.dialects.sqlite import (BLOB, BOOLEAN, CHAR, DATE, DATETIME,",
"summary_detail = Column(String(256)) link = Column(String(256)) tags = Column(String(256)) key = Column(String(256)) create_dt",
"import logging from contextlib import contextmanager from sqlite3 import dbapi2 as sqlite from",
"TEXT, TIME, TIMESTAMP, VARCHAR) logger = logging.getLogger('db') engine = create_engine(\"sqlite+pysqlite:///pubmed.db\", execution_options={\"sqlite_raw_colnames\": True}, module=sqlite)",
"= Column(String(256)) key = Column(String(256)) create_dt = Column(DATETIME) def __repr__(self): return \"<PubMed(pmid=%s,title=%s)>\" %",
"= sessionmaker(bind=engine) @contextmanager def session_scope(): \"\"\"Provide a transactional scope around a series of",
"__repr__(self): return \"<PubMed(pmid=%s,title=%s)>\" % (self.pmid, self.title) class Metric(Base): __tablename__ = 'metric' id =",
"= 'pubmed' pmid = Column(String(64), primary_key=True) title = Column(String(256), nullable=False) authors = Column(String(256))",
"title='title', authors='authors', create_dt=dt.datetime.now() ) session.merge(pubmed) pubmed = PubMed( pmid='000000', title='title', authors='authors2', create_dt=dt.datetime.now() )",
"\"\"\"Provide a transactional scope around a series of operations.\"\"\" session = Session() try:",
"= Column(String(256), nullable=False) authors = Column(String(256)) summary = Column(String(256)) summary_detail = Column(String(256)) link",
"session.commit() except Exception as ex: logger.error(ex) session.rollback() raise finally: session.close() Base = declarative_base()",
"session = Session() try: yield session session.commit() except Exception as ex: logger.error(ex) session.rollback()",
"Column(Integer, Sequence('user_id_seq'), primary_key=True) pmid = Column(String(64)) altmetric = Column(FLOAT) create_dt = Column(DATETIME) def",
"Column(String(256), nullable=False) authors = Column(String(256)) summary = Column(String(256)) summary_detail = Column(String(256)) link =",
"__repr__(self): return \"<Metric(pmid=%s, metric=%s)>\" % (self.pmid, self.altmetric) Base.metadata.create_all(engine) if __name__ == '__main__': import",
"PubMed( pmid='000000', title='title', authors='authors', create_dt=dt.datetime.now() ) session.merge(pubmed) pubmed = PubMed( pmid='000000', title='title', authors='authors2',",
"'pubmed' pmid = Column(String(64), primary_key=True) title = Column(String(256), nullable=False) authors = Column(String(256)) summary",
"self.title) class Metric(Base): __tablename__ = 'metric' id = Column(Integer, Sequence('user_id_seq'), primary_key=True) pmid =",
"ex: logger.error(ex) session.rollback() raise finally: session.close() Base = declarative_base() class PubMed(Base): __tablename__ =",
"def __repr__(self): return \"<Metric(pmid=%s, metric=%s)>\" % (self.pmid, self.altmetric) Base.metadata.create_all(engine) if __name__ == '__main__':",
"sqlalchemy.ext.declarative import declarative_base from sqlalchemy.dialects.sqlite import (BLOB, BOOLEAN, CHAR, DATE, DATETIME, DECIMAL, FLOAT,",
"primary_key=True) pmid = Column(String(64)) altmetric = Column(FLOAT) create_dt = Column(DATETIME) def __repr__(self): return",
"pmid='000000', title='title', authors='authors', create_dt=dt.datetime.now() ) session.merge(pubmed) pubmed = PubMed( pmid='000000', title='title', authors='authors2', create_dt=dt.datetime.now()",
"Column, String, Integer, Sequence from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.dialects.sqlite import (BLOB, BOOLEAN,",
"DATETIME, DECIMAL, FLOAT, INTEGER, NUMERIC, SMALLINT, TEXT, TIME, TIMESTAMP, VARCHAR) logger = logging.getLogger('db')",
"= Column(String(64), primary_key=True) title = Column(String(256), nullable=False) authors = Column(String(256)) summary = Column(String(256))",
"from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from sqlalchemy import Column, String,",
"link = Column(String(256)) tags = Column(String(256)) key = Column(String(256)) create_dt = Column(DATETIME) def",
"FLOAT, INTEGER, NUMERIC, SMALLINT, TEXT, TIME, TIMESTAMP, VARCHAR) logger = logging.getLogger('db') engine =",
"except Exception as ex: logger.error(ex) session.rollback() raise finally: session.close() Base = declarative_base() class",
"a series of operations.\"\"\" session = Session() try: yield session session.commit() except Exception",
"engine = create_engine(\"sqlite+pysqlite:///pubmed.db\", execution_options={\"sqlite_raw_colnames\": True}, module=sqlite) Session = sessionmaker(bind=engine) @contextmanager def session_scope(): \"\"\"Provide",
"(self.pmid, self.title) class Metric(Base): __tablename__ = 'metric' id = Column(Integer, Sequence('user_id_seq'), primary_key=True) pmid",
"logger = logging.getLogger('db') engine = create_engine(\"sqlite+pysqlite:///pubmed.db\", execution_options={\"sqlite_raw_colnames\": True}, module=sqlite) Session = sessionmaker(bind=engine) @contextmanager",
"Base.metadata.create_all(engine) if __name__ == '__main__': import datetime as dt Base.metadata.create_all(engine) with session_scope() as",
"session.rollback() raise finally: session.close() Base = declarative_base() class PubMed(Base): __tablename__ = 'pubmed' pmid",
"NUMERIC, SMALLINT, TEXT, TIME, TIMESTAMP, VARCHAR) logger = logging.getLogger('db') engine = create_engine(\"sqlite+pysqlite:///pubmed.db\", execution_options={\"sqlite_raw_colnames\":",
"= Column(Integer, Sequence('user_id_seq'), primary_key=True) pmid = Column(String(64)) altmetric = Column(FLOAT) create_dt = Column(DATETIME)",
"@contextmanager def session_scope(): \"\"\"Provide a transactional scope around a series of operations.\"\"\" session",
"metric=%s)>\" % (self.pmid, self.altmetric) Base.metadata.create_all(engine) if __name__ == '__main__': import datetime as dt",
"== '__main__': import datetime as dt Base.metadata.create_all(engine) with session_scope() as session: pubmed =",
"Base = declarative_base() class PubMed(Base): __tablename__ = 'pubmed' pmid = Column(String(64), primary_key=True) title",
"(BLOB, BOOLEAN, CHAR, DATE, DATETIME, DECIMAL, FLOAT, INTEGER, NUMERIC, SMALLINT, TEXT, TIME, TIMESTAMP,",
"'__main__': import datetime as dt Base.metadata.create_all(engine) with session_scope() as session: pubmed = PubMed(",
"title = Column(String(256), nullable=False) authors = Column(String(256)) summary = Column(String(256)) summary_detail = Column(String(256))",
"with session_scope() as session: pubmed = PubMed( pmid='000000', title='title', authors='authors', create_dt=dt.datetime.now() ) session.merge(pubmed)",
"= Column(DATETIME) def __repr__(self): return \"<Metric(pmid=%s, metric=%s)>\" % (self.pmid, self.altmetric) Base.metadata.create_all(engine) if __name__",
"from sqlite3 import dbapi2 as sqlite from sqlalchemy import create_engine from sqlalchemy.orm import",
"= logging.getLogger('db') engine = create_engine(\"sqlite+pysqlite:///pubmed.db\", execution_options={\"sqlite_raw_colnames\": True}, module=sqlite) Session = sessionmaker(bind=engine) @contextmanager def",
"create_engine from sqlalchemy.orm import sessionmaker from sqlalchemy import Column, String, Integer, Sequence from",
"Column(DATETIME) def __repr__(self): return \"<PubMed(pmid=%s,title=%s)>\" % (self.pmid, self.title) class Metric(Base): __tablename__ = 'metric'",
"summary = Column(String(256)) summary_detail = Column(String(256)) link = Column(String(256)) tags = Column(String(256)) key",
"Session() try: yield session session.commit() except Exception as ex: logger.error(ex) session.rollback() raise finally:",
"Session = sessionmaker(bind=engine) @contextmanager def session_scope(): \"\"\"Provide a transactional scope around a series",
"sessionmaker(bind=engine) @contextmanager def session_scope(): \"\"\"Provide a transactional scope around a series of operations.\"\"\"",
"nullable=False) authors = Column(String(256)) summary = Column(String(256)) summary_detail = Column(String(256)) link = Column(String(256))",
"raise finally: session.close() Base = declarative_base() class PubMed(Base): __tablename__ = 'pubmed' pmid =",
"Integer, Sequence from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.dialects.sqlite import (BLOB, BOOLEAN, CHAR, DATE,",
"os import logging from contextlib import contextmanager from sqlite3 import dbapi2 as sqlite",
"contextlib import contextmanager from sqlite3 import dbapi2 as sqlite from sqlalchemy import create_engine",
"authors='authors', create_dt=dt.datetime.now() ) session.merge(pubmed) pubmed = PubMed( pmid='000000', title='title', authors='authors2', create_dt=dt.datetime.now() ) session.merge(pubmed)",
"logging from contextlib import contextmanager from sqlite3 import dbapi2 as sqlite from sqlalchemy",
"as sqlite from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from sqlalchemy import",
"= Column(DATETIME) def __repr__(self): return \"<PubMed(pmid=%s,title=%s)>\" % (self.pmid, self.title) class Metric(Base): __tablename__ =",
"logging.getLogger('db') engine = create_engine(\"sqlite+pysqlite:///pubmed.db\", execution_options={\"sqlite_raw_colnames\": True}, module=sqlite) Session = sessionmaker(bind=engine) @contextmanager def session_scope():",
"= Column(String(256)) tags = Column(String(256)) key = Column(String(256)) create_dt = Column(DATETIME) def __repr__(self):",
"import datetime as dt Base.metadata.create_all(engine) with session_scope() as session: pubmed = PubMed( pmid='000000',",
"around a series of operations.\"\"\" session = Session() try: yield session session.commit() except",
"Column(String(256)) key = Column(String(256)) create_dt = Column(DATETIME) def __repr__(self): return \"<PubMed(pmid=%s,title=%s)>\" % (self.pmid,",
"sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from sqlalchemy import Column, String, Integer,",
"pmid = Column(String(64), primary_key=True) title = Column(String(256), nullable=False) authors = Column(String(256)) summary =",
"TIME, TIMESTAMP, VARCHAR) logger = logging.getLogger('db') engine = create_engine(\"sqlite+pysqlite:///pubmed.db\", execution_options={\"sqlite_raw_colnames\": True}, module=sqlite) Session",
"self.altmetric) Base.metadata.create_all(engine) if __name__ == '__main__': import datetime as dt Base.metadata.create_all(engine) with session_scope()",
"'metric' id = Column(Integer, Sequence('user_id_seq'), primary_key=True) pmid = Column(String(64)) altmetric = Column(FLOAT) create_dt",
"key = Column(String(256)) create_dt = Column(DATETIME) def __repr__(self): return \"<PubMed(pmid=%s,title=%s)>\" % (self.pmid, self.title)",
"= 'metric' id = Column(Integer, Sequence('user_id_seq'), primary_key=True) pmid = Column(String(64)) altmetric = Column(FLOAT)",
"__tablename__ = 'metric' id = Column(Integer, Sequence('user_id_seq'), primary_key=True) pmid = Column(String(64)) altmetric =",
"authors = Column(String(256)) summary = Column(String(256)) summary_detail = Column(String(256)) link = Column(String(256)) tags",
"Column(String(256)) create_dt = Column(DATETIME) def __repr__(self): return \"<PubMed(pmid=%s,title=%s)>\" % (self.pmid, self.title) class Metric(Base):",
"if __name__ == '__main__': import datetime as dt Base.metadata.create_all(engine) with session_scope() as session:",
"True}, module=sqlite) Session = sessionmaker(bind=engine) @contextmanager def session_scope(): \"\"\"Provide a transactional scope around",
"CHAR, DATE, DATETIME, DECIMAL, FLOAT, INTEGER, NUMERIC, SMALLINT, TEXT, TIME, TIMESTAMP, VARCHAR) logger",
"of operations.\"\"\" session = Session() try: yield session session.commit() except Exception as ex:",
"declarative_base() class PubMed(Base): __tablename__ = 'pubmed' pmid = Column(String(64), primary_key=True) title = Column(String(256),",
"Column(String(64), primary_key=True) title = Column(String(256), nullable=False) authors = Column(String(256)) summary = Column(String(256)) summary_detail",
"create_dt = Column(DATETIME) def __repr__(self): return \"<PubMed(pmid=%s,title=%s)>\" % (self.pmid, self.title) class Metric(Base): __tablename__",
"execution_options={\"sqlite_raw_colnames\": True}, module=sqlite) Session = sessionmaker(bind=engine) @contextmanager def session_scope(): \"\"\"Provide a transactional scope",
"session: pubmed = PubMed( pmid='000000', title='title', authors='authors', create_dt=dt.datetime.now() ) session.merge(pubmed) pubmed = PubMed(",
"BOOLEAN, CHAR, DATE, DATETIME, DECIMAL, FLOAT, INTEGER, NUMERIC, SMALLINT, TEXT, TIME, TIMESTAMP, VARCHAR)",
"session session.commit() except Exception as ex: logger.error(ex) session.rollback() raise finally: session.close() Base =",
"return \"<Metric(pmid=%s, metric=%s)>\" % (self.pmid, self.altmetric) Base.metadata.create_all(engine) if __name__ == '__main__': import datetime",
"module=sqlite) Session = sessionmaker(bind=engine) @contextmanager def session_scope(): \"\"\"Provide a transactional scope around a",
"from contextlib import contextmanager from sqlite3 import dbapi2 as sqlite from sqlalchemy import",
"class PubMed(Base): __tablename__ = 'pubmed' pmid = Column(String(64), primary_key=True) title = Column(String(256), nullable=False)",
"SMALLINT, TEXT, TIME, TIMESTAMP, VARCHAR) logger = logging.getLogger('db') engine = create_engine(\"sqlite+pysqlite:///pubmed.db\", execution_options={\"sqlite_raw_colnames\": True},",
"= create_engine(\"sqlite+pysqlite:///pubmed.db\", execution_options={\"sqlite_raw_colnames\": True}, module=sqlite) Session = sessionmaker(bind=engine) @contextmanager def session_scope(): \"\"\"Provide a",
"import sessionmaker from sqlalchemy import Column, String, Integer, Sequence from sqlalchemy.ext.declarative import declarative_base",
"% (self.pmid, self.altmetric) Base.metadata.create_all(engine) if __name__ == '__main__': import datetime as dt Base.metadata.create_all(engine)",
"sessionmaker from sqlalchemy import Column, String, Integer, Sequence from sqlalchemy.ext.declarative import declarative_base from",
"session_scope() as session: pubmed = PubMed( pmid='000000', title='title', authors='authors', create_dt=dt.datetime.now() ) session.merge(pubmed) pubmed",
"= Column(String(256)) link = Column(String(256)) tags = Column(String(256)) key = Column(String(256)) create_dt =",
"pmid = Column(String(64)) altmetric = Column(FLOAT) create_dt = Column(DATETIME) def __repr__(self): return \"<Metric(pmid=%s,",
"TIMESTAMP, VARCHAR) logger = logging.getLogger('db') engine = create_engine(\"sqlite+pysqlite:///pubmed.db\", execution_options={\"sqlite_raw_colnames\": True}, module=sqlite) Session =",
"\"<Metric(pmid=%s, metric=%s)>\" % (self.pmid, self.altmetric) Base.metadata.create_all(engine) if __name__ == '__main__': import datetime as",
"DATE, DATETIME, DECIMAL, FLOAT, INTEGER, NUMERIC, SMALLINT, TEXT, TIME, TIMESTAMP, VARCHAR) logger =",
"create_dt = Column(DATETIME) def __repr__(self): return \"<Metric(pmid=%s, metric=%s)>\" % (self.pmid, self.altmetric) Base.metadata.create_all(engine) if",
"= PubMed( pmid='000000', title='title', authors='authors', create_dt=dt.datetime.now() ) session.merge(pubmed) pubmed = PubMed( pmid='000000', title='title',",
"session_scope(): \"\"\"Provide a transactional scope around a series of operations.\"\"\" session = Session()",
"as ex: logger.error(ex) session.rollback() raise finally: session.close() Base = declarative_base() class PubMed(Base): __tablename__",
"from sqlalchemy.dialects.sqlite import (BLOB, BOOLEAN, CHAR, DATE, DATETIME, DECIMAL, FLOAT, INTEGER, NUMERIC, SMALLINT,",
"__tablename__ = 'pubmed' pmid = Column(String(64), primary_key=True) title = Column(String(256), nullable=False) authors =",
"a transactional scope around a series of operations.\"\"\" session = Session() try: yield",
"session.close() Base = declarative_base() class PubMed(Base): __tablename__ = 'pubmed' pmid = Column(String(64), primary_key=True)",
"transactional scope around a series of operations.\"\"\" session = Session() try: yield session",
"class Metric(Base): __tablename__ = 'metric' id = Column(Integer, Sequence('user_id_seq'), primary_key=True) pmid = Column(String(64))",
"% (self.pmid, self.title) class Metric(Base): __tablename__ = 'metric' id = Column(Integer, Sequence('user_id_seq'), primary_key=True)",
"sqlite3 import dbapi2 as sqlite from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker",
"datetime as dt Base.metadata.create_all(engine) with session_scope() as session: pubmed = PubMed( pmid='000000', title='title',",
"sqlite from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from sqlalchemy import Column,",
"import contextmanager from sqlite3 import dbapi2 as sqlite from sqlalchemy import create_engine from",
"import os import logging from contextlib import contextmanager from sqlite3 import dbapi2 as",
"def __repr__(self): return \"<PubMed(pmid=%s,title=%s)>\" % (self.pmid, self.title) class Metric(Base): __tablename__ = 'metric' id",
"Column(FLOAT) create_dt = Column(DATETIME) def __repr__(self): return \"<Metric(pmid=%s, metric=%s)>\" % (self.pmid, self.altmetric) Base.metadata.create_all(engine)",
"def session_scope(): \"\"\"Provide a transactional scope around a series of operations.\"\"\" session =",
"from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.dialects.sqlite import (BLOB, BOOLEAN, CHAR, DATE, DATETIME, DECIMAL,",
"pubmed = PubMed( pmid='000000', title='title', authors='authors', create_dt=dt.datetime.now() ) session.merge(pubmed) pubmed = PubMed( pmid='000000',",
"VARCHAR) logger = logging.getLogger('db') engine = create_engine(\"sqlite+pysqlite:///pubmed.db\", execution_options={\"sqlite_raw_colnames\": True}, module=sqlite) Session = sessionmaker(bind=engine)",
"create_engine(\"sqlite+pysqlite:///pubmed.db\", execution_options={\"sqlite_raw_colnames\": True}, module=sqlite) Session = sessionmaker(bind=engine) @contextmanager def session_scope(): \"\"\"Provide a transactional",
"= Column(String(256)) summary = Column(String(256)) summary_detail = Column(String(256)) link = Column(String(256)) tags =",
"import Column, String, Integer, Sequence from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.dialects.sqlite import (BLOB,",
"Column(String(256)) summary_detail = Column(String(256)) link = Column(String(256)) tags = Column(String(256)) key = Column(String(256))",
"= declarative_base() class PubMed(Base): __tablename__ = 'pubmed' pmid = Column(String(64), primary_key=True) title =",
"dbapi2 as sqlite from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from sqlalchemy",
"return \"<PubMed(pmid=%s,title=%s)>\" % (self.pmid, self.title) class Metric(Base): __tablename__ = 'metric' id = Column(Integer,",
"PubMed(Base): __tablename__ = 'pubmed' pmid = Column(String(64), primary_key=True) title = Column(String(256), nullable=False) authors",
"dt Base.metadata.create_all(engine) with session_scope() as session: pubmed = PubMed( pmid='000000', title='title', authors='authors', create_dt=dt.datetime.now()",
"sqlalchemy import Column, String, Integer, Sequence from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.dialects.sqlite import",
"sqlalchemy.dialects.sqlite import (BLOB, BOOLEAN, CHAR, DATE, DATETIME, DECIMAL, FLOAT, INTEGER, NUMERIC, SMALLINT, TEXT,",
"try: yield session session.commit() except Exception as ex: logger.error(ex) session.rollback() raise finally: session.close()",
"yield session session.commit() except Exception as ex: logger.error(ex) session.rollback() raise finally: session.close() Base",
"as dt Base.metadata.create_all(engine) with session_scope() as session: pubmed = PubMed( pmid='000000', title='title', authors='authors',",
"Column(DATETIME) def __repr__(self): return \"<Metric(pmid=%s, metric=%s)>\" % (self.pmid, self.altmetric) Base.metadata.create_all(engine) if __name__ ==",
"Column(String(256)) link = Column(String(256)) tags = Column(String(256)) key = Column(String(256)) create_dt = Column(DATETIME)",
"= Column(String(256)) summary_detail = Column(String(256)) link = Column(String(256)) tags = Column(String(256)) key =",
"tags = Column(String(256)) key = Column(String(256)) create_dt = Column(DATETIME) def __repr__(self): return \"<PubMed(pmid=%s,title=%s)>\"",
"from sqlalchemy import Column, String, Integer, Sequence from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.dialects.sqlite",
"import declarative_base from sqlalchemy.dialects.sqlite import (BLOB, BOOLEAN, CHAR, DATE, DATETIME, DECIMAL, FLOAT, INTEGER,",
"DECIMAL, FLOAT, INTEGER, NUMERIC, SMALLINT, TEXT, TIME, TIMESTAMP, VARCHAR) logger = logging.getLogger('db') engine",
"import (BLOB, BOOLEAN, CHAR, DATE, DATETIME, DECIMAL, FLOAT, INTEGER, NUMERIC, SMALLINT, TEXT, TIME,",
"series of operations.\"\"\" session = Session() try: yield session session.commit() except Exception as",
"operations.\"\"\" session = Session() try: yield session session.commit() except Exception as ex: logger.error(ex)",
"sqlalchemy.orm import sessionmaker from sqlalchemy import Column, String, Integer, Sequence from sqlalchemy.ext.declarative import",
"Exception as ex: logger.error(ex) session.rollback() raise finally: session.close() Base = declarative_base() class PubMed(Base):",
"= Column(String(64)) altmetric = Column(FLOAT) create_dt = Column(DATETIME) def __repr__(self): return \"<Metric(pmid=%s, metric=%s)>\"",
"Base.metadata.create_all(engine) with session_scope() as session: pubmed = PubMed( pmid='000000', title='title', authors='authors', create_dt=dt.datetime.now() )",
"altmetric = Column(FLOAT) create_dt = Column(DATETIME) def __repr__(self): return \"<Metric(pmid=%s, metric=%s)>\" % (self.pmid,",
"finally: session.close() Base = declarative_base() class PubMed(Base): __tablename__ = 'pubmed' pmid = Column(String(64),",
"from sqlalchemy.orm import sessionmaker from sqlalchemy import Column, String, Integer, Sequence from sqlalchemy.ext.declarative",
"__name__ == '__main__': import datetime as dt Base.metadata.create_all(engine) with session_scope() as session: pubmed",
"import create_engine from sqlalchemy.orm import sessionmaker from sqlalchemy import Column, String, Integer, Sequence",
"logger.error(ex) session.rollback() raise finally: session.close() Base = declarative_base() class PubMed(Base): __tablename__ = 'pubmed'",
"= Column(FLOAT) create_dt = Column(DATETIME) def __repr__(self): return \"<Metric(pmid=%s, metric=%s)>\" % (self.pmid, self.altmetric)",
"primary_key=True) title = Column(String(256), nullable=False) authors = Column(String(256)) summary = Column(String(256)) summary_detail =",
"String, Integer, Sequence from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.dialects.sqlite import (BLOB, BOOLEAN, CHAR,",
"Column(String(256)) summary = Column(String(256)) summary_detail = Column(String(256)) link = Column(String(256)) tags = Column(String(256))"
] |
[
"pv import cv from pyvision.face.CascadeDetector import CascadeDetector from pyvision.face.FilterEyeLocator import FilterEyeLocator def mouseCallback(event,",
"and eye detection. Copyright <NAME> Created on Jul 9, 2011 @author: bolme '''",
"basic framework for a live demo. In this case the demo is for",
"# Grab a frame from the webcam frame = webcam.query() # Run Face",
"Setup the face and eye detectors cd = CascadeDetector(min_size=(100,100)) el = FilterEyeLocator() #",
"# Annotate the result for rect,leye,reye in eyes: frame.annotateThickRect(rect, 'green', width=3) frame.annotatePoint(leye, color='green')",
"frame from the webcam frame = webcam.query() # Run Face and Eye Detection",
"mouse callback to handle mause events (optional) cv.NamedWindow(\"PyVision Live Demo\") cv.SetMouseCallback(\"PyVision Live Demo\",",
"cd(frame) eyes = el(frame,rects) # Annotate the result for rect,leye,reye in eyes: frame.annotateThickRect(rect,",
"cv.NamedWindow(\"PyVision Live Demo\") cv.SetMouseCallback(\"PyVision Live Demo\", mouseCallback) while True: # Grab a frame",
"eyes = el(frame,rects) # Annotate the result for rect,leye,reye in eyes: frame.annotateThickRect(rect, 'green',",
"x, y, flags, param): if event in [cv.CV_EVENT_LBUTTONDOWN,cv.CV_EVENT_LBUTTONUP]: print \"Mouse Event:\",event,x,y if __name__",
"to quit.\") # Show the frame (uses opencv highgui) key_press = frame.show(\"PyVision Live",
"Face and Eye Detection rects = cd(frame) eyes = el(frame,rects) # Annotate the",
"pyvision.face.CascadeDetector import CascadeDetector from pyvision.face.FilterEyeLocator import FilterEyeLocator def mouseCallback(event, x, y, flags, param):",
"import FilterEyeLocator def mouseCallback(event, x, y, flags, param): if event in [cv.CV_EVENT_LBUTTONDOWN,cv.CV_EVENT_LBUTTONUP]: print",
"mouseCallback(event, x, y, flags, param): if event in [cv.CV_EVENT_LBUTTONDOWN,cv.CV_EVENT_LBUTTONUP]: print \"Mouse Event:\",event,x,y if",
"eyes: frame.annotateThickRect(rect, 'green', width=3) frame.annotatePoint(leye, color='green') frame.annotatePoint(reye, color='green') # Annotate instructions frame.annotateLabel(pv.Point(10,10), \"Press",
"bolme ''' import pyvision as pv import cv from pyvision.face.CascadeDetector import CascadeDetector from",
"'q' to quit.\") # Show the frame (uses opencv highgui) key_press = frame.show(\"PyVision",
"from pyvision.face.FilterEyeLocator import FilterEyeLocator def mouseCallback(event, x, y, flags, param): if event in",
"# Show the frame (uses opencv highgui) key_press = frame.show(\"PyVision Live Demo\") #",
"Show the frame (uses opencv highgui) key_press = frame.show(\"PyVision Live Demo\") # Handle",
"import cv from pyvision.face.CascadeDetector import CascadeDetector from pyvision.face.FilterEyeLocator import FilterEyeLocator def mouseCallback(event, x,",
"(uses opencv highgui) key_press = frame.show(\"PyVision Live Demo\") # Handle key press events.",
"highgui) key_press = frame.show(\"PyVision Live Demo\") # Handle key press events. if key_press",
"This file provides a basic framework for a live demo. In this case",
"Live Demo\") cv.SetMouseCallback(\"PyVision Live Demo\", mouseCallback) while True: # Grab a frame from",
"demo. In this case the demo is for face and eye detection. Copyright",
"cd = CascadeDetector(min_size=(100,100)) el = FilterEyeLocator() # Setup the mouse callback to handle",
"if event in [cv.CV_EVENT_LBUTTONDOWN,cv.CV_EVENT_LBUTTONUP]: print \"Mouse Event:\",event,x,y if __name__ == '__main__': # Setup",
"[cv.CV_EVENT_LBUTTONDOWN,cv.CV_EVENT_LBUTTONUP]: print \"Mouse Event:\",event,x,y if __name__ == '__main__': # Setup the webcam webcam",
"callback to handle mause events (optional) cv.NamedWindow(\"PyVision Live Demo\") cv.SetMouseCallback(\"PyVision Live Demo\", mouseCallback)",
"2011 @author: bolme ''' import pyvision as pv import cv from pyvision.face.CascadeDetector import",
"\"Mouse Event:\",event,x,y if __name__ == '__main__': # Setup the webcam webcam = pv.Webcam()",
"(optional) cv.NamedWindow(\"PyVision Live Demo\") cv.SetMouseCallback(\"PyVision Live Demo\", mouseCallback) while True: # Grab a",
"'green', width=3) frame.annotatePoint(leye, color='green') frame.annotatePoint(reye, color='green') # Annotate instructions frame.annotateLabel(pv.Point(10,10), \"Press 'q' to",
"width=3) frame.annotatePoint(leye, color='green') frame.annotatePoint(reye, color='green') # Annotate instructions frame.annotateLabel(pv.Point(10,10), \"Press 'q' to quit.\")",
"__name__ == '__main__': # Setup the webcam webcam = pv.Webcam() # Setup the",
"to handle mause events (optional) cv.NamedWindow(\"PyVision Live Demo\") cv.SetMouseCallback(\"PyVision Live Demo\", mouseCallback) while",
"FilterEyeLocator def mouseCallback(event, x, y, flags, param): if event in [cv.CV_EVENT_LBUTTONDOWN,cv.CV_EVENT_LBUTTONUP]: print \"Mouse",
"frame (uses opencv highgui) key_press = frame.show(\"PyVision Live Demo\") # Handle key press",
"= cd(frame) eyes = el(frame,rects) # Annotate the result for rect,leye,reye in eyes:",
"CascadeDetector(min_size=(100,100)) el = FilterEyeLocator() # Setup the mouse callback to handle mause events",
"mouseCallback) while True: # Grab a frame from the webcam frame = webcam.query()",
"def mouseCallback(event, x, y, flags, param): if event in [cv.CV_EVENT_LBUTTONDOWN,cv.CV_EVENT_LBUTTONUP]: print \"Mouse Event:\",event,x,y",
"event in [cv.CV_EVENT_LBUTTONDOWN,cv.CV_EVENT_LBUTTONUP]: print \"Mouse Event:\",event,x,y if __name__ == '__main__': # Setup the",
"the webcam webcam = pv.Webcam() # Setup the face and eye detectors cd",
"handle mause events (optional) cv.NamedWindow(\"PyVision Live Demo\") cv.SetMouseCallback(\"PyVision Live Demo\", mouseCallback) while True:",
"for a live demo. In this case the demo is for face and",
"# Annotate instructions frame.annotateLabel(pv.Point(10,10), \"Press 'q' to quit.\") # Show the frame (uses",
"opencv highgui) key_press = frame.show(\"PyVision Live Demo\") # Handle key press events. if",
"face and eye detectors cd = CascadeDetector(min_size=(100,100)) el = FilterEyeLocator() # Setup the",
"for rect,leye,reye in eyes: frame.annotateThickRect(rect, 'green', width=3) frame.annotatePoint(leye, color='green') frame.annotatePoint(reye, color='green') # Annotate",
"while True: # Grab a frame from the webcam frame = webcam.query() #",
"webcam = pv.Webcam() # Setup the face and eye detectors cd = CascadeDetector(min_size=(100,100))",
"on Jul 9, 2011 @author: bolme ''' import pyvision as pv import cv",
"frame.show(\"PyVision Live Demo\") # Handle key press events. if key_press == ord('q'): break",
"Jul 9, 2011 @author: bolme ''' import pyvision as pv import cv from",
"rect,leye,reye in eyes: frame.annotateThickRect(rect, 'green', width=3) frame.annotatePoint(leye, color='green') frame.annotatePoint(reye, color='green') # Annotate instructions",
"== '__main__': # Setup the webcam webcam = pv.Webcam() # Setup the face",
"rects = cd(frame) eyes = el(frame,rects) # Annotate the result for rect,leye,reye in",
"el(frame,rects) # Annotate the result for rect,leye,reye in eyes: frame.annotateThickRect(rect, 'green', width=3) frame.annotatePoint(leye,",
"the result for rect,leye,reye in eyes: frame.annotateThickRect(rect, 'green', width=3) frame.annotatePoint(leye, color='green') frame.annotatePoint(reye, color='green')",
"in [cv.CV_EVENT_LBUTTONDOWN,cv.CV_EVENT_LBUTTONUP]: print \"Mouse Event:\",event,x,y if __name__ == '__main__': # Setup the webcam",
"''' import pyvision as pv import cv from pyvision.face.CascadeDetector import CascadeDetector from pyvision.face.FilterEyeLocator",
"Setup the mouse callback to handle mause events (optional) cv.NamedWindow(\"PyVision Live Demo\") cv.SetMouseCallback(\"PyVision",
"as pv import cv from pyvision.face.CascadeDetector import CascadeDetector from pyvision.face.FilterEyeLocator import FilterEyeLocator def",
"Demo\", mouseCallback) while True: # Grab a frame from the webcam frame =",
"= pv.Webcam() # Setup the face and eye detectors cd = CascadeDetector(min_size=(100,100)) el",
"= CascadeDetector(min_size=(100,100)) el = FilterEyeLocator() # Setup the mouse callback to handle mause",
"and Eye Detection rects = cd(frame) eyes = el(frame,rects) # Annotate the result",
"this case the demo is for face and eye detection. Copyright <NAME> Created",
"Grab a frame from the webcam frame = webcam.query() # Run Face and",
"is for face and eye detection. Copyright <NAME> Created on Jul 9, 2011",
"In this case the demo is for face and eye detection. Copyright <NAME>",
"live demo. In this case the demo is for face and eye detection.",
"9, 2011 @author: bolme ''' import pyvision as pv import cv from pyvision.face.CascadeDetector",
"= el(frame,rects) # Annotate the result for rect,leye,reye in eyes: frame.annotateThickRect(rect, 'green', width=3)",
"Live Demo\", mouseCallback) while True: # Grab a frame from the webcam frame",
"cv.SetMouseCallback(\"PyVision Live Demo\", mouseCallback) while True: # Grab a frame from the webcam",
"import pyvision as pv import cv from pyvision.face.CascadeDetector import CascadeDetector from pyvision.face.FilterEyeLocator import",
"detectors cd = CascadeDetector(min_size=(100,100)) el = FilterEyeLocator() # Setup the mouse callback to",
"the webcam frame = webcam.query() # Run Face and Eye Detection rects =",
"Created on Jul 9, 2011 @author: bolme ''' import pyvision as pv import",
"result for rect,leye,reye in eyes: frame.annotateThickRect(rect, 'green', width=3) frame.annotatePoint(leye, color='green') frame.annotatePoint(reye, color='green') #",
"Setup the webcam webcam = pv.Webcam() # Setup the face and eye detectors",
"pv.Webcam() # Setup the face and eye detectors cd = CascadeDetector(min_size=(100,100)) el =",
"provides a basic framework for a live demo. In this case the demo",
"# Setup the face and eye detectors cd = CascadeDetector(min_size=(100,100)) el = FilterEyeLocator()",
"Detection rects = cd(frame) eyes = el(frame,rects) # Annotate the result for rect,leye,reye",
"<NAME> Created on Jul 9, 2011 @author: bolme ''' import pyvision as pv",
"eye detectors cd = CascadeDetector(min_size=(100,100)) el = FilterEyeLocator() # Setup the mouse callback",
"in eyes: frame.annotateThickRect(rect, 'green', width=3) frame.annotatePoint(leye, color='green') frame.annotatePoint(reye, color='green') # Annotate instructions frame.annotateLabel(pv.Point(10,10),",
"demo is for face and eye detection. Copyright <NAME> Created on Jul 9,",
"the mouse callback to handle mause events (optional) cv.NamedWindow(\"PyVision Live Demo\") cv.SetMouseCallback(\"PyVision Live",
"Run Face and Eye Detection rects = cd(frame) eyes = el(frame,rects) # Annotate",
"y, flags, param): if event in [cv.CV_EVENT_LBUTTONDOWN,cv.CV_EVENT_LBUTTONUP]: print \"Mouse Event:\",event,x,y if __name__ ==",
"= FilterEyeLocator() # Setup the mouse callback to handle mause events (optional) cv.NamedWindow(\"PyVision",
"the face and eye detectors cd = CascadeDetector(min_size=(100,100)) el = FilterEyeLocator() # Setup",
"webcam webcam = pv.Webcam() # Setup the face and eye detectors cd =",
"instructions frame.annotateLabel(pv.Point(10,10), \"Press 'q' to quit.\") # Show the frame (uses opencv highgui)",
"from pyvision.face.CascadeDetector import CascadeDetector from pyvision.face.FilterEyeLocator import FilterEyeLocator def mouseCallback(event, x, y, flags,",
"\"Press 'q' to quit.\") # Show the frame (uses opencv highgui) key_press =",
"case the demo is for face and eye detection. Copyright <NAME> Created on",
"frame = webcam.query() # Run Face and Eye Detection rects = cd(frame) eyes",
"FilterEyeLocator() # Setup the mouse callback to handle mause events (optional) cv.NamedWindow(\"PyVision Live",
"# Setup the webcam webcam = pv.Webcam() # Setup the face and eye",
"frame.annotatePoint(reye, color='green') # Annotate instructions frame.annotateLabel(pv.Point(10,10), \"Press 'q' to quit.\") # Show the",
"file provides a basic framework for a live demo. In this case the",
"'__main__': # Setup the webcam webcam = pv.Webcam() # Setup the face and",
"print \"Mouse Event:\",event,x,y if __name__ == '__main__': # Setup the webcam webcam =",
"a basic framework for a live demo. In this case the demo is",
"Eye Detection rects = cd(frame) eyes = el(frame,rects) # Annotate the result for",
"flags, param): if event in [cv.CV_EVENT_LBUTTONDOWN,cv.CV_EVENT_LBUTTONUP]: print \"Mouse Event:\",event,x,y if __name__ == '__main__':",
"events (optional) cv.NamedWindow(\"PyVision Live Demo\") cv.SetMouseCallback(\"PyVision Live Demo\", mouseCallback) while True: # Grab",
"from the webcam frame = webcam.query() # Run Face and Eye Detection rects",
"# Setup the mouse callback to handle mause events (optional) cv.NamedWindow(\"PyVision Live Demo\")",
"mause events (optional) cv.NamedWindow(\"PyVision Live Demo\") cv.SetMouseCallback(\"PyVision Live Demo\", mouseCallback) while True: #",
"the frame (uses opencv highgui) key_press = frame.show(\"PyVision Live Demo\") # Handle key",
"the demo is for face and eye detection. Copyright <NAME> Created on Jul",
"Copyright <NAME> Created on Jul 9, 2011 @author: bolme ''' import pyvision as",
"key_press = frame.show(\"PyVision Live Demo\") # Handle key press events. if key_press ==",
"a frame from the webcam frame = webcam.query() # Run Face and Eye",
"# Run Face and Eye Detection rects = cd(frame) eyes = el(frame,rects) #",
"frame.annotateLabel(pv.Point(10,10), \"Press 'q' to quit.\") # Show the frame (uses opencv highgui) key_press",
"CascadeDetector from pyvision.face.FilterEyeLocator import FilterEyeLocator def mouseCallback(event, x, y, flags, param): if event",
"Demo\") cv.SetMouseCallback(\"PyVision Live Demo\", mouseCallback) while True: # Grab a frame from the",
"for face and eye detection. Copyright <NAME> Created on Jul 9, 2011 @author:",
"el = FilterEyeLocator() # Setup the mouse callback to handle mause events (optional)",
"detection. Copyright <NAME> Created on Jul 9, 2011 @author: bolme ''' import pyvision",
"webcam frame = webcam.query() # Run Face and Eye Detection rects = cd(frame)",
"and eye detectors cd = CascadeDetector(min_size=(100,100)) el = FilterEyeLocator() # Setup the mouse",
"cv from pyvision.face.CascadeDetector import CascadeDetector from pyvision.face.FilterEyeLocator import FilterEyeLocator def mouseCallback(event, x, y,",
"= webcam.query() # Run Face and Eye Detection rects = cd(frame) eyes =",
"color='green') # Annotate instructions frame.annotateLabel(pv.Point(10,10), \"Press 'q' to quit.\") # Show the frame",
"quit.\") # Show the frame (uses opencv highgui) key_press = frame.show(\"PyVision Live Demo\")",
"color='green') frame.annotatePoint(reye, color='green') # Annotate instructions frame.annotateLabel(pv.Point(10,10), \"Press 'q' to quit.\") # Show",
"import CascadeDetector from pyvision.face.FilterEyeLocator import FilterEyeLocator def mouseCallback(event, x, y, flags, param): if",
"= frame.show(\"PyVision Live Demo\") # Handle key press events. if key_press == ord('q'):",
"''' This file provides a basic framework for a live demo. In this",
"eye detection. Copyright <NAME> Created on Jul 9, 2011 @author: bolme ''' import",
"framework for a live demo. In this case the demo is for face",
"Event:\",event,x,y if __name__ == '__main__': # Setup the webcam webcam = pv.Webcam() #",
"face and eye detection. Copyright <NAME> Created on Jul 9, 2011 @author: bolme",
"Annotate the result for rect,leye,reye in eyes: frame.annotateThickRect(rect, 'green', width=3) frame.annotatePoint(leye, color='green') frame.annotatePoint(reye,",
"@author: bolme ''' import pyvision as pv import cv from pyvision.face.CascadeDetector import CascadeDetector",
"pyvision as pv import cv from pyvision.face.CascadeDetector import CascadeDetector from pyvision.face.FilterEyeLocator import FilterEyeLocator",
"Annotate instructions frame.annotateLabel(pv.Point(10,10), \"Press 'q' to quit.\") # Show the frame (uses opencv",
"webcam.query() # Run Face and Eye Detection rects = cd(frame) eyes = el(frame,rects)",
"frame.annotatePoint(leye, color='green') frame.annotatePoint(reye, color='green') # Annotate instructions frame.annotateLabel(pv.Point(10,10), \"Press 'q' to quit.\") #",
"if __name__ == '__main__': # Setup the webcam webcam = pv.Webcam() # Setup",
"pyvision.face.FilterEyeLocator import FilterEyeLocator def mouseCallback(event, x, y, flags, param): if event in [cv.CV_EVENT_LBUTTONDOWN,cv.CV_EVENT_LBUTTONUP]:",
"frame.annotateThickRect(rect, 'green', width=3) frame.annotatePoint(leye, color='green') frame.annotatePoint(reye, color='green') # Annotate instructions frame.annotateLabel(pv.Point(10,10), \"Press 'q'",
"a live demo. In this case the demo is for face and eye",
"True: # Grab a frame from the webcam frame = webcam.query() # Run",
"param): if event in [cv.CV_EVENT_LBUTTONDOWN,cv.CV_EVENT_LBUTTONUP]: print \"Mouse Event:\",event,x,y if __name__ == '__main__': #"
] |
[
"be looked out for when looking for candidates to give loans to. #",
"- I followed this from a previous project to see the most important",
"# In[1]: # Libraries we need import pandas as pd import numpy as",
"= gridCV.best_estimator_ tree_estimator.fit(x_train, y_train) # In[23]: dependent_performance_dt = tree_estimator.predict(x_train) metrics_score(y_train, dependent_performance_dt) # -",
"plt.show() # In[17]: dtree = DecisionTreeClassifier(class_weight={0:0.20, 1:0.80}, random_state=1) # In[18]: dtree.fit(x_train, y_train) #",
"a loan is the debt to income ratio. If someone has a lot",
"test_size=0.3, random_state=1) # In[16]: def metrics_score(actual, predicted): print(classification_report(actual, predicted)) cm = confusion_matrix(actual, predicted)",
"shap_vals = explain(x_train) # In[37]: type(shap_vals) # In[38]: shap.plots.bar(shap_vals[:, :, 0]) # In[39]:",
"that someone who cannot make their credit card payments will have a hard",
"thing that effects defaulting on a loan is the debt to income ratio.",
"Run the grid search grid_obj = GridSearchCV(forest_estimator_tuned, parameters_rf, scoring=score, cv=5) grid_obj = grid_obj.fit(x_train,",
"less harmful error but decreased the harmful error # In[24]: dependent_test_performance_dt = tree_estimator.predict(x_test)",
"In[24]: dependent_test_performance_dt = tree_estimator.predict(x_test) metrics_score(y_test, dependent_test_performance_dt) # - Although the performance is slightly",
"y_train) # Set the clf to the best combination of parameters forest_estimator_tuned =",
"import matplotlib.pyplot as plt import seaborn as sns from sklearn.preprocessing import StandardScaler from",
"large number of years at a job could indicate financial stability. # -",
"models to get the best results. # - The first one I made",
"a lot of debt and a lower income they may have a harder",
"lot better than the original single tree # - Lets fix overfitting #",
"paying back a loan. # - Years at job is also a driver",
"= tree_estimator.predict(x_train) metrics_score(y_train, dependent_performance_dt) # - We increased the less harmful error but",
"LogisticRegression from sklearn.neighbors import KNeighborsClassifier from sklearn import metrics from sklearn.metrics import confusion_matrix,",
"looked out for when looking for candidates to give loans to. # #",
"In[6]: df.describe() # In[7]: plt.hist(df['BAD'], bins=3) plt.show() # In[8]: df['LOAN'].plot(kind='density') plt.show() # In[9]:",
"# In[23]: dependent_performance_dt = tree_estimator.predict(x_train) metrics_score(y_train, dependent_performance_dt) # - We increased the less",
"QuadraticDiscriminantAnalysis from sklearn.linear_model import LogisticRegression from sklearn.neighbors import KNeighborsClassifier from sklearn import metrics",
"lets see if we can do better # - Selfnote: do importance features",
"tried to tune the model, this reduced the harmful error. # - Then",
"plt.pie(df['REASON'].value_counts(), labels=['DebtCon', 'HomeImp'], autopct='%.1f') plt.show() df['REASON'].value_counts() # In[10]: correlation = df.corr() sns.heatmap(correlation) plt.show()",
"Years at job is also a driver of a loans outcome. A large",
"# In[9]: plt.pie(df['REASON'].value_counts(), labels=['DebtCon', 'HomeImp'], autopct='%.1f') plt.show() df['REASON'].value_counts() # In[10]: correlation = df.corr()",
"bins=3) plt.show() # In[8]: df['LOAN'].plot(kind='density') plt.show() # In[9]: plt.pie(df['REASON'].value_counts(), labels=['DebtCon', 'HomeImp'], autopct='%.1f') plt.show()",
"fix overfitting # In[30]: forest_estimator_tuned = RandomForestClassifier(class_weight={0:0.20,1:0.80}, random_state=1) parameters_rf = { \"n_estimators\": [100,250,500],",
"improve even more I created a decision tree model, this had excellent performance",
"- Nothing needs to be dropped # In[6]: df.describe() # In[7]: plt.hist(df['BAD'], bins=3)",
"- Something else that effects defaulting on a loan is the number of",
"In[9]: plt.pie(df['REASON'].value_counts(), labels=['DebtCon', 'HomeImp'], autopct='%.1f') plt.show() df['REASON'].value_counts() # In[10]: correlation = df.corr() sns.heatmap(correlation)",
"import shap # In[35]: shap.initjs() # In[36]: explain = shap.TreeExplainer(forest_estimator_tuned) shap_vals = explain(x_train)",
"test data # In[20]: dependent_test_performance_dt = dtree.predict(x_test) metrics_score(y_test,dependent_test_performance_dt) # - As we can",
"to tune the model, this reduced the harmful error. # - Then to",
"we got decent performance from this model, lets see if we can do",
"forest_estimator.predict(x_test) metrics_score(y_test, y_predict_test_forest) # - The performance is a lot better than the",
"# - To improve the performance of this we tried to tune the",
"a decision tree model, this had excellent performance once we created a second",
"loan. # - Those are some warning signs/good signs that should be looked",
"a lower income they may have a harder time paying back a loan.",
"the clf to the best combination of parameters forest_estimator_tuned = grid_obj.best_estimator_ # In[31]:",
"of delinquent credit lines. This means that someone who cannot make their credit",
"explain(x_train) # In[37]: type(shap_vals) # In[38]: shap.plots.bar(shap_vals[:, :, 0]) # In[39]: shap.plots.heatmap(shap_vals[:, :,",
"paying back a loan. # - Something else that effects defaulting on a",
"# - Then to improve even more I created a decision tree model,",
"importance_df=pd.DataFrame(important,index=columns,columns=['Importance']).sort_values(by='Importance',ascending=False) plt.figure(figsize=(13,13)) sns.barplot(importance_df.Importance,importance_df.index) plt.show() # In[26]: features = list(independent.columns) plt.figure(figsize=(30,20)) tree.plot_tree(dtree,max_depth=4,feature_names=features,filled=True,fontsize=12,node_ids=True,class_names=True) plt.show() #",
"In[8]: df['LOAN'].plot(kind='density') plt.show() # In[9]: plt.pie(df['REASON'].value_counts(), labels=['DebtCon', 'HomeImp'], autopct='%.1f') plt.show() df['REASON'].value_counts() # In[10]:",
"x_test, y_train, y_test = train_test_split(independent, dependent, test_size=0.3, random_state=1) # In[16]: def metrics_score(actual, predicted):",
"# - Those are some warning signs/good signs that should be looked out",
"- The biggest thing that effects defaulting on a loan is the debt",
"as pd import numpy as np import matplotlib.pyplot as plt import seaborn as",
"Nothing needs to be dropped # In[6]: df.describe() # In[7]: plt.hist(df['BAD'], bins=3) plt.show()",
"# In[8]: df['LOAN'].plot(kind='density') plt.show() # In[9]: plt.pie(df['REASON'].value_counts(), labels=['DebtCon', 'HomeImp'], autopct='%.1f') plt.show() df['REASON'].value_counts() #",
"dtree.feature_importances_ columns = independent.columns important_items_df = pd.DataFrame(important, index=columns, columns=['Importance']).sort_values(by='Importance', ascending=False) plt.figure(figsize=(13,13)) sns.barplot(important_items_df.Importance, important_items_df.index)",
"the best combination of parameters forest_estimator_tuned = grid_obj.best_estimator_ # In[31]: forest_estimator_tuned.fit(x_train, y_train) #",
"sklearn import tree from sklearn.tree import DecisionTreeClassifier from sklearn.ensemble import BaggingClassifier from sklearn.ensemble",
"CLAGE and CLNO # In[22]: tree_estimator = DecisionTreeClassifier(class_weight={0:0.20, 1:0.80}, random_state=1) parameters = {",
"# In[26]: features = list(independent.columns) plt.figure(figsize=(30,20)) tree.plot_tree(dtree,max_depth=4,feature_names=features,filled=True,fontsize=12,node_ids=True,class_names=True) plt.show() # - A visualization is",
"should be looked out for when looking for candidates to give loans to.",
"features are DEBTINC, CLAGE and CLNO # In[22]: tree_estimator = DecisionTreeClassifier(class_weight={0:0.20, 1:0.80}, random_state=1)",
"sklearn.model_selection import GridSearchCV # In[2]: df = pd.read_csv(\"Dataset.csv\") # In[3]: df.head() # In[4]:",
"that dtrees offer, we can show this to the client ot show the",
"that Reason and Bad are binary variables # - Nothing needs to be",
"In[19]: dependent_performance_dt = dtree.predict(x_train) metrics_score(y_train, dependent_performance_dt) # - The above is perfect because",
"sklearn.ensemble import RandomForestClassifier from sklearn.model_selection import GridSearchCV # In[2]: df = pd.read_csv(\"Dataset.csv\") #",
"4,1), \"max_features\": [0.7,0.9,'auto'], } score = metrics.make_scorer(recall_score, pos_label=1) # Run the grid search",
"'max_depth':np.arange(2,7), 'criterion':['gini', 'entropy'], 'min_samples_leaf':[5,10,20,25] } score = metrics.make_scorer(recall_score, pos_label=1) gridCV= GridSearchCV(tree_estimator, parameters, scoring=score,cv=10)",
"y_train) # In[28]: y_predict_training_forest = forest_estimator.predict(x_train) metrics_score(y_train, y_predict_training_forest) # - A perfect classification",
"from a previous project to see the most important features # - We",
"df = df.drop('REASON', axis=1) df = df.join(one_hot_encoding) df # In[14]: one_hot_encoding2 = pd.get_dummies(df['JOB'])",
"one of the advantages that dtrees offer, we can show this to the",
"Lets test on test data # In[20]: dependent_test_performance_dt = dtree.predict(x_test) metrics_score(y_test,dependent_test_performance_dt) # -",
"# - Nothing needs to be dropped # In[6]: df.describe() # In[7]: plt.hist(df['BAD'],",
"above is perfect because we are using the train values, not the test",
"y_predict_train_forest_tuned) # In[33]: y_predict_test_forest_tuned = forest_estimator_tuned.predict(x_test) metrics_score(y_test, y_predict_test_forest_tuned) # - We now have",
"# - As we can see, we got decent performance from this model,",
"y_predict_training_forest = forest_estimator.predict(x_train) metrics_score(y_train, y_predict_training_forest) # - A perfect classification # - This",
"are some warning signs/good signs that should be looked out for when looking",
"a lot better than the original single tree # - Lets fix overfitting",
"from sklearn.model_selection import GridSearchCV # In[2]: df = pd.read_csv(\"Dataset.csv\") # In[3]: df.head() #",
"autopct='%.1f') plt.show() df['REASON'].value_counts() # In[10]: correlation = df.corr() sns.heatmap(correlation) plt.show() # In[11]: df['BAD'].value_counts(normalize=True)",
"df['BAD'] independent = df.drop(['BAD'], axis=1) x_train, x_test, y_train, y_test = train_test_split(independent, dependent, test_size=0.3,",
"This implies overfitting # In[29]: y_predict_test_forest = forest_estimator.predict(x_test) metrics_score(y_test, y_predict_test_forest) # - The",
"= pd.get_dummies(df['JOB']) df = df.drop('JOB', axis=1) df = df.join(one_hot_encoding2) df # In[15]: dependent",
"# In[40]: shap.summary_plot(shap_vals[:, :, 0], x_train) # In[53]: print(forest_estimator_tuned.predict(x_test.iloc[107].to_numpy().reshape(1,-1))) # This predicts for",
"In[12]: df.fillna(df.mean(), inplace=True) # In[13]: one_hot_encoding = pd.get_dummies(df['REASON']) df = df.drop('REASON', axis=1) df",
"= DecisionTreeClassifier(class_weight={0:0.20, 1:0.80}, random_state=1) # In[18]: dtree.fit(x_train, y_train) # In[19]: dependent_performance_dt = dtree.predict(x_train)",
"number of years at a job could indicate financial stability. # - DEROG,",
"we can see that Reason and Bad are binary variables # - Nothing",
"KNeighborsClassifier from sklearn import metrics from sklearn.metrics import confusion_matrix, classification_report, precision_recall_curve,recall_score from sklearn",
"plt.ylabel('Actual') plt.xlabel('Predicted') plt.show() # In[17]: dtree = DecisionTreeClassifier(class_weight={0:0.20, 1:0.80}, random_state=1) # In[18]: dtree.fit(x_train,",
"metrics_score(actual, predicted): print(classification_report(actual, predicted)) cm = confusion_matrix(actual, predicted) plt.figure(figsize=(8,5)) sns.heatmap(cm, annot=True, fmt='.2f', xticklabels=['Not",
"are using the train values, not the test # - Lets test on",
"from sklearn.tree import DecisionTreeClassifier from sklearn.ensemble import BaggingClassifier from sklearn.ensemble import RandomForestClassifier from",
"can see, we got decent performance from this model, lets see if we",
"- We increased the less harmful error but decreased the harmful error #",
"more into this model. # In[34]: get_ipython().system('pip install shap') import shap # In[35]:",
"In[2]: df = pd.read_csv(\"Dataset.csv\") # In[3]: df.head() # In[4]: df.info() # In[5]: df.nunique()",
"sklearn.ensemble import BaggingClassifier from sklearn.ensemble import RandomForestClassifier from sklearn.model_selection import GridSearchCV # In[2]:",
"sign of not being able to pay back a loan. # - Those",
"# - We can submit this to the company # ### Conclusion #",
"implies overfitting # In[29]: y_predict_test_forest = forest_estimator.predict(x_test) metrics_score(y_test, y_predict_test_forest) # - The performance",
"variables # - Nothing needs to be dropped # In[6]: df.describe() # In[7]:",
"parameters, scoring=score,cv=10) gridCV = gridCV.fit(x_train, y_train) tree_estimator = gridCV.best_estimator_ tree_estimator.fit(x_train, y_train) # In[23]:",
"we can see, we got decent performance from this model, lets see if",
"error but decreased the harmful error # In[24]: dependent_test_performance_dt = tree_estimator.predict(x_test) metrics_score(y_test, dependent_test_performance_dt)",
"first one I made was a decision tree, this is not as good",
"can see that the most important features are DEBTINC, CLAGE and CLNO #",
"The biggest thing that effects defaulting on a loan is the debt to",
"which removed overfitting. # ### Recommendations # - The biggest thing that effects",
"stability. # - DEROG, or a history of delinquent payments is also a",
"= df.join(one_hot_encoding) df # In[14]: one_hot_encoding2 = pd.get_dummies(df['JOB']) df = df.drop('JOB', axis=1) df",
"We now have very good performance # - We can submit this to",
"import seaborn as sns from sklearn.preprocessing import StandardScaler from sklearn.model_selection import train_test_split from",
"plt.figure(figsize=(13,13)) sns.barplot(importance_df.Importance,importance_df.index) plt.show() # In[26]: features = list(independent.columns) plt.figure(figsize=(30,20)) tree.plot_tree(dtree,max_depth=4,feature_names=features,filled=True,fontsize=12,node_ids=True,class_names=True) plt.show() # -",
"that the most important features are DEBTINC, CLAGE and CLNO # In[22]: tree_estimator",
"delinquent credit lines. This means that someone who cannot make their credit card",
"metrics_score(y_test, y_predict_test_forest) # - The performance is a lot better than the original",
"as plt import seaborn as sns from sklearn.preprocessing import StandardScaler from sklearn.model_selection import",
"card payments will have a hard time paying back a loan. # -",
"parameters_rf = { \"n_estimators\": [100,250,500], \"min_samples_leaf\": np.arange(1, 4,1), \"max_features\": [0.7,0.9,'auto'], } score =",
"important features are DEBTINC, CLAGE and CLNO # In[22]: tree_estimator = DecisionTreeClassifier(class_weight={0:0.20, 1:0.80},",
"is transparent as it lets us visualize it. This first one had decent",
"GridSearchCV(forest_estimator_tuned, parameters_rf, scoring=score, cv=5) grid_obj = grid_obj.fit(x_train, y_train) # Set the clf to",
"importance features next # In[21]: important = dtree.feature_importances_ columns = independent.columns important_items_df =",
"= forest_estimator_tuned.predict(x_train) metrics_score(y_train, y_predict_train_forest_tuned) # In[33]: y_predict_test_forest_tuned = forest_estimator_tuned.predict(x_test) metrics_score(y_test, y_predict_test_forest_tuned) # -",
"y_predict_test_forest = forest_estimator.predict(x_test) metrics_score(y_test, y_predict_test_forest) # - The performance is a lot better",
"next # In[21]: important = dtree.feature_importances_ columns = independent.columns important_items_df = pd.DataFrame(important, index=columns,",
"a history of delinquent payments is also a warning sign of not being",
"In[17]: dtree = DecisionTreeClassifier(class_weight={0:0.20, 1:0.80}, random_state=1) # In[18]: dtree.fit(x_train, y_train) # In[19]: dependent_performance_dt",
"once we created a second version which removed overfitting. # ### Recommendations #",
"because we are using the train values, not the test # - Lets",
"} score = metrics.make_scorer(recall_score, pos_label=1) # Run the grid search grid_obj = GridSearchCV(forest_estimator_tuned,",
"= { \"n_estimators\": [100,250,500], \"min_samples_leaf\": np.arange(1, 4,1), \"max_features\": [0.7,0.9,'auto'], } score = metrics.make_scorer(recall_score,",
"indicate financial stability. # - DEROG, or a history of delinquent payments is",
"In[34]: get_ipython().system('pip install shap') import shap # In[35]: shap.initjs() # In[36]: explain =",
"us visualize it. This first one had decent performance. # - To improve",
"was a decision tree, this is not as good as random forest but",
"a hard time paying back a loan. # - Years at job is",
"loan. # - Something else that effects defaulting on a loan is the",
"from sklearn.neighbors import KNeighborsClassifier from sklearn import metrics from sklearn.metrics import confusion_matrix, classification_report,",
"to look more into this model. # In[34]: get_ipython().system('pip install shap') import shap",
"= metrics.make_scorer(recall_score, pos_label=1) gridCV= GridSearchCV(tree_estimator, parameters, scoring=score,cv=10) gridCV = gridCV.fit(x_train, y_train) tree_estimator =",
"y_train) tree_estimator = gridCV.best_estimator_ tree_estimator.fit(x_train, y_train) # In[23]: dependent_performance_dt = tree_estimator.predict(x_train) metrics_score(y_train, dependent_performance_dt)",
"GridSearchCV # In[2]: df = pd.read_csv(\"Dataset.csv\") # In[3]: df.head() # In[4]: df.info() #",
"# In[7]: plt.hist(df['BAD'], bins=3) plt.show() # In[8]: df['LOAN'].plot(kind='density') plt.show() # In[9]: plt.pie(df['REASON'].value_counts(), labels=['DebtCon',",
"scoring=score,cv=10) gridCV = gridCV.fit(x_train, y_train) tree_estimator = gridCV.best_estimator_ tree_estimator.fit(x_train, y_train) # In[23]: dependent_performance_dt",
"slightly worse, we still reduce harmful error # In[25]: important = tree_estimator.feature_importances_ columns=independent.columns",
"most important features are DEBTINC, CLAGE and CLNO # In[22]: tree_estimator = DecisionTreeClassifier(class_weight={0:0.20,",
"In[31]: forest_estimator_tuned.fit(x_train, y_train) # In[32]: y_predict_train_forest_tuned = forest_estimator_tuned.predict(x_train) metrics_score(y_train, y_predict_train_forest_tuned) # In[33]: y_predict_test_forest_tuned",
"sns.barplot(important_items_df.Importance, important_items_df.index) plt.show() # - I followed this from a previous project to",
"np import matplotlib.pyplot as plt import seaborn as sns from sklearn.preprocessing import StandardScaler",
"loan is the number of delinquent credit lines. This means that someone who",
"print(forest_estimator_tuned.predict(x_test.iloc[107].to_numpy().reshape(1,-1))) # This predicts for one row, 0 means approved, 1 means no.",
"for when looking for candidates to give loans to. # # I will",
"# In[16]: def metrics_score(actual, predicted): print(classification_report(actual, predicted)) cm = confusion_matrix(actual, predicted) plt.figure(figsize=(8,5)) sns.heatmap(cm,",
"is slightly worse, we still reduce harmful error # In[25]: important = tree_estimator.feature_importances_",
"defaulting on a loan is the number of delinquent credit lines. This means",
"# In[10]: correlation = df.corr() sns.heatmap(correlation) plt.show() # In[11]: df['BAD'].value_counts(normalize=True) # In[12]: df.fillna(df.mean(),",
"performance # - We can submit this to the company # ### Conclusion",
"plt.hist(df['BAD'], bins=3) plt.show() # In[8]: df['LOAN'].plot(kind='density') plt.show() # In[9]: plt.pie(df['REASON'].value_counts(), labels=['DebtCon', 'HomeImp'], autopct='%.1f')",
"dependent_test_performance_dt = dtree.predict(x_test) metrics_score(y_test,dependent_test_performance_dt) # - As we can see, we got decent",
"= explain(x_train) # In[37]: type(shap_vals) # In[38]: shap.plots.bar(shap_vals[:, :, 0]) # In[39]: shap.plots.heatmap(shap_vals[:,",
"DecisionTreeClassifier(class_weight={0:0.20, 1:0.80}, random_state=1) parameters = { 'max_depth':np.arange(2,7), 'criterion':['gini', 'entropy'], 'min_samples_leaf':[5,10,20,25] } score =",
"# - Something else that effects defaulting on a loan is the number",
"random_state=1) # In[18]: dtree.fit(x_train, y_train) # In[19]: dependent_performance_dt = dtree.predict(x_train) metrics_score(y_train, dependent_performance_dt) #",
"a loan. # - Those are some warning signs/good signs that should be",
"show the thought process # In[27]: forest_estimator = RandomForestClassifier(class_weight={0:0.20, 1:0.80}, random_state=1) forest_estimator.fit(x_train, y_train)",
"show this to the client ot show the thought process # In[27]: forest_estimator",
"very good performance # - We can submit this to the company #",
"from sklearn.metrics import confusion_matrix, classification_report, precision_recall_curve,recall_score from sklearn import tree from sklearn.tree import",
"In[27]: forest_estimator = RandomForestClassifier(class_weight={0:0.20, 1:0.80}, random_state=1) forest_estimator.fit(x_train, y_train) # In[28]: y_predict_training_forest = forest_estimator.predict(x_train)",
"df.corr() sns.heatmap(correlation) plt.show() # In[11]: df['BAD'].value_counts(normalize=True) # In[12]: df.fillna(df.mean(), inplace=True) # In[13]: one_hot_encoding",
"important_items_df = pd.DataFrame(important, index=columns, columns=['Importance']).sort_values(by='Importance', ascending=False) plt.figure(figsize=(13,13)) sns.barplot(important_items_df.Importance, important_items_df.index) plt.show() # - I",
"is the debt to income ratio. If someone has a lot of debt",
"from sklearn.discriminant_analysis import QuadraticDiscriminantAnalysis from sklearn.linear_model import LogisticRegression from sklearn.neighbors import KNeighborsClassifier from",
"to be dropped # In[6]: df.describe() # In[7]: plt.hist(df['BAD'], bins=3) plt.show() # In[8]:",
"fmt='.2f', xticklabels=['Not Default', 'Default'], yticklabels=['Not Default', 'Default']) plt.ylabel('Actual') plt.xlabel('Predicted') plt.show() # In[17]: dtree",
"or a history of delinquent payments is also a warning sign of not",
"I will now apply SHAP to look more into this model. # In[34]:",
"df['BAD'].value_counts(normalize=True) # In[12]: df.fillna(df.mean(), inplace=True) # In[13]: one_hot_encoding = pd.get_dummies(df['REASON']) df = df.drop('REASON',",
"pd.get_dummies(df['REASON']) df = df.drop('REASON', axis=1) df = df.join(one_hot_encoding) df # In[14]: one_hot_encoding2 =",
"many models to get the best results. # - The first one I",
"made was a decision tree, this is not as good as random forest",
"In[30]: forest_estimator_tuned = RandomForestClassifier(class_weight={0:0.20,1:0.80}, random_state=1) parameters_rf = { \"n_estimators\": [100,250,500], \"min_samples_leaf\": np.arange(1, 4,1),",
"sklearn.neighbors import KNeighborsClassifier from sklearn import metrics from sklearn.metrics import confusion_matrix, classification_report, precision_recall_curve,recall_score",
"df.describe() # In[7]: plt.hist(df['BAD'], bins=3) plt.show() # In[8]: df['LOAN'].plot(kind='density') plt.show() # In[9]: plt.pie(df['REASON'].value_counts(),",
"who cannot make their credit card payments will have a hard time paying",
"ot show the thought process # In[27]: forest_estimator = RandomForestClassifier(class_weight={0:0.20, 1:0.80}, random_state=1) forest_estimator.fit(x_train,",
"forest but it is transparent as it lets us visualize it. This first",
"# In[31]: forest_estimator_tuned.fit(x_train, y_train) # In[32]: y_predict_train_forest_tuned = forest_estimator_tuned.predict(x_train) metrics_score(y_train, y_predict_train_forest_tuned) # In[33]:",
"years at a job could indicate financial stability. # - DEROG, or a",
"RandomForestClassifier from sklearn.model_selection import GridSearchCV # In[2]: df = pd.read_csv(\"Dataset.csv\") # In[3]: df.head()",
"# - I followed this from a previous project to see the most",
"to give loans to. # # I will now apply SHAP to look",
"y_train, y_test = train_test_split(independent, dependent, test_size=0.3, random_state=1) # In[16]: def metrics_score(actual, predicted): print(classification_report(actual,",
"time paying back a loan. # - Years at job is also a",
"important features # - We can see that the most important features are",
"someone who cannot make their credit card payments will have a hard time",
"hard time paying back a loan. # - Years at job is also",
"- A perfect classification # - This implies overfitting # In[29]: y_predict_test_forest =",
"# # Loan Classification Project # In[1]: # Libraries we need import pandas",
"to the company # ### Conclusion # - I made many models to",
"it lets us visualize it. This first one had decent performance. # -",
"a loan is the number of delinquent credit lines. This means that someone",
"model, this had excellent performance once we created a second version which removed",
"In[14]: one_hot_encoding2 = pd.get_dummies(df['JOB']) df = df.drop('JOB', axis=1) df = df.join(one_hot_encoding2) df #",
"# coding: utf-8 # # Loan Classification Project # In[1]: # Libraries we",
"performance once we created a second version which removed overfitting. # ### Recommendations",
"tree_estimator.feature_importances_ columns=independent.columns importance_df=pd.DataFrame(important,index=columns,columns=['Importance']).sort_values(by='Importance',ascending=False) plt.figure(figsize=(13,13)) sns.barplot(importance_df.Importance,importance_df.index) plt.show() # In[26]: features = list(independent.columns) plt.figure(figsize=(30,20)) tree.plot_tree(dtree,max_depth=4,feature_names=features,filled=True,fontsize=12,node_ids=True,class_names=True)",
"In[33]: y_predict_test_forest_tuned = forest_estimator_tuned.predict(x_test) metrics_score(y_test, y_predict_test_forest_tuned) # - We now have very good",
"metrics_score(y_train, y_predict_training_forest) # - A perfect classification # - This implies overfitting #",
"being able to pay back a loan. # - Those are some warning",
"import pandas as pd import numpy as np import matplotlib.pyplot as plt import",
"had decent performance. # - To improve the performance of this we tried",
"= pd.get_dummies(df['REASON']) df = df.drop('REASON', axis=1) df = df.join(one_hot_encoding) df # In[14]: one_hot_encoding2",
"performance from this model, lets see if we can do better # -",
"it. This first one had decent performance. # - To improve the performance",
"= grid_obj.best_estimator_ # In[31]: forest_estimator_tuned.fit(x_train, y_train) # In[32]: y_predict_train_forest_tuned = forest_estimator_tuned.predict(x_train) metrics_score(y_train, y_predict_train_forest_tuned)",
"have a hard time paying back a loan. # - Years at job",
"# I will now apply SHAP to look more into this model. #",
"- As we can see, we got decent performance from this model, lets",
"we can do better # - Selfnote: do importance features next # In[21]:",
"to the best combination of parameters forest_estimator_tuned = grid_obj.best_estimator_ # In[31]: forest_estimator_tuned.fit(x_train, y_train)",
"from sklearn.ensemble import RandomForestClassifier from sklearn.model_selection import GridSearchCV # In[2]: df = pd.read_csv(\"Dataset.csv\")",
"random forest but it is transparent as it lets us visualize it. This",
"# In[35]: shap.initjs() # In[36]: explain = shap.TreeExplainer(forest_estimator_tuned) shap_vals = explain(x_train) # In[37]:",
"forest_estimator_tuned.predict(x_test) metrics_score(y_test, y_predict_test_forest_tuned) # - We now have very good performance # -",
"performance is slightly worse, we still reduce harmful error # In[25]: important =",
"a harder time paying back a loan. # - Something else that effects",
"gridCV.fit(x_train, y_train) tree_estimator = gridCV.best_estimator_ tree_estimator.fit(x_train, y_train) # In[23]: dependent_performance_dt = tree_estimator.predict(x_train) metrics_score(y_train,",
"# In[36]: explain = shap.TreeExplainer(forest_estimator_tuned) shap_vals = explain(x_train) # In[37]: type(shap_vals) # In[38]:",
"type(shap_vals) # In[38]: shap.plots.bar(shap_vals[:, :, 0]) # In[39]: shap.plots.heatmap(shap_vals[:, :, 0]) # In[40]:",
"sklearn.discriminant_analysis import LinearDiscriminantAnalysis from sklearn.discriminant_analysis import QuadraticDiscriminantAnalysis from sklearn.linear_model import LogisticRegression from sklearn.neighbors",
"= pd.read_csv(\"Dataset.csv\") # In[3]: df.head() # In[4]: df.info() # In[5]: df.nunique() # -",
"harder time paying back a loan. # - Something else that effects defaulting",
"df = df.join(one_hot_encoding2) df # In[15]: dependent = df['BAD'] independent = df.drop(['BAD'], axis=1)",
"= independent.columns important_items_df = pd.DataFrame(important, index=columns, columns=['Importance']).sort_values(by='Importance', ascending=False) plt.figure(figsize=(13,13)) sns.barplot(important_items_df.Importance, important_items_df.index) plt.show() #",
"see, we got decent performance from this model, lets see if we can",
"if we can do better # - Selfnote: do importance features next #",
"someone has a lot of debt and a lower income they may have",
"sklearn.model_selection import train_test_split from sklearn.discriminant_analysis import LinearDiscriminantAnalysis from sklearn.discriminant_analysis import QuadraticDiscriminantAnalysis from sklearn.linear_model",
"of years at a job could indicate financial stability. # - DEROG, or",
"the performance is slightly worse, we still reduce harmful error # In[25]: important",
"# - The first one I made was a decision tree, this is",
"loans to. # # I will now apply SHAP to look more into",
"at a job could indicate financial stability. # - DEROG, or a history",
"import DecisionTreeClassifier from sklearn.ensemble import BaggingClassifier from sklearn.ensemble import RandomForestClassifier from sklearn.model_selection import",
"sns.heatmap(cm, annot=True, fmt='.2f', xticklabels=['Not Default', 'Default'], yticklabels=['Not Default', 'Default']) plt.ylabel('Actual') plt.xlabel('Predicted') plt.show() #",
"= df.corr() sns.heatmap(correlation) plt.show() # In[11]: df['BAD'].value_counts(normalize=True) # In[12]: df.fillna(df.mean(), inplace=True) # In[13]:",
"grid_obj = GridSearchCV(forest_estimator_tuned, parameters_rf, scoring=score, cv=5) grid_obj = grid_obj.fit(x_train, y_train) # Set the",
"y_train) # In[19]: dependent_performance_dt = dtree.predict(x_train) metrics_score(y_train, dependent_performance_dt) # - The above is",
"df.drop('JOB', axis=1) df = df.join(one_hot_encoding2) df # In[15]: dependent = df['BAD'] independent =",
"the debt to income ratio. If someone has a lot of debt and",
"shap # In[35]: shap.initjs() # In[36]: explain = shap.TreeExplainer(forest_estimator_tuned) shap_vals = explain(x_train) #",
"python # coding: utf-8 # # Loan Classification Project # In[1]: # Libraries",
"as sns from sklearn.preprocessing import StandardScaler from sklearn.model_selection import train_test_split from sklearn.discriminant_analysis import",
"plt.show() # In[9]: plt.pie(df['REASON'].value_counts(), labels=['DebtCon', 'HomeImp'], autopct='%.1f') plt.show() df['REASON'].value_counts() # In[10]: correlation =",
"most important features # - We can see that the most important features",
"the harmful error # In[24]: dependent_test_performance_dt = tree_estimator.predict(x_test) metrics_score(y_test, dependent_test_performance_dt) # - Although",
"performance is a lot better than the original single tree # - Lets",
"offer, we can show this to the client ot show the thought process",
"I made was a decision tree, this is not as good as random",
"seaborn as sns from sklearn.preprocessing import StandardScaler from sklearn.model_selection import train_test_split from sklearn.discriminant_analysis",
"at job is also a driver of a loans outcome. A large number",
"a loan. # - Something else that effects defaulting on a loan is",
"= dtree.predict(x_test) metrics_score(y_test,dependent_test_performance_dt) # - As we can see, we got decent performance",
"features = list(independent.columns) plt.figure(figsize=(30,20)) tree.plot_tree(dtree,max_depth=4,feature_names=features,filled=True,fontsize=12,node_ids=True,class_names=True) plt.show() # - A visualization is one of",
"= list(independent.columns) plt.figure(figsize=(30,20)) tree.plot_tree(dtree,max_depth=4,feature_names=features,filled=True,fontsize=12,node_ids=True,class_names=True) plt.show() # - A visualization is one of the",
"In[29]: y_predict_test_forest = forest_estimator.predict(x_test) metrics_score(y_test, y_predict_test_forest) # - The performance is a lot",
"random_state=1) # In[16]: def metrics_score(actual, predicted): print(classification_report(actual, predicted)) cm = confusion_matrix(actual, predicted) plt.figure(figsize=(8,5))",
"RandomForestClassifier(class_weight={0:0.20,1:0.80}, random_state=1) parameters_rf = { \"n_estimators\": [100,250,500], \"min_samples_leaf\": np.arange(1, 4,1), \"max_features\": [0.7,0.9,'auto'], }",
"one I made was a decision tree, this is not as good as",
"If someone has a lot of debt and a lower income they may",
":, 0], x_train) # In[53]: print(forest_estimator_tuned.predict(x_test.iloc[107].to_numpy().reshape(1,-1))) # This predicts for one row, 0",
"made many models to get the best results. # - The first one",
"Bad are binary variables # - Nothing needs to be dropped # In[6]:",
"tree.plot_tree(dtree,max_depth=4,feature_names=features,filled=True,fontsize=12,node_ids=True,class_names=True) plt.show() # - A visualization is one of the advantages that dtrees",
"labels=['DebtCon', 'HomeImp'], autopct='%.1f') plt.show() df['REASON'].value_counts() # In[10]: correlation = df.corr() sns.heatmap(correlation) plt.show() #",
"they may have a harder time paying back a loan. # - Something",
"shap.TreeExplainer(forest_estimator_tuned) shap_vals = explain(x_train) # In[37]: type(shap_vals) # In[38]: shap.plots.bar(shap_vals[:, :, 0]) #",
"- Although the performance is slightly worse, we still reduce harmful error #",
"perfect classification # - This implies overfitting # In[29]: y_predict_test_forest = forest_estimator.predict(x_test) metrics_score(y_test,",
"= forest_estimator.predict(x_test) metrics_score(y_test, y_predict_test_forest) # - The performance is a lot better than",
"be dropped # In[6]: df.describe() # In[7]: plt.hist(df['BAD'], bins=3) plt.show() # In[8]: df['LOAN'].plot(kind='density')",
"'Default']) plt.ylabel('Actual') plt.xlabel('Predicted') plt.show() # In[17]: dtree = DecisionTreeClassifier(class_weight={0:0.20, 1:0.80}, random_state=1) # In[18]:",
"the most important features # - We can see that the most important",
"and a lower income they may have a harder time paying back a",
"Default', 'Default']) plt.ylabel('Actual') plt.xlabel('Predicted') plt.show() # In[17]: dtree = DecisionTreeClassifier(class_weight={0:0.20, 1:0.80}, random_state=1) #",
"is the number of delinquent credit lines. This means that someone who cannot",
"is perfect because we are using the train values, not the test #",
"metrics from sklearn.metrics import confusion_matrix, classification_report, precision_recall_curve,recall_score from sklearn import tree from sklearn.tree",
"data # In[20]: dependent_test_performance_dt = dtree.predict(x_test) metrics_score(y_test,dependent_test_performance_dt) # - As we can see,",
"grid_obj = grid_obj.fit(x_train, y_train) # Set the clf to the best combination of",
"forest_estimator_tuned = grid_obj.best_estimator_ # In[31]: forest_estimator_tuned.fit(x_train, y_train) # In[32]: y_predict_train_forest_tuned = forest_estimator_tuned.predict(x_train) metrics_score(y_train,",
"client ot show the thought process # In[27]: forest_estimator = RandomForestClassifier(class_weight={0:0.20, 1:0.80}, random_state=1)",
"second version which removed overfitting. # ### Recommendations # - The biggest thing",
"# - This implies overfitting # In[29]: y_predict_test_forest = forest_estimator.predict(x_test) metrics_score(y_test, y_predict_test_forest) #",
"# In[53]: print(forest_estimator_tuned.predict(x_test.iloc[107].to_numpy().reshape(1,-1))) # This predicts for one row, 0 means approved, 1",
"y_predict_test_forest) # - The performance is a lot better than the original single",
"= forest_estimator.predict(x_train) metrics_score(y_train, y_predict_training_forest) # - A perfect classification # - This implies",
"predicted): print(classification_report(actual, predicted)) cm = confusion_matrix(actual, predicted) plt.figure(figsize=(8,5)) sns.heatmap(cm, annot=True, fmt='.2f', xticklabels=['Not Default',",
"In[4]: df.info() # In[5]: df.nunique() # - Above we can see that Reason",
"In[5]: df.nunique() # - Above we can see that Reason and Bad are",
"= tree_estimator.predict(x_test) metrics_score(y_test, dependent_test_performance_dt) # - Although the performance is slightly worse, we",
"# In[32]: y_predict_train_forest_tuned = forest_estimator_tuned.predict(x_train) metrics_score(y_train, y_predict_train_forest_tuned) # In[33]: y_predict_test_forest_tuned = forest_estimator_tuned.predict(x_test) metrics_score(y_test,",
"for candidates to give loans to. # # I will now apply SHAP",
"debt and a lower income they may have a harder time paying back",
"dtree.predict(x_test) metrics_score(y_test,dependent_test_performance_dt) # - As we can see, we got decent performance from",
"y_test = train_test_split(independent, dependent, test_size=0.3, random_state=1) # In[16]: def metrics_score(actual, predicted): print(classification_report(actual, predicted))",
"# - Years at job is also a driver of a loans outcome.",
"a loans outcome. A large number of years at a job could indicate",
"parameters = { 'max_depth':np.arange(2,7), 'criterion':['gini', 'entropy'], 'min_samples_leaf':[5,10,20,25] } score = metrics.make_scorer(recall_score, pos_label=1) gridCV=",
"this model. # In[34]: get_ipython().system('pip install shap') import shap # In[35]: shap.initjs() #",
"can submit this to the company # ### Conclusion # - I made",
"y_predict_test_forest_tuned) # - We now have very good performance # - We can",
"has a lot of debt and a lower income they may have a",
"Default', 'Default'], yticklabels=['Not Default', 'Default']) plt.ylabel('Actual') plt.xlabel('Predicted') plt.show() # In[17]: dtree = DecisionTreeClassifier(class_weight={0:0.20,",
"metrics_score(y_test, dependent_test_performance_dt) # - Although the performance is slightly worse, we still reduce",
"the company # ### Conclusion # - I made many models to get",
"from sklearn.discriminant_analysis import LinearDiscriminantAnalysis from sklearn.discriminant_analysis import QuadraticDiscriminantAnalysis from sklearn.linear_model import LogisticRegression from",
"classification # - This implies overfitting # In[29]: y_predict_test_forest = forest_estimator.predict(x_test) metrics_score(y_test, y_predict_test_forest)",
"- This implies overfitting # In[29]: y_predict_test_forest = forest_estimator.predict(x_test) metrics_score(y_test, y_predict_test_forest) # -",
"In[38]: shap.plots.bar(shap_vals[:, :, 0]) # In[39]: shap.plots.heatmap(shap_vals[:, :, 0]) # In[40]: shap.summary_plot(shap_vals[:, :,",
"on a loan is the debt to income ratio. If someone has a",
"Lets fix overfitting # In[30]: forest_estimator_tuned = RandomForestClassifier(class_weight={0:0.20,1:0.80}, random_state=1) parameters_rf = { \"n_estimators\":",
"dependent_performance_dt = tree_estimator.predict(x_train) metrics_score(y_train, dependent_performance_dt) # - We increased the less harmful error",
"of the advantages that dtrees offer, we can show this to the client",
"test # - Lets test on test data # In[20]: dependent_test_performance_dt = dtree.predict(x_test)",
"The performance is a lot better than the original single tree # -",
"= df.drop('REASON', axis=1) df = df.join(one_hot_encoding) df # In[14]: one_hot_encoding2 = pd.get_dummies(df['JOB']) df",
"some warning signs/good signs that should be looked out for when looking for",
"got decent performance from this model, lets see if we can do better",
"= dtree.predict(x_train) metrics_score(y_train, dependent_performance_dt) # - The above is perfect because we are",
"predicted) plt.figure(figsize=(8,5)) sns.heatmap(cm, annot=True, fmt='.2f', xticklabels=['Not Default', 'Default'], yticklabels=['Not Default', 'Default']) plt.ylabel('Actual') plt.xlabel('Predicted')",
"see the most important features # - We can see that the most",
"and CLNO # In[22]: tree_estimator = DecisionTreeClassifier(class_weight={0:0.20, 1:0.80}, random_state=1) parameters = { 'max_depth':np.arange(2,7),",
"the original single tree # - Lets fix overfitting # In[30]: forest_estimator_tuned =",
"a loan. # - Years at job is also a driver of a",
"sklearn.linear_model import LogisticRegression from sklearn.neighbors import KNeighborsClassifier from sklearn import metrics from sklearn.metrics",
"project to see the most important features # - We can see that",
"reduce harmful error # In[25]: important = tree_estimator.feature_importances_ columns=independent.columns importance_df=pd.DataFrame(important,index=columns,columns=['Importance']).sort_values(by='Importance',ascending=False) plt.figure(figsize=(13,13)) sns.barplot(importance_df.Importance,importance_df.index) plt.show()",
"to get the best results. # - The first one I made was",
"In[53]: print(forest_estimator_tuned.predict(x_test.iloc[107].to_numpy().reshape(1,-1))) # This predicts for one row, 0 means approved, 1 means",
"coding: utf-8 # # Loan Classification Project # In[1]: # Libraries we need",
"when looking for candidates to give loans to. # # I will now",
"y_predict_training_forest) # - A perfect classification # - This implies overfitting # In[29]:",
"as good as random forest but it is transparent as it lets us",
"A perfect classification # - This implies overfitting # In[29]: y_predict_test_forest = forest_estimator.predict(x_test)",
"dropped # In[6]: df.describe() # In[7]: plt.hist(df['BAD'], bins=3) plt.show() # In[8]: df['LOAN'].plot(kind='density') plt.show()",
"- Lets fix overfitting # In[30]: forest_estimator_tuned = RandomForestClassifier(class_weight={0:0.20,1:0.80}, random_state=1) parameters_rf = {",
"pay back a loan. # - Those are some warning signs/good signs that",
"to. # # I will now apply SHAP to look more into this",
"driver of a loans outcome. A large number of years at a job",
"clf to the best combination of parameters forest_estimator_tuned = grid_obj.best_estimator_ # In[31]: forest_estimator_tuned.fit(x_train,",
"Reason and Bad are binary variables # - Nothing needs to be dropped",
"cannot make their credit card payments will have a hard time paying back",
"from sklearn.preprocessing import StandardScaler from sklearn.model_selection import train_test_split from sklearn.discriminant_analysis import LinearDiscriminantAnalysis from",
"DecisionTreeClassifier(class_weight={0:0.20, 1:0.80}, random_state=1) # In[18]: dtree.fit(x_train, y_train) # In[19]: dependent_performance_dt = dtree.predict(x_train) metrics_score(y_train,",
"score = metrics.make_scorer(recall_score, pos_label=1) gridCV= GridSearchCV(tree_estimator, parameters, scoring=score,cv=10) gridCV = gridCV.fit(x_train, y_train) tree_estimator",
"this to the company # ### Conclusion # - I made many models",
"are DEBTINC, CLAGE and CLNO # In[22]: tree_estimator = DecisionTreeClassifier(class_weight={0:0.20, 1:0.80}, random_state=1) parameters",
"plt.figure(figsize=(30,20)) tree.plot_tree(dtree,max_depth=4,feature_names=features,filled=True,fontsize=12,node_ids=True,class_names=True) plt.show() # - A visualization is one of the advantages that",
"will now apply SHAP to look more into this model. # In[34]: get_ipython().system('pip",
"df # In[14]: one_hot_encoding2 = pd.get_dummies(df['JOB']) df = df.drop('JOB', axis=1) df = df.join(one_hot_encoding2)",
"# In[3]: df.head() # In[4]: df.info() # In[5]: df.nunique() # - Above we",
"to improve even more I created a decision tree model, this had excellent",
"y_predict_train_forest_tuned = forest_estimator_tuned.predict(x_train) metrics_score(y_train, y_predict_train_forest_tuned) # In[33]: y_predict_test_forest_tuned = forest_estimator_tuned.predict(x_test) metrics_score(y_test, y_predict_test_forest_tuned) #",
"In[1]: # Libraries we need import pandas as pd import numpy as np",
"# In[34]: get_ipython().system('pip install shap') import shap # In[35]: shap.initjs() # In[36]: explain",
"sns from sklearn.preprocessing import StandardScaler from sklearn.model_selection import train_test_split from sklearn.discriminant_analysis import LinearDiscriminantAnalysis",
"- The performance is a lot better than the original single tree #",
"grid_obj.best_estimator_ # In[31]: forest_estimator_tuned.fit(x_train, y_train) # In[32]: y_predict_train_forest_tuned = forest_estimator_tuned.predict(x_train) metrics_score(y_train, y_predict_train_forest_tuned) #",
"created a decision tree model, this had excellent performance once we created a",
"forest_estimator_tuned.predict(x_train) metrics_score(y_train, y_predict_train_forest_tuned) # In[33]: y_predict_test_forest_tuned = forest_estimator_tuned.predict(x_test) metrics_score(y_test, y_predict_test_forest_tuned) # - We",
"Classification Project # In[1]: # Libraries we need import pandas as pd import",
"are binary variables # - Nothing needs to be dropped # In[6]: df.describe()",
"version which removed overfitting. # ### Recommendations # - The biggest thing that",
"# Libraries we need import pandas as pd import numpy as np import",
"combination of parameters forest_estimator_tuned = grid_obj.best_estimator_ # In[31]: forest_estimator_tuned.fit(x_train, y_train) # In[32]: y_predict_train_forest_tuned",
"In[18]: dtree.fit(x_train, y_train) # In[19]: dependent_performance_dt = dtree.predict(x_train) metrics_score(y_train, dependent_performance_dt) # - The",
"Recommendations # - The biggest thing that effects defaulting on a loan is",
"can see that Reason and Bad are binary variables # - Nothing needs",
"} score = metrics.make_scorer(recall_score, pos_label=1) gridCV= GridSearchCV(tree_estimator, parameters, scoring=score,cv=10) gridCV = gridCV.fit(x_train, y_train)",
"to see the most important features # - We can see that the",
"# In[18]: dtree.fit(x_train, y_train) # In[19]: dependent_performance_dt = dtree.predict(x_train) metrics_score(y_train, dependent_performance_dt) # -",
"= tree_estimator.feature_importances_ columns=independent.columns importance_df=pd.DataFrame(important,index=columns,columns=['Importance']).sort_values(by='Importance',ascending=False) plt.figure(figsize=(13,13)) sns.barplot(importance_df.Importance,importance_df.index) plt.show() # In[26]: features = list(independent.columns) plt.figure(figsize=(30,20))",
"correlation = df.corr() sns.heatmap(correlation) plt.show() # In[11]: df['BAD'].value_counts(normalize=True) # In[12]: df.fillna(df.mean(), inplace=True) #",
"dependent = df['BAD'] independent = df.drop(['BAD'], axis=1) x_train, x_test, y_train, y_test = train_test_split(independent,",
"Selfnote: do importance features next # In[21]: important = dtree.feature_importances_ columns = independent.columns",
"effects defaulting on a loan is the number of delinquent credit lines. This",
"lot of debt and a lower income they may have a harder time",
"submit this to the company # ### Conclusion # - I made many",
"In[3]: df.head() # In[4]: df.info() # In[5]: df.nunique() # - Above we can",
"Something else that effects defaulting on a loan is the number of delinquent",
"forest_estimator_tuned.fit(x_train, y_train) # In[32]: y_predict_train_forest_tuned = forest_estimator_tuned.predict(x_train) metrics_score(y_train, y_predict_train_forest_tuned) # In[33]: y_predict_test_forest_tuned =",
"- The above is perfect because we are using the train values, not",
"dependent, test_size=0.3, random_state=1) # In[16]: def metrics_score(actual, predicted): print(classification_report(actual, predicted)) cm = confusion_matrix(actual,",
"the client ot show the thought process # In[27]: forest_estimator = RandomForestClassifier(class_weight={0:0.20, 1:0.80},",
"I made many models to get the best results. # - The first",
"else that effects defaulting on a loan is the number of delinquent credit",
"# In[17]: dtree = DecisionTreeClassifier(class_weight={0:0.20, 1:0.80}, random_state=1) # In[18]: dtree.fit(x_train, y_train) # In[19]:",
"defaulting on a loan is the debt to income ratio. If someone has",
"now apply SHAP to look more into this model. # In[34]: get_ipython().system('pip install",
"- Lets test on test data # In[20]: dependent_test_performance_dt = dtree.predict(x_test) metrics_score(y_test,dependent_test_performance_dt) #",
"binary variables # - Nothing needs to be dropped # In[6]: df.describe() #",
"tree, this is not as good as random forest but it is transparent",
"- Above we can see that Reason and Bad are binary variables #",
"'entropy'], 'min_samples_leaf':[5,10,20,25] } score = metrics.make_scorer(recall_score, pos_label=1) gridCV= GridSearchCV(tree_estimator, parameters, scoring=score,cv=10) gridCV =",
"first one had decent performance. # - To improve the performance of this",
"look more into this model. # In[34]: get_ipython().system('pip install shap') import shap #",
"created a second version which removed overfitting. # ### Recommendations # - The",
"tree_estimator.predict(x_test) metrics_score(y_test, dependent_test_performance_dt) # - Although the performance is slightly worse, we still",
"# In[37]: type(shap_vals) # In[38]: shap.plots.bar(shap_vals[:, :, 0]) # In[39]: shap.plots.heatmap(shap_vals[:, :, 0])",
"test on test data # In[20]: dependent_test_performance_dt = dtree.predict(x_test) metrics_score(y_test,dependent_test_performance_dt) # - As",
"train values, not the test # - Lets test on test data #",
"grid_obj.fit(x_train, y_train) # Set the clf to the best combination of parameters forest_estimator_tuned",
"- DEROG, or a history of delinquent payments is also a warning sign",
"increased the less harmful error but decreased the harmful error # In[24]: dependent_test_performance_dt",
"harmful error # In[24]: dependent_test_performance_dt = tree_estimator.predict(x_test) metrics_score(y_test, dependent_test_performance_dt) # - Although the",
"can show this to the client ot show the thought process # In[27]:",
"score = metrics.make_scorer(recall_score, pos_label=1) # Run the grid search grid_obj = GridSearchCV(forest_estimator_tuned, parameters_rf,",
"# In[11]: df['BAD'].value_counts(normalize=True) # In[12]: df.fillna(df.mean(), inplace=True) # In[13]: one_hot_encoding = pd.get_dummies(df['REASON']) df",
"than the original single tree # - Lets fix overfitting # In[30]: forest_estimator_tuned",
"1:0.80}, random_state=1) forest_estimator.fit(x_train, y_train) # In[28]: y_predict_training_forest = forest_estimator.predict(x_train) metrics_score(y_train, y_predict_training_forest) # -",
"to the client ot show the thought process # In[27]: forest_estimator = RandomForestClassifier(class_weight={0:0.20,",
"index=columns, columns=['Importance']).sort_values(by='Importance', ascending=False) plt.figure(figsize=(13,13)) sns.barplot(important_items_df.Importance, important_items_df.index) plt.show() # - I followed this from",
"tree model, this had excellent performance once we created a second version which",
"warning signs/good signs that should be looked out for when looking for candidates",
"1:0.80}, random_state=1) parameters = { 'max_depth':np.arange(2,7), 'criterion':['gini', 'entropy'], 'min_samples_leaf':[5,10,20,25] } score = metrics.make_scorer(recall_score,",
"to pay back a loan. # - Those are some warning signs/good signs",
"RandomForestClassifier(class_weight={0:0.20, 1:0.80}, random_state=1) forest_estimator.fit(x_train, y_train) # In[28]: y_predict_training_forest = forest_estimator.predict(x_train) metrics_score(y_train, y_predict_training_forest) #",
"better than the original single tree # - Lets fix overfitting # In[30]:",
"confusion_matrix(actual, predicted) plt.figure(figsize=(8,5)) sns.heatmap(cm, annot=True, fmt='.2f', xticklabels=['Not Default', 'Default'], yticklabels=['Not Default', 'Default']) plt.ylabel('Actual')",
"plt.figure(figsize=(13,13)) sns.barplot(important_items_df.Importance, important_items_df.index) plt.show() # - I followed this from a previous project",
"y_predict_test_forest_tuned = forest_estimator_tuned.predict(x_test) metrics_score(y_test, y_predict_test_forest_tuned) # - We now have very good performance",
"that effects defaulting on a loan is the debt to income ratio. If",
"import train_test_split from sklearn.discriminant_analysis import LinearDiscriminantAnalysis from sklearn.discriminant_analysis import QuadraticDiscriminantAnalysis from sklearn.linear_model import",
"credit card payments will have a hard time paying back a loan. #",
"able to pay back a loan. # - Those are some warning signs/good",
"get_ipython().system('pip install shap') import shap # In[35]: shap.initjs() # In[36]: explain = shap.TreeExplainer(forest_estimator_tuned)",
"we tried to tune the model, this reduced the harmful error. # -",
"excellent performance once we created a second version which removed overfitting. # ###",
"### Conclusion # - I made many models to get the best results.",
"pd.DataFrame(important, index=columns, columns=['Importance']).sort_values(by='Importance', ascending=False) plt.figure(figsize=(13,13)) sns.barplot(important_items_df.Importance, important_items_df.index) plt.show() # - I followed this",
"pos_label=1) gridCV= GridSearchCV(tree_estimator, parameters, scoring=score,cv=10) gridCV = gridCV.fit(x_train, y_train) tree_estimator = gridCV.best_estimator_ tree_estimator.fit(x_train,",
"independent = df.drop(['BAD'], axis=1) x_train, x_test, y_train, y_test = train_test_split(independent, dependent, test_size=0.3, random_state=1)",
"scoring=score, cv=5) grid_obj = grid_obj.fit(x_train, y_train) # Set the clf to the best",
"have a harder time paying back a loan. # - Something else that",
"= pd.DataFrame(important, index=columns, columns=['Importance']).sort_values(by='Importance', ascending=False) plt.figure(figsize=(13,13)) sns.barplot(important_items_df.Importance, important_items_df.index) plt.show() # - I followed",
"overfitting # In[29]: y_predict_test_forest = forest_estimator.predict(x_test) metrics_score(y_test, y_predict_test_forest) # - The performance is",
"plt.xlabel('Predicted') plt.show() # In[17]: dtree = DecisionTreeClassifier(class_weight={0:0.20, 1:0.80}, random_state=1) # In[18]: dtree.fit(x_train, y_train)",
"# Loan Classification Project # In[1]: # Libraries we need import pandas as",
"In[26]: features = list(independent.columns) plt.figure(figsize=(30,20)) tree.plot_tree(dtree,max_depth=4,feature_names=features,filled=True,fontsize=12,node_ids=True,class_names=True) plt.show() # - A visualization is one",
"is a lot better than the original single tree # - Lets fix",
"visualize it. This first one had decent performance. # - To improve the",
"Libraries we need import pandas as pd import numpy as np import matplotlib.pyplot",
"1:0.80}, random_state=1) # In[18]: dtree.fit(x_train, y_train) # In[19]: dependent_performance_dt = dtree.predict(x_train) metrics_score(y_train, dependent_performance_dt)",
"'Default'], yticklabels=['Not Default', 'Default']) plt.ylabel('Actual') plt.xlabel('Predicted') plt.show() # In[17]: dtree = DecisionTreeClassifier(class_weight={0:0.20, 1:0.80},",
":, 0]) # In[39]: shap.plots.heatmap(shap_vals[:, :, 0]) # In[40]: shap.summary_plot(shap_vals[:, :, 0], x_train)",
"# In[12]: df.fillna(df.mean(), inplace=True) # In[13]: one_hot_encoding = pd.get_dummies(df['REASON']) df = df.drop('REASON', axis=1)",
"yticklabels=['Not Default', 'Default']) plt.ylabel('Actual') plt.xlabel('Predicted') plt.show() # In[17]: dtree = DecisionTreeClassifier(class_weight={0:0.20, 1:0.80}, random_state=1)",
"sns.heatmap(correlation) plt.show() # In[11]: df['BAD'].value_counts(normalize=True) # In[12]: df.fillna(df.mean(), inplace=True) # In[13]: one_hot_encoding =",
"decent performance from this model, lets see if we can do better #",
"best results. # - The first one I made was a decision tree,",
"# In[30]: forest_estimator_tuned = RandomForestClassifier(class_weight={0:0.20,1:0.80}, random_state=1) parameters_rf = { \"n_estimators\": [100,250,500], \"min_samples_leaf\": np.arange(1,",
"pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn",
"but decreased the harmful error # In[24]: dependent_test_performance_dt = tree_estimator.predict(x_test) metrics_score(y_test, dependent_test_performance_dt) #",
"precision_recall_curve,recall_score from sklearn import tree from sklearn.tree import DecisionTreeClassifier from sklearn.ensemble import BaggingClassifier",
"In[7]: plt.hist(df['BAD'], bins=3) plt.show() # In[8]: df['LOAN'].plot(kind='density') plt.show() # In[9]: plt.pie(df['REASON'].value_counts(), labels=['DebtCon', 'HomeImp'],",
"In[20]: dependent_test_performance_dt = dtree.predict(x_test) metrics_score(y_test,dependent_test_performance_dt) # - As we can see, we got",
"GridSearchCV(tree_estimator, parameters, scoring=score,cv=10) gridCV = gridCV.fit(x_train, y_train) tree_estimator = gridCV.best_estimator_ tree_estimator.fit(x_train, y_train) #",
"give loans to. # # I will now apply SHAP to look more",
"In[35]: shap.initjs() # In[36]: explain = shap.TreeExplainer(forest_estimator_tuned) shap_vals = explain(x_train) # In[37]: type(shap_vals)",
"we need import pandas as pd import numpy as np import matplotlib.pyplot as",
"the performance of this we tried to tune the model, this reduced the",
"financial stability. # - DEROG, or a history of delinquent payments is also",
"this from a previous project to see the most important features # -",
"it is transparent as it lets us visualize it. This first one had",
"performance of this we tried to tune the model, this reduced the harmful",
"shap.plots.heatmap(shap_vals[:, :, 0]) # In[40]: shap.summary_plot(shap_vals[:, :, 0], x_train) # In[53]: print(forest_estimator_tuned.predict(x_test.iloc[107].to_numpy().reshape(1,-1))) #",
"plt.figure(figsize=(8,5)) sns.heatmap(cm, annot=True, fmt='.2f', xticklabels=['Not Default', 'Default'], yticklabels=['Not Default', 'Default']) plt.ylabel('Actual') plt.xlabel('Predicted') plt.show()",
"df = df.join(one_hot_encoding) df # In[14]: one_hot_encoding2 = pd.get_dummies(df['JOB']) df = df.drop('JOB', axis=1)",
"random_state=1) parameters = { 'max_depth':np.arange(2,7), 'criterion':['gini', 'entropy'], 'min_samples_leaf':[5,10,20,25] } score = metrics.make_scorer(recall_score, pos_label=1)",
"as random forest but it is transparent as it lets us visualize it.",
"Project # In[1]: # Libraries we need import pandas as pd import numpy",
"from sklearn import tree from sklearn.tree import DecisionTreeClassifier from sklearn.ensemble import BaggingClassifier from",
"tree_estimator.predict(x_train) metrics_score(y_train, dependent_performance_dt) # - We increased the less harmful error but decreased",
"- We can submit this to the company # ### Conclusion # -",
"- I made many models to get the best results. # - The",
"number of delinquent credit lines. This means that someone who cannot make their",
"0]) # In[40]: shap.summary_plot(shap_vals[:, :, 0], x_train) # In[53]: print(forest_estimator_tuned.predict(x_test.iloc[107].to_numpy().reshape(1,-1))) # This predicts",
"sklearn.discriminant_analysis import QuadraticDiscriminantAnalysis from sklearn.linear_model import LogisticRegression from sklearn.neighbors import KNeighborsClassifier from sklearn",
"[100,250,500], \"min_samples_leaf\": np.arange(1, 4,1), \"max_features\": [0.7,0.9,'auto'], } score = metrics.make_scorer(recall_score, pos_label=1) # Run",
"import BaggingClassifier from sklearn.ensemble import RandomForestClassifier from sklearn.model_selection import GridSearchCV # In[2]: df",
"that effects defaulting on a loan is the number of delinquent credit lines.",
"this model, lets see if we can do better # - Selfnote: do",
"= df.drop(['BAD'], axis=1) x_train, x_test, y_train, y_test = train_test_split(independent, dependent, test_size=0.3, random_state=1) #",
"the most important features are DEBTINC, CLAGE and CLNO # In[22]: tree_estimator =",
"explain = shap.TreeExplainer(forest_estimator_tuned) shap_vals = explain(x_train) # In[37]: type(shap_vals) # In[38]: shap.plots.bar(shap_vals[:, :,",
"y_train) # In[23]: dependent_performance_dt = tree_estimator.predict(x_train) metrics_score(y_train, dependent_performance_dt) # - We increased the",
"overfitting # In[30]: forest_estimator_tuned = RandomForestClassifier(class_weight={0:0.20,1:0.80}, random_state=1) parameters_rf = { \"n_estimators\": [100,250,500], \"min_samples_leaf\":",
"- Those are some warning signs/good signs that should be looked out for",
"worse, we still reduce harmful error # In[25]: important = tree_estimator.feature_importances_ columns=independent.columns importance_df=pd.DataFrame(important,index=columns,columns=['Importance']).sort_values(by='Importance',ascending=False)",
"df['REASON'].value_counts() # In[10]: correlation = df.corr() sns.heatmap(correlation) plt.show() # In[11]: df['BAD'].value_counts(normalize=True) # In[12]:",
"= grid_obj.fit(x_train, y_train) # Set the clf to the best combination of parameters",
"In[15]: dependent = df['BAD'] independent = df.drop(['BAD'], axis=1) x_train, x_test, y_train, y_test =",
"As we can see, we got decent performance from this model, lets see",
"x_train) # In[53]: print(forest_estimator_tuned.predict(x_test.iloc[107].to_numpy().reshape(1,-1))) # This predicts for one row, 0 means approved,",
"# In[22]: tree_estimator = DecisionTreeClassifier(class_weight={0:0.20, 1:0.80}, random_state=1) parameters = { 'max_depth':np.arange(2,7), 'criterion':['gini', 'entropy'],",
"a decision tree, this is not as good as random forest but it",
"independent.columns important_items_df = pd.DataFrame(important, index=columns, columns=['Importance']).sort_values(by='Importance', ascending=False) plt.figure(figsize=(13,13)) sns.barplot(important_items_df.Importance, important_items_df.index) plt.show() # -",
"gridCV= GridSearchCV(tree_estimator, parameters, scoring=score,cv=10) gridCV = gridCV.fit(x_train, y_train) tree_estimator = gridCV.best_estimator_ tree_estimator.fit(x_train, y_train)",
"one_hot_encoding2 = pd.get_dummies(df['JOB']) df = df.drop('JOB', axis=1) df = df.join(one_hot_encoding2) df # In[15]:",
"# - The biggest thing that effects defaulting on a loan is the",
"see that Reason and Bad are binary variables # - Nothing needs to",
"a previous project to see the most important features # - We can",
"forest_estimator.predict(x_train) metrics_score(y_train, y_predict_training_forest) # - A perfect classification # - This implies overfitting",
"is also a driver of a loans outcome. A large number of years",
"# In[29]: y_predict_test_forest = forest_estimator.predict(x_test) metrics_score(y_test, y_predict_test_forest) # - The performance is a",
"- We now have very good performance # - We can submit this",
"This first one had decent performance. # - To improve the performance of",
"original single tree # - Lets fix overfitting # In[30]: forest_estimator_tuned = RandomForestClassifier(class_weight={0:0.20,1:0.80},",
"dtree = DecisionTreeClassifier(class_weight={0:0.20, 1:0.80}, random_state=1) # In[18]: dtree.fit(x_train, y_train) # In[19]: dependent_performance_dt =",
"now have very good performance # - We can submit this to the",
"lower income they may have a harder time paying back a loan. #",
"sklearn.tree import DecisionTreeClassifier from sklearn.ensemble import BaggingClassifier from sklearn.ensemble import RandomForestClassifier from sklearn.model_selection",
"import RandomForestClassifier from sklearn.model_selection import GridSearchCV # In[2]: df = pd.read_csv(\"Dataset.csv\") # In[3]:",
"axis=1) x_train, x_test, y_train, y_test = train_test_split(independent, dependent, test_size=0.3, random_state=1) # In[16]: def",
"do better # - Selfnote: do importance features next # In[21]: important =",
"ascending=False) plt.figure(figsize=(13,13)) sns.barplot(important_items_df.Importance, important_items_df.index) plt.show() # - I followed this from a previous",
"- Years at job is also a driver of a loans outcome. A",
"# - DEROG, or a history of delinquent payments is also a warning",
"# In[4]: df.info() # In[5]: df.nunique() # - Above we can see that",
"of a loans outcome. A large number of years at a job could",
"important = dtree.feature_importances_ columns = independent.columns important_items_df = pd.DataFrame(important, index=columns, columns=['Importance']).sort_values(by='Importance', ascending=False) plt.figure(figsize=(13,13))",
"better # - Selfnote: do importance features next # In[21]: important = dtree.feature_importances_",
"visualization is one of the advantages that dtrees offer, we can show this",
"# - Above we can see that Reason and Bad are binary variables",
"Conclusion # - I made many models to get the best results. #",
"random_state=1) parameters_rf = { \"n_estimators\": [100,250,500], \"min_samples_leaf\": np.arange(1, 4,1), \"max_features\": [0.7,0.9,'auto'], } score",
"CLNO # In[22]: tree_estimator = DecisionTreeClassifier(class_weight={0:0.20, 1:0.80}, random_state=1) parameters = { 'max_depth':np.arange(2,7), 'criterion':['gini',",
"thought process # In[27]: forest_estimator = RandomForestClassifier(class_weight={0:0.20, 1:0.80}, random_state=1) forest_estimator.fit(x_train, y_train) # In[28]:",
"sklearn.metrics import confusion_matrix, classification_report, precision_recall_curve,recall_score from sklearn import tree from sklearn.tree import DecisionTreeClassifier",
"# Run the grid search grid_obj = GridSearchCV(forest_estimator_tuned, parameters_rf, scoring=score, cv=5) grid_obj =",
"a driver of a loans outcome. A large number of years at a",
"np.arange(1, 4,1), \"max_features\": [0.7,0.9,'auto'], } score = metrics.make_scorer(recall_score, pos_label=1) # Run the grid",
"= DecisionTreeClassifier(class_weight={0:0.20, 1:0.80}, random_state=1) parameters = { 'max_depth':np.arange(2,7), 'criterion':['gini', 'entropy'], 'min_samples_leaf':[5,10,20,25] } score",
"will have a hard time paying back a loan. # - Years at",
"perfect because we are using the train values, not the test # -",
"= shap.TreeExplainer(forest_estimator_tuned) shap_vals = explain(x_train) # In[37]: type(shap_vals) # In[38]: shap.plots.bar(shap_vals[:, :, 0])",
"grid search grid_obj = GridSearchCV(forest_estimator_tuned, parameters_rf, scoring=score, cv=5) grid_obj = grid_obj.fit(x_train, y_train) #",
"metrics_score(y_train, dependent_performance_dt) # - We increased the less harmful error but decreased the",
"# - We increased the less harmful error but decreased the harmful error",
"In[40]: shap.summary_plot(shap_vals[:, :, 0], x_train) # In[53]: print(forest_estimator_tuned.predict(x_test.iloc[107].to_numpy().reshape(1,-1))) # This predicts for one",
"df['LOAN'].plot(kind='density') plt.show() # In[9]: plt.pie(df['REASON'].value_counts(), labels=['DebtCon', 'HomeImp'], autopct='%.1f') plt.show() df['REASON'].value_counts() # In[10]: correlation",
"The above is perfect because we are using the train values, not the",
"still reduce harmful error # In[25]: important = tree_estimator.feature_importances_ columns=independent.columns importance_df=pd.DataFrame(important,index=columns,columns=['Importance']).sort_values(by='Importance',ascending=False) plt.figure(figsize=(13,13)) sns.barplot(importance_df.Importance,importance_df.index)",
"looking for candidates to give loans to. # # I will now apply",
"= RandomForestClassifier(class_weight={0:0.20, 1:0.80}, random_state=1) forest_estimator.fit(x_train, y_train) # In[28]: y_predict_training_forest = forest_estimator.predict(x_train) metrics_score(y_train, y_predict_training_forest)",
"- Then to improve even more I created a decision tree model, this",
"of debt and a lower income they may have a harder time paying",
"DEROG, or a history of delinquent payments is also a warning sign of",
"from sklearn.model_selection import train_test_split from sklearn.discriminant_analysis import LinearDiscriminantAnalysis from sklearn.discriminant_analysis import QuadraticDiscriminantAnalysis from",
"To improve the performance of this we tried to tune the model, this",
"- We can see that the most important features are DEBTINC, CLAGE and",
"need import pandas as pd import numpy as np import matplotlib.pyplot as plt",
"from sklearn.ensemble import BaggingClassifier from sklearn.ensemble import RandomForestClassifier from sklearn.model_selection import GridSearchCV #",
"df.drop(['BAD'], axis=1) x_train, x_test, y_train, y_test = train_test_split(independent, dependent, test_size=0.3, random_state=1) # In[16]:",
"from sklearn.linear_model import LogisticRegression from sklearn.neighbors import KNeighborsClassifier from sklearn import metrics from",
"followed this from a previous project to see the most important features #",
"this to the client ot show the thought process # In[27]: forest_estimator =",
"StandardScaler from sklearn.model_selection import train_test_split from sklearn.discriminant_analysis import LinearDiscriminantAnalysis from sklearn.discriminant_analysis import QuadraticDiscriminantAnalysis",
"the less harmful error but decreased the harmful error # In[24]: dependent_test_performance_dt =",
"is not as good as random forest but it is transparent as it",
"In[36]: explain = shap.TreeExplainer(forest_estimator_tuned) shap_vals = explain(x_train) # In[37]: type(shap_vals) # In[38]: shap.plots.bar(shap_vals[:,",
"had excellent performance once we created a second version which removed overfitting. #",
"# In[21]: important = dtree.feature_importances_ columns = independent.columns important_items_df = pd.DataFrame(important, index=columns, columns=['Importance']).sort_values(by='Importance',",
"plt.show() # In[26]: features = list(independent.columns) plt.figure(figsize=(30,20)) tree.plot_tree(dtree,max_depth=4,feature_names=features,filled=True,fontsize=12,node_ids=True,class_names=True) plt.show() # - A visualization",
"columns=independent.columns importance_df=pd.DataFrame(important,index=columns,columns=['Importance']).sort_values(by='Importance',ascending=False) plt.figure(figsize=(13,13)) sns.barplot(importance_df.Importance,importance_df.index) plt.show() # In[26]: features = list(independent.columns) plt.figure(figsize=(30,20)) tree.plot_tree(dtree,max_depth=4,feature_names=features,filled=True,fontsize=12,node_ids=True,class_names=True) plt.show()",
"# In[27]: forest_estimator = RandomForestClassifier(class_weight={0:0.20, 1:0.80}, random_state=1) forest_estimator.fit(x_train, y_train) # In[28]: y_predict_training_forest =",
"history of delinquent payments is also a warning sign of not being able",
"also a driver of a loans outcome. A large number of years at",
"# - Lets fix overfitting # In[30]: forest_estimator_tuned = RandomForestClassifier(class_weight={0:0.20,1:0.80}, random_state=1) parameters_rf =",
"decision tree, this is not as good as random forest but it is",
"We can see that the most important features are DEBTINC, CLAGE and CLNO",
"forest_estimator.fit(x_train, y_train) # In[28]: y_predict_training_forest = forest_estimator.predict(x_train) metrics_score(y_train, y_predict_training_forest) # - A perfect",
"= confusion_matrix(actual, predicted) plt.figure(figsize=(8,5)) sns.heatmap(cm, annot=True, fmt='.2f', xticklabels=['Not Default', 'Default'], yticklabels=['Not Default', 'Default'])",
"a second version which removed overfitting. # ### Recommendations # - The biggest",
"not being able to pay back a loan. # - Those are some",
"candidates to give loans to. # # I will now apply SHAP to",
"the model, this reduced the harmful error. # - Then to improve even",
"install shap') import shap # In[35]: shap.initjs() # In[36]: explain = shap.TreeExplainer(forest_estimator_tuned) shap_vals",
"model, this reduced the harmful error. # - Then to improve even more",
"= { 'max_depth':np.arange(2,7), 'criterion':['gini', 'entropy'], 'min_samples_leaf':[5,10,20,25] } score = metrics.make_scorer(recall_score, pos_label=1) gridCV= GridSearchCV(tree_estimator,",
"the train values, not the test # - Lets test on test data",
"as np import matplotlib.pyplot as plt import seaborn as sns from sklearn.preprocessing import",
"df # In[15]: dependent = df['BAD'] independent = df.drop(['BAD'], axis=1) x_train, x_test, y_train,",
"warning sign of not being able to pay back a loan. # -",
"Those are some warning signs/good signs that should be looked out for when",
"the advantages that dtrees offer, we can show this to the client ot",
"metrics_score(y_test,dependent_test_performance_dt) # - As we can see, we got decent performance from this",
"DEBTINC, CLAGE and CLNO # In[22]: tree_estimator = DecisionTreeClassifier(class_weight={0:0.20, 1:0.80}, random_state=1) parameters =",
"harmful error. # - Then to improve even more I created a decision",
"inplace=True) # In[13]: one_hot_encoding = pd.get_dummies(df['REASON']) df = df.drop('REASON', axis=1) df = df.join(one_hot_encoding)",
"= RandomForestClassifier(class_weight={0:0.20,1:0.80}, random_state=1) parameters_rf = { \"n_estimators\": [100,250,500], \"min_samples_leaf\": np.arange(1, 4,1), \"max_features\": [0.7,0.9,'auto'],",
"list(independent.columns) plt.figure(figsize=(30,20)) tree.plot_tree(dtree,max_depth=4,feature_names=features,filled=True,fontsize=12,node_ids=True,class_names=True) plt.show() # - A visualization is one of the advantages",
"import KNeighborsClassifier from sklearn import metrics from sklearn.metrics import confusion_matrix, classification_report, precision_recall_curve,recall_score from",
"# In[6]: df.describe() # In[7]: plt.hist(df['BAD'], bins=3) plt.show() # In[8]: df['LOAN'].plot(kind='density') plt.show() #",
"def metrics_score(actual, predicted): print(classification_report(actual, predicted)) cm = confusion_matrix(actual, predicted) plt.figure(figsize=(8,5)) sns.heatmap(cm, annot=True, fmt='.2f',",
"credit lines. This means that someone who cannot make their credit card payments",
"we can show this to the client ot show the thought process #",
"x_train, x_test, y_train, y_test = train_test_split(independent, dependent, test_size=0.3, random_state=1) # In[16]: def metrics_score(actual,",
"# In[38]: shap.plots.bar(shap_vals[:, :, 0]) # In[39]: shap.plots.heatmap(shap_vals[:, :, 0]) # In[40]: shap.summary_plot(shap_vals[:,",
"shap.initjs() # In[36]: explain = shap.TreeExplainer(forest_estimator_tuned) shap_vals = explain(x_train) # In[37]: type(shap_vals) #",
"In[23]: dependent_performance_dt = tree_estimator.predict(x_train) metrics_score(y_train, dependent_performance_dt) # - We increased the less harmful",
"# In[13]: one_hot_encoding = pd.get_dummies(df['REASON']) df = df.drop('REASON', axis=1) df = df.join(one_hot_encoding) df",
"# In[33]: y_predict_test_forest_tuned = forest_estimator_tuned.predict(x_test) metrics_score(y_test, y_predict_test_forest_tuned) # - We now have very",
"0], x_train) # In[53]: print(forest_estimator_tuned.predict(x_test.iloc[107].to_numpy().reshape(1,-1))) # This predicts for one row, 0 means",
"plt.show() # In[8]: df['LOAN'].plot(kind='density') plt.show() # In[9]: plt.pie(df['REASON'].value_counts(), labels=['DebtCon', 'HomeImp'], autopct='%.1f') plt.show() df['REASON'].value_counts()",
"on test data # In[20]: dependent_test_performance_dt = dtree.predict(x_test) metrics_score(y_test,dependent_test_performance_dt) # - As we",
"plt.show() # In[11]: df['BAD'].value_counts(normalize=True) # In[12]: df.fillna(df.mean(), inplace=True) # In[13]: one_hot_encoding = pd.get_dummies(df['REASON'])",
"to income ratio. If someone has a lot of debt and a lower",
"plt.show() df['REASON'].value_counts() # In[10]: correlation = df.corr() sns.heatmap(correlation) plt.show() # In[11]: df['BAD'].value_counts(normalize=True) #",
"cv=5) grid_obj = grid_obj.fit(x_train, y_train) # Set the clf to the best combination",
"get the best results. # - The first one I made was a",
"forest_estimator_tuned = RandomForestClassifier(class_weight={0:0.20,1:0.80}, random_state=1) parameters_rf = { \"n_estimators\": [100,250,500], \"min_samples_leaf\": np.arange(1, 4,1), \"max_features\":",
"even more I created a decision tree model, this had excellent performance once",
"dtree.predict(x_train) metrics_score(y_train, dependent_performance_dt) # - The above is perfect because we are using",
"# - A perfect classification # - This implies overfitting # In[29]: y_predict_test_forest",
"have very good performance # - We can submit this to the company",
"from sklearn import metrics from sklearn.metrics import confusion_matrix, classification_report, precision_recall_curve,recall_score from sklearn import",
"- To improve the performance of this we tried to tune the model,",
"print(classification_report(actual, predicted)) cm = confusion_matrix(actual, predicted) plt.figure(figsize=(8,5)) sns.heatmap(cm, annot=True, fmt='.2f', xticklabels=['Not Default', 'Default'],",
"loan. # - Years at job is also a driver of a loans",
"pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns",
"In[16]: def metrics_score(actual, predicted): print(classification_report(actual, predicted)) cm = confusion_matrix(actual, predicted) plt.figure(figsize=(8,5)) sns.heatmap(cm, annot=True,",
"columns=['Importance']).sort_values(by='Importance', ascending=False) plt.figure(figsize=(13,13)) sns.barplot(important_items_df.Importance, important_items_df.index) plt.show() # - I followed this from a",
"tree from sklearn.tree import DecisionTreeClassifier from sklearn.ensemble import BaggingClassifier from sklearn.ensemble import RandomForestClassifier",
"- The first one I made was a decision tree, this is not",
"the number of delinquent credit lines. This means that someone who cannot make",
"a warning sign of not being able to pay back a loan. #",
"import StandardScaler from sklearn.model_selection import train_test_split from sklearn.discriminant_analysis import LinearDiscriminantAnalysis from sklearn.discriminant_analysis import",
"dtree.fit(x_train, y_train) # In[19]: dependent_performance_dt = dtree.predict(x_train) metrics_score(y_train, dependent_performance_dt) # - The above",
"In[32]: y_predict_train_forest_tuned = forest_estimator_tuned.predict(x_train) metrics_score(y_train, y_predict_train_forest_tuned) # In[33]: y_predict_test_forest_tuned = forest_estimator_tuned.predict(x_test) metrics_score(y_test, y_predict_test_forest_tuned)",
"the grid search grid_obj = GridSearchCV(forest_estimator_tuned, parameters_rf, scoring=score, cv=5) grid_obj = grid_obj.fit(x_train, y_train)",
"dependent_test_performance_dt) # - Although the performance is slightly worse, we still reduce harmful",
"delinquent payments is also a warning sign of not being able to pay",
"SHAP to look more into this model. # In[34]: get_ipython().system('pip install shap') import",
"using the train values, not the test # - Lets test on test",
"LinearDiscriminantAnalysis from sklearn.discriminant_analysis import QuadraticDiscriminantAnalysis from sklearn.linear_model import LogisticRegression from sklearn.neighbors import KNeighborsClassifier",
"reduced the harmful error. # - Then to improve even more I created",
"predicted)) cm = confusion_matrix(actual, predicted) plt.figure(figsize=(8,5)) sns.heatmap(cm, annot=True, fmt='.2f', xticklabels=['Not Default', 'Default'], yticklabels=['Not",
"process # In[27]: forest_estimator = RandomForestClassifier(class_weight={0:0.20, 1:0.80}, random_state=1) forest_estimator.fit(x_train, y_train) # In[28]: y_predict_training_forest",
"# - A visualization is one of the advantages that dtrees offer, we",
"as it lets us visualize it. This first one had decent performance. #",
"on a loan is the number of delinquent credit lines. This means that",
"[0.7,0.9,'auto'], } score = metrics.make_scorer(recall_score, pos_label=1) # Run the grid search grid_obj =",
"means that someone who cannot make their credit card payments will have a",
"= dtree.feature_importances_ columns = independent.columns important_items_df = pd.DataFrame(important, index=columns, columns=['Importance']).sort_values(by='Importance', ascending=False) plt.figure(figsize=(13,13)) sns.barplot(important_items_df.Importance,",
"I created a decision tree model, this had excellent performance once we created",
"back a loan. # - Something else that effects defaulting on a loan",
"job could indicate financial stability. # - DEROG, or a history of delinquent",
"important_items_df.index) plt.show() # - I followed this from a previous project to see",
"We can submit this to the company # ### Conclusion # - I",
"we created a second version which removed overfitting. # ### Recommendations # -",
"effects defaulting on a loan is the debt to income ratio. If someone",
"this we tried to tune the model, this reduced the harmful error. #",
"is also a warning sign of not being able to pay back a",
"see if we can do better # - Selfnote: do importance features next",
"df.join(one_hot_encoding2) df # In[15]: dependent = df['BAD'] independent = df.drop(['BAD'], axis=1) x_train, x_test,",
"back a loan. # - Those are some warning signs/good signs that should",
"In[37]: type(shap_vals) # In[38]: shap.plots.bar(shap_vals[:, :, 0]) # In[39]: shap.plots.heatmap(shap_vals[:, :, 0]) #",
"random_state=1) forest_estimator.fit(x_train, y_train) # In[28]: y_predict_training_forest = forest_estimator.predict(x_train) metrics_score(y_train, y_predict_training_forest) # - A",
"but it is transparent as it lets us visualize it. This first one",
"features next # In[21]: important = dtree.feature_importances_ columns = independent.columns important_items_df = pd.DataFrame(important,",
"tree_estimator.fit(x_train, y_train) # In[23]: dependent_performance_dt = tree_estimator.predict(x_train) metrics_score(y_train, dependent_performance_dt) # - We increased",
"Set the clf to the best combination of parameters forest_estimator_tuned = grid_obj.best_estimator_ #",
"# In[24]: dependent_test_performance_dt = tree_estimator.predict(x_test) metrics_score(y_test, dependent_test_performance_dt) # - Although the performance is",
"performance. # - To improve the performance of this we tried to tune",
"= df.drop('JOB', axis=1) df = df.join(one_hot_encoding2) df # In[15]: dependent = df['BAD'] independent",
"0]) # In[39]: shap.plots.heatmap(shap_vals[:, :, 0]) # In[40]: shap.summary_plot(shap_vals[:, :, 0], x_train) #",
"overfitting. # ### Recommendations # - The biggest thing that effects defaulting on",
"df = pd.read_csv(\"Dataset.csv\") # In[3]: df.head() # In[4]: df.info() # In[5]: df.nunique() #",
"In[22]: tree_estimator = DecisionTreeClassifier(class_weight={0:0.20, 1:0.80}, random_state=1) parameters = { 'max_depth':np.arange(2,7), 'criterion':['gini', 'entropy'], 'min_samples_leaf':[5,10,20,25]",
"axis=1) df = df.join(one_hot_encoding) df # In[14]: one_hot_encoding2 = pd.get_dummies(df['JOB']) df = df.drop('JOB',",
"pos_label=1) # Run the grid search grid_obj = GridSearchCV(forest_estimator_tuned, parameters_rf, scoring=score, cv=5) grid_obj",
"gridCV.best_estimator_ tree_estimator.fit(x_train, y_train) # In[23]: dependent_performance_dt = tree_estimator.predict(x_train) metrics_score(y_train, dependent_performance_dt) # - We",
"Then to improve even more I created a decision tree model, this had",
"\"n_estimators\": [100,250,500], \"min_samples_leaf\": np.arange(1, 4,1), \"max_features\": [0.7,0.9,'auto'], } score = metrics.make_scorer(recall_score, pos_label=1) #",
"error # In[24]: dependent_test_performance_dt = tree_estimator.predict(x_test) metrics_score(y_test, dependent_test_performance_dt) # - Although the performance",
"dependent_performance_dt) # - The above is perfect because we are using the train",
"do importance features next # In[21]: important = dtree.feature_importances_ columns = independent.columns important_items_df",
"In[25]: important = tree_estimator.feature_importances_ columns=independent.columns importance_df=pd.DataFrame(important,index=columns,columns=['Importance']).sort_values(by='Importance',ascending=False) plt.figure(figsize=(13,13)) sns.barplot(importance_df.Importance,importance_df.index) plt.show() # In[26]: features =",
"see that the most important features are DEBTINC, CLAGE and CLNO # In[22]:",
"= df.join(one_hot_encoding2) df # In[15]: dependent = df['BAD'] independent = df.drop(['BAD'], axis=1) x_train,",
"from this model, lets see if we can do better # - Selfnote:",
"payments is also a warning sign of not being able to pay back",
"{ \"n_estimators\": [100,250,500], \"min_samples_leaf\": np.arange(1, 4,1), \"max_features\": [0.7,0.9,'auto'], } score = metrics.make_scorer(recall_score, pos_label=1)",
"model, lets see if we can do better # - Selfnote: do importance",
"Although the performance is slightly worse, we still reduce harmful error # In[25]:",
"removed overfitting. # ### Recommendations # - The biggest thing that effects defaulting",
"lines. This means that someone who cannot make their credit card payments will",
"sklearn import metrics from sklearn.metrics import confusion_matrix, classification_report, precision_recall_curve,recall_score from sklearn import tree",
"may have a harder time paying back a loan. # - Something else",
"tree_estimator = gridCV.best_estimator_ tree_estimator.fit(x_train, y_train) # In[23]: dependent_performance_dt = tree_estimator.predict(x_train) metrics_score(y_train, dependent_performance_dt) #",
"of not being able to pay back a loan. # - Those are",
"# In[15]: dependent = df['BAD'] independent = df.drop(['BAD'], axis=1) x_train, x_test, y_train, y_test",
"can do better # - Selfnote: do importance features next # In[21]: important",
"In[21]: important = dtree.feature_importances_ columns = independent.columns important_items_df = pd.DataFrame(important, index=columns, columns=['Importance']).sort_values(by='Importance', ascending=False)",
"In[10]: correlation = df.corr() sns.heatmap(correlation) plt.show() # In[11]: df['BAD'].value_counts(normalize=True) # In[12]: df.fillna(df.mean(), inplace=True)",
"previous project to see the most important features # - We can see",
"more I created a decision tree model, this had excellent performance once we",
"outcome. A large number of years at a job could indicate financial stability.",
"features # - We can see that the most important features are DEBTINC,",
"decreased the harmful error # In[24]: dependent_test_performance_dt = tree_estimator.predict(x_test) metrics_score(y_test, dependent_test_performance_dt) # -",
"also a warning sign of not being able to pay back a loan.",
"results. # - The first one I made was a decision tree, this",
"search grid_obj = GridSearchCV(forest_estimator_tuned, parameters_rf, scoring=score, cv=5) grid_obj = grid_obj.fit(x_train, y_train) # Set",
"one_hot_encoding = pd.get_dummies(df['REASON']) df = df.drop('REASON', axis=1) df = df.join(one_hot_encoding) df # In[14]:",
"not as good as random forest but it is transparent as it lets",
"df.join(one_hot_encoding) df # In[14]: one_hot_encoding2 = pd.get_dummies(df['JOB']) df = df.drop('JOB', axis=1) df =",
"A large number of years at a job could indicate financial stability. #",
"metrics.make_scorer(recall_score, pos_label=1) gridCV= GridSearchCV(tree_estimator, parameters, scoring=score,cv=10) gridCV = gridCV.fit(x_train, y_train) tree_estimator = gridCV.best_estimator_",
"In[28]: y_predict_training_forest = forest_estimator.predict(x_train) metrics_score(y_train, y_predict_training_forest) # - A perfect classification # -",
"import GridSearchCV # In[2]: df = pd.read_csv(\"Dataset.csv\") # In[3]: df.head() # In[4]: df.info()",
"df.drop('REASON', axis=1) df = df.join(one_hot_encoding) df # In[14]: one_hot_encoding2 = pd.get_dummies(df['JOB']) df =",
"#!/usr/bin/env python # coding: utf-8 # # Loan Classification Project # In[1]: #",
"values, not the test # - Lets test on test data # In[20]:",
"I followed this from a previous project to see the most important features",
"# In[5]: df.nunique() # - Above we can see that Reason and Bad",
"this had excellent performance once we created a second version which removed overfitting.",
"single tree # - Lets fix overfitting # In[30]: forest_estimator_tuned = RandomForestClassifier(class_weight={0:0.20,1:0.80}, random_state=1)",
"tree # - Lets fix overfitting # In[30]: forest_estimator_tuned = RandomForestClassifier(class_weight={0:0.20,1:0.80}, random_state=1) parameters_rf",
"harmful error # In[25]: important = tree_estimator.feature_importances_ columns=independent.columns importance_df=pd.DataFrame(important,index=columns,columns=['Importance']).sort_values(by='Importance',ascending=False) plt.figure(figsize=(13,13)) sns.barplot(importance_df.Importance,importance_df.index) plt.show() #",
"train_test_split from sklearn.discriminant_analysis import LinearDiscriminantAnalysis from sklearn.discriminant_analysis import QuadraticDiscriminantAnalysis from sklearn.linear_model import LogisticRegression",
"that should be looked out for when looking for candidates to give loans",
"- A visualization is one of the advantages that dtrees offer, we can",
"= GridSearchCV(forest_estimator_tuned, parameters_rf, scoring=score, cv=5) grid_obj = grid_obj.fit(x_train, y_train) # Set the clf",
"of delinquent payments is also a warning sign of not being able to",
"\"max_features\": [0.7,0.9,'auto'], } score = metrics.make_scorer(recall_score, pos_label=1) # Run the grid search grid_obj",
"= gridCV.fit(x_train, y_train) tree_estimator = gridCV.best_estimator_ tree_estimator.fit(x_train, y_train) # In[23]: dependent_performance_dt = tree_estimator.predict(x_train)",
"matplotlib.pyplot as plt import seaborn as sns from sklearn.preprocessing import StandardScaler from sklearn.model_selection",
"df.nunique() # - Above we can see that Reason and Bad are binary",
"confusion_matrix, classification_report, precision_recall_curve,recall_score from sklearn import tree from sklearn.tree import DecisionTreeClassifier from sklearn.ensemble",
"This means that someone who cannot make their credit card payments will have",
"# - The above is perfect because we are using the train values,",
"we are using the train values, not the test # - Lets test",
"biggest thing that effects defaulting on a loan is the debt to income",
"import confusion_matrix, classification_report, precision_recall_curve,recall_score from sklearn import tree from sklearn.tree import DecisionTreeClassifier from",
"dtrees offer, we can show this to the client ot show the thought",
"shap') import shap # In[35]: shap.initjs() # In[36]: explain = shap.TreeExplainer(forest_estimator_tuned) shap_vals =",
"sklearn.preprocessing import StandardScaler from sklearn.model_selection import train_test_split from sklearn.discriminant_analysis import LinearDiscriminantAnalysis from sklearn.discriminant_analysis",
"plt.show() # - A visualization is one of the advantages that dtrees offer,",
"a job could indicate financial stability. # - DEROG, or a history of",
"and Bad are binary variables # - Nothing needs to be dropped #",
"= forest_estimator_tuned.predict(x_test) metrics_score(y_test, y_predict_test_forest_tuned) # - We now have very good performance #",
"out for when looking for candidates to give loans to. # # I",
"cm = confusion_matrix(actual, predicted) plt.figure(figsize=(8,5)) sns.heatmap(cm, annot=True, fmt='.2f', xticklabels=['Not Default', 'Default'], yticklabels=['Not Default',",
"income they may have a harder time paying back a loan. # -",
"'HomeImp'], autopct='%.1f') plt.show() df['REASON'].value_counts() # In[10]: correlation = df.corr() sns.heatmap(correlation) plt.show() # In[11]:",
"one had decent performance. # - To improve the performance of this we",
"In[11]: df['BAD'].value_counts(normalize=True) # In[12]: df.fillna(df.mean(), inplace=True) # In[13]: one_hot_encoding = pd.get_dummies(df['REASON']) df =",
"best combination of parameters forest_estimator_tuned = grid_obj.best_estimator_ # In[31]: forest_estimator_tuned.fit(x_train, y_train) # In[32]:",
"dependent_test_performance_dt = tree_estimator.predict(x_test) metrics_score(y_test, dependent_test_performance_dt) # - Although the performance is slightly worse,",
"import metrics from sklearn.metrics import confusion_matrix, classification_report, precision_recall_curve,recall_score from sklearn import tree from",
"# - We can see that the most important features are DEBTINC, CLAGE",
"pd.get_dummies(df['JOB']) df = df.drop('JOB', axis=1) df = df.join(one_hot_encoding2) df # In[15]: dependent =",
"their credit card payments will have a hard time paying back a loan.",
"A visualization is one of the advantages that dtrees offer, we can show",
"utf-8 # # Loan Classification Project # In[1]: # Libraries we need import",
"\"min_samples_leaf\": np.arange(1, 4,1), \"max_features\": [0.7,0.9,'auto'], } score = metrics.make_scorer(recall_score, pos_label=1) # Run the",
"{ 'max_depth':np.arange(2,7), 'criterion':['gini', 'entropy'], 'min_samples_leaf':[5,10,20,25] } score = metrics.make_scorer(recall_score, pos_label=1) gridCV= GridSearchCV(tree_estimator, parameters,",
"xticklabels=['Not Default', 'Default'], yticklabels=['Not Default', 'Default']) plt.ylabel('Actual') plt.xlabel('Predicted') plt.show() # In[17]: dtree =",
"harmful error but decreased the harmful error # In[24]: dependent_test_performance_dt = tree_estimator.predict(x_test) metrics_score(y_test,",
"df = df.drop('JOB', axis=1) df = df.join(one_hot_encoding2) df # In[15]: dependent = df['BAD']",
"# Set the clf to the best combination of parameters forest_estimator_tuned = grid_obj.best_estimator_",
"transparent as it lets us visualize it. This first one had decent performance.",
"# In[14]: one_hot_encoding2 = pd.get_dummies(df['JOB']) df = df.drop('JOB', axis=1) df = df.join(one_hot_encoding2) df",
"import LinearDiscriminantAnalysis from sklearn.discriminant_analysis import QuadraticDiscriminantAnalysis from sklearn.linear_model import LogisticRegression from sklearn.neighbors import",
"into this model. # In[34]: get_ipython().system('pip install shap') import shap # In[35]: shap.initjs()",
"the test # - Lets test on test data # In[20]: dependent_test_performance_dt =",
"we still reduce harmful error # In[25]: important = tree_estimator.feature_importances_ columns=independent.columns importance_df=pd.DataFrame(important,index=columns,columns=['Importance']).sort_values(by='Importance',ascending=False) plt.figure(figsize=(13,13))",
"# In[2]: df = pd.read_csv(\"Dataset.csv\") # In[3]: df.head() # In[4]: df.info() # In[5]:",
"dependent_performance_dt = dtree.predict(x_train) metrics_score(y_train, dependent_performance_dt) # - The above is perfect because we",
"tune the model, this reduced the harmful error. # - Then to improve",
"model. # In[34]: get_ipython().system('pip install shap') import shap # In[35]: shap.initjs() # In[36]:",
"plt.show() # - I followed this from a previous project to see the",
"# - I made many models to get the best results. # -",
"### Recommendations # - The biggest thing that effects defaulting on a loan",
"In[13]: one_hot_encoding = pd.get_dummies(df['REASON']) df = df.drop('REASON', axis=1) df = df.join(one_hot_encoding) df #",
"import LogisticRegression from sklearn.neighbors import KNeighborsClassifier from sklearn import metrics from sklearn.metrics import",
"forest_estimator = RandomForestClassifier(class_weight={0:0.20, 1:0.80}, random_state=1) forest_estimator.fit(x_train, y_train) # In[28]: y_predict_training_forest = forest_estimator.predict(x_train) metrics_score(y_train,",
"- Selfnote: do importance features next # In[21]: important = dtree.feature_importances_ columns =",
"apply SHAP to look more into this model. # In[34]: get_ipython().system('pip install shap')",
"the thought process # In[27]: forest_estimator = RandomForestClassifier(class_weight={0:0.20, 1:0.80}, random_state=1) forest_estimator.fit(x_train, y_train) #",
"error # In[25]: important = tree_estimator.feature_importances_ columns=independent.columns importance_df=pd.DataFrame(important,index=columns,columns=['Importance']).sort_values(by='Importance',ascending=False) plt.figure(figsize=(13,13)) sns.barplot(importance_df.Importance,importance_df.index) plt.show() # In[26]:",
"metrics.make_scorer(recall_score, pos_label=1) # Run the grid search grid_obj = GridSearchCV(forest_estimator_tuned, parameters_rf, scoring=score, cv=5)",
"df.info() # In[5]: df.nunique() # - Above we can see that Reason and",
"dependent_performance_dt) # - We increased the less harmful error but decreased the harmful",
"this reduced the harmful error. # - Then to improve even more I",
"BaggingClassifier from sklearn.ensemble import RandomForestClassifier from sklearn.model_selection import GridSearchCV # In[2]: df =",
"df.fillna(df.mean(), inplace=True) # In[13]: one_hot_encoding = pd.get_dummies(df['REASON']) df = df.drop('REASON', axis=1) df =",
"decision tree model, this had excellent performance once we created a second version",
"gridCV = gridCV.fit(x_train, y_train) tree_estimator = gridCV.best_estimator_ tree_estimator.fit(x_train, y_train) # In[23]: dependent_performance_dt =",
"of parameters forest_estimator_tuned = grid_obj.best_estimator_ # In[31]: forest_estimator_tuned.fit(x_train, y_train) # In[32]: y_predict_train_forest_tuned =",
"important = tree_estimator.feature_importances_ columns=independent.columns importance_df=pd.DataFrame(important,index=columns,columns=['Importance']).sort_values(by='Importance',ascending=False) plt.figure(figsize=(13,13)) sns.barplot(importance_df.Importance,importance_df.index) plt.show() # In[26]: features = list(independent.columns)",
"y_train) # In[32]: y_predict_train_forest_tuned = forest_estimator_tuned.predict(x_train) metrics_score(y_train, y_predict_train_forest_tuned) # In[33]: y_predict_test_forest_tuned = forest_estimator_tuned.predict(x_test)",
"= df['BAD'] independent = df.drop(['BAD'], axis=1) x_train, x_test, y_train, y_test = train_test_split(independent, dependent,",
"# In[39]: shap.plots.heatmap(shap_vals[:, :, 0]) # In[40]: shap.summary_plot(shap_vals[:, :, 0], x_train) # In[53]:",
"income ratio. If someone has a lot of debt and a lower income",
"annot=True, fmt='.2f', xticklabels=['Not Default', 'Default'], yticklabels=['Not Default', 'Default']) plt.ylabel('Actual') plt.xlabel('Predicted') plt.show() # In[17]:",
"# - The performance is a lot better than the original single tree",
"The first one I made was a decision tree, this is not as",
"payments will have a hard time paying back a loan. # - Years",
"DecisionTreeClassifier from sklearn.ensemble import BaggingClassifier from sklearn.ensemble import RandomForestClassifier from sklearn.model_selection import GridSearchCV",
"parameters forest_estimator_tuned = grid_obj.best_estimator_ # In[31]: forest_estimator_tuned.fit(x_train, y_train) # In[32]: y_predict_train_forest_tuned = forest_estimator_tuned.predict(x_train)",
"signs/good signs that should be looked out for when looking for candidates to",
"of this we tried to tune the model, this reduced the harmful error.",
"good as random forest but it is transparent as it lets us visualize",
"# In[20]: dependent_test_performance_dt = dtree.predict(x_test) metrics_score(y_test,dependent_test_performance_dt) # - As we can see, we",
"Loan Classification Project # In[1]: # Libraries we need import pandas as pd",
"# In[28]: y_predict_training_forest = forest_estimator.predict(x_train) metrics_score(y_train, y_predict_training_forest) # - A perfect classification #",
"classification_report, precision_recall_curve,recall_score from sklearn import tree from sklearn.tree import DecisionTreeClassifier from sklearn.ensemble import",
"lets us visualize it. This first one had decent performance. # - To",
"make their credit card payments will have a hard time paying back a",
"# - Lets test on test data # In[20]: dependent_test_performance_dt = dtree.predict(x_test) metrics_score(y_test,dependent_test_performance_dt)",
"plt import seaborn as sns from sklearn.preprocessing import StandardScaler from sklearn.model_selection import train_test_split",
"could indicate financial stability. # - DEROG, or a history of delinquent payments",
":, 0]) # In[40]: shap.summary_plot(shap_vals[:, :, 0], x_train) # In[53]: print(forest_estimator_tuned.predict(x_test.iloc[107].to_numpy().reshape(1,-1))) # This",
"is one of the advantages that dtrees offer, we can show this to",
"# In[19]: dependent_performance_dt = dtree.predict(x_train) metrics_score(y_train, dependent_performance_dt) # - The above is perfect",
"improve the performance of this we tried to tune the model, this reduced",
"this is not as good as random forest but it is transparent as",
"columns = independent.columns important_items_df = pd.DataFrame(important, index=columns, columns=['Importance']).sort_values(by='Importance', ascending=False) plt.figure(figsize=(13,13)) sns.barplot(important_items_df.Importance, important_items_df.index) plt.show()",
"'min_samples_leaf':[5,10,20,25] } score = metrics.make_scorer(recall_score, pos_label=1) gridCV= GridSearchCV(tree_estimator, parameters, scoring=score,cv=10) gridCV = gridCV.fit(x_train,",
"# - Although the performance is slightly worse, we still reduce harmful error",
"pd.read_csv(\"Dataset.csv\") # In[3]: df.head() # In[4]: df.info() # In[5]: df.nunique() # - Above",
"company # ### Conclusion # - I made many models to get the",
"loan is the debt to income ratio. If someone has a lot of",
"advantages that dtrees offer, we can show this to the client ot show",
"shap.plots.bar(shap_vals[:, :, 0]) # In[39]: shap.plots.heatmap(shap_vals[:, :, 0]) # In[40]: shap.summary_plot(shap_vals[:, :, 0],",
"metrics_score(y_train, y_predict_train_forest_tuned) # In[33]: y_predict_test_forest_tuned = forest_estimator_tuned.predict(x_test) metrics_score(y_test, y_predict_test_forest_tuned) # - We now",
"signs that should be looked out for when looking for candidates to give",
"decent performance. # - To improve the performance of this we tried to",
"# - We now have very good performance # - We can submit",
"= metrics.make_scorer(recall_score, pos_label=1) # Run the grid search grid_obj = GridSearchCV(forest_estimator_tuned, parameters_rf, scoring=score,",
"# - Selfnote: do importance features next # In[21]: important = dtree.feature_importances_ columns",
"axis=1) df = df.join(one_hot_encoding2) df # In[15]: dependent = df['BAD'] independent = df.drop(['BAD'],",
"# In[25]: important = tree_estimator.feature_importances_ columns=independent.columns importance_df=pd.DataFrame(important,index=columns,columns=['Importance']).sort_values(by='Importance',ascending=False) plt.figure(figsize=(13,13)) sns.barplot(importance_df.Importance,importance_df.index) plt.show() # In[26]: features",
"debt to income ratio. If someone has a lot of debt and a",
"metrics_score(y_train, dependent_performance_dt) # - The above is perfect because we are using the",
"'criterion':['gini', 'entropy'], 'min_samples_leaf':[5,10,20,25] } score = metrics.make_scorer(recall_score, pos_label=1) gridCV= GridSearchCV(tree_estimator, parameters, scoring=score,cv=10) gridCV",
"# # I will now apply SHAP to look more into this model.",
"job is also a driver of a loans outcome. A large number of",
"not the test # - Lets test on test data # In[20]: dependent_test_performance_dt",
"In[39]: shap.plots.heatmap(shap_vals[:, :, 0]) # In[40]: shap.summary_plot(shap_vals[:, :, 0], x_train) # In[53]: print(forest_estimator_tuned.predict(x_test.iloc[107].to_numpy().reshape(1,-1)))",
"# ### Conclusion # - I made many models to get the best",
"Above we can see that Reason and Bad are binary variables # -",
"numpy as np import matplotlib.pyplot as plt import seaborn as sns from sklearn.preprocessing",
"shap.summary_plot(shap_vals[:, :, 0], x_train) # In[53]: print(forest_estimator_tuned.predict(x_test.iloc[107].to_numpy().reshape(1,-1))) # This predicts for one row,",
"tree_estimator = DecisionTreeClassifier(class_weight={0:0.20, 1:0.80}, random_state=1) parameters = { 'max_depth':np.arange(2,7), 'criterion':['gini', 'entropy'], 'min_samples_leaf':[5,10,20,25] }",
"# ### Recommendations # - The biggest thing that effects defaulting on a",
"good performance # - We can submit this to the company # ###",
"train_test_split(independent, dependent, test_size=0.3, random_state=1) # In[16]: def metrics_score(actual, predicted): print(classification_report(actual, predicted)) cm =",
"parameters_rf, scoring=score, cv=5) grid_obj = grid_obj.fit(x_train, y_train) # Set the clf to the",
"needs to be dropped # In[6]: df.describe() # In[7]: plt.hist(df['BAD'], bins=3) plt.show() #",
"= train_test_split(independent, dependent, test_size=0.3, random_state=1) # In[16]: def metrics_score(actual, predicted): print(classification_report(actual, predicted)) cm",
"loans outcome. A large number of years at a job could indicate financial",
"df.head() # In[4]: df.info() # In[5]: df.nunique() # - Above we can see",
"sns.barplot(importance_df.Importance,importance_df.index) plt.show() # In[26]: features = list(independent.columns) plt.figure(figsize=(30,20)) tree.plot_tree(dtree,max_depth=4,feature_names=features,filled=True,fontsize=12,node_ids=True,class_names=True) plt.show() # - A",
"metrics_score(y_test, y_predict_test_forest_tuned) # - We now have very good performance # - We",
"import numpy as np import matplotlib.pyplot as plt import seaborn as sns from",
"import QuadraticDiscriminantAnalysis from sklearn.linear_model import LogisticRegression from sklearn.neighbors import KNeighborsClassifier from sklearn import",
"the harmful error. # - Then to improve even more I created a",
"error. # - Then to improve even more I created a decision tree",
"import tree from sklearn.tree import DecisionTreeClassifier from sklearn.ensemble import BaggingClassifier from sklearn.ensemble import",
"We increased the less harmful error but decreased the harmful error # In[24]:",
"the best results. # - The first one I made was a decision",
"time paying back a loan. # - Something else that effects defaulting on",
"back a loan. # - Years at job is also a driver of",
"ratio. If someone has a lot of debt and a lower income they"
] |
[
"Built-in Exceptions try: a=[int(i) for i in input('Enter a list:').split()] except Exception as",
"try: a=[int(i) for i in input('Enter a list:').split()] except Exception as e: print(e)",
"#Handling Built-in Exceptions try: a=[int(i) for i in input('Enter a list:').split()] except Exception",
"<filename>InBuiltExcptionHandling.py #Handling Built-in Exceptions try: a=[int(i) for i in input('Enter a list:').split()] except",
"Exceptions try: a=[int(i) for i in input('Enter a list:').split()] except Exception as e:",
"for i in input('Enter a list:').split()] except Exception as e: print(e) else: print(sum(a))",
"a=[int(i) for i in input('Enter a list:').split()] except Exception as e: print(e) else:"
] |
[
"senha: ') while len(chave) > 8: chave = input('A base só pode ter",
"senha novamente: ') for c in range(0, len(chave)): letras.append(chave[c]) senha.append(letras[:]) letras.pop() caracteres =",
"ele basicamente pega todo tipo de caractere digitado pelo usuário e depois de",
"8 caracteres, digite a base da sua senha novamente: ') for c in",
"gerada é: ') shuffle(senha) cores = ('\\033[1;31m', '\\033[1;32m', '\\033[1;33m') for i, l in",
"shuffle \"\"\"gerador de senha simples ele basicamente pega todo tipo de caractere digitado",
"novamente: ') for c in range(0, len(chave)): letras.append(chave[c]) senha.append(letras[:]) letras.pop() caracteres = (')',",
"cores = ('\\033[1;31m', '\\033[1;32m', '\\033[1;33m') for i, l in enumerate(senha): adcionais = randint(0,",
"in range(0, len(chave)): letras.append(chave[c]) senha.append(letras[:]) letras.pop() caracteres = (')', '*', '/', '%', '!')",
"len(chave) > 8: chave = input('A base só pode ter até 8 caracteres,",
"i, l in enumerate(senha): adcionais = randint(0, 10) p = l[:][0] p +=",
"= input('A base só pode ter até 8 caracteres, digite a base da",
"l in enumerate(senha): adcionais = randint(0, 10) p = l[:][0] p += str(adcionais)",
"caractere digitado pelo usuário e depois de cada um deles é colocado um",
"= (')', '*', '/', '%', '!') print('a senha gerada é: ') shuffle(senha) cores",
"> 8: chave = input('A base só pode ter até 8 caracteres, digite",
"e depois de cada um deles é colocado um número de 1 a",
"'/', '%', '!') print('a senha gerada é: ') shuffle(senha) cores = ('\\033[1;31m', '\\033[1;32m',",
"') while len(chave) > 8: chave = input('A base só pode ter até",
"senha.append(letras[:]) letras.pop() caracteres = (')', '*', '/', '%', '!') print('a senha gerada é:",
"'%', '!') print('a senha gerada é: ') shuffle(senha) cores = ('\\033[1;31m', '\\033[1;32m', '\\033[1;33m')",
"de cada um deles é colocado um número de 1 a 10 e",
"senha simples ele basicamente pega todo tipo de caractere digitado pelo usuário e",
"símbolo\"\"\" letras = list() senha = list() chave = input('Digite a base da",
"(')', '*', '/', '%', '!') print('a senha gerada é: ') shuffle(senha) cores =",
"da sua senha novamente: ') for c in range(0, len(chave)): letras.append(chave[c]) senha.append(letras[:]) letras.pop()",
"10 e mais um símbolo\"\"\" letras = list() senha = list() chave =",
"cada um deles é colocado um número de 1 a 10 e mais",
"input('Digite a base da sua senha: ') while len(chave) > 8: chave =",
"senha = list() chave = input('Digite a base da sua senha: ') while",
"randint(0, 10) p = l[:][0] p += str(adcionais) + choice(caracteres) print(p,end='') print('\\n\\033[32;1mBoa sorte",
"for c in range(0, len(chave)): letras.append(chave[c]) senha.append(letras[:]) letras.pop() caracteres = (')', '*', '/',",
"colocado um número de 1 a 10 e mais um símbolo\"\"\" letras =",
"ter até 8 caracteres, digite a base da sua senha novamente: ') for",
"input('A base só pode ter até 8 caracteres, digite a base da sua",
"= ('\\033[1;31m', '\\033[1;32m', '\\033[1;33m') for i, l in enumerate(senha): adcionais = randint(0, 10)",
"in enumerate(senha): adcionais = randint(0, 10) p = l[:][0] p += str(adcionais) +",
"= list() senha = list() chave = input('Digite a base da sua senha:",
"sua senha novamente: ') for c in range(0, len(chave)): letras.append(chave[c]) senha.append(letras[:]) letras.pop() caracteres",
"só pode ter até 8 caracteres, digite a base da sua senha novamente:",
"todo tipo de caractere digitado pelo usuário e depois de cada um deles",
"for i, l in enumerate(senha): adcionais = randint(0, 10) p = l[:][0] p",
"letras.pop() caracteres = (')', '*', '/', '%', '!') print('a senha gerada é: ')",
"c in range(0, len(chave)): letras.append(chave[c]) senha.append(letras[:]) letras.pop() caracteres = (')', '*', '/', '%',",
"mais um símbolo\"\"\" letras = list() senha = list() chave = input('Digite a",
"list() chave = input('Digite a base da sua senha: ') while len(chave) >",
"('\\033[1;31m', '\\033[1;32m', '\\033[1;33m') for i, l in enumerate(senha): adcionais = randint(0, 10) p",
"de caractere digitado pelo usuário e depois de cada um deles é colocado",
"caracteres, digite a base da sua senha novamente: ') for c in range(0,",
"basicamente pega todo tipo de caractere digitado pelo usuário e depois de cada",
"um número de 1 a 10 e mais um símbolo\"\"\" letras = list()",
"é colocado um número de 1 a 10 e mais um símbolo\"\"\" letras",
"chave = input('A base só pode ter até 8 caracteres, digite a base",
"\"\"\"gerador de senha simples ele basicamente pega todo tipo de caractere digitado pelo",
"enumerate(senha): adcionais = randint(0, 10) p = l[:][0] p += str(adcionais) + choice(caracteres)",
"um símbolo\"\"\" letras = list() senha = list() chave = input('Digite a base",
"digite a base da sua senha novamente: ') for c in range(0, len(chave)):",
"chave = input('Digite a base da sua senha: ') while len(chave) > 8:",
"a base da sua senha novamente: ') for c in range(0, len(chave)): letras.append(chave[c])",
"pode ter até 8 caracteres, digite a base da sua senha novamente: ')",
"range(0, len(chave)): letras.append(chave[c]) senha.append(letras[:]) letras.pop() caracteres = (')', '*', '/', '%', '!') print('a",
"e mais um símbolo\"\"\" letras = list() senha = list() chave = input('Digite",
"'*', '/', '%', '!') print('a senha gerada é: ') shuffle(senha) cores = ('\\033[1;31m',",
"pega todo tipo de caractere digitado pelo usuário e depois de cada um",
"= randint(0, 10) p = l[:][0] p += str(adcionais) + choice(caracteres) print(p,end='') print('\\n\\033[32;1mBoa",
"while len(chave) > 8: chave = input('A base só pode ter até 8",
"print('a senha gerada é: ') shuffle(senha) cores = ('\\033[1;31m', '\\033[1;32m', '\\033[1;33m') for i,",
"letras.append(chave[c]) senha.append(letras[:]) letras.pop() caracteres = (')', '*', '/', '%', '!') print('a senha gerada",
"usuário e depois de cada um deles é colocado um número de 1",
"shuffle(senha) cores = ('\\033[1;31m', '\\033[1;32m', '\\033[1;33m') for i, l in enumerate(senha): adcionais =",
"um deles é colocado um número de 1 a 10 e mais um",
"simples ele basicamente pega todo tipo de caractere digitado pelo usuário e depois",
"é: ') shuffle(senha) cores = ('\\033[1;31m', '\\033[1;32m', '\\033[1;33m') for i, l in enumerate(senha):",
"número de 1 a 10 e mais um símbolo\"\"\" letras = list() senha",
"deles é colocado um número de 1 a 10 e mais um símbolo\"\"\"",
"len(chave)): letras.append(chave[c]) senha.append(letras[:]) letras.pop() caracteres = (')', '*', '/', '%', '!') print('a senha",
"') shuffle(senha) cores = ('\\033[1;31m', '\\033[1;32m', '\\033[1;33m') for i, l in enumerate(senha): adcionais",
"= l[:][0] p += str(adcionais) + choice(caracteres) print(p,end='') print('\\n\\033[32;1mBoa sorte em decorar ela!')",
"até 8 caracteres, digite a base da sua senha novamente: ') for c",
"'!') print('a senha gerada é: ') shuffle(senha) cores = ('\\033[1;31m', '\\033[1;32m', '\\033[1;33m') for",
"depois de cada um deles é colocado um número de 1 a 10",
"random import randint, choice, shuffle \"\"\"gerador de senha simples ele basicamente pega todo",
"pelo usuário e depois de cada um deles é colocado um número de",
"tipo de caractere digitado pelo usuário e depois de cada um deles é",
"1 a 10 e mais um símbolo\"\"\" letras = list() senha = list()",
"letras = list() senha = list() chave = input('Digite a base da sua",
"choice, shuffle \"\"\"gerador de senha simples ele basicamente pega todo tipo de caractere",
"de senha simples ele basicamente pega todo tipo de caractere digitado pelo usuário",
"'\\033[1;32m', '\\033[1;33m') for i, l in enumerate(senha): adcionais = randint(0, 10) p =",
"a 10 e mais um símbolo\"\"\" letras = list() senha = list() chave",
"8: chave = input('A base só pode ter até 8 caracteres, digite a",
"base da sua senha novamente: ') for c in range(0, len(chave)): letras.append(chave[c]) senha.append(letras[:])",
"p = l[:][0] p += str(adcionais) + choice(caracteres) print(p,end='') print('\\n\\033[32;1mBoa sorte em decorar",
"sua senha: ') while len(chave) > 8: chave = input('A base só pode",
"a base da sua senha: ') while len(chave) > 8: chave = input('A",
"de 1 a 10 e mais um símbolo\"\"\" letras = list() senha =",
"randint, choice, shuffle \"\"\"gerador de senha simples ele basicamente pega todo tipo de",
"da sua senha: ') while len(chave) > 8: chave = input('A base só",
"10) p = l[:][0] p += str(adcionais) + choice(caracteres) print(p,end='') print('\\n\\033[32;1mBoa sorte em",
"= list() chave = input('Digite a base da sua senha: ') while len(chave)",
"list() senha = list() chave = input('Digite a base da sua senha: ')",
"'\\033[1;33m') for i, l in enumerate(senha): adcionais = randint(0, 10) p = l[:][0]",
"from random import randint, choice, shuffle \"\"\"gerador de senha simples ele basicamente pega",
"base só pode ter até 8 caracteres, digite a base da sua senha",
"caracteres = (')', '*', '/', '%', '!') print('a senha gerada é: ') shuffle(senha)",
"adcionais = randint(0, 10) p = l[:][0] p += str(adcionais) + choice(caracteres) print(p,end='')",
"import randint, choice, shuffle \"\"\"gerador de senha simples ele basicamente pega todo tipo",
"= input('Digite a base da sua senha: ') while len(chave) > 8: chave",
"base da sua senha: ') while len(chave) > 8: chave = input('A base",
"senha gerada é: ') shuffle(senha) cores = ('\\033[1;31m', '\\033[1;32m', '\\033[1;33m') for i, l",
"digitado pelo usuário e depois de cada um deles é colocado um número",
"') for c in range(0, len(chave)): letras.append(chave[c]) senha.append(letras[:]) letras.pop() caracteres = (')', '*',"
] |
[
"plt s1 = set(open('wd-inst-of-prot', 'r').readlines()) s2 = set(open('wd-subc-of-prot', 'r').readlines()) s3 = set(open('wd-refseqp', 'r').readlines())",
"set(open('wd-subc-of-prot', 'r').readlines()) s3 = set(open('wd-refseqp', 'r').readlines()) #s4 = set(open('t4', 'r').readlines()) venn3([s3,s2,s1], ('RefSeq', 'subc',",
"from sys import * from matplotlib_venn import venn3, venn3_circles from matplotlib import pyplot",
"* from matplotlib_venn import venn3, venn3_circles from matplotlib import pyplot as plt s1",
"as plt s1 = set(open('wd-inst-of-prot', 'r').readlines()) s2 = set(open('wd-subc-of-prot', 'r').readlines()) s3 = set(open('wd-refseqp',",
"s3 = set(open('wd-refseqp', 'r').readlines()) #s4 = set(open('t4', 'r').readlines()) venn3([s3,s2,s1], ('RefSeq', 'subc', 'inst of",
"venn3, venn3_circles from matplotlib import pyplot as plt s1 = set(open('wd-inst-of-prot', 'r').readlines()) s2",
"s2 = set(open('wd-subc-of-prot', 'r').readlines()) s3 = set(open('wd-refseqp', 'r').readlines()) #s4 = set(open('t4', 'r').readlines()) venn3([s3,s2,s1],",
"set(open('wd-refseqp', 'r').readlines()) #s4 = set(open('t4', 'r').readlines()) venn3([s3,s2,s1], ('RefSeq', 'subc', 'inst of protein')) c",
"import pyplot as plt s1 = set(open('wd-inst-of-prot', 'r').readlines()) s2 = set(open('wd-subc-of-prot', 'r').readlines()) s3",
"matplotlib_venn import venn3, venn3_circles from matplotlib import pyplot as plt s1 = set(open('wd-inst-of-prot',",
"from matplotlib import pyplot as plt s1 = set(open('wd-inst-of-prot', 'r').readlines()) s2 = set(open('wd-subc-of-prot',",
"'r').readlines()) venn3([s3,s2,s1], ('RefSeq', 'subc', 'inst of protein')) c = venn3_circles([s3,s2,s1]) c[0].set_lw(1.0) plt.show() #plt.savefig('venn.svg')",
"= set(open('wd-inst-of-prot', 'r').readlines()) s2 = set(open('wd-subc-of-prot', 'r').readlines()) s3 = set(open('wd-refseqp', 'r').readlines()) #s4 =",
"from matplotlib_venn import venn3, venn3_circles from matplotlib import pyplot as plt s1 =",
"venn3_circles from matplotlib import pyplot as plt s1 = set(open('wd-inst-of-prot', 'r').readlines()) s2 =",
"'r').readlines()) s2 = set(open('wd-subc-of-prot', 'r').readlines()) s3 = set(open('wd-refseqp', 'r').readlines()) #s4 = set(open('t4', 'r').readlines())",
"set(open('wd-inst-of-prot', 'r').readlines()) s2 = set(open('wd-subc-of-prot', 'r').readlines()) s3 = set(open('wd-refseqp', 'r').readlines()) #s4 = set(open('t4',",
"matplotlib import pyplot as plt s1 = set(open('wd-inst-of-prot', 'r').readlines()) s2 = set(open('wd-subc-of-prot', 'r').readlines())",
"pyplot as plt s1 = set(open('wd-inst-of-prot', 'r').readlines()) s2 = set(open('wd-subc-of-prot', 'r').readlines()) s3 =",
"'r').readlines()) #s4 = set(open('t4', 'r').readlines()) venn3([s3,s2,s1], ('RefSeq', 'subc', 'inst of protein')) c =",
"sys import * from matplotlib_venn import venn3, venn3_circles from matplotlib import pyplot as",
"import * from matplotlib_venn import venn3, venn3_circles from matplotlib import pyplot as plt",
"import venn3, venn3_circles from matplotlib import pyplot as plt s1 = set(open('wd-inst-of-prot', 'r').readlines())",
"= set(open('wd-subc-of-prot', 'r').readlines()) s3 = set(open('wd-refseqp', 'r').readlines()) #s4 = set(open('t4', 'r').readlines()) venn3([s3,s2,s1], ('RefSeq',",
"= set(open('t4', 'r').readlines()) venn3([s3,s2,s1], ('RefSeq', 'subc', 'inst of protein')) c = venn3_circles([s3,s2,s1]) c[0].set_lw(1.0)",
"'r').readlines()) s3 = set(open('wd-refseqp', 'r').readlines()) #s4 = set(open('t4', 'r').readlines()) venn3([s3,s2,s1], ('RefSeq', 'subc', 'inst",
"#s4 = set(open('t4', 'r').readlines()) venn3([s3,s2,s1], ('RefSeq', 'subc', 'inst of protein')) c = venn3_circles([s3,s2,s1])",
"set(open('t4', 'r').readlines()) venn3([s3,s2,s1], ('RefSeq', 'subc', 'inst of protein')) c = venn3_circles([s3,s2,s1]) c[0].set_lw(1.0) plt.show()",
"= set(open('wd-refseqp', 'r').readlines()) #s4 = set(open('t4', 'r').readlines()) venn3([s3,s2,s1], ('RefSeq', 'subc', 'inst of protein'))",
"s1 = set(open('wd-inst-of-prot', 'r').readlines()) s2 = set(open('wd-subc-of-prot', 'r').readlines()) s3 = set(open('wd-refseqp', 'r').readlines()) #s4"
] |
[
"i in x: y.append(3*i**2 + 5) p_coeff = np.polyfit(x, y, 2) poly =",
"stations = build_station_list() import numpy as np def test_polt_water_level_with_fit(): x = np.linspace(1, 1000,",
"5) p_coeff = np.polyfit(x, y, 2) poly = np.poly1d(p_coeff) assert int(p_coeff[0]) == 2",
"import plot_water_levels, plot_water_level_with_fit stations = build_station_list() import numpy as np def test_polt_water_level_with_fit(): x",
"import datetime from floodsystem.datafetcher import fetch_measure_levels from floodsystem.stationdata import build_station_list from floodsystem.plot import",
"numpy as np def test_polt_water_level_with_fit(): x = np.linspace(1, 1000, 100000) y = []",
"from floodsystem.stationdata import build_station_list from floodsystem.plot import plot_water_levels, plot_water_level_with_fit stations = build_station_list() import",
"plot_water_level_with_fit stations = build_station_list() import numpy as np def test_polt_water_level_with_fit(): x = np.linspace(1,",
"floodsystem.stationdata import build_station_list from floodsystem.plot import plot_water_levels, plot_water_level_with_fit stations = build_station_list() import numpy",
"1000, 100000) y = [] for i in x: y.append(3*i**2 + 5) p_coeff",
"= [] for i in x: y.append(3*i**2 + 5) p_coeff = np.polyfit(x, y,",
"datetime from floodsystem.datafetcher import fetch_measure_levels from floodsystem.stationdata import build_station_list from floodsystem.plot import plot_water_levels,",
"np def test_polt_water_level_with_fit(): x = np.linspace(1, 1000, 100000) y = [] for i",
"from floodsystem.datafetcher import fetch_measure_levels from floodsystem.stationdata import build_station_list from floodsystem.plot import plot_water_levels, plot_water_level_with_fit",
"for i in x: y.append(3*i**2 + 5) p_coeff = np.polyfit(x, y, 2) poly",
"floodsystem.plot import plot_water_levels, plot_water_level_with_fit stations = build_station_list() import numpy as np def test_polt_water_level_with_fit():",
"import numpy as np def test_polt_water_level_with_fit(): x = np.linspace(1, 1000, 100000) y =",
"as np def test_polt_water_level_with_fit(): x = np.linspace(1, 1000, 100000) y = [] for",
"x = np.linspace(1, 1000, 100000) y = [] for i in x: y.append(3*i**2",
"import fetch_measure_levels from floodsystem.stationdata import build_station_list from floodsystem.plot import plot_water_levels, plot_water_level_with_fit stations =",
"100000) y = [] for i in x: y.append(3*i**2 + 5) p_coeff =",
"x: y.append(3*i**2 + 5) p_coeff = np.polyfit(x, y, 2) poly = np.poly1d(p_coeff) assert",
"y.append(3*i**2 + 5) p_coeff = np.polyfit(x, y, 2) poly = np.poly1d(p_coeff) assert int(p_coeff[0])",
"floodsystem.datafetcher import fetch_measure_levels from floodsystem.stationdata import build_station_list from floodsystem.plot import plot_water_levels, plot_water_level_with_fit stations",
"test_polt_water_level_with_fit(): x = np.linspace(1, 1000, 100000) y = [] for i in x:",
"def test_polt_water_level_with_fit(): x = np.linspace(1, 1000, 100000) y = [] for i in",
"build_station_list() import numpy as np def test_polt_water_level_with_fit(): x = np.linspace(1, 1000, 100000) y",
"import build_station_list from floodsystem.plot import plot_water_levels, plot_water_level_with_fit stations = build_station_list() import numpy as",
"plot_water_levels, plot_water_level_with_fit stations = build_station_list() import numpy as np def test_polt_water_level_with_fit(): x =",
"build_station_list from floodsystem.plot import plot_water_levels, plot_water_level_with_fit stations = build_station_list() import numpy as np",
"in x: y.append(3*i**2 + 5) p_coeff = np.polyfit(x, y, 2) poly = np.poly1d(p_coeff)",
"= np.linspace(1, 1000, 100000) y = [] for i in x: y.append(3*i**2 +",
"fetch_measure_levels from floodsystem.stationdata import build_station_list from floodsystem.plot import plot_water_levels, plot_water_level_with_fit stations = build_station_list()",
"from floodsystem.plot import plot_water_levels, plot_water_level_with_fit stations = build_station_list() import numpy as np def",
"= build_station_list() import numpy as np def test_polt_water_level_with_fit(): x = np.linspace(1, 1000, 100000)",
"+ 5) p_coeff = np.polyfit(x, y, 2) poly = np.poly1d(p_coeff) assert int(p_coeff[0]) ==",
"np.linspace(1, 1000, 100000) y = [] for i in x: y.append(3*i**2 + 5)",
"[] for i in x: y.append(3*i**2 + 5) p_coeff = np.polyfit(x, y, 2)",
"y = [] for i in x: y.append(3*i**2 + 5) p_coeff = np.polyfit(x,"
] |
[
"not edit class KlLEMarkeringSoort(KeuzelijstField): \"\"\"Mogelijke markeringsoorten op een lijvormig element.\"\"\" naam = 'KlLEMarkeringSoort'",
"het meestal hoger gelegen trottoir', objectUri='https://wegenenverkeer.data.vlaanderen.be/id/concept/KlLEMarkeringSoort/boordsteen'), 'boordsteen-parkeerverbod': KeuzelijstWaarde(invulwaarde='boordsteen-parkeerverbod', label='boordsteen parkeerverbod', definitie='Een lijnvormig element",
"een lijvormig element.' codelist = 'https://wegenenverkeer.data.vlaanderen.be/id/conceptscheme/KlLEMarkeringSoort' options = { 'biggenrug': KeuzelijstWaarde(invulwaarde='biggenrug', label='biggenrug', definitie='Een",
"meestal hoger gelegen trottoir', objectUri='https://wegenenverkeer.data.vlaanderen.be/id/concept/KlLEMarkeringSoort/boordsteen'), 'boordsteen-parkeerverbod': KeuzelijstWaarde(invulwaarde='boordsteen-parkeerverbod', label='boordsteen parkeerverbod', definitie='Een lijnvormig element dat",
"als functie het aanduiden van parkeerverbod', objectUri='https://wegenenverkeer.data.vlaanderen.be/id/concept/KlLEMarkeringSoort/boordsteen-parkeerverbod'), 'new-Jersey': KeuzelijstWaarde(invulwaarde='new-Jersey', label='new Jersey', definitie='Een afschermende",
"naast wegen wordt geplaatst om te voorkomen dat voertuigen de weg in zijdelingse",
"rijbaan en het meestal hoger gelegen trottoir met als functie het aanduiden van",
"definitie='Een afschermende constructie die naast wegen wordt geplaatst om te voorkomen dat voertuigen",
"Generated with OTLEnumerationCreator. To modify: extend, do not edit class KlLEMarkeringSoort(KeuzelijstField): \"\"\"Mogelijke markeringsoorten",
"KeuzelijstWaarde # Generated with OTLEnumerationCreator. To modify: extend, do not edit class KlLEMarkeringSoort(KeuzelijstField):",
"label='biggenrug', definitie='Een betonnen obstakel dat meestal een infrastructurele en beschermende functie heeft', objectUri='https://wegenenverkeer.data.vlaanderen.be/id/concept/KlLEMarkeringSoort/biggenrug'),",
"trottoir met als functie het aanduiden van parkeerverbod', objectUri='https://wegenenverkeer.data.vlaanderen.be/id/concept/KlLEMarkeringSoort/boordsteen-parkeerverbod'), 'new-Jersey': KeuzelijstWaarde(invulwaarde='new-Jersey', label='new Jersey',",
"wordt geplaatst om te voorkomen dat voertuigen de weg in zijdelingse richting verlaten,",
"import KeuzelijstWaarde # Generated with OTLEnumerationCreator. To modify: extend, do not edit class",
"de scheiding verzorgt tussen een rijbaan en het meestal hoger gelegen trottoir met",
"van lijnvormig element' objectUri = 'https://wegenenverkeer.data.vlaanderen.be/ns/onderdeel#KlLEMarkeringSoort' definition = 'Mogelijke markeringsoorten op een lijvormig",
"meestal hoger gelegen trottoir met als functie het aanduiden van parkeerverbod', objectUri='https://wegenenverkeer.data.vlaanderen.be/id/concept/KlLEMarkeringSoort/boordsteen-parkeerverbod'), 'new-Jersey':",
"obstakel dat meestal een infrastructurele en beschermende functie heeft', objectUri='https://wegenenverkeer.data.vlaanderen.be/id/concept/KlLEMarkeringSoort/biggenrug'), 'boordsteen': KeuzelijstWaarde(invulwaarde='boordsteen', label='boordsteen',",
"het aanduiden van parkeerverbod', objectUri='https://wegenenverkeer.data.vlaanderen.be/id/concept/KlLEMarkeringSoort/boordsteen-parkeerverbod'), 'new-Jersey': KeuzelijstWaarde(invulwaarde='new-Jersey', label='new Jersey', definitie='Een afschermende constructie uit",
"KeuzelijstWaarde(invulwaarde='vangrail', label='vangrail', definitie='Een afschermende constructie die naast wegen wordt geplaatst om te voorkomen",
"lijvormig element.' codelist = 'https://wegenenverkeer.data.vlaanderen.be/id/conceptscheme/KlLEMarkeringSoort' options = { 'biggenrug': KeuzelijstWaarde(invulwaarde='biggenrug', label='biggenrug', definitie='Een betonnen",
"KeuzelijstWaarde(invulwaarde='boordsteen-parkeerverbod', label='boordsteen parkeerverbod', definitie='Een lijnvormig element dat de scheiding verzorgt tussen een rijbaan",
"kantelen of de middenberm doorkruisen.', objectUri='https://wegenenverkeer.data.vlaanderen.be/id/concept/KlLEMarkeringSoort/new-Jersey'), 'vangrail': KeuzelijstWaarde(invulwaarde='vangrail', label='vangrail', definitie='Een afschermende constructie die",
"markeringsoorten op een lijvormig element.\"\"\" naam = 'KlLEMarkeringSoort' label = 'Soort markering van",
"label='vangrail', definitie='Een afschermende constructie die naast wegen wordt geplaatst om te voorkomen dat",
"edit class KlLEMarkeringSoort(KeuzelijstField): \"\"\"Mogelijke markeringsoorten op een lijvormig element.\"\"\" naam = 'KlLEMarkeringSoort' label",
"label='new Jersey', definitie='Een afschermende constructie uit kunststof, beton of metaal dat naast wegen",
"scheiding verzorgt tussen een rijbaan en het meestal hoger gelegen trottoir met als",
"KeuzelijstWaarde(invulwaarde='biggenrug', label='biggenrug', definitie='Een betonnen obstakel dat meestal een infrastructurele en beschermende functie heeft',",
"'boordsteen-parkeerverbod': KeuzelijstWaarde(invulwaarde='boordsteen-parkeerverbod', label='boordsteen parkeerverbod', definitie='Een lijnvormig element dat de scheiding verzorgt tussen een",
"Jersey', definitie='Een afschermende constructie uit kunststof, beton of metaal dat naast wegen wordt",
"de middenberm doorkruisen.', objectUri='https://wegenenverkeer.data.vlaanderen.be/id/concept/KlLEMarkeringSoort/new-Jersey'), 'vangrail': KeuzelijstWaarde(invulwaarde='vangrail', label='vangrail', definitie='Een afschermende constructie die naast wegen",
"with OTLEnumerationCreator. To modify: extend, do not edit class KlLEMarkeringSoort(KeuzelijstField): \"\"\"Mogelijke markeringsoorten op",
"constructie uit kunststof, beton of metaal dat naast wegen wordt geplaatst om te",
"richting verlaten, kantelen of de middenberm doorkruisen.', objectUri='https://wegenenverkeer.data.vlaanderen.be/id/concept/KlLEMarkeringSoort/new-Jersey'), 'vangrail': KeuzelijstWaarde(invulwaarde='vangrail', label='vangrail', definitie='Een afschermende",
"constructie die naast wegen wordt geplaatst om te voorkomen dat voertuigen de weg",
"de weg in zijdelingse richting verlaten, kantelen of de middenberm doorkruisen.', objectUri='https://wegenenverkeer.data.vlaanderen.be/id/concept/KlLEMarkeringSoort/new-Jersey'), 'vangrail':",
"element.\"\"\" naam = 'KlLEMarkeringSoort' label = 'Soort markering van lijnvormig element' objectUri =",
"meestal een infrastructurele en beschermende functie heeft', objectUri='https://wegenenverkeer.data.vlaanderen.be/id/concept/KlLEMarkeringSoort/biggenrug'), 'boordsteen': KeuzelijstWaarde(invulwaarde='boordsteen', label='boordsteen', definitie='Een lijnvormig",
"voertuigen de weg in zijdelingse richting verlaten, kantelen of de middenberm doorkruisen.', objectUri='https://wegenenverkeer.data.vlaanderen.be/id/concept/KlLEMarkeringSoort/new-Jersey'),",
"KlLEMarkeringSoort(KeuzelijstField): \"\"\"Mogelijke markeringsoorten op een lijvormig element.\"\"\" naam = 'KlLEMarkeringSoort' label = 'Soort",
"trottoir', objectUri='https://wegenenverkeer.data.vlaanderen.be/id/concept/KlLEMarkeringSoort/boordsteen'), 'boordsteen-parkeerverbod': KeuzelijstWaarde(invulwaarde='boordsteen-parkeerverbod', label='boordsteen parkeerverbod', definitie='Een lijnvormig element dat de scheiding verzorgt",
"de scheiding verzorgt tussen een rijbaan en het meestal hoger gelegen trottoir', objectUri='https://wegenenverkeer.data.vlaanderen.be/id/concept/KlLEMarkeringSoort/boordsteen'),",
"KeuzelijstWaarde(invulwaarde='new-Jersey', label='new Jersey', definitie='Een afschermende constructie uit kunststof, beton of metaal dat naast",
"scheiding verzorgt tussen een rijbaan en het meestal hoger gelegen trottoir', objectUri='https://wegenenverkeer.data.vlaanderen.be/id/concept/KlLEMarkeringSoort/boordsteen'), 'boordsteen-parkeerverbod':",
"element.' codelist = 'https://wegenenverkeer.data.vlaanderen.be/id/conceptscheme/KlLEMarkeringSoort' options = { 'biggenrug': KeuzelijstWaarde(invulwaarde='biggenrug', label='biggenrug', definitie='Een betonnen obstakel",
"en het meestal hoger gelegen trottoir met als functie het aanduiden van parkeerverbod',",
"definitie='Een afschermende constructie uit kunststof, beton of metaal dat naast wegen wordt geplaatst",
"tussen een rijbaan en het meestal hoger gelegen trottoir met als functie het",
"from OTLMOW.OTLModel.Datatypes.KeuzelijstWaarde import KeuzelijstWaarde # Generated with OTLEnumerationCreator. To modify: extend, do not",
"from OTLMOW.OTLModel.Datatypes.KeuzelijstField import KeuzelijstField from OTLMOW.OTLModel.Datatypes.KeuzelijstWaarde import KeuzelijstWaarde # Generated with OTLEnumerationCreator. To",
"tussen een rijbaan en het meestal hoger gelegen trottoir', objectUri='https://wegenenverkeer.data.vlaanderen.be/id/concept/KlLEMarkeringSoort/boordsteen'), 'boordsteen-parkeerverbod': KeuzelijstWaarde(invulwaarde='boordsteen-parkeerverbod', label='boordsteen",
"geplaatst om te voorkomen dat voertuigen de weg in zijdelingse richting verlaten, kantelen",
"weg in zijdelingse richting verlaten, kantelen of de middenberm doorkruisen.', objectUri='https://wegenenverkeer.data.vlaanderen.be/id/concept/KlLEMarkeringSoort/new-Jersey'), 'vangrail': KeuzelijstWaarde(invulwaarde='vangrail',",
"KeuzelijstWaarde(invulwaarde='boordsteen', label='boordsteen', definitie='Een lijnvormig element dat de scheiding verzorgt tussen een rijbaan en",
"definitie='Een lijnvormig element dat de scheiding verzorgt tussen een rijbaan en het meestal",
"betonnen obstakel dat meestal een infrastructurele en beschermende functie heeft', objectUri='https://wegenenverkeer.data.vlaanderen.be/id/concept/KlLEMarkeringSoort/biggenrug'), 'boordsteen': KeuzelijstWaarde(invulwaarde='boordsteen',",
"parkeerverbod', objectUri='https://wegenenverkeer.data.vlaanderen.be/id/concept/KlLEMarkeringSoort/boordsteen-parkeerverbod'), 'new-Jersey': KeuzelijstWaarde(invulwaarde='new-Jersey', label='new Jersey', definitie='Een afschermende constructie uit kunststof, beton of",
"die naast wegen wordt geplaatst om te voorkomen dat voertuigen de weg in",
"en het meestal hoger gelegen trottoir', objectUri='https://wegenenverkeer.data.vlaanderen.be/id/concept/KlLEMarkeringSoort/boordsteen'), 'boordsteen-parkeerverbod': KeuzelijstWaarde(invulwaarde='boordsteen-parkeerverbod', label='boordsteen parkeerverbod', definitie='Een lijnvormig",
"= 'Mogelijke markeringsoorten op een lijvormig element.' codelist = 'https://wegenenverkeer.data.vlaanderen.be/id/conceptscheme/KlLEMarkeringSoort' options = {",
"'Mogelijke markeringsoorten op een lijvormig element.' codelist = 'https://wegenenverkeer.data.vlaanderen.be/id/conceptscheme/KlLEMarkeringSoort' options = { 'biggenrug':",
"<gh_stars>1-10 # coding=utf-8 from OTLMOW.OTLModel.Datatypes.KeuzelijstField import KeuzelijstField from OTLMOW.OTLModel.Datatypes.KeuzelijstWaarde import KeuzelijstWaarde # Generated",
"verzorgt tussen een rijbaan en het meestal hoger gelegen trottoir met als functie",
"een infrastructurele en beschermende functie heeft', objectUri='https://wegenenverkeer.data.vlaanderen.be/id/concept/KlLEMarkeringSoort/biggenrug'), 'boordsteen': KeuzelijstWaarde(invulwaarde='boordsteen', label='boordsteen', definitie='Een lijnvormig element",
"lijnvormig element' objectUri = 'https://wegenenverkeer.data.vlaanderen.be/ns/onderdeel#KlLEMarkeringSoort' definition = 'Mogelijke markeringsoorten op een lijvormig element.'",
"het meestal hoger gelegen trottoir met als functie het aanduiden van parkeerverbod', objectUri='https://wegenenverkeer.data.vlaanderen.be/id/concept/KlLEMarkeringSoort/boordsteen-parkeerverbod'),",
"import KeuzelijstField from OTLMOW.OTLModel.Datatypes.KeuzelijstWaarde import KeuzelijstWaarde # Generated with OTLEnumerationCreator. To modify: extend,",
"label = 'Soort markering van lijnvormig element' objectUri = 'https://wegenenverkeer.data.vlaanderen.be/ns/onderdeel#KlLEMarkeringSoort' definition = 'Mogelijke",
"modify: extend, do not edit class KlLEMarkeringSoort(KeuzelijstField): \"\"\"Mogelijke markeringsoorten op een lijvormig element.\"\"\"",
"op een lijvormig element.' codelist = 'https://wegenenverkeer.data.vlaanderen.be/id/conceptscheme/KlLEMarkeringSoort' options = { 'biggenrug': KeuzelijstWaarde(invulwaarde='biggenrug', label='biggenrug',",
"hoger gelegen trottoir met als functie het aanduiden van parkeerverbod', objectUri='https://wegenenverkeer.data.vlaanderen.be/id/concept/KlLEMarkeringSoort/boordsteen-parkeerverbod'), 'new-Jersey': KeuzelijstWaarde(invulwaarde='new-Jersey',",
"rijbaan en het meestal hoger gelegen trottoir', objectUri='https://wegenenverkeer.data.vlaanderen.be/id/concept/KlLEMarkeringSoort/boordsteen'), 'boordsteen-parkeerverbod': KeuzelijstWaarde(invulwaarde='boordsteen-parkeerverbod', label='boordsteen parkeerverbod', definitie='Een",
"do not edit class KlLEMarkeringSoort(KeuzelijstField): \"\"\"Mogelijke markeringsoorten op een lijvormig element.\"\"\" naam =",
"of de middenberm doorkruisen.', objectUri='https://wegenenverkeer.data.vlaanderen.be/id/concept/KlLEMarkeringSoort/new-Jersey'), 'vangrail': KeuzelijstWaarde(invulwaarde='vangrail', label='vangrail', definitie='Een afschermende constructie die naast",
"= 'https://wegenenverkeer.data.vlaanderen.be/id/conceptscheme/KlLEMarkeringSoort' options = { 'biggenrug': KeuzelijstWaarde(invulwaarde='biggenrug', label='biggenrug', definitie='Een betonnen obstakel dat meestal",
"doorkruisen.', objectUri='https://wegenenverkeer.data.vlaanderen.be/id/concept/KlLEMarkeringSoort/new-Jersey'), 'vangrail': KeuzelijstWaarde(invulwaarde='vangrail', label='vangrail', definitie='Een afschermende constructie die naast wegen wordt geplaatst",
"beschermende functie heeft', objectUri='https://wegenenverkeer.data.vlaanderen.be/id/concept/KlLEMarkeringSoort/biggenrug'), 'boordsteen': KeuzelijstWaarde(invulwaarde='boordsteen', label='boordsteen', definitie='Een lijnvormig element dat de scheiding",
"voertuigen de weg in zijdelingse richting verlaten, kantelen of de middenberm doorkruisen.', objectUri='https://wegenenverkeer.data.vlaanderen.be/id/concept/KlLEMarkeringSoort/vangrail')",
"'new-Jersey': KeuzelijstWaarde(invulwaarde='new-Jersey', label='new Jersey', definitie='Een afschermende constructie uit kunststof, beton of metaal dat",
"gelegen trottoir met als functie het aanduiden van parkeerverbod', objectUri='https://wegenenverkeer.data.vlaanderen.be/id/concept/KlLEMarkeringSoort/boordsteen-parkeerverbod'), 'new-Jersey': KeuzelijstWaarde(invulwaarde='new-Jersey', label='new",
"definitie='Een betonnen obstakel dat meestal een infrastructurele en beschermende functie heeft', objectUri='https://wegenenverkeer.data.vlaanderen.be/id/concept/KlLEMarkeringSoort/biggenrug'), 'boordsteen':",
"of metaal dat naast wegen wordt geplaatst om te voorkomen dat voertuigen de",
"dat meestal een infrastructurele en beschermende functie heeft', objectUri='https://wegenenverkeer.data.vlaanderen.be/id/concept/KlLEMarkeringSoort/biggenrug'), 'boordsteen': KeuzelijstWaarde(invulwaarde='boordsteen', label='boordsteen', definitie='Een",
"in zijdelingse richting verlaten, kantelen of de middenberm doorkruisen.', objectUri='https://wegenenverkeer.data.vlaanderen.be/id/concept/KlLEMarkeringSoort/new-Jersey'), 'vangrail': KeuzelijstWaarde(invulwaarde='vangrail', label='vangrail',",
"element dat de scheiding verzorgt tussen een rijbaan en het meestal hoger gelegen",
"extend, do not edit class KlLEMarkeringSoort(KeuzelijstField): \"\"\"Mogelijke markeringsoorten op een lijvormig element.\"\"\" naam",
"heeft', objectUri='https://wegenenverkeer.data.vlaanderen.be/id/concept/KlLEMarkeringSoort/biggenrug'), 'boordsteen': KeuzelijstWaarde(invulwaarde='boordsteen', label='boordsteen', definitie='Een lijnvormig element dat de scheiding verzorgt tussen",
"'boordsteen': KeuzelijstWaarde(invulwaarde='boordsteen', label='boordsteen', definitie='Een lijnvormig element dat de scheiding verzorgt tussen een rijbaan",
"en beschermende functie heeft', objectUri='https://wegenenverkeer.data.vlaanderen.be/id/concept/KlLEMarkeringSoort/biggenrug'), 'boordsteen': KeuzelijstWaarde(invulwaarde='boordsteen', label='boordsteen', definitie='Een lijnvormig element dat de",
"objectUri = 'https://wegenenverkeer.data.vlaanderen.be/ns/onderdeel#KlLEMarkeringSoort' definition = 'Mogelijke markeringsoorten op een lijvormig element.' codelist =",
"objectUri='https://wegenenverkeer.data.vlaanderen.be/id/concept/KlLEMarkeringSoort/boordsteen'), 'boordsteen-parkeerverbod': KeuzelijstWaarde(invulwaarde='boordsteen-parkeerverbod', label='boordsteen parkeerverbod', definitie='Een lijnvormig element dat de scheiding verzorgt tussen",
"= { 'biggenrug': KeuzelijstWaarde(invulwaarde='biggenrug', label='biggenrug', definitie='Een betonnen obstakel dat meestal een infrastructurele en",
"To modify: extend, do not edit class KlLEMarkeringSoort(KeuzelijstField): \"\"\"Mogelijke markeringsoorten op een lijvormig",
"beton of metaal dat naast wegen wordt geplaatst om te voorkomen dat voertuigen",
"dat naast wegen wordt geplaatst om te voorkomen dat voertuigen de weg in",
"met als functie het aanduiden van parkeerverbod', objectUri='https://wegenenverkeer.data.vlaanderen.be/id/concept/KlLEMarkeringSoort/boordsteen-parkeerverbod'), 'new-Jersey': KeuzelijstWaarde(invulwaarde='new-Jersey', label='new Jersey', definitie='Een",
"label='boordsteen', definitie='Een lijnvormig element dat de scheiding verzorgt tussen een rijbaan en het",
"afschermende constructie die naast wegen wordt geplaatst om te voorkomen dat voertuigen de",
"verlaten, kantelen of de middenberm doorkruisen.', objectUri='https://wegenenverkeer.data.vlaanderen.be/id/concept/KlLEMarkeringSoort/new-Jersey'), 'vangrail': KeuzelijstWaarde(invulwaarde='vangrail', label='vangrail', definitie='Een afschermende constructie",
"= 'KlLEMarkeringSoort' label = 'Soort markering van lijnvormig element' objectUri = 'https://wegenenverkeer.data.vlaanderen.be/ns/onderdeel#KlLEMarkeringSoort' definition",
"# coding=utf-8 from OTLMOW.OTLModel.Datatypes.KeuzelijstField import KeuzelijstField from OTLMOW.OTLModel.Datatypes.KeuzelijstWaarde import KeuzelijstWaarde # Generated with",
"dat de scheiding verzorgt tussen een rijbaan en het meestal hoger gelegen trottoir",
"objectUri='https://wegenenverkeer.data.vlaanderen.be/id/concept/KlLEMarkeringSoort/biggenrug'), 'boordsteen': KeuzelijstWaarde(invulwaarde='boordsteen', label='boordsteen', definitie='Een lijnvormig element dat de scheiding verzorgt tussen een",
"'https://wegenenverkeer.data.vlaanderen.be/id/conceptscheme/KlLEMarkeringSoort' options = { 'biggenrug': KeuzelijstWaarde(invulwaarde='biggenrug', label='biggenrug', definitie='Een betonnen obstakel dat meestal een",
"'biggenrug': KeuzelijstWaarde(invulwaarde='biggenrug', label='biggenrug', definitie='Een betonnen obstakel dat meestal een infrastructurele en beschermende functie",
"voorkomen dat voertuigen de weg in zijdelingse richting verlaten, kantelen of de middenberm",
"'vangrail': KeuzelijstWaarde(invulwaarde='vangrail', label='vangrail', definitie='Een afschermende constructie die naast wegen wordt geplaatst om te",
"lijnvormig element dat de scheiding verzorgt tussen een rijbaan en het meestal hoger",
"afschermende constructie uit kunststof, beton of metaal dat naast wegen wordt geplaatst om",
"element' objectUri = 'https://wegenenverkeer.data.vlaanderen.be/ns/onderdeel#KlLEMarkeringSoort' definition = 'Mogelijke markeringsoorten op een lijvormig element.' codelist",
"een rijbaan en het meestal hoger gelegen trottoir', objectUri='https://wegenenverkeer.data.vlaanderen.be/id/concept/KlLEMarkeringSoort/boordsteen'), 'boordsteen-parkeerverbod': KeuzelijstWaarde(invulwaarde='boordsteen-parkeerverbod', label='boordsteen parkeerverbod',",
"zijdelingse richting verlaten, kantelen of de middenberm doorkruisen.', objectUri='https://wegenenverkeer.data.vlaanderen.be/id/concept/KlLEMarkeringSoort/new-Jersey'), 'vangrail': KeuzelijstWaarde(invulwaarde='vangrail', label='vangrail', definitie='Een",
"OTLMOW.OTLModel.Datatypes.KeuzelijstWaarde import KeuzelijstWaarde # Generated with OTLEnumerationCreator. To modify: extend, do not edit",
"options = { 'biggenrug': KeuzelijstWaarde(invulwaarde='biggenrug', label='biggenrug', definitie='Een betonnen obstakel dat meestal een infrastructurele",
"objectUri='https://wegenenverkeer.data.vlaanderen.be/id/concept/KlLEMarkeringSoort/new-Jersey'), 'vangrail': KeuzelijstWaarde(invulwaarde='vangrail', label='vangrail', definitie='Een afschermende constructie die naast wegen wordt geplaatst om",
"functie het aanduiden van parkeerverbod', objectUri='https://wegenenverkeer.data.vlaanderen.be/id/concept/KlLEMarkeringSoort/boordsteen-parkeerverbod'), 'new-Jersey': KeuzelijstWaarde(invulwaarde='new-Jersey', label='new Jersey', definitie='Een afschermende constructie",
"markering van lijnvormig element' objectUri = 'https://wegenenverkeer.data.vlaanderen.be/ns/onderdeel#KlLEMarkeringSoort' definition = 'Mogelijke markeringsoorten op een",
"objectUri='https://wegenenverkeer.data.vlaanderen.be/id/concept/KlLEMarkeringSoort/boordsteen-parkeerverbod'), 'new-Jersey': KeuzelijstWaarde(invulwaarde='new-Jersey', label='new Jersey', definitie='Een afschermende constructie uit kunststof, beton of metaal",
"= 'https://wegenenverkeer.data.vlaanderen.be/ns/onderdeel#KlLEMarkeringSoort' definition = 'Mogelijke markeringsoorten op een lijvormig element.' codelist = 'https://wegenenverkeer.data.vlaanderen.be/id/conceptscheme/KlLEMarkeringSoort'",
"te voorkomen dat voertuigen de weg in zijdelingse richting verlaten, kantelen of de",
"wegen wordt geplaatst om te voorkomen dat voertuigen de weg in zijdelingse richting",
"OTLMOW.OTLModel.Datatypes.KeuzelijstField import KeuzelijstField from OTLMOW.OTLModel.Datatypes.KeuzelijstWaarde import KeuzelijstWaarde # Generated with OTLEnumerationCreator. To modify:",
"= 'Soort markering van lijnvormig element' objectUri = 'https://wegenenverkeer.data.vlaanderen.be/ns/onderdeel#KlLEMarkeringSoort' definition = 'Mogelijke markeringsoorten",
"markeringsoorten op een lijvormig element.' codelist = 'https://wegenenverkeer.data.vlaanderen.be/id/conceptscheme/KlLEMarkeringSoort' options = { 'biggenrug': KeuzelijstWaarde(invulwaarde='biggenrug',",
"aanduiden van parkeerverbod', objectUri='https://wegenenverkeer.data.vlaanderen.be/id/concept/KlLEMarkeringSoort/boordsteen-parkeerverbod'), 'new-Jersey': KeuzelijstWaarde(invulwaarde='new-Jersey', label='new Jersey', definitie='Een afschermende constructie uit kunststof,",
"functie heeft', objectUri='https://wegenenverkeer.data.vlaanderen.be/id/concept/KlLEMarkeringSoort/biggenrug'), 'boordsteen': KeuzelijstWaarde(invulwaarde='boordsteen', label='boordsteen', definitie='Een lijnvormig element dat de scheiding verzorgt",
"dat de scheiding verzorgt tussen een rijbaan en het meestal hoger gelegen trottoir',",
"parkeerverbod', definitie='Een lijnvormig element dat de scheiding verzorgt tussen een rijbaan en het",
"'Soort markering van lijnvormig element' objectUri = 'https://wegenenverkeer.data.vlaanderen.be/ns/onderdeel#KlLEMarkeringSoort' definition = 'Mogelijke markeringsoorten op",
"coding=utf-8 from OTLMOW.OTLModel.Datatypes.KeuzelijstField import KeuzelijstField from OTLMOW.OTLModel.Datatypes.KeuzelijstWaarde import KeuzelijstWaarde # Generated with OTLEnumerationCreator.",
"naam = 'KlLEMarkeringSoort' label = 'Soort markering van lijnvormig element' objectUri = 'https://wegenenverkeer.data.vlaanderen.be/ns/onderdeel#KlLEMarkeringSoort'",
"de weg in zijdelingse richting verlaten, kantelen of de middenberm doorkruisen.', objectUri='https://wegenenverkeer.data.vlaanderen.be/id/concept/KlLEMarkeringSoort/vangrail') }",
"'https://wegenenverkeer.data.vlaanderen.be/ns/onderdeel#KlLEMarkeringSoort' definition = 'Mogelijke markeringsoorten op een lijvormig element.' codelist = 'https://wegenenverkeer.data.vlaanderen.be/id/conceptscheme/KlLEMarkeringSoort' options",
"class KlLEMarkeringSoort(KeuzelijstField): \"\"\"Mogelijke markeringsoorten op een lijvormig element.\"\"\" naam = 'KlLEMarkeringSoort' label =",
"codelist = 'https://wegenenverkeer.data.vlaanderen.be/id/conceptscheme/KlLEMarkeringSoort' options = { 'biggenrug': KeuzelijstWaarde(invulwaarde='biggenrug', label='biggenrug', definitie='Een betonnen obstakel dat",
"verzorgt tussen een rijbaan en het meestal hoger gelegen trottoir', objectUri='https://wegenenverkeer.data.vlaanderen.be/id/concept/KlLEMarkeringSoort/boordsteen'), 'boordsteen-parkeerverbod': KeuzelijstWaarde(invulwaarde='boordsteen-parkeerverbod',",
"infrastructurele en beschermende functie heeft', objectUri='https://wegenenverkeer.data.vlaanderen.be/id/concept/KlLEMarkeringSoort/biggenrug'), 'boordsteen': KeuzelijstWaarde(invulwaarde='boordsteen', label='boordsteen', definitie='Een lijnvormig element dat",
"{ 'biggenrug': KeuzelijstWaarde(invulwaarde='biggenrug', label='biggenrug', definitie='Een betonnen obstakel dat meestal een infrastructurele en beschermende",
"\"\"\"Mogelijke markeringsoorten op een lijvormig element.\"\"\" naam = 'KlLEMarkeringSoort' label = 'Soort markering",
"definition = 'Mogelijke markeringsoorten op een lijvormig element.' codelist = 'https://wegenenverkeer.data.vlaanderen.be/id/conceptscheme/KlLEMarkeringSoort' options =",
"op een lijvormig element.\"\"\" naam = 'KlLEMarkeringSoort' label = 'Soort markering van lijnvormig",
"van parkeerverbod', objectUri='https://wegenenverkeer.data.vlaanderen.be/id/concept/KlLEMarkeringSoort/boordsteen-parkeerverbod'), 'new-Jersey': KeuzelijstWaarde(invulwaarde='new-Jersey', label='new Jersey', definitie='Een afschermende constructie uit kunststof, beton",
"kunststof, beton of metaal dat naast wegen wordt geplaatst om te voorkomen dat",
"# Generated with OTLEnumerationCreator. To modify: extend, do not edit class KlLEMarkeringSoort(KeuzelijstField): \"\"\"Mogelijke",
"metaal dat naast wegen wordt geplaatst om te voorkomen dat voertuigen de weg",
"om te voorkomen dat voertuigen de weg in zijdelingse richting verlaten, kantelen of",
"uit kunststof, beton of metaal dat naast wegen wordt geplaatst om te voorkomen",
"middenberm doorkruisen.', objectUri='https://wegenenverkeer.data.vlaanderen.be/id/concept/KlLEMarkeringSoort/new-Jersey'), 'vangrail': KeuzelijstWaarde(invulwaarde='vangrail', label='vangrail', definitie='Een afschermende constructie die naast wegen wordt",
"label='boordsteen parkeerverbod', definitie='Een lijnvormig element dat de scheiding verzorgt tussen een rijbaan en",
"gelegen trottoir', objectUri='https://wegenenverkeer.data.vlaanderen.be/id/concept/KlLEMarkeringSoort/boordsteen'), 'boordsteen-parkeerverbod': KeuzelijstWaarde(invulwaarde='boordsteen-parkeerverbod', label='boordsteen parkeerverbod', definitie='Een lijnvormig element dat de scheiding",
"dat voertuigen de weg in zijdelingse richting verlaten, kantelen of de middenberm doorkruisen.',",
"'KlLEMarkeringSoort' label = 'Soort markering van lijnvormig element' objectUri = 'https://wegenenverkeer.data.vlaanderen.be/ns/onderdeel#KlLEMarkeringSoort' definition =",
"een lijvormig element.\"\"\" naam = 'KlLEMarkeringSoort' label = 'Soort markering van lijnvormig element'",
"een rijbaan en het meestal hoger gelegen trottoir met als functie het aanduiden",
"OTLEnumerationCreator. To modify: extend, do not edit class KlLEMarkeringSoort(KeuzelijstField): \"\"\"Mogelijke markeringsoorten op een",
"KeuzelijstField from OTLMOW.OTLModel.Datatypes.KeuzelijstWaarde import KeuzelijstWaarde # Generated with OTLEnumerationCreator. To modify: extend, do",
"lijvormig element.\"\"\" naam = 'KlLEMarkeringSoort' label = 'Soort markering van lijnvormig element' objectUri",
"hoger gelegen trottoir', objectUri='https://wegenenverkeer.data.vlaanderen.be/id/concept/KlLEMarkeringSoort/boordsteen'), 'boordsteen-parkeerverbod': KeuzelijstWaarde(invulwaarde='boordsteen-parkeerverbod', label='boordsteen parkeerverbod', definitie='Een lijnvormig element dat de"
] |
[
"self.noise_floor = csv_line[14] self.ampdu_cnt = csv_line[15] self.channel = csv_line[16] self.secondary_channel = csv_line[17] self.local_timestamp",
"= csv_line[23] self.len = csv_line[24] string_data = csv_line[25] self.csi_matrix = ESP32CSIFrame.parse_matrix(string_data) @staticmethod def",
"self.fec_coding = csv_line[12] self.sgi = csv_line[13] self.noise_floor = csv_line[14] self.ampdu_cnt = csv_line[15] self.channel",
"self.local_timestamp = csv_line[18] self.ant = csv_line[19] self.sig_len = csv_line[20] self.rx_state = csv_line[21] self.real_time_set",
"def parse_matrix(string_data, bandwidth=20): array_string = string_data.replace(\" \", \", \") array_string_asarray = ast.literal_eval(array_string) if",
"\"local_timestamp\", \"ant\", \"sig_len\", \"rx_state\", \"real_time_set\", \"real_timestamp\", \"len\", \"CSI_DATA\"] def __init__(self, csv_line: list): self.type",
"ESP32CSIFrame(CSIFrame): # https://docs.espressif.com/projects/esp-idf/en/latest/esp32/api-reference/network/esp_wifi.html#_CPPv418wifi_pkt_rx_ctrl_t __slots__ = [\"type\", \"role\", \"mac\", \"rssi\", \"rate\", \"sig_mode\", \"mcs\", \"bandwidth\",",
"\"ampdu_cnt\", \"channel\", \"secondary_channel\", \"local_timestamp\", \"ant\", \"sig_len\", \"rx_state\", \"real_time_set\", \"real_timestamp\", \"len\", \"CSI_DATA\"] def __init__(self,",
"csv_line[15] self.channel = csv_line[16] self.secondary_channel = csv_line[17] self.local_timestamp = csv_line[18] self.ant = csv_line[19]",
"complex_matrix # Seems some CSI lines are missing a value. # Very rare,",
"self.mcs = csv_line[6] self.bandwidth = 20 if csv_line[7] == \"0\" else 40 self.smoothing",
"= csv_line[11] self.fec_coding = csv_line[12] self.sgi = csv_line[13] self.noise_floor = csv_line[14] self.ampdu_cnt =",
"Seems some CSI lines are missing a value. # Very rare, I assume",
"CSI lines are missing a value. # Very rare, I assume weird dropped",
"string_data = csv_line[25] self.csi_matrix = ESP32CSIFrame.parse_matrix(string_data) @staticmethod def parse_matrix(string_data, bandwidth=20): array_string = string_data.replace(\"",
"\"not_sounding\", \"aggregation\", \"stbc\", \"fec_coding\", \"sgi\", \"noise_floor\", \"ampdu_cnt\", \"channel\", \"secondary_channel\", \"local_timestamp\", \"ant\", \"sig_len\", \"rx_state\",",
"csv_line[5] self.mcs = csv_line[6] self.bandwidth = 20 if csv_line[7] == \"0\" else 40",
"40 and len(array_string_asarray) < 256: ESP32CSIFrame.fill_missing(array_string_asarray, 256) int8_matrix = np.array(array_string_asarray) int8_matrix = int8_matrix.reshape(-1,",
"[\"type\", \"role\", \"mac\", \"rssi\", \"rate\", \"sig_mode\", \"mcs\", \"bandwidth\", \"smoothing\", \"not_sounding\", \"aggregation\", \"stbc\", \"fec_coding\",",
"40 self.smoothing = csv_line[8] self.not_sounding = csv_line[9] self.aggregation = csv_line[10] self.stbc = csv_line[11]",
"@staticmethod def fill_missing(array, expected_length): remainder = expected_length - len(array) for _ in range(remainder):",
"return complex_matrix # Seems some CSI lines are missing a value. # Very",
"csv_line[16] self.secondary_channel = csv_line[17] self.local_timestamp = csv_line[18] self.ant = csv_line[19] self.sig_len = csv_line[20]",
"ast import numpy as np class ESP32CSIFrame(CSIFrame): # https://docs.espressif.com/projects/esp-idf/en/latest/esp32/api-reference/network/esp_wifi.html#_CPPv418wifi_pkt_rx_ctrl_t __slots__ = [\"type\", \"role\",",
"\"aggregation\", \"stbc\", \"fec_coding\", \"sgi\", \"noise_floor\", \"ampdu_cnt\", \"channel\", \"secondary_channel\", \"local_timestamp\", \"ant\", \"sig_len\", \"rx_state\", \"real_time_set\",",
"= csv_line[2] self.rssi = csv_line[3] self.rate = csv_line[4] self.sig_mode = csv_line[5] self.mcs =",
"Probably not the best way to fill the gap. @staticmethod def fill_missing(array, expected_length):",
"\"stbc\", \"fec_coding\", \"sgi\", \"noise_floor\", \"ampdu_cnt\", \"channel\", \"secondary_channel\", \"local_timestamp\", \"ant\", \"sig_len\", \"rx_state\", \"real_time_set\", \"real_timestamp\",",
"np.array(array_string_asarray) int8_matrix = int8_matrix.reshape(-1, 2) complex_matrix = int8_matrix.astype(np.float32).view(np.complex64) return complex_matrix # Seems some",
"= int8_matrix.astype(np.float32).view(np.complex64) return complex_matrix # Seems some CSI lines are missing a value.",
"\", \", \") array_string_asarray = ast.literal_eval(array_string) if bandwidth == 20 and len(array_string_asarray) <",
"\") array_string_asarray = ast.literal_eval(array_string) if bandwidth == 20 and len(array_string_asarray) < 128: ESP32CSIFrame.fill_missing(array_string_asarray,",
"csv_line[8] self.not_sounding = csv_line[9] self.aggregation = csv_line[10] self.stbc = csv_line[11] self.fec_coding = csv_line[12]",
"= csv_line[0] self.role = csv_line[1] self.mac = csv_line[2] self.rssi = csv_line[3] self.rate =",
"\"sgi\", \"noise_floor\", \"ampdu_cnt\", \"channel\", \"secondary_channel\", \"local_timestamp\", \"ant\", \"sig_len\", \"rx_state\", \"real_time_set\", \"real_timestamp\", \"len\", \"CSI_DATA\"]",
"\"sig_len\", \"rx_state\", \"real_time_set\", \"real_timestamp\", \"len\", \"CSI_DATA\"] def __init__(self, csv_line: list): self.type = csv_line[0]",
"I assume weird dropped behaviour. # Probably not the best way to fill",
"csv_line[6] self.bandwidth = 20 if csv_line[7] == \"0\" else 40 self.smoothing = csv_line[8]",
"csv_line[19] self.sig_len = csv_line[20] self.rx_state = csv_line[21] self.real_time_set = csv_line[22] self.real_timestamp = csv_line[23]",
"self.secondary_channel = csv_line[17] self.local_timestamp = csv_line[18] self.ant = csv_line[19] self.sig_len = csv_line[20] self.rx_state",
"int8_matrix.reshape(-1, 2) complex_matrix = int8_matrix.astype(np.float32).view(np.complex64) return complex_matrix # Seems some CSI lines are",
"complex_matrix = int8_matrix.astype(np.float32).view(np.complex64) return complex_matrix # Seems some CSI lines are missing a",
"= csv_line[17] self.local_timestamp = csv_line[18] self.ant = csv_line[19] self.sig_len = csv_line[20] self.rx_state =",
"\", \") array_string_asarray = ast.literal_eval(array_string) if bandwidth == 20 and len(array_string_asarray) < 128:",
"= csv_line[10] self.stbc = csv_line[11] self.fec_coding = csv_line[12] self.sgi = csv_line[13] self.noise_floor =",
"csv_line[20] self.rx_state = csv_line[21] self.real_time_set = csv_line[22] self.real_timestamp = csv_line[23] self.len = csv_line[24]",
"self.aggregation = csv_line[10] self.stbc = csv_line[11] self.fec_coding = csv_line[12] self.sgi = csv_line[13] self.noise_floor",
"string_data.replace(\" \", \", \") array_string_asarray = ast.literal_eval(array_string) if bandwidth == 20 and len(array_string_asarray)",
"numpy as np class ESP32CSIFrame(CSIFrame): # https://docs.espressif.com/projects/esp-idf/en/latest/esp32/api-reference/network/esp_wifi.html#_CPPv418wifi_pkt_rx_ctrl_t __slots__ = [\"type\", \"role\", \"mac\", \"rssi\",",
"way to fill the gap. @staticmethod def fill_missing(array, expected_length): remainder = expected_length -",
"a value. # Very rare, I assume weird dropped behaviour. # Probably not",
"\"0\" else 40 self.smoothing = csv_line[8] self.not_sounding = csv_line[9] self.aggregation = csv_line[10] self.stbc",
"np class ESP32CSIFrame(CSIFrame): # https://docs.espressif.com/projects/esp-idf/en/latest/esp32/api-reference/network/esp_wifi.html#_CPPv418wifi_pkt_rx_ctrl_t __slots__ = [\"type\", \"role\", \"mac\", \"rssi\", \"rate\", \"sig_mode\",",
"self.ant = csv_line[19] self.sig_len = csv_line[20] self.rx_state = csv_line[21] self.real_time_set = csv_line[22] self.real_timestamp",
"array_string = string_data.replace(\" \", \", \") array_string_asarray = ast.literal_eval(array_string) if bandwidth == 20",
"fill the gap. @staticmethod def fill_missing(array, expected_length): remainder = expected_length - len(array) for",
"= csv_line[24] string_data = csv_line[25] self.csi_matrix = ESP32CSIFrame.parse_matrix(string_data) @staticmethod def parse_matrix(string_data, bandwidth=20): array_string",
"csv_line[17] self.local_timestamp = csv_line[18] self.ant = csv_line[19] self.sig_len = csv_line[20] self.rx_state = csv_line[21]",
"elif bandwidth == 40 and len(array_string_asarray) < 256: ESP32CSIFrame.fill_missing(array_string_asarray, 256) int8_matrix = np.array(array_string_asarray)",
"len(array_string_asarray) < 256: ESP32CSIFrame.fill_missing(array_string_asarray, 256) int8_matrix = np.array(array_string_asarray) int8_matrix = int8_matrix.reshape(-1, 2) complex_matrix",
"== \"0\" else 40 self.smoothing = csv_line[8] self.not_sounding = csv_line[9] self.aggregation = csv_line[10]",
"= csv_line[19] self.sig_len = csv_line[20] self.rx_state = csv_line[21] self.real_time_set = csv_line[22] self.real_timestamp =",
"csv_line[21] self.real_time_set = csv_line[22] self.real_timestamp = csv_line[23] self.len = csv_line[24] string_data = csv_line[25]",
"class ESP32CSIFrame(CSIFrame): # https://docs.espressif.com/projects/esp-idf/en/latest/esp32/api-reference/network/esp_wifi.html#_CPPv418wifi_pkt_rx_ctrl_t __slots__ = [\"type\", \"role\", \"mac\", \"rssi\", \"rate\", \"sig_mode\", \"mcs\",",
"= [\"type\", \"role\", \"mac\", \"rssi\", \"rate\", \"sig_mode\", \"mcs\", \"bandwidth\", \"smoothing\", \"not_sounding\", \"aggregation\", \"stbc\",",
"\"rate\", \"sig_mode\", \"mcs\", \"bandwidth\", \"smoothing\", \"not_sounding\", \"aggregation\", \"stbc\", \"fec_coding\", \"sgi\", \"noise_floor\", \"ampdu_cnt\", \"channel\",",
"import ast import numpy as np class ESP32CSIFrame(CSIFrame): # https://docs.espressif.com/projects/esp-idf/en/latest/esp32/api-reference/network/esp_wifi.html#_CPPv418wifi_pkt_rx_ctrl_t __slots__ = [\"type\",",
"csv_line: list): self.type = csv_line[0] self.role = csv_line[1] self.mac = csv_line[2] self.rssi =",
"256: ESP32CSIFrame.fill_missing(array_string_asarray, 256) int8_matrix = np.array(array_string_asarray) int8_matrix = int8_matrix.reshape(-1, 2) complex_matrix = int8_matrix.astype(np.float32).view(np.complex64)",
"csv_line[10] self.stbc = csv_line[11] self.fec_coding = csv_line[12] self.sgi = csv_line[13] self.noise_floor = csv_line[14]",
"= csv_line[1] self.mac = csv_line[2] self.rssi = csv_line[3] self.rate = csv_line[4] self.sig_mode =",
"= csv_line[12] self.sgi = csv_line[13] self.noise_floor = csv_line[14] self.ampdu_cnt = csv_line[15] self.channel =",
"self.type = csv_line[0] self.role = csv_line[1] self.mac = csv_line[2] self.rssi = csv_line[3] self.rate",
"< 256: ESP32CSIFrame.fill_missing(array_string_asarray, 256) int8_matrix = np.array(array_string_asarray) int8_matrix = int8_matrix.reshape(-1, 2) complex_matrix =",
"csv_line[0] self.role = csv_line[1] self.mac = csv_line[2] self.rssi = csv_line[3] self.rate = csv_line[4]",
"CSIFrame import ast import numpy as np class ESP32CSIFrame(CSIFrame): # https://docs.espressif.com/projects/esp-idf/en/latest/esp32/api-reference/network/esp_wifi.html#_CPPv418wifi_pkt_rx_ctrl_t __slots__ =",
"\"bandwidth\", \"smoothing\", \"not_sounding\", \"aggregation\", \"stbc\", \"fec_coding\", \"sgi\", \"noise_floor\", \"ampdu_cnt\", \"channel\", \"secondary_channel\", \"local_timestamp\", \"ant\",",
"if bandwidth == 20 and len(array_string_asarray) < 128: ESP32CSIFrame.fill_missing(array_string_asarray, 128) elif bandwidth ==",
"= ast.literal_eval(array_string) if bandwidth == 20 and len(array_string_asarray) < 128: ESP32CSIFrame.fill_missing(array_string_asarray, 128) elif",
"self.role = csv_line[1] self.mac = csv_line[2] self.rssi = csv_line[3] self.rate = csv_line[4] self.sig_mode",
"= csv_line[22] self.real_timestamp = csv_line[23] self.len = csv_line[24] string_data = csv_line[25] self.csi_matrix =",
"ast.literal_eval(array_string) if bandwidth == 20 and len(array_string_asarray) < 128: ESP32CSIFrame.fill_missing(array_string_asarray, 128) elif bandwidth",
"self.rate = csv_line[4] self.sig_mode = csv_line[5] self.mcs = csv_line[6] self.bandwidth = 20 if",
"= csv_line[8] self.not_sounding = csv_line[9] self.aggregation = csv_line[10] self.stbc = csv_line[11] self.fec_coding =",
"bandwidth == 40 and len(array_string_asarray) < 256: ESP32CSIFrame.fill_missing(array_string_asarray, 256) int8_matrix = np.array(array_string_asarray) int8_matrix",
"csv_line[11] self.fec_coding = csv_line[12] self.sgi = csv_line[13] self.noise_floor = csv_line[14] self.ampdu_cnt = csv_line[15]",
"csv_line[3] self.rate = csv_line[4] self.sig_mode = csv_line[5] self.mcs = csv_line[6] self.bandwidth = 20",
"int8_matrix = np.array(array_string_asarray) int8_matrix = int8_matrix.reshape(-1, 2) complex_matrix = int8_matrix.astype(np.float32).view(np.complex64) return complex_matrix #",
"import CSIFrame import ast import numpy as np class ESP32CSIFrame(CSIFrame): # https://docs.espressif.com/projects/esp-idf/en/latest/esp32/api-reference/network/esp_wifi.html#_CPPv418wifi_pkt_rx_ctrl_t __slots__",
"self.channel = csv_line[16] self.secondary_channel = csv_line[17] self.local_timestamp = csv_line[18] self.ant = csv_line[19] self.sig_len",
"csv_line[9] self.aggregation = csv_line[10] self.stbc = csv_line[11] self.fec_coding = csv_line[12] self.sgi = csv_line[13]",
"\"smoothing\", \"not_sounding\", \"aggregation\", \"stbc\", \"fec_coding\", \"sgi\", \"noise_floor\", \"ampdu_cnt\", \"channel\", \"secondary_channel\", \"local_timestamp\", \"ant\", \"sig_len\",",
"= csv_line[4] self.sig_mode = csv_line[5] self.mcs = csv_line[6] self.bandwidth = 20 if csv_line[7]",
"= csv_line[20] self.rx_state = csv_line[21] self.real_time_set = csv_line[22] self.real_timestamp = csv_line[23] self.len =",
"lines are missing a value. # Very rare, I assume weird dropped behaviour.",
"len(array_string_asarray) < 128: ESP32CSIFrame.fill_missing(array_string_asarray, 128) elif bandwidth == 40 and len(array_string_asarray) < 256:",
"< 128: ESP32CSIFrame.fill_missing(array_string_asarray, 128) elif bandwidth == 40 and len(array_string_asarray) < 256: ESP32CSIFrame.fill_missing(array_string_asarray,",
"self.sgi = csv_line[13] self.noise_floor = csv_line[14] self.ampdu_cnt = csv_line[15] self.channel = csv_line[16] self.secondary_channel",
"self.csi_matrix = ESP32CSIFrame.parse_matrix(string_data) @staticmethod def parse_matrix(string_data, bandwidth=20): array_string = string_data.replace(\" \", \", \")",
"if csv_line[7] == \"0\" else 40 self.smoothing = csv_line[8] self.not_sounding = csv_line[9] self.aggregation",
"\"mac\", \"rssi\", \"rate\", \"sig_mode\", \"mcs\", \"bandwidth\", \"smoothing\", \"not_sounding\", \"aggregation\", \"stbc\", \"fec_coding\", \"sgi\", \"noise_floor\",",
"\"ant\", \"sig_len\", \"rx_state\", \"real_time_set\", \"real_timestamp\", \"len\", \"CSI_DATA\"] def __init__(self, csv_line: list): self.type =",
"array_string_asarray = ast.literal_eval(array_string) if bandwidth == 20 and len(array_string_asarray) < 128: ESP32CSIFrame.fill_missing(array_string_asarray, 128)",
"= csv_line[9] self.aggregation = csv_line[10] self.stbc = csv_line[11] self.fec_coding = csv_line[12] self.sgi =",
"int8_matrix = int8_matrix.reshape(-1, 2) complex_matrix = int8_matrix.astype(np.float32).view(np.complex64) return complex_matrix # Seems some CSI",
"the gap. @staticmethod def fill_missing(array, expected_length): remainder = expected_length - len(array) for _",
"self.real_time_set = csv_line[22] self.real_timestamp = csv_line[23] self.len = csv_line[24] string_data = csv_line[25] self.csi_matrix",
"20 and len(array_string_asarray) < 128: ESP32CSIFrame.fill_missing(array_string_asarray, 128) elif bandwidth == 40 and len(array_string_asarray)",
"256) int8_matrix = np.array(array_string_asarray) int8_matrix = int8_matrix.reshape(-1, 2) complex_matrix = int8_matrix.astype(np.float32).view(np.complex64) return complex_matrix",
"# Seems some CSI lines are missing a value. # Very rare, I",
"\"real_timestamp\", \"len\", \"CSI_DATA\"] def __init__(self, csv_line: list): self.type = csv_line[0] self.role = csv_line[1]",
"== 20 and len(array_string_asarray) < 128: ESP32CSIFrame.fill_missing(array_string_asarray, 128) elif bandwidth == 40 and",
"as np class ESP32CSIFrame(CSIFrame): # https://docs.espressif.com/projects/esp-idf/en/latest/esp32/api-reference/network/esp_wifi.html#_CPPv418wifi_pkt_rx_ctrl_t __slots__ = [\"type\", \"role\", \"mac\", \"rssi\", \"rate\",",
"csv_line[7] == \"0\" else 40 self.smoothing = csv_line[8] self.not_sounding = csv_line[9] self.aggregation =",
"csv_line[22] self.real_timestamp = csv_line[23] self.len = csv_line[24] string_data = csv_line[25] self.csi_matrix = ESP32CSIFrame.parse_matrix(string_data)",
"missing a value. # Very rare, I assume weird dropped behaviour. # Probably",
"csv_line[1] self.mac = csv_line[2] self.rssi = csv_line[3] self.rate = csv_line[4] self.sig_mode = csv_line[5]",
"behaviour. # Probably not the best way to fill the gap. @staticmethod def",
"= csv_line[14] self.ampdu_cnt = csv_line[15] self.channel = csv_line[16] self.secondary_channel = csv_line[17] self.local_timestamp =",
"not the best way to fill the gap. @staticmethod def fill_missing(array, expected_length): remainder",
"rare, I assume weird dropped behaviour. # Probably not the best way to",
"gap. @staticmethod def fill_missing(array, expected_length): remainder = expected_length - len(array) for _ in",
"\"CSI_DATA\"] def __init__(self, csv_line: list): self.type = csv_line[0] self.role = csv_line[1] self.mac =",
"assume weird dropped behaviour. # Probably not the best way to fill the",
"__slots__ = [\"type\", \"role\", \"mac\", \"rssi\", \"rate\", \"sig_mode\", \"mcs\", \"bandwidth\", \"smoothing\", \"not_sounding\", \"aggregation\",",
"= csv_line[3] self.rate = csv_line[4] self.sig_mode = csv_line[5] self.mcs = csv_line[6] self.bandwidth =",
"bandwidth=20): array_string = string_data.replace(\" \", \", \") array_string_asarray = ast.literal_eval(array_string) if bandwidth ==",
"the best way to fill the gap. @staticmethod def fill_missing(array, expected_length): remainder =",
"= int8_matrix.reshape(-1, 2) complex_matrix = int8_matrix.astype(np.float32).view(np.complex64) return complex_matrix # Seems some CSI lines",
"csv_line[2] self.rssi = csv_line[3] self.rate = csv_line[4] self.sig_mode = csv_line[5] self.mcs = csv_line[6]",
"parse_matrix(string_data, bandwidth=20): array_string = string_data.replace(\" \", \", \") array_string_asarray = ast.literal_eval(array_string) if bandwidth",
"to fill the gap. @staticmethod def fill_missing(array, expected_length): remainder = expected_length - len(array)",
"== 40 and len(array_string_asarray) < 256: ESP32CSIFrame.fill_missing(array_string_asarray, 256) int8_matrix = np.array(array_string_asarray) int8_matrix =",
"csv_line[14] self.ampdu_cnt = csv_line[15] self.channel = csv_line[16] self.secondary_channel = csv_line[17] self.local_timestamp = csv_line[18]",
"csv_line[18] self.ant = csv_line[19] self.sig_len = csv_line[20] self.rx_state = csv_line[21] self.real_time_set = csv_line[22]",
"bandwidth == 20 and len(array_string_asarray) < 128: ESP32CSIFrame.fill_missing(array_string_asarray, 128) elif bandwidth == 40",
"some CSI lines are missing a value. # Very rare, I assume weird",
"csv_line[4] self.sig_mode = csv_line[5] self.mcs = csv_line[6] self.bandwidth = 20 if csv_line[7] ==",
"ESP32CSIFrame.fill_missing(array_string_asarray, 256) int8_matrix = np.array(array_string_asarray) int8_matrix = int8_matrix.reshape(-1, 2) complex_matrix = int8_matrix.astype(np.float32).view(np.complex64) return",
"int8_matrix.astype(np.float32).view(np.complex64) return complex_matrix # Seems some CSI lines are missing a value. #",
"= csv_line[21] self.real_time_set = csv_line[22] self.real_timestamp = csv_line[23] self.len = csv_line[24] string_data =",
"best way to fill the gap. @staticmethod def fill_missing(array, expected_length): remainder = expected_length",
"and len(array_string_asarray) < 128: ESP32CSIFrame.fill_missing(array_string_asarray, 128) elif bandwidth == 40 and len(array_string_asarray) <",
"\"mcs\", \"bandwidth\", \"smoothing\", \"not_sounding\", \"aggregation\", \"stbc\", \"fec_coding\", \"sgi\", \"noise_floor\", \"ampdu_cnt\", \"channel\", \"secondary_channel\", \"local_timestamp\",",
"self.rssi = csv_line[3] self.rate = csv_line[4] self.sig_mode = csv_line[5] self.mcs = csv_line[6] self.bandwidth",
"\"real_time_set\", \"real_timestamp\", \"len\", \"CSI_DATA\"] def __init__(self, csv_line: list): self.type = csv_line[0] self.role =",
"20 if csv_line[7] == \"0\" else 40 self.smoothing = csv_line[8] self.not_sounding = csv_line[9]",
"128: ESP32CSIFrame.fill_missing(array_string_asarray, 128) elif bandwidth == 40 and len(array_string_asarray) < 256: ESP32CSIFrame.fill_missing(array_string_asarray, 256)",
"and len(array_string_asarray) < 256: ESP32CSIFrame.fill_missing(array_string_asarray, 256) int8_matrix = np.array(array_string_asarray) int8_matrix = int8_matrix.reshape(-1, 2)",
"= csv_line[5] self.mcs = csv_line[6] self.bandwidth = 20 if csv_line[7] == \"0\" else",
"= csv_line[13] self.noise_floor = csv_line[14] self.ampdu_cnt = csv_line[15] self.channel = csv_line[16] self.secondary_channel =",
"csv_line[23] self.len = csv_line[24] string_data = csv_line[25] self.csi_matrix = ESP32CSIFrame.parse_matrix(string_data) @staticmethod def parse_matrix(string_data,",
"= csv_line[6] self.bandwidth = 20 if csv_line[7] == \"0\" else 40 self.smoothing =",
"ESP32CSIFrame.fill_missing(array_string_asarray, 128) elif bandwidth == 40 and len(array_string_asarray) < 256: ESP32CSIFrame.fill_missing(array_string_asarray, 256) int8_matrix",
"128) elif bandwidth == 40 and len(array_string_asarray) < 256: ESP32CSIFrame.fill_missing(array_string_asarray, 256) int8_matrix =",
"self.ampdu_cnt = csv_line[15] self.channel = csv_line[16] self.secondary_channel = csv_line[17] self.local_timestamp = csv_line[18] self.ant",
"https://docs.espressif.com/projects/esp-idf/en/latest/esp32/api-reference/network/esp_wifi.html#_CPPv418wifi_pkt_rx_ctrl_t __slots__ = [\"type\", \"role\", \"mac\", \"rssi\", \"rate\", \"sig_mode\", \"mcs\", \"bandwidth\", \"smoothing\", \"not_sounding\",",
"dropped behaviour. # Probably not the best way to fill the gap. @staticmethod",
"self.bandwidth = 20 if csv_line[7] == \"0\" else 40 self.smoothing = csv_line[8] self.not_sounding",
"\"fec_coding\", \"sgi\", \"noise_floor\", \"ampdu_cnt\", \"channel\", \"secondary_channel\", \"local_timestamp\", \"ant\", \"sig_len\", \"rx_state\", \"real_time_set\", \"real_timestamp\", \"len\",",
"\"len\", \"CSI_DATA\"] def __init__(self, csv_line: list): self.type = csv_line[0] self.role = csv_line[1] self.mac",
"csv_line[13] self.noise_floor = csv_line[14] self.ampdu_cnt = csv_line[15] self.channel = csv_line[16] self.secondary_channel = csv_line[17]",
"self.smoothing = csv_line[8] self.not_sounding = csv_line[9] self.aggregation = csv_line[10] self.stbc = csv_line[11] self.fec_coding",
"= csv_line[18] self.ant = csv_line[19] self.sig_len = csv_line[20] self.rx_state = csv_line[21] self.real_time_set =",
"else 40 self.smoothing = csv_line[8] self.not_sounding = csv_line[9] self.aggregation = csv_line[10] self.stbc =",
"# https://docs.espressif.com/projects/esp-idf/en/latest/esp32/api-reference/network/esp_wifi.html#_CPPv418wifi_pkt_rx_ctrl_t __slots__ = [\"type\", \"role\", \"mac\", \"rssi\", \"rate\", \"sig_mode\", \"mcs\", \"bandwidth\", \"smoothing\",",
"self.not_sounding = csv_line[9] self.aggregation = csv_line[10] self.stbc = csv_line[11] self.fec_coding = csv_line[12] self.sgi",
"\"role\", \"mac\", \"rssi\", \"rate\", \"sig_mode\", \"mcs\", \"bandwidth\", \"smoothing\", \"not_sounding\", \"aggregation\", \"stbc\", \"fec_coding\", \"sgi\",",
"csv_line[24] string_data = csv_line[25] self.csi_matrix = ESP32CSIFrame.parse_matrix(string_data) @staticmethod def parse_matrix(string_data, bandwidth=20): array_string =",
"self.sig_len = csv_line[20] self.rx_state = csv_line[21] self.real_time_set = csv_line[22] self.real_timestamp = csv_line[23] self.len",
"self.real_timestamp = csv_line[23] self.len = csv_line[24] string_data = csv_line[25] self.csi_matrix = ESP32CSIFrame.parse_matrix(string_data) @staticmethod",
"self.mac = csv_line[2] self.rssi = csv_line[3] self.rate = csv_line[4] self.sig_mode = csv_line[5] self.mcs",
"list): self.type = csv_line[0] self.role = csv_line[1] self.mac = csv_line[2] self.rssi = csv_line[3]",
"Very rare, I assume weird dropped behaviour. # Probably not the best way",
"are missing a value. # Very rare, I assume weird dropped behaviour. #",
"= np.array(array_string_asarray) int8_matrix = int8_matrix.reshape(-1, 2) complex_matrix = int8_matrix.astype(np.float32).view(np.complex64) return complex_matrix # Seems",
"value. # Very rare, I assume weird dropped behaviour. # Probably not the",
"= ESP32CSIFrame.parse_matrix(string_data) @staticmethod def parse_matrix(string_data, bandwidth=20): array_string = string_data.replace(\" \", \", \") array_string_asarray",
"\"secondary_channel\", \"local_timestamp\", \"ant\", \"sig_len\", \"rx_state\", \"real_time_set\", \"real_timestamp\", \"len\", \"CSI_DATA\"] def __init__(self, csv_line: list):",
"__init__(self, csv_line: list): self.type = csv_line[0] self.role = csv_line[1] self.mac = csv_line[2] self.rssi",
"def __init__(self, csv_line: list): self.type = csv_line[0] self.role = csv_line[1] self.mac = csv_line[2]",
"self.sig_mode = csv_line[5] self.mcs = csv_line[6] self.bandwidth = 20 if csv_line[7] == \"0\"",
"= 20 if csv_line[7] == \"0\" else 40 self.smoothing = csv_line[8] self.not_sounding =",
"csv_line[12] self.sgi = csv_line[13] self.noise_floor = csv_line[14] self.ampdu_cnt = csv_line[15] self.channel = csv_line[16]",
"\"channel\", \"secondary_channel\", \"local_timestamp\", \"ant\", \"sig_len\", \"rx_state\", \"real_time_set\", \"real_timestamp\", \"len\", \"CSI_DATA\"] def __init__(self, csv_line:",
"= csv_line[15] self.channel = csv_line[16] self.secondary_channel = csv_line[17] self.local_timestamp = csv_line[18] self.ant =",
"= csv_line[16] self.secondary_channel = csv_line[17] self.local_timestamp = csv_line[18] self.ant = csv_line[19] self.sig_len =",
"self.len = csv_line[24] string_data = csv_line[25] self.csi_matrix = ESP32CSIFrame.parse_matrix(string_data) @staticmethod def parse_matrix(string_data, bandwidth=20):",
"@staticmethod def parse_matrix(string_data, bandwidth=20): array_string = string_data.replace(\" \", \", \") array_string_asarray = ast.literal_eval(array_string)",
"ESP32CSIFrame.parse_matrix(string_data) @staticmethod def parse_matrix(string_data, bandwidth=20): array_string = string_data.replace(\" \", \", \") array_string_asarray =",
"= csv_line[25] self.csi_matrix = ESP32CSIFrame.parse_matrix(string_data) @staticmethod def parse_matrix(string_data, bandwidth=20): array_string = string_data.replace(\" \",",
"= string_data.replace(\" \", \", \") array_string_asarray = ast.literal_eval(array_string) if bandwidth == 20 and",
"\"noise_floor\", \"ampdu_cnt\", \"channel\", \"secondary_channel\", \"local_timestamp\", \"ant\", \"sig_len\", \"rx_state\", \"real_time_set\", \"real_timestamp\", \"len\", \"CSI_DATA\"] def",
"weird dropped behaviour. # Probably not the best way to fill the gap.",
"CSIKit.csi import CSIFrame import ast import numpy as np class ESP32CSIFrame(CSIFrame): # https://docs.espressif.com/projects/esp-idf/en/latest/esp32/api-reference/network/esp_wifi.html#_CPPv418wifi_pkt_rx_ctrl_t",
"\"rssi\", \"rate\", \"sig_mode\", \"mcs\", \"bandwidth\", \"smoothing\", \"not_sounding\", \"aggregation\", \"stbc\", \"fec_coding\", \"sgi\", \"noise_floor\", \"ampdu_cnt\",",
"# Probably not the best way to fill the gap. @staticmethod def fill_missing(array,",
"csv_line[25] self.csi_matrix = ESP32CSIFrame.parse_matrix(string_data) @staticmethod def parse_matrix(string_data, bandwidth=20): array_string = string_data.replace(\" \", \",",
"\"sig_mode\", \"mcs\", \"bandwidth\", \"smoothing\", \"not_sounding\", \"aggregation\", \"stbc\", \"fec_coding\", \"sgi\", \"noise_floor\", \"ampdu_cnt\", \"channel\", \"secondary_channel\",",
"# Very rare, I assume weird dropped behaviour. # Probably not the best",
"self.rx_state = csv_line[21] self.real_time_set = csv_line[22] self.real_timestamp = csv_line[23] self.len = csv_line[24] string_data",
"2) complex_matrix = int8_matrix.astype(np.float32).view(np.complex64) return complex_matrix # Seems some CSI lines are missing",
"from CSIKit.csi import CSIFrame import ast import numpy as np class ESP32CSIFrame(CSIFrame): #",
"def fill_missing(array, expected_length): remainder = expected_length - len(array) for _ in range(remainder): array.append(0)",
"import numpy as np class ESP32CSIFrame(CSIFrame): # https://docs.espressif.com/projects/esp-idf/en/latest/esp32/api-reference/network/esp_wifi.html#_CPPv418wifi_pkt_rx_ctrl_t __slots__ = [\"type\", \"role\", \"mac\",",
"self.stbc = csv_line[11] self.fec_coding = csv_line[12] self.sgi = csv_line[13] self.noise_floor = csv_line[14] self.ampdu_cnt",
"\"rx_state\", \"real_time_set\", \"real_timestamp\", \"len\", \"CSI_DATA\"] def __init__(self, csv_line: list): self.type = csv_line[0] self.role"
] |
[
"activation=activation), dense_value_inflater_builder=None, # unused node_inflater_builder= DecoderCellsBuilder.simple_node_inflater_builder(FLAGS.hidden_cell_coef, activation=activation, gate=FLAGS.decoder_gate)), variable_arity_strategy=FLAGS.dec_variable_arity_strategy) ########### # TRAINING ###########",
"activation=activation, gate=FLAGS.decoder_gate)), variable_arity_strategy=FLAGS.dec_variable_arity_strategy) ########### # TRAINING ########### optimizer = tf.train.AdamOptimizer() with tfs.always_record_summaries(): for",
"gate=FLAGS.encoder_gate), EncoderCellsBuilder.simple_dense_embedder_builder(activation=activation)), name='encoder') decoder = Decoder(tree_def=tree_gen.tree_def, embedding_size=FLAGS.embedding_size, max_node_count=FLAGS.max_node_count, max_depth=FLAGS.max_depth, max_arity=FLAGS.max_arity, cut_arity=FLAGS.cut_arity, cellsbuilder=DecoderCellsBuilder( distrib_builder=",
"get_batch() batch_enc = encoder(xs) batch_dec = decoder(encodings=batch_enc.get_root_embeddings(), targets=xs) loss_struct, loss_val = batch_dec.reconstruction_loss() loss",
"batch_dec = decoder(encodings=batch_enc.get_root_embeddings(), targets=xs) loss_struct, loss_val = batch_dec.reconstruction_loss() loss = loss_struct + loss_val",
"tfs.scalar(\"overlaps/supervised/value_avg\", v_avg_sup) tfs.scalar(\"overlaps/supervised/value_acc\", v_acc_sup) tfs.scalar(\"overlaps/unsupervised/struct_avg\", s_avg) tfs.scalar(\"overlaps/unsupervised/struct_acc\", s_acc) tfs.scalar(\"overlaps/unsupervised/value_avg\", v_avg) tfs.scalar(\"overlaps/unsupervised/value_acc\", v_acc) if",
"already exists!\") else: tf.gfile.MakeDirs(FLAGS.model_dir) summary_writer = tfs.create_file_writer(FLAGS.model_dir, flush_millis=1000) summary_writer.set_as_default() print(\"Summaries in \" +",
"= getattr(tf.nn, FLAGS.activation) encoder = Encoder(tree_def=tree_gen.tree_def, embedding_size=FLAGS.embedding_size, cut_arity=FLAGS.cut_arity, max_arity=FLAGS.max_arity, variable_arity_strategy=FLAGS.enc_variable_arity_strategy, cellsbuilder=EncoderCellsBuilder( EncoderCellsBuilder.simple_cell_builder(hidden_coef=FLAGS.hidden_cell_coef, activation=activation,",
"batch_dec.decoded_trees) s_avg, s_acc, v_avg, v_acc = Tree.compare_trees(xs, batch_unsuperv.decoded_trees) print(\"{0}:\\t{1:.3f}\".format(i, loss)) tfs.scalar(\"loss/struct\", loss_struct) tfs.scalar(\"loss/val\",",
"max_node_count=FLAGS.max_node_count, max_depth=FLAGS.max_depth, max_arity=FLAGS.max_arity, cut_arity=FLAGS.cut_arity, cellsbuilder=DecoderCellsBuilder( distrib_builder= DecoderCellsBuilder.simple_distrib_cell_builder(FLAGS.hidden_cell_coef, activation=activation), categorical_value_inflater_builder= DecoderCellsBuilder.simple_1ofk_value_inflater_builder(FLAGS.hidden_cell_coef, activation=activation), dense_value_inflater_builder=None, #",
"tensorflow_trees.encoder import Encoder, EncoderCellsBuilder from tensorflow_trees.decoder import Decoder, DecoderCellsBuilder from examples.simple_expression.exp_definition import BinaryExpressionTreeGen,",
"from examples.simple_expression.exp_definition import BinaryExpressionTreeGen, NaryExpressionTreeGen from tensorflow_trees.definition import Tree from examples.simple_expression.flags_definition import *",
"FLAGS.check_every == 0: batch_unsuperv = decoder(encodings=batch_enc.get_root_embeddings()) _, _, v_avg_sup, v_acc_sup = Tree.compare_trees(xs, batch_dec.decoded_trees)",
"import tensorflow.contrib.summary as tfs import os import json FLAGS = tf.flags.FLAGS def main(argv=None):",
"Tree from examples.simple_expression.flags_definition import * import tensorflow as tf import tensorflow.contrib.eager as tfe",
"flush_millis=1000) summary_writer.set_as_default() print(\"Summaries in \" + FLAGS.model_dir) with open(os.path.join(FLAGS.model_dir, \"flags.json\"), 'w') as f:",
"= NaryExpressionTreeGen(9, FLAGS.max_arity) def get_batch(): return [tree_gen.generate(FLAGS.max_depth) for _ in range(FLAGS.batch_size)] ######### #",
"max_arity=FLAGS.max_arity, cut_arity=FLAGS.cut_arity, cellsbuilder=DecoderCellsBuilder( distrib_builder= DecoderCellsBuilder.simple_distrib_cell_builder(FLAGS.hidden_cell_coef, activation=activation), categorical_value_inflater_builder= DecoderCellsBuilder.simple_1ofk_value_inflater_builder(FLAGS.hidden_cell_coef, activation=activation), dense_value_inflater_builder=None, # unused node_inflater_builder=",
"variables = encoder.variables + decoder.variables grad = tape.gradient(loss, variables) gnorm = tf.global_norm(grad) grad,",
"activation=activation), categorical_value_inflater_builder= DecoderCellsBuilder.simple_1ofk_value_inflater_builder(FLAGS.hidden_cell_coef, activation=activation), dense_value_inflater_builder=None, # unused node_inflater_builder= DecoderCellsBuilder.simple_node_inflater_builder(FLAGS.hidden_cell_coef, activation=activation, gate=FLAGS.decoder_gate)), variable_arity_strategy=FLAGS.dec_variable_arity_strategy) ###########",
"tf.train.AdamOptimizer() with tfs.always_record_summaries(): for i in range(FLAGS.max_iter): with tfe.GradientTape() as tape: xs =",
"FLAGS.fixed_arity: tree_gen = BinaryExpressionTreeGen(9) else: tree_gen = NaryExpressionTreeGen(9, FLAGS.max_arity) def get_batch(): return [tree_gen.generate(FLAGS.max_depth)",
"tf.clip_by_global_norm(grad, 0.02, gnorm) tfs.scalar(\"norms/grad\", gnorm) optimizer.apply_gradients(zip(grad, variables), global_step=tf.train.get_or_create_global_step()) if i % FLAGS.check_every ==",
"as tape: xs = get_batch() batch_enc = encoder(xs) batch_dec = decoder(encodings=batch_enc.get_root_embeddings(), targets=xs) loss_struct,",
"* import tensorflow as tf import tensorflow.contrib.eager as tfe import tensorflow.contrib.summary as tfs",
"ValueError(\"Log dir already exists!\") else: tf.gfile.MakeDirs(FLAGS.model_dir) summary_writer = tfs.create_file_writer(FLAGS.model_dir, flush_millis=1000) summary_writer.set_as_default() print(\"Summaries in",
"######### if FLAGS.fixed_arity: tree_gen = BinaryExpressionTreeGen(9) else: tree_gen = NaryExpressionTreeGen(9, FLAGS.max_arity) def get_batch():",
"unused node_inflater_builder= DecoderCellsBuilder.simple_node_inflater_builder(FLAGS.hidden_cell_coef, activation=activation, gate=FLAGS.decoder_gate)), variable_arity_strategy=FLAGS.dec_variable_arity_strategy) ########### # TRAINING ########### optimizer = tf.train.AdamOptimizer()",
"import json FLAGS = tf.flags.FLAGS def main(argv=None): ######### # Checkpoints and Summaries #########",
"######### # Checkpoints and Summaries ######### if tf.gfile.Exists(FLAGS.model_dir): if FLAGS.overwrite: tf.logging.warn(\"Deleting old log",
"i % FLAGS.check_every == 0: batch_unsuperv = decoder(encodings=batch_enc.get_root_embeddings()) _, _, v_avg_sup, v_acc_sup =",
"tfs.scalar(\"loss/struct\", loss_struct) tfs.scalar(\"loss/val\", loss_val) tfs.scalar(\"loss/loss\", loss) tfs.scalar(\"overlaps/supervised/value_avg\", v_avg_sup) tfs.scalar(\"overlaps/supervised/value_acc\", v_acc_sup) tfs.scalar(\"overlaps/unsupervised/struct_avg\", s_avg) tfs.scalar(\"overlaps/unsupervised/struct_acc\",",
"examples.simple_expression.exp_definition import BinaryExpressionTreeGen, NaryExpressionTreeGen from tensorflow_trees.definition import Tree from examples.simple_expression.flags_definition import * import",
"FLAGS = tf.flags.FLAGS def main(argv=None): ######### # Checkpoints and Summaries ######### if tf.gfile.Exists(FLAGS.model_dir):",
"########### # TRAINING ########### optimizer = tf.train.AdamOptimizer() with tfs.always_record_summaries(): for i in range(FLAGS.max_iter):",
"targets=xs) loss_struct, loss_val = batch_dec.reconstruction_loss() loss = loss_struct + loss_val variables = encoder.variables",
"decoder(encodings=batch_enc.get_root_embeddings()) _, _, v_avg_sup, v_acc_sup = Tree.compare_trees(xs, batch_dec.decoded_trees) s_avg, s_acc, v_avg, v_acc =",
"= decoder(encodings=batch_enc.get_root_embeddings(), targets=xs) loss_struct, loss_val = batch_dec.reconstruction_loss() loss = loss_struct + loss_val variables",
"= Encoder(tree_def=tree_gen.tree_def, embedding_size=FLAGS.embedding_size, cut_arity=FLAGS.cut_arity, max_arity=FLAGS.max_arity, variable_arity_strategy=FLAGS.enc_variable_arity_strategy, cellsbuilder=EncoderCellsBuilder( EncoderCellsBuilder.simple_cell_builder(hidden_coef=FLAGS.hidden_cell_coef, activation=activation, gate=FLAGS.encoder_gate), EncoderCellsBuilder.simple_dense_embedder_builder(activation=activation)), name='encoder') decoder",
"tfs.create_file_writer(FLAGS.model_dir, flush_millis=1000) summary_writer.set_as_default() print(\"Summaries in \" + FLAGS.model_dir) with open(os.path.join(FLAGS.model_dir, \"flags.json\"), 'w') as",
"= tf.flags.FLAGS def main(argv=None): ######### # Checkpoints and Summaries ######### if tf.gfile.Exists(FLAGS.model_dir): if",
"else: tree_gen = NaryExpressionTreeGen(9, FLAGS.max_arity) def get_batch(): return [tree_gen.generate(FLAGS.max_depth) for _ in range(FLAGS.batch_size)]",
"tf.gfile.MakeDirs(FLAGS.model_dir) else: raise ValueError(\"Log dir already exists!\") else: tf.gfile.MakeDirs(FLAGS.model_dir) summary_writer = tfs.create_file_writer(FLAGS.model_dir, flush_millis=1000)",
"import os import json FLAGS = tf.flags.FLAGS def main(argv=None): ######### # Checkpoints and",
"tf.gfile.DeleteRecursively(FLAGS.model_dir) tf.gfile.MakeDirs(FLAGS.model_dir) else: raise ValueError(\"Log dir already exists!\") else: tf.gfile.MakeDirs(FLAGS.model_dir) summary_writer = tfs.create_file_writer(FLAGS.model_dir,",
"from tensorflow_trees.decoder import Decoder, DecoderCellsBuilder from examples.simple_expression.exp_definition import BinaryExpressionTreeGen, NaryExpressionTreeGen from tensorflow_trees.definition import",
"summary_writer = tfs.create_file_writer(FLAGS.model_dir, flush_millis=1000) summary_writer.set_as_default() print(\"Summaries in \" + FLAGS.model_dir) with open(os.path.join(FLAGS.model_dir, \"flags.json\"),",
"with open(os.path.join(FLAGS.model_dir, \"flags.json\"), 'w') as f: json.dump(FLAGS.flag_values_dict(), f) ######### # DATA ######### if",
"\" + FLAGS.model_dir) with open(os.path.join(FLAGS.model_dir, \"flags.json\"), 'w') as f: json.dump(FLAGS.flag_values_dict(), f) ######### #",
"= get_batch() batch_enc = encoder(xs) batch_dec = decoder(encodings=batch_enc.get_root_embeddings(), targets=xs) loss_struct, loss_val = batch_dec.reconstruction_loss()",
"# TRAINING ########### optimizer = tf.train.AdamOptimizer() with tfs.always_record_summaries(): for i in range(FLAGS.max_iter): with",
"if i % FLAGS.check_every == 0: batch_unsuperv = decoder(encodings=batch_enc.get_root_embeddings()) _, _, v_avg_sup, v_acc_sup",
"exists!\") else: tf.gfile.MakeDirs(FLAGS.model_dir) summary_writer = tfs.create_file_writer(FLAGS.model_dir, flush_millis=1000) summary_writer.set_as_default() print(\"Summaries in \" + FLAGS.model_dir)",
"categorical_value_inflater_builder= DecoderCellsBuilder.simple_1ofk_value_inflater_builder(FLAGS.hidden_cell_coef, activation=activation), dense_value_inflater_builder=None, # unused node_inflater_builder= DecoderCellsBuilder.simple_node_inflater_builder(FLAGS.hidden_cell_coef, activation=activation, gate=FLAGS.decoder_gate)), variable_arity_strategy=FLAGS.dec_variable_arity_strategy) ########### #",
"tape.gradient(loss, variables) gnorm = tf.global_norm(grad) grad, _ = tf.clip_by_global_norm(grad, 0.02, gnorm) tfs.scalar(\"norms/grad\", gnorm)",
"in \" + FLAGS.model_dir) with open(os.path.join(FLAGS.model_dir, \"flags.json\"), 'w') as f: json.dump(FLAGS.flag_values_dict(), f) #########",
"examples.simple_expression.flags_definition import * import tensorflow as tf import tensorflow.contrib.eager as tfe import tensorflow.contrib.summary",
"s_avg, s_acc, v_avg, v_acc = Tree.compare_trees(xs, batch_unsuperv.decoded_trees) print(\"{0}:\\t{1:.3f}\".format(i, loss)) tfs.scalar(\"loss/struct\", loss_struct) tfs.scalar(\"loss/val\", loss_val)",
"tensorflow.contrib.eager as tfe import tensorflow.contrib.summary as tfs import os import json FLAGS =",
"distrib_builder= DecoderCellsBuilder.simple_distrib_cell_builder(FLAGS.hidden_cell_coef, activation=activation), categorical_value_inflater_builder= DecoderCellsBuilder.simple_1ofk_value_inflater_builder(FLAGS.hidden_cell_coef, activation=activation), dense_value_inflater_builder=None, # unused node_inflater_builder= DecoderCellsBuilder.simple_node_inflater_builder(FLAGS.hidden_cell_coef, activation=activation, gate=FLAGS.decoder_gate)),",
"s_avg) tfs.scalar(\"overlaps/unsupervised/struct_acc\", s_acc) tfs.scalar(\"overlaps/unsupervised/value_avg\", v_avg) tfs.scalar(\"overlaps/unsupervised/value_acc\", v_acc) if __name__ == \"__main__\": define_common_flags() define_encoder_flags()",
"== 0: batch_unsuperv = decoder(encodings=batch_enc.get_root_embeddings()) _, _, v_avg_sup, v_acc_sup = Tree.compare_trees(xs, batch_dec.decoded_trees) s_avg,",
"and Summaries ######### if tf.gfile.Exists(FLAGS.model_dir): if FLAGS.overwrite: tf.logging.warn(\"Deleting old log directory at {}\".format(FLAGS.model_dir))",
"EncoderCellsBuilder from tensorflow_trees.decoder import Decoder, DecoderCellsBuilder from examples.simple_expression.exp_definition import BinaryExpressionTreeGen, NaryExpressionTreeGen from tensorflow_trees.definition",
"v_acc = Tree.compare_trees(xs, batch_unsuperv.decoded_trees) print(\"{0}:\\t{1:.3f}\".format(i, loss)) tfs.scalar(\"loss/struct\", loss_struct) tfs.scalar(\"loss/val\", loss_val) tfs.scalar(\"loss/loss\", loss) tfs.scalar(\"overlaps/supervised/value_avg\",",
"tfe import tensorflow.contrib.summary as tfs import os import json FLAGS = tf.flags.FLAGS def",
"batch_enc = encoder(xs) batch_dec = decoder(encodings=batch_enc.get_root_embeddings(), targets=xs) loss_struct, loss_val = batch_dec.reconstruction_loss() loss =",
"print(\"{0}:\\t{1:.3f}\".format(i, loss)) tfs.scalar(\"loss/struct\", loss_struct) tfs.scalar(\"loss/val\", loss_val) tfs.scalar(\"loss/loss\", loss) tfs.scalar(\"overlaps/supervised/value_avg\", v_avg_sup) tfs.scalar(\"overlaps/supervised/value_acc\", v_acc_sup) tfs.scalar(\"overlaps/unsupervised/struct_avg\",",
"embedding_size=FLAGS.embedding_size, max_node_count=FLAGS.max_node_count, max_depth=FLAGS.max_depth, max_arity=FLAGS.max_arity, cut_arity=FLAGS.cut_arity, cellsbuilder=DecoderCellsBuilder( distrib_builder= DecoderCellsBuilder.simple_distrib_cell_builder(FLAGS.hidden_cell_coef, activation=activation), categorical_value_inflater_builder= DecoderCellsBuilder.simple_1ofk_value_inflater_builder(FLAGS.hidden_cell_coef, activation=activation), dense_value_inflater_builder=None,",
"print(\"Summaries in \" + FLAGS.model_dir) with open(os.path.join(FLAGS.model_dir, \"flags.json\"), 'w') as f: json.dump(FLAGS.flag_values_dict(), f)",
"= tf.train.AdamOptimizer() with tfs.always_record_summaries(): for i in range(FLAGS.max_iter): with tfe.GradientTape() as tape: xs",
"s_acc, v_avg, v_acc = Tree.compare_trees(xs, batch_unsuperv.decoded_trees) print(\"{0}:\\t{1:.3f}\".format(i, loss)) tfs.scalar(\"loss/struct\", loss_struct) tfs.scalar(\"loss/val\", loss_val) tfs.scalar(\"loss/loss\",",
"summary_writer.set_as_default() print(\"Summaries in \" + FLAGS.model_dir) with open(os.path.join(FLAGS.model_dir, \"flags.json\"), 'w') as f: json.dump(FLAGS.flag_values_dict(),",
"tensorflow_trees.decoder import Decoder, DecoderCellsBuilder from examples.simple_expression.exp_definition import BinaryExpressionTreeGen, NaryExpressionTreeGen from tensorflow_trees.definition import Tree",
"as f: json.dump(FLAGS.flag_values_dict(), f) ######### # DATA ######### if FLAGS.fixed_arity: tree_gen = BinaryExpressionTreeGen(9)",
"from tensorflow_trees.definition import Tree from examples.simple_expression.flags_definition import * import tensorflow as tf import",
"activation=activation, gate=FLAGS.encoder_gate), EncoderCellsBuilder.simple_dense_embedder_builder(activation=activation)), name='encoder') decoder = Decoder(tree_def=tree_gen.tree_def, embedding_size=FLAGS.embedding_size, max_node_count=FLAGS.max_node_count, max_depth=FLAGS.max_depth, max_arity=FLAGS.max_arity, cut_arity=FLAGS.cut_arity, cellsbuilder=DecoderCellsBuilder(",
"tree_gen = NaryExpressionTreeGen(9, FLAGS.max_arity) def get_batch(): return [tree_gen.generate(FLAGS.max_depth) for _ in range(FLAGS.batch_size)] #########",
"return [tree_gen.generate(FLAGS.max_depth) for _ in range(FLAGS.batch_size)] ######### # MODEL ######### activation = getattr(tf.nn,",
"+ FLAGS.model_dir) with open(os.path.join(FLAGS.model_dir, \"flags.json\"), 'w') as f: json.dump(FLAGS.flag_values_dict(), f) ######### # DATA",
"tf.gfile.MakeDirs(FLAGS.model_dir) summary_writer = tfs.create_file_writer(FLAGS.model_dir, flush_millis=1000) summary_writer.set_as_default() print(\"Summaries in \" + FLAGS.model_dir) with open(os.path.join(FLAGS.model_dir,",
"FLAGS.overwrite: tf.logging.warn(\"Deleting old log directory at {}\".format(FLAGS.model_dir)) tf.gfile.DeleteRecursively(FLAGS.model_dir) tf.gfile.MakeDirs(FLAGS.model_dir) else: raise ValueError(\"Log dir",
"v_acc_sup = Tree.compare_trees(xs, batch_dec.decoded_trees) s_avg, s_acc, v_avg, v_acc = Tree.compare_trees(xs, batch_unsuperv.decoded_trees) print(\"{0}:\\t{1:.3f}\".format(i, loss))",
"v_avg, v_acc = Tree.compare_trees(xs, batch_unsuperv.decoded_trees) print(\"{0}:\\t{1:.3f}\".format(i, loss)) tfs.scalar(\"loss/struct\", loss_struct) tfs.scalar(\"loss/val\", loss_val) tfs.scalar(\"loss/loss\", loss)",
"loss_struct) tfs.scalar(\"loss/val\", loss_val) tfs.scalar(\"loss/loss\", loss) tfs.scalar(\"overlaps/supervised/value_avg\", v_avg_sup) tfs.scalar(\"overlaps/supervised/value_acc\", v_acc_sup) tfs.scalar(\"overlaps/unsupervised/struct_avg\", s_avg) tfs.scalar(\"overlaps/unsupervised/struct_acc\", s_acc)",
"node_inflater_builder= DecoderCellsBuilder.simple_node_inflater_builder(FLAGS.hidden_cell_coef, activation=activation, gate=FLAGS.decoder_gate)), variable_arity_strategy=FLAGS.dec_variable_arity_strategy) ########### # TRAINING ########### optimizer = tf.train.AdamOptimizer() with",
"json FLAGS = tf.flags.FLAGS def main(argv=None): ######### # Checkpoints and Summaries ######### if",
"gate=FLAGS.decoder_gate)), variable_arity_strategy=FLAGS.dec_variable_arity_strategy) ########### # TRAINING ########### optimizer = tf.train.AdamOptimizer() with tfs.always_record_summaries(): for i",
"######### activation = getattr(tf.nn, FLAGS.activation) encoder = Encoder(tree_def=tree_gen.tree_def, embedding_size=FLAGS.embedding_size, cut_arity=FLAGS.cut_arity, max_arity=FLAGS.max_arity, variable_arity_strategy=FLAGS.enc_variable_arity_strategy, cellsbuilder=EncoderCellsBuilder(",
"FLAGS.activation) encoder = Encoder(tree_def=tree_gen.tree_def, embedding_size=FLAGS.embedding_size, cut_arity=FLAGS.cut_arity, max_arity=FLAGS.max_arity, variable_arity_strategy=FLAGS.enc_variable_arity_strategy, cellsbuilder=EncoderCellsBuilder( EncoderCellsBuilder.simple_cell_builder(hidden_coef=FLAGS.hidden_cell_coef, activation=activation, gate=FLAGS.encoder_gate), EncoderCellsBuilder.simple_dense_embedder_builder(activation=activation)),",
"_ = tf.clip_by_global_norm(grad, 0.02, gnorm) tfs.scalar(\"norms/grad\", gnorm) optimizer.apply_gradients(zip(grad, variables), global_step=tf.train.get_or_create_global_step()) if i %",
"######### # MODEL ######### activation = getattr(tf.nn, FLAGS.activation) encoder = Encoder(tree_def=tree_gen.tree_def, embedding_size=FLAGS.embedding_size, cut_arity=FLAGS.cut_arity,",
"tfs.scalar(\"norms/grad\", gnorm) optimizer.apply_gradients(zip(grad, variables), global_step=tf.train.get_or_create_global_step()) if i % FLAGS.check_every == 0: batch_unsuperv =",
"decoder = Decoder(tree_def=tree_gen.tree_def, embedding_size=FLAGS.embedding_size, max_node_count=FLAGS.max_node_count, max_depth=FLAGS.max_depth, max_arity=FLAGS.max_arity, cut_arity=FLAGS.cut_arity, cellsbuilder=DecoderCellsBuilder( distrib_builder= DecoderCellsBuilder.simple_distrib_cell_builder(FLAGS.hidden_cell_coef, activation=activation), categorical_value_inflater_builder=",
"NaryExpressionTreeGen from tensorflow_trees.definition import Tree from examples.simple_expression.flags_definition import * import tensorflow as tf",
"def main(argv=None): ######### # Checkpoints and Summaries ######### if tf.gfile.Exists(FLAGS.model_dir): if FLAGS.overwrite: tf.logging.warn(\"Deleting",
"import Encoder, EncoderCellsBuilder from tensorflow_trees.decoder import Decoder, DecoderCellsBuilder from examples.simple_expression.exp_definition import BinaryExpressionTreeGen, NaryExpressionTreeGen",
"= BinaryExpressionTreeGen(9) else: tree_gen = NaryExpressionTreeGen(9, FLAGS.max_arity) def get_batch(): return [tree_gen.generate(FLAGS.max_depth) for _",
"name='encoder') decoder = Decoder(tree_def=tree_gen.tree_def, embedding_size=FLAGS.embedding_size, max_node_count=FLAGS.max_node_count, max_depth=FLAGS.max_depth, max_arity=FLAGS.max_arity, cut_arity=FLAGS.cut_arity, cellsbuilder=DecoderCellsBuilder( distrib_builder= DecoderCellsBuilder.simple_distrib_cell_builder(FLAGS.hidden_cell_coef, activation=activation),",
"% FLAGS.check_every == 0: batch_unsuperv = decoder(encodings=batch_enc.get_root_embeddings()) _, _, v_avg_sup, v_acc_sup = Tree.compare_trees(xs,",
"_, v_avg_sup, v_acc_sup = Tree.compare_trees(xs, batch_dec.decoded_trees) s_avg, s_acc, v_avg, v_acc = Tree.compare_trees(xs, batch_unsuperv.decoded_trees)",
"os import json FLAGS = tf.flags.FLAGS def main(argv=None): ######### # Checkpoints and Summaries",
"BinaryExpressionTreeGen(9) else: tree_gen = NaryExpressionTreeGen(9, FLAGS.max_arity) def get_batch(): return [tree_gen.generate(FLAGS.max_depth) for _ in",
"with tfe.GradientTape() as tape: xs = get_batch() batch_enc = encoder(xs) batch_dec = decoder(encodings=batch_enc.get_root_embeddings(),",
"global_step=tf.train.get_or_create_global_step()) if i % FLAGS.check_every == 0: batch_unsuperv = decoder(encodings=batch_enc.get_root_embeddings()) _, _, v_avg_sup,",
"Encoder(tree_def=tree_gen.tree_def, embedding_size=FLAGS.embedding_size, cut_arity=FLAGS.cut_arity, max_arity=FLAGS.max_arity, variable_arity_strategy=FLAGS.enc_variable_arity_strategy, cellsbuilder=EncoderCellsBuilder( EncoderCellsBuilder.simple_cell_builder(hidden_coef=FLAGS.hidden_cell_coef, activation=activation, gate=FLAGS.encoder_gate), EncoderCellsBuilder.simple_dense_embedder_builder(activation=activation)), name='encoder') decoder =",
"[tree_gen.generate(FLAGS.max_depth) for _ in range(FLAGS.batch_size)] ######### # MODEL ######### activation = getattr(tf.nn, FLAGS.activation)",
"f) ######### # DATA ######### if FLAGS.fixed_arity: tree_gen = BinaryExpressionTreeGen(9) else: tree_gen =",
"getattr(tf.nn, FLAGS.activation) encoder = Encoder(tree_def=tree_gen.tree_def, embedding_size=FLAGS.embedding_size, cut_arity=FLAGS.cut_arity, max_arity=FLAGS.max_arity, variable_arity_strategy=FLAGS.enc_variable_arity_strategy, cellsbuilder=EncoderCellsBuilder( EncoderCellsBuilder.simple_cell_builder(hidden_coef=FLAGS.hidden_cell_coef, activation=activation, gate=FLAGS.encoder_gate),",
"as tfe import tensorflow.contrib.summary as tfs import os import json FLAGS = tf.flags.FLAGS",
"gnorm) tfs.scalar(\"norms/grad\", gnorm) optimizer.apply_gradients(zip(grad, variables), global_step=tf.train.get_or_create_global_step()) if i % FLAGS.check_every == 0: batch_unsuperv",
"Tree.compare_trees(xs, batch_unsuperv.decoded_trees) print(\"{0}:\\t{1:.3f}\".format(i, loss)) tfs.scalar(\"loss/struct\", loss_struct) tfs.scalar(\"loss/val\", loss_val) tfs.scalar(\"loss/loss\", loss) tfs.scalar(\"overlaps/supervised/value_avg\", v_avg_sup) tfs.scalar(\"overlaps/supervised/value_acc\",",
"json.dump(FLAGS.flag_values_dict(), f) ######### # DATA ######### if FLAGS.fixed_arity: tree_gen = BinaryExpressionTreeGen(9) else: tree_gen",
"batch_dec.reconstruction_loss() loss = loss_struct + loss_val variables = encoder.variables + decoder.variables grad =",
"NaryExpressionTreeGen(9, FLAGS.max_arity) def get_batch(): return [tree_gen.generate(FLAGS.max_depth) for _ in range(FLAGS.batch_size)] ######### # MODEL",
"= Tree.compare_trees(xs, batch_dec.decoded_trees) s_avg, s_acc, v_avg, v_acc = Tree.compare_trees(xs, batch_unsuperv.decoded_trees) print(\"{0}:\\t{1:.3f}\".format(i, loss)) tfs.scalar(\"loss/struct\",",
"\"flags.json\"), 'w') as f: json.dump(FLAGS.flag_values_dict(), f) ######### # DATA ######### if FLAGS.fixed_arity: tree_gen",
"loss) tfs.scalar(\"overlaps/supervised/value_avg\", v_avg_sup) tfs.scalar(\"overlaps/supervised/value_acc\", v_acc_sup) tfs.scalar(\"overlaps/unsupervised/struct_avg\", s_avg) tfs.scalar(\"overlaps/unsupervised/struct_acc\", s_acc) tfs.scalar(\"overlaps/unsupervised/value_avg\", v_avg) tfs.scalar(\"overlaps/unsupervised/value_acc\", v_acc)",
"from examples.simple_expression.flags_definition import * import tensorflow as tf import tensorflow.contrib.eager as tfe import",
"+ decoder.variables grad = tape.gradient(loss, variables) gnorm = tf.global_norm(grad) grad, _ = tf.clip_by_global_norm(grad,",
"loss = loss_struct + loss_val variables = encoder.variables + decoder.variables grad = tape.gradient(loss,",
"batch_unsuperv.decoded_trees) print(\"{0}:\\t{1:.3f}\".format(i, loss)) tfs.scalar(\"loss/struct\", loss_struct) tfs.scalar(\"loss/val\", loss_val) tfs.scalar(\"loss/loss\", loss) tfs.scalar(\"overlaps/supervised/value_avg\", v_avg_sup) tfs.scalar(\"overlaps/supervised/value_acc\", v_acc_sup)",
"tfs.scalar(\"overlaps/supervised/value_acc\", v_acc_sup) tfs.scalar(\"overlaps/unsupervised/struct_avg\", s_avg) tfs.scalar(\"overlaps/unsupervised/struct_acc\", s_acc) tfs.scalar(\"overlaps/unsupervised/value_avg\", v_avg) tfs.scalar(\"overlaps/unsupervised/value_acc\", v_acc) if __name__ ==",
"tf.global_norm(grad) grad, _ = tf.clip_by_global_norm(grad, 0.02, gnorm) tfs.scalar(\"norms/grad\", gnorm) optimizer.apply_gradients(zip(grad, variables), global_step=tf.train.get_or_create_global_step()) if",
"v_avg_sup) tfs.scalar(\"overlaps/supervised/value_acc\", v_acc_sup) tfs.scalar(\"overlaps/unsupervised/struct_avg\", s_avg) tfs.scalar(\"overlaps/unsupervised/struct_acc\", s_acc) tfs.scalar(\"overlaps/unsupervised/value_avg\", v_avg) tfs.scalar(\"overlaps/unsupervised/value_acc\", v_acc) if __name__",
"= encoder.variables + decoder.variables grad = tape.gradient(loss, variables) gnorm = tf.global_norm(grad) grad, _",
"DecoderCellsBuilder.simple_distrib_cell_builder(FLAGS.hidden_cell_coef, activation=activation), categorical_value_inflater_builder= DecoderCellsBuilder.simple_1ofk_value_inflater_builder(FLAGS.hidden_cell_coef, activation=activation), dense_value_inflater_builder=None, # unused node_inflater_builder= DecoderCellsBuilder.simple_node_inflater_builder(FLAGS.hidden_cell_coef, activation=activation, gate=FLAGS.decoder_gate)), variable_arity_strategy=FLAGS.dec_variable_arity_strategy)",
"with tfs.always_record_summaries(): for i in range(FLAGS.max_iter): with tfe.GradientTape() as tape: xs = get_batch()",
"encoder.variables + decoder.variables grad = tape.gradient(loss, variables) gnorm = tf.global_norm(grad) grad, _ =",
"xs = get_batch() batch_enc = encoder(xs) batch_dec = decoder(encodings=batch_enc.get_root_embeddings(), targets=xs) loss_struct, loss_val =",
"as tfs import os import json FLAGS = tf.flags.FLAGS def main(argv=None): ######### #",
"tf.flags.FLAGS def main(argv=None): ######### # Checkpoints and Summaries ######### if tf.gfile.Exists(FLAGS.model_dir): if FLAGS.overwrite:",
"tf.gfile.Exists(FLAGS.model_dir): if FLAGS.overwrite: tf.logging.warn(\"Deleting old log directory at {}\".format(FLAGS.model_dir)) tf.gfile.DeleteRecursively(FLAGS.model_dir) tf.gfile.MakeDirs(FLAGS.model_dir) else: raise",
"######### # DATA ######### if FLAGS.fixed_arity: tree_gen = BinaryExpressionTreeGen(9) else: tree_gen = NaryExpressionTreeGen(9,",
"# MODEL ######### activation = getattr(tf.nn, FLAGS.activation) encoder = Encoder(tree_def=tree_gen.tree_def, embedding_size=FLAGS.embedding_size, cut_arity=FLAGS.cut_arity, max_arity=FLAGS.max_arity,",
"for _ in range(FLAGS.batch_size)] ######### # MODEL ######### activation = getattr(tf.nn, FLAGS.activation) encoder",
"loss_val variables = encoder.variables + decoder.variables grad = tape.gradient(loss, variables) gnorm = tf.global_norm(grad)",
"tfe.GradientTape() as tape: xs = get_batch() batch_enc = encoder(xs) batch_dec = decoder(encodings=batch_enc.get_root_embeddings(), targets=xs)",
"decoder.variables grad = tape.gradient(loss, variables) gnorm = tf.global_norm(grad) grad, _ = tf.clip_by_global_norm(grad, 0.02,",
"{}\".format(FLAGS.model_dir)) tf.gfile.DeleteRecursively(FLAGS.model_dir) tf.gfile.MakeDirs(FLAGS.model_dir) else: raise ValueError(\"Log dir already exists!\") else: tf.gfile.MakeDirs(FLAGS.model_dir) summary_writer =",
"import Tree from examples.simple_expression.flags_definition import * import tensorflow as tf import tensorflow.contrib.eager as",
"= tfs.create_file_writer(FLAGS.model_dir, flush_millis=1000) summary_writer.set_as_default() print(\"Summaries in \" + FLAGS.model_dir) with open(os.path.join(FLAGS.model_dir, \"flags.json\"), 'w')",
"as tf import tensorflow.contrib.eager as tfe import tensorflow.contrib.summary as tfs import os import",
"tree_gen = BinaryExpressionTreeGen(9) else: tree_gen = NaryExpressionTreeGen(9, FLAGS.max_arity) def get_batch(): return [tree_gen.generate(FLAGS.max_depth) for",
"encoder = Encoder(tree_def=tree_gen.tree_def, embedding_size=FLAGS.embedding_size, cut_arity=FLAGS.cut_arity, max_arity=FLAGS.max_arity, variable_arity_strategy=FLAGS.enc_variable_arity_strategy, cellsbuilder=EncoderCellsBuilder( EncoderCellsBuilder.simple_cell_builder(hidden_coef=FLAGS.hidden_cell_coef, activation=activation, gate=FLAGS.encoder_gate), EncoderCellsBuilder.simple_dense_embedder_builder(activation=activation)), name='encoder')",
"variables), global_step=tf.train.get_or_create_global_step()) if i % FLAGS.check_every == 0: batch_unsuperv = decoder(encodings=batch_enc.get_root_embeddings()) _, _,",
"Tree.compare_trees(xs, batch_dec.decoded_trees) s_avg, s_acc, v_avg, v_acc = Tree.compare_trees(xs, batch_unsuperv.decoded_trees) print(\"{0}:\\t{1:.3f}\".format(i, loss)) tfs.scalar(\"loss/struct\", loss_struct)",
"MODEL ######### activation = getattr(tf.nn, FLAGS.activation) encoder = Encoder(tree_def=tree_gen.tree_def, embedding_size=FLAGS.embedding_size, cut_arity=FLAGS.cut_arity, max_arity=FLAGS.max_arity, variable_arity_strategy=FLAGS.enc_variable_arity_strategy,",
"tensorflow_trees.definition import Tree from examples.simple_expression.flags_definition import * import tensorflow as tf import tensorflow.contrib.eager",
"f: json.dump(FLAGS.flag_values_dict(), f) ######### # DATA ######### if FLAGS.fixed_arity: tree_gen = BinaryExpressionTreeGen(9) else:",
"tfs.always_record_summaries(): for i in range(FLAGS.max_iter): with tfe.GradientTape() as tape: xs = get_batch() batch_enc",
"range(FLAGS.max_iter): with tfe.GradientTape() as tape: xs = get_batch() batch_enc = encoder(xs) batch_dec =",
"+ loss_val variables = encoder.variables + decoder.variables grad = tape.gradient(loss, variables) gnorm =",
"optimizer.apply_gradients(zip(grad, variables), global_step=tf.train.get_or_create_global_step()) if i % FLAGS.check_every == 0: batch_unsuperv = decoder(encodings=batch_enc.get_root_embeddings()) _,",
"BinaryExpressionTreeGen, NaryExpressionTreeGen from tensorflow_trees.definition import Tree from examples.simple_expression.flags_definition import * import tensorflow as",
"loss)) tfs.scalar(\"loss/struct\", loss_struct) tfs.scalar(\"loss/val\", loss_val) tfs.scalar(\"loss/loss\", loss) tfs.scalar(\"overlaps/supervised/value_avg\", v_avg_sup) tfs.scalar(\"overlaps/supervised/value_acc\", v_acc_sup) tfs.scalar(\"overlaps/unsupervised/struct_avg\", s_avg)",
"range(FLAGS.batch_size)] ######### # MODEL ######### activation = getattr(tf.nn, FLAGS.activation) encoder = Encoder(tree_def=tree_gen.tree_def, embedding_size=FLAGS.embedding_size,",
"gnorm = tf.global_norm(grad) grad, _ = tf.clip_by_global_norm(grad, 0.02, gnorm) tfs.scalar(\"norms/grad\", gnorm) optimizer.apply_gradients(zip(grad, variables),",
"encoder(xs) batch_dec = decoder(encodings=batch_enc.get_root_embeddings(), targets=xs) loss_struct, loss_val = batch_dec.reconstruction_loss() loss = loss_struct +",
"Checkpoints and Summaries ######### if tf.gfile.Exists(FLAGS.model_dir): if FLAGS.overwrite: tf.logging.warn(\"Deleting old log directory at",
"max_arity=FLAGS.max_arity, variable_arity_strategy=FLAGS.enc_variable_arity_strategy, cellsbuilder=EncoderCellsBuilder( EncoderCellsBuilder.simple_cell_builder(hidden_coef=FLAGS.hidden_cell_coef, activation=activation, gate=FLAGS.encoder_gate), EncoderCellsBuilder.simple_dense_embedder_builder(activation=activation)), name='encoder') decoder = Decoder(tree_def=tree_gen.tree_def, embedding_size=FLAGS.embedding_size, max_node_count=FLAGS.max_node_count,",
"FLAGS.model_dir) with open(os.path.join(FLAGS.model_dir, \"flags.json\"), 'w') as f: json.dump(FLAGS.flag_values_dict(), f) ######### # DATA #########",
"# unused node_inflater_builder= DecoderCellsBuilder.simple_node_inflater_builder(FLAGS.hidden_cell_coef, activation=activation, gate=FLAGS.decoder_gate)), variable_arity_strategy=FLAGS.dec_variable_arity_strategy) ########### # TRAINING ########### optimizer =",
"= Tree.compare_trees(xs, batch_unsuperv.decoded_trees) print(\"{0}:\\t{1:.3f}\".format(i, loss)) tfs.scalar(\"loss/struct\", loss_struct) tfs.scalar(\"loss/val\", loss_val) tfs.scalar(\"loss/loss\", loss) tfs.scalar(\"overlaps/supervised/value_avg\", v_avg_sup)",
"import BinaryExpressionTreeGen, NaryExpressionTreeGen from tensorflow_trees.definition import Tree from examples.simple_expression.flags_definition import * import tensorflow",
"tensorflow.contrib.summary as tfs import os import json FLAGS = tf.flags.FLAGS def main(argv=None): #########",
"EncoderCellsBuilder.simple_dense_embedder_builder(activation=activation)), name='encoder') decoder = Decoder(tree_def=tree_gen.tree_def, embedding_size=FLAGS.embedding_size, max_node_count=FLAGS.max_node_count, max_depth=FLAGS.max_depth, max_arity=FLAGS.max_arity, cut_arity=FLAGS.cut_arity, cellsbuilder=DecoderCellsBuilder( distrib_builder= DecoderCellsBuilder.simple_distrib_cell_builder(FLAGS.hidden_cell_coef,",
"Decoder(tree_def=tree_gen.tree_def, embedding_size=FLAGS.embedding_size, max_node_count=FLAGS.max_node_count, max_depth=FLAGS.max_depth, max_arity=FLAGS.max_arity, cut_arity=FLAGS.cut_arity, cellsbuilder=DecoderCellsBuilder( distrib_builder= DecoderCellsBuilder.simple_distrib_cell_builder(FLAGS.hidden_cell_coef, activation=activation), categorical_value_inflater_builder= DecoderCellsBuilder.simple_1ofk_value_inflater_builder(FLAGS.hidden_cell_coef, activation=activation),",
"gnorm) optimizer.apply_gradients(zip(grad, variables), global_step=tf.train.get_or_create_global_step()) if i % FLAGS.check_every == 0: batch_unsuperv = decoder(encodings=batch_enc.get_root_embeddings())",
"cut_arity=FLAGS.cut_arity, cellsbuilder=DecoderCellsBuilder( distrib_builder= DecoderCellsBuilder.simple_distrib_cell_builder(FLAGS.hidden_cell_coef, activation=activation), categorical_value_inflater_builder= DecoderCellsBuilder.simple_1ofk_value_inflater_builder(FLAGS.hidden_cell_coef, activation=activation), dense_value_inflater_builder=None, # unused node_inflater_builder= DecoderCellsBuilder.simple_node_inflater_builder(FLAGS.hidden_cell_coef,",
"TRAINING ########### optimizer = tf.train.AdamOptimizer() with tfs.always_record_summaries(): for i in range(FLAGS.max_iter): with tfe.GradientTape()",
"tf import tensorflow.contrib.eager as tfe import tensorflow.contrib.summary as tfs import os import json",
"main(argv=None): ######### # Checkpoints and Summaries ######### if tf.gfile.Exists(FLAGS.model_dir): if FLAGS.overwrite: tf.logging.warn(\"Deleting old",
"in range(FLAGS.max_iter): with tfe.GradientTape() as tape: xs = get_batch() batch_enc = encoder(xs) batch_dec",
"FLAGS.max_arity) def get_batch(): return [tree_gen.generate(FLAGS.max_depth) for _ in range(FLAGS.batch_size)] ######### # MODEL #########",
"_, _, v_avg_sup, v_acc_sup = Tree.compare_trees(xs, batch_dec.decoded_trees) s_avg, s_acc, v_avg, v_acc = Tree.compare_trees(xs,",
"tf.logging.warn(\"Deleting old log directory at {}\".format(FLAGS.model_dir)) tf.gfile.DeleteRecursively(FLAGS.model_dir) tf.gfile.MakeDirs(FLAGS.model_dir) else: raise ValueError(\"Log dir already",
"DecoderCellsBuilder.simple_node_inflater_builder(FLAGS.hidden_cell_coef, activation=activation, gate=FLAGS.decoder_gate)), variable_arity_strategy=FLAGS.dec_variable_arity_strategy) ########### # TRAINING ########### optimizer = tf.train.AdamOptimizer() with tfs.always_record_summaries():",
"0.02, gnorm) tfs.scalar(\"norms/grad\", gnorm) optimizer.apply_gradients(zip(grad, variables), global_step=tf.train.get_or_create_global_step()) if i % FLAGS.check_every == 0:",
"cut_arity=FLAGS.cut_arity, max_arity=FLAGS.max_arity, variable_arity_strategy=FLAGS.enc_variable_arity_strategy, cellsbuilder=EncoderCellsBuilder( EncoderCellsBuilder.simple_cell_builder(hidden_coef=FLAGS.hidden_cell_coef, activation=activation, gate=FLAGS.encoder_gate), EncoderCellsBuilder.simple_dense_embedder_builder(activation=activation)), name='encoder') decoder = Decoder(tree_def=tree_gen.tree_def, embedding_size=FLAGS.embedding_size,",
"batch_unsuperv = decoder(encodings=batch_enc.get_root_embeddings()) _, _, v_avg_sup, v_acc_sup = Tree.compare_trees(xs, batch_dec.decoded_trees) s_avg, s_acc, v_avg,",
"import tensorflow.contrib.eager as tfe import tensorflow.contrib.summary as tfs import os import json FLAGS",
"if FLAGS.overwrite: tf.logging.warn(\"Deleting old log directory at {}\".format(FLAGS.model_dir)) tf.gfile.DeleteRecursively(FLAGS.model_dir) tf.gfile.MakeDirs(FLAGS.model_dir) else: raise ValueError(\"Log",
"loss_val) tfs.scalar(\"loss/loss\", loss) tfs.scalar(\"overlaps/supervised/value_avg\", v_avg_sup) tfs.scalar(\"overlaps/supervised/value_acc\", v_acc_sup) tfs.scalar(\"overlaps/unsupervised/struct_avg\", s_avg) tfs.scalar(\"overlaps/unsupervised/struct_acc\", s_acc) tfs.scalar(\"overlaps/unsupervised/value_avg\", v_avg)",
"i in range(FLAGS.max_iter): with tfe.GradientTape() as tape: xs = get_batch() batch_enc = encoder(xs)",
"s_acc) tfs.scalar(\"overlaps/unsupervised/value_avg\", v_avg) tfs.scalar(\"overlaps/unsupervised/value_acc\", v_acc) if __name__ == \"__main__\": define_common_flags() define_encoder_flags() define_decoder_flags() tfe.run()",
"raise ValueError(\"Log dir already exists!\") else: tf.gfile.MakeDirs(FLAGS.model_dir) summary_writer = tfs.create_file_writer(FLAGS.model_dir, flush_millis=1000) summary_writer.set_as_default() print(\"Summaries",
"optimizer = tf.train.AdamOptimizer() with tfs.always_record_summaries(): for i in range(FLAGS.max_iter): with tfe.GradientTape() as tape:",
"embedding_size=FLAGS.embedding_size, cut_arity=FLAGS.cut_arity, max_arity=FLAGS.max_arity, variable_arity_strategy=FLAGS.enc_variable_arity_strategy, cellsbuilder=EncoderCellsBuilder( EncoderCellsBuilder.simple_cell_builder(hidden_coef=FLAGS.hidden_cell_coef, activation=activation, gate=FLAGS.encoder_gate), EncoderCellsBuilder.simple_dense_embedder_builder(activation=activation)), name='encoder') decoder = Decoder(tree_def=tree_gen.tree_def,",
"import * import tensorflow as tf import tensorflow.contrib.eager as tfe import tensorflow.contrib.summary as",
"from tensorflow_trees.encoder import Encoder, EncoderCellsBuilder from tensorflow_trees.decoder import Decoder, DecoderCellsBuilder from examples.simple_expression.exp_definition import",
"tfs.scalar(\"overlaps/unsupervised/struct_avg\", s_avg) tfs.scalar(\"overlaps/unsupervised/struct_acc\", s_acc) tfs.scalar(\"overlaps/unsupervised/value_avg\", v_avg) tfs.scalar(\"overlaps/unsupervised/value_acc\", v_acc) if __name__ == \"__main__\": define_common_flags()",
"Encoder, EncoderCellsBuilder from tensorflow_trees.decoder import Decoder, DecoderCellsBuilder from examples.simple_expression.exp_definition import BinaryExpressionTreeGen, NaryExpressionTreeGen from",
"import tensorflow as tf import tensorflow.contrib.eager as tfe import tensorflow.contrib.summary as tfs import",
"old log directory at {}\".format(FLAGS.model_dir)) tf.gfile.DeleteRecursively(FLAGS.model_dir) tf.gfile.MakeDirs(FLAGS.model_dir) else: raise ValueError(\"Log dir already exists!\")",
"# DATA ######### if FLAGS.fixed_arity: tree_gen = BinaryExpressionTreeGen(9) else: tree_gen = NaryExpressionTreeGen(9, FLAGS.max_arity)",
"grad = tape.gradient(loss, variables) gnorm = tf.global_norm(grad) grad, _ = tf.clip_by_global_norm(grad, 0.02, gnorm)",
"else: tf.gfile.MakeDirs(FLAGS.model_dir) summary_writer = tfs.create_file_writer(FLAGS.model_dir, flush_millis=1000) summary_writer.set_as_default() print(\"Summaries in \" + FLAGS.model_dir) with",
"if tf.gfile.Exists(FLAGS.model_dir): if FLAGS.overwrite: tf.logging.warn(\"Deleting old log directory at {}\".format(FLAGS.model_dir)) tf.gfile.DeleteRecursively(FLAGS.model_dir) tf.gfile.MakeDirs(FLAGS.model_dir) else:",
"max_depth=FLAGS.max_depth, max_arity=FLAGS.max_arity, cut_arity=FLAGS.cut_arity, cellsbuilder=DecoderCellsBuilder( distrib_builder= DecoderCellsBuilder.simple_distrib_cell_builder(FLAGS.hidden_cell_coef, activation=activation), categorical_value_inflater_builder= DecoderCellsBuilder.simple_1ofk_value_inflater_builder(FLAGS.hidden_cell_coef, activation=activation), dense_value_inflater_builder=None, # unused",
"tensorflow as tf import tensorflow.contrib.eager as tfe import tensorflow.contrib.summary as tfs import os",
"tfs.scalar(\"loss/val\", loss_val) tfs.scalar(\"loss/loss\", loss) tfs.scalar(\"overlaps/supervised/value_avg\", v_avg_sup) tfs.scalar(\"overlaps/supervised/value_acc\", v_acc_sup) tfs.scalar(\"overlaps/unsupervised/struct_avg\", s_avg) tfs.scalar(\"overlaps/unsupervised/struct_acc\", s_acc) tfs.scalar(\"overlaps/unsupervised/value_avg\",",
"activation = getattr(tf.nn, FLAGS.activation) encoder = Encoder(tree_def=tree_gen.tree_def, embedding_size=FLAGS.embedding_size, cut_arity=FLAGS.cut_arity, max_arity=FLAGS.max_arity, variable_arity_strategy=FLAGS.enc_variable_arity_strategy, cellsbuilder=EncoderCellsBuilder( EncoderCellsBuilder.simple_cell_builder(hidden_coef=FLAGS.hidden_cell_coef,",
"######### if tf.gfile.Exists(FLAGS.model_dir): if FLAGS.overwrite: tf.logging.warn(\"Deleting old log directory at {}\".format(FLAGS.model_dir)) tf.gfile.DeleteRecursively(FLAGS.model_dir) tf.gfile.MakeDirs(FLAGS.model_dir)",
"loss_val = batch_dec.reconstruction_loss() loss = loss_struct + loss_val variables = encoder.variables + decoder.variables",
"= decoder(encodings=batch_enc.get_root_embeddings()) _, _, v_avg_sup, v_acc_sup = Tree.compare_trees(xs, batch_dec.decoded_trees) s_avg, s_acc, v_avg, v_acc",
"else: raise ValueError(\"Log dir already exists!\") else: tf.gfile.MakeDirs(FLAGS.model_dir) summary_writer = tfs.create_file_writer(FLAGS.model_dir, flush_millis=1000) summary_writer.set_as_default()",
"_ in range(FLAGS.batch_size)] ######### # MODEL ######### activation = getattr(tf.nn, FLAGS.activation) encoder =",
"= tape.gradient(loss, variables) gnorm = tf.global_norm(grad) grad, _ = tf.clip_by_global_norm(grad, 0.02, gnorm) tfs.scalar(\"norms/grad\",",
"DecoderCellsBuilder from examples.simple_expression.exp_definition import BinaryExpressionTreeGen, NaryExpressionTreeGen from tensorflow_trees.definition import Tree from examples.simple_expression.flags_definition import",
"DATA ######### if FLAGS.fixed_arity: tree_gen = BinaryExpressionTreeGen(9) else: tree_gen = NaryExpressionTreeGen(9, FLAGS.max_arity) def",
"loss_struct + loss_val variables = encoder.variables + decoder.variables grad = tape.gradient(loss, variables) gnorm",
"0: batch_unsuperv = decoder(encodings=batch_enc.get_root_embeddings()) _, _, v_avg_sup, v_acc_sup = Tree.compare_trees(xs, batch_dec.decoded_trees) s_avg, s_acc,",
"def get_batch(): return [tree_gen.generate(FLAGS.max_depth) for _ in range(FLAGS.batch_size)] ######### # MODEL ######### activation",
"DecoderCellsBuilder.simple_1ofk_value_inflater_builder(FLAGS.hidden_cell_coef, activation=activation), dense_value_inflater_builder=None, # unused node_inflater_builder= DecoderCellsBuilder.simple_node_inflater_builder(FLAGS.hidden_cell_coef, activation=activation, gate=FLAGS.decoder_gate)), variable_arity_strategy=FLAGS.dec_variable_arity_strategy) ########### # TRAINING",
"get_batch(): return [tree_gen.generate(FLAGS.max_depth) for _ in range(FLAGS.batch_size)] ######### # MODEL ######### activation =",
"open(os.path.join(FLAGS.model_dir, \"flags.json\"), 'w') as f: json.dump(FLAGS.flag_values_dict(), f) ######### # DATA ######### if FLAGS.fixed_arity:",
"directory at {}\".format(FLAGS.model_dir)) tf.gfile.DeleteRecursively(FLAGS.model_dir) tf.gfile.MakeDirs(FLAGS.model_dir) else: raise ValueError(\"Log dir already exists!\") else: tf.gfile.MakeDirs(FLAGS.model_dir)",
"in range(FLAGS.batch_size)] ######### # MODEL ######### activation = getattr(tf.nn, FLAGS.activation) encoder = Encoder(tree_def=tree_gen.tree_def,",
"EncoderCellsBuilder.simple_cell_builder(hidden_coef=FLAGS.hidden_cell_coef, activation=activation, gate=FLAGS.encoder_gate), EncoderCellsBuilder.simple_dense_embedder_builder(activation=activation)), name='encoder') decoder = Decoder(tree_def=tree_gen.tree_def, embedding_size=FLAGS.embedding_size, max_node_count=FLAGS.max_node_count, max_depth=FLAGS.max_depth, max_arity=FLAGS.max_arity, cut_arity=FLAGS.cut_arity,",
"grad, _ = tf.clip_by_global_norm(grad, 0.02, gnorm) tfs.scalar(\"norms/grad\", gnorm) optimizer.apply_gradients(zip(grad, variables), global_step=tf.train.get_or_create_global_step()) if i",
"= Decoder(tree_def=tree_gen.tree_def, embedding_size=FLAGS.embedding_size, max_node_count=FLAGS.max_node_count, max_depth=FLAGS.max_depth, max_arity=FLAGS.max_arity, cut_arity=FLAGS.cut_arity, cellsbuilder=DecoderCellsBuilder( distrib_builder= DecoderCellsBuilder.simple_distrib_cell_builder(FLAGS.hidden_cell_coef, activation=activation), categorical_value_inflater_builder= DecoderCellsBuilder.simple_1ofk_value_inflater_builder(FLAGS.hidden_cell_coef,",
"variables) gnorm = tf.global_norm(grad) grad, _ = tf.clip_by_global_norm(grad, 0.02, gnorm) tfs.scalar(\"norms/grad\", gnorm) optimizer.apply_gradients(zip(grad,",
"tfs.scalar(\"overlaps/unsupervised/struct_acc\", s_acc) tfs.scalar(\"overlaps/unsupervised/value_avg\", v_avg) tfs.scalar(\"overlaps/unsupervised/value_acc\", v_acc) if __name__ == \"__main__\": define_common_flags() define_encoder_flags() define_decoder_flags()",
"Summaries ######### if tf.gfile.Exists(FLAGS.model_dir): if FLAGS.overwrite: tf.logging.warn(\"Deleting old log directory at {}\".format(FLAGS.model_dir)) tf.gfile.DeleteRecursively(FLAGS.model_dir)",
"= batch_dec.reconstruction_loss() loss = loss_struct + loss_val variables = encoder.variables + decoder.variables grad",
"variable_arity_strategy=FLAGS.enc_variable_arity_strategy, cellsbuilder=EncoderCellsBuilder( EncoderCellsBuilder.simple_cell_builder(hidden_coef=FLAGS.hidden_cell_coef, activation=activation, gate=FLAGS.encoder_gate), EncoderCellsBuilder.simple_dense_embedder_builder(activation=activation)), name='encoder') decoder = Decoder(tree_def=tree_gen.tree_def, embedding_size=FLAGS.embedding_size, max_node_count=FLAGS.max_node_count, max_depth=FLAGS.max_depth,",
"cellsbuilder=DecoderCellsBuilder( distrib_builder= DecoderCellsBuilder.simple_distrib_cell_builder(FLAGS.hidden_cell_coef, activation=activation), categorical_value_inflater_builder= DecoderCellsBuilder.simple_1ofk_value_inflater_builder(FLAGS.hidden_cell_coef, activation=activation), dense_value_inflater_builder=None, # unused node_inflater_builder= DecoderCellsBuilder.simple_node_inflater_builder(FLAGS.hidden_cell_coef, activation=activation,",
"variable_arity_strategy=FLAGS.dec_variable_arity_strategy) ########### # TRAINING ########### optimizer = tf.train.AdamOptimizer() with tfs.always_record_summaries(): for i in",
"decoder(encodings=batch_enc.get_root_embeddings(), targets=xs) loss_struct, loss_val = batch_dec.reconstruction_loss() loss = loss_struct + loss_val variables =",
"dir already exists!\") else: tf.gfile.MakeDirs(FLAGS.model_dir) summary_writer = tfs.create_file_writer(FLAGS.model_dir, flush_millis=1000) summary_writer.set_as_default() print(\"Summaries in \"",
"cellsbuilder=EncoderCellsBuilder( EncoderCellsBuilder.simple_cell_builder(hidden_coef=FLAGS.hidden_cell_coef, activation=activation, gate=FLAGS.encoder_gate), EncoderCellsBuilder.simple_dense_embedder_builder(activation=activation)), name='encoder') decoder = Decoder(tree_def=tree_gen.tree_def, embedding_size=FLAGS.embedding_size, max_node_count=FLAGS.max_node_count, max_depth=FLAGS.max_depth, max_arity=FLAGS.max_arity,",
"dense_value_inflater_builder=None, # unused node_inflater_builder= DecoderCellsBuilder.simple_node_inflater_builder(FLAGS.hidden_cell_coef, activation=activation, gate=FLAGS.decoder_gate)), variable_arity_strategy=FLAGS.dec_variable_arity_strategy) ########### # TRAINING ########### optimizer",
"v_avg_sup, v_acc_sup = Tree.compare_trees(xs, batch_dec.decoded_trees) s_avg, s_acc, v_avg, v_acc = Tree.compare_trees(xs, batch_unsuperv.decoded_trees) print(\"{0}:\\t{1:.3f}\".format(i,",
"tfs import os import json FLAGS = tf.flags.FLAGS def main(argv=None): ######### # Checkpoints",
"Decoder, DecoderCellsBuilder from examples.simple_expression.exp_definition import BinaryExpressionTreeGen, NaryExpressionTreeGen from tensorflow_trees.definition import Tree from examples.simple_expression.flags_definition",
"v_acc_sup) tfs.scalar(\"overlaps/unsupervised/struct_avg\", s_avg) tfs.scalar(\"overlaps/unsupervised/struct_acc\", s_acc) tfs.scalar(\"overlaps/unsupervised/value_avg\", v_avg) tfs.scalar(\"overlaps/unsupervised/value_acc\", v_acc) if __name__ == \"__main__\":",
"= encoder(xs) batch_dec = decoder(encodings=batch_enc.get_root_embeddings(), targets=xs) loss_struct, loss_val = batch_dec.reconstruction_loss() loss = loss_struct",
"tape: xs = get_batch() batch_enc = encoder(xs) batch_dec = decoder(encodings=batch_enc.get_root_embeddings(), targets=xs) loss_struct, loss_val",
"'w') as f: json.dump(FLAGS.flag_values_dict(), f) ######### # DATA ######### if FLAGS.fixed_arity: tree_gen =",
"= loss_struct + loss_val variables = encoder.variables + decoder.variables grad = tape.gradient(loss, variables)",
"= tf.clip_by_global_norm(grad, 0.02, gnorm) tfs.scalar(\"norms/grad\", gnorm) optimizer.apply_gradients(zip(grad, variables), global_step=tf.train.get_or_create_global_step()) if i % FLAGS.check_every",
"at {}\".format(FLAGS.model_dir)) tf.gfile.DeleteRecursively(FLAGS.model_dir) tf.gfile.MakeDirs(FLAGS.model_dir) else: raise ValueError(\"Log dir already exists!\") else: tf.gfile.MakeDirs(FLAGS.model_dir) summary_writer",
"# Checkpoints and Summaries ######### if tf.gfile.Exists(FLAGS.model_dir): if FLAGS.overwrite: tf.logging.warn(\"Deleting old log directory",
"for i in range(FLAGS.max_iter): with tfe.GradientTape() as tape: xs = get_batch() batch_enc =",
"log directory at {}\".format(FLAGS.model_dir)) tf.gfile.DeleteRecursively(FLAGS.model_dir) tf.gfile.MakeDirs(FLAGS.model_dir) else: raise ValueError(\"Log dir already exists!\") else:",
"tfs.scalar(\"loss/loss\", loss) tfs.scalar(\"overlaps/supervised/value_avg\", v_avg_sup) tfs.scalar(\"overlaps/supervised/value_acc\", v_acc_sup) tfs.scalar(\"overlaps/unsupervised/struct_avg\", s_avg) tfs.scalar(\"overlaps/unsupervised/struct_acc\", s_acc) tfs.scalar(\"overlaps/unsupervised/value_avg\", v_avg) tfs.scalar(\"overlaps/unsupervised/value_acc\",",
"########### optimizer = tf.train.AdamOptimizer() with tfs.always_record_summaries(): for i in range(FLAGS.max_iter): with tfe.GradientTape() as",
"= tf.global_norm(grad) grad, _ = tf.clip_by_global_norm(grad, 0.02, gnorm) tfs.scalar(\"norms/grad\", gnorm) optimizer.apply_gradients(zip(grad, variables), global_step=tf.train.get_or_create_global_step())",
"loss_struct, loss_val = batch_dec.reconstruction_loss() loss = loss_struct + loss_val variables = encoder.variables +",
"import Decoder, DecoderCellsBuilder from examples.simple_expression.exp_definition import BinaryExpressionTreeGen, NaryExpressionTreeGen from tensorflow_trees.definition import Tree from",
"if FLAGS.fixed_arity: tree_gen = BinaryExpressionTreeGen(9) else: tree_gen = NaryExpressionTreeGen(9, FLAGS.max_arity) def get_batch(): return"
] |