max_stars_repo_path
stringlengths
4
245
max_stars_repo_name
stringlengths
7
115
max_stars_count
int64
101
368k
id
stringlengths
2
8
content
stringlengths
6
1.03M
tests/components/lateral_erosion/test_node_finder.py
scottrdavid/landlab
257
150445
<filename>tests/components/lateral_erosion/test_node_finder.py import numpy as np import pytest from landlab import RasterModelGrid from landlab.components.lateral_erosion.node_finder import angle_finder @pytest.mark.parametrize( "node_1,node_2", [(12, 8), (13, 3), (8, 2), (3, 1), (6, 2), (11, 1), (12, 6), (13, 11)], ) def test_angle_finder_90(node_1, node_2): grid = RasterModelGrid((4, 5)) assert angle_finder(grid, node_1, 7, node_2) == pytest.approx(np.pi * 0.5) assert angle_finder(grid, node_2, 7, node_1) == pytest.approx(np.pi * 0.5) @pytest.mark.parametrize( "node_1,node_2", [(10, 6), (6, 2), (2, 1), (1, 0), (0, 4), (4, 8), (8, 9), (9, 10)], ) def test_angle_finder_45(node_1, node_2): grid = RasterModelGrid((3, 4)) assert angle_finder(grid, node_1, 5, node_2) == pytest.approx(np.pi * 0.25) assert angle_finder(grid, node_2, 5, node_1) == pytest.approx(np.pi * 0.25) @pytest.mark.parametrize("node", [6, 10, 9, 8, 4, 0, 1, 2]) def test_angle_finder_0(node): grid = RasterModelGrid((3, 4)) assert angle_finder(grid, node, 5, node) == pytest.approx(0.0) def test_angle_finder_array(): grid = RasterModelGrid((3, 4)) assert angle_finder(grid, (10, 6, 2), 5, (6, 2, 1)) == pytest.approx(np.pi * 0.25) @pytest.mark.parametrize("dx", [0.5, 1.0, 2.0]) @pytest.mark.parametrize("dy", [0.5, 1.0, 2.0]) def test_unequal_spacing(dx, dy): grid = RasterModelGrid((3, 4), xy_spacing=(dx, dy)) assert angle_finder(grid, (6, 9, 4, 1), 5, (1, 6, 9, 4)) == pytest.approx( np.pi * 0.5 ) assert angle_finder(grid, (10, 8, 0, 2), 5, (6, 4, 4, 6)) == pytest.approx( np.arctan(dy / dx) ) assert angle_finder(grid, (9, 1, 1, 9), 5, (8, 0, 2, 10)) == pytest.approx( np.arctan(dx / dy) )
mmdet/models/roi_heads/bbox_heads/obb/gv_bbox_head.py
vpeopleonatank/OBBDetection
274
150473
<reponame>vpeopleonatank/OBBDetection<filename>mmdet/models/roi_heads/bbox_heads/obb/gv_bbox_head.py import torch import torch.nn as nn import torch.nn.functional as F from torch.nn.modules.utils import _pair from mmdet.core import (auto_fp16, build_bbox_coder, force_fp32, multi_apply, multiclass_arb_nms, hbb2poly, bbox2type) from mmdet.models.builder import HEADS, build_loss from mmdet.models.losses import accuracy @HEADS.register_module() class GVBBoxHead(nn.Module): def __init__(self, with_avg_pool=False, num_shared_fcs=2, roi_feat_size=7, in_channels=256, fc_out_channels=1024, num_classes=15, reg_class_agnostic=False, ratio_thr=0.8, bbox_coder=dict( type='DeltaXYWHBBoxCoder', target_means=[0., 0., 0., 0.], target_stds=[0.1, 0.1, 0.2, 0.2]), fix_coder=dict(type='GVFixCoder'), ratio_coder=dict(type='GVRatioCoder'), loss_cls=dict( type='CrossEntropyLoss', use_sigmoid=False, loss_weight=1.0), loss_bbox=dict( type='SmoothL1Loss', beta=1./3., loss_weight=1.0), loss_fix=dict( type='SmoothL1Loss', beta=1./3., loss_weight=1.0), loss_ratio=dict( type='SmoothL1Loss', beta=1./3., loss_weight=16.0), ): super(GVBBoxHead, self).__init__() self.with_avg_pool = with_avg_pool self.num_shared_fcs = num_shared_fcs self.roi_feat_size = _pair(roi_feat_size) self.roi_feat_area = self.roi_feat_size[0] * self.roi_feat_size[1] self.in_channels = in_channels self.fc_out_channels = fc_out_channels self.num_classes = num_classes self.reg_class_agnostic = reg_class_agnostic self.ratio_thr = ratio_thr self.fp16_enabled = False self.start_bbox_type = 'hbb' self.end_bbox_type = 'poly' self.bbox_coder = build_bbox_coder(bbox_coder) self.fix_coder = build_bbox_coder(fix_coder) self.ratio_coder = build_bbox_coder(ratio_coder) self.loss_cls = build_loss(loss_cls) self.loss_bbox = build_loss(loss_bbox) self.loss_fix = build_loss(loss_fix) self.loss_ratio = build_loss(loss_ratio) self._init_layers() def _init_layers(self): self.relu = nn.ReLU(inplace=True) in_channels = self.in_channels if self.with_avg_pool: self.avg_pool = nn.AvgPool2d(self.roi_feat_size) else: in_channels *= self.roi_feat_area self.shared_fcs = nn.ModuleList() for i in range(self.num_shared_fcs): fc_in_channels = ( in_channels if i == 0 else self.fc_out_channels) self.shared_fcs.append( nn.Linear(fc_in_channels, self.fc_out_channels)) last_dim = in_channels if self.num_shared_fcs == 0 \ else self.fc_out_channels self.fc_cls = nn.Linear(last_dim, self.num_classes + 1) out_dim_reg = (4 if self.reg_class_agnostic else 4*self.num_classes) self.fc_reg = nn.Linear(last_dim, out_dim_reg) out_dim_fix = (4 if self.reg_class_agnostic else 4*self.num_classes) self.fc_fix = nn.Linear(last_dim, out_dim_fix) out_dim_ratio = (1 if self.reg_class_agnostic else self.num_classes) self.fc_ratio = nn.Linear(last_dim, out_dim_ratio) def init_weights(self): for m in self.shared_fcs: nn.init.xavier_uniform_(m.weight) nn.init.constant_(m.bias, 0) nn.init.normal_(self.fc_cls.weight, 0, 0.01) nn.init.constant_(self.fc_cls.bias, 0) nn.init.normal_(self.fc_reg.weight, 0, 0.001) nn.init.constant_(self.fc_reg.bias, 0) nn.init.normal_(self.fc_fix.weight, 0, 0.001) nn.init.constant_(self.fc_fix.bias, 0) nn.init.normal_(self.fc_ratio.weight, 0, 0.001) nn.init.constant_(self.fc_ratio.bias, 0) @auto_fp16() def forward(self, x): if self.with_avg_pool: x = self.avg_pool(x) x = x.flatten(1) for fc in self.shared_fcs: x = self.relu(fc(x)) cls_score = self.fc_cls(x) bbox_pred = self.fc_reg(x) fix_pred = torch.sigmoid(self.fc_fix(x)) ratio_pred = torch.sigmoid(self.fc_ratio(x)) return cls_score, bbox_pred, fix_pred, ratio_pred def _get_target_single(self, pos_bboxes, neg_bboxes, pos_gt_bboxes, pos_gt_labels, cfg): num_pos = pos_bboxes.size(0) num_neg = neg_bboxes.size(0) num_samples = num_pos + num_neg # original implementation uses new_zeros since BG are set to be 0 # now use empty & fill because BG cat_id = num_classes, # FG cat_id = [0, num_classes-1] labels = pos_bboxes.new_full((num_samples, ), self.num_classes, dtype=torch.long) label_weights = pos_bboxes.new_zeros(num_samples) bbox_targets = pos_bboxes.new_zeros(num_samples, 4) bbox_weights = pos_bboxes.new_zeros(num_samples, 4) fix_targets = pos_bboxes.new_zeros(num_samples, 4) fix_weights = pos_bboxes.new_zeros(num_samples, 4) ratio_targets = pos_bboxes.new_zeros(num_samples, 1) ratio_weights = pos_bboxes.new_zeros(num_samples, 1) if num_pos > 0: labels[:num_pos] = pos_gt_labels pos_weight = 1.0 if cfg.pos_weight <= 0 else cfg.pos_weight label_weights[:num_pos] = pos_weight pos_bbox_targets = self.bbox_coder.encode( pos_bboxes, bbox2type(pos_gt_bboxes, 'hbb')) bbox_targets[:num_pos, :] = pos_bbox_targets bbox_weights[:num_pos, :] = 1 pos_fix_targets = self.fix_coder.encode( bbox2type(pos_gt_bboxes, 'poly')) fix_targets[:num_pos, :] = pos_fix_targets fix_weights[:num_pos, :] = 1 pos_ratio_targets = self.ratio_coder.encode( bbox2type(pos_gt_bboxes, 'poly')) ratio_targets[:num_pos, :] = pos_ratio_targets ratio_weights[:num_pos, :] = 1 if num_neg > 0: label_weights[-num_neg:] = 1.0 return (labels, label_weights, bbox_targets, bbox_weights, fix_targets, fix_weights, ratio_targets, ratio_weights) def get_targets(self, sampling_results, gt_bboxes, gt_labels, rcnn_train_cfg, concat=True): pos_bboxes_list = [res.pos_bboxes for res in sampling_results] neg_bboxes_list = [res.neg_bboxes for res in sampling_results] pos_gt_bboxes_list = [res.pos_gt_bboxes for res in sampling_results] pos_gt_labels_list = [res.pos_gt_labels for res in sampling_results] outputs = multi_apply( self._get_target_single, pos_bboxes_list, neg_bboxes_list, pos_gt_bboxes_list, pos_gt_labels_list, cfg=rcnn_train_cfg) (labels, label_weights, bbox_targets, bbox_weights, fix_targets, fix_weights, ratio_targets, ratio_weights) = outputs if concat: labels = torch.cat(labels, 0) label_weights = torch.cat(label_weights, 0) bbox_targets = torch.cat(bbox_targets, 0) bbox_weights = torch.cat(bbox_weights, 0) fix_targets = torch.cat(fix_targets, 0) fix_weights = torch.cat(fix_weights, 0) ratio_targets = torch.cat(ratio_targets, 0) ratio_weights = torch.cat(ratio_weights, 0) return (labels, label_weights, bbox_targets, bbox_weights, fix_targets, fix_weights, ratio_targets, ratio_weights) @force_fp32(apply_to=('cls_score', 'bbox_pred', 'fix_pred', 'ratio_pred')) def loss(self, cls_score, bbox_pred, fix_pred, ratio_pred, rois, labels, label_weights, bbox_targets, bbox_weights, fix_targets, fix_weights, ratio_targets, ratio_weights, reduction_override=None): losses = dict() avg_factor = max(torch.sum(label_weights > 0).float().item(), 1.) if cls_score.numel() > 0: losses['loss_cls'] = self.loss_cls( cls_score, labels, label_weights, avg_factor=avg_factor, reduction_override=reduction_override) losses['acc'] = accuracy(cls_score, labels) bg_class_ind = self.num_classes # 0~self.num_classes-1 are FG, self.num_classes is BG pos_inds = (labels >= 0) & (labels < bg_class_ind) # do not perform bounding box regression for BG anymore. if pos_inds.any(): if self.reg_class_agnostic: pos_bbox_pred = bbox_pred.view( bbox_pred.size(0), 4)[pos_inds.type(torch.bool)] else: pos_bbox_pred = bbox_pred.view( bbox_pred.size(0), -1, 4)[pos_inds.type(torch.bool), labels[pos_inds.type(torch.bool)]] losses['loss_bbox'] = self.loss_bbox( pos_bbox_pred, bbox_targets[pos_inds.type(torch.bool)], bbox_weights[pos_inds.type(torch.bool)], avg_factor=bbox_targets.size(0), reduction_override=reduction_override) else: losses['loss_bbox'] = bbox_pred.sum() * 0 if pos_inds.any(): if self.reg_class_agnostic: pos_fix_pred = fix_pred.view( fix_pred.size(0), 4)[pos_inds.type(torch.bool)] else: pos_fix_pred = fix_pred.view( fix_pred.size(0), -1, 4)[pos_inds.type(torch.bool), labels[pos_inds.type(torch.bool)]] losses['loss_fix'] = self.loss_fix( pos_fix_pred, fix_targets[pos_inds.type(torch.bool)], fix_weights[pos_inds.type(torch.bool)], avg_factor=fix_targets.size(0), reduction_override=reduction_override) else: losses['loss_fix'] = fix_pred.sum() * 0 if pos_inds.any(): if self.reg_class_agnostic: pos_ratio_pred = ratio_pred.view( ratio_pred.size(0), 1)[pos_inds.type(torch.bool)] else: pos_ratio_pred = ratio_pred.view( ratio_pred.size(0), -1, 1)[pos_inds.type(torch.bool), labels[pos_inds.type(torch.bool)]] losses['loss_ratio'] = self.loss_ratio( pos_ratio_pred, ratio_targets[pos_inds.type(torch.bool)], ratio_weights[pos_inds.type(torch.bool)], avg_factor=ratio_targets.size(0), reduction_override=reduction_override) else: losses['loss_ratio'] = ratio_pred.sum() * 0 return losses @force_fp32(apply_to=('cls_score', 'bbox_pred', 'fix_pred', 'ratio_pred')) def get_bboxes(self, rois, cls_score, bbox_pred, fix_pred, ratio_pred, img_shape, scale_factor, rescale=False, cfg=None): if isinstance(cls_score, list): cls_score = sum(cls_score) / float(len(cls_score)) scores = F.softmax(cls_score, dim=1) bboxes = self.bbox_coder.decode( rois[:, 1:], bbox_pred, max_shape=img_shape) polys = self.fix_coder.decode(bboxes, fix_pred) bboxes = bboxes.view(*ratio_pred.size(), 4) polys = polys.view(*ratio_pred.size(), 8) polys[ratio_pred > self.ratio_thr] = \ hbb2poly(bboxes[ratio_pred > self.ratio_thr]) if rescale: if isinstance(scale_factor, float): scale_factor = [scale_factor for _ in range(4)] scale_factor = bboxes.new_tensor(scale_factor) polys /= scale_factor.repeat(2) polys = polys.view(polys.size(0), -1) if cfg is None: return polys, scores else: det_bboxes, det_labels = \ multiclass_arb_nms(polys, scores, cfg.score_thr, cfg.nms, cfg.max_per_img, bbox_type='poly') return det_bboxes, det_labels def refine_bboxes(self, rois, labels, bbox_preds, fix_preds, ratio_preds, pos_is_gts, img_metas): img_ids = rois[:, 0].long().unique(sorted=True) assert img_ids.numel() <= len(img_metas) bboxes_list = [] for i in range(len(img_metas)): inds = torch.nonzero( rois[:, 0] == i, as_tuple=False).squeeze(dim=1) num_rois = inds.numel() bboxes_ = rois[inds, 1:] label_ = labels[inds] bbox_pred_ = bbox_preds[inds] fix_pred_ = fix_preds[inds] ratio_pred_ = ratio_preds[inds] img_meta_ = img_metas[i] pos_is_gts_ = pos_is_gts[i] bboxes = self.regress_by_class(bboxes_, label_, bbox_pred_, fix_pred_, ratio_pred_, img_meta_) # filter gt bboxes pos_keep = 1 - pos_is_gts_ keep_inds = pos_is_gts_.new_ones(num_rois) keep_inds[:len(pos_is_gts_)] = pos_keep bboxes_list.append(bboxes[keep_inds.type(torch.bool)]) return bboxes_list @force_fp32(apply_to=('bbox_pred', 'fix_pred', 'ratio_pred')) def regress_by_class(self, rois, label, bbox_pred, fix_pred, ratio_pred, img_meta): assert rois.size(1) == 4 or rois.size(1) == 5, repr(rois.shape) if not self.reg_class_agnostic: ratio_pred = torch.gather(ratio_pred, 1, label[:, None]) label = label * 4 inds = torch.stack([label + i for i in range(4)], 1) bbox_pred = torch.gather(bbox_pred, 1, inds) fix_pred = torch.gather(fix_pred, 1, inds) assert bbox_pred.size(1) == 4 assert fix_pred.size(1) == 4 if rois.size(1) == 4: bboxes = self.bbox_coder.decode( rois, bbox_pred, max_shape=img_meta['img_shape']) new_rois = self.fix_coder.decode(bboxes, fix_pred) ratio_pred = ratio_pred.squeeze(1) new_rois[ratio_pred > self.ratio_thr] = hbb2poly(bboxes) else: bboxes = self.bbox_coder.decode( rois[:, 1:], bbox_pred, max_shape=img_meta['img_shape']) polys = self.fix_coder.decode(bboxes, fix_pred) ratio_pred = ratio_pred.squeeze(1) polys[ratio_pred > self.ratio_thr] = hbb2poly(bboxes) new_rois = torch.cat((rois[:, [0]], polys), dim=1) return new_rois
src/dialogs/apiviewer.py
goncaloperes/Scraping_Facepager
430
150504
from PySide2.QtCore import * from PySide2.QtGui import * from PySide2.QtWidgets import * import os import shutil from tempfile import TemporaryDirectory import sys import re import json from widgets.textviewer import * from urllib.parse import urlparse import requests import threading import webbrowser import platform from utilities import * from widgets.progressbar import ProgressBar class ApiViewer(QDialog): logmessage = Signal(str) def __init__(self, parent=None): super(ApiViewer,self).__init__(parent) # Main window self.mainWindow = parent self.setWindowTitle("API Viewer") self.setMinimumWidth(700) self.setMinimumHeight(600) # Properties self.folder = os.path.join(os.path.expanduser("~"), 'Facepager', 'APIs') self.folderDefault = os.path.join(os.path.expanduser("~"), 'Facepager', 'DefaultAPIs') self.filesSuffix = ['.oa3.json'] self.lastSelected = None # Hold the list of loaded ApiDocs, # indexed by filename self.apis = {} # List of top nodes in the view, # indexed by filename # deprecated: use self.apis instead self.topNodes= {} self.detailTables = {} self.detailWidgets = {} self.allFilesLoaded = False self.filesDownloaded = False #layout layout = QVBoxLayout(self) self.setLayout(layout) #loading indicator self.loadingLock = threading.Lock() self.loadingIndicator = QLabel('Loading...please wait a second.') self.loadingIndicator.hide() layout.addWidget(self.loadingIndicator) #Middle central = QSplitter(self) layout.addWidget(central,1) #list view self.itemList = QTreeWidget(self) self.itemList.setHeaderHidden(True) self.itemList.setColumnCount(1) self.itemList.setIndentation(15) self.itemList.itemSelectionChanged.connect(self.currentChanged) central.addWidget(self.itemList) central.setStretchFactor(0, 0) #detail view self.detailView=QScrollArea() self.detailView.setWidgetResizable(True) self.detailWidget = QWidget() self.detailWidget.setAutoFillBackground(True) self.detailWidget.setStyleSheet("background-color: rgb(255,255,255);") self.detailLayout=QVBoxLayout() self.detailWidget.setLayout(self.detailLayout) self.detailView.setWidget(self.detailWidget) central.addWidget(self.detailView) central.setStretchFactor(1, 2) self.detailName = QLabel('') self.detailName.setWordWrap(True) self.detailName.setStyleSheet("QLabel {font-size:15pt;font-weight:bold;}") self.detailLayout.addWidget(self.detailName) self.detailDescription = TextViewer() #self.detailDescription .setStyleSheet("QTextViewer {padding-left:0px;}") self.detailLayout.addWidget(self.detailDescription) self.detailLayout.addStretch(100) #buttons buttons= QHBoxLayout() #QDialogButtonBox() self.folderButton = QPushButton("") self.folderButton.setFlat(True) self.folderButton.setText(self.folder) self.folderButton.clicked.connect(self.folderClicked) buttons.addWidget(self.folderButton) buttons.addStretch() self.reloadButton=QPushButton('Reload') self.reloadButton.clicked.connect(self.reloadDocs) self.reloadButton.setToolTip("Reload all API files.") buttons.addWidget(self.reloadButton) self.rejectButton=QPushButton('Close') self.rejectButton.clicked.connect(self.close) self.rejectButton.setToolTip("Close the window") buttons.addWidget(self.rejectButton) self.applyButton=QPushButton('Apply') self.applyButton.setDefault(True) self.applyButton.clicked.connect(self.applyItem) self.applyButton.setToolTip("Apply the selected path.") buttons.addWidget(self.applyButton) layout.addLayout(buttons) #status bar #self.statusbar = QStatusBar() #self.statusbar.insertWidget(0,self.folderButton) #layout.addWidget(self.statusbar) def folderClicked(self): if not os.path.exists(self.folder): os.makedirs(self.folder) if platform.system() == "Windows": webbrowser.open(self.folder) elif platform.system() == "Darwin": webbrowser.open('file:///' + self.folder) else: webbrowser.open('file:///' + self.folder) def reloadDocs(self): self.filesDownloaded = False self.downloadDefaultFiles() self.clear() self.topNodes = {} self.apis = {} self.initDocs() for i in range(0, self.mainWindow.RequestTabs.count()): tab = self.mainWindow.RequestTabs.widget(i) tab.reloadDoc() def showWindow(self): self.show() QApplication.processEvents() # Load files self.initDocs() # Select item if (self.lastSelected is None) or (self.lastSelected not in self.topNodes): selected = self.itemList.topLevelItem(0) else: selected = self.topNodes.get(self.lastSelected) self.itemList.setCurrentItem(selected) self.itemList.setFocus() #self.applyButton.setDefault(True) self.raise_() def showDoc(self, module, basepath, path, field = None): # Show self.show() QApplication.processEvents() self.initDocs() # Find file / module / api selectedItem = self.getApiNode(module, basepath, path) self.itemList.setCurrentItem(selectedItem) self.itemList.setFocus() # Focus field if field is not None: params = self.detailWidgets.get('Response',{}) while (not field in params) and (field != ''): field = field.rsplit('.', 1) field = field[0] if len(field) > 1 else '' if field in params: valuewidget = params.get(field) valuewidget.setStyleSheet("border: 2px solid blue;font-weight:bold;") self.detailView.ensureWidgetVisible(valuewidget) #self.exec_() def addDetailTable(self, caption): detailForm=QFormLayout() detailForm.setRowWrapPolicy(QFormLayout.DontWrapRows); detailForm.setFieldGrowthPolicy(QFormLayout.AllNonFixedFieldsGrow); detailForm.setFormAlignment(Qt.AlignLeft | Qt.AlignTop); detailForm.setLabelAlignment(Qt.AlignLeft); self.detailLayout.insertLayout(self.detailLayout.count()-1, detailForm,1) self.detailTables[caption] = detailForm caption = QLabel(caption) caption.setWordWrap(True) caption.setStyleSheet("QLabel {font-size:12pt;margin-top:1em;margin-bottom:0.5em;font-weight:bold;}") detailForm.addRow(caption) def addDetailText(self,value): detailCaption, detailForm = list(self.detailTables.items())[-1] caption = QLabel(value) caption.setStyleSheet("QLabel {padding-left:0.4em;}") caption.setWordWrap(True) detailForm.addRow(caption) def addDetailRow(self,name,value): detailCaption, detailForm = list(self.detailTables.items())[-1] nameWidget = QLabel(name) nameWidget.setWordWrap(True) nameWidget.setStyleSheet("QLabel {padding-left:0.4em;}") valueWidget = TextViewer() valueWidget.setText(value) detailForm.addRow(nameWidget,valueWidget) if not detailCaption in self.detailWidgets: self.detailWidgets[detailCaption] = {} self.detailWidgets[detailCaption][name] = nameWidget def currentChanged(self): self.clearDetails() current = self.itemList.currentItem() if current and current.isSelected(): data = current.data(0,Qt.UserRole) self.lastSelected = os.path.join(data.get('folder',''),data.get('filename','')) # Caption if data.get('type', '') == 'file': title = getDictValue(data, 'info.title') self.detailName.setText(title) # Description self.detailDescription.setText(getDictValue(data,'info.description')) # Info self.addDetailTable('Paths') self.addDetailRow('Documentation: ',getDictValue(data, 'info.externalDocs.url')) self.addDetailRow('Base path: ', getDictValue(data, 'info.servers.0.url')) elif data.get('type', '') == 'path': title = getDictValue(data, 'info.title') + " " + data['path'] self.detailName.setText(title) operation = getDictValue(data, 'operations.get', False) if operation: # Description self.detailDescription.setText(getDictValue(operation, 'summary')) # Info self.addDetailTable('Paths') self.addDetailRow('Documentation: ', getDictValue(operation, 'externalDocs.url')) self.addDetailRow('Base path: ', getDictValue(data, 'info.servers.0.url')) self.addDetailRow('Resource path: ', getDictValue(data, 'path')) # Parameters params = operation.get('parameters',{}) if params: self.addDetailTable('Parameters') for param in params: paramname = param.get('name') if param.get('in','query') == 'path': paramname = '<'+paramname+'>' # Description description = param.get('description') # Options schema = param.get('schema',{}) items = schema.get('items', {}) if schema.get('type') == 'array' else schema enum = items.get('enum', []) oneof = [value.get('const', '') for value in items.get('oneOf', [])] bool = ['0','1'] if items.get('type') == 'boolean' else [] options = ",".join(enum+oneof+bool) if options != '': description += "\n\nOptions: "+options self.addDetailRow(paramname, description) # Response self.addDetailTable('Response') self.addDetailText(getDictValue(operation, 'responses.200.description', '')) def addDetailProperties(schema, key = ''): if not isinstance(schema, dict): return False if schema.get('type', None) == 'object': properties = schema.get('properties',None) if isinstance(properties, dict): ref = properties.get("$ref",None) if ref is not None: properties = self.getSchemaComponent(data, ref) if isinstance(properties, dict): for name, value in properties.items(): if not isinstance(value,dict): return False self.addDetailRow(key + name, value.get('description', '')) if value.get("type",None) == "object": addDetailProperties(value,key+name+".") elif value.get("type",None) == "array": addDetailProperties(value,key+name+".") elif schema.get('type', None) == 'array': items = schema.get('items',{}) addDetailProperties(items, key+'*.') schema = getDictValue(operation, 'responses.200.content.application/json.schema', None) addDetailProperties(schema) self.detailWidget.show() def clearDetails(self): self.detailWidget.hide() self.detailName.setText("") self.detailDescription.setText("") for detailCaption,detailForm in self.detailTables.items(): while detailForm.rowCount() > 0: detailForm.removeRow(0) self.detailLayout.removeItem(detailForm) self.detailTables = {} self.detailWidgets = {} def clear(self): self.allFilesLoaded=False self.itemList.clear() self.clearDetails() def checkDefaultFiles(self): if not os.path.exists(self.folderDefault): self.reloadDocs() elif len(os.listdir(self.folderDefault)) == 0: self.reloadDocs() def downloadDefaultFiles(self,silent=False): with self.loadingLock: if self.filesDownloaded: return False # Progress progress = ProgressBar("Downloading default API definitions from GitHub...", self) if not silent else None QApplication.processEvents() # Create temporary download folder tmp = TemporaryDirectory(suffix='FacepagerDefaultAPIs') try: #Download files = requests.get("https://api.github.com/repos/strohne/Facepager/contents/apis").json() files = [f['path'] for f in files if f['path'].endswith(tuple(self.filesSuffix))] if progress is not None: progress.setMaximum(len(files)) for filename in files: response = requests.get("https://raw.githubusercontent.com/strohne/Facepager/master/"+filename) if response.status_code != 200: raise(f"GitHub is not available (status code {response.status_code})") with open(os.path.join(tmp.name, os.path.basename(filename)), 'wb') as f: f.write(response.content) if progress is not None: progress.step() # Create folder if not os.path.exists(self.folderDefault): os.makedirs(self.folderDefault) # Clear folder for filename in os.listdir(self.folderDefault): os.remove(os.path.join(self.folderDefault, filename)) # Move files from tempfolder for filename in os.listdir(tmp.name): shutil.move(os.path.join(tmp.name, filename), self.folderDefault) self.logmessage.emit("Default API definitions downloaded from GitHub.") except Exception as e: if not silent: QMessageBox.information(self,"Facepager","Error downloading default API definitions:"+str(e)) self.logmessage.emit("Error downloading default API definitions:"+str(e)) return False else: self.filesDownloaded = True return True finally: tmp.cleanup() if progress is not None: progress.close() def initDocs(self): if self.allFilesLoaded: return False self.loadingIndicator.show() QApplication.processEvents() try: #self.downloadDefaultFiles() if os.path.exists(self.folderDefault): files = [f for f in os.listdir(self.folderDefault) if f.endswith(tuple(self.filesSuffix))] for filename in files: self.loadFile(self.folderDefault, filename, True) if os.path.exists(self.folder): files = [f for f in os.listdir(self.folder) if f.endswith(tuple(self.filesSuffix))] for filename in files: self.loadFile(self.folder, filename) self.itemList.sortItems(0, Qt.AscendingOrder) self.allFilesLoaded = True except: self.loadingIndicator.hide() return False finally: self.loadingIndicator.hide() return True def loadFiles(self,folder, module, default=False): # self.downloadDefaultFiles(True) # Create folders if not os.path.exists(folder): os.makedirs(folder) module = module.replace(" ", "") for filename in os.listdir(folder): if filename.startswith(module) and filename.endswith(self.filesSuffix[0]): self.loadFile(folder, filename, default) def loadFile(self, folder, filename, default=False): if os.path.join(folder, filename) in self.topNodes: return self.topNodes[os.path.join(folder, filename)] if not os.path.isfile(os.path.join(folder, filename)): return None try: with open(os.path.join(folder, filename), 'r',encoding="utf-8") as input: data = json.load(input) if not isinstance(data,dict): return None data['x-facepager-default'] = default self.apis[os.path.join(folder, filename)] = data # Prepare node itemData = {} itemData = {k:v for (k,v) in data.items() if k.startswith('x-facepager-')} itemData['type'] = 'file' itemData['filename'] = filename itemData['folder'] = folder itemData['default'] = default itemData['info'] = data.get('info',{}) itemData['info']['externalDocs'] = data.get('externalDocs',{}) itemData['info']['servers'] = data.get('servers', []) itemData['module'] = data.get("x-facepager-module", "Generic") # Root node in the view if default: itemData['caption'] = itemData['info'].get('title', '') +" *" else: itemData['caption'] = itemData['info'].get('title', '') topItem = ApiWidgetItem() topItem.setText(0,itemData['caption']) ft = topItem.font(0) ft.setWeight(QFont.Bold) topItem.setFont(0,ft) if default: topItem.setForeground(0, QBrush(QColor("darkblue"))) topItem.setData(0,Qt.UserRole,itemData) self.itemList.addTopLevelItem(topItem) self.topNodes[os.path.join(folder, filename)] = topItem # Path nodes for path,operations in data.get('paths',{}).items(): path = path.replace("{", "<").replace("}", ">") pathItemData = itemData.copy() pathItemData['type'] = 'path' pathItemData['caption'] = path pathItemData['path'] = path pathItemData['operations'] = operations pathItemData['components'] = data.get('components',{}) newItem = ApiWidgetItem() newItem.setText(0,path) newItem.setData(0,Qt.UserRole, pathItemData) topItem.addChild(newItem) QApplication.processEvents() return topItem except Exception as e: QMessageBox.information(self,"Facepager","Error loading items:"+str(e)) return None def getApiBasePaths(self, module): urls = [] try: # Load files self.loadFiles(self.folder, module) self.loadFiles(self.folderDefault, module) # Extract urls for k,v in self.apis.items(): api_module = getDictValue(v,'x-facepager-module','Generic') if (api_module == module): api_urls = getDictValue(v, 'servers.*.url', []) urls.extend(api_urls) urls= list(set(urls)) except Exception as e: self.logmessage(f"Error loading base paths: {str(e)}") return urls def getApiDoc(self, module, basepath = ''): try: # Documentation self.loadFiles(self.folder, module) self.loadFiles(self.folderDefault, module, True) # Get best match based on module and basepath api = None for k,v in self.apis.items(): api_module = getDictValue(v,'x-facepager-module','Generic') api_urls = getDictValue(v,'servers.*.url',[]) api_default = getDictValue(v,'x-facepager-default',False) # Prio 1: user defined docs matching module and basepath if (api_module == module) and (basepath in api_urls) and (not api_default): api = v break # Prio 2: default docs matching module and basepath elif (api_module == module) and (basepath in api_urls): api = v # Prio 3: docs matching module elif (api_module == module): api = v if api is None else api return api except: return None def getApiNode(self, module, basepath, path): node = None for idx_file in range(self.itemList.topLevelItemCount()): topItem = self.itemList.topLevelItem(idx_file) topData = topItem.data(0, Qt.UserRole) # Find path # TODO: prioritize non default apis # TODO: fuzzy match (module matches, basepath is similar) api_module = topData.get('module', 'Generic') api_urls = getDictValue(topData, 'info.servers.*.url', []) api_default = topData['default'] if (api_module == module) and (basepath in api_urls): node = topItem for idx_path in range(topItem.childCount()): pathItem = topItem.child(idx_path) pathData = pathItem.data(0, Qt.UserRole) if pathData.get('path', None) == path: return pathItem return node def getApiField(self, module = '', basepath = '', path='', field=''): try: data = self.getApiDoc(module, basepath) if data is not None: basepath = getDictValue(data,"servers.0.url") if data is not None else basepath paths = data.get('paths',{}) if data is not None else None # Operation response path = path.replace("<", "{").replace(">", "}") if path in paths: operation = paths.get(path) elif path.replace(basepath,"") in paths: operation = paths.get(path.replace(basepath,"")) else: operation = None operation = getDictValue(operation,"get.responses.200",False) if operation is not None else {} # Field if field is None and operation is not None and isinstance(operation, dict): return operation.get('description',None) # Field def findFieldProperties(key, schema): if not isinstance(schema, dict): return schema keys = key.split('.', 1) if keys[0] == '': return schema if schema.get('type', None) == 'object': properties = schema.get('properties', None) if isinstance(properties, dict): ref = properties.get("$ref", None) if ref is not None: properties = self.getSchemaComponent(data, ref) if isinstance(properties, dict): value = properties.get(keys[0],{}) if len(keys) == 1: return value else: return findFieldProperties(keys[1], value) elif (schema.get('type', None) == 'array') and (keys[0] == '*'): value = schema.get('items', {}) if len(keys) == 1: return value else: return findFieldProperties(keys[1], value) return schema schema = getDictValue(operation, 'content.application/json.schema', None) fieldprops = findFieldProperties(field, schema) if fieldprops is not None: return fieldprops.get('description','') # response = getDictValue(operation, 'content.application/json.schema.properties', False) # if not response: # response = getDictValue(operation, 'content.application/json.schema.items.properties', False) # # if response and isinstance(response, dict): # if not field in response: # parts = field.split(".") # field = parts[0] if len(parts) > 0 else None # # if field is not None and field in response: # return response.get(field).get('description') return None except: return None def getSchemaComponent(self, data, key): # eg "#components/schema/user/properties key = key.replace("#", "").replace("/", ".") return getDictValue(data, key, False) def applyItem(self): if not self.itemList.currentItem(): return False # Find API module data = self.itemList.currentItem().data(0,Qt.UserRole) module = data.get('module', None) if module is None: return False tab = self.mainWindow.getModule(module) if tab is not None: path = data.get('path', '') options = { 'basepath' : getDictValue(data, 'info.servers.0.url',''), 'resource' : path } # Will pull the default settings from the API doc tab.setSettings(options) self.mainWindow.RequestTabs.setCurrentWidget(tab) self.close() class ApiWidgetItem(QTreeWidgetItem): def __lt__(self, other): data1 = self.data(0,Qt.UserRole) data2 = other.data(0,Qt.UserRole) if data1.get('iscategory',False) and data2.get('iscategory',False): return data1.get('name','') < data2.get('name','') elif data1.get('default',False) != data2.get('default',False): return data1.get('default',False) else: return data1.get('name','') < data2.get('name','')
api/tacticalrmm/automation/migrations/0006_delete_policyexclusions.py
infinite8co/tacticalrmm
903
150507
<filename>api/tacticalrmm/automation/migrations/0006_delete_policyexclusions.py # Generated by Django 3.1.2 on 2020-11-02 19:13 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ("automation", "0005_auto_20200922_1344"), ] operations = [ migrations.DeleteModel( name="PolicyExclusions", ), ]
tools/android/instrumentation_test_check_test.py
jobechoi/bazel
16,989
150544
# Copyright 2017 The Bazel Authors. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the 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 in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Unit tests for instrumentation_test_check.""" import unittest from tools.android.instrumentation_test_check import _ExtractTargetPackageName from tools.android.instrumentation_test_check import _ExtractTargetPackageToInstrument from tools.android.instrumentation_test_check import _ValidateManifestPackageNames from tools.android.instrumentation_test_check import ManifestError INSTRUMENTATION_MANIFEST = """<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.test" > <instrumentation android:targetPackage="com.example" android:name="android.support.test.runner.AndroidJUnitRunner"/> <application android:label="Test"/> </manifest> """ INCORRECT_INSTRUMENTATION_MANIFEST = """<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.test" > <instrumentation android:targetPackage="not.com.example" android:name="android.support.test.runner.AndroidJUnitRunner"/> <application android:label="Test"/> </manifest> """ TARGET_MANIFEST = """<?xml version="2.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example" > <application android:label="App" /> </manifest> """ class InstrumentationTestCheckTest(unittest.TestCase): def test_extract_instrumentation_target_package(self): self.assertEqual( _ExtractTargetPackageToInstrument(INSTRUMENTATION_MANIFEST, ""), "com.example") def test_extract_target_package(self): self.assertEqual( _ExtractTargetPackageName(TARGET_MANIFEST, "unused"), "com.example") def test_target_package_check(self): self.assertEqual( _ValidateManifestPackageNames(INSTRUMENTATION_MANIFEST, "unused", TARGET_MANIFEST, "unused"), ("com.example", "com.example")) def test_target_package_check_failure(self): with self.assertRaises(ManifestError): _ValidateManifestPackageNames(INCORRECT_INSTRUMENTATION_MANIFEST, "unused", TARGET_MANIFEST, "unused") if __name__ == "__main__": unittest.main()
facebook_business/adobjects/instagraminsightsresult.py
MyrikLD/facebook-python-business-sdk
576
150570
# Copyright 2014 Facebook, Inc. # You are hereby granted a non-exclusive, worldwide, royalty-free license to # use, copy, modify, and distribute this software in source code or binary # form for use in connection with the web services and APIs provided by # Facebook. # As with any software that integrates with the Facebook platform, your use # of this software is subject to the Facebook Developer Principles and # Policies [http://developers.facebook.com/policy/]. This copyright notice # shall be included in all copies or substantial portions of the software. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER # DEALINGS IN THE SOFTWARE. from facebook_business.adobjects.abstractobject import AbstractObject from facebook_business.adobjects.abstractcrudobject import AbstractCrudObject from facebook_business.adobjects.objectparser import ObjectParser from facebook_business.api import FacebookRequest from facebook_business.typechecker import TypeChecker """ This class is auto-generated. For any issues or feature requests related to this class, please let us know on github and we'll fix in our codegen framework. We'll not be able to accept pull request for this class. """ class InstagramInsightsResult( AbstractCrudObject, ): def __init__(self, fbid=None, parent_id=None, api=None): self._isInstagramInsightsResult = True super(InstagramInsightsResult, self).__init__(fbid, parent_id, api) class Field(AbstractObject.Field): description = 'description' id = 'id' name = 'name' period = 'period' title = 'title' values = 'values' class Metric: carousel_album_engagement = 'carousel_album_engagement' carousel_album_impressions = 'carousel_album_impressions' carousel_album_reach = 'carousel_album_reach' carousel_album_saved = 'carousel_album_saved' carousel_album_video_views = 'carousel_album_video_views' engagement = 'engagement' exits = 'exits' impressions = 'impressions' reach = 'reach' replies = 'replies' saved = 'saved' taps_back = 'taps_back' taps_forward = 'taps_forward' video_views = 'video_views' class Period: day = 'day' days_28 = 'days_28' lifetime = 'lifetime' month = 'month' week = 'week' _field_types = { 'description': 'string', 'id': 'string', 'name': 'string', 'period': 'string', 'title': 'string', 'values': 'list<InstagramInsightsValue>', } @classmethod def _get_field_enum_info(cls): field_enum_info = {} field_enum_info['Metric'] = InstagramInsightsResult.Metric.__dict__.values() field_enum_info['Period'] = InstagramInsightsResult.Period.__dict__.values() return field_enum_info
smug_saliency/mnist_models/mnist_constants.py
DionysisChristopoulos/google-research
23,901
150580
<reponame>DionysisChristopoulos/google-research # coding=utf-8 # Copyright 2021 The Google Research Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the 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 in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """MNIST Constants. These constants, specific to the MNIST dataset, are used across multiple places in this project. """ NUM_OUTPUTS = 10 # Using 80% of the train data for training and 20% for validation TRAIN_DATA_PERCENT = 80 TRAIN_VAL_SPLIT = (4, 1) NUM_TRAIN_EXAMPLES = 48000 IMAGE_EDGE_LENGTH = 28 NUM_FLATTEN_FEATURES = IMAGE_EDGE_LENGTH * IMAGE_EDGE_LENGTH
governance-at-scale-account-factory/account-creation-shared/v4/src/handler.py
RichMerritt/aws-service-catalog-products
137
150603
# Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 import json, logging, time from urllib.request import Request, urlopen from betterboto import client as betterboto_client import os logger = logging.getLogger() logger.setLevel(logging.INFO) def handler(event, context): request_type = event["RequestType"] try: logger.info(request_type) if request_type in ["Create", "Update"]: assumable_role_in_root_account_arn = os.environ.get( "ASSUMABLE_ROLE_IN_ROOT_ACCOUNT_ARN" ) organization_account_access_role = os.environ.get( "ORGANIZATION_ACCOUNT_ACCESS_ROLE" ) account_name = event.get("ResourceProperties").get("AccountName") email = event.get("ResourceProperties").get("Email") iam_user_access_to_billing = event.get("ResourceProperties").get( "IamUserAccessToBilling" ) with betterboto_client.CrossAccountClientContextManager( "organizations", assumable_role_in_root_account_arn, "assumable_org_role", ) as organizations: logger.info("Checking if need to create") response = organizations.list_accounts_single_page() for account in response.get("Accounts", []): if account.get("Name") == account_name: account_id = account.get("Id") logger.info("Already created") send_response( event, context, "SUCCESS" if account.get("Status") == "ACTIVE" else "FAILED", { "Message": "Account was already created", "account_id": account_id, }, ) logger.info("Creating account") response = organizations.create_account( Email=email, AccountName=account_name, RoleName=organization_account_access_role, IamUserAccessToBilling=iam_user_access_to_billing, ) id = response.get("CreateAccountStatus").get("Id") logger.info("Waiting") while response.get("CreateAccountStatus").get("State") == "IN_PROGRESS": logger.info( "Still waiting: {}".format( response.get("CreateAccountStatus").get("State") ) ) time.sleep(5) response = organizations.describe_create_account_status( CreateAccountRequestId=id ) state = response.get("CreateAccountStatus").get("State") account_id = response.get("CreateAccountStatus").get("AccountId") logger.info(f"Finished: {state}") send_response( event, context, "SUCCESS" if state == "SUCCEEDED" else "FAILED", { "Message": "Account was created" if state == "SUCCEEDED" else f"Failed: {response.get('CreateAccountStatus').get('FailureReason')}", "account_id": account_id, }, ) elif request_type == "Update": send_response(event, context, "SUCCESS", {"Message": "Updated"}) elif request_type == "Delete": send_response(event, context, "SUCCESS", {"Message": "Deleted"}) else: send_response(event, context, "FAILED", {"Message": "Unexpected"}) except Exception as ex: logger.error(ex) send_response(event, context, "FAILED", {"Message": "Exception"}) def send_response(e, c, rs, rd): r = json.dumps( { "Status": rs, "Reason": "CloudWatch Log Stream: " + c.log_stream_name, "PhysicalResourceId": c.log_stream_name, "StackId": e["StackId"], "RequestId": e["RequestId"], "LogicalResourceId": e["LogicalResourceId"], "Data": rd, } ) d = str.encode(r) h = {"content-type": "", "content-length": str(len(d))} req = Request(e["ResponseURL"], data=d, method="PUT", headers=h) r = urlopen(req) logger.info("Status message: {} {}".format(r.msg, r.getcode()))
alipay/aop/api/domain/AlipaySecurityDataAlibabaSecuritydataSendModel.py
antopen/alipay-sdk-python-all
213
150641
<filename>alipay/aop/api/domain/AlipaySecurityDataAlibabaSecuritydataSendModel.py #!/usr/bin/env python # -*- coding: utf-8 -*- import json from alipay.aop.api.constant.ParamConstants import * class AlipaySecurityDataAlibabaSecuritydataSendModel(object): def __init__(self): self._biz_content_value = None self._biz_id = None self._ingest_name = None self._main_target_type = None self._main_target_value = None self._property = None self._property_second = None self._property_third = None self._risk_type = None self._scope = None self._source = None self._system_name = None self._table_name = None self._time = None self._use_scope = None self._user_id = None @property def biz_content_value(self): return self._biz_content_value @biz_content_value.setter def biz_content_value(self, value): self._biz_content_value = value @property def biz_id(self): return self._biz_id @biz_id.setter def biz_id(self, value): self._biz_id = value @property def ingest_name(self): return self._ingest_name @ingest_name.setter def ingest_name(self, value): self._ingest_name = value @property def main_target_type(self): return self._main_target_type @main_target_type.setter def main_target_type(self, value): self._main_target_type = value @property def main_target_value(self): return self._main_target_value @main_target_value.setter def main_target_value(self, value): self._main_target_value = value @property def property(self): return self._property @property.setter def property(self, value): self._property = value @property def property_second(self): return self._property_second @property_second.setter def property_second(self, value): self._property_second = value @property def property_third(self): return self._property_third @property_third.setter def property_third(self, value): self._property_third = value @property def risk_type(self): return self._risk_type @risk_type.setter def risk_type(self, value): self._risk_type = value @property def scope(self): return self._scope @scope.setter def scope(self, value): self._scope = value @property def source(self): return self._source @source.setter def source(self, value): self._source = value @property def system_name(self): return self._system_name @system_name.setter def system_name(self, value): self._system_name = value @property def table_name(self): return self._table_name @table_name.setter def table_name(self, value): self._table_name = value @property def time(self): return self._time @time.setter def time(self, value): self._time = value @property def use_scope(self): return self._use_scope @use_scope.setter def use_scope(self, value): self._use_scope = value @property def user_id(self): return self._user_id @user_id.setter def user_id(self, value): self._user_id = value def to_alipay_dict(self): params = dict() if self.biz_content_value: if hasattr(self.biz_content_value, 'to_alipay_dict'): params['biz_content_value'] = self.biz_content_value.to_alipay_dict() else: params['biz_content_value'] = self.biz_content_value if self.biz_id: if hasattr(self.biz_id, 'to_alipay_dict'): params['biz_id'] = self.biz_id.to_alipay_dict() else: params['biz_id'] = self.biz_id if self.ingest_name: if hasattr(self.ingest_name, 'to_alipay_dict'): params['ingest_name'] = self.ingest_name.to_alipay_dict() else: params['ingest_name'] = self.ingest_name if self.main_target_type: if hasattr(self.main_target_type, 'to_alipay_dict'): params['main_target_type'] = self.main_target_type.to_alipay_dict() else: params['main_target_type'] = self.main_target_type if self.main_target_value: if hasattr(self.main_target_value, 'to_alipay_dict'): params['main_target_value'] = self.main_target_value.to_alipay_dict() else: params['main_target_value'] = self.main_target_value if self.property: if hasattr(self.property, 'to_alipay_dict'): params['property'] = self.property.to_alipay_dict() else: params['property'] = self.property if self.property_second: if hasattr(self.property_second, 'to_alipay_dict'): params['property_second'] = self.property_second.to_alipay_dict() else: params['property_second'] = self.property_second if self.property_third: if hasattr(self.property_third, 'to_alipay_dict'): params['property_third'] = self.property_third.to_alipay_dict() else: params['property_third'] = self.property_third if self.risk_type: if hasattr(self.risk_type, 'to_alipay_dict'): params['risk_type'] = self.risk_type.to_alipay_dict() else: params['risk_type'] = self.risk_type if self.scope: if hasattr(self.scope, 'to_alipay_dict'): params['scope'] = self.scope.to_alipay_dict() else: params['scope'] = self.scope if self.source: if hasattr(self.source, 'to_alipay_dict'): params['source'] = self.source.to_alipay_dict() else: params['source'] = self.source if self.system_name: if hasattr(self.system_name, 'to_alipay_dict'): params['system_name'] = self.system_name.to_alipay_dict() else: params['system_name'] = self.system_name if self.table_name: if hasattr(self.table_name, 'to_alipay_dict'): params['table_name'] = self.table_name.to_alipay_dict() else: params['table_name'] = self.table_name if self.time: if hasattr(self.time, 'to_alipay_dict'): params['time'] = self.time.to_alipay_dict() else: params['time'] = self.time if self.use_scope: if hasattr(self.use_scope, 'to_alipay_dict'): params['use_scope'] = self.use_scope.to_alipay_dict() else: params['use_scope'] = self.use_scope if self.user_id: if hasattr(self.user_id, 'to_alipay_dict'): params['user_id'] = self.user_id.to_alipay_dict() else: params['user_id'] = self.user_id return params @staticmethod def from_alipay_dict(d): if not d: return None o = AlipaySecurityDataAlibabaSecuritydataSendModel() if 'biz_content_value' in d: o.biz_content_value = d['biz_content_value'] if 'biz_id' in d: o.biz_id = d['biz_id'] if 'ingest_name' in d: o.ingest_name = d['ingest_name'] if 'main_target_type' in d: o.main_target_type = d['main_target_type'] if 'main_target_value' in d: o.main_target_value = d['main_target_value'] if 'property' in d: o.property = d['property'] if 'property_second' in d: o.property_second = d['property_second'] if 'property_third' in d: o.property_third = d['property_third'] if 'risk_type' in d: o.risk_type = d['risk_type'] if 'scope' in d: o.scope = d['scope'] if 'source' in d: o.source = d['source'] if 'system_name' in d: o.system_name = d['system_name'] if 'table_name' in d: o.table_name = d['table_name'] if 'time' in d: o.time = d['time'] if 'use_scope' in d: o.use_scope = d['use_scope'] if 'user_id' in d: o.user_id = d['user_id'] return o
strings/string_fundamental/python/isogram.py
avi-pal/al-go-rithms
1,253
150663
<reponame>avi-pal/al-go-rithms<gh_stars>1000+ """ AAn isogram is a word that has no repeating letters, consecutive or non-consecutive. For example "something" and "brother" are isograms, where as "nothing" and "sister" are not. Below method compares the length of the string with the length (or size) of the set of the same string. The set of the string removes all duplicates, therefore if it is equal to the original string, then its an isogram """ # Function to check if string is an isogram def check_isogram(string_to_be_evaluated): if len(string_to_be_evaluated) == len(set(string_to_be_evaluated.lower())): return True return False if __name__ == '__main__': string_one = input("Enter string to check if it's an isogram:") is_isogram = check_isogram(string_one) if check_isogram: print("The string has no repeated letters and is therefore an Isogram.") else: print("The string is not an Isogram.")
salt/grains/junos.py
babs/salt
9,425
150681
""" Grains for junos. NOTE this is a little complicated--junos can only be accessed via salt-proxy-minion. Thus, some grains make sense to get them from the minion (PYTHONPATH), but others don't (ip_interfaces) """ import logging import salt.utils.platform __proxyenabled__ = ["junos"] __virtualname__ = "junos" # Get looging started log = logging.getLogger(__name__) def __virtual__(): if "proxy" not in __opts__: return False else: return __virtualname__ def _remove_complex_types(dictionary): """ junos-eznc is now returning some complex types that are not serializable by msgpack. Kill those. """ for k, v in dictionary.items(): if isinstance(v, dict): dictionary[k] = _remove_complex_types(v) elif hasattr(v, "to_eng_string"): dictionary[k] = v.to_eng_string() return dictionary def defaults(): if salt.utils.platform.is_proxy(): return {"os": "proxy", "kernel": "unknown", "osrelease": "proxy"} else: return { "os": "junos", "kernel": "junos", "osrelease": "junos FIXME", } def facts(proxy=None): if proxy is None or proxy["junos.initialized"]() is False: return {} ret_value = proxy["junos.get_serialized_facts"]() if salt.utils.platform.is_proxy(): ret = {"junos_facts": ret_value} else: ret = {"junos_facts": ret_value, "osrelease": ret_value["version"]} return ret def os_family(): return {"os_family": "junos"}
onnxmltools/convert/coreml/operator_converters/ArrayFeatureExtractor.py
xhochy/onnxmltools
623
150693
# SPDX-License-Identifier: Apache-2.0 from ....proto import onnx_proto from ...common._registration import register_converter def convert_array_feature_extractor(scope, operator, container): op_type = 'ArrayFeatureExtractor' attrs = {'name': operator.full_name} target_indexes = operator.raw_operator.arrayFeatureExtractor.extractIndex index_buffer_name = scope.get_unique_variable_name('target_indexes') container.add_initializer(index_buffer_name, onnx_proto.TensorProto.INT64, [len(target_indexes)], target_indexes) inputs = [operator.inputs[0].full_name, index_buffer_name] outputs = [operator.outputs[0].full_name] container.add_node(op_type, inputs, outputs, op_domain='ai.onnx.ml', **attrs) register_converter('arrayFeatureExtractor', convert_array_feature_extractor)
omega_miya/plugins/maybe/__init__.py
rinrini001/omega-miya
120
150698
import datetime import random from nonebot import CommandGroup, logger from nonebot.plugin.export import export from nonebot.typing import T_State from nonebot.adapters.cqhttp.bot import Bot from nonebot.adapters.cqhttp.event import GroupMessageEvent from nonebot.adapters.cqhttp.permission import GROUP from nonebot.adapters.cqhttp.message import Message, MessageSegment from omega_miya.utils.omega_plugin_utils import init_export, init_processor_state from .utils import maybe, sp, sp_event # from ._oldalmanac import old_almanac # Custom plugin usage text __plugin_custom_name__ = '求签' __plugin_usage__ = r'''【求签】 求签, 求运势, 包括且不限于抽卡、吃饭、睡懒觉、DD 每个人每天求同一个东西的结果是一样的啦! 不要不信邪重新抽啦! 仅限群聊使用 **Permission** Command & Lv.10 or AuthNode **AuthNode** basic **Usage** /求签 [所求之事] /帮我选 [选项1 选项2 ...]''' # Init plugin export init_export(export(), __plugin_custom_name__, __plugin_usage__) # 注册事件响应器 Maybe = CommandGroup( 'maybe', # 使用run_preprocessor拦截权限管理, 在default_state初始化所需权限 state=init_processor_state( name='maybe', command=True, level=10), permission=GROUP, priority=10, block=True) luck = Maybe.command('luck', aliases={'求签'}) # 修改默认参数处理 @luck.args_parser async def parse(bot: Bot, event: GroupMessageEvent, state: T_State): args = str(event.get_plaintext()).strip().split() if not args: await luck.reject('你似乎没有发送有效的参数呢QAQ, 请重新发送:') state[state["_current_key"]] = args[0] if state[state["_current_key"]] == '取消': await luck.finish('操作已取消') @luck.handle() async def handle_first_receive(bot: Bot, event: GroupMessageEvent, state: T_State): args = str(event.get_plaintext()).strip().split() if not args: pass elif args and len(args) == 1: state['draw'] = args[0] else: await luck.finish('参数错误QAQ') @luck.got('draw', prompt='你想问什么事呢?') async def handle_luck(bot: Bot, event: GroupMessageEvent, state: T_State): user_id = event.user_id _draw = state['draw'] # 求签者昵称, 优先使用群昵称 draw_user = event.sender.card if not draw_user: draw_user = event.sender.nickname # 判断特殊事件 if _draw in sp.keys(): draw_result = sp_event(_draw) else: draw_result = maybe(draw=_draw, user_id=user_id) # 向用户发送结果 today = datetime.date.today().strftime('%Y年%m月%d日') msg = f'今天是{today}\n{draw_user}{draw_result}' logger.info(f'{event.group_id}/{event.user_id} 进行了一次求签') await luck.finish(msg) help_choice = Maybe.command('choice', aliases={'帮我选', '选择困难症'}) # 修改默认参数处理 @help_choice.args_parser async def parse(bot: Bot, event: GroupMessageEvent, state: T_State): args = str(event.get_plaintext()).strip() if not args: await help_choice.reject('你似乎没有发送有效的参数呢QAQ, 请重新发送:') state[state["_current_key"]] = args if state[state["_current_key"]] == '取消': await help_choice.finish('操作已取消') @help_choice.handle() async def handle_first_receive(bot: Bot, event: GroupMessageEvent, state: T_State): args = str(event.get_plaintext()).strip() if not args: pass else: state['choices'] = args @help_choice.got('choices', prompt='有啥选项, 发来我帮你选~') async def handle_help_choice(bot: Bot, event: GroupMessageEvent, state: T_State): choices = state['choices'] result = random.choice(str(choices).split()) result_text = f'''帮你从“{'”,“'.join(str(choices).split())}”中选择了:\n\n“{result}”''' msg = Message(MessageSegment.at(user_id=event.user_id)).append(result_text) await help_choice.finish(msg) # almanac = Maybe.command('almanac', aliases={'DD老黄历', 'dd老黄历'}) # # # @almanac.handle() # async def handle_first_receive(bot: Bot, event: GroupMessageEvent, state: T_State): # args = str(event.get_plaintext()).strip().lower().split() # if not args: # pass # else: # await almanac.finish('参数错误QAQ') # # user_id = event.user_id # # # 求签者昵称, 优先使用群昵称 # draw_user = event.sender.card # if not draw_user: # draw_user = event.sender.nickname # # draw_result = old_almanac(user_id=user_id) # # # 向用户发送结果 # today = datetime.date.today().strftime('%Y年%m月%d日') # msg = f"今天是{today}\n{draw_user}今日:\n{'='*12}\n{draw_result}" # logger.info(f'{event.group_id}/{event.user_id} 进行了一次dd老黄历查询') # await almanac.finish(msg)
setup.py
ponty/pyscreenshot
416
150700
<reponame>ponty/pyscreenshot<filename>setup.py import os.path from setuptools import setup NAME = "pyscreenshot" # get __version__ __version__ = None exec(open(os.path.join(NAME, "about.py")).read()) VERSION = __version__ URL = "https://github.com/ponty/pyscreenshot" DESCRIPTION = "python screenshot" LONG_DESCRIPTION = """The pyscreenshot module is obsolete in most cases. It was created because PIL ImageGrab module worked on Windows only, but now Linux and macOS are also supported. There are some features in pyscreenshot which can be useful in special cases: flexible backends, Wayland support, sometimes better performance, optional subprocessing. The module can be used to copy the contents of the screen to a Pillow image memory using various back-ends. Replacement for the ImageGrab Module. Documentation: https://github.com/ponty/pyscreenshot/tree/""" LONG_DESCRIPTION += VERSION PACKAGES = [ NAME, NAME + ".plugins", NAME + ".check", NAME + ".cli", NAME + ".examples", ] classifiers = [ # Get more strings from # http://www.python.org/pypi?%3Aaction=list_classifiers "License :: OSI Approved :: BSD License", "Natural Language :: English", "Operating System :: OS Independent", "Programming Language :: Python", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3 :: Only", "Programming Language :: Python :: 3.6", "Programming Language :: Python :: 3.7", "Programming Language :: Python :: 3.8", "Programming Language :: Python :: 3.9", ] install_requires = [ "EasyProcess", "entrypoint2", "mss ; python_version > '3.4'", "jeepney ; python_version > '3.4' and platform_system == 'Linux'", ] setup( name=NAME, version=VERSION, description=DESCRIPTION, long_description=LONG_DESCRIPTION, long_description_content_type="text/x-rst", python_requires=">=3.4", classifiers=classifiers, keywords="screenshot", author="ponty", # author_email='', url=URL, license="BSD", packages=PACKAGES, # include_package_data=True, # zip_safe=False, install_requires=install_requires, # **extra )
scripts/dataset_size.py
CandyHuiZhang/Semantic-Segmentation-for-Aerial-Satellite-Images-with-Convolutional-Neural-Networks-including-an-
276
150721
#!/usr/bin/env python # -*- coding: utf-8 -*- import argparse import glob import re import sys import numpy as np if 'linux' in sys.platform: import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt else: import matplotlib.pyplot as plt def get_args(): parser = argparse.ArgumentParser() parser.add_argument('--model_type', type=str, choices=['cis', 'multi']) parser.add_argument('--epoch', type=int, default=400) return parser.parse_args() def get_breakeven(pre_rec): return np.argmin((pre_rec[:, 0] - pre_rec[:, 1]) ** 2) if __name__ == '__main__': args = get_args() plt.ylim([0.87, 1.0]) for model_type in ['cis', 'multi']: bldg_recs = [] road_recs = [] for dname in glob.glob('results/{}_*'.format(model_type)): d = '{0}/integrated_{epoch}/evaluation_{epoch}'.format( dname, epoch=args.epoch) ratio = float(re.search('{}_([0-9\.]+)'.format(model_type), dname).groups()[0]) if ratio > 0.5: continue bldg = np.load('{}/pre_rec_1.npy'.format(d)) road = np.load('{}/pre_rec_2.npy'.format(d)) bldg_rec = bldg[get_breakeven(bldg)][1] road_rec = road[get_breakeven(road)][1] print('[{}, {}, {}]'.format(ratio, bldg_rec, road_rec)) bldg_recs.append((ratio, bldg_rec)) road_recs.append((ratio, road_rec)) bldg_recs = np.array(sorted(bldg_recs)) road_recs = np.array(sorted(road_recs)) plt.plot(bldg_recs[:, 0], bldg_recs[:, 1], label='Building prediction ({})'.format(model_type)) plt.plot(road_recs[:, 0], road_recs[:, 1], label='Road prediction ({})'.format(model_type)) plt.legend() plt.xlabel('Percentage of data used for training') plt.ylabel('Recall at breakeven point') plt.savefig('dataset_ratio.png')
TopQuarkAnalysis/Configuration/python/patRefSel_outputModule_cff.py
ckamtsikis/cmssw
852
150738
<reponame>ckamtsikis/cmssw import FWCore.ParameterSet.Config as cms from TopQuarkAnalysis.Configuration.patRefSel_outputModule_cfi import out outpath = cms.EndPath( out )
src/graph_notebook/neptune/gremlin/graphsonV3d0_MapType_objectify_patch.py
Sam-Martin/graph-notebook
378
150741
""" Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. SPDX-License-Identifier: Apache-2.0 """ from gremlin_python.structure.io.graphsonV3d0 import MapType from graph_notebook.neptune.gremlin.hashable_dict_patch import HashableDict # Original code from Tinkerpop 3.4.1 # # class MapType(_GraphSONTypeIO): # python_type = DictType # graphson_type = "g:Map" # # @classmethod # def dictify(cls, d, writer): # l = [] # for key in d: # l.append(writer.toDict(key)) # l.append(writer.toDict(d[key])) # return GraphSONUtil.typedValue("Map", l) # # @classmethod # def objectify(cls, l, reader): # new_dict = {} # if len(l) > 0: # x = 0 # while x < len(l): # new_dict[reader.toObject(l[x])] = reader.toObject(l[x + 1]) # x = x + 2 # return new_dict # Backport from TinkerPop 3.5.0 pre-release # https://github.com/apache/tinkerpop/blob/master/gremlin-python/src/main/python/gremlin_python/structure/io/graphsonV3d0.py#L474 # https://github.com/apache/tinkerpop/pull/1314/files class MapType_patch: @classmethod def objectify(cls, l, reader): # noqa E741 new_dict = {} if len(l) > 0: x = 0 while x < len(l): new_dict[HashableDict.of(reader.toObject(l[x]))] = reader.toObject(l[x + 1]) x = x + 2 return new_dict MapType.objectify = MapType_patch.objectify
wasm/tests/test_exec_mode.py
dbrgn/RustPython
11,058
150767
<gh_stars>1000+ def test_eval_mode(wdriver): assert wdriver.execute_script("return window.rp.pyEval('1+1')") == 2 def test_exec_mode(wdriver): assert wdriver.execute_script("return window.rp.pyExec('1+1')") is None def test_exec_single_mode(wdriver): assert wdriver.execute_script("return window.rp.pyExecSingle('1+1')") == 2 stdout = wdriver.execute_script( """ let output = ""; save_output = function(text) {{ output += text }}; window.rp.pyExecSingle('1+1\\n2+2',{stdout: save_output}); return output; """ ) assert stdout == "2\n4\n"
lib/tracker/lighttrack.py
Kevoen/LightTrack
221
150771
<reponame>Kevoen/LightTrack<gh_stars>100-1000 import os import cv2 import yaml import numpy as np import torch import torch.nn.functional as F from lib.utils.utils import load_yaml, im_to_torch, get_subwindow_tracking, make_scale_pyramid, python2round class Lighttrack(object): def __init__(self, info, even=0): super(Lighttrack, self).__init__() self.info = info # model and benchmark info self.stride = info.stride self.even = even self.mean = torch.tensor([0.485, 0.456, 0.406]).view(3, 1, 1) self.std = torch.tensor([0.229, 0.224, 0.225]).view(3, 1, 1) def normalize(self, x): """ input is in (C,H,W) format""" x /= 255 x -= self.mean x /= self.std return x def init(self, im, target_pos, target_sz, model): state = dict() p = Config(stride=self.stride, even=self.even) state['im_h'] = im.shape[0] state['im_w'] = im.shape[1] # load hyper-parameters from the yaml file prefix = [x for x in ['OTB', 'VOT'] if x in self.info.dataset] if len(prefix) == 0: prefix = [self.info.dataset] yaml_path = os.path.join(os.path.dirname(__file__), '../../experiments/test/%s/' % prefix[0], 'LightTrack.yaml') cfg = load_yaml(yaml_path) cfg_benchmark = cfg[self.info.dataset] p.update(cfg_benchmark) p.renew() if ((target_sz[0] * target_sz[1]) / float(state['im_h'] * state['im_w'])) < 0.004: p.instance_size = cfg_benchmark['big_sz'] p.renew() else: p.instance_size = cfg_benchmark['small_sz'] p.renew() self.grids(p) # self.grid_to_search_x, self.grid_to_search_y net = model wc_z = target_sz[0] + p.context_amount * sum(target_sz) hc_z = target_sz[1] + p.context_amount * sum(target_sz) s_z = round(np.sqrt(wc_z * hc_z)) avg_chans = np.mean(im, axis=(0, 1)) z_crop, _ = get_subwindow_tracking(im, target_pos, p.exemplar_size, s_z, avg_chans) z_crop = self.normalize(z_crop) z = z_crop.unsqueeze(0) net.template(z.cuda()) if p.windowing == 'cosine': window = np.outer(np.hanning(p.score_size), np.hanning(p.score_size)) # [17,17] elif p.windowing == 'uniform': window = np.ones(int(p.score_size), int(p.score_size)) else: raise ValueError("Unsupported window type") state['p'] = p state['net'] = net state['avg_chans'] = avg_chans state['window'] = window state['target_pos'] = target_pos state['target_sz'] = target_sz return state def update(self, net, x_crops, target_pos, target_sz, window, scale_z, p, debug=False): cls_score, bbox_pred = net.track(x_crops) cls_score = F.sigmoid(cls_score).squeeze().cpu().data.numpy() # bbox to real predict bbox_pred = bbox_pred.squeeze().cpu().data.numpy() pred_x1 = self.grid_to_search_x - bbox_pred[0, ...] pred_y1 = self.grid_to_search_y - bbox_pred[1, ...] pred_x2 = self.grid_to_search_x + bbox_pred[2, ...] pred_y2 = self.grid_to_search_y + bbox_pred[3, ...] # size penalty s_c = self.change(self.sz(pred_x2 - pred_x1, pred_y2 - pred_y1) / (self.sz_wh(target_sz))) # scale penalty r_c = self.change((target_sz[0] / target_sz[1]) / ((pred_x2 - pred_x1) / (pred_y2 - pred_y1))) # ratio penalty penalty = np.exp(-(r_c * s_c - 1) * p.penalty_k) pscore = penalty * cls_score # window penalty pscore = pscore * (1 - p.window_influence) + window * p.window_influence # get max r_max, c_max = np.unravel_index(pscore.argmax(), pscore.shape) # to real size pred_x1 = pred_x1[r_max, c_max] pred_y1 = pred_y1[r_max, c_max] pred_x2 = pred_x2[r_max, c_max] pred_y2 = pred_y2[r_max, c_max] pred_xs = (pred_x1 + pred_x2) / 2 pred_ys = (pred_y1 + pred_y2) / 2 pred_w = pred_x2 - pred_x1 pred_h = pred_y2 - pred_y1 diff_xs = pred_xs - p.instance_size // 2 diff_ys = pred_ys - p.instance_size // 2 diff_xs, diff_ys, pred_w, pred_h = diff_xs / scale_z, diff_ys / scale_z, pred_w / scale_z, pred_h / scale_z target_sz = target_sz / scale_z # size learning rate lr = penalty[r_max, c_max] * cls_score[r_max, c_max] * p.lr # size rate res_xs = target_pos[0] + diff_xs res_ys = target_pos[1] + diff_ys res_w = pred_w * lr + (1 - lr) * target_sz[0] res_h = pred_h * lr + (1 - lr) * target_sz[1] target_pos = np.array([res_xs, res_ys]) target_sz = target_sz * (1 - lr) + lr * np.array([res_w, res_h]) if debug: return target_pos, target_sz, cls_score[r_max, c_max], cls_score else: return target_pos, target_sz, cls_score[r_max, c_max] def track(self, state, im): p = state['p'] net = state['net'] avg_chans = state['avg_chans'] window = state['window'] target_pos = state['target_pos'] target_sz = state['target_sz'] hc_z = target_sz[1] + p.context_amount * sum(target_sz) wc_z = target_sz[0] + p.context_amount * sum(target_sz) s_z = np.sqrt(wc_z * hc_z) scale_z = p.exemplar_size / s_z d_search = (p.instance_size - p.exemplar_size) / 2 # slightly different from rpn++ pad = d_search / scale_z s_x = s_z + 2 * pad x_crop, _ = get_subwindow_tracking(im, target_pos, p.instance_size, python2round(s_x), avg_chans) state['x_crop'] = x_crop.clone() # torch float tensor, (3,H,W) x_crop = self.normalize(x_crop) x_crop = x_crop.unsqueeze(0) debug = True if debug: target_pos, target_sz, _, cls_score = self.update(net, x_crop.cuda(), target_pos, target_sz * scale_z, window, scale_z, p, debug=debug) state['cls_score'] = cls_score else: target_pos, target_sz, _ = self.update(net, x_crop.cuda(), target_pos, target_sz * scale_z, window, scale_z, p, debug=debug) target_pos[0] = max(0, min(state['im_w'], target_pos[0])) target_pos[1] = max(0, min(state['im_h'], target_pos[1])) target_sz[0] = max(10, min(state['im_w'], target_sz[0])) target_sz[1] = max(10, min(state['im_h'], target_sz[1])) state['target_pos'] = target_pos state['target_sz'] = target_sz state['p'] = p return state def grids(self, p): """ each element of feature map on input search image :return: H*W*2 (position for each element) """ # print('ATTENTION',p.instance_size,p.score_size) sz = p.score_size # the real shift is -param['shifts'] sz_x = sz // 2 sz_y = sz // 2 x, y = np.meshgrid(np.arange(0, sz) - np.floor(float(sz_x)), np.arange(0, sz) - np.floor(float(sz_y))) self.grid_to_search_x = x * p.total_stride + p.instance_size // 2 self.grid_to_search_y = y * p.total_stride + p.instance_size // 2 def change(self, r): return np.maximum(r, 1. / r) def sz(self, w, h): pad = (w + h) * 0.5 sz2 = (w + pad) * (h + pad) return np.sqrt(sz2) def sz_wh(self, wh): pad = (wh[0] + wh[1]) * 0.5 sz2 = (wh[0] + pad) * (wh[1] + pad) return np.sqrt(sz2) class Config(object): def __init__(self, stride=8, even=0): self.penalty_k = 0.062 self.window_influence = 0.38 self.lr = 0.765 self.windowing = 'cosine' if even: self.exemplar_size = 128 self.instance_size = 256 else: self.exemplar_size = 127 self.instance_size = 255 # total_stride = 8 # score_size = (instance_size - exemplar_size) // total_stride + 1 + 8 # for ++ self.total_stride = stride self.score_size = int(round(self.instance_size / self.total_stride)) self.context_amount = 0.5 self.ratio = 0.94 def update(self, newparam=None): if newparam: for key, value in newparam.items(): setattr(self, key, value) self.renew() def renew(self): # self.score_size = (self.instance_size - self.exemplar_size) // self.total_stride + 1 + 8 # for ++ self.score_size = int(round(self.instance_size / self.total_stride))
opendatatools/common/string_util.py
solider245/OpenData
1,179
150775
<reponame>solider245/OpenData # encoding: UTF-8 def remove_chinese(str): s = "" for w in str: if w >= u'\u4e00' and w <= u'\u9fa5': continue s += w return s def remove_non_numerical(s): f = '' for i in range(len(s)): try: f = float(s[:i+1]) except: return f return str(f)
bert-distillation-multimetric/squad_distillation_abstract_clis/a_run_squad_w_distillation_cli.py
meghanaravikumar/sigopt-examples
213
150799
<reponame>meghanaravikumar/sigopt-examples<filename>bert-distillation-multimetric/squad_distillation_abstract_clis/a_run_squad_w_distillation_cli.py import argparse from distilbert_run_and_hpo_configurations.distilbert_squad_run_parameters import RunParameters, get_default_run_parameters from distilbert_run_and_hpo_configurations.distilbert_squad_hpo_parameters import SGDHyperparameter, \ get_default_hyperparameters, SquadArchitectureHyperparameter, ArchitectureHyperparameter class ARunDistilBertSquadCLI(object): parser_prefix = "--" def __init__(self): pass def define_run_commandline_args(self): parser = argparse.ArgumentParser() squad_finetuning_run_defaults = get_default_run_parameters() parser.add_argument( self.parser_prefix + RunParameters.MODEL_TYPE.value, default="distilbert", type=str, required=False, help="Model type selected", ) parser.add_argument( self.parser_prefix + RunParameters.MODEL_NAME_OR_PATH.value, default="distilbert-base-uncased", type=str, required=False, help="Path to pre-trained model or shortcut name selected", ) # Distillation parameters (optional) parser.add_argument( self.parser_prefix + RunParameters.TEACHER_TYPE.value, default=None, type=str, help="Teacher type. Teacher tokenizer and student (model) tokenizer must output the same tokenization. Only for distillation.", ) parser.add_argument( self.parser_prefix + RunParameters.TEACHER_NAME_OR_PATH.value, default=None, type=str, help="Path to the already SQuAD fine-tuned teacher model. Only for distillation.", ) parser.add_argument( self.parser_prefix + RunParameters.OUTPUT_DIR.value, default=None, type=str, required=True, help="The output directory where the model checkpoints and predictions will be written.", ) parser.add_argument( "--data_dir", default=None, type=str, help="The input data dir. Should contain the .json files for the task." + "If no data dir or train/predict files are specified, will run with tensorflow_datasets.", ) parser.add_argument( self.parser_prefix + RunParameters.TRAIN_FILE.value, default=None, type=str, help="The input training file. If a data dir is specified, will look for the file there" + "If no data dir or train/predict files are specified, will run with tensorflow_datasets.", ) parser.add_argument( self.parser_prefix + RunParameters.PREDICT_FILE.value, default=None, type=str, help="The input evaluation file. If a data dir is specified, will look for the file there" + "If no data dir or train/predict files are specified, will run with tensorflow_datasets.", ) parser.add_argument( self.parser_prefix + RunParameters.VERSION_2.value, type=lambda x: str(x).lower() == 'true', default=True, help="If true, the SQuAD examples contain some that do not have an answer.", ) parser.add_argument(self.parser_prefix + RunParameters.LOAD_PRETRAINED_MODEL.value, action="store_true", help="if flag turned on, will use --model_type and --model_name_or_path to load " "pretrained model") parser.add_argument(self.parser_prefix + RunParameters.LOAD_SEMI_PRETRAINED_MODEL.value, type=lambda x: str(x).lower() == 'true', default=True, help="if flag turned on, will use --model_type and --model_name_or_path to load " "model with pretrained weights") parser.add_argument(self.parser_prefix + RunParameters.DO_TRAIN.value, type=lambda x: str(x).lower() == 'true', default=True, help="Whether to run training.") parser.add_argument(self.parser_prefix + RunParameters.DO_EVAL.value, type=lambda x: str(x).lower() == 'true', default=True, help="Whether to run eval on the dev set.") parser.add_argument( self.parser_prefix + RunParameters.EVALUATE_DURING_TRAINING.value, type=lambda x: str(x).lower() == 'true', default=True, help="Rul evaluation during training at each logging step." ) parser.add_argument( self.parser_prefix + RunParameters.DO_LOWER_CASE.value, type=lambda x: str(x).lower() == 'true', default=True, help="Set this flag if you are using an uncased model." ) parser.add_argument(self.parser_prefix + RunParameters.NUM_TRAIN_EPOCHS.value, default=squad_finetuning_run_defaults[ RunParameters.NUM_TRAIN_EPOCHS.value], type=float, help="Total number of training epochs to perform." ) parser.add_argument( self.parser_prefix + RunParameters.N_BEST_SIZE.value, default=squad_finetuning_run_defaults[RunParameters.N_BEST_SIZE.value], type=int, help="The total number of n-best predictions to generate in the nbest_predictions.json output file.", ) parser.add_argument(self.parser_prefix + RunParameters.LOGGING_STEPS.value, type=int, default=squad_finetuning_run_defaults[ RunParameters.LOGGING_STEPS.value], help="Log every X updates steps.") parser.add_argument(self.parser_prefix + RunParameters.SAVE_STEPS.value, type=int, default=squad_finetuning_run_defaults[ RunParameters.SAVE_STEPS.value], help="Save checkpoint every X updates steps.") parser.add_argument( self.parser_prefix + RunParameters.EVAL_ALL_CHECKPOINTS.value, action="store_true", help="Evaluate all checkpoints starting with the same prefix as " "model_name ending and ending with step number", ) parser.add_argument(self.parser_prefix + RunParameters.NO_CUDA.value, action="store_true", help="Whether not to use CUDA when available") parser.add_argument( self.parser_prefix + RunParameters.OVERWRITE_OUTPUT_DIR.value, action="store_true", help="Overwrite the content of the output directory" ) parser.add_argument( self.parser_prefix + RunParameters.OVERWRTIE_CACHE.value, action="store_true", help="Overwrite the cached training and evaluation sets" ) parser.add_argument(self.parser_prefix + RunParameters.SEED.value, type=int, default=squad_finetuning_run_defaults[ RunParameters.SEED.value], help="random seed for initialization") parser.add_argument(self.parser_prefix + RunParameters.LOCAL_RANK.value, type=int, default=-1, help="local_rank for distributed training on gpus") parser.add_argument( self.parser_prefix + RunParameters.FP_16.value, action="store_true", help="Whether to use 16-bit (mixed) precision (through NVIDIA apex) instead of 32-bit", ) parser.add_argument( "--fp16_opt_level", type=str, default="O1", help="For fp16: Apex AMP optimization level selected in ['O0', 'O1', 'O2', and 'O3']." "See details at https://nvidia.github.io/apex/amp.html", ) parser.add_argument( self.parser_prefix + RunParameters.VERBOSE_LOGGING.value, action="store_true", help="If true, all of the warnings related to data processing will be printed. " "A number of warnings are expected for a normal SQuAD evaluation.", ) parser.add_argument( self.parser_prefix + RunParameters.MAX_STEPS.value, default=-1, type=int, help="If > 0: set total number of training steps to perform. Override num_train_epochs.", ) parser.add_argument( self.parser_prefix + RunParameters.CACHE_DIR.value, default="", type=str, help="Where do you want to store the pre-trained models downloaded from s3", ) parser.add_argument( self.parser_prefix + RunParameters.TRAIN_CACHE_S3_DIRECTORY.value, type=str, help="location of squad2 cache files in s3. if present, will download cached features instead of loading " "features" ) parser.add_argument( self.parser_prefix + RunParameters.EVAL_CACHE_S3_DIRECTORY.value, type=str, help="location of squad2 cache files in s3. if present, will download cached features instead of loading " "features" ) parser.add_argument( self.parser_prefix + RunParameters.CACHE_S3_BUCKET.value, type=str, help="s3 bucket name for cache files" ) # Other parameters parser.add_argument( self.parser_prefix + RunParameters.CONFIG_NAME.value, default="", type=str, help="Pretrained config name or path if not the same as model_name" ) parser.add_argument( self.parser_prefix + RunParameters.TOKENIZER_NAME.value, default="", type=str, help="Pretrained tokenizer name or path if not the same as model_name", ) return parser def define_common_hpo_commandline_args(self, parser): squad_finetuning_hpo_defaults = get_default_hyperparameters() parser.add_argument( self.parser_prefix + SGDHyperparameter.GRADIENT_ACCUMULATION_STEPS.value, type=int, default=1, help="Number of updates steps to accumulate before performing a backward/update pass.", ) parser.add_argument(self.parser_prefix + SGDHyperparameter.MAX_GRAD_NORM.value, default=squad_finetuning_hpo_defaults[ SGDHyperparameter.MAX_GRAD_NORM.value], type=float, help="Max gradient norm.") parser.add_argument( "--null_score_diff_threshold", type=float, default=0.0, help="If null_score - best_non_null is greater than the threshold predict null.", ) # SQUAD preprocessing parameters parser.add_argument( self.parser_prefix + SquadArchitectureHyperparameter.MAX_SEQ_LENGTH.value, default=squad_finetuning_hpo_defaults[SquadArchitectureHyperparameter.MAX_SEQ_LENGTH.value], type=int, help="The maximum total input sequence length after WordPiece tokenization. Sequences " "longer than this will be truncated, and sequences shorter than this will be padded.", ) parser.add_argument( self.parser_prefix + SquadArchitectureHyperparameter.DOC_STRIDE.value, default=squad_finetuning_hpo_defaults[SquadArchitectureHyperparameter.DOC_STRIDE.value], type=int, help="When splitting up a long document into chunks, how much stride to take between chunks.", ) parser.add_argument( self.parser_prefix + SquadArchitectureHyperparameter.MAX_QUERY_LENGTH.value, default=squad_finetuning_hpo_defaults[SquadArchitectureHyperparameter.MAX_QUERY_LENGTH.value], type=int, help="The maximum number of tokens for the question. Questions longer than this will " "be truncated to this length.", ) parser.add_argument( self.parser_prefix + SquadArchitectureHyperparameter.MAX_ANSWER_LENGTH.value, default=squad_finetuning_hpo_defaults[SquadArchitectureHyperparameter.MAX_ANSWER_LENGTH.value], type=int, help="The maximum length of an answer that can be generated. This is needed because the start " "and end predictions are not conditioned on one another.", ) parser.add_argument(self.parser_prefix + ArchitectureHyperparameter.DIMENSION.value, default=squad_finetuning_hpo_defaults[ArchitectureHyperparameter.DIMENSION.value], type=int, help="dimension of multihead attention, fully connected layer") parser.add_argument(self.parser_prefix + ArchitectureHyperparameter.HIDDEN_DIMENSION.value, default=squad_finetuning_hpo_defaults[ArchitectureHyperparameter.HIDDEN_DIMENSION.value], type=int, help="dim of hidden layers for linear layers") return parser def get_commandline_args(self): pass
setup.py
eegemberdiev/probablepeople
505
150840
try: from setuptools import setup except ImportError : raise ImportError("setuptools module required, please go to https://pypi.python.org/pypi/setuptools and follow the instructions for installing setuptools") setup( version='0.5.4', url='https://github.com/datamade/probablepeople', description='Parse romanized names & companies using advanced NLP methods', name='probablepeople', packages=['probablepeople'], package_data={'probablepeople' : ['generic_learned_settings.crfsuite', 'person_learned_settings.crfsuite', 'company_learned_settings.crfsuite']}, license='The MIT License: http://www.opensource.org/licenses/mit-license.php', install_requires=[ 'python-crfsuite>=0.8', 'probableparsing', 'future>=0.14', 'doublemetaphone'], classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'Intended Audience :: Science/Research', 'License :: OSI Approved :: MIT License', 'Natural Language :: English', 'Operating System :: MacOS :: MacOS X', 'Operating System :: Microsoft :: Windows', 'Operating System :: POSIX', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Topic :: Software Development :: Libraries :: Python Modules', 'Topic :: Scientific/Engineering', 'Topic :: Scientific/Engineering :: Information Analysis'], long_description=""" probablepeople is a python library for parsing unstructured romanized name or company strings into components, using conditional random fields. From the python interpreter: >>> import probablepeople >>> probablepeople.parse('Mr George "Gob" Bluth II') [('Mr', 'PrefixMarital'), ('George', 'GivenName'), ('"Gob"', 'Nickname'), ('Bluth', 'Surname'), ('II', 'SuffixGenerational')] >>> probablepeople.parse('Sitwell Housing Inc') [('Sitwell', 'CorporationName'), ('Housing', 'CorporationName'), ('Inc', 'CorporationLegalType')] """ )
openvqa/utils/make_mask.py
AcceptedDoge/openvqa
274
150854
# -------------------------------------------------------- # OpenVQA # Written by <NAME> https://github.com/cuiyuhao1996 # -------------------------------------------------------- import torch # Masking the sequence mask def make_mask(feature): return (torch.sum( torch.abs(feature), dim=-1 ) == 0).unsqueeze(1).unsqueeze(2)
angr/engines/pcode/arch/ArchPcode_z180_LE_16_default.py
matthewpruett/angr
6,132
150858
<reponame>matthewpruett/angr ### ### This file was automatically generated ### from archinfo.arch import register_arch, Endness, Register from .common import ArchPcode class ArchPcode_z180_LE_16_default(ArchPcode): name = 'z180:LE:16:default' pcode_arch = 'z180:LE:16:default' description = 'Zilog Z180' bits = 16 ip_offset = 0x42 sp_offset = 0x44 bp_offset = sp_offset instruction_endness = Endness.LE register_list = [ Register('af', 2, 0x0), Register('f', 1, 0x0), Register('a', 1, 0x1), Register('bc', 2, 0x2), Register('c', 1, 0x2), Register('b', 1, 0x3), Register('de', 2, 0x4), Register('e', 1, 0x4), Register('d', 1, 0x5), Register('hl', 2, 0x6), Register('l', 1, 0x6), Register('h', 1, 0x7), Register('i', 1, 0x8), Register('r', 1, 0x9), Register('af_', 2, 0x20), Register('f_', 1, 0x20), Register('a_', 1, 0x21), Register('bc_', 2, 0x22), Register('c_', 1, 0x22), Register('b_', 1, 0x23), Register('de_', 2, 0x24), Register('e_', 1, 0x24), Register('d_', 1, 0x25), Register('hl_', 2, 0x26), Register('l_', 1, 0x26), Register('h_', 1, 0x27), Register('pc', 2, 0x42, alias_names=('ip',)), Register('sp', 2, 0x44), Register('ix', 2, 0x46), Register('iy', 2, 0x48), Register('rcbar', 1, 0x50), Register('rcbr', 1, 0x51), Register('rbbr', 1, 0x52), Register('decompile_mode', 1, 0x60), Register('contextreg', 4, 0xf0) ] register_arch(['z180:le:16:default'], 16, Endness.LE, ArchPcode_z180_LE_16_default)
mmdet/core/bbox/__init__.py
vpeopleonatank/OBBDetection
274
150865
from .assigners import (AssignResult, BaseAssigner, CenterRegionAssigner, MaxIoUAssigner) from .builder import build_assigner, build_bbox_coder, build_sampler from .coder import (BaseBBoxCoder, DeltaXYWHBBoxCoder, PseudoBBoxCoder, TBLRBBoxCoder) from .iou_calculators import BboxOverlaps2D, bbox_overlaps from .samplers import (BaseSampler, CombinedSampler, InstanceBalancedPosSampler, IoUBalancedNegSampler, PseudoSampler, RandomSampler, SamplingResult) from .transforms import (bbox2distance, bbox2result, bbox2roi, bbox_flip, bbox_mapping, bbox_mapping_back, distance2bbox, roi2bbox) from .transforms_obb import (poly2obb, rectpoly2obb, poly2hbb, obb2poly, obb2hbb, hbb2poly, hbb2obb, bbox2type, hbb_flip, obb_flip, poly_flip, hbb_warp, obb_warp, poly_warp, hbb_mapping, obb_mapping, poly_mapping, hbb_mapping_back, obb_mapping_back, poly_mapping_back, arb_mapping, arb_mapping_back, get_bbox_type, get_bbox_dim, get_bbox_areas, choice_by_type, arb2result, arb2roi, distance2obb, regular_theta, regular_obb, mintheta_obb) from .iou_calculators import OBBOverlaps, PolyOverlaps from .samplers import (OBBSamplingResult, OBBBaseSampler, OBBRandomSampler, OBBOHEMSampler) from .coder import OBB2OBBDeltaXYWHTCoder, HBB2OBBDeltaXYWHTCoder __all__ = [ 'bbox_overlaps', 'BboxOverlaps2D', 'BaseAssigner', 'MaxIoUAssigner', 'AssignResult', 'BaseSampler', 'PseudoSampler', 'RandomSampler', 'InstanceBalancedPosSampler', 'IoUBalancedNegSampler', 'CombinedSampler', 'SamplingResult', 'build_assigner', 'build_sampler', 'bbox_flip', 'bbox_mapping', 'bbox_mapping_back', 'bbox2roi', 'roi2bbox', 'bbox2result', 'distance2bbox', 'bbox2distance', 'build_bbox_coder', 'BaseBBoxCoder', 'PseudoBBoxCoder', 'DeltaXYWHBBoxCoder', 'TBLRBBoxCoder', 'CenterRegionAssigner', 'poly2obb', 'rectpoly2obb', 'poly2hbb', 'obb2poly', 'obb2hbb', 'hbb2poly', 'hbb2obb', 'bbox2type', 'hbb_flip', 'obb_flip', 'poly_flip', 'hbb_warp', 'obb_warp', 'poly_warp', 'hbb_mapping', 'obb_mapping', 'poly_mapping', 'hbb_mapping_back', 'obb_mapping_back', 'poly_mapping_back', 'get_bbox_type', 'get_bbox_dim', 'get_bbox_areas', 'choice_by_type', 'arb2roi', 'arb2result', 'distance2obb', 'arb_mapping', 'arb_mapping_back', 'OBBOverlaps', 'PolyOverlaps', 'OBBSamplingResult', 'OBBBaseSampler', 'OBBRandomSampler', 'OBBOHEMSampler', 'OBB2OBBDeltaXYWHTCoder', 'HBB2OBBDeltaXYWHTCoder', 'regular_theta', 'regular_obb', 'mintheta_obb' ]
utils/stringUtils.py
fsanges/glTools
165
150896
import math def stripSuffix(name,delineator='_'): ''' Return the portion of name minus the last element separated by the name delineator. Useful for determining a name prefix from an existing object name. @param name: String name to strip the suffix from @type name: str @param delineator: String delineator to split the string name with. If default will inherit the class delineator string. @type delineator: str ''' # Check for Delineator in Name if not name.count(delineator): return name # Determine Suffix suffix = name.split(delineator)[-1] # Remove Suffix result = name.replace(delineator+suffix,'') # Return Result return result def stringIndex(index,padding=2): ''' Return the string equivalent for the specified iteger index. @param index: The index to get the string equivalent for @type index: int @param padding: The number of characters for the index string @type padding: int ''' # Convert to String strInd = str(index) # Prepend Padding for i in range(padding-len(strInd)): strInd = '0'+strInd # Return Result return strInd def alphaIndex(index,upper=True): ''' Return the alpha string equivalent for the specified iteger index. @param index: The index to get the alpha string equivalent for @type index: int @param upper: Return the result in upper case form @type upper: bool ''' # Define Alpha List alpha = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'] # Build Alpha Index alphaInd = alpha[index % 26] depth = index / 26.0 while int(math.floor(depth)): alphaInd = alpha[int(depth % 26)-1] + alphaInd depth = depth / 26.0 # Check Case if upper: alphaInd = alphaInd.upper() # Return result return alphaInd
tests/rules/test_IAMRolesOverprivilegedRule.py
lpmi-13/cfripper
360
150923
import pytest from pycfmodel.model.cf_model import CFModel from cfripper.model.enums import RuleGranularity, RuleMode, RuleRisk from cfripper.model.result import Failure from cfripper.rules.iam_roles import IAMRolesOverprivilegedRule from tests.utils import compare_lists_of_failures, get_cfmodel_from @pytest.fixture() def valid_role_inline_policy() -> CFModel: return get_cfmodel_from("rules/IAMRolesOverprivilegedRule/valid_role_inline_policy.json").resolve() @pytest.fixture() def invalid_role_inline_policy() -> CFModel: return get_cfmodel_from("rules/IAMRolesOverprivilegedRule/invalid_role_inline_policy.json").resolve() @pytest.fixture() def invalid_role_inline_policy_resource_as_array() -> CFModel: return get_cfmodel_from( "rules/IAMRolesOverprivilegedRule/invalid_role_inline_policy_resource_as_array.json" ).resolve() @pytest.fixture() def valid_role_managed_policy() -> CFModel: return get_cfmodel_from("rules/IAMRolesOverprivilegedRule/valid_role_managed_policy.json").resolve() @pytest.fixture() def invalid_role_managed_policy() -> CFModel: return get_cfmodel_from("rules/IAMRolesOverprivilegedRule/invalid_role_managed_policy.json").resolve() @pytest.fixture() def invalid_role_inline_policy_fn_if() -> CFModel: return get_cfmodel_from("rules/IAMRolesOverprivilegedRule/invalid_role_inline_policy_fn_if.json").resolve() def test_with_valid_role_inline_policy(valid_role_inline_policy): rule = IAMRolesOverprivilegedRule(None) result = rule.invoke(valid_role_inline_policy) assert result.valid assert compare_lists_of_failures(result.failures, []) def test_with_invalid_role_inline_policy(invalid_role_inline_policy): rule = IAMRolesOverprivilegedRule(None) result = rule.invoke(invalid_role_inline_policy) assert not result.valid assert compare_lists_of_failures( result.failures, [ Failure( granularity=RuleGranularity.RESOURCE, reason="Role 'RootRole' contains an insecure permission 'ec2:DeleteInternetGateway' in policy 'not_so_chill_policy'", risk_value=RuleRisk.MEDIUM, rule="IAMRolesOverprivilegedRule", rule_mode=RuleMode.BLOCKING, actions=None, resource_ids={"RootRole"}, ) ], ) def test_with_invalid_role_inline_policy_resource_as_array(invalid_role_inline_policy_resource_as_array): rule = IAMRolesOverprivilegedRule(None) result = rule.invoke(invalid_role_inline_policy_resource_as_array) assert not result.valid assert compare_lists_of_failures( result.failures, [ Failure( granularity=RuleGranularity.RESOURCE, reason="Role 'RootRole' contains an insecure permission 'ec2:DeleteInternetGateway' in policy 'not_so_chill_policy'", risk_value=RuleRisk.MEDIUM, rule="IAMRolesOverprivilegedRule", rule_mode=RuleMode.BLOCKING, actions=None, resource_ids={"RootRole"}, ) ], ) def test_with_valid_role_managed_policy(valid_role_managed_policy): rule = IAMRolesOverprivilegedRule(None) result = rule.invoke(valid_role_managed_policy) assert result.valid assert compare_lists_of_failures(result.failures, []) def test_with_invalid_role_managed_policy(invalid_role_managed_policy): rule = IAMRolesOverprivilegedRule(None) result = rule.invoke(invalid_role_managed_policy) assert not result.valid assert compare_lists_of_failures( result.failures, [ Failure( granularity=RuleGranularity.RESOURCE, reason="Role RootRole has forbidden Managed Policy arn:aws:iam::aws:policy/AdministratorAccess", risk_value=RuleRisk.MEDIUM, rule="IAMRolesOverprivilegedRule", rule_mode=RuleMode.BLOCKING, actions=None, resource_ids={"RootRole"}, ) ], ) def test_with_invalid_role_inline_policy_fn_if(invalid_role_inline_policy_fn_if): rule = IAMRolesOverprivilegedRule(None) result = rule.invoke(invalid_role_inline_policy_fn_if) assert not result.valid assert compare_lists_of_failures( result.failures, [ Failure( granularity=RuleGranularity.RESOURCE, reason="Role 'RootRole' contains an insecure permission 'ec2:DeleteVpc' in policy 'ProdCredentialStoreAccessPolicy'", risk_value=RuleRisk.MEDIUM, rule="IAMRolesOverprivilegedRule", rule_mode=RuleMode.BLOCKING, actions=None, resource_ids={"RootRole"}, ) ], ) def test_rule_supports_filter_config(invalid_role_managed_policy, default_allow_all_config): rule = IAMRolesOverprivilegedRule(default_allow_all_config) result = rule.invoke(invalid_role_managed_policy) assert result.valid assert compare_lists_of_failures(result.failures, [])
Training/MOOC Tensorflow 2.0/BeiDa/class2/p4_where.py
church06/Pythons
177
150986
<reponame>church06/Pythons<gh_stars>100-1000 import tensorflow as tf a = tf.constant([1, 2, 3, 1, 1]) b = tf.constant([0, 1, 3, 4, 5]) c = tf.where(tf.greater(a, b), a, b) # 若a>b,返回a对应位置的元素,否则返回b对应位置的元素 print("c:", c)
uflow/data/flow_data_test.py
deepneuralmachine/google-research
23,901
151010
<reponame>deepneuralmachine/google-research<filename>uflow/data/flow_data_test.py # coding=utf-8 # Copyright 2021 The Google Research Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the 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 in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests for data loaders with supervised flow.""" import os from absl.testing import absltest import matplotlib matplotlib.use('Agg') # None-interactive plots do not need tk # pylint:disable=g-import-not-at-top import matplotlib.pyplot as plt import numpy as np import tensorflow as tf from uflow import uflow_plotting from uflow import uflow_utils from uflow.data import generic_flow_dataset from uflow.data import kitti from uflow.data import sintel from uflow.data.dataset_locations import dataset_locations def plot_images(image1, image2, flow, image2_to_image1, plot_dir): """Display some images and make sure they look correct.""" if not os.path.exists(plot_dir): os.mkdir(plot_dir) num_rows = 2 num_columns = 2 def subplot_at(column, row): plt.subplot(num_rows, num_columns, 1 + column + row * num_columns) def post_imshow(label): plt.xlabel(label) plt.xticks([]) plt.yticks([]) plt.figure('eval', [14, 8.5]) plt.clf() subplot_at(0, 0) plt.imshow(image1[0]) post_imshow(label='Image1') subplot_at(1, 0) plt.imshow(image2[0]) post_imshow(label='Image2') subplot_at(0, 1) plt.imshow(uflow_plotting.flow_to_rgb(flow[0].numpy())) post_imshow(label='Flow') subplot_at(1, 1) plt.imshow(image2_to_image1[0]) post_imshow(label='Image2_to_Image1') plt.subplots_adjust( left=0.05, bottom=0.05, right=1 - 0.05, top=1, wspace=0.05, hspace=0.05) filename = 'demo_flow.png' uflow_plotting.save_and_close(os.path.join(plot_dir, filename)) def mock_inference_fn(x, y, input_height, input_width, infer_occlusion): del input_height # unused del input_width # unused del y # unused if infer_occlusion: return [tf.convert_to_tensor( value=np.zeros((x.shape[0], x.shape[1], 2), np.float32))] * 2 return tf.convert_to_tensor( value=np.zeros((x.shape[0], x.shape[1], 2), np.float32)) class FlowDataTest(absltest.TestCase): def _check_images_and_flow(self, image1, image2, flow, save_images=False, plot_dir='/tmp/flow_images'): self.assertGreaterEqual(np.min(image1), 0.) self.assertLessEqual(np.max(image1), 1.) # Check that the image2 warped by flow1 into image1 has lower pixelwise # error than the unwarped image mean_unwarped_diff = np.mean(np.abs(image1 - image2)) warp = uflow_utils.flow_to_warp(flow) image2_to_image1 = uflow_utils.resample(image2, warp) mean_warped_diff = np.mean(np.abs(image2_to_image1 - image1)) if save_images: plot_images(image1, image2, flow, image2_to_image1, plot_dir=plot_dir) # Check that the warped image has lower pixelwise error than the unwarped. self.assertLess(mean_warped_diff, mean_unwarped_diff) def test_kitti_eval(self): dataset = kitti.make_dataset( path=dataset_locations['kitti15-train-pairs'], mode='eval') dataset = dataset.prefetch(1) dataset = dataset.batch(1) results = kitti.evaluate(mock_inference_fn, dataset, height=320, width=320) expected_keys = kitti.list_eval_keys() self.assertEqual(set(expected_keys), set(results.keys())) def test_flying_chairs(self): dataset = generic_flow_dataset.make_dataset( path=dataset_locations['chairs-all'], mode='train-sup') dataset = dataset.prefetch(1) dataset = dataset.batch(1) data_it = tf.compat.v1.data.make_one_shot_iterator(dataset) data = data_it.next() image1 = data[0][:, 0] image2 = data[0][:, 1] flow = data[1] self._check_images_and_flow( image1, image2, flow, save_images=False, plot_dir='/tmp/flying_chairs') def test_flying_chairs_eval(self): dataset = generic_flow_dataset.make_dataset( path=dataset_locations['chairs-all'], mode='train-sup') dataset = dataset.take(1) results = generic_flow_dataset.evaluate( mock_inference_fn, dataset, height=200, width=400, num_plots=0, plot_dir='/tmp/flying_chairs', has_occlusion=False) expected_keys = generic_flow_dataset.list_eval_keys() self.assertEqual(set(expected_keys), set(results.keys())) def test_sintel(self): dataset = sintel.make_dataset( path=dataset_locations['sintel-train-clean'], mode='eval-occlusion') dataset = dataset.prefetch(1) dataset = dataset.batch(1) data_it = tf.compat.v1.data.make_one_shot_iterator(dataset) data = data_it.next() image1 = data[0][:, 0] image2 = data[0][:, 1] flow = data[1] self._check_images_and_flow( image1, image2, flow, save_images=False, plot_dir='/tmp/sintel') def test_sintel_eval(self): dataset = sintel.make_dataset( path=dataset_locations['sintel-train-clean'], mode='eval-occlusion') dataset = dataset.take(1) results = sintel.evaluate( mock_inference_fn, dataset, height=200, width=400, num_plots=0, plot_dir='/tmp/sintel') expected_keys = sintel.list_eval_keys() self.assertEqual(set(expected_keys), set(results.keys())) if __name__ == '__main__': absltest.main()
retro/examples/discretizer.py
MatPoliquin/retro
2,706
151040
""" Define discrete action spaces for Gym Retro environments with a limited set of button combos """ import gym import numpy as np import retro class Discretizer(gym.ActionWrapper): """ Wrap a gym environment and make it use discrete actions. Args: combos: ordered list of lists of valid button combinations """ def __init__(self, env, combos): super().__init__(env) assert isinstance(env.action_space, gym.spaces.MultiBinary) buttons = env.unwrapped.buttons self._decode_discrete_action = [] for combo in combos: arr = np.array([False] * env.action_space.n) for button in combo: arr[buttons.index(button)] = True self._decode_discrete_action.append(arr) self.action_space = gym.spaces.Discrete(len(self._decode_discrete_action)) def action(self, act): return self._decode_discrete_action[act].copy() class SonicDiscretizer(Discretizer): """ Use Sonic-specific discrete actions based on https://github.com/openai/retro-baselines/blob/master/agents/sonic_util.py """ def __init__(self, env): super().__init__(env=env, combos=[['LEFT'], ['RIGHT'], ['LEFT', 'DOWN'], ['RIGHT', 'DOWN'], ['DOWN'], ['DOWN', 'B'], ['B']]) def main(): env = retro.make(game='SonicTheHedgehog-Genesis', use_restricted_actions=retro.Actions.DISCRETE) print('retro.Actions.DISCRETE action_space', env.action_space) env.close() env = retro.make(game='SonicTheHedgehog-Genesis') env = SonicDiscretizer(env) print('SonicDiscretizer action_space', env.action_space) env.close() if __name__ == '__main__': main()
backend/accounts/management/commands/load.py
aibek79/Django-React-knboard
665
151045
from django.conf import settings from django.core import management from django.core.management.base import BaseCommand, CommandError class Command(BaseCommand): help = "Helpful command to load all fixtures" def handle(self, *args, **options): if not settings.DEBUG: raise CommandError("Command not meant for production") management.call_command("loaddata", "users") management.call_command("loaddata", "tasks") management.call_command("loaddata", "avatars")
allennlp/fairness/adversarial_bias_mitigator.py
alle-pawols/allennlp
11,433
151047
<gh_stars>1000+ """ A Model wrapper to adversarially mitigate biases in predictions produced by a pretrained model for a downstream task. The documentation and explanations are heavily based on: <NAME>., <NAME>., & <NAME>. (2018). [Mitigating Unwanted Biases with Adversarial Learning] (https://api.semanticscholar.org/CorpusID:9424845). Proceedings of the 2018 AAAI/ACM Conference on AI, Ethics, and Society. and [Mitigating Unwanted Biases in Word Embeddings with Adversarial Learning](https://colab.research.google.com/notebooks/ ml_fairness/adversarial_debiasing.ipynb) colab notebook. Adversarial networks mitigate some biases based on the idea that predicting an outcome Y given an input X should ideally be independent of some protected variable Z. Informally, "knowing Y would not help you predict Z any better than chance" (Zaldivar et al., 2018). This can be achieved using two networks in a series, where the first attempts to predict Y using X as input, and the second attempts to use the predicted value of Y to recover Z. Please refer to Figure 1 of [Mitigating Unwanted Biases with Adversarial Learning] (https://api.semanticscholar.org/CorpusID:9424845). Ideally, we would like the first network to predict Y without permitting the second network to predict Z any better than chance. For common NLP tasks, it's usually clear what X and Y are, but Z is not always available. We can construct our own Z by: 1. computing a bias direction (e.g. for binary gender) 2. computing the inner product of static sentence embeddings and the bias direction Training adversarial networks is extremely difficult. It is important to: 1. lower the step size of both the predictor and adversary to train both models slowly to avoid parameters diverging, 2. initialize the parameters of the adversary to be small to avoid the predictor overfitting against a sub-optimal adversary, 3. increase the adversary’s learning rate to prevent divergence if the predictor is too good at hiding the protected variable from the adversary. """ from overrides import overrides from typing import Dict, Optional import torch from allennlp.common.checks import ConfigurationError from allennlp.data import Vocabulary from allennlp.fairness.bias_direction_wrappers import BiasDirectionWrapper from allennlp.modules.feedforward import FeedForward from allennlp.models import Model from allennlp.nn import InitializerApplicator from allennlp.nn.util import find_embedding_layer from allennlp.training.callbacks.callback import TrainerCallback from allennlp.training.callbacks.backward import OnBackwardException from allennlp.training.gradient_descent_trainer import GradientDescentTrainer @Model.register("adversarial_bias_mitigator") class AdversarialBiasMitigator(Model): """ Wrapper class to adversarially mitigate biases in any pretrained Model. # Parameters vocab : `Vocabulary` Vocabulary of predictor. predictor : `Model` Model for which to mitigate biases. adversary : `Model` Model that attempts to recover protected variable values from predictor's predictions. bias_direction : `BiasDirectionWrapper` Bias direction used by adversarial bias mitigator. predictor_output_key : `str` Key corresponding to output in `output_dict` of predictor that should be passed as input to adversary. !!! Note adversary must use same vocab as predictor, if it requires a vocab. """ def __init__( self, vocab: Vocabulary, predictor: Model, adversary: Model, bias_direction: BiasDirectionWrapper, predictor_output_key: str, **kwargs, ): super().__init__(vocab, **kwargs) self.predictor = predictor self.adversary = adversary # want to keep adversary label hook during evaluation embedding_layer = find_embedding_layer(self.predictor) self.bias_direction = bias_direction self.predetermined_bias_direction = self.bias_direction(embedding_layer) self._adversary_label_hook = _AdversaryLabelHook(self.predetermined_bias_direction) embedding_layer.register_forward_hook(self._adversary_label_hook) self.vocab = self.predictor.vocab self._regularizer = self.predictor._regularizer self.predictor_output_key = predictor_output_key @overrides def train(self, mode: bool = True): super().train(mode) self.predictor.train(mode) self.adversary.train(mode) # appropriately change requires_grad # in bias direction when train() and # eval() are called self.bias_direction.train(mode) @overrides def forward(self, *args, **kwargs): predictor_output_dict = self.predictor.forward(*args, **kwargs) adversary_output_dict = self.adversary.forward( predictor_output_dict[self.predictor_output_key], self._adversary_label_hook.adversary_label, ) # prepend "adversary_" to every key in adversary_output_dict # to distinguish from predictor_output_dict keys adversary_output_dict = {("adversary_" + k): v for k, v in adversary_output_dict.items()} output_dict = {**predictor_output_dict, **adversary_output_dict} return output_dict # Delegate Model function calls to predictor # Currently doing this manually because difficult to # dynamically forward __getattribute__ due to # behind-the-scenes usage of dunder attributes by torch.nn.Module # and predictor inheriting from Model # Assumes Model is relatively stable @overrides def forward_on_instance(self, *args, **kwargs): return self.predictor.forward_on_instance(*args, **kwargs) @overrides def forward_on_instances(self, *args, **kwargs): return self.predictor.forward_on_instances(*args, **kwargs) @overrides def get_regularization_penalty(self, *args, **kwargs): return self.predictor.get_regularization_penalty(*args, **kwargs) @overrides def get_parameters_for_histogram_logging(self, *args, **kwargs): return self.predictor.get_parameters_for_histogram_logging(*args, **kwargs) @overrides def get_parameters_for_histogram_tensorboard_logging(self, *args, **kwargs): return self.predictor.get_parameters_for_histogram_tensorboard_logging(*args, **kwargs) @overrides def make_output_human_readable(self, *args, **kwargs): return self.predictor.make_output_human_readable(*args, **kwargs) @overrides def get_metrics(self, *args, **kwargs): return self.predictor.get_metrics(*args, **kwargs) @overrides def _get_prediction_device(self, *args, **kwargs): return self.predictor._get_prediction_device(*args, **kwargs) @overrides def _maybe_warn_for_unseparable_batches(self, *args, **kwargs): return self.predictor._maybe_warn_for_unseparable_batches(*args, **kwargs) @overrides def extend_embedder_vocab(self, *args, **kwargs): return self.predictor.extend_embedder_vocab(*args, **kwargs) @Model.register("feedforward_regression_adversary") class FeedForwardRegressionAdversary(Model): """ This `Model` implements a simple feedforward regression adversary. Registered as a `Model` with name "feedforward_regression_adversary". # Parameters vocab : `Vocabulary` feedforward : `FeedForward` A feedforward layer. initializer : `Optional[InitializerApplicator]`, optional (default=`InitializerApplicator()`) If provided, will be used to initialize the model parameters. """ def __init__( self, vocab: Vocabulary, feedforward: FeedForward, initializer: Optional[InitializerApplicator] = InitializerApplicator(), **kwargs, ) -> None: super().__init__(vocab, **kwargs) self._feedforward = feedforward self._loss = torch.nn.MSELoss() initializer(self) # type: ignore def forward( # type: ignore self, input: torch.FloatTensor, label: torch.FloatTensor ) -> Dict[str, torch.Tensor]: """ # Parameters input : `torch.FloatTensor` A tensor of size (batch_size, ...). label : `torch.FloatTensor` A tensor of the same size as input. # Returns An output dictionary consisting of: - `loss` : `torch.FloatTensor` A scalar loss to be optimised. """ pred = self._feedforward(input) return {"loss": self._loss(pred, label)} @TrainerCallback.register("adversarial_bias_mitigator_backward") class AdversarialBiasMitigatorBackwardCallback(TrainerCallback): """ Performs backpropagation for adversarial bias mitigation. While the adversary's gradients are computed normally, the predictor's gradients are computed such that updates to the predictor's parameters will not aid the adversary and will make it more difficult for the adversary to recover protected variables. !!! Note Intended to be used with `AdversarialBiasMitigator`. trainer.model is expected to have `predictor` and `adversary` data members. # Parameters adversary_loss_weight : `float`, optional (default = `1.0`) Quantifies how difficult predictor makes it for adversary to recover protected variables. """ def __init__(self, serialization_dir: str, adversary_loss_weight: float = 1.0) -> None: super().__init__(serialization_dir) self.adversary_loss_weight = adversary_loss_weight def on_backward( self, trainer: GradientDescentTrainer, batch_outputs: Dict[str, torch.Tensor], backward_called: bool, **kwargs, ) -> bool: if backward_called: raise OnBackwardException() if not hasattr(trainer.model, "predictor") or not hasattr(trainer.model, "adversary"): raise ConfigurationError( "Model is expected to have `predictor` and `adversary` data members." ) trainer.optimizer.zero_grad() # `retain_graph=True` prevents computation graph from being erased batch_outputs["adversary_loss"].backward(retain_graph=True) # trainer.model is expected to have `predictor` and `adversary` data members adversary_loss_grad = { name: param.grad.clone() for name, param in trainer.model.predictor.named_parameters() if param.grad is not None } trainer.model.predictor.zero_grad() batch_outputs["loss"].backward() with torch.no_grad(): for name, param in trainer.model.predictor.named_parameters(): if param.grad is not None: unit_adversary_loss_grad = adversary_loss_grad[name] / torch.linalg.norm( adversary_loss_grad[name] ) # prevent predictor from accidentally aiding adversary # by removing projection of predictor loss grad onto adversary loss grad param.grad -= ( (param.grad * unit_adversary_loss_grad) * unit_adversary_loss_grad ).sum() # make it difficult for adversary to recover protected variables param.grad -= self.adversary_loss_weight * adversary_loss_grad[name] # remove adversary_loss from computation graph batch_outputs["adversary_loss"] = batch_outputs["adversary_loss"].detach() return True class _AdversaryLabelHook: def __init__(self, predetermined_bias_direction): self.predetermined_bias_direction = predetermined_bias_direction def __call__(self, module, module_in, module_out): """ Called as forward hook. """ with torch.no_grad(): # mean pooling over static word embeddings to get sentence embedding module_out = module_out.mean(dim=1) self.adversary_label = torch.matmul( module_out, self.predetermined_bias_direction.to(module_out.device) ).unsqueeze(-1)
src/page/showreview.py
fekblom/critic
216
151091
# -*- mode: python; encoding: utf-8 -*- # # Copyright 2012 <NAME>, Opera Software ASA # # Licensed under the Apache License, Version 2.0 (the "License"); you may not # use this file except in compliance with the 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 in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations under # the License. import datetime import calendar import traceback import dbutils import gitutils import htmlutils import page.utils import log.html import reviewing.utils as review_utils import reviewing.html as review_html import reviewing.comment as review_comment import configuration import diff import profiling import linkify import textutils try: from customization.paths import getModuleFromFile except: def getModuleFromFile(repository, filename): try: base, rest = filename.split("/", 1) return base + "/" except: return None class SummaryColumn(log.html.SummaryColumn): def __init__(self, review): log.html.SummaryColumn.__init__(self) self.__review = review self.__cache = {} def fillCache(self, db, review): cursor = db.cursor() cursor.execute("""SELECT DISTINCT assignee, child FROM fullreviewuserfiles JOIN changesets ON (changesets.id=changeset) WHERE review=%s AND state='pending'""", (review.id,)) for user_id, commit_id in cursor: self.__cache.setdefault(commit_id, set()).add(user_id) def render(self, db, commit, target, overrides={}): user_ids = self.__cache.get(commit.getId(db)) if user_ids: users = ["%s:%s" % (user.fullname, user.status) for user in dbutils.User.fromIds(db, [user_id for user_id in user_ids])] target.setAttribute("critic-reviewers", ",".join(sorted(users))) log.html.SummaryColumn.render(self, db, commit, target, overrides=overrides) class ApprovalColumn: APPROVED = 1 TOTAL = 2 def __init__(self, user, review, type, cache): self.__user = user self.__review = review self.__type = type self.__cache = cache @staticmethod def fillCache(db, user, review, cache, profiler): cursor = db.cursor() profiler.check("fillCache") cursor.execute("""SELECT child, state, COUNT(*), SUM(deleted), SUM(inserted) FROM changesets JOIN reviewfiles ON (changeset=changesets.id) WHERE review=%s GROUP BY child, state""", (review.id,)) for commit_id, state, nfiles, deleted, inserted in cursor: data = cache.get(commit_id) if not data: data = cache[commit_id] = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] if state == 'reviewed': data[3] += nfiles data[4] += deleted data[5] += inserted data[0] += nfiles data[1] += deleted data[2] += inserted profiler.check("fillCache: total") cursor.execute("""SELECT child, COALESCE(reviewfilechanges.to_state, reviewfiles.state) AS effective_state, COUNT(*), SUM(deleted), SUM(inserted) FROM changesets JOIN reviewfiles ON (changeset=changesets.id) JOIN reviewuserfiles ON (reviewuserfiles.file=reviewfiles.id) LEFT OUTER JOIN reviewfilechanges ON (reviewfilechanges.file=reviewfiles.id AND reviewfilechanges.uid=reviewuserfiles.uid AND reviewfilechanges.state='draft') WHERE review=%s AND reviewuserfiles.uid=%s GROUP BY child, effective_state""", (review.id, user.id)) for commit_id, state, nfiles, deleted, inserted in cursor: data = cache.get(commit_id) if state == 'reviewed': data[9] += nfiles data[10] += deleted data[11] += inserted data[6] += nfiles data[7] += deleted data[8] += inserted profiler.check("fillCache: user") def __calculate(self, db, commit): return self.__cache.get(commit.id, [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]) def className(self, db, commit): if commit: (total_nfiles, total_deleted, total_inserted, approved_nfiles, approved_deleted, approved_inserted, user_total_nfiles, user_total_deleted, user_total_inserted, user_approved_nfiles, user_approved_deleted, user_approved_inserted) = self.__calculate(db, commit) if user_approved_nfiles == user_total_nfiles: category = "" else: category = " user" else: category = "" if self.__type == ApprovalColumn.APPROVED: return "approval" + category else: return "total" + category def heading(self, target): if self.__type == ApprovalColumn.APPROVED: target.text("Pending") else: target.text("Total") def render(self, db, commit, target, overrides={}): (total_nfiles, total_deleted, total_inserted, approved_nfiles, approved_deleted, approved_inserted, user_total_nfiles, user_total_deleted, user_total_inserted, user_approved_nfiles, user_approved_deleted, user_approved_inserted) = self.__calculate(db, commit) if self.__type == ApprovalColumn.APPROVED: if user_approved_nfiles == user_total_nfiles: if approved_nfiles == total_nfiles: target.text() elif approved_deleted == total_deleted and approved_inserted == total_inserted: target.span().text("?? %") else: target.span().text("%d %%" % int(100.0 * ((total_deleted + total_inserted) - (approved_deleted + approved_inserted)) / (total_deleted + total_inserted))) elif user_approved_deleted == user_total_deleted and user_approved_inserted == user_total_inserted: target.span().text("?? %") else: target.span().text("%d %%" % int(100.0 * ((user_total_deleted + user_total_inserted) - (user_approved_deleted + user_approved_inserted)) / (user_total_deleted + user_total_inserted))) else: if user_approved_deleted == user_total_deleted and user_approved_inserted == user_total_inserted: target.span().text("-%d/+%d" % (total_deleted, total_inserted)) else: target.span().text("-%d/+%d" % (user_total_deleted, user_total_inserted)) def notModified(req, db, user, review): value = req.getRequestHeader("If-None-Match") return review.getETag(db, user) == value def renderShowReview(req, db, user): profiler = profiling.Profiler() cursor = db.cursor() if user.getPreference(db, "commit.diff.compactMode"): default_compact = "yes" else: default_compact = "no" compact = req.getParameter("compact", default_compact) == "yes" highlight = req.getParameter("highlight", None) review_id = req.getParameter("id", filter=int) review = dbutils.Review.fromId(db, review_id, profiler=profiler) profiler.check("create review") if not review: raise page.utils.DisplayMessage("Invalid Review ID", "%d is not a valid review ID." % review_id) if review.getETag(db, user) == req.getRequestHeader("If-None-Match"): raise page.utils.NotModified profiler.check("ETag") repository = review.repository prefetch_commits = {} cursor.execute("""SELECT DISTINCT sha1, child FROM changesets JOIN reviewchangesets ON (reviewchangesets.changeset=changesets.id) JOIN commits ON (commits.id=changesets.child) WHERE review=%s""", (review.id,)) prefetch_commits.update(dict(cursor)) profiler.check("commits (query)") cursor.execute("""SELECT old_head, old_head_commit.sha1, new_head, new_head_commit.sha1, new_upstream, new_upstream_commit.sha1, equivalent_merge, equivalent_merge_commit.sha1, replayed_rebase, replayed_rebase_commit.sha1 FROM reviewrebases LEFT OUTER JOIN commits AS old_head_commit ON (old_head_commit.id=old_head) LEFT OUTER JOIN commits AS new_head_commit ON (new_head_commit.id=new_head) LEFT OUTER JOIN commits AS new_upstream_commit ON (new_upstream_commit.id=new_upstream) LEFT OUTER JOIN commits AS equivalent_merge_commit ON (equivalent_merge_commit.id=equivalent_merge) LEFT OUTER JOIN commits AS replayed_rebase_commit ON (replayed_rebase_commit.id=replayed_rebase) WHERE review=%s""", (review.id,)) rebases = cursor.fetchall() if rebases: has_finished_rebases = False for (old_head_id, old_head_sha1, new_head_id, new_head_sha1, new_upstream_id, new_upstream_sha1, equivalent_merge_id, equivalent_merge_sha1, replayed_rebase_id, replayed_rebase_sha1) in rebases: if old_head_id: prefetch_commits[old_head_sha1] = old_head_id if new_head_id: prefetch_commits[new_head_sha1] = new_head_id has_finished_rebases = True if new_upstream_id: prefetch_commits[new_upstream_sha1] = new_upstream_id if equivalent_merge_id: prefetch_commits[equivalent_merge_sha1] = equivalent_merge_id if replayed_rebase_id: prefetch_commits[replayed_rebase_sha1] = replayed_rebase_id profiler.check("auxiliary commits (query)") if has_finished_rebases: cursor.execute("""SELECT commits.sha1, commits.id FROM commits JOIN reachable ON (reachable.commit=commits.id) WHERE branch=%s""", (review.branch.id,)) prefetch_commits.update(dict(cursor)) profiler.check("actual commits (query)") prefetch_commits = gitutils.FetchCommits(repository, prefetch_commits) document = htmlutils.Document(req) html = document.html() head = html.head() body = html.body(onunload="void(0);") def flush(target=None): return document.render(stop=target, pretty=not compact) def renderHeaderItems(target): has_draft_items = review_utils.renderDraftItems(db, user, review, target) target = target.div("buttons") if not has_draft_items: if review.state == "open": if review.accepted(db): target.button(id="closeReview", onclick="closeReview();").text("Close Review") else: if user in review.owners or user.getPreference(db, "review.pingAnyReview"): target.button(id="pingReview", onclick="pingReview();").text("Ping Review") if user in review.owners or user.getPreference(db, "review.dropAnyReview"): target.button(id="dropReview", onclick="dropReview();").text("Drop Review") if user in review.owners and not review.description: target.button(id="writeDescription", onclick="editDescription();").text("Write Description") else: target.button(id="reopenReview", onclick="reopenReview();").text("Reopen Review") target.span("buttonscope buttonscope-global") profiler.check("prologue") page.utils.generateHeader(body, db, user, renderHeaderItems, profiler=profiler) cursor.execute("SELECT 1 FROM fullreviewuserfiles WHERE review=%s AND state='pending' AND assignee=%s", (review.id, user.id)) hasPendingChanges = bool(cursor.fetchone()) if hasPendingChanges: head.setLink("next", "showcommit?review=%d&filter=pending" % review.id) profiler.check("header") document.addExternalStylesheet("resource/showreview.css") document.addExternalStylesheet("resource/review.css") document.addExternalStylesheet("resource/comment.css") document.addExternalScript("resource/showreview.js") document.addExternalScript("resource/review.js") document.addExternalScript("resource/comment.js") document.addExternalScript("resource/reviewfilters.js") document.addExternalScript("resource/autocomplete.js") document.addInternalScript(user.getJS()) document.addInternalScript("var isReviewFrontpage = true;") document.addInternalScript("var owners = [ %s ];" % ", ".join(owner.getJSConstructor() for owner in review.owners)) document.addInternalScript("var updateCheckInterval = %d;" % user.getPreference(db, "review.updateCheckInterval")); log.html.addResources(document) document.addInternalScript(review.getJS()) target = body.div("main") basic = target.table('paleyellow basic', align='center') basic.col(width='10%') basic.col(width='60%') basic.col(width='30%') h1 = basic.tr().td('h1', colspan=3).h1() h1.text("r/%d: " % review.id) h1.span(id="summary").text("%s" % review.summary, linkify=linkify.Context(db=db, review=review)) h1.a("edit", href="javascript:editSummary();").text("[edit]") def linkToCommit(commit): cursor.execute("SELECT 1 FROM commits JOIN changesets ON (child=commits.id) JOIN reviewchangesets ON (changeset=changesets.id) WHERE sha1=%s AND review=%s", (commit.sha1, review.id)) if cursor.fetchone(): return "%s/%s?review=%d" % (review.repository.name, commit.sha1, review.id) return "%s/%s" % (review.repository.name, commit.sha1) def row(heading, value, help, right=None, linkify=False, cellId=None): main_row = basic.tr('line') main_row.td('heading').text("%s:" % heading) if right is False: colspan = 2 else: colspan = None if callable(value): value(main_row.td('value', id=cellId, colspan=colspan).preformatted()) else: main_row.td('value', id=cellId, colspan=colspan).preformatted().text(value, linkify=linkify, repository=review.repository) if right is False: pass elif callable(right): right(main_row.td('right', valign='bottom')) else: main_row.td('right').text() if help: basic.tr('help').td('help', colspan=3).text(help) def renderBranchName(target): classes = "branch inset" if review.branch.archived: classes += " archived" target.code(classes).text(review.branch.name, linkify=linkify.Context()) if repository.name != user.getPreference(db, "defaultRepository"): target.text(" in ") target.code("repository inset").text(repository.getURL(db, user)) buttons = target.div("buttons") cursor.execute("""SELECT id, remote, remote_name, disabled, previous FROM trackedbranches WHERE repository=%s AND local_name=%s""", (repository.id, review.branch.name)) row = cursor.fetchone() if row: trackedbranch_id, remote, remote_name, disabled, previous = row target.p("tracking disabled" if disabled else "tracking").text("tracking") target.code("branch inset").text(remote_name, linkify=linkify.Context(remote=remote)) target.text(" in ") target.code("repository inset").text(remote, linkify=linkify.Context()) if previous: target.span("lastupdate").script(type="text/javascript").text("document.write('(last fetched: ' + shortDate(new Date(%d)) + ')');" % (calendar.timegm(previous.utctimetuple()) * 1000)) if user in review.owners or user.hasRole(db, "administrator"): if review.state == "open": if disabled: button = buttons.button("enabletracking", onclick=("enableTracking(%d, %s, %s);" % (trackedbranch_id, htmlutils.jsify(remote), htmlutils.jsify(remote_name)))) button.text("Enable Tracking") else: buttons.button("disabletracking", onclick="triggerUpdate(%d);" % trackedbranch_id).text("Update Now") buttons.button("disabletracking", onclick="disableTracking(%d);" % trackedbranch_id).text("Disable Tracking") buttons.button("rebasereview", onclick="location.assign('/rebasetrackingreview?review=%d');" % review.id).text("Rebase Review") if review.state != "open" and review.branch.archived: buttons.button("resurrect").text("Resurrect Branch") def renderPeople(target, list): for index, person in enumerate(list): if index != 0: target.text(", ") span = target.span("user %s" % person.status) span.span("name").text(person.fullname) if person.status == 'absent': span.span("status").text(" (%s)" % person.getAbsence(db)) elif person.status == 'retired': span.span("status").text(" (retired)") def renderOwners(target): renderPeople(target, review.owners) def renderReviewers(target): if review.reviewers: renderPeople(target, review.reviewers) else: target.i().text("No reviewers.") cursor.execute("""SELECT reviewfilters.id, reviewfilters.uid, reviewfilters.path FROM reviewfilters JOIN users ON (reviewfilters.uid=users.id) WHERE reviewfilters.review=%s AND reviewfilters.type='reviewer' AND users.status!='retired'""", (review.id,)) rows = cursor.fetchall() reviewer_filters_hidden = [] if rows: table = target.table("reviewfilters reviewers") row = table.thead().tr("h1") row.th("h1", colspan=4).text("Custom filters:") filter_data = {} reviewfilters = {} for filter_id, user_id, path in rows: filter_user = dbutils.User.fromId(db, user_id) path = path or '/' reviewfilters.setdefault(filter_user.fullname, []).append(path) filter_data[(filter_user.fullname, path)] = (filter_id, filter_user) count = 0 tbody = table.tbody() for fullname in sorted(reviewfilters.keys()): original_paths = sorted(reviewfilters[fullname]) trimmed_paths = diff.File.eliminateCommonPrefixes(original_paths[:]) first = True for original_path, trimmed_path in zip(original_paths, trimmed_paths): row = tbody.tr("filter") if first: row.td("username", rowspan=len(original_paths)).text(fullname) row.td("reviews", rowspan=len(original_paths)).text("reviews") first = False row.td("path").span().innerHTML(trimmed_path) filter_id, filter_user = filter_data[(fullname, original_path)] href = "javascript:removeReviewFilter(%d, %s, 'reviewer', %s, %s);" % (filter_id, filter_user.getJSConstructor(), htmlutils.jsify(original_path), "true" if filter_user != user else "false") row.td("remove").a(href=href).text("[remove]") count += 1 tfoot = table.tfoot() tfoot.tr().td(colspan=4).text("%d line%s hidden" % (count, "s" if count > 1 else "")) if count > 10: tbody.setAttribute("class", "hidden") reviewer_filters_hidden.append(True) else: tfoot.setAttribute("class", "hidden") reviewer_filters_hidden.append(False) buttons = target.div("buttons") if reviewer_filters_hidden: buttons.button("showfilters", onclick="toggleReviewFilters('reviewers', $(this));").text("%s Custom Filters" % ("Show" if reviewer_filters_hidden[0] else "Hide")) if not review.applyfilters: buttons.button("applyfilters", onclick="applyFilters('global');").text("Apply Global Filters") if review.applyfilters and review.repository.parent and not review.applyparentfilters: buttons.button("applyparentfilters", onclick="applyFilters('upstream');").text("Apply Upstream Filters") buttons.button("addreviewer", onclick="addReviewer();").text("Add Reviewer") buttons.button("manage", onclick="location.href='managereviewers?review=%d';" % review.id).text("Manage Assignments") def renderWatchers(target): if review.watchers: renderPeople(target, review.watchers) else: target.i().text("No watchers.") cursor.execute("""SELECT reviewfilters.id, reviewfilters.uid, reviewfilters.path FROM reviewfilters JOIN users ON (reviewfilters.uid=users.id) WHERE reviewfilters.review=%s AND reviewfilters.type='watcher' AND users.status!='retired'""", (review.id,)) rows = cursor.fetchall() watcher_filters_hidden = [] if rows: table = target.table("reviewfilters watchers") row = table.thead().tr("h1") row.th("h1", colspan=4).text("Custom filters:") filter_data = {} reviewfilters = {} for filter_id, user_id, path in rows: filter_user = dbutils.User.fromId(db, user_id) path = path or '/' reviewfilters.setdefault(filter_user.fullname, []).append(path) filter_data[(filter_user.fullname, path)] = (filter_id, filter_user) count = 0 tbody = table.tbody() for fullname in sorted(reviewfilters.keys()): original_paths = sorted(reviewfilters[fullname]) trimmed_paths = diff.File.eliminateCommonPrefixes(original_paths[:]) first = True for original_path, trimmed_path in zip(original_paths, trimmed_paths): row = tbody.tr("filter") if first: row.td("username", rowspan=len(original_paths)).text(fullname) row.td("reviews", rowspan=len(original_paths)).text("watches") first = False row.td("path").span().innerHTML(trimmed_path) filter_id, filter_user = filter_data[(fullname, original_path)] href = "javascript:removeReviewFilter(%d, %s, 'watcher', %s, %s);" % (filter_id, filter_user.getJSConstructor(), htmlutils.jsify(original_path), "true" if filter_user != user else "false") row.td("remove").a(href=href).text("[remove]") count += 1 tfoot = table.tfoot() tfoot.tr().td(colspan=4).text("%d line%s hidden" % (count, "s" if count > 1 else "")) if count > 10: tbody.setAttribute("class", "hidden") watcher_filters_hidden.append(True) else: tfoot.setAttribute("class", "hidden") watcher_filters_hidden.append(False) buttons = target.div("buttons") if watcher_filters_hidden: buttons.button("showfilters", onclick="toggleReviewFilters('watchers', $(this));").text("%s Custom Filters" % ("Show" if watcher_filters_hidden[0] else "Hide")) buttons.button("addwatcher", onclick="addWatcher();").text("Add Watcher") if user not in review.reviewers and user not in review.owners: if user not in review.watchers: buttons.button("watch", onclick="watchReview();").text("Watch Review") elif review.watchers[user] == "manual": buttons.button("watch", onclick="unwatchReview();").text("Stop Watching Review") def renderEditOwners(target): target.button("description", onclick="editOwners();").text("Edit Owners") def renderEditDescription(target): target.button("description", onclick="editDescription();").text("Edit Description") def renderRecipientList(target): cursor.execute("""SELECT uid, fullname, include FROM reviewrecipientfilters LEFT OUTER JOIN users ON (uid=id) WHERE review=%s""", (review.id,)) default_include = True included = dict((owner.fullname, owner.id) for owner in review.owners) excluded = {} for user_id, fullname, include in cursor: if user_id is None: default_include = include elif include: included[fullname] = user_id elif user_id not in review.owners: excluded[fullname] = user_id mode = None users = None buttons = [] opt_in_button = False opt_out_button = False if default_include: if excluded: mode = "Everyone except " users = excluded opt_out_button = user.fullname not in excluded opt_in_button = not opt_out_button else: mode = "Everyone." opt_out_button = True else: if included: mode = "No-one except " users = included opt_in_button = user.fullname not in included opt_out_button = not opt_in_button else: mode = "No-one at all." opt_in_button = True if user not in review.owners and (user in review.reviewers or user in review.watchers): if opt_in_button: buttons.append(("Include me, please!", "includeRecipient(%d);" % user.id)) if opt_out_button: buttons.append(("Exclude me, please!", "excludeRecipient(%d);" % user.id)) target.span("mode").text(mode) if users: container = target.span("users") first = True for fullname in sorted(users.keys()): if first: first = False else: container.text(", ") container.span("user", critic_user_id=users[fullname]).text(fullname) container.text(".") if buttons: container = target.div("buttons") for label, onclick in buttons: container.button(onclick=onclick).text(label) row("Branch", renderBranchName, "The branch containing the commits to review.", right=False) row("Owner%s" % ("s" if len(review.owners) > 1 else ""), renderOwners, "The users who created and/or owns the review.", right=renderEditOwners) if review.description: row("Description", review.description, "A longer description of the changes to be reviewed.", linkify=linkToCommit, cellId="description", right=renderEditDescription) row("Reviewers", renderReviewers, "Users responsible for reviewing the changes in this review.", right=False) row("Watchers", renderWatchers, "Additional users who receive e-mails about updates to this review.", right=False) row("Recipient List", renderRecipientList, "Users (among the reviewers and watchers) who will receive any e-mails about the review.", right=False) profiler.check("basic") review_state = review.getReviewState(db) profiler.check("review state") progress = target.table('paleyellow progress', align='center') progress_header = progress.tr().td('h1', colspan=3).h1() progress_header.text("Review Progress") progress_header_right = progress_header.span("right") progress_header_right.text("Display log: ") progress_header_right.a(href="showreviewlog?review=%d&granularity=module" % review.id).text("[per module]") progress_header_right.text() progress_header_right.a(href="showreviewlog?review=%d&granularity=file" % review.id).text("[per file]") progress_h1 = progress.tr().td('percent', colspan=3).h1() title_data = { 'id': 'r/%d' % review.id, 'summary': review.summary, 'progress': str(review_state) } if review.state == "closed": progress_h1.img(src=htmlutils.getStaticResourceURI("seal-of-approval-left.png"), style="position: absolute; margin-left: -80px; margin-top: -100px") progress_h1.text("Finished!") for branch in review.repository.getSignificantBranches(db): if review.branch.getHead(db).isAncestorOf(branch.head_sha1): remark = progress_h1.div().span("remark") remark.text("Merged to ") remark.a(href="/log?repository=%s&branch=%s" % (review.repository.name, branch.name)).text(branch.name) remark.text(".") elif review.state == "dropped": progress_h1.text("Dropped...") elif review.state == "open" and review_state.accepted: progress_h1.img(src=htmlutils.getStaticResourceURI("seal-of-approval-left.png"), style="position: absolute; margin-left: -80px; margin-top: -100px") progress_h1.text("Accepted!") progress_h1.div().span("remark").text("Hurry up and close it before anyone has a change of heart.") else: progress_h1.text(review_state.getProgress()) if review_state.issues: progress_h1.span("comments").text(" and ") progress_h1.text("%d" % review_state.issues) progress_h1.span("comments").text(" issue%s" % (review_state.issues > 1 and "s" or "")) if review_state.getPercentReviewed() != 100.0: cursor = db.cursor() cursor.execute("""SELECT 1 FROM reviewfiles LEFT OUTER JOIN reviewuserfiles ON (reviewuserfiles.file=reviewfiles.id) WHERE reviewfiles.review=%s AND reviewfiles.state='pending' AND reviewuserfiles.uid IS NULL""", (review.id,)) if cursor.fetchone(): progress.tr().td('stuck', colspan=3).a(href="showreviewlog?review=%d&granularity=file&unassigned=yes" % review.id).text("Not all changes have a reviewer assigned!") cursor.execute("""SELECT uid, MIN(reviewuserfiles.time) FROM reviewfiles JOIN reviewuserfiles ON (reviewuserfiles.file=reviewfiles.id) WHERE reviewfiles.review=%s AND reviewfiles.state='pending' GROUP BY reviewuserfiles.uid""", (review.id,)) now = datetime.datetime.now() def seconds_since(timestamp): if isinstance(timestamp, int): # We tell sqlite3 to convert TIMESTAMP values into datetime # objects, but apparently MIN(timestamp) as used in the # query above isn't typed as TIMESTAMP by SQLite, so doesn't # get converted automatically. timestamp = datetime.datetime.fromtimestamp(timestamp) delta = now - timestamp return delta.days * 60 * 60 * 24 + delta.seconds pending_reviewers = [(dbutils.User.fromId(db, user_id), seconds_since(timestamp)) for (user_id, timestamp) in cursor.fetchall() if seconds_since(timestamp) > 60 * 60 * 8] if pending_reviewers: progress.tr().td('stragglers', colspan=3).text("Needs review from") for reviewer, seconds in pending_reviewers: if reviewer.status == 'retired': continue elif reviewer.status == 'absent': warning = " absent" elif not reviewer.getPreference(db, "email.activated"): warning = " no-email" else: warning = "" if seconds < 60 * 60 * 24: hours = seconds / (60 * 60) duration = " (%d hour%s)" % (hours, "s" if hours > 1 else "") elif seconds < 60 * 60 * 24 * 7: days = seconds / (60 * 60 * 24) duration = " (%d day%s)" % (days, "s" if days > 1 else "") elif seconds < 60 * 60 * 24 * 30: weeks = seconds / (60 * 60 * 24 * 7) duration = " (%d week%s)" % (weeks, "s" if weeks > 1 else "") else: duration = " (wake up!)" progress.tr().td('straggler' + warning, colspan=3).text("%s%s" % (reviewer.fullname, duration)) if user in review.owners: progress.tr().td('pinging', colspan=3).span().text("Send a message to these users by pinging the review.") title_format = user.getPreference(db, 'ui.title.showReview') try: document.setTitle(title_format % title_data) except Exception as exc: document.setTitle(traceback.format_exception_only(type(exc), exc)[0].strip()) profiler.check("progress") check = profiler.start("ApprovalColumn.fillCache") approval_cache = {} ApprovalColumn.fillCache(db, user, review, approval_cache, profiler) check.stop() summary_column = SummaryColumn(review) summary_column.fillCache(db, review) profiler.check("SummaryColumn.fillCache") columns = [(10, log.html.WhenColumn()), (60, summary_column), (16, log.html.AuthorColumn()), (7, ApprovalColumn(user, review, ApprovalColumn.APPROVED, approval_cache)), (7, ApprovalColumn(user, review, ApprovalColumn.TOTAL, approval_cache))] def renderReviewPending(db, target): if not user.isAnonymous(): target.text("Filter: ") if hasPendingChanges: target.a(href="showcommit?review=%d&filter=pending" % review.id, title="All changes you need to review.").text("[pending]") target.text() if user in review.reviewers: target.a(href="showcommit?review=%d&filter=reviewable" % review.id, title="All changes you can review, including what you've already reviewed.").text("[reviewable]") target.text() target.a(href="showcommit?review=%d&filter=relevant" % review.id, title="All changes that match your filters.").text("[relevant]") target.text() target.text("Manual: ") target.a(href="filterchanges?review=%d" % review.id, title="Manually select what files to display of the changes from all commits.").text("[full]") target.text() target.a(href="javascript:void(filterPartialChanges());", title="Manually select what files to display of the changes in a selection of commits.").text("[partial]") req.addResponseHeader("ETag", review.getETag(db, user)) if user.getPreference(db, "review.useMustRevalidate"): req.addResponseHeader("Cache-Control", "must-revalidate") yield flush(target) try: if prefetch_commits.error is None: prefetch_commits.getCommits(db) profiler.check("FetchCommits.getCommits()") cursor.execute("""SELECT DISTINCT parent, child FROM changesets JOIN reviewchangesets ON (reviewchangesets.changeset=changesets.id) JOIN commits ON (commits.id=changesets.child) WHERE review=%s AND type!='conflicts'""", (review.id,)) commits = set() for parent_id, child_id in cursor: commits.add(gitutils.Commit.fromId(db, repository, child_id)) commits = list(commits) cursor.execute("""SELECT id, old_head, new_head, new_upstream, equivalent_merge, replayed_rebase, uid, branch FROM reviewrebases WHERE review=%s""", (review.id,)) all_rebases = [(rebase_id, gitutils.Commit.fromId(db, repository, old_head), gitutils.Commit.fromId(db, repository, new_head) if new_head else None, dbutils.User.fromId(db, user_id), gitutils.Commit.fromId(db, repository, new_upstream) if new_upstream is not None else None, gitutils.Commit.fromId(db, repository, equivalent_merge) if equivalent_merge is not None else None, gitutils.Commit.fromId(db, repository, replayed_rebase) if replayed_rebase is not None else None, branch_name) for rebase_id, old_head, new_head, new_upstream, equivalent_merge, replayed_rebase, user_id, branch_name in cursor] bottom_right = None finished_rebases = filter(lambda item: item[2] is not None, all_rebases) current_rebases = filter(lambda item: item[2] is None, all_rebases) if current_rebases: assert len(current_rebases) == 1 def renderCancelRebase(db, target): target.button("cancelrebase").text("Cancel Rebase") if user == current_rebases[0][3]: bottom_right = renderCancelRebase else: def renderPrepareRebase(db, target): target.button("preparerebase").text("Prepare Rebase") bottom_right = renderPrepareRebase if finished_rebases: cursor.execute("""SELECT commit FROM reachable WHERE branch=%s""", (review.branch.id,)) actual_commits = [gitutils.Commit.fromId(db, repository, commit_id) for (commit_id,) in cursor] else: actual_commits = [] log.html.render(db, target, "Commits (%d)", commits=commits, columns=columns, title_right=renderReviewPending, rebases=finished_rebases, branch_name=review.branch.name, bottom_right=bottom_right, review=review, highlight=highlight, profiler=profiler, user=user, extra_commits=actual_commits) yield flush(target) profiler.check("log") except gitutils.GitReferenceError as error: div = target.div("error") div.h1().text("Error!") div.text("The commit %s is missing from the repository." % error.sha1) except gitutils.GitError as error: div = target.div("error") div.h1().text("Error!") div.text("Failed to read commits from the repository: %s" % error.message) all_chains = review_comment.CommentChain.fromReview(db, review, user) profiler.check("chains (load)") if all_chains: issue_chains = filter(lambda chain: chain.type == "issue", all_chains) draft_issues = filter(lambda chain: chain.state == "draft", issue_chains) open_issues = filter(lambda chain: chain.state == "open", issue_chains) addressed_issues = filter(lambda chain: chain.state == "addressed", issue_chains) closed_issues = filter(lambda chain: chain.state == "closed", issue_chains) note_chains = filter(lambda chain: chain.type == "note", all_chains) draft_notes = filter(lambda chain: chain.state == "draft", note_chains) open_notes = filter(lambda chain: chain.state != "draft" and chain.state != "empty", note_chains) else: open_issues = [] open_notes = [] chains = target.table("paleyellow comments", align="center", cellspacing=0) h1 = chains.tr("h1").td("h1", colspan=3).h1().text("Comments") links = h1.span("links") if all_chains: links.a(href="showcomments?review=%d&filter=all" % review.id).text("[display all]") if not user.isAnonymous(): links.a(href="showcomments?review=%d&filter=all&blame=%s" % (review.id, user.name)).text("[in my commits]") cursor.execute("""SELECT count(commentstoread.comment) > 0 FROM commentchains JOIN comments ON (comments.chain=commentchains.id) JOIN commentstoread ON (commentstoread.comment=comments.id) WHERE commentchains.review=%s AND commentstoread.uid=%s""", [review.id, user.id]) if cursor.fetchone()[0]: links.a(href="showcomments?review=%d&filter=toread" % review.id).text("[display unread]") def renderChains(target, chains): for chain in chains: row = target.tr("comment %s %s" % (chain.type, chain.state)) row.td("author").text(chain.user.fullname) row.td("title").a(href="showcomment?chain=%d" % chain.id).innerHTML(chain.leader()) ncomments = chain.countComments() nunread = chain.countUnread() cell = row.td("when") if ncomments <= 1: if nunread: cell.b().text("Unread") else: cell.text("No replies") else: if nunread: cell.b().text("%d of %d unread" % (nunread, ncomments)) else: cell.text("%d repl%s" % (ncomments - 1, "ies" if ncomments > 2 else "y")) if draft_issues: h2 = chains.tr("h2", id="draft-issues").td("h2", colspan=3).h2().text("Draft Issues") h2.a(href="showcomments?review=%d&filter=draft-issues" % review.id).text("[display all]") h2.a(href="showcomments?review=%d&filter=draft-issues&blame=%s" % (review.id, user.name)).text("[in my commits]") renderChains(chains, draft_issues) if open_issues: h2 = chains.tr("h2", id="open-issues").td("h2", colspan=3).h2().text("Open Issues") h2.a(href="showcomments?review=%d&filter=open-issues" % review.id).text("[display all]") h2.a(href="showcomments?review=%d&filter=open-issues&blame=%s" % (review.id, user.name)).text("[in my commits]") renderChains(chains, open_issues) if addressed_issues: h2 = chains.tr("h2", id="addressed-issues").td("h2", colspan=3).h2().text("Addressed Issues") h2.a(href="showcomments?review=%d&filter=addressed-issues" % review.id).text("[display all]") h2.a(href="showcomments?review=%d&filter=addressed-issues&blame=%s" % (review.id, user.name)).text("[in my commits]") renderChains(chains, addressed_issues) if closed_issues: h2 = chains.tr("h2", id="closed-issues").td("h2", colspan=3).h2().text("Resolved Issues") h2.a(href="showcomments?review=%d&filter=closed-issues" % review.id).text("[display all]") h2.a(href="showcomments?review=%d&filter=closed-issues&blame=%s" % (review.id, user.name)).text("[in my commits]") renderChains(chains, closed_issues) if draft_notes: h2 = chains.tr("h2", id="draft-notes").td("h2", colspan=3).h2().text("Draft Notes") h2.a(href="showcomments?review=%d&filter=draft-notes" % review.id).text("[display all]") h2.a(href="showcomments?review=%d&filter=draft-notes&blame=%s" % (review.id, user.name)).text("[in my commits]") renderChains(chains, draft_notes) if open_notes: h2 = chains.tr("h2", id="notes").td("h2", colspan=3).h2().text("Notes") h2.a(href="showcomments?review=%d&filter=open-notes" % review.id).text("[display all]") h2.a(href="showcomments?review=%d&filter=open-notes&blame=%s" % (review.id, user.name)).text("[in my commits]") renderChains(chains, open_notes) buttons = chains.tr("buttons").td("buttons", colspan=3) buttons.button(onclick="CommentChain.create('issue');").text("Raise Issue") buttons.button(onclick="CommentChain.create('note');").text("Write Note") profiler.check("chains (render)") yield flush(target) cursor.execute("""SELECT DISTINCT reviewfiles.file, theirs.uid FROM reviewfiles JOIN reviewuserfiles AS yours ON (yours.file=reviewfiles.id) JOIN reviewuserfiles AS theirs ON (theirs.file=yours.file AND theirs.uid!=yours.uid) WHERE reviewfiles.review=%s AND yours.uid=%s""", (review.id, user.id)) rows = cursor.fetchall() profiler.check("shared assignments (query)") if rows: reviewers = {} for file_id, user_id in rows: reviewers.setdefault(file_id, {})[user_id] = set() shared = target.table('paleyellow shared', align='center', cellspacing=0) row = shared.tr('h1') shared_header = row.td('h1', colspan=2).h1() shared_header.text("Shared Assignments") shared_buttons = row.td('buttons', colspan=2).span(style="display: none") shared_buttons.button("confirm").text("Confirm") shared_buttons.button("cancel").text("Cancel") granularity = "module" def moduleFromFile(file_id): filename = dbutils.describe_file(db, file_id) return getModuleFromFile(repository, filename) or filename def formatFiles(files): paths = sorted([dbutils.describe_file(db, file_id) for file_id in files]) if granularity == "file": return diff.File.eliminateCommonPrefixes(paths) else: modules = set() files = [] for path in paths: module = getModuleFromFile(path) if module: modules.add(module) else: files.append(path) return sorted(modules) + diff.File.eliminateCommonPrefixes(files) files_per_team = review_utils.collectReviewTeams(reviewers) teams_per_modules = {} profiler.check("shared assignments (collect teams)") for team, files in files_per_team.items(): modules = set() for file_id in files: modules.add(moduleFromFile(file_id)) teams_per_modules.setdefault(frozenset(modules), set()).update(team) for modules, team in teams_per_modules.items(): row = shared.tr("reviewers") cell = row.td("reviewers") members = sorted([dbutils.User.fromId(db, user_id).fullname for user_id in team]) for member in members: cell.text(member).br() row.td("willreview").innerHTML("<span class='also'>also</span>&nbsp;review&nbsp;changes&nbsp;in") cell = row.td("files") for path in diff.File.eliminateCommonPrefixes(sorted(modules)): cell.span("file").innerHTML(path).br() paths = textutils.json_encode(list(modules)) user_ids = textutils.json_encode(list(team)) cell = row.td("buttons") cell.button("accept", critic_paths=paths, critic_user_ids=user_ids).text("I will review this!") cell.button("deny", critic_paths=paths, critic_user_ids=user_ids).text("They will review this!") yield flush(target) profiler.check("shared assignments") cursor.execute("""SELECT batches.id, batches.time, users.fullname, comments.comment FROM batches JOIN users ON (users.id=batches.uid) LEFT OUTER JOIN commentchains ON (commentchains.id=batches.comment) LEFT OUTER JOIN comments ON (comments.id=commentchains.first_comment) WHERE batches.review=%s ORDER BY batches.id DESC""", (review.id,)) rows = cursor.fetchall() if rows: numbers = {} cursor.execute("""SELECT batches.id, reviewfilechanges.to_state, SUM(deleted), SUM(inserted) FROM batches JOIN reviewfilechanges ON (reviewfilechanges.batch=batches.id) JOIN reviewfiles ON (reviewfiles.id=reviewfilechanges.file) WHERE batches.review=%s GROUP BY batches.id, reviewfilechanges.to_state""", (review.id,)) for batch_id, state, deleted, inserted in cursor: per_batch = numbers.setdefault(batch_id, {}) per_batch[state] = (deleted, inserted) cursor.execute("""SELECT batches.id, commentchains.type, COUNT(commentchains.id) FROM batches JOIN commentchains ON (commentchains.batch=batches.id) WHERE batches.review=%s GROUP BY batches.id, commentchains.type""", (review.id,)) for batch_id, commentchain_type, count in cursor: per_batch = numbers.setdefault(batch_id, {}) per_batch[commentchain_type] = count cursor.execute("""SELECT batches.id, commentchainchanges.to_state, COUNT(commentchainchanges.chain) FROM batches JOIN commentchainchanges ON (commentchainchanges.batch=batches.id) WHERE batches.review=%s AND commentchainchanges.to_state IS NOT NULL GROUP BY batches.id, commentchainchanges.to_state""", (review.id,)) for batch_id, commentchainchange_state, count in cursor: per_batch = numbers.setdefault(batch_id, {}) per_batch[commentchainchange_state] = count cursor.execute("""SELECT batches.id, COUNT(commentchainchanges.chain) FROM batches JOIN commentchainchanges ON (commentchainchanges.batch=batches.id) WHERE batches.review=%s AND commentchainchanges.to_type IS NOT NULL GROUP BY batches.id""", (review.id,)) for batch_id, count in cursor: per_batch = numbers.setdefault(batch_id, {}) per_batch["morph"] = count cursor.execute("""SELECT batches.id, COUNT(comments.id) FROM batches JOIN commentchains ON (commentchains.batch!=batches.id) JOIN comments ON (comments.batch=batches.id AND comments.chain=commentchains.id) WHERE batches.review=%s GROUP BY batches.id""", (review.id,)) for batch_id, count in cursor: per_batch = numbers.setdefault(batch_id, {}) per_batch["reply"] = count batches = target.table("paleyellow batches", align="center", cellspacing=0) batches.tr().td("h1", colspan=3).h1().text("Work Log") def format_lines(deleted, inserted): if deleted and inserted: return "-%d/+%d" % (deleted, inserted) elif deleted: return "-%d" % deleted else: return "+%d" % inserted def with_plural(count, one, many): return (count, many if count > 1 else one) def with_plural_s(count): return with_plural(count, "", "s") for batch_id, timestamp, user_fullname, comment in rows: row = batches.tr("batch") row.td("author").text(user_fullname) title = row.td("title clickable").a( "clickable-target", href="showbatch?batch=%d" % batch_id) if comment: title.innerHTML(textutils.summarize(comment, as_html=True)) else: title.i().text("No comment") per_batch = numbers.get(batch_id) if per_batch: items = [] reviewed = per_batch.get("reviewed") if reviewed: items.append("reviewed %s lines" % format_lines(*reviewed)) unreviewed = per_batch.get("pending") if unreviewed: items.append("unreviewed %s lines" % format_lines(*unreviewed)) issues = per_batch.get("issue") if issues: items.append("raised %d issue%s" % with_plural_s(issues)) notes = per_batch.get("note") if notes: items.append("wrote %d note%s" % with_plural_s(notes)) resolved = per_batch.get("closed") if resolved: items.append("resolved %d issue%s" % with_plural_s(resolved)) reopened = per_batch.get("open") if reopened: items.append("reopened %d issue%s" % with_plural_s(reopened)) morphed = per_batch.get("morph") if morphed: items.append("morphed %d comment%s" % with_plural_s(morphed)) replies = per_batch.get("reply") if replies: items.append("wrote %d %s" % with_plural(replies, "reply", "replies")) if items: if len(items) == 1: items = items[0] else: items = "%s and %s" % (", ".join(items[:-1]), items[-1]) else: items = "nothing" title.span("numbers").text(items) row.td("when").text(user.formatTimestamp(db, timestamp)) profiler.check("batches") profiler.output(db, user, target) yield flush() try: head = review.branch.getHead(db) except gitutils.GitReferenceError: # Commit missing from repository. pass else: try: head_according_to_git = repository.revparse(review.branch.name) except gitutils.GitReferenceError: # Branch missing from repository. head_according_to_git = None head_according_to_us = head.sha1 if head_according_to_git != head_according_to_us: # The git repository disagrees with us. Potentially harmful updates # to the branch will be rejected by the git hook while this is the # case, but this means that "our" head might not be referenced at # all and thus that it might be GC:ed by the git repository at some # point. To avoid that, add a keepalive reference. repository.keepalive(head_according_to_us) yield "\n<!-- branch head mismatch: git=%s, us=%s (corrected) -->" % (head_according_to_git[:8] if head_according_to_git else "N/A", head_according_to_us[:8])
src/compas_plotters/artists/__init__.py
funkchaser/compas
235
151095
<gh_stars>100-1000 """ ******************************************************************************** compas_plotters.artists ******************************************************************************** .. currentmodule:: compas_plotters.artists Primitive Artists ================= .. autosummary:: :toctree: generated/ :nosignatures: PointArtist VectorArtist LineArtist PolylineArtist PolygonArtist CircleArtist EllipseArtist Datastructure Artists ===================== .. autosummary:: :toctree: generated/ :nosignatures: MeshArtist NetworkArtist Base Classes ============ .. autosummary:: :toctree: generated/ :nosignatures: PlotterArtist """ from compas.plugins import plugin from compas.artists import Artist from compas.geometry import Point from compas.geometry import Vector from compas.geometry import Line from compas.geometry import Polyline from compas.geometry import Polygon from compas.geometry import Circle from compas.geometry import Ellipse from compas.datastructures import Mesh from compas.datastructures import Network from .artist import PlotterArtist from .pointartist import PointArtist from .vectorartist import VectorArtist from .lineartist import LineArtist from .polylineartist import PolylineArtist from .polygonartist import PolygonArtist from .circleartist import CircleArtist from .ellipseartist import EllipseArtist from .meshartist import MeshArtist from .networkartist import NetworkArtist @plugin(category='factories', requires=['matplotlib']) def register_artists(): Artist.register(Point, PointArtist, context='Plotter') Artist.register(Vector, VectorArtist, context='Plotter') Artist.register(Line, LineArtist, context='Plotter') Artist.register(Polyline, PolylineArtist, context='Plotter') Artist.register(Polygon, PolygonArtist, context='Plotter') Artist.register(Circle, CircleArtist, context='Plotter') Artist.register(Ellipse, EllipseArtist, context='Plotter') Artist.register(Mesh, MeshArtist, context='Plotter') Artist.register(Network, NetworkArtist, context='Plotter') __all__ = [ 'PlotterArtist', 'PointArtist', 'VectorArtist', 'LineArtist', 'PolylineArtist', 'PolygonArtist', 'CircleArtist', 'EllipseArtist', 'MeshArtist', 'NetworkArtist', ]
PyEngine3D/App/SceneManager.py
ubuntunux/PyEngine3D
121
151145
<gh_stars>100-1000 import copy from collections import OrderedDict import os import glob import math import numpy as np from PyEngine3D.Common import logger from PyEngine3D.Common.Constants import * from PyEngine3D.Render import CollisionActor, StaticActor, SkeletonActor, AxisGizmo from PyEngine3D.Render import Camera, MainLight, PointLight, LightProbe from PyEngine3D.Render import gather_render_infos, always_pass, view_frustum_culling_geometry, shadow_culling from PyEngine3D.Render import Atmosphere, Ocean, Terrain from PyEngine3D.Render import Effect from PyEngine3D.Render import Spline3D from PyEngine3D.Render.RenderOptions import RenderOption from PyEngine3D.Render.RenderTarget import RenderTargets from PyEngine3D.Utilities import * class SceneManager(Singleton): def __init__(self): self.core_manager = None self.resource_manager = None self.scene_loader = None self.renderer = None self.effect_manager = None self.__current_scene_name = "" # Scene Objects self.main_camera = None self.main_light = None self.main_light_probe = None self.selected_object = None self.selected_object_transform = TransformObject() self.selected_object_id = 0 self.selected_spline_point_gizmo_id = None self.selected_spline_control_point_gizmo_id = None self.spline_control_point_gizmo_id0 = None self.spline_control_point_gizmo_id1 = None self.spline_gizmo_object_map = {} self.selected_axis_gizmo_id = None self.axis_gizmo = None # envirment object self.atmosphere = None self.ocean = None self.terrain = None self.cameras = [] self.point_lights = [] self.light_probes = [] self.collision_actors = [] self.static_actors = [] self.skeleton_actors = [] self.objectMap = {} # All of objects self.objectIDMap = {} self.objectIDEntry = list(range(2 ** 16)) self.objectIDCounter = AxisGizmo.ID_COUNT # render group self.point_light_count = 0 self.static_solid_render_infos = [] self.static_translucent_render_infos = [] self.static_shadow_render_infos = [] self.skeleton_solid_render_infos = [] self.skeleton_translucent_render_infos = [] self.skeleton_shadow_render_infos = [] self.axis_gizmo_render_infos = [] self.spline_gizmo_render_infos = [] def initialize(self, core_manager): logger.info("initialize " + GetClassName(self)) self.core_manager = core_manager self.resource_manager = core_manager.resource_manager self.scene_loader = self.resource_manager.scene_loader self.renderer = core_manager.renderer self.effect_manager = core_manager.effect_manager self.axis_gizmo = AxisGizmo(name='axis_gizmo', model=self.resource_manager.get_model('axis_gizmo')) def get_current_scene_name(self): return self.__current_scene_name def set_current_scene_name(self, scene_name): self.__current_scene_name = scene_name self.core_manager.set_window_title(scene_name) def clear_scene(self): self.core_manager.notify_clear_scene() self.clear_selected_object() self.clear_spline_gizmo() self.clear_selected_axis_gizmo_id() self.effect_manager.clear() self.main_camera = None self.main_light = None self.main_light_probe = None self.selected_object = None self.selected_object_id = 0 self.selected_axis_gizmo_id = None self.cameras = [] self.point_lights = [] self.light_probes = [] self.collision_actors = [] self.static_actors = [] self.skeleton_actors = [] self.splines = [] self.objectMap = {} self.objectIDMap = {} self.objectIDEntry = list(range(2 ** 16)) self.static_solid_render_infos = [] self.static_translucent_render_infos = [] self.static_shadow_render_infos = [] self.skeleton_solid_render_infos = [] self.skeleton_translucent_render_infos = [] self.skeleton_shadow_render_infos = [] self.selected_object_render_info = [] self.spline_gizmo_render_infos = [] self.renderer.set_debug_texture(None) def begin_open_scene(self): self.clear_scene() def end_open_scene(self): self.update_scene(0.0) self.renderer.reset_renderer() self.regist_object(self.renderer.postprocess) # Important : update camera projection for camera in self.cameras: camera.update() def new_scene(self): self.begin_open_scene() # add scene objects self.main_camera = self.add_camera() self.main_light = self.add_main_light() self.main_light_probe = self.add_light_probe(pos=[0.0, 5.0, 0.0]) self.atmosphere = self.add_atmosphere() self.ocean = self.add_ocean() self.terrain = self.add_terrain() self.set_current_scene_name(self.resource_manager.scene_loader.get_new_resource_name("new_scene")) logger.info("New scene : %s" % self.__current_scene_name) scene_data = self.get_save_data() self.resource_manager.scene_loader.create_resource(self.__current_scene_name, scene_data) self.end_open_scene() def open_scene(self, scene_name, scene_data): self.begin_open_scene() self.set_current_scene_name(scene_name) logger.info("Open scene : %s" % scene_name) camera_datas = scene_data.get('cameras', []) for camera_data in camera_datas: self.add_camera(**camera_data) self.main_camera = self.cameras[0] if 0 < len(self.cameras) else None main_light_data = scene_data.get('main_light', None) if main_light_data is not None: self.main_light = self.add_main_light(**main_light_data) else: self.main_light = self.add_main_light() light_datas = scene_data.get('lights', []) for light_data in light_datas: self.add_light(**light_data) light_probe_datas = scene_data.get('light_probes', []) if light_probe_datas: for light_probe_data in light_probe_datas: self.add_light_probe(**light_probe_data) else: self.add_light_probe() self.main_light_probe = self.light_probes[0] if 0 < len(self.light_probes) else None spline_datas = scene_data.get('splines', []) for spline_data in spline_datas: self.add_spline(**spline_data) atmosphere_data = scene_data.get('atmosphere', {}) self.atmosphere = self.add_atmosphere(**atmosphere_data) ocean_data = scene_data.get('ocean', {}) self.ocean = self.add_ocean(**ocean_data) terrain_data = scene_data.get('terrain', {}) self.terrain = self.add_terrain(**terrain_data) for collision_data in scene_data.get('collision_actors', []): self.add_collision(**collision_data) for object_data in scene_data.get('static_actors', []): self.add_object(**object_data) for object_data in scene_data.get('skeleton_actors', []): self.add_object(**object_data) for effect_data in scene_data.get('effects', []): self.add_effect(**effect_data) self.end_open_scene() def save_scene(self): if self.__current_scene_name == "": self.set_current_scene_name(self.resource_manager.scene_loader.get_new_resource_name("new_scene")) self.resource_manager.scene_loader.save_resource(self.__current_scene_name) def get_save_data(self): scene_data = dict( cameras=[camera.get_save_data() for camera in self.cameras], main_light=self.main_light.get_save_data() if self.main_light is not None else dict(), lights=[light.get_save_data() for light in self.point_lights], light_probes=[light_probe.get_save_data() for light_probe in self.light_probes], splines=[spline.get_save_data() for spline in self.splines], atmosphere=self.atmosphere.get_save_data(), ocean=self.ocean.get_save_data(), terrain=self.terrain.get_save_data(), collision_actors=[collision_actor.get_save_data() for collision_actor in self.collision_actors], static_actors=[static_actor.get_save_data() for static_actor in self.static_actors], skeleton_actors=[skeleton_actor.get_save_data() for skeleton_actor in self.skeleton_actors], effects=self.effect_manager.get_save_data() ) return scene_data def generate_object_name(self, currName): index = 0 if currName in self.objectMap: while True: newName = "%s_%d" % (currName, index) if newName not in self.objectMap: return newName index += 1 return currName def get_object_list(self, object_type): if Camera == object_type: return self.cameras elif PointLight == object_type: return self.point_lights elif LightProbe == object_type: return self.light_probes elif CollisionActor == object_type: return self.collision_actors elif StaticActor == object_type: return self.static_actors elif SkeletonActor == object_type: return self.skeleton_actors elif Spline3D == object_type: return self.splines return None def generate_object_id(self): object_id = self.objectIDEntry[self.objectIDCounter] self.objectIDCounter += 1 return object_id def restore_object_id(self, object_id): if 0 < self.objectIDCounter: self.objectIDCounter -= 1 self.objectIDEntry[self.objectIDCounter] = object_id def regist_object(self, obj): if obj is not None and obj.name not in self.objectMap: object_type = type(obj) object_list = self.get_object_list(object_type) if object_list is not None: object_list.append(obj) elif object_type is Effect: self.effect_manager.add_effect(obj) if hasattr(obj, 'set_object_id'): object_id = self.generate_object_id() obj.set_object_id(object_id) self.objectIDMap[object_id] = obj self.objectMap[obj.name] = obj self.core_manager.send_object_info(obj) else: logger.error("SceneManager::regist_object error. %s" % obj.name if obj else 'None') def unregist_resource(self, obj): if obj is not None and obj.name in self.objectMap: object_type = type(obj) object_list = self.get_object_list(object_type) if object_list is not None: object_list.remove(obj) elif object_type is Effect: self.effect_manager.delete_effect(obj) self.objectMap.pop(obj.name) if hasattr(obj, 'get_object_id'): object_id = obj.get_object_id() self.restore_object_id(object_id) if AxisGizmo.ID_COUNT <= object_id: self.objectIDMap.pop(object_id) self.core_manager.notify_delete_object(obj.name) if self.selected_object is obj and hasattr(self.selected_object, "set_selected"): obj.set_selected(False) self.selected_object = None if hasattr(obj, 'delete'): obj.delete() else: logger.error("SceneManager::unregist_resource error. %s" % obj.name if obj else 'None') def add_camera(self, **camera_data): name = self.generate_object_name(camera_data.get('name', 'camera')) camera_data['name'] = name camera_data['model'] = self.resource_manager.get_model('Cube') logger.info("add Camera : %s" % name) camera = Camera(scene_manager=self, **camera_data) camera.initialize() self.regist_object(camera) return camera def add_main_light(self, **light_data): name = self.generate_object_name(light_data.get('name', 'main_light')) light_data['name'] = name light_data['model'] = self.resource_manager.get_model('Cube') logger.info("add MainLight : %s" % name) light = MainLight(**light_data) self.regist_object(light) return light def add_light(self, **light_data): name = self.generate_object_name(light_data.get('name', 'light')) light_data['name'] = name light_data['model'] = self.resource_manager.get_model('Cube') logger.info("add Light : %s" % name) light = PointLight(**light_data) self.regist_object(light) return light def add_light_probe(self, **light_probe_data): name = self.generate_object_name(light_probe_data.get('name', 'light_probe')) light_probe_data['name'] = name light_probe_data['model'] = self.resource_manager.get_model('Cube') logger.info("add Light Probe : %s" % name) light_probe = LightProbe(**light_probe_data) self.regist_object(light_probe) return light_probe def add_spline_here(self, **spline_data): spline_data['pos'] = self.main_camera.transform.pos - self.main_camera.transform.front * 10.0 self.add_spline(**spline_data) def add_spline(self, **spline_data): name = self.generate_object_name(spline_data.get('name', 'spline')) spline_data['name'] = name spline_data['spline_data'] = self.resource_manager.get_spline(spline_data.get('spline_data', '')) logger.info("add Spline : %s" % name) spline = Spline3D(**spline_data) self.regist_object(spline) return spline def create_spline_gizmo(self, spline): spline_point_name = spline.name + '_point' control_point_name = spline.name + '_control_point' gizmo_model = self.resource_manager.get_model('Cube') if len(spline.spline_data.spline_points) < 1: return for spline_point in spline.spline_data.spline_points: pos = np.dot(Float4(*spline_point.position, 1.0), spline.transform.matrix)[:3] gizmo_object = StaticActor(name=spline_point_name, model=gizmo_model, pos=Float3(*pos), scale=Float3(0.1, 0.1, 0.1), object_id=self.generate_object_id(), object_color=Float3(0.5, 0.5, 1.0)) self.spline_gizmo_object_map[gizmo_object.get_object_id()] = gizmo_object spline_point = spline.spline_data.spline_points[0] def create_spline_control_point_gizmo(spline_gizmo_object_map, object_id, inverse): if inverse: pos = np.dot(Float4(*(spline_point.position + spline_point.control_point), 1.0), spline.transform.matrix)[:3] else: pos = np.dot(Float4(*(spline_point.position - spline_point.control_point), 1.0), spline.transform.matrix)[:3] gizmo_object = StaticActor(name=control_point_name, model=gizmo_model, pos=Float3(*pos), scale=Float3(0.075, 0.075, 0.075), object_id=object_id, object_color=Float3(0.0, 1.0, 0.0)) spline_gizmo_object_map[gizmo_object.get_object_id()] = gizmo_object return gizmo_object.get_object_id() self.spline_control_point_gizmo_id0 = create_spline_control_point_gizmo(self.spline_gizmo_object_map, self.generate_object_id(), inverse=False) self.spline_control_point_gizmo_id1 = create_spline_control_point_gizmo(self.spline_gizmo_object_map, self.generate_object_id(), inverse=True) # select first spline gizmo object # self.set_selected_spline_gizmo_id(list(self.spline_gizmo_object_map.keys())[0]) gather_render_infos(culling_func=always_pass, camera=self.main_camera, light=self.main_light, actor_list=self.spline_gizmo_object_map.values(), solid_render_infos=self.spline_gizmo_render_infos, translucent_render_infos=None) def set_selected_spline_gizmo_id(self, spline_gizmo_id): if spline_gizmo_id == self.spline_control_point_gizmo_id0 or spline_gizmo_id == self.spline_control_point_gizmo_id1: self.selected_spline_control_point_gizmo_id = spline_gizmo_id else: self.selected_spline_control_point_gizmo_id = None self.selected_spline_point_gizmo_id = spline_gizmo_id def clear_spline_gizmo(self): self.selected_spline_point_gizmo_id = None self.selected_spline_control_point_gizmo_id = None self.spline_control_point_gizmo_id0 = None self.spline_control_point_gizmo_id1 = None for spline_gizmo_object_id in self.spline_gizmo_object_map: self.restore_object_id(self.spline_gizmo_object_map[spline_gizmo_object_id].get_object_id()) self.spline_gizmo_object_map.clear() self.spline_gizmo_render_infos.clear() def clear_selected_axis_gizmo_id(self): self.selected_axis_gizmo_id = None def is_axis_gizmo_drag(self): return self.selected_axis_gizmo_id is not None def add_effect_here(self, **effect_data): effect_data['pos'] = self.main_camera.transform.pos - self.main_camera.transform.front * 10.0 self.add_effect(**effect_data) def add_effect(self, **effect_data): name = self.generate_object_name(effect_data.get('name', 'effect')) logger.info("add Particle : %s" % name) effect_data['name'] = name effect_data['effect_info'] = self.resource_manager.get_effect(effect_data.get('effect_info', '')) effect = Effect(**effect_data) self.regist_object(effect) return effect def add_atmosphere(self, **atmosphere_data): atmosphere_data['name'] = self.generate_object_name(atmosphere_data.get('name', 'atmosphere')) logger.info("add Atmosphere : %s" % atmosphere_data['name']) atmosphere = Atmosphere(**atmosphere_data) if not self.core_manager.is_basic_mode: atmosphere.initialize() self.regist_object(atmosphere) return atmosphere def add_ocean(self, **object_data): object_data['name'] = self.generate_object_name(object_data.get('name', 'ocean')) logger.info("add Ocean : %s" % object_data['name']) ocean = Ocean(**object_data) if not self.core_manager.is_basic_mode: ocean.initialize() self.regist_object(ocean) return ocean def add_terrain(self, **object_data): object_data['name'] = self.generate_object_name(object_data.get('name', 'terrain')) logger.info("add Terrain : %s" % object_data['name']) terrain = Terrain(**object_data) if not self.core_manager.is_basic_mode: terrain.initialize() self.regist_object(terrain) return terrain def add_object(self, **object_data): model = object_data.get('model') if model: object_data['name'] = self.generate_object_name(object_data.get('name', model.name)) objType = GetClassName(model) logger.info("add %s : %s" % (objType, object_data['name'])) if model.mesh and model.mesh.has_bone(): obj_instance = SkeletonActor(**object_data) else: obj_instance = StaticActor(**object_data) # regist self.regist_object(obj_instance) return obj_instance return None def add_object_here(self, model): pos = self.main_camera.transform.pos - self.main_camera.transform.front * 10.0 return self.add_object(model=model, pos=pos) def add_collision(self, **collision_data): name = self.generate_object_name(collision_data.get('name', 'collision')) mesh = self.resource_manager.get_model(collision_data.get('model')) if mesh is not None: collision_data['name'] = name collision_data['model'] = mesh logger.info("add Collision : %s" % name) collision = CollisionActor(**collision_data) self.regist_object(collision) return collision return None def clear_objects(self): self.cameras = [] self.point_lights = [] self.collision_actors = [] self.static_actors = [] self.skeleton_actors = [] self.splines = [] self.objectMap = {} def clear_actors(self): for obj_name in list(self.objectMap.keys()): self.delete_object(obj_name) def action_object(self, object_name): obj = self.get_object(object_name) if obj is not None: object_type = type(obj) if LightProbe == object_type: self.renderer.set_debug_texture(obj.texture_probe) self.core_manager.send_object_attribute(obj.texture_probe.get_attribute()) def delete_object(self, object_name): obj = self.get_object(object_name) logger.info("delete %s : %s" % (type(obj), object_name)) if obj is not None and obj not in (self.main_camera, self.main_light, self.main_light_probe): self.unregist_resource(obj) def get_axis_gizmo(self): return self.axis_gizmo def get_object(self, object_name): return self.objectMap.get(object_name) def get_object_names(self): return self.objectMap.keys() def get_objects(self): return self.objectMap.values() def get_light_probe_texture(self): if RenderOption.RENDER_LIGHT_PROBE: return RenderTargets.LIGHT_PROBE_ATMOSPHERE return self.main_light_probe.texture_probe def reset_light_probe(self): for light_probe in self.light_probes: light_probe.isRendered = False def get_object_attribute(self, object_name, objectTypeName): obj = self.get_object(object_name) return obj.get_attribute() if obj else None def set_object_attribute(self, object_name, objectTypeName, attribute_name, attribute_value, item_info_history, attribute_index): obj = self.get_object(object_name) obj and obj.set_attribute(attribute_name, attribute_value, item_info_history, attribute_index) def get_selected_object_id(self): return self.selected_object_id def set_selected_object_id(self, object_id): self.selected_object_id = object_id def clear_selected_object(self): self.selected_object = None self.selected_object_id = 0 def get_selected_object(self): return self.selected_object def set_selected_object(self, object_name): selected_object = self.get_object(object_name) if self.selected_object is not selected_object: self.clear_selected_axis_gizmo_id() self.clear_spline_gizmo() self.selected_object_render_info = [] if self.selected_object and hasattr(self.selected_object, "set_selected"): self.selected_object.set_selected(False) # set selected object self.selected_object = selected_object if selected_object is not None: if hasattr(selected_object, "get_object_id"): self.set_selected_object_id(selected_object.get_object_id()) if hasattr(selected_object, "set_selected"): selected_object.set_selected(True) if type(selected_object) in (SkeletonActor, StaticActor): gather_render_infos(culling_func=always_pass, camera=self.main_camera, light=self.main_light, actor_list=[self.selected_object, ], solid_render_infos=self.selected_object_render_info, translucent_render_infos=self.selected_object_render_info) elif type(selected_object) is Spline3D: self.create_spline_gizmo(selected_object) def backup_selected_object_transform(self): if self.selected_object and hasattr(self.selected_object, "transform"): self.selected_object_transform.clone(self.selected_object.transform) def restore_selected_object_transform(self): if self.selected_object and hasattr(self.selected_object, "transform"): self.selected_object.transform.clone(self.selected_object_transform) def edit_selected_object_transform(self): selected_spline_control_point_gizmo_object = self.spline_gizmo_object_map.get(self.selected_spline_control_point_gizmo_id) selected_spline_point_gizmo_object = self.spline_gizmo_object_map.get(self.selected_spline_point_gizmo_id) edit_object = selected_spline_control_point_gizmo_object or selected_spline_point_gizmo_object or self.selected_object if edit_object is None: return mouse_delta = self.core_manager.game_backend.mouse_delta if any(0.0 != mouse_delta): mouse_pos = self.core_manager.game_backend.mouse_pos mouse_pos_old = self.core_manager.game_backend.mouse_pos_old camera = self.main_camera camera_transform = camera.transform screen_width = self.core_manager.viewport_manager.main_viewport.width screen_height = self.core_manager.viewport_manager.main_viewport.height edit_object_transform = edit_object.transform use_quaternion = False mouse_x_ratio = mouse_pos[0] / screen_width mouse_y_ratio = mouse_pos[1] / screen_height mouse_x_ratio_old = mouse_pos_old[0] / screen_width mouse_y_ratio_old = mouse_pos_old[1] / screen_height mouse_world_pos = np.dot(Float4(mouse_x_ratio * 2.0 - 1.0, mouse_y_ratio * 2.0 - 1.0, 0.0, 1.0), camera.inv_view_origin_projection) mouse_world_pos_old = np.dot(Float4(mouse_x_ratio_old * 2.0 - 1.0, mouse_y_ratio_old * 2.0 - 1.0, 0.0, 1.0), camera.inv_view_origin_projection) to_object = edit_object_transform.get_pos() - camera_transform.get_pos() to_object_xz_dist = length(Float2(to_object[0], to_object[2])) mouse_xz_dist = length(Float2(mouse_world_pos[0], mouse_world_pos[2])) mouse_xz_dist_old = length(Float2(mouse_world_pos_old[0], mouse_world_pos_old[2])) if AxisGizmo.ID_POSITION_X == self.selected_axis_gizmo_id: edit_object_transform.move_x((mouse_world_pos[0] * to_object[2] / mouse_world_pos[2]) - (mouse_world_pos_old[0] * to_object[2] / mouse_world_pos_old[2])) elif AxisGizmo.ID_POSITION_Y == self.selected_axis_gizmo_id: edit_object_transform.move_y((mouse_world_pos[1] * to_object_xz_dist / mouse_xz_dist) - (mouse_world_pos_old[1] * to_object_xz_dist / mouse_xz_dist_old)) elif AxisGizmo.ID_POSITION_Z == self.selected_axis_gizmo_id: edit_object_transform.move_z((mouse_world_pos[2] * to_object[0] / mouse_world_pos[0]) - (mouse_world_pos_old[2] * to_object[0] / mouse_world_pos_old[0])) elif AxisGizmo.ID_POSITION_XY == self.selected_axis_gizmo_id: edit_object_transform.move_x((mouse_world_pos[0] * to_object[2] / mouse_world_pos[2]) - (mouse_world_pos_old[0] * to_object[2] / mouse_world_pos_old[2])) edit_object_transform.move_y((mouse_world_pos[1] * to_object_xz_dist / mouse_xz_dist) - (mouse_world_pos_old[1] * to_object_xz_dist / mouse_xz_dist_old)) elif AxisGizmo.ID_POSITION_XZ == self.selected_axis_gizmo_id: edit_object_transform.move_x((mouse_world_pos[0] * to_object[1] / mouse_world_pos[1]) - (mouse_world_pos_old[0] * to_object[1] / mouse_world_pos_old[1])) edit_object_transform.move_z((mouse_world_pos[2] * to_object[1] / mouse_world_pos[1]) - (mouse_world_pos_old[2] * to_object[1] / mouse_world_pos_old[1])) elif AxisGizmo.ID_POSITION_YZ == self.selected_axis_gizmo_id: edit_object_transform.move_y((mouse_world_pos[1] * to_object_xz_dist / mouse_xz_dist) - (mouse_world_pos_old[1] * to_object_xz_dist / mouse_xz_dist_old)) edit_object_transform.move_z((mouse_world_pos[2] * to_object[0] / mouse_world_pos[0]) - (mouse_world_pos_old[2] * to_object[0] / mouse_world_pos_old[0])) elif AxisGizmo.ID_ROTATION_PITCH == self.selected_axis_gizmo_id: yz = Float2(mouse_world_pos[1] * to_object[0] / mouse_world_pos[0], mouse_world_pos[2] * to_object[0] / mouse_world_pos[0]) - Float2(to_object[1], to_object[2]) yz_old = Float2(mouse_world_pos_old[1] * to_object[0] / mouse_world_pos_old[0], mouse_world_pos_old[2] * to_object[0] / mouse_world_pos_old[0]) - Float2(to_object[1], to_object[2]) if use_quaternion: quat = axis_rotation(edit_object_transform.left, math.atan2(yz[1], yz[0]) - math.atan2(yz_old[1], yz_old[0])) edit_object_transform.multiply_quaternion(quat) else: edit_object_transform.rotation_pitch(math.atan2(yz[1], yz[0]) - math.atan2(yz_old[1], yz_old[0])) elif AxisGizmo.ID_ROTATION_YAW == self.selected_axis_gizmo_id: xz = Float2(mouse_world_pos[0] * to_object[1] / mouse_world_pos[1], mouse_world_pos[2] * to_object[1] / mouse_world_pos[1]) - Float2(to_object[0], to_object[2]) xz_old = Float2(mouse_world_pos_old[0] * to_object[1] / mouse_world_pos_old[1], mouse_world_pos_old[2] * to_object[1] / mouse_world_pos_old[1]) - Float2(to_object[0], to_object[2]) if use_quaternion: quat = axis_rotation(edit_object_transform.up, math.atan2(xz_old[1], xz_old[0]) - math.atan2(xz[1], xz[0])) edit_object_transform.multiply_quaternion(quat) else: edit_object_transform.rotation_yaw(math.atan2(xz_old[1], xz_old[0]) - math.atan2(xz[1], xz[0])) elif AxisGizmo.ID_ROTATION_ROLL == self.selected_axis_gizmo_id: xy = Float2(mouse_world_pos[0] * to_object[2] / mouse_world_pos[2], mouse_world_pos[1] * to_object[2] / mouse_world_pos[2]) - Float2(to_object[0], to_object[1]) xy_old = Float2(mouse_world_pos_old[0] * to_object[2] / mouse_world_pos_old[2], mouse_world_pos_old[1] * to_object[2] / mouse_world_pos_old[2]) - Float2(to_object[0], to_object[1]) if use_quaternion: quat = axis_rotation(edit_object_transform.front, math.atan2(xy[1], xy[0]) - math.atan2(xy_old[1], xy_old[0])) edit_object_transform.multiply_quaternion(quat) else: edit_object_transform.rotation_roll(math.atan2(xy[1], xy[0]) - math.atan2(xy_old[1], xy_old[0])) elif AxisGizmo.ID_SCALE_X == self.selected_axis_gizmo_id: edit_object_transform.scale_x(((mouse_world_pos[0] * to_object[2] / mouse_world_pos[2]) - (mouse_world_pos_old[0] * to_object[2] / mouse_world_pos_old[2]))) elif AxisGizmo.ID_SCALE_Y == self.selected_axis_gizmo_id: edit_object_transform.scale_y((mouse_world_pos[1] * to_object_xz_dist / mouse_xz_dist) - (mouse_world_pos_old[1] * to_object_xz_dist / mouse_xz_dist_old)) elif AxisGizmo.ID_SCALE_Z == self.selected_axis_gizmo_id: edit_object_transform.scale_z((mouse_world_pos[2] * to_object[0] / mouse_world_pos[0]) - (mouse_world_pos_old[2] * to_object[0] / mouse_world_pos_old[0])) else: d0 = np.dot(-camera_transform.front, to_object) d1 = np.dot(-camera_transform.front, mouse_world_pos[0:3]) pos = (mouse_world_pos[0:3] / d1 * d0) - to_object edit_object_transform.move(pos) # update_spline_gizmo_object if selected_spline_point_gizmo_object is not None and self.selected_object is not None: spline_index = list(self.spline_gizmo_object_map).index(self.selected_spline_point_gizmo_id) spline_point = self.selected_object.spline_data.spline_points[spline_index] spline_point_gizmo_pos = np.dot(Float4(*selected_spline_point_gizmo_object.transform.get_pos(), 1.0), self.selected_object.transform.inverse_matrix)[:3] spline_point.position[...] = spline_point_gizmo_pos if selected_spline_control_point_gizmo_object is not None: spline_control_point_gizmo_pos = np.dot(Float4(*selected_spline_control_point_gizmo_object.transform.get_pos(), 1.0), self.selected_object.transform.inverse_matrix)[:3] if self.spline_control_point_gizmo_id0 == self.selected_spline_control_point_gizmo_id: spline_point.control_point[...] = spline_point_gizmo_pos - spline_control_point_gizmo_pos elif self.spline_control_point_gizmo_id1 == self.selected_spline_control_point_gizmo_id: spline_point.control_point[...] = spline_control_point_gizmo_pos - spline_point_gizmo_pos self.selected_object.spline_data.resampling() def update_select_object_id(self): windows_size = self.core_manager.get_window_size() mouse_pos = self.core_manager.get_mouse_pos() x = math.floor(min(1.0, (mouse_pos[0] / windows_size[0])) * (RenderTargets.OBJECT_ID.width - 1)) y = math.floor(min(1.0, (mouse_pos[1] / windows_size[1])) * (RenderTargets.OBJECT_ID.height - 1)) object_ids = RenderTargets.OBJECT_ID.get_image_data() object_id = math.floor(object_ids[y][x] + 0.5) return object_id def intersect_select_object(self): object_id = self.update_select_object_id() if 0 < object_id: if object_id < AxisGizmo.ID_COUNT: self.selected_axis_gizmo_id = object_id elif object_id in self.spline_gizmo_object_map: self.set_selected_spline_gizmo_id(object_id) else: obj = self.objectIDMap.get(object_id) if obj is not None: self.set_selected_object(obj.name) else: self.set_selected_object("") def set_object_focus(self, object_name): obj = self.get_object(object_name) if obj and obj != self.main_camera: self.main_camera.transform.set_pos(obj.transform.pos - self.main_camera.transform.front * 2.0) def update_camera_projection_matrix(self, fov=0.0, aspect=0.0): for camera in self.cameras: camera.update_projection(fov, aspect) def update_static_render_info(self): self.static_solid_render_infos = [] self.static_translucent_render_infos = [] self.static_shadow_render_infos = [] if RenderOption.RENDER_COLLISION: gather_render_infos(culling_func=view_frustum_culling_geometry, camera=self.main_camera, light=self.main_light, actor_list=self.collision_actors, solid_render_infos=self.static_solid_render_infos, translucent_render_infos=self.static_translucent_render_infos) if RenderOption.RENDER_STATIC_ACTOR: gather_render_infos(culling_func=view_frustum_culling_geometry, camera=self.main_camera, light=self.main_light, actor_list=self.static_actors, solid_render_infos=self.static_solid_render_infos, translucent_render_infos=self.static_translucent_render_infos) gather_render_infos(culling_func=shadow_culling, camera=self.main_camera, light=self.main_light, actor_list=self.static_actors, solid_render_infos=self.static_shadow_render_infos, translucent_render_infos=None) self.static_solid_render_infos.sort(key=lambda x: (id(x.geometry), id(x.material))) self.static_translucent_render_infos.sort(key=lambda x: (id(x.geometry), id(x.material))) def update_skeleton_render_info(self): self.skeleton_solid_render_infos = [] self.skeleton_translucent_render_infos = [] self.skeleton_shadow_render_infos = [] if RenderOption.RENDER_SKELETON_ACTOR: gather_render_infos(culling_func=view_frustum_culling_geometry, camera=self.main_camera, light=self.main_light, actor_list=self.skeleton_actors, solid_render_infos=self.skeleton_solid_render_infos, translucent_render_infos=self.skeleton_translucent_render_infos) gather_render_infos(culling_func=shadow_culling, camera=self.main_camera, light=self.main_light, actor_list=self.skeleton_actors, solid_render_infos=self.skeleton_shadow_render_infos, translucent_render_infos=None) self.skeleton_solid_render_infos.sort(key=lambda x: (id(x.geometry), id(x.material))) self.skeleton_translucent_render_infos.sort(key=lambda x: (id(x.geometry), id(x.material))) def update_light_render_infos(self): self.point_light_count = 0 self.renderer.uniform_point_light_data.fill(0.0) for point_light in self.point_lights: to_light = point_light.transform.pos - self.main_camera.transform.pos for i in range(4): d = np.dot(self.main_camera.frustum_vectors[i], to_light) if point_light.light_radius < d: # culling break else: # pass culling point_light_uniform_block = self.renderer.uniform_point_light_data[self.point_light_count] point_light_uniform_block['color'] = point_light.light_color point_light_uniform_block['radius'] = point_light.light_radius point_light_uniform_block['pos'] = point_light.transform.pos point_light_uniform_block['render'] = 1.0 self.point_light_count += 1 if MAX_POINT_LIGHTS <= self.point_light_count: break def update_scene(self, dt): if not self.core_manager.is_basic_mode: self.renderer.postprocess.update() for camera in self.cameras: camera.update() if self.main_light is not None: self.main_light.update(self.main_camera) if self.main_light.changed: self.main_light.reset_changed() self.reset_light_probe() for light in self.point_lights: light.update() for collision_actor in self.collision_actors: collision_actor.update(dt) for static_actor in self.static_actors: static_actor.update(dt) for skeleton_actor in self.skeleton_actors: skeleton_actor.update(dt) for spline in self.splines: spline.update(dt) if not self.core_manager.is_basic_mode: self.atmosphere.update(self.main_light) self.ocean.update(dt) if self.terrain.is_render_terrain: self.terrain.update(dt) self.effect_manager.update(dt) # culling self.update_static_render_info() self.update_skeleton_render_info() self.update_light_render_infos() if self.selected_object is not None and hasattr(self.selected_object, 'transform'): # update spline gizmo objects spline_point_gizmo_object = self.spline_gizmo_object_map.get(self.selected_spline_point_gizmo_id) if 0 < len(self.spline_gizmo_object_map): spline_gizmo_position = Float3(0.0, 0.0, 0.0) for spline_gizmo_object_id in self.spline_gizmo_object_map: spline_gizmo_object = self.spline_gizmo_object_map[spline_gizmo_object_id] # spline control point gizmo if spline_gizmo_object_id in (self.spline_control_point_gizmo_id0, self.spline_control_point_gizmo_id1): if self.selected_spline_point_gizmo_id is not None: spline_gizmo_object.visible = True spline_index = list(self.spline_gizmo_object_map).index(self.selected_spline_point_gizmo_id) spline_point = self.selected_object.spline_data.spline_points[spline_index] if spline_gizmo_object_id == self.spline_control_point_gizmo_id0: spline_gizmo_position[...] = spline_point.position - spline_point.control_point elif spline_gizmo_object_id == self.spline_control_point_gizmo_id1: spline_gizmo_position[...] = spline_point.position + spline_point.control_point else: spline_gizmo_object.visible = False else: # spline point gizmo spline_index = list(self.spline_gizmo_object_map).index(spline_gizmo_object_id) spline_point = self.selected_object.spline_data.spline_points[spline_index] spline_gizmo_position[...] = spline_point.position spline_gizmo_object.transform.set_pos(np.dot(Float4(*spline_gizmo_position, 1.0), self.selected_object.transform.matrix)[:3]) spline_gizmo_object.update(dt) spline_control_point_gizmo_object0 = self.spline_gizmo_object_map.get(self.spline_control_point_gizmo_id0) spline_control_point_gizmo_object1 = self.spline_gizmo_object_map.get(self.spline_control_point_gizmo_id1) if spline_point_gizmo_object is not None and spline_control_point_gizmo_object0 is not None and spline_control_point_gizmo_object1 is not None: self.renderer.debug_line_manager.draw_debug_line_3d(spline_point_gizmo_object.get_pos(), spline_control_point_gizmo_object0.get_pos(), Float4(0.0, 1.0, 0.0, 1.0), width=3.0) self.renderer.debug_line_manager.draw_debug_line_3d(spline_point_gizmo_object.get_pos(), spline_control_point_gizmo_object1.get_pos(), Float4(0.0, 1.0, 0.0, 1.0), width=3.0) # update axis gizmo transform spline_control_point_gizmo_object = self.spline_gizmo_object_map.get(self.selected_spline_control_point_gizmo_id) axis_gizmo_object = spline_control_point_gizmo_object or spline_point_gizmo_object or self.selected_object axis_gizmo_pos = axis_gizmo_object.transform.get_pos() self.axis_gizmo.transform.set_pos(axis_gizmo_pos) self.axis_gizmo.transform.set_scale(length(axis_gizmo_pos - self.main_camera.transform.get_pos()) * 0.15) self.axis_gizmo.update(dt)
libraries/botframework-streaming/tests/test_header_serializer.py
andreikop/botbuilder-python
388
151171
<filename>libraries/botframework-streaming/tests/test_header_serializer.py from typing import List from unittest import TestCase from uuid import uuid4, UUID import pytest from botframework.streaming.payloads import HeaderSerializer from botframework.streaming.payloads.models import Header, PayloadTypes from botframework.streaming.transport import TransportConstants class TestHeaderSerializer(TestCase): def test_can_round_trip(self): header = Header() header.type = PayloadTypes.REQUEST header.payload_length = 168 header.id = uuid4() header.end = True buffer: List[int] = [None] * TransportConstants.MAX_PAYLOAD_LENGTH offset: int = 0 length = HeaderSerializer.serialize(header, buffer, offset) result = HeaderSerializer.deserialize(buffer, 0, length) self.assertEqual(header.type, result.type) self.assertEqual(header.payload_length, result.payload_length) self.assertEqual(header.id, result.id) self.assertEqual(header.end, result.end) def test_serializes_to_ascii(self): header = Header() header.type = PayloadTypes.REQUEST header.payload_length = 168 header.id = uuid4() header.end = True buffer: List[int] = [None] * TransportConstants.MAX_PAYLOAD_LENGTH offset: int = 0 length = HeaderSerializer.serialize(header, buffer, offset) decoded = bytes(buffer[offset:length]).decode("ascii") self.assertEqual(f"A.000168.{str(header.id)}.1\n", decoded) def test_deserializes_from_ascii(self): header_id: UUID = uuid4() header: str = f"A.000168.{str(header_id)}.1\n" buffer: List[int] = list(bytes(header, "ascii")) result = HeaderSerializer.deserialize(buffer, 0, len(buffer)) self.assertEqual("A", result.type) self.assertEqual(168, result.payload_length) self.assertEqual(header_id, result.id) self.assertTrue(result.end) def test_deserialize_unknown_type(self): header_id: UUID = uuid4() header: str = f"Z.000168.{str(header_id)}.1\n" buffer: List[int] = list(bytes(header, "ascii")) result = HeaderSerializer.deserialize(buffer, 0, len(buffer)) self.assertEqual("Z", result.type) self.assertEqual(168, result.payload_length) def test_deserialize_length_too_short_throws(self): header_id: UUID = uuid4() header: str = f"A.000168.{str(header_id)}.1\n" buffer: List[int] = list(bytes(header, "ascii")) with pytest.raises(ValueError): HeaderSerializer.deserialize(buffer, 0, 5) def test_deserialize_length_too_long_throws(self): header_id: UUID = uuid4() header: str = f"A.000168.{str(header_id)}.1\n" buffer: List[int] = list(bytes(header, "ascii")) with pytest.raises(ValueError): HeaderSerializer.deserialize(buffer, 0, 55) def test_deserialize_bad_type_delimiter_throws(self): header_id: UUID = uuid4() header: str = f"Ax000168.{str(header_id)}.1\n" buffer: List[int] = list(bytes(header, "ascii")) with pytest.raises(ValueError): HeaderSerializer.deserialize(buffer, 0, len(buffer)) def test_deserialize_bad_length_delimiter_throws(self): header_id: UUID = uuid4() header: str = f"A.000168x{str(header_id)}.1\n" buffer: List[int] = list(bytes(header, "ascii")) with pytest.raises(ValueError): HeaderSerializer.deserialize(buffer, 0, len(buffer)) def test_deserialize_bad_id_delimiter_throws(self): header_id: UUID = uuid4() header: str = f"A.000168.{str(header_id)}x1\n" buffer: List[int] = list(bytes(header, "ascii")) with pytest.raises(ValueError): HeaderSerializer.deserialize(buffer, 0, len(buffer)) def test_deserialize_bad_terminator_throws(self): header_id: UUID = uuid4() header: str = f"A.000168.{str(header_id)}.1c" buffer: List[int] = list(bytes(header, "ascii")) with pytest.raises(ValueError): HeaderSerializer.deserialize(buffer, 0, len(buffer)) def test_deserialize_bad_length_throws(self): header_id: UUID = uuid4() header: str = f"A.00p168.{str(header_id)}.1\n" buffer: List[int] = list(bytes(header, "ascii")) with pytest.raises(ValueError): HeaderSerializer.deserialize(buffer, 0, len(buffer)) def test_deserialize_bad_id_throws(self): header: str = "A.000168.68e9p9ca-a651-40f4-ad8f-3aaf781862b4.1\n" buffer: List[int] = list(bytes(header, "ascii")) with pytest.raises(ValueError): HeaderSerializer.deserialize(buffer, 0, len(buffer)) def test_deserialize_bad_end_throws(self): header_id: UUID = uuid4() header: str = f"A.000168.{str(header_id)}.z\n" buffer: List[int] = list(bytes(header, "ascii")) with pytest.raises(ValueError): HeaderSerializer.deserialize(buffer, 0, len(buffer))
src/graph_notebook/static_resources/install.py
Sam-Martin/graph-notebook
378
151178
<gh_stars>100-1000 """ Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. SPDX-License-Identifier: Apache-2.0 """ import os import site from shutil import copy2 from os.path import join as pjoin files = [ 'datatables.css', 'datatables.js' ] def main(): sitepackages = site.getsitepackages() static_base_directory = sitepackages[0] if os.name != 'nt' else sitepackages[1] destination = pjoin(static_base_directory, 'notebook', 'static') dir_path = os.path.dirname(os.path.realpath(__file__)) for file in files: full_path = pjoin(dir_path, file) print(f'copying file {file} to {destination}') copy2(full_path, destination) if __name__ == '__main__': main()
tests/widget_styles/test_floodgauge.py
dmalves/ttkbootstrap
406
151198
<filename>tests/widget_styles/test_floodgauge.py import tkinter as tk import ttkbootstrap as ttk from random import choice from ttkbootstrap import utility utility.enable_high_dpi_awareness() root = tk.Tk() root.geometry('500x500') root.title('ttkbootstrap') style = ttk.Style() def change_style(): theme = choice(style.theme_names()) style.theme_use(theme) p1 = ttk.Floodgauge( bootstyle='info', font='helvetica 24 bold', mask="Memory Used {}%", value=45 ) p1.pack(fill=tk.BOTH, expand=tk.YES, padx=10, pady=10) p1.start() btn = ttk.Button(text="Change Theme", command=change_style) btn.pack(padx=10, pady=10) p1['value'] = 50 assert p1['value'] == 50 assert p1.configure('value') == 50 p1['mask'] = None assert p1.configure('mask') is None p1['text'] = "Updating the database" assert p1['text'] == "Updating the database" p1['font'] = "arial 18" assert p1['font'] == 'arial 18' p1['mask'] = '{}% Complete' assert p1.configure('mask') == '{}% Complete' root.mainloop()
alipay/aop/api/response/MybankCreditLoanapplyQrcodeCreateResponse.py
antopen/alipay-sdk-python-all
213
151209
#!/usr/bin/env python # -*- coding: utf-8 -*- import json from alipay.aop.api.response.AlipayResponse import AlipayResponse class MybankCreditLoanapplyQrcodeCreateResponse(AlipayResponse): def __init__(self): super(MybankCreditLoanapplyQrcodeCreateResponse, self).__init__() self._encrypt_token = None self._url = None @property def encrypt_token(self): return self._encrypt_token @encrypt_token.setter def encrypt_token(self, value): self._encrypt_token = value @property def url(self): return self._url @url.setter def url(self, value): self._url = value def parse_response_content(self, response_content): response = super(MybankCreditLoanapplyQrcodeCreateResponse, self).parse_response_content(response_content) if 'encrypt_token' in response: self.encrypt_token = response['encrypt_token'] if 'url' in response: self.url = response['url']
webservices/decoders.py
18F/openFEC
246
151216
<gh_stars>100-1000 import json election_types = { 'GR': 'General runoff', 'SG': 'Special election general', 'SGR': 'Special election general runoff', 'C': 'Convention', 'SPR': 'Special primary runoff', 'SC': 'Special convention', 'PR': 'Primary runoff', 'G': 'General election', 'P': 'Primary election', 'SP': 'Special primary', 'R': 'Runoff', 'SR': 'Special runoff', } form_types = { 'F1': 'Statement of organization', 'F1M': 'Notification of multicandidate status', 'F2': 'Statement of candidacy', 'F9': '24-hour notice of disbursements for electioneering communications', 'F10': '24-hour notice of expenditure of personal funds', 'F11': '24-hour notice of opposition personal funds amount', 'F12': '24-hour notice of suspension of increased limits', 'F99': 'Miscellaneous document', 'F6': '48-hour notice of contribution/loans received', } def dumper(f3p_col_a, f3p_col_b, f3p_description, dumped): for row in dumped: description, col_a, col_b = row f3p_col_a.append(col_a) f3p_col_b.append(col_b) f3p_description.append(description) fp = open("data/" + "efile_guide_f3p.json", 'r') dumped = json.load(fp) f3p_col_a = [] f3p_col_b = [] f3p_description = [] dumper(f3p_col_a, f3p_col_b, f3p_description, dumped) f3_col_a = [] f3_col_b = [] f3_description = [] fp = open("data/" + "efile_guide_f3.json", 'r') dumped = json.load(fp) dumper(f3_col_a, f3_col_b, f3_description, dumped) fp = open("data/" + "efile_guide_f3x.json", 'r') dumped = json.load(fp) f3x_col_a = [] f3x_col_b = [] f3x_description = [] dumper(f3x_col_a, f3x_col_b, f3x_description, dumped)
dash_docs/chapters/dash_datatable/interactivity/examples/interactivity_row_ids.py
joelostblom/dash-docs
379
151235
import dash from dash.dependencies import Input, Output import dash_table import dash_core_components as dcc import dash_html_components as html import pandas as pd df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/gapminder2007.csv') # add an id column and set it as the index # in this case the unique ID is just the country name, so we could have just # renamed 'country' to 'id' (but given it the display name 'country'), but # here it's duplicated just to show the more general pattern. df['id'] = df['country'] df.set_index('id', inplace=True, drop=False) app = dash.Dash(__name__) app.layout = html.Div([ dash_table.DataTable( id='datatable-row-ids', columns=[ {'name': i, 'id': i, 'deletable': True} for i in df.columns # omit the id column if i != 'id' ], data=df.to_dict('records'), editable=True, filter_action="native", sort_action="native", sort_mode='multi', row_selectable='multi', row_deletable=True, selected_rows=[], page_action='native', page_current= 0, page_size= 10, ), html.Div(id='datatable-row-ids-container') ]) @app.callback( Output('datatable-row-ids-container', 'children'), Input('datatable-row-ids', 'derived_virtual_row_ids'), Input('datatable-row-ids', 'selected_row_ids'), Input('datatable-row-ids', 'active_cell')) def update_graphs(row_ids, selected_row_ids, active_cell): # When the table is first rendered, `derived_virtual_data` and # `derived_virtual_selected_rows` will be `None`. This is due to an # idiosyncrasy in Dash (unsupplied properties are always None and Dash # calls the dependent callbacks when the component is first rendered). # So, if `rows` is `None`, then the component was just rendered # and its value will be the same as the component's dataframe. # Instead of setting `None` in here, you could also set # `derived_virtual_data=df.to_rows('dict')` when you initialize # the component. selected_id_set = set(selected_row_ids or []) if row_ids is None: dff = df # pandas Series works enough like a list for this to be OK row_ids = df['id'] else: dff = df.loc[row_ids] active_row_id = active_cell['row_id'] if active_cell else None colors = ['#FF69B4' if id == active_row_id else '#7FDBFF' if id in selected_id_set else '#0074D9' for id in row_ids] return [ dcc.Graph( id=column + '--row-ids', figure={ 'data': [ { 'x': dff['country'], 'y': dff[column], 'type': 'bar', 'marker': {'color': colors}, } ], 'layout': { 'xaxis': {'automargin': True}, 'yaxis': { 'automargin': True, 'title': {'text': column} }, 'height': 250, 'margin': {'t': 10, 'l': 10, 'r': 10}, }, }, ) # check if column exists - user may have deleted it # If `column.deletable=False`, then you don't # need to do this check. for column in ['pop', 'lifeExp', 'gdpPercap'] if column in dff ] if __name__ == '__main__': app.run_server(debug=True)
src/probflow/distributions/multivariate_normal.py
chiragnagpal/probflow
134
151246
<reponame>chiragnagpal/probflow from probflow.utils.base import BaseDistribution from probflow.utils.settings import get_backend from probflow.utils.validation import ensure_tensor_like class MultivariateNormal(BaseDistribution): r"""The multivariate Normal distribution. The `multivariate normal distribution <https://en.wikipedia.org/wiki/Multivariate_normal_distribution>`_ is a continuous distribution in :math:`d`-dimensional space, and has two parameters: - a location vector (``loc`` or :math:`\boldsymbol{\mu} \in \mathbb{R}^d`) which determines the mean of the distribution, and - a covariance matrix (``scale`` or :math:`\boldsymbol{\Sigma} \in \mathbb{R}^{d \times d}_{>0}`) which determines the spread and covariance of the distribution. A random variable :math:`\mathbf{x} \in \mathbb{R}^d` drawn from a multivariate normal distribution .. math:: \mathbf{x} \sim \mathcal{N}(\boldsymbol{\mu}, \boldsymbol{\Sigma}) has probability .. math:: p(\mathbf{x}) = (2\pi)^{-\frac{d}{2}} \det(\boldsymbol{\Sigma})^{-\frac{1}{2}} \exp \left( -\frac{1}{2} (\mathbf{x}-\boldsymbol{\mu})^\top \boldsymbol{\Sigma}^{-1} (\mathbf{x}-\boldsymbol{\mu}) \right) TODO: example image of the distribution Parameters ---------- loc : |ndarray|, or Tensor Mean of the multivariate normal distribution (:math:`\boldsymbol{\mu}`). cov : |ndarray|, or Tensor Covariance matrix of the multivariate normal distribution (:math:`\boldsymbol{\Sigma}`). """ def __init__(self, loc, cov): # Check input ensure_tensor_like(loc, "loc") ensure_tensor_like(cov, "cov") # Store args self.loc = loc self.cov = cov def __call__(self): """Get the distribution object from the backend""" if get_backend() == "pytorch": import torch.distributions as tod return tod.multivariate_normal.MultivariateNormal( self["loc"], covariance_matrix=self["cov"] ) else: import tensorflow as tf from tensorflow_probability import distributions as tfd tril = tf.linalg.cholesky(self["cov"]) return tfd.MultivariateNormalTriL(loc=self["loc"], scale_tril=tril)
scripts/python/rheatrace/enhanced_systrace/systrace_capturer.py
cjztool/btrace
1,007
151256
#!/usr/bin/env python # Copyright (C) 2021 ByteDance Inc # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the 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 in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import sys import io_extender import rhea_config from enhanced_systrace import systrace_env from common import cmd_executer from rhea_atrace.rhea_log.rhea_logger import rhea_logger logger = rhea_logger def capture(context): root_cmd = ["root"] (out, return_code) = cmd_executer.exec_commands(cmd_executer.get_complete_abd_cmd(root_cmd, context.serial_number)) open_android_fs = False if return_code is 0: if "cannot" not in out: logger.info("current devices is rooted!") _drop_cache() open_android_fs = __open_android_fs(context.serial_number) logger.debug("start to capture systrace.") (out, return_code) = __capture_systrace(context) logger.debug(out) if return_code is 0: context.set_params(rhea_config.ENVIRONMENT_PARAMS_ANDROID_FS, open_android_fs) if open_android_fs: io_extender.extend(context.get_build_file_path(rhea_config.ORIGIN_SYSTRACE_FILE), context.get_build_file_path(rhea_config.ORIGIN_SYSTRACE_FS_FILE)) return True logger.error("failed to capture systrace, check your inputs firstly.") return False def show_list_categories(serial_number): systrace_path = systrace_env.get_executable_systrace() if systrace_path is None: logger.error("can't find systrace in system environment.") sys.exit(1) cmd = [systrace_path] cmd.extend(["-l"]) if serial_number is not None: cmd.extend(["-e", serial_number]) return cmd_executer.exec_commands(cmd) def from_file(file_path): systrace_path = systrace_env.get_executable_systrace() if systrace_path is None: logger.error("can't find systrace in system environment.") sys.exit(1) cmd = [systrace_path] cmd.extend(["--from-file", file_path]) return cmd_executer.exec_commands(cmd) def _drop_cache(): """ free pagecache dentries and inodes cache, only root device effected """ (out, return_code) = cmd_executer.exec_write_value("/proc/sys/vm/drop_caches", "3") if return_code is 0 and out is None: logger.debug("succeed to drop caches.") def __open_android_fs(serial_number): """ tracing android_fs events, only root device effected. """ (out, return_code) = cmd_executer.exec_write_value("/d/tracing/events/android_fs/enable", "1") open_successful = False if return_code is 0 and out is None: open_successful = True logger.info("succeed to tracing android_fs events.") else: (out_1, return_code_1) = cmd_executer.exec_adb_shell_with_append_commands( "su -c 'echo 1 > /d/tracing/events/android_fs/enable'", serial_number) if return_code_1 is 0 and out_1 is None: open_successful = True logger.info("ensure to tracing android_fs events successfully.") return open_successful def __capture_systrace(context): systrace_path = systrace_env.get_executable_systrace() cmd = ["python2.7", systrace_path] if context.serial_number is not None: cmd.extend(["-e", context.serial_number]) if context.categories: cmd.extend(context.categories) cmd.extend(["-o", context.get_build_file_path(rhea_config.ORIGIN_SYSTRACE_FILE)]) if context.app_name is not None: cmd.extend(["-a", context.app_name]) if context.trace_time is not None: cmd.extend(["-t", str(context.trace_time + context.advanced_systrace_time + 2)]) if context.trace_buf_size is not None: cmd.extend(["-b", str(context.trace_buf_size)]) if context.kfuncs is not None: cmd.extend(["-k", str(context.kfuncs)]) logger.debug("systrace cmd: " + str(cmd)) return cmd_executer.exec_commands(cmd)
models/vision/classification/datasets.py
piyushghai/deep-learning-models
129
151297
import horovod.tensorflow as hvd import os import tensorflow as tf from preprocessing import resnet_preprocessing, imagenet_preprocessing, darknet_preprocessing import functools def create_dataset(data_dir, batch_size, preprocessing='resnet', validation=False): filenames = [os.path.join(data_dir, i) for i in os.listdir(data_dir)] data = tf.data.TFRecordDataset(filenames).shard(hvd.size(), hvd.rank()) if not validation: parse_fn = functools.partial(parse_train, preprocessing=preprocessing) data = data.shuffle(buffer_size=1000) data = data.map(parse_fn, num_parallel_calls=tf.data.experimental.AUTOTUNE) else: parse_fn = functools.partial(parse_validation, preprocessing=preprocessing) data = data.map(parse_fn, num_parallel_calls=tf.data.experimental.AUTOTUNE) # we drop remainder because we want same sized batches - XLA and because of allreduce being used to calculate # accuracy - validation accuracy may be slightly different than computing on all of validation data data = data.batch(batch_size, drop_remainder=True).prefetch(tf.data.experimental.AUTOTUNE) return data @tf.function def parse(record, is_training, preprocessing): features = {'image/encoded': tf.io.FixedLenFeature((), tf.string), 'image/class/label': tf.io.FixedLenFeature((), tf.int64), 'image/object/bbox/xmin': tf.io.VarLenFeature(dtype=tf.float32), 'image/object/bbox/ymin': tf.io.VarLenFeature(dtype=tf.float32), 'image/object/bbox/xmax': tf.io.VarLenFeature(dtype=tf.float32), 'image/object/bbox/ymax': tf.io.VarLenFeature(dtype=tf.float32), } parsed = tf.io.parse_single_example(record, features) image_bytes = tf.reshape(parsed['image/encoded'], shape=[]) # bbox = tf.constant([0.0, 0.0, 1.0, 1.0], dtype=tf.float32, shape=[1, 1, 4]) bbox = tf.stack([parsed['image/object/bbox/%s' % x].values for x in ['ymin', 'xmin', 'ymax', 'xmax']]) bbox = tf.transpose(tf.expand_dims(bbox, 0), [0, 2, 1]) if preprocessing == 'resnet': augmenter = None # augment.AutoAugment() image = resnet_preprocessing.preprocess_image(image_bytes, bbox, 224, 224, 3, is_training=is_training) elif preprocessing == 'imagenet': # used by hrnet image = imagenet_preprocessing.preprocess_image(image_bytes, bbox, 224, 224, 3, is_training=is_training) elif preprocessing == 'darknet': image = darknet_preprocessing.preprocess_image(image_bytes, bbox, 256, 256, 3, is_training=is_training) label = tf.cast(parsed['image/class/label'] - 1, tf.int32) one_hot_label = tf.one_hot(label, depth=1000, dtype=tf.float32) return image, one_hot_label def parse_train(record, preprocessing): return parse(record, is_training=True, preprocessing=preprocessing) def parse_validation(record, preprocessing): return parse(record, is_training=False, preprocessing=preprocessing)
website/content/ChapterFour/pytool/WordCount.py
sohaoo/LeetCode-Go
25,030
151300
<reponame>sohaoo/LeetCode-Go<filename>website/content/ChapterFour/pytool/WordCount.py<gh_stars>1000+ from collections import defaultdict import glob import os def str_count2(str): count_zh = count_dg = 0 for s in str: # 中文字符范围 if '\u4e00' <= s <= '\u9fff': count_zh += 1 if s.isdigit(): count_dg += 1 # print(count_zh + count_dg) return count_zh + count_dg current_working_dir = os.getcwd() # print(f"current_working_dir: {current_working_dir}") dir_names = glob.glob("*.md") dir_names.sort() word_count = 0 for file_name in dir_names: with open(file_name, "r") as myfile: codeContent = myfile.read() print("当前读取文件: {}, 字数统计: {}".format(file_name, str_count2(codeContent))) word_count += str_count2(codeContent) print(word_count)
judge/statistics_in_paper.py
zwangab91/ctw-baseline
333
151309
<reponame>zwangab91/ctw-baseline<filename>judge/statistics_in_paper.py # -*- coding: utf-8 -*- from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import bisect import codecs import json import matplotlib.pyplot as plt import os import plot_tools import settings import six import threading from collections import defaultdict from pythonapi import anno_tools, common_tools from six.moves import urllib @common_tools.synchronized(threading.Lock()) def get_chinese_ttf(): if not os.path.isdir(settings.PLOTS_DIR): os.makedirs(settings.PLOTS_DIR) chinese_ttf = os.path.join(settings.PRODUCTS_ROOT, 'SimHei.ttf') if not os.path.isfile(chinese_ttf) or 9751960 != os.path.getsize(chinese_ttf): url = 'http://fonts.cooltext.com/Downloader.aspx?ID=11120' print('please download {} to {}'.format(url, chinese_ttf)) if os.path.isfile(chinese_ttf): os.unlink(chinese_ttf) urllib.request.urlretrieve('http://fonts.cooltext.com/Downloader.aspx?ID=11120', chinese_ttf) return chinese_ttf def main(): most_freq = defaultdict(lambda: {'trainval': 0, 'test': 0}) num_char = defaultdict(lambda: {'trainval': 0, 'test': 0}) num_uniq_char = defaultdict(lambda: {'trainval': 0, 'test': 0}) num_image = {'trainval': 0, 'test': 0} sum_chinese = {'trainval': 0, 'test': 0} sum_not_chinese = {'trainval': 0, 'test': 0} sum_ignore = {'trainval': 0, 'test': 0} longsizes = {'trainval': list(), 'test': list()} attrs = {szname: {attr: 0 for attr in settings.ATTRIBUTES + ['__all__']} for szname, _ in settings.SIZE_RANGES} with open(settings.TRAIN) as f, open(settings.VAL) as f2: for line in f.read().splitlines() + f2.read().splitlines(): anno = json.loads(line.strip()) num = 0 uniq = set() for char in anno_tools.each_char(anno): if char['is_chinese']: most_freq[char['text']]['trainval'] += 1 num += 1 uniq.add(char['text']) sum_chinese['trainval'] += 1 longsize = max(char['adjusted_bbox'][2], char['adjusted_bbox'][3]) longsizes['trainval'].append(longsize) for szname, szrange in settings.SIZE_RANGES: if szrange[0] <= longsize < szrange[1]: for attr in char['attributes']: attrs[szname][attr] += 1 attrs[szname]['__all__'] += 1 else: sum_not_chinese['trainval'] += 1 assert 0 < len(uniq) num_char[num]['trainval'] += 1 num_uniq_char[len(uniq)]['trainval'] += 1 num_image['trainval'] += 1 sum_ignore['trainval'] += len(anno['ignore']) with open(settings.TEST_CLASSIFICATION_GT) as f: for line in f: gt = json.loads(line.strip())['ground_truth'] num = 0 uniq = set() for char in gt: most_freq[char['text']]['test'] += 1 num += 1 uniq.add(char['text']) sum_chinese['test'] += 1 longsize = max(*char['size']) longsizes['test'].append(longsize) for szname, szrange in settings.SIZE_RANGES: if szrange[0] <= longsize < szrange[1]: for attr in char['attributes']: attrs[szname][attr] += 1 attrs[szname]['__all__'] += 1 assert 0 < len(uniq) num_char[num]['test'] += 1 num_uniq_char[len(uniq)]['test'] += 1 num_image['test'] += 1 with open(settings.TEST_DETECTION_GT) as f: for line in f: anno = json.loads(line.strip()) num = 0 uniq = set() for char in anno_tools.each_char(anno): if char['is_chinese']: most_freq[char['text']]['test'] += 1 num += 1 uniq.add(char['text']) sum_chinese['test'] += 1 longsizes['test'].append(max(char['adjusted_bbox'][2], char['adjusted_bbox'][3])) for szname, szrange in settings.SIZE_RANGES: if szrange[0] <= longsize < szrange[1]: for attr in char['attributes']: attrs[szname][attr] += 1 attrs[szname]['__all__'] += 1 else: sum_not_chinese['test'] += 1 assert 0 < len(uniq) num_char[num]['test'] += 1 num_uniq_char[len(uniq)]['test'] += 1 num_image['test'] += 1 sum_ignore['test'] += len(anno['ignore']) most_freq = [{ 'text': k, 'trainval': v['trainval'], 'test': v['test'], } for k, v in most_freq.items()] most_freq.sort(key=lambda o: (-o['trainval'] - o['test'], o['text'])) print('10_most_frequent_characters') for i, o in enumerate(most_freq[:10]): print(i + 1, o['text'], o['trainval'], o['test']) print('over_all') print('uniq_chinese', len(most_freq)) print('num_image', num_image['trainval'], num_image['test']) print('sum_chinese', sum_chinese['trainval'], sum_chinese['test']) print('sum_not_chinese', sum_not_chinese['trainval'], sum_not_chinese['test']) print('sum_ignore', sum_ignore['trainval'], sum_ignore['test']) with codecs.open(settings.STAT_FREQUENCY, 'w', 'utf-8') as f: json.dump(most_freq, f, ensure_ascii=False, indent=2) # most_freq meta = most_freq[:50] data = [ [ { 'legend': 'training set', 'data': [o['trainval'] for o in meta], }, { 'legend': 'testing set', 'data': [o['test'] for o in meta], }, ], ] labels = [o['text'] for o in meta] with plt.style.context({ 'figure.subplot.left': .06, 'figure.subplot.right': .98, 'figure.subplot.top': .96, 'pdf.fonttype': 42, }): plt.figure(figsize=(10, 3)) plt.xlim((0, len(labels) + 1)) plt.grid(which='major', axis='y', linestyle='dotted') plot_tools.draw_bar(data, labels, xticks_font_fname=get_chinese_ttf()) plt.savefig(os.path.join(settings.PLOTS_DIR, 'stat_most_freq.pdf')) plt.close() # num_char meta = [num_char[i] for i in range(1, 61)] data = [ [ { 'legend': 'training set', 'data': [o['trainval'] for o in meta], }, { 'legend': 'testing set', 'data': [o['test'] for o in meta], }, ], ] labels = [i + 1 if (i + 1) % 10 == 0 else None for i, _ in enumerate(meta)] with plt.style.context({ 'figure.subplot.left': .14, 'figure.subplot.right': .96, 'figure.subplot.bottom': .16, 'figure.subplot.top': .96, 'pdf.fonttype': 42, }): plt.figure(figsize=(5, 3)) plt.xlim((0, len(labels) + 1)) plt.grid(which='major', axis='y', linestyle='dotted') plot_tools.draw_bar(data, labels) plt.xlabel('number of character instances') plt.ylabel('number of images') plt.savefig(os.path.join(settings.PLOTS_DIR, 'stat_num_char.pdf')) plt.close() # num_uniq_char meta = [num_uniq_char[i] for i in range(1, 61)] data = [ [ { 'legend': 'training set', 'data': [o['trainval'] for o in meta], }, { 'legend': 'testing set', 'data': [o['test'] for o in meta], }, ], ] labels = [i + 1 if (i + 1) % 10 == 0 else None for i, _ in enumerate(meta)] with plt.style.context({ 'figure.subplot.left': .14, 'figure.subplot.right': .96, 'figure.subplot.bottom': .16, 'figure.subplot.top': .96, 'pdf.fonttype': 42, }): plt.figure(figsize=(5, 3)) plt.xlim((0, len(labels) + 1)) plt.grid(which='major', axis='y', linestyle='dotted') plot_tools.draw_bar(data, labels) plt.xlabel('number of character categories') plt.ylabel('number of images') plt.savefig(os.path.join(settings.PLOTS_DIR, 'stat_num_uniq_char.pdf')) plt.close() # instance size longsizes['trainval'].sort() longsizes['test'].sort() ranges = list(range(0, 65, 8)) data = [ [ { 'legend': 'training set', 'data': [bisect.bisect_left(longsizes['trainval'], hi) - bisect.bisect_left(longsizes['trainval'], lo) for lo, hi in zip(ranges, ranges[1:] + [float('inf')])], }, { 'legend': 'testing set', 'data': [bisect.bisect_left(longsizes['test'], hi) - bisect.bisect_left(longsizes['test'], lo) for lo, hi in zip(ranges, ranges[1:] + [float('inf')])], }, ], ] labels = ['{}-{}'.format(lo, hi) for lo, hi in zip(ranges, ranges[1:] + [''])] with plt.style.context({ 'figure.subplot.left': .12, 'figure.subplot.right': .96, 'figure.subplot.bottom': .10, 'figure.subplot.top': .96, 'pdf.fonttype': 42, }): plt.figure(figsize=(6, 3)) plt.xlim((0, len(labels) + 1)) plt.grid(which='major', axis='y', linestyle='dotted') plot_tools.draw_bar(data, labels) plt.savefig(os.path.join(settings.PLOTS_DIR, 'stat_instance_size.pdf')) plt.close() # attributes percentage data = [ [ { 'legend': szname, 'data': [attrs[szname][attr] / attrs[szname]['__all__'] * 100 for attr in settings.ATTRIBUTES], } ] for szname, szrange in settings.SIZE_RANGES ] labels = settings.ATTRIBUTES with plt.style.context({ 'figure.subplot.left': .12, 'figure.subplot.right': .96, 'figure.subplot.bottom': .10, 'figure.subplot.top': .96, 'pdf.fonttype': 42, }): plt.figure(figsize=(6, 3)) plt.xlim((.3, .7 + len(labels))) plt.grid(which='major', axis='y', linestyle='dotted') plt.gca().yaxis.set_major_formatter(plt.FuncFormatter('{:.0f}%'.format)) plot_tools.draw_bar(data, labels, width=.18) plt.savefig(os.path.join(settings.PLOTS_DIR, 'stat_attributes.pdf')) plt.close() if __name__ == '__main__': main()
mitreattack/__init__.py
wetkind/mitreattack-python
137
151322
from .attackToExcel import * from .navlayers import * from .collections import *
tests/model_permalink/tests.py
MikeAmy/django
5,079
151325
<reponame>MikeAmy/django<gh_stars>1000+ from django.test import SimpleTestCase, override_settings from .models import Guitarist @override_settings(ROOT_URLCONF='model_permalink.urls') class PermalinkTests(SimpleTestCase): def test_permalink(self): g = Guitarist(name='<NAME>', slug='adrienmoignard') self.assertEqual(g.url(), '/guitarists/adrienmoignard/') def test_wrapped_docstring(self): "Methods using the @permalink decorator retain their docstring." g = Guitarist(name='<NAME>', slug='adrienmoignard') self.assertEqual(g.url.__doc__, "Returns the URL for this guitarist.") def test_wrapped_attribute(self): """ Methods using the @permalink decorator can have attached attributes from other decorators """ g = Guitarist(name='<NAME>', slug='adrienmoignard') self.assertTrue(hasattr(g.url_with_attribute, 'attribute')) self.assertEqual(g.url_with_attribute.attribute, 'value')
src/tasks/challenge/round1/tests/test_mini_tasks.py
general-ai-challenge/Round1
107
151331
# Copyright (c) 2017-present, GoodAI # All rights reserved. # # This source code is licensed under the BSD-style license found in the # LICENSE_CHALLENGE file in the root directory of this source tree. import re import unittest import core.environment as environment import core.serializer as serializer import tasks.challenge.round1.challenge_mini as comm_ai_mini from core.scheduler import ConsecutiveTaskScheduler from learners.base import BaseLearner from tasks.challenge.round1.tests.test_micro_tasks import EnvironmentByteMessenger, FixedLearner from tasks.competition.tests.helpers import SingleTaskScheduler from tasks.competition.tests.helpers import task_messenger as commai_messenger from worlds.grid_world import GridWorld class TestCommAIMiniBase(unittest.TestCase): @classmethod def setUpClass(cls): if cls is TestCommAIMiniBase: raise unittest.SkipTest("Skip BaseTest tests, it's a base class") super(TestCommAIMiniBase, cls).setUpClass() def __init__(self, *args, **kwargs): super(TestCommAIMiniBase, self).__init__(*args, **kwargs) self.task_set = None def _obtains_feedback(self, m): feedback_len = m.read() self.assertGreater(feedback_len, 0) def test_new_correct(self): with commai_messenger(self.task_set, GridWorld) as m: m.read() correct_answer = m._env._task_scheduler.task.answer + '.' m.send(correct_answer) self._obtains_feedback(m) m.send() self.assertEqual(m.get_cumulative_reward(), 1) def test_new_timeout(self): with commai_messenger(self.task_set, GridWorld) as m: m.read() while m.is_silent(): m.send() self._obtains_feedback(m) feedback = m.get_last_message() self.assertTrue('Wrong' in feedback) m.send() self.assertEqual(m.get_cumulative_reward(), 0) def test_error_answer(self): with commai_messenger(self.task_set, GridWorld) as m: m.read() m.send("wrong answer.") self._obtains_feedback(m) feedback = m.get_last_message() self.assertTrue('Wrong' in feedback) m.send() self.assertEqual(m.get_cumulative_reward(), 0) class TestCommAIMiniTS1(TestCommAIMiniBase): def __init__(self, *args, **kwargs): super(TestCommAIMiniTS1, self).__init__(*args, **kwargs) self.task_set = comm_ai_mini.TaskSet1 class TestCommAIMiniTS2(TestCommAIMiniBase): def __init__(self, *args, **kwargs): super(TestCommAIMiniTS2, self).__init__(*args, **kwargs) self.task_set = comm_ai_mini.TaskSet2 class TestCommAIMiniTS3(TestCommAIMiniBase): def __init__(self, *args, **kwargs): super(TestCommAIMiniTS3, self).__init__(*args, **kwargs) self.task_set = comm_ai_mini.TaskSet3 class TestCommAIMiniTS4(TestCommAIMiniBase): def __init__(self, *args, **kwargs): super(TestCommAIMiniTS4, self).__init__(*args, **kwargs) self.task_set = comm_ai_mini.TaskSet4 class TestCommAIMiniTS5(TestCommAIMiniBase): def __init__(self, *args, **kwargs): super(TestCommAIMiniTS5, self).__init__(*args, **kwargs) self.task_set = comm_ai_mini.TaskSet5 def task_solved_successfuly(task): return task._env._last_result def basic_task_run(test, messenger, learner, task): limit = task._max_time while True: limit -= 1 if limit < 1: test.assertFalse(True) # raise the timeout constant on these tasks, because they are not finishing # on nr_of_questions timeout, but on nr_of_characters timeout break question = messenger.get_text()[-1] answer = learner.next(question) reward = messenger.send(answer) learner.reward(reward) if task._env._last_result is not None: # agent succeeded break def task_messenger(task): slzr = serializer.StandardSerializer() scheduler = SingleTaskScheduler(task) env = environment.Environment(slzr, scheduler, max_reward_per_task=float("inf"), byte_mode=True) return EnvironmentByteMessenger(env, slzr) class TestMicroTaskBase(unittest.TestCase): task = None task_instance_multiplier = 3 task_run_multiplier = 10 @classmethod def setUpClass(cls): if cls is TestMicroTaskBase: raise unittest.SkipTest("Skip MicroTaskBase tests, it's a base class") super(TestMicroTaskBase, cls).setUpClass() def _get_task(self): task = self.task() task.success_tolerance = 0 task.failed_task_tolerance = 0 return task def _get_learner(self): pass def _get_failing_learner(self): return FixedLearner('*') def init_env(self, task, success_threshold=2): slzr = serializer.StandardSerializer() scheduler = ConsecutiveTaskScheduler([task], success_threshold) env = environment.Environment(slzr, scheduler, max_reward_per_task=float("inf"), byte_mode=True) messenger = EnvironmentByteMessenger(env, slzr) return (scheduler, messenger) def test_task(self): for _ in range(self.task_instance_multiplier): task = self._get_task() for _ in range(self.task_run_multiplier): learner = self._get_learner() messenger = task_messenger(task) basic_task_run(self, messenger, learner, task) self.assertTrue(task_solved_successfuly(task)) def test_successful_evaluation(self): # Tests that task instance can be solved and that there are no residuals from 1st instance, which would prevent agent from solving 2nd instance task = self._get_task() scheduler, messenger = self.init_env(task) # first run learner = self._get_learner() basic_task_run(self, messenger, learner, task) self.assertTrue(task_solved_successfuly(task)) self.assertEqual(scheduler.reward_count, 1) # second run learner = self._get_learner() basic_task_run(self, messenger, learner, task) self.assertTrue(task_solved_successfuly(task)) self.assertEqual(scheduler.reward_count, 0) # 2 % 2 = 0, because the scheduler switched to next task def test_failed_evaluation(self): # Tests that instance can be failed and that there are no residuals from 1st instance, which would solve the 2nd instance instead of agent task = self.task() scheduler, messenger = self.init_env(task) # first run learner = self._get_failing_learner() basic_task_run(self, messenger, learner, task) self.assertFalse(task_solved_successfuly(task)) self.assertEqual(scheduler.reward_count, 0) # second run basic_task_run(self, messenger, learner, task) self.assertFalse(task_solved_successfuly(task)) self.assertEqual(scheduler.reward_count, 0) class TestCommAIMiniNewTS1(TestMicroTaskBase): task = comm_ai_mini.TaskSet1 def _get_learner(self): return Mini1Learner() def _get_failing_learner(self): return FixedLearner('.') class TestMatchQuestionAndFeedbackBase(BaseLearner): matcher_feedback = None matcher_output = None def __init__(self): self._buffer = [] self._read_assignment = True self._output = [] def next(self, input_char): self._buffer.append(input_char) if self._read_assignment: if input_char == '.': # Commands received. # Get the whole assignment, remove dot. received_sentence = ''.join(self._buffer) if self.matcher_feedback is None: feedback_match = [''] else: feedback_match = self.matcher_feedback.findall(received_sentence) output_match = self.matcher_output.findall(received_sentence) if len(output_match) > 0: self._output = list(self.generate_response(feedback_match, output_match)) self._buffer = [] self._read_assignment = False if not self._read_assignment: if len(self._output) > 0: return self._output.pop(0) else: self._read_assignment = True return '.' return ' ' def generate_response(self, feedback_match, output_match): raise NotImplementedError() def verify_description(verify, description): verification_array = [False for _ in verify] window_length = len(description) for i in range(0, len(verify) - window_length + 1): covers = description == verify[i:i + window_length] verification_array[i:i + window_length] = [covers or verification_array[i + j] for j in range(0, window_length)] return all(verification_array) class Mini1Learner(TestMatchQuestionAndFeedbackBase): matcher_output = re.compile('description: (.+); verify: (.+)\.') def generate_response(self, feedback_match, output_match): description = output_match[0][0] verify = output_match[0][1] if verify_description(verify, description): return 'true' else: return 'false'
datasets/dialog_systems/dialog-bAbI/utils.py
chetanchougle/chatbot2
246
151364
<gh_stars>100-1000 DATA_SOURCE = 'data/dialog-bAbI-tasks/dialog-babi-candidates.txt' DATA_SOURCE_TASK6 = 'data/dialog-bAbI-tasks/dialog-babi-task6-dstc2-candidates.txt' DATA_DIR = 'dialog-bAbI-tasks/dialog-babi-candidates.txt' STOP_WORDS=set(["a","an","the"]) import re import os from itertools import chain from six.moves import range, reduce import numpy as np import tensorflow as tf def tokenize(sent): '''Return the tokens of a sentence including punctuation. >>> tokenize('Bob dropped the apple. Where is the apple?') ['Bob', 'dropped', 'the', 'apple', '.', 'Where', 'is', 'the', 'apple'] ''' sent=sent.lower() if sent=='<silence>': return [sent] result=[x.strip() for x in re.split('(\W+)?', sent) if x.strip() and x.strip() not in STOP_WORDS] if not result: result=['<silence>'] if result[-1]=='.' or result[-1]=='?' or result[-1]=='!': result=result[:-1] return result def load_candidates(task_id, candidates_f=DATA_SOURCE): # containers candidates, candid2idx, idx2candid = [], {}, {} # update data source file based on task id candidates_f = DATA_SOURCE_TASK6 if task_id==6 else candidates_f # read from file with open(candidates_f) as f: # iterate through lines for i, line in enumerate(f): # tokenize each line into... well.. tokens! candid2idx[line.strip().split(' ',1)[1]] = i candidates.append(tokenize(line.strip())) idx2candid[i] = line.strip().split(' ',1)[1] return candidates, candid2idx, idx2candid def parse_dialogs_per_response(lines,candid_dic): ''' Parse dialogs provided in the babi tasks format ''' data=[] context=[] u=None r=None for line in lines: line=line.strip() if line: nid, line = line.split(' ', 1) nid = int(nid) if '\t' in line: u, r = line.split('\t') a = candid_dic[r] u = tokenize(u) r = tokenize(r) # temporal encoding, and utterance/response encoding # data.append((context[:],u[:],candid_dic[' '.join(r)])) data.append((context[:],u[:],a)) u.append('$u') u.append('#'+str(nid)) r.append('$r') r.append('#'+str(nid)) context.append(u) context.append(r) else: r=tokenize(line) r.append('$r') r.append('#'+str(nid)) context.append(r) else: # clear context context=[] return data def get_dialogs(f,candid_dic): '''Given a file name, read the file, retrieve the dialogs, and then convert the sentences into a single dialog. If max_length is supplied, any stories longer than max_length tokens will be discarded. ''' with open(f) as f: return parse_dialogs_per_response(f.readlines(),candid_dic) def load_dialog_task(data_dir, task_id, candid_dic, isOOV=False): '''Load the nth task. Returns a tuple containing the training and testing data for the task. ''' assert task_id > 0 and task_id < 7 files = os.listdir(data_dir) files = [os.path.join(data_dir, f) for f in files] s = 'dialog-babi-task{}-'.format(task_id) train_file = [f for f in files if s in f and 'trn' in f][0] if isOOV: test_file = [f for f in files if s in f and 'tst-OOV' in f][0] else: test_file = [f for f in files if s in f and 'tst.' in f][0] val_file = [f for f in files if s in f and 'dev' in f][0] train_data = get_dialogs(train_file,candid_dic) test_data = get_dialogs(test_file,candid_dic) val_data = get_dialogs(val_file,candid_dic) return train_data, test_data, val_data def build_vocab(data, candidates, memory_size=50): vocab = reduce(lambda x, y: x | y, (set(list(chain.from_iterable(s)) + q) for s, q, a in data)) vocab |= reduce(lambda x,y: x|y, (set(candidate) for candidate in candidates) ) vocab=sorted(vocab) w2idx = dict((c, i + 1) for i, c in enumerate(vocab)) max_story_size = max(map(len, (s for s, _, _ in data))) mean_story_size = int(np.mean([ len(s) for s, _, _ in data ])) sentence_size = max(map(len, chain.from_iterable(s for s, _, _ in data))) candidate_sentence_size=max(map(len,candidates)) query_size = max(map(len, (q for _, q, _ in data))) memory_size = min(memory_size, max_story_size) vocab_size = len(w2idx) + 1 # +1 for nil word sentence_size = max(query_size, sentence_size) # for the position return { 'w2idx' : w2idx, 'idx2w' : vocab, 'sentence_size' : sentence_size, 'candidate_sentence_size' : candidate_sentence_size, 'memory_size' : memory_size, 'vocab_size' : vocab_size, 'n_cand' : len(candidates) } # metadata def vectorize_candidates(candidates, word_idx, sentence_size): shape=(len(candidates),sentence_size) C=[] for i,candidate in enumerate(candidates): lc=max(0,sentence_size-len(candidate)) C.append([word_idx[w] if w in word_idx else 0 for w in candidate] + [0] * lc) return tf.constant(C,shape=shape) def vectorize_data(data, word_idx, sentence_size, batch_size, candidates_size, max_memory_size): """ Vectorize stories and queries. If a sentence length < sentence_size, the sentence will be padded with 0's. If a story length < memory_size, the story will be padded with empty memories. Empty memories are 1-D arrays of length sentence_size filled with 0's. The answer array is returned as a one-hot encoding. """ S = [] Q = [] A = [] data.sort(key=lambda x:len(x[0]),reverse=True) for i, (story, query, answer) in enumerate(data): if i%batch_size==0: memory_size=max(1,min(max_memory_size,len(story))) ss = [] for i, sentence in enumerate(story, 1): ls = max(0, sentence_size - len(sentence)) ss.append([word_idx[w] if w in word_idx else 0 for w in sentence] + [0] * ls) # take only the most recent sentences that fit in memory ss = ss[::-1][:memory_size][::-1] # pad to memory_size lm = max(0, memory_size - len(ss)) for _ in range(lm): ss.append([0] * sentence_size) lq = max(0, sentence_size - len(query)) q = [word_idx[w] if w in word_idx else 0 for w in query] + [0] * lq S.append(np.array(ss)) Q.append(np.array(q)) A.append(np.array(answer)) return S, Q, A def get_batches(train_data, val_data, test_data, metadata, batch_size): ''' input : train data, valid data metadata : {batch_size, w2idx, sentence_size, num_cand, memory_size} output : batch indices ([start, end]); train, val split into stories, ques, answers ''' w2idx = metadata['w2idx'] sentence_size = metadata['sentence_size'] memory_size = metadata['memory_size'] n_cand = metadata['n_cand'] trainS, trainQ, trainA = vectorize_data(train_data, w2idx, sentence_size, batch_size, n_cand, memory_size) valS, valQ, valA = vectorize_data(val_data, w2idx, sentence_size, batch_size, n_cand, memory_size) testS, testQ, testA = vectorize_data(test_data, w2idx, sentence_size, batch_size, n_cand, memory_size) n_train = len(trainS) n_val = len(valS) n_test = len(testS) print("Training Size",n_train) print("Validation Size", n_val) print("Test Size", n_test) batches = zip(range(0, n_train-batch_size, batch_size), range(batch_size, n_train, batch_size)) # package train set train = { 's' : trainS, 'q' : trainQ, 'a' : trainA } # you have a better idea? # package validation set val = { 's' : valS, 'q' : valQ, 'a' : valA } # package test set test = { 's' : testS, 'q' : testQ, 'a' : testA } return train, val, test, [(start, end) for start, end in batches] if __name__ == '__main__': candidates, candid2idx, idx2candid = load_candidates(task_id=1)
tools/mo/openvino/tools/mo/back/ReduceMerge.py
ryanloney/openvino-1
1,127
151369
<filename>tools/mo/openvino/tools/mo/back/ReduceMerge.py # Copyright (C) 2018-2022 Intel Corporation # SPDX-License-Identifier: Apache-2.0 import logging as log import numpy as np from openvino.tools.mo.ops.ReduceOps import reduce_map from openvino.tools.mo.back.replacement import BackReplacementPattern from openvino.tools.mo.front.common.partial_infer.utils import int64_array from openvino.tools.mo.graph.graph import Graph from openvino.tools.mo.ops.concat import Concat class ReduceMerge(BackReplacementPattern): """ Fuses sequence of Reduces of the same type into one Reduce layer of this particular type with updated axes input Limitations: - `keep_dims` attribute should be the same for all Reduces in the sequence - in case `keep_dims`=False: next Reduce axes should be strictly less than previous Reduce axes """ enabled = True force_clean_up = True @staticmethod def fuse_reduces(first_reduce, second_reduce): first_reduce_name = first_reduce.soft_get('name', first_reduce.id) second_reduce_name = second_reduce.soft_get('name', second_reduce.id) reduce_type = first_reduce.type assert first_reduce.type == second_reduce.type if len(first_reduce.out_port(0).get_destinations()) != 1: # data dependency return if first_reduce.keep_dims != second_reduce.keep_dims: return first_axes = first_reduce.in_port(1).data.get_value() second_axes = second_reduce.in_port(1).data.get_value() if first_axes is None or second_axes is None: # dynamic axes merging is not supported return if not first_reduce.keep_dims: if not np.all(first_axes > second_axes): # indexing of upper reduce input dimensions changed return graph = second_reduce.graph new_axes = Concat(graph, {'name': second_reduce_name + '/Axes', 'axis': int64_array(0), 'in_ports_count': 2, 'override_output_shape': True}).create_node() new_axes.in_port(0).connect(first_reduce.in_port(1).get_source()) new_axes.in_port(1).connect(second_reduce.in_port(1).get_source()) first_reduce.in_port(0).get_source().node['need_shape_inference'] = True first_reduce.in_port(0).get_source().node['override_output_shape'] = True second_reduce.in_port(1).get_connection().set_source(new_axes.out_port(0)) first_reduce.out_port(0).get_connection().set_source(first_reduce.in_port(0).get_connection().get_source()) first_reduce.in_port(1).disconnect() graph.remove_node(first_reduce.id) log.debug('{0} nodes {1} and {2} were fused to a single {2} node with updated axes input' ''.format(reduce_type, first_reduce_name, second_reduce_name)) def find_and_replace_pattern(self, graph: Graph): rsorted_nodes = graph.pseudo_topological_sort(reverse=True) for reduce_type in reduce_map.keys(): reduces_of_type = [n for n in rsorted_nodes if n.id in graph and n.soft_get('type') == reduce_type] for second_reduce_node in reduces_of_type: if second_reduce_node.id not in graph: continue first_reduce_node = second_reduce_node.in_port(0).get_source().node if first_reduce_node.soft_get('type', None) == reduce_type: ReduceMerge.fuse_reduces(first_reduce=first_reduce_node, second_reduce=second_reduce_node)
blacksheep/testing/client.py
q0w/BlackSheep
420
151372
<gh_stars>100-1000 from typing import Optional from blacksheep.contents import Content from blacksheep.server.application import Application from blacksheep.server.responses import Response from blacksheep.testing.simulator import AbstractTestSimulator, TestSimulator from .helpers import CookiesType, HeadersType, QueryType class TestClient: # Setting this dunder variable # We tell to pytest don't discover this up __test__ = False def __init__( self, app: Application, test_simulator: Optional[AbstractTestSimulator] = None ): self._test_simulator = test_simulator or TestSimulator(app) async def get( self, path: str, headers: HeadersType = None, query: QueryType = None, cookies: CookiesType = None, ) -> Response: """Simulates HTTP GET method""" return await self._test_simulator.send_request( method="GET", path=path, headers=headers, query=query, cookies=cookies, content=None, ) async def post( self, path: str, headers: HeadersType = None, query: QueryType = None, content: Optional[Content] = None, cookies: CookiesType = None, ) -> Response: """Simulates HTTP POST method""" return await self._test_simulator.send_request( method="POST", path=path, headers=headers, query=query, cookies=cookies, content=content, ) async def patch( self, path: str, headers: HeadersType = None, query: QueryType = None, content: Optional[Content] = None, cookies: CookiesType = None, ) -> Response: """Simulates HTTP PATCH method""" return await self._test_simulator.send_request( method="PATCH", path=path, headers=headers, query=query, cookies=cookies, content=content, ) async def put( self, path: str, headers: HeadersType = None, query: QueryType = None, content: Optional[Content] = None, cookies: CookiesType = None, ) -> Response: """Simulates HTTP PUT method""" return await self._test_simulator.send_request( method="PUT", path=path, headers=headers, query=query, content=content, cookies=cookies, ) async def delete( self, path: str, headers: HeadersType = None, query: QueryType = None, content: Optional[Content] = None, cookies: CookiesType = None, ) -> Response: """Simulates HTTP DELETE method""" return await self._test_simulator.send_request( method="DELETE", path=path, headers=headers, query=query, content=content, cookies=cookies, ) async def options( self, path: str, headers: HeadersType = None, query: QueryType = None, cookies: CookiesType = None, ) -> Response: """Simulates HTTP OPTIONS method""" return await self._test_simulator.send_request( method="OPTIONS", path=path, headers=headers, query=query, content=None, cookies=cookies, ) async def head( self, path: str, headers: HeadersType = None, query: QueryType = None, cookies: CookiesType = None, ) -> Response: """Simulates HTTP HEAD method""" return await self._test_simulator.send_request( method="HEAD", path=path, headers=headers, query=query, content=None, cookies=cookies, ) async def trace( self, path: str, headers: HeadersType = None, query: QueryType = None, cookies: CookiesType = None, ) -> Response: """Simulates HTTP TRACE method""" return await self._test_simulator.send_request( method="TRACE", path=path, headers=headers, query=query, content=None, cookies=cookies, )
desktop/core/ext-py/docutils-0.14/test/test_readers/test_pep/test_inline_markup.py
kokosing/hue
5,079
151374
#! /usr/bin/env python # $Id: test_inline_markup.py 7793 2015-02-17 14:55:01Z milde $ # Author: <NAME> <<EMAIL>> # Copyright: This module has been placed in the public domain. """ Tests for inline markup in PEPs (readers/pep.py). """ from __init__ import DocutilsTestSupport def suite(): s = DocutilsTestSupport.PEPParserTestSuite() s.generateTests(totest) return s totest = {} totest['standalone_references'] = [ ["""\ See PEP 287 (pep-0287.txt), and RFC 2822 (which obsoletes RFC822 and RFC-733). """, """\ <document source="test data"> <paragraph> See \n\ <reference refuri="http://www.python.org/dev/peps/pep-0287"> PEP 287 ( <reference refuri="http://www.python.org/dev/peps/pep-0287"> pep-0287.txt ), and \n\ <reference refuri="http://tools.ietf.org/html/rfc2822.html"> RFC 2822 (which obsoletes \n\ <reference refuri="http://tools.ietf.org/html/rfc822.html"> RFC822 and \n\ <reference refuri="http://tools.ietf.org/html/rfc733.html"> RFC-733 ). """], ["""\ References split across lines: PEP 287 RFC 2822 """, """\ <document source="test data"> <paragraph> References split across lines: <paragraph> <reference refuri="http://www.python.org/dev/peps/pep-0287"> PEP 287 <paragraph> <reference refuri="http://tools.ietf.org/html/rfc2822.html"> RFC 2822 """], ["""\ Test PEP-specific implicit references before a URL: PEP 287 (http://www.python.org/dev/peps/pep-0287), RFC 2822. """, """\ <document source="test data"> <paragraph> Test PEP-specific implicit references before a URL: <paragraph> <reference refuri="http://www.python.org/dev/peps/pep-0287"> PEP 287 ( <reference refuri="http://www.python.org/dev/peps/pep-0287"> http://www.python.org/dev/peps/pep-0287 ), \n\ <reference refuri="http://tools.ietf.org/html/rfc2822.html"> RFC 2822 . """], ] totest['miscellaneous'] = [ ["""\ For *completeness*, _`let's` ``test`` **other** forms_ |of| `inline markup` [*]_. .. [*] See http://docutils.sf.net/docs/ref/rst/restructuredtext.html. """, """\ <document source="test data"> <paragraph> For \n\ <emphasis> completeness , \n\ <target ids="let-s" names="let's"> let's \n\ <literal> test \n\ <strong> other \n\ <reference name="forms" refname="forms"> forms \n\ <substitution_reference refname="of"> of \n\ <title_reference> inline markup \n\ <footnote_reference auto="*" ids="id1"> . <footnote auto="*" ids="id2"> <paragraph> See \n\ <reference refuri="http://docutils.sf.net/docs/ref/rst/restructuredtext.html"> http://docutils.sf.net/docs/ref/rst/restructuredtext.html . """], ] if __name__ == '__main__': import unittest unittest.main(defaultTest='suite')
courses/backend/django-for-everybody/Web Application Technologies and Django/resources/dj4e-samples/bookone/apps.py
Nahid-Hassan/fullstack-software-development
297
151410
from django.apps import AppConfig class BookoneConfig(AppConfig): name = 'bookone'
combo/models/cluster_comb.py
vishalbelsare/combo
611
151412
# -*- coding: utf-8 -*- """A collection of combination methods for clustering """ # Author: <NAME> <<EMAIL>> # License: BSD 2 clause import numpy as np from sklearn.utils import check_array from sklearn.utils.validation import check_is_fitted from numpy.testing import assert_equal from pyod.utils.utility import check_parameter from .base import BaseAggregator from .score_comb import majority_vote OFFSET_FACTOR = 1000000 class ClustererEnsemble(BaseAggregator): """Clusterer Ensemble combines multiple base clustering estimators by alignment. See :cite:`zhou2006clusterer` for details. Parameters ---------- base_estimators : list or numpy array of shape (n_estimators,) A list of base estimators. Estimators must have a `labels_` attribute once fitted. Sklearn clustering estimators are recommended. n_clusters : int, optional (default=8) The number of clusters. weights : numpy array of shape (n_estimators,) Estimator weights. May be used after the alignment. reference_idx : int in range [0, n_estimators-1], optional (default=0) The ith base estimator used as the reference for label alignment. pre_fitted : bool, optional (default=False) Whether the base estimators are trained. If True, `fit` process may be skipped. Attributes ---------- labels_ : int The predicted label of the fitted data. """ def __init__(self, base_estimators, n_clusters, weights=None, reference_idx=0, pre_fitted=False): super(ClustererEnsemble, self).__init__( base_estimators=base_estimators, pre_fitted=pre_fitted) check_parameter(n_clusters, low=2, param_name='n_clusters') self.n_clusters = n_clusters check_parameter(reference_idx, low=0, high=self.n_base_estimators_ - 1, include_left=True, include_right=True) self.reference_idx = reference_idx # set estimator weights self._set_weights(weights) def fit(self, X): """Fit estimators. Parameters ---------- X : numpy array of shape (n_samples, n_features) The input samples. """ # Validate inputs X X = check_array(X) # initialize the score matrix to store the results original_labels = np.zeros([X.shape[0], self.n_base_estimators_]) if self.pre_fitted: print("Training Skipped") else: for clf in self.base_estimators: clf.fit(X) clf.fitted_ = True for i, estimator in enumerate(self.base_estimators): check_is_fitted(estimator, ['labels_']) original_labels[:, i] = estimator.labels_ self.original_labels_ = original_labels # get the aligned result self.labels_, self.aligned_labels_ = clusterer_ensemble_scores( original_labels, self.n_base_estimators_, n_clusters=self.n_clusters, weights=self.weights, return_results=True, reference_idx=self.reference_idx) def predict(self, X): """Predict the class labels for the provided data. Parameters ---------- X : numpy array of shape (n_samples, n_features) The input samples. Returns ------- labels : numpy array of shape (n_samples,) Class labels for each data sample. """ # TODO: decide whether enable predict function for clustering raise NotImplemented("predict function is currently disabled for" "clustering due to inconsistent behaviours.") # Validate inputs X X = check_array(X) # initialize the score matrix to store the results original_labels = np.zeros([X.shape[0], self.n_base_estimators_]) for i, estimator in enumerate(self.base_estimators): check_is_fitted(estimator, ['labels_']) original_labels[:, i] = estimator.predict(X) # get the aligned result predicted_labels = clusterer_ensemble_scores( original_labels, self.n_base_estimators_, n_clusters=self.n_clusters, weights=self.weights, return_results=False, reference_idx=self.reference_idx) return predicted_labels def predict_proba(self, X): """Predict the class labels for the provided data. Parameters ---------- X : numpy array of shape (n_samples, n_features) The input samples. Returns ------- labels : numpy array of shape (n_samples,) Class labels for each data sample. """ raise NotImplemented("predict_proba function is currently disabled for" "clustering due to inconsistent behaviours.") def fit_predict(self, X, y=None): """Fit estimator and predict on X. y is optional for unsupervised methods. Parameters ---------- X : numpy array of shape (n_samples, n_features) The input samples. y : numpy array of shape (n_samples,), optional (default=None) The ground truth of the input samples (labels). Returns ------- labels : numpy array of shape (n_samples,) Cluster labels for each data sample. """ self.fit(X) return self.labels_ def clusterer_ensemble_scores(original_labels, n_estimators, n_clusters, weights=None, return_results=False, reference_idx=0): """Function to align the raw clustering results from base estimators. Different from ClustererEnsemble class, this function takes in the output from base estimators directly without training and prediction. Parameters ---------- original_labels : numpy array of shape (n_samples, n_estimators) The raw output from base estimators n_estimators : int The number of base estimators. n_clusters : int, optional (default=8) The number of clusters. weights : numpy array of shape (1, n_estimators) Estimators weights. return_results : bool, optional (default=False) If True, also return the aligned label matrix. reference_idx : int in range [0, n_estimators-1], optional (default=0) The ith base estimator used as the reference for label alignment. Returns ------- aligned_labels : numpy array of shape (n_samples, n_estimators) The aligned label results by using reference_idx estimator as the reference. """ original_labels = _validate_cluster_number(original_labels, n_clusters) alignment_mat = np.zeros([n_clusters, n_estimators]) aligned_labels = np.copy(original_labels) for i in range(n_estimators): inter_mat = _intersection_mat(original_labels, reference_idx, i, n_clusters) index_mapping = _alignment(inter_mat, n_clusters, i, aligned_labels, OFFSET_FACTOR) alignment_mat[:, i] = index_mapping[:, 1] aligned_labels = aligned_labels - OFFSET_FACTOR if weights is not None: assert_equal(original_labels.shape[1], weights.shape[1]) # equal weights if not set else: weights = np.ones([1, n_estimators]) labels_by_vote = majority_vote(aligned_labels, n_classes=n_clusters, weights=weights) if return_results: return labels_by_vote.astype(int), aligned_labels.astype(int) else: return labels_by_vote.astype(int) def _intersection_mat(result_mat, first_idx, second_idx, n_clusters): """Calculate the number of overlappings of second_idx based on first_idx. alignment_mat[i,j] represents the number of labels == j in second_idx when labels == i in the first idx. In other words, we should do the alignment based on the max by first assigning the most Parameters ---------- result_mat first_idx second_idx n_clusters Returns ------- """ alignment_mat = np.zeros([n_clusters, n_clusters]) for i in range(n_clusters): for j in range(n_clusters): i_index = np.argwhere(result_mat[:, first_idx] == i) j_index = np.argwhere(result_mat[:, second_idx] == j) inter_ij = np.intersect1d(i_index, j_index) alignment_mat[i, j] = len(inter_ij) return alignment_mat def _alignment(inter_mat, n_clusters, second_idx, result_mat_aligned, offset=OFFSET_FACTOR): index_mapping = np.zeros([n_clusters, 2]) index_mapping[:, 0] = list(range(0, n_clusters)) while np.sum(inter_mat) > (-1 * n_clusters * n_clusters): max_i, max_j = np.unravel_index(inter_mat.argmax(), inter_mat.shape) index_mapping[max_i, 1] = max_j inter_mat[max_i, :] = -1 inter_mat[:, max_j] = -1 # print('component 1 cluser', max_i, '==', 'component 2 cluser', max_j) result_mat_aligned[ np.where(result_mat_aligned[:, second_idx] == max_j), second_idx] \ = max_i + offset return index_mapping def _validate_cluster_number(original_results, n_clusters): """validate all estimators form the same number of clusters as defined in n_clusters. Parameters ---------- original_results : n_clusters Returns ------- """ original_results = check_array(original_results) for i in range(original_results.shape[1]): values, counts = np.unique(original_results[:, i], return_counts=True) if len(values) != n_clusters: print(len(values), len(counts)) RuntimeError('cluster result does not equal to n_clusters') return original_results
wagtailmenus/migrations/0014_auto_20160423_1339.py
pierremanceaux/wagtailmenus
329
151433
# -*- coding: utf-8 -*- # Generated by Django 1.9.5 on 2016-04-23 12:39 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('wagtailmenus', '0013_auto_20160423_1124'), ] operations = [ migrations.AlterField( model_name='flatmenuitem', name='allow_subnav', field=models.BooleanField(default=False, help_text='NOTE: The sub-menu might might not be displayed, even if checked. It depends on how the menu is being used within your project.', verbose_name='allow sub-menu for this item'), ), migrations.AlterField( model_name='mainmenuitem', name='allow_subnav', field=models.BooleanField(default=True, help_text='NOTE: The sub-menu might might not be displayed, even if checked. It depends on how the menu is being used within your project.', verbose_name='allow sub-menu for this item'), ), ]
ktrain/text/ner/anago/__init__.py
RobWillison/ktrain
1,013
151441
<gh_stars>1000+ from .tagger import Tagger from .trainer import Trainer from .wrapper import Sequence
tcfcli/common/user_config.py
tencentyun/scfcli
103
151455
# -*- coding: utf-8 -*- import os import platform from tcfcli.common.user_exceptions import * home = os.path.expanduser('~') _USER_CONFIG_FILE = home + '/.tcli_config.ini' version = platform.python_version() if version >= '3': from configparser import ConfigParser else: from ConfigParser import ConfigParser class CliConfigParser(ConfigParser): def __init__(self, defaults=None): ConfigParser.__init__(self, defaults=None) # super(CliConfigParser, self).__init__(defaults) def optionxform(self, optionstr): return optionstr class UserConfig(object): API = "API" USER_QCLOUD_CONFIG = "USER_QCLOUD_CONFIG" GIT_CONFIG = "GIT_CONFIG" ENV = "ENV" OTHERS = "OTHERS" SECTION_LIST = [USER_QCLOUD_CONFIG, GIT_CONFIG, ENV, OTHERS] COMMON_SECTION_LIST = [GIT_CONFIG, ENV, OTHERS] def __init__(self): self.secret_id = "None" self.secret_key = "None" self.region = "None" self.appid = "None" self.using_cos = "False (By default, it isn't deployed by COS.)" self.python2_path = "None" self.python3_path = "None" self.version_time = "None" self.section_map = { UserConfig.USER_QCLOUD_CONFIG: { "secret_id": "None", "secret_key": "None", "region": "None", "appid": "None", "using_cos": "False (By default, it isn't deployed by COS.)" }, UserConfig.GIT_CONFIG: { "git_url": "None", "git_username": "None", "git_password": "<PASSWORD>" }, UserConfig.ENV: { "python2_path": "None", "python3_path": "None", }, UserConfig.OTHERS: { "curr_user": "None", "version_time": "None", "no_color": "False", "language": "None", "allow_report": "True", } } self._migrate() self._load_config() self._dumpattr() # 新老配置迁移函数 def _migrate(self): cf = CliConfigParser() cf.read(_USER_CONFIG_FILE) # 读取旧的section数据 if UserConfig.API in cf.sections(): attrs = {} for attrs_keys in cf.options(UserConfig.API): attrs[self._name_attr2obj(attrs_keys)] = cf.get(UserConfig.API, attrs_keys) self.set_attrs(attrs) self.section_map[UserConfig.OTHERS]['curr_user'] = 'USER_'+str(1) self._dump_config() def _dumpattr(self): self.secret_id = self.section_map[UserConfig.USER_QCLOUD_CONFIG]['secret_id'] self.secret_key = self.section_map[UserConfig.USER_QCLOUD_CONFIG]['secret_key'] self.region = self.section_map[UserConfig.USER_QCLOUD_CONFIG]['region'] self.appid = self.section_map[UserConfig.USER_QCLOUD_CONFIG]['appid'] self.using_cos = self.section_map[UserConfig.USER_QCLOUD_CONFIG]['using_cos'] self.python2_path = self.section_map[UserConfig.ENV]['python2_path'] self.python3_path = self.section_map[UserConfig.ENV]['python3_path'] self.version_time = self.section_map[UserConfig.OTHERS]['version_time'] def set_attrs(self, attrs): for section in self.section_map: # 只设置当前用户和公共配置 if section not in UserConfig.SECTION_LIST: continue for key in list(self.section_map[section].keys()): # 更新section_map中存在的配置变量 if key in list(attrs.keys()) and attrs[key]: self.section_map[section][key] = attrs[key] def get_attrs(self, attrs): ret = {} for attr_key in [k for k, v in attrs.items() if v]: for section in self.section_map: if section not in UserConfig.SECTION_LIST: continue if self._name_attr2obj(attr_key) in self.section_map[section].keys(): ret[self._name_attr2obj(attr_key)] = self.section_map[section][self._name_attr2obj(attr_key)] return ret def flush(self): self._dump_config() def _get_curr_user_section(self): cf = CliConfigParser() if not cf.read(_USER_CONFIG_FILE): return None if UserConfig.OTHERS not in cf.sections(): return None return cf.get(UserConfig.OTHERS, self._name_obj2attr('curr_user')) def get_all_user(self): cf = CliConfigParser() userlist = [] if not cf.read(_USER_CONFIG_FILE): return None for section in cf.sections(): # 若有新版本用户标志section,不迁移 if section.startswith('USER_'): userlist.append(section) return userlist def add_user(self, data): userlist = self.get_all_user() user_section = 'USER_' for i in range(100): user_section = 'USER_'+str(i+1) if user_section not in userlist: break if i >= 99: raise UserLimitException("Amount of Users Limit!") self.section_map[user_section] = {} format_data = {} for k in data: format_data[self._name_attr2obj(k)] = data[k] for key in list(self.section_map[UserConfig.USER_QCLOUD_CONFIG].keys()): if key in format_data and format_data[key]: self.section_map[user_section][key] = format_data[key] elif key == 'using_cos': self.section_map[user_section][key] = "False (By default, it isn't deployed by COS.)" else: self.section_map[user_section][key] = "None" return user_section def changeuser(self, user): self.section_map[UserConfig.OTHERS]['curr_user'] = user for key in list(self.section_map[UserConfig.USER_QCLOUD_CONFIG].keys()): self.section_map[UserConfig.USER_QCLOUD_CONFIG][key] = self.section_map[user][key] def get_user_info(self, user): data = {} data['appid'] = self.section_map[user]['appid'] data['secret_id'] = self.section_map[user]['secret_id'] data['secret_key'] = self.section_map[user]['secret_key'] data['region'] = self.section_map[user]['region'] data['using_cos'] = self.section_map[user]['using_cos'] return data def _load_config(self): cf = CliConfigParser() if not cf.read(_USER_CONFIG_FILE): return # 从配置文件获取当前用户 curr_user = self._get_curr_user_section() if not curr_user: return for section in cf.sections(): if section not in UserConfig.SECTION_LIST and not section.startswith('USER_'): continue attrs = cf.options(section) # 获取当前用户配置到对象 if section == curr_user: for attr in attrs: if self._name_attr2obj(attr) in list(self.section_map[UserConfig.USER_QCLOUD_CONFIG].keys()): self.section_map[UserConfig.USER_QCLOUD_CONFIG][self._name_attr2obj(attr)] = cf.get(section, attr) # 获取所有用户配置到对象 if section.startswith('USER_'): self.section_map[section] = {} for key in list(self.section_map[UserConfig.USER_QCLOUD_CONFIG].keys()): if self._name_obj2attr(key) in attrs: self.section_map[section][key] = cf.get(section, self._name_obj2attr(key)) else: self.section_map[section][key] = 'None' # 获取共有配置到对象 else: for attr in attrs: if self._name_attr2obj(attr) in list(self.section_map[section].keys()): self.section_map[section][self._name_attr2obj(attr)] = cf.get(section, attr) def _dump_config(self): cf = CliConfigParser() # 保证先遍历到USER_QCLOUD_CONFIG for section in sorted(list(self.section_map.keys()), reverse=True): # 当前用户的配置 if section == UserConfig.USER_QCLOUD_CONFIG: curr_user = self.section_map[UserConfig.OTHERS]['curr_user'] # 当前用户非User_开头,强制修正为user_1 if not curr_user.startswith('USER_'): self.section_map[UserConfig.OTHERS]['curr_user'] = 'USER_1' curr_user = 'USER_1' cf.add_section(curr_user) for key in list(self.section_map[section].keys()): if self.section_map[section][key]: cf.set(curr_user, self._name_obj2attr(key), self.section_map[section][key]) # 其他用户列表的配置 elif section.startswith('USER_') and section != self.section_map[UserConfig.OTHERS]['curr_user']: cf.add_section(section) for key in list(self.section_map[UserConfig.USER_QCLOUD_CONFIG].keys()): if self.section_map[section][key]: cf.set(section, self._name_obj2attr(key), self.section_map[section][key]) # 公用配置 elif section in UserConfig.COMMON_SECTION_LIST: cf.add_section(section) for key in list(self.section_map[section].keys()): if self.section_map[section][key]: cf.set(section, self._name_obj2attr(key), self.section_map[section][key]) with open(_USER_CONFIG_FILE, "w") as f: cf.write(f) @staticmethod def _name_attr2obj(name): return name.replace("-", "_") @staticmethod def _name_obj2attr(name): return name.replace("_", "-") if __name__ == '__main__': uc = UserConfig() # print uc.get_attrs({"secret-sssd": True, "region": False, "secret-key": "000000000"}) # print uc.get_attrs({"secret-id": True, "region": True, "secret-key": "000000000"}) # uc.set_attrs({"region":"asss-gz"}) # uc.flush() print(uc.get_attrs({"region": True, "secret-key": "000000000"}))
ioflo/aid/test/test_timing.py
BradyHammond/ioflo
128
151457
# -*- coding: utf-8 -*- """ Unit Test Template """ from __future__ import absolute_import, division, print_function import sys import unittest import os import datetime from ioflo.aid.sixing import * from ioflo.aid.odicting import odict from ioflo.test import testing from ioflo.aid.consoling import getConsole console = getConsole() from ioflo.aid import timing def setUpModule(): console.reinit(verbosity=console.Wordage.concise) def tearDownModule(): console.reinit(verbosity=console.Wordage.concise) class BasicTestCase(unittest.TestCase): """ Example TestCase """ def setUp(self): """ Call super if override so House Framer and Frame are setup correctly """ super(BasicTestCase, self).setUp() console.reinit(verbosity=console.Wordage.profuse) def tearDown(self): """ Call super if override so House Framer and Frame are torn down correctly """ super(BasicTestCase, self).tearDown() console.reinit(verbosity=console.Wordage.concise) def testTimestamp(self): """ Test posix timestamp generation """ console.terse("{0}\n".format(self.testTimestamp.__doc__)) if hasattr(datetime, "timezone"): # python3.2+ dt = datetime.datetime.now(datetime.timezone.utc) older = (dt - datetime.datetime(1970, 1, 1, tzinfo=datetime.timezone.utc)).total_seconds() else: dt = datetime.datetime.utcnow() # not aware older = (dt - datetime.datetime(1970, 1, 1)).total_seconds() ts = timing.timestamp() self.assertNotEqual(ts, 0.0) self.assertGreaterEqual(ts, older) ts = timing.timestamp(dt=dt) self.assertNotEqual(ts, 0.0) self.assertEqual(ts, older) def testIso8601(self): """ Test iso8601 generation """ console.terse("{0}\n".format(self.testIso8601.__doc__)) stamp = timing.iso8601() self.assertEqual(len(stamp), 26) dt = datetime.datetime(2000, 1, 1) stamp = timing.iso8601(dt) self.assertEqual(stamp, "2000-01-01T00:00:00") stamp = timing.iso8601(aware=True) if hasattr(datetime, 'timezone'): # only aware in python3.2+ self.assertEqual(len(stamp), 32) # '2017-02-07T23:47:16.498821+00:00' else: self.assertEqual(len(stamp), 26) # '2017-08-14T16:19:36.070661' if hasattr(datetime, "timezone"): # python3.2+ dt = datetime.datetime(2000, 1, 1, tzinfo=datetime.timezone.utc) stamp = timing.iso8601(dt, aware=True) self.assertEqual(stamp, "2000-01-01T00:00:00+00:00") else: dt = datetime.datetime(2000, 1, 1) stamp = timing.iso8601(dt) self.assertEqual(stamp, "2000-01-01T00:00:00") def testTuuid(self): """ Test TUUID generation """ console.terse("{0}\n".format(self.testTuuid.__doc__)) tuid = timing.tuuid() self.assertEqual(len(tuid), 24) stamp, sep, randomized = tuid.rpartition('_') self.assertEqual(sep, '_') self.assertEqual(len(stamp), 16) self.assertEqual(len(randomized), 7) tuid = timing.tuuid(9) self.assertEqual(len(tuid), 24) stamp, sep, randomized = tuid.rpartition('_') self.assertEqual(sep, '_') self.assertEqual(len(stamp), 16) self.assertEqual(len(randomized), 7) self.assertEqual(stamp[:16], '0000000000895440' ) tuid = timing.tuuid(stamp=9, prefix="m") self.assertEqual(len(tuid), 26) prefix, stamp, randomized = tuid.split('_') self.assertEqual(prefix, 'm') self.assertEqual(len(stamp), 16) self.assertEqual(len(randomized), 7) self.assertEqual(stamp[:16], '0000000000895440' ) def testStamper(self): """ Test Stamper Class """ console.terse("{0}\n".format(self.testStamper.__doc__)) stamper = timing.Stamper() self.assertEqual(stamper.stamp, 0.0) stamper.advanceStamp(0.25) self.assertEqual(stamper.stamp, 0.25) stamper.advance(0.25) self.assertEqual(stamper.stamp, 0.5) stamper.change(1.5) self.assertEqual(stamper.stamp, 1.5) def runOne(test): ''' Unittest Runner ''' test = BasicTestCase(test) suite = unittest.TestSuite([test]) unittest.TextTestRunner(verbosity=2).run(suite) def runSome(): """ Unittest runner """ tests = [] names = [ 'testTimestamp', 'testIso8601', 'testTuuid', 'testStamper', ] tests.extend(map(BasicTestCase, names)) suite = unittest.TestSuite(tests) unittest.TextTestRunner(verbosity=2).run(suite) def runAll(): """ Unittest runner """ suite = unittest.TestSuite() suite.addTest(unittest.TestLoader().loadTestsFromTestCase(BasicTestCase)) unittest.TextTestRunner(verbosity=2).run(suite) if __name__ == '__main__' and __package__ is None: #console.reinit(verbosity=console.Wordage.concise) #runAll() #run all unittests runSome()#only run some #runOne('testBasic')
python/src/nnabla/utils/converter/supported_info.py
daniel-falk/nnabla
2,792
151467
# Copyright 2018,2019,2020,2021 Sony Corporation. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the 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 in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import collections _SupportedInfo = collections.namedtuple( '_SupportedInfo', 'import_name export_name') extensions = _SupportedInfo(import_name=['.nnp', '.onnx', '.ckpt', '.meta', '.pb', 'saved_model', '.tflite'], export_name=[ '.nnp', '.nnb', '.onnx', '.tflite', 'saved_model', '.pb']) formats = _SupportedInfo(import_name=['NNP', 'ONNX', 'TF_CKPT_V1', 'TF_CKPT_V2', 'TF_PB', 'SAVED_MODEL', 'TFLITE'], export_name=[ 'NNP', 'NNB', 'CSRC', 'ONNX', 'SAVED_MODEL', 'TFLITE', 'TF_PB'])
indra/sources/geneways/processor.py
zebulon2/indra
136
151473
""" This module provides an input processor for information extracted using the Geneways software suite, converting extraction data in Geneways format into INDRA statements. See publication: Rzhetsky, Andrey, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME> et al. "GeneWays: a system for extracting, analyzing, visualizing, and integrating molecular pathway data." Journal of biomedical informatics 37, no. 1 (2004): 43-53. """ from indra.statements import Evidence, Agent import indra.databases.hgnc_client as hgc from indra.literature import * from indra.statements import Complex, Phosphorylation from indra.ontology.standardize import \ standardize_agent_name from indra.sources.geneways.action_parser import GenewaysActionParser try: from indra.sources.geneways.find_full_text_sentence import FullTextMention get_ft_mention = True except ImportError: logger.error('Install the nltk and stemming packages to extract full ' 'text evidence for Geneways mentions.') get_ft_mention = False logger = logging.getLogger(__name__) # This will take in an action and action mention and create a single statement class GenewaysProcessor(object): """The GenewaysProcessors converts extracted Geneways action mentions into INDRA statements. Parameters ---------- search_path : list[str] A list of directories in which to search for Geneways data Attributes ---------- statements : list[indra.statements.Statement] A list of INDRA statements converted from Geneways action mentions, populated by calling the constructor """ def __init__(self, search_path, get_evidence=True): if get_evidence and get_ft_mention: self.get_ft_mention = True else: self.get_ft_mention = False # Parse Geneways data. Will give an error if it can't find # the Geneways data logger.info('Loading Geneways extractions') parser = GenewaysActionParser(search_path) logger.info('Geneways extractions loaded') actions = parser.actions # Make a list of statements from the actions self.statements = [] for action in actions: for mention in action.action_mentions: if mention.negative != '1': new_statement = self.make_statement(action, mention) if new_statement is not None: self.statements.append(new_statement) def make_statement(self, action, mention): """Makes an INDRA statement from a Geneways action and action mention. Parameters ---------- action : GenewaysAction The mechanism that the Geneways mention maps to. Note that several text mentions can correspond to the same action if they are referring to the same relationship - there may be multiple Geneways action mentions corresponding to each action. mention : GenewaysActionMention The Geneways action mention object corresponding to a single mention of a mechanism in a specific text. We make a new INDRA statement corresponding to each action mention. Returns ------- statement : indra.statements.Statement An INDRA statement corresponding to the provided Geneways action mention, or None if the action mention's type does not map onto any INDRA statement type in geneways_action_type_mapper. """ (statement_generator, is_direct) = \ geneways_action_to_indra_statement_type(mention.actiontype, action.plo) if statement_generator is None: # Geneways statement does not map onto an indra statement return None # Try to find the full-text sentence # Unfortunately, the sentence numbers in the Geneways dataset # don't correspond to an obvious sentence segmentation. # This code looks for sentences with the subject, object, and verb # listed by the Geneways action mention table and only includes # it in the evidence if there is exactly one such sentence text = None if self.get_ft_mention: try: content, content_type = get_full_text(mention.pmid, 'pmid') if content is not None: ftm = FullTextMention(mention, content) sentences = ftm.find_matching_sentences() if len(sentences) == 1: text = sentences[0] except Exception: logger.warning('Could not fetch full text for PMID ' + mention.pmid) # Make an evidence object epistemics = dict() epistemics['direct'] = is_direct annotations = mention.make_annotation() annotations['plo'] = action.plo # plo only in action table evidence = Evidence(source_api='geneways', source_id=mention.actionmentionid, pmid=mention.pmid, text=text, epistemics=epistemics, annotations=annotations) # Construct the grounded and name standardized agents # Note that this involves grounding the agent by # converting the Entrez ID listed in the Geneways data with # HGNC and UniProt upstream_agent = get_agent(mention.upstream, action.up) downstream_agent = get_agent(mention.downstream, action.dn) # Make the statement return statement_generator(upstream_agent, downstream_agent, evidence) def get_agent(raw_name, entrez_id): db_refs = {'TEXT': raw_name, 'EGID': entrez_id} logger.debug('Looking up grounding data for Entrez #%s' % entrez_id) hgnc_id = hgc.get_hgnc_from_entrez(entrez_id) if hgnc_id: db_refs['HGNC'] = hgnc_id agent = Agent(raw_name, db_refs=db_refs) standardize_agent_name(agent, standardize_refs=True) return agent def geneways_action_to_indra_statement_type(actiontype, plo): """Return INDRA Statement corresponding to Geneways action type. Parameters ---------- actiontype : str The verb extracted by the Geneways processor plo : str A one character string designating whether Geneways classifies this verb as a physical, logical, or other interaction Returns ------- statement_generator : If there is no mapping to INDRA statements from this action type the return value is None. If there is such a mapping, statement_generator is an anonymous function that takes in the subject agent, object agent, and evidence, in that order, and returns an INDRA statement object. """ actiontype = actiontype.lower() statement_generator = None is_direct = (plo == 'P') if actiontype == 'bind': statement_generator = lambda substance1, substance2, evidence: \ Complex([substance1, substance2], evidence=evidence) is_direct = True elif actiontype == 'phosphorylate': statement_generator = lambda substance1, substance2, evidence: \ Phosphorylation(substance1, substance2, evidence=evidence) is_direct = True return (statement_generator, is_direct)
reviewboard/admin/tests/test_change_form_fieldset.py
seekingalpha/reviewboard
921
151478
<filename>reviewboard/admin/tests/test_change_form_fieldset.py """Unit tests for reviewboard.admin.forms.change_form.ChangeFormFieldset.""" from __future__ import unicode_literals from django.contrib.admin.helpers import AdminForm from django.contrib.auth.models import User from reviewboard.admin import admin_site from reviewboard.admin.forms.change_form import (ChangeFormFieldset, ChangeFormRow) from reviewboard.testing.testcase import TestCase from reviewboard.admin.templatetags.rbadmintags import change_form_fieldsets class ChangeFormFieldsetTests(TestCase): """Unit tests for ChangeFormFieldset.""" def setUp(self): super(ChangeFormFieldsetTests, self).setUp() request = self.create_http_request() model_admin = admin_site.get_model_admin(User) self.admin_form = AdminForm( form=model_admin.get_form(request)(), fieldsets=list(model_admin.get_fieldsets(request)), prepopulated_fields=model_admin.get_prepopulated_fields(request), readonly_fields=model_admin.get_readonly_fields(request), model_admin=model_admin) def test_init_normalizes_classes(self): """Testing ChangeFormFieldset.__init__ normalizes Django fieldset CSS classes """ fieldset = ChangeFormFieldset(form=self.admin_form, classes=('collapse', 'wide', '-is-test')) self.assertEqual( fieldset.classes, 'rb-c-form-fieldset -can-collapse -is-collapsed -is-wide -is-test') def test_collapsed_with_true(self): """Testing ChangeFormFieldset.collapsed with Django collapse CSS class """ fieldset = ChangeFormFieldset(form=self.admin_form, classes=('collapse',)) self.assertTrue(fieldset.collapsed) def test_collapsed_with_false(self): """Testing ChangeFormFieldset.collapsed without Django collapse CSS class """ fieldset = ChangeFormFieldset(form=self.admin_form) self.assertFalse(fieldset.collapsed) def test_iter(self): """Testing ChangeFormFieldset.__iter__""" fieldset = list(change_form_fieldsets(self.admin_form))[0] rows = list(fieldset) self.assertGreater(len(rows), 0) for row in rows: self.assertIsInstance(row, ChangeFormRow)
utildialog/confirmdialog.py
dragondjf/QMarkdowner
115
151488
#!/usr/bin/python # -*- coding: utf-8 -*- import os from qframer.qt import QtGui from qframer.qt import QtCore from basedialog import BaseDialog class ConfirmDialog(BaseDialog): def __init__(self, text, styleoptions, parent=None): super(ConfirmDialog, self).__init__(styleoptions, parent) # message内容提示 self.msglabel = QtGui.QLabel(text) self.msglabel.setAlignment(QtCore.Qt.AlignCenter) #确认按钮布局 self.enterwidget = QtGui.QWidget() self.pbEnter = QtGui.QPushButton(u'确定', self) self.pbCancel = QtGui.QPushButton(u'取消', self) self.pbEnter.clicked.connect(self.enter) self.pbCancel.clicked.connect(self.close) enterwidget_mainlayout = QtGui.QGridLayout() enterwidget_mainlayout.addWidget(self.pbEnter, 0, 0) enterwidget_mainlayout.addWidget(self.pbCancel, 0, 1) self.enterwidget.setLayout(enterwidget_mainlayout) self.layout().addWidget(self.msglabel) self.layout().addWidget(self.enterwidget) self.resize(self.width(), self.height()) def enter(self): self.accept() # 关闭对话框并返回1 def confirm(text, styleoptions): """返回True或False""" dialog = ConfirmDialog(text, styleoptions) if dialog.exec_(): return True else: return False if __name__ == '__main__': import sys app = QtGui.QApplication(sys.argv) styleoptions = { 'title': u'消息提示', 'windowicon': os.sep.join([os.path.dirname(__file__), 'utildialogskin', 'images', 'bg.jpg']), 'minsize': (400, 300), 'size': (400, 300), 'logo_title': u'智能光纤云终端管理平台', 'logo_img_url': os.sep.join([os.path.dirname(__file__), 'utildialogskin', 'images', 'bg.jpg']) } print confirm('sddsdsdsdssddsds', styleoptions) sys.exit(app.exec_())
tests/py/test_sync_npm.py
kant/gratipay.com
517
151491
<reponame>kant/gratipay.com # -*- coding: utf-8 -*- from __future__ import absolute_import, division, print_function, unicode_literals from gratipay.testing import Harness from gratipay import sync_npm class ProcessDocTests(Harness): def test_returns_None_if_no_name(self): assert sync_npm.process_doc({}) is None def test_backfills_missing_keys(self): actual = sync_npm.process_doc({'name': 'foo'}) assert actual == {'name': 'foo', 'description': '', 'emails': []} def test_extracts_maintainer_emails(self): doc = {'name': 'foo', 'maintainers': [{'email': '<EMAIL>'}]} assert sync_npm.process_doc(doc)['emails'] == ['<EMAIL>'] def test_skips_empty_emails(self): doc = {'name': 'foo', 'maintainers': [{'email': ''}, {'email': ' '}]} assert sync_npm.process_doc(doc)['emails'] == [] def test_sorts_emails(self): doc = {'name': 'foo', 'maintainers': [{'email': 'bob'}, {'email': 'alice'}]} assert sync_npm.process_doc(doc)['emails'] == ['alice', 'bob'] def test_dedupes_emails(self): doc = {'name': 'foo', 'maintainers': [{'email': 'alice'}, {'email': 'alice'}]} assert sync_npm.process_doc(doc)['emails'] == ['alice'] class ConsumeChangeStreamTests(Harness): def change_stream(self, changes): for i, change in enumerate(changes): change['seq'] = i yield change def test_packages_starts_empty(self): assert self.db.all('select * from packages') == [] def test_consumes_change_stream(self): docs = [ {'doc': {'name': 'foo', 'description': 'Foo.'}} , {'doc': {'name': 'foo', 'description': 'Foo?'}} , {'doc': {'name': 'foo', 'description': 'Foo!'}} ] sync_npm.consume_change_stream(self.change_stream(docs), self.db) package = self.db.one('select * from packages') assert package.package_manager == 'npm' assert package.name == 'foo' assert package.description == 'Foo!' assert package.emails == [] def test_consumes_change_stream_with_missing_doc(self): docs = [ {'doc': {'name': 'foo', 'description': 'Foo.'}} , {'doc': {'name': 'foo', 'description': 'Foo?'}} , {'': {'name': 'foo', 'description': 'Foo!'}} ] sync_npm.consume_change_stream(self.change_stream(docs), self.db) package = self.db.one('select * from packages') assert package.package_manager == 'npm' assert package.name == 'foo' assert package.description == 'Foo?' assert package.emails == [] def test_not_afraid_to_delete_docs(self): docs = [ {'doc': {'name': 'foo', 'description': 'Foo.'}} , {'doc': {'name': 'foo', 'description': 'Foo?'}} , {'deleted': True, 'id': 'foo'} ] sync_npm.consume_change_stream(self.change_stream(docs), self.db) assert self.db.one('select * from packages') is None def test_delete_tolerates_inexistent_packages(self): docs = [{'deleted': True, 'id': 'foo'}] sync_npm.consume_change_stream(self.change_stream(docs), self.db) def test_even_deletes_package_with_linked_team(self): # Set up package linked to team. foo = self.make_package() alice = self.make_participant('alice') with self.db.get_cursor() as cursor: team = foo.get_or_create_linked_team(cursor, alice) assert self.db.one('select p.*::packages from packages p').team == team # Delete package. docs = [{'deleted': True, 'id': 'foo'}] sync_npm.consume_change_stream(self.change_stream(docs), self.db) assert self.db.one('select * from packages') is None def test_sets_last_seq(self): docs = [{'doc': {'name': 'foo', 'description': 'Foo.'}}] * 13 assert self.db.one('select npm_last_seq from worker_coordination') == -1 sync_npm.consume_change_stream(self.change_stream(docs), self.db) assert self.db.one('select npm_last_seq from worker_coordination') == 12 def test_logs_lag(self): captured = {} def capture(message): captured['message'] = message self.db.run('update worker_coordination set npm_last_seq=500') sync_npm.check(self.db, capture) assert captured['message'].startswith('count#npm-sync-lag=') assert captured['message'].split('=')[1].isdigit()
examples/plot_normalize.py
mewbak/hypertools
1,681
151518
<reponame>mewbak/hypertools<gh_stars>1000+ # -*- coding: utf-8 -*- """ ============================= Normalizing your features ============================= Often times its useful to normalize (z-score) you features before plotting, so that they are on the same scale. Otherwise, some features will be weighted more heavily than others when doing PCA, and that may or may not be what you want. The `normalize` kwarg can be passed to the plot function. If `normalize` is set to 'across', the zscore will be computed for the column across all of the lists passed. Conversely, if `normalize` is set to 'within', the z-score will be computed separately for each column in each list. Finally, if `normalize` is set to 'row', each row of the matrix will be zscored. Alternatively, you can use the normalize function found in tools (see the third example). """ # Code source: <NAME> # License: MIT # import import hypertools as hyp import numpy as np import matplotlib.pyplot as plt # simulate data cluster1 = np.random.multivariate_normal(np.zeros(3), np.eye(3), size=100) cluster2 = np.random.multivariate_normal(np.zeros(3)+10, np.eye(3), size=100) data = [cluster1, cluster2] # plot normalized across lists hyp.plot(data, '.', normalize='across', title='Normalized across datasets') # plot normalized within list hyp.plot(data, '.', normalize='within', title='Normalized within dataset') # normalize by row normalized_row = hyp.normalize(data, normalize='row') # plot normalized by row hyp.plot(normalized_row, '.', title='Normalized across row')
modules/api/functional_test/live_tests/internal/color_test.py
slandry90/vinyldns
333
151522
<reponame>slandry90/vinyldns import pytest from hamcrest import * from vinyldns_python import VinylDNSClient def test_color(shared_zone_test_context): """ Tests that the color endpoint works appropriately """ client = shared_zone_test_context.ok_vinyldns_client result = client.color() assert_that(["green", "blue"], has_item(result))
scrapy/douban_login/douban_login/spiders/douban.py
dengwei1999/spider_python
762
151526
<filename>scrapy/douban_login/douban_login/spiders/douban.py # -*- coding: utf-8 -*- import scrapy from urllib import request from PIL import Image import ssl # 使用Scrapy登录豆瓣网 # 验证码识别可以通过手动输入【PIL】和自动识别 class DoubanSpider(scrapy.Spider): name = 'douban' allowed_domains = ['douban.com'] # 默认首先请求这个地址【GET】,然后把请求结果返回给parse()函数解析 start_urls = ['https://accounts.douban.com/login'] # 登录url login_url = 'https://accounts.douban.com/login' # 个人中心url person_center_url = 'https://www.douban.com/people/165725759/' # 编辑签名的请求地址 edit_signature = 'https://www.douban.com/j/people/165725759/edit_signature' def parse(self, response): """ 请求后的解析 包含两种情况:1.第一次请求start_urls;2.某一次请求不包含callback :param response: :return: """ # 注意:把最后的请求解析过滤掉 # 如果解析到相应地址不是login_url就不做处理 if response.url != self.login_url: return print('调用parse函数,此时的url:%s' % response.url) form_data = { 'source': 'index_nav', 'redir': 'https://www.douban.com/', # 登录后跳转到哪个界面 'form_email': '18520876423', 'form_password': '<PASSWORD>', # 'captcha-solution': 'chemical', # 验证码【需要识别图片】 # 'captcha-id': 'ysCwMdnnq8YVpDJZdfmzHu1V:en', # 验证码ID 【每次刷新都重新生成一个,放入到input标签的name为captcha-id的value中】 'remember': 'on', 'login': '登录' } # 获取id为captcha-id的img标签【css方式,也可以选择用xpath】 # 验证码图片的url captcha_img = response.css('img#captcha_image::attr(src)').get() # 注意:如果存在验证码,就识别验证码;如果没有验证码,不传入以下两个参数直接登录 if captcha_img: # 手动识别验证码 captcha = self._regonize_captcha(captcha_img) form_data['captcha-solution'] = captcha # 验证码id【每次刷新都会变化】 captcha_id = response.xpath('//input[@name="captcha-id"]/@value').get() form_data['captcha-id'] = captcha_id print('带有验证码的参数已经补充完整,现在开始发送请求') else: print('没有验证码,现在开始发送请求') # 发送登录请求【POST】 yield scrapy.FormRequest(url=self.login_url, formdata=form_data, callback=self.parse_after_login) def _regonize_captcha(self, image_url): """ 人工识别验证码【urllib+PIL】 :param image_url: :return: """ print('验证码的地址:%s,开始下载图片' % image_url) # 下载图片到本地 request.urlretrieve(image_url, 'captcha.png') print('下载图片完成,开始显示图片') # 显示在控制台,手动输入验证码 # 打开图片 image = Image.open('captcha.png') # 展示 image.show() # 提示输入验证码 captcha = input('请输入验证码:') return captcha def parse_after_login(self, response): """ 登录成功之后,请求【个人中心】 :param response: :return: """ # 当前url current_page_url = response.url print('调用登录接口后,现在的界面是:%s' % current_page_url) if current_page_url == 'https://www.douban.com/': print('登录成功') # 请求个人中心的页面 request = scrapy.Request(url=self.person_center_url, callback=self.parse_person_center) yield request else: print('登录失败') def parse_person_center(self, response): """ 解析个人中心页面 :param response: :return: """ if response.url == self.person_center_url: print('进入到个人中心页面了') ck = response.xpath('//input[@name="ck"]/@value').get() print('获取的ck是:%s' % ck) formdata = { 'ck': ck, 'signature': '时光如水,岁月如斯' } # 发送post请求来更改签名 yield scrapy.FormRequest(self.edit_signature, formdata=formdata) else: print('进入个人中心页面失败')
tests/pylon_tests/emulated/calltest.py
matt-phair/pypylon
358
151529
from pylonemutestcase import PylonEmuTestCase from pypylon import pylon import unittest class CallTestSuite(PylonEmuTestCase): # Tests that you can set the GainRaw parameter of the camera def test_gain_raw(self): cam = self.create_first() cam.Open() # Set GainRaw to min value (192) cam.GainRaw.Value = cam.GainRaw.Min self.assertEqual(192, cam.GainRaw.Value) # Set GainRaw to max value (1023) cam.GainRaw.Value = cam.GainRaw.Max self.assertEqual(1023, cam.GainRaw.Value) # Set GainRaw to 500 cam.GainRaw.Value = 500 self.assertEqual(500, cam.GainRaw.Value) cam.Close() # Tests that you can set the Height parameter of the camera def test_height(self): cam = self.create_first() cam.Open() cam.Height.Value = cam.Height.Min self.assertEqual(1, cam.Height.Value) cam.Height.Value = cam.Height.Max self.assertEqual(4096, cam.Height.Value) cam.Height.Value = 500 self.assertEqual(500, cam.Height.Value) cam.Close() # Tests that you can set the Width parameter of the camera def test_width(self): cam = self.create_first() cam.Open() cam.Width.Value = cam.Width.Min self.assertEqual(1, cam.Width.Value) cam.Width.Value = cam.Width.Max self.assertEqual(4096, cam.Width.Value) cam.Width.Value = 500 self.assertEqual(500, cam.Width.Value) cam.Close() # Tests that you can set the ExposureTimeRaw parameter of the camera def test_exposure_time_raw(self): cam = self.create_first() cam.Open() cam.ExposureTimeRaw.Value = cam.ExposureTimeRaw.Min self.assertEqual(100, cam.ExposureTimeRaw.Value) cam.ExposureTimeRaw.Value = cam.ExposureTimeRaw.Max self.assertEqual(3000000, cam.ExposureTimeRaw.Value) cam.ExposureTimeRaw.Value = 1000 self.assertEqual(1000, cam.ExposureTimeRaw.Value) cam.Close() # Tests that an emulated camera has no hardware interface def test_has_hardware_interface(self): cam = self.create_first() cam.Open() self.assertFalse(cam.Is1394()) self.assertFalse(cam.IsUsb()) self.assertFalse(cam.IsCameraLink()) self.assertFalse(cam.IsGigE()) cam.Close() if __name__ == "__main__": # import sys;sys.argv = ['', 'Test.testName'] unittest.main()
app/migrations/0002_fermentationprofile_notes.py
fossabot/fermentrack
114
151543
# Generated by Django 3.0.6 on 2020-11-05 16:16 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('app', '0001_squashed_0009_auto_20180709_0256'), ] operations = [ migrations.AddField( model_name='fermentationprofile', name='notes', field=models.TextField(blank=True, default='', help_text='Notes about the fermentation profile (Optional)'), ), ]
pes/PES/main.py
git163/Cornell-MOE
218
151586
import functools import warnings import numpy as np import numpy.linalg as npla import sys, os import time from PES.compute_covariance import * from PES.initial_sample import * from PES.hyper_samples import * from PES.utilities import * from PES.sample_minimum import * from PES.PES import * from PES.compute_posterior import * from PES.EP import * from PES.global_optimization import * from PES.target_function import * #The function to run PES to minimize the target function. #Parameters: @target_function: the obejective function we want to minimize # @x_minimum: the lower bounds for each dimension # @x_maximum: the upper bounds for each dimension # @dimension: the dimensions of the objective function # @number_of_hyperparameter_sets: the number of the samples of the hyperparameters of the kernel we want to draw. # It is the M defined in the paper. # @number_of_burnin: number of burnins # @sampling_method: the method used to sample the posterior distribution of the hyperparameters. User can choose # 'mcmc' or 'hmc'. # @number_of_initial_points: the number of samples we want to use as initial observations # @number_of_experiments: number of experiments we want to run. For each experiment, we use different randomizations # for starting points. # @number_of_iterations: number of iterations we want to run for each experiment # @number_of_features: the number of features that we would like to use for feature mapping. It is the "m" in the paper. # @optimization_method: optimization method used when calling global_optimization function. User can choose any method # specified in the scipy.optimize.minimize # @seed: seed specified for randomization def run_PES(target_function, x_minimum, x_maximum, dimension, number_of_hyperparameter_sets = 100, number_of_burnin = 50, \ sampling_method = 'mcmc', number_of_initial_points = 3, number_of_experiments = 1, number_of_iterations = 60, \ number_of_features = 1000, optimization_method = 'SLSQP', seed = None): warnings.filterwarnings('ignore') check_result_file_exist() if seed is not None: np.random.seed(seed) #For Hartmann6 x_min = x_minimum x_max = x_maximum target = target_function #For Branin-Hoo #x_min = np.asarray([0.0,0.0]) #x_max = np.asarray([1.0,1.0]) #target = Branin_Hoo d = dimension num_of_hyperSets_initial = number_of_hyperparameter_sets number_burn = number_of_burnin sample_method = sampling_method bnds = get_bounds(x_min, x_max) opt_method = 'L-BFGS-B' #We obtain three random samples num_initial_points = number_of_initial_points final_result = [] for pp in range(number_of_experiments): write_header_to_files(pp) warnings.filterwarnings('ignore') Xsamples = initial_samples(x_min, x_max, num_initial_points) write_data_to_file("Xsamples.txt", Xsamples) #Guesses first stores the initilized guesses guesses = Xsamples write_data_to_file("guesses.txt", guesses) Ysamples = np.zeros((Xsamples.shape[0])) for i in range(Xsamples.shape[0]): Ysamples[i] = target(Xsamples[i,:]) Ysamples = np.asarray([Ysamples]) Ysamples = Ysamples.T print('Best so far in the initial data ' + str((min(Ysamples))[0])) write_data_to_file("Ysamples.txt", Ysamples) #We sample from the posterior distribution of the hyper-parameters with hide_prints(): noise, l, sigma = sample_hypers(Xsamples, Ysamples, d, 0.3, num_of_hyperSets_initial, number_burn, sample_method, seed) #global_minimum = target(np.array([(5-np.pi)/15,12.275/15])) #global_minimum = target(np.array([0.20169, 0.150011, 0.476874, 0.275332, 0.311652, 0.6573])) valid_evaluation = 1 log10_scale_vec = [] for g in range(number_of_iterations): print('PES, ' + str(pp) + 'th job, ' + str(g) + 'th iteration') start_1 = time.time() num_of_hyperSets = num_of_hyperSets_initial Xsamples_count_before = len(Xsamples) Ysamples_count_before = len(Ysamples) guesses_count_before = len(guesses) initial_point = guesses[-1,:] num_of_features = number_of_features num_of_obser = len(Ysamples) x_minimum_vec = [] K_vec = [] K_star_min_vec = [] K_plus_W_tilde_inverse_vec = [] m_f_minimum_vec = [] v_f_minimum_vec = [] c_and_m_vec = [] opt_method = 'L-BFGS-B' warnings.filterwarnings("error") valid_num_hyperSets = 0 for j in range(num_of_hyperSets): opt_method = 'L-BFGS-B' try: result = sample_min_with_randFeatures(num_of_features, d, Xsamples, Ysamples, sigma[j], l[j], noise[j], initial_point, opt_method, False, bnds) x_minimum = result.x x_minimum_vec.append(x_minimum) if opt_method == 'L-BFGS-B': hess_at_min_inverse = result.hess_inv.todense() else: hess_at_min_inverse = result.hess_inv hess_at_min = compute_inverse(hess_at_min_inverse) value_of_nObservations = (Ysamples.T)[0] K, K_star_min, K_plus_W_tilde_inverse, m_f_minimum, v_f_minimum, c_and_m = Expectation_Propagation(Xsamples, value_of_nObservations, num_of_obser, x_minimum, d, l[j,:], sigma[j], noise[j], hess_at_min) K_vec.append(K) K_star_min_vec.append(K_star_min) K_plus_W_tilde_inverse_vec.append(K_plus_W_tilde_inverse) m_f_minimum_vec.append(m_f_minimum) v_f_minimum_vec.append(v_f_minimum) c_and_m_vec.append(c_and_m) valid_num_hyperSets = valid_num_hyperSets + 1 except: pass num_of_hyperSets = valid_num_hyperSets opt_method = optimization_method warnings.filterwarnings("error") PES_fail = False try: PES = functools.partial(PES_aquisition_function_multi, Xsamples = Xsamples, x_minimum = x_minimum_vec, l_vec = l, \ sigma = sigma, noise = noise, K = K_vec, K_star_min = K_star_min_vec, \ K_plus_W_tilde_inverse = K_plus_W_tilde_inverse_vec, \ m_f_minimum = m_f_minimum_vec, v_f_minimum = v_f_minimum_vec, c_and_m = c_and_m_vec, \ num_of_hyperSets = num_of_hyperSets) ret = global_optimization(PES, d, x_min, x_max, gradient = None, gridsize = 500, stored_min_guesses = None, \ using_grid = True, optimize_method = opt_method, maxiter = 2000, bnds = bnds) optimum = np.array(ret.x) optimum_value = np.array([target(optimum)]) except: print('PES falied') PES_fail = True pass if PES_fail: warnings.filterwarnings('ignore') with hide_prints(): noise, l, sigma = sample_hypers(Xsamples, Ysamples, d, 0.3, num_of_hyperSets_initial, number_burn, sample_method, seed) print('return back due to PES fail') continue Xsamples = np.vstack((Xsamples, optimum)) Ysamples = np.vstack((Ysamples, optimum_value)) end_1 = time.time() print('PES takes ' + str(end_1 - start_1) + ' seconds') print('PES suggests: ') print(optimum) start_2 = time.time() #We sample from the posterior distribution of the hyper-parameters warnings.filterwarnings('ignore') num_of_hyperSets = num_of_hyperSets_initial try: with hide_prints(): noise, l, sigma = sample_hypers(Xsamples, Ysamples, d, 0.3, num_of_hyperSets_initial, number_burn, sample_method, seed) except: if len(Xsamples) > Xsamples_count_before: Xsamples = Xsamples[:-1,:] if len(Ysamples) > Ysamples_count_before: Ysamples = Ysamples[:-1] print('Sampling hyperparameters of posterior GP failed') continue end_2 = time.time() print('Retraining the model takes '+ str(end_2 - start_2) + ' seconds') write_data_to_file("Xsamples.txt", optimum) write_data_to_file("Ysamples.txt", optimum_value) start_3 = time.time() K_plus_I_inverse_vec = [] num_of_obser = len(Xsamples) for w in range(num_of_hyperSets): K_plus_I_inverse = covNobeservations(Xsamples, num_of_obser, sigma[w], noise[w], l[w]) + sigma[w]*10**(-10)*np.eye((num_of_obser)) K_plus_I_inverse_vec.append(np.array(K_plus_I_inverse)) warnings.filterwarnings("error") try: pos_mean_function = functools.partial(posterior_mean_given_nObservations, X_nObservations = Xsamples, value_of_nObservations = Ysamples, \ K_plus_I_inverse = K_plus_I_inverse_vec, l = l, sigma = sigma, \ num_of_hyperSets = num_of_hyperSets) pos_mean_grad_function = functools.partial(posterior_gradient_given_nObservations, X_nObservations = Xsamples, value_of_nObservations = Ysamples, \ K_plus_I_inverse = K_plus_I_inverse_vec, l = l, sigma = sigma, \ num_of_hyperSets = num_of_hyperSets, d = d) ret_pos = global_optimization(pos_mean_function, d, x_min, x_max, gradient = pos_mean_grad_function, gridsize = 500, \ stored_min_guesses = None, using_grid = True, optimize_method = opt_method, \ maxiter = 2000, bnds = bnds) except: if len(Xsamples) > Xsamples_count_before: Xsamples = Xsamples[:-1,:] if len(Ysamples) > Ysamples_count_before: Ysamples = Ysamples[:-1] print('Find the minimum of posterior mean failed') continue pos_optimum = np.array(ret_pos.x) write_data_to_file("guesses.txt", pos_optimum) current_value = target(pos_optimum) if current_value < (min(Ysamples))[0]: print('The recommended point ' + str(pos_optimum)) else: current_value = (min(Ysamples))[0] print('The recommended point ' + str(Xsamples[np.argmin(Ysamples)])) end_3 = time.time() print('Recommending the point takes '+ str(end_3 - start_3) + ' seconds') print('Best so far ' + str(current_value)) guesses = np.vstack((guesses, pos_optimum))
sdks/python/apache_beam/io/gcp/experimental/spannerio_read_it_test.py
ajothomas/beam
5,279
151603
# # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the 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 in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import logging import random import sys import unittest import uuid import pytest import apache_beam as beam from apache_beam.testing.test_pipeline import TestPipeline from apache_beam.testing.util import assert_that from apache_beam.testing.util import equal_to # Protect against environments where spanner library is not available. # pylint: disable=wrong-import-order, wrong-import-position, ungrouped-imports # pylint: disable=unused-import try: from google.cloud import spanner from apache_beam.io.gcp.experimental.spannerio import create_transaction from apache_beam.io.gcp.experimental.spannerio import ReadOperation from apache_beam.io.gcp.experimental.spannerio import ReadFromSpanner except ImportError: spanner = None # pylint: enable=wrong-import-order, wrong-import-position, ungrouped-imports # pylint: enable=unused-import _LOGGER = logging.getLogger(__name__) _TEST_INSTANCE_ID = 'beam-test' @unittest.skipIf(spanner is None, 'GCP dependencies are not installed.') class SpannerReadIntegrationTest(unittest.TestCase): TEST_DATABASE = None _database_prefix = "pybeam-read-{}" _data = None _SPANNER_CLIENT = None _SPANNER_INSTANCE = None @classmethod def _generate_table_name(cls): cls.TEST_DATABASE = cls._database_prefix.format( ''.join(random.sample(uuid.uuid4().hex, 15))) return cls.TEST_DATABASE @classmethod def _create_database(cls): _LOGGER.info("Creating test database: %s" % cls.TEST_DATABASE) instance = cls._SPANNER_INSTANCE database = instance.database( cls.TEST_DATABASE, ddl_statements=[ """CREATE TABLE Users ( UserId INT64 NOT NULL, Key STRING(1024) ) PRIMARY KEY (UserId)""", ]) operation = database.create() _LOGGER.info("Creating database: Done! %s" % str(operation.result())) @classmethod def _add_dummy_entries(cls): _LOGGER.info("Dummy Data: Adding dummy data...") instance = cls._SPANNER_INSTANCE database = instance.database(cls.TEST_DATABASE) data = cls._data = [(x + 1, uuid.uuid4().hex) for x in range(200)] with database.batch() as batch: batch.insert(table='Users', columns=('UserId', 'Key'), values=data) @classmethod def setUpClass(cls): _LOGGER.info(".... PyVersion ---> %s" % str(sys.version)) _LOGGER.info(".... Setting up!") cls.test_pipeline = TestPipeline(is_integration_test=True) cls.args = cls.test_pipeline.get_full_options_as_args() cls.runner_name = type(cls.test_pipeline.runner).__name__ cls.project = cls.test_pipeline.get_option('project') cls.instance = ( cls.test_pipeline.get_option('instance') or _TEST_INSTANCE_ID) _ = cls._generate_table_name() spanner_client = cls._SPANNER_CLIENT = spanner.Client() _LOGGER.info(".... Spanner Client created!") cls._SPANNER_INSTANCE = spanner_client.instance(cls.instance) cls._create_database() cls._add_dummy_entries() _LOGGER.info("Spanner Read IT Setup Complete...") @pytest.mark.it_postcommit def test_read_via_table(self): _LOGGER.info("Spanner Read via table") with beam.Pipeline(argv=self.args) as p: r = p | ReadFromSpanner( self.project, self.instance, self.TEST_DATABASE, table="Users", columns=["UserId", "Key"]) assert_that(r, equal_to(self._data)) @pytest.mark.it_postcommit def test_read_via_sql(self): _LOGGER.info("Running Spanner via sql") with beam.Pipeline(argv=self.args) as p: r = p | ReadFromSpanner( self.project, self.instance, self.TEST_DATABASE, sql="select * from Users") assert_that(r, equal_to(self._data)) @classmethod def tearDownClass(cls): # drop the testing database after the tests database = cls._SPANNER_INSTANCE.database(cls.TEST_DATABASE) database.drop() if __name__ == '__main__': logging.getLogger().setLevel(logging.INFO) unittest.main()
external/CoAPthon/coapthon/layers/requestlayer.py
iconnect-iot/intel-device-resource-mgt-lib
237
151627
<filename>external/CoAPthon/coapthon/layers/requestlayer.py from coapthon.messages.response import Response from coapthon import defines __author__ = '<NAME>' class RequestLayer(object): """ Class to handle the Request/Response layer """ def __init__(self, server): self._server = server def receive_request(self, transaction): """ Handle request and execute the requested method :type transaction: Transaction :param transaction: the transaction that owns the request :rtype : Transaction :return: the edited transaction with the response to the request """ method = transaction.request.code if method == defines.Codes.GET.number: transaction = self._handle_get(transaction) elif method == defines.Codes.POST.number: transaction = self._handle_post(transaction) elif method == defines.Codes.PUT.number: transaction = self._handle_put(transaction) elif method == defines.Codes.DELETE.number: transaction = self._handle_delete(transaction) else: transaction.response = None return transaction def send_request(self, request): """ Dummy function. Used to do not broke the layered architecture. :type request: Request :param request: the request :return: the request unmodified """ return request def _handle_get(self, transaction): """ Handle GET requests :type transaction: Transaction :param transaction: the transaction that owns the request :rtype : Transaction :return: the edited transaction with the response to the request """ path = str("/" + transaction.request.uri_path) transaction.response = Response() transaction.response.destination = transaction.request.source transaction.response.token = transaction.request.token if path == defines.DISCOVERY_URL: transaction = self._server.resourceLayer.discover(transaction) else: try: resource = self._server.root[path] except KeyError: resource = None if resource is None or path == '/': # Not Found transaction.response.code = defines.Codes.NOT_FOUND.number else: transaction.resource = resource transaction = self._server.resourceLayer.get_resource(transaction) return transaction def _handle_put(self, transaction): """ Handle PUT requests :type transaction: Transaction :param transaction: the transaction that owns the request :rtype : Transaction :return: the edited transaction with the response to the request """ path = str("/" + transaction.request.uri_path) transaction.response = Response() transaction.response.destination = transaction.request.source transaction.response.token = transaction.request.token try: resource = self._server.root[path] except KeyError: resource = None if resource is None: transaction.response.code = defines.Codes.NOT_FOUND.number else: transaction.resource = resource # Update request transaction = self._server.resourceLayer.update_resource(transaction) return transaction def _handle_post(self, transaction): """ Handle POST requests :type transaction: Transaction :param transaction: the transaction that owns the request :rtype : Transaction :return: the edited transaction with the response to the request """ path = str("/" + transaction.request.uri_path) transaction.response = Response() transaction.response.destination = transaction.request.source transaction.response.token = transaction.request.token # Create request transaction = self._server.resourceLayer.create_resource(path, transaction) return transaction def _handle_delete(self, transaction): """ Handle DELETE requests :type transaction: Transaction :param transaction: the transaction that owns the request :rtype : Transaction :return: the edited transaction with the response to the request """ path = str("/" + transaction.request.uri_path) transaction.response = Response() transaction.response.destination = transaction.request.source transaction.response.token = transaction.request.token try: resource = self._server.root[path] except KeyError: resource = None if resource is None: transaction.response.code = defines.Codes.NOT_FOUND.number else: # Delete transaction.resource = resource transaction = self._server.resourceLayer.delete_resource(transaction, path) return transaction
janitor/functions/move.py
vishalbelsare/pyjanitor
674
151640
import pandas_flavor as pf import pandas as pd from typing import Union @pf.register_dataframe_method def move( df: pd.DataFrame, source: Union[int, str], target: Union[int, str], position: str = "before", axis: int = 0, ) -> pd.DataFrame: """ Move column or row to a position adjacent to another column or row in dataframe. Must have unique column names or indices. This operation does not reset the index of the dataframe. User must explicitly do so. Does not apply to multilevel dataframes. Functional usage syntax: ```python df = move(df, source=3, target=15, position='after', axis=0) ``` Method chaining syntax: ```python import pandas as pd import janitor df = ( pd.DataFrame(...) .move(source=3, target=15, position='after', axis=0) ) ``` :param df: The pandas Dataframe object. :param source: column or row to move :param target: column or row to move adjacent to :param position: Specifies whether the Series is moved to before or after the adjacent Series. Values can be either `before` or `after`; defaults to `before`. :param axis: Axis along which the function is applied. 0 to move a row, 1 to move a column. :returns: The dataframe with the Series moved. :raises ValueError: if `axis` is not `0` or `1``. :raises ValueError: if `position` is not `before` or `after``. :raises ValueError: if `source` row or column is not in dataframe. :raises ValueError: if `target` row or column is not in dataframe. """ df = df.copy() if axis not in [0, 1]: raise ValueError(f"Invalid axis '{axis}'. Can only be 0 or 1.") if position not in ["before", "after"]: raise ValueError( f"Invalid position '{position}'. Can only be 'before' or 'after'." ) if axis == 0: names = list(df.index) if source not in names: raise ValueError(f"Source row '{source}' not in dataframe.") if target not in names: raise ValueError(f"Target row '{target}' not in dataframe.") names.remove(source) pos = names.index(target) if position == "after": pos += 1 names.insert(pos, source) df = df.loc[names, :] else: names = list(df.columns) if source not in names: raise ValueError(f"Source column '{source}' not in dataframe.") if target not in names: raise ValueError(f"Target column '{target}' not in dataframe.") names.remove(source) pos = names.index(target) if position == "after": pos += 1 names.insert(pos, source) df = df.loc[:, names] return df
v2/utils/functional.py
oxygenman/DanceRevolution
209
151647
# This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this open-source project. """ Define the functions to load data. """ import os import json import argparse import numpy as np def load_data(data_dir, interval=100, data_type='2D'): music_data, dance_data = [], [] fnames = sorted(os.listdir(data_dir)) # fnames = fnames[:10] # For debug for fname in fnames: path = os.path.join(data_dir, fname) with open(path) as f: sample_dict = json.loads(f.read()) np_music = np.array(sample_dict['music_array']) np_dance = np.array(sample_dict['dance_array']) if data_type == '2D': # Only use 25 keypoints skeleton (basic bone) for 2D np_dance = np_dance[:, :50] root = np_dance[:, 2*8:2*9] np_dance = np_dance - np.tile(root, (1, 25)) np_dance[:, 2*8:2*9] = root seq_len, dim = np_music.shape for i in range(0, seq_len, interval): music_sub_seq = np_music[i: i + interval] dance_sub_seq = np_dance[i: i + interval] if len(music_sub_seq) == interval: music_data.append(music_sub_seq) dance_data.append(dance_sub_seq) return music_data, dance_data def load_test_data(data_dir, data_type='2D'): music_data, dance_data = [], [] fnames = sorted(os.listdir(data_dir)) print(fnames) # fnames = fnames[:60] # For debug for fname in fnames: path = os.path.join(data_dir, fname) with open(path) as f: sample_dict = json.loads(f.read()) np_music = np.array(sample_dict['music_array']) np_dance = np.array(sample_dict['dance_array']) if data_type == '2D': # Only use 25 keypoints skeleton (basic bone) for 2D np_dance = np_dance[:, :50] root = np_dance[:, 2*8:2*9] np_dance = np_dance - np.tile(root, (1, 25)) np_dance[:, 2*8:2*9] = root music_data.append(np_music) dance_data.append(np_dance) return music_data, dance_data, fnames def load_json_data(data_file, max_seq_len=150): music_data = [] dance_data = [] count = 0 total_count = 0 with open(data_file) as f: data_list = json.loads(f.read()) for data in data_list: # The first and last segment may be unusable music_segs = data['music_segments'] dance_segs = data['dance_segments'] assert len(music_segs) == len(dance_segs), 'alignment' for i in range(len(music_segs)): total_count += 1 if len(music_segs[i]) > max_seq_len: count += 1 continue music_data.append(music_segs[i]) dance_data.append(dance_segs[i]) rate = count / total_count print(f'total num of segments: {total_count}') print(f'num of segments length > {max_seq_len}: {count}') print(f'the rate: {rate}') return music_data, dance_data def str2bool(v): if v.lower() in ('yes', 'true', 't', 'y', '1'): return True elif v.lower() in ('no', 'false', 'f', 'n', '0'): return False else: raise argparse.ArgumentTypeError('Boolean value expected.')
pwnlib/gdb_api_bridge.py
tkmikan/pwntools
8,966
151670
<gh_stars>1000+ """GDB Python API bridge.""" import gdb import socket from threading import Condition import time from rpyc.core.protocol import Connection from rpyc.core.service import Service from rpyc.lib import spawn from rpyc.lib.compat import select_error from rpyc.utils.server import ThreadedServer class ServeResult: """Result of serving requests on GDB thread.""" def __init__(self): self.cv = Condition() self.done = False self.exc = None def set(self, exc): with self.cv: self.done = True self.exc = exc self.cv.notify() def wait(self): with self.cv: while not self.done: self.cv.wait() if self.exc is not None: raise self.exc class GdbConnection(Connection): """A Connection implementation that serves requests on GDB thread. Serving on GDB thread might not be ideal from the responsiveness perspective, however, it is simple and reliable. """ SERVE_TIME = 0.1 # Number of seconds to serve. IDLE_TIME = 0.1 # Number of seconds to wait after serving. def serve_gdb_thread(self, serve_result): """Serve requests on GDB thread.""" try: deadline = time.time() + self.SERVE_TIME while True: timeout = deadline - time.time() if timeout < 0: break super().serve(timeout=timeout) except Exception as exc: serve_result.set(exc) else: serve_result.set(None) def serve_all(self): """Modified version of rpyc.core.protocol.Connection.serve_all.""" try: while not self.closed: serve_result = ServeResult() gdb.post_event(lambda: self.serve_gdb_thread(serve_result)) serve_result.wait() time.sleep(self.IDLE_TIME) except (socket.error, select_error, IOError): if not self.closed: raise except EOFError: pass finally: self.close() class GdbService(Service): """A public interface for Pwntools.""" _protocol = GdbConnection # Connection subclass. exposed_gdb = gdb # ``gdb`` module. def exposed_set_breakpoint(self, client, has_stop, *args, **kwargs): """Create a breakpoint and connect it with the client-side mirror.""" if has_stop: class Breakpoint(gdb.Breakpoint): def stop(self): return client.stop() return Breakpoint(*args, **kwargs) return gdb.Breakpoint(*args, **kwargs) def exposed_quit(self): """Terminate GDB.""" gdb.post_event(lambda: gdb.execute('quit')) spawn(ThreadedServer( service=GdbService(), socket_path=socket_path, protocol_config={ 'allow_all_attrs': True, }, ).start)
rl_coach/environments/robosuite_environment.py
JohnnyPeng18/coach
1,960
151672
<reponame>JohnnyPeng18/coach # # Copyright (c) 2020 Intel Corporation # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the 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 in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # from typing import Union ,Dict, Any from enum import Enum, Flag, auto from copy import deepcopy import numpy as np import random from collections import namedtuple try: import robosuite from robosuite.wrappers import Wrapper, DomainRandomizationWrapper except ImportError: from rl_coach.logger import failed_imports failed_imports.append("Robosuite") from rl_coach.base_parameters import Parameters, VisualizationParameters from rl_coach.environments.environment import Environment, EnvironmentParameters, LevelSelection from rl_coach.spaces import BoxActionSpace, VectorObservationSpace, StateSpace, PlanarMapsObservationSpace # Importing our custom Robosuite environments here so that they are properly # registered in Robosuite, and so recognized by 'robosuite.make()' and included # in 'robosuite.ALL_ENVIRONMENTS' import rl_coach.environments.robosuite.cube_exp robosuite_environments = list(robosuite.ALL_ENVIRONMENTS) robosuite_robots = list(robosuite.ALL_ROBOTS) robosuite_controllers = list(robosuite.ALL_CONTROLLERS) def get_robosuite_env_extra_parameters(env_name: str): import inspect assert env_name in robosuite_environments env_params = inspect.signature(robosuite.environments.REGISTERED_ENVS[env_name]).parameters base_params = list(RobosuiteBaseParameters().env_kwargs_dict().keys()) + ['robots', 'controller_configs'] return {n: p.default for n, p in env_params.items() if n not in base_params} class OptionalObservations(Flag): NONE = 0 CAMERA = auto() OBJECT = auto() class RobosuiteBaseParameters(Parameters): def __init__(self, optional_observations: OptionalObservations = OptionalObservations.NONE): super(RobosuiteBaseParameters, self).__init__() # NOTE: Attribute names should exactly match the attribute names in Robosuite self.horizon = 1000 # Every episode lasts for exactly horizon timesteps self.ignore_done = True # True if never terminating the environment (ignore horizon) self.reward_shaping = True # if True, use dense rewards. # How many control signals to receive in every simulated second. This sets the amount of simulation time # that passes between every action input (this is NOT the same as frame_skip) self.control_freq = 10 # Optional observations (robot state is always returned) # if True, every observation includes a rendered image self.use_camera_obs = bool(optional_observations & OptionalObservations.CAMERA) # if True, include object (cube/etc.) information in the observation self.use_object_obs = bool(optional_observations & OptionalObservations.OBJECT) # Camera parameters self.has_renderer = False # Set to true to use Mujoco native viewer for on-screen rendering self.render_camera = 'frontview' # name of camera to use for on-screen rendering self.has_offscreen_renderer = self.use_camera_obs self.render_collision_mesh = False # True if rendering collision meshes in camera. False otherwise self.render_visual_mesh = True # True if rendering visual meshes in camera. False otherwise self.camera_names = 'agentview' # name of camera for rendering camera observations self.camera_heights = 84 # height of camera frame. self.camera_widths = 84 # width of camera frame. self.camera_depths = False # True if rendering RGB-D, and RGB otherwise. # Collision self.penalize_reward_on_collision = True self.end_episode_on_collision = False @property def optional_observations(self): flag = OptionalObservations.NONE if self.use_camera_obs: flag = OptionalObservations.CAMERA if self.use_object_obs: flag |= OptionalObservations.OBJECT elif self.use_object_obs: flag = OptionalObservations.OBJECT return flag @optional_observations.setter def optional_observations(self, value): self.use_camera_obs = bool(value & OptionalObservations.CAMERA) if self.use_camera_obs: self.has_offscreen_renderer = True self.use_object_obs = bool(value & OptionalObservations.OBJECT) def env_kwargs_dict(self): res = {k: (v.value if isinstance(v, Enum) else v) for k, v in vars(self).items()} return res class RobosuiteEnvironmentParameters(EnvironmentParameters): def __init__(self, level, robot=None, controller=None, apply_dr: bool = False, dr_every_n_steps_min: int = 10, dr_every_n_steps_max: int = 20, use_joint_vel_obs=False): super().__init__(level=level) self.base_parameters = RobosuiteBaseParameters() self.extra_parameters = {} self.robot = robot self.controller = controller self.apply_dr = apply_dr self.dr_every_n_steps_min = dr_every_n_steps_min self.dr_every_n_steps_max = dr_every_n_steps_max self.use_joint_vel_obs = use_joint_vel_obs self.custom_controller_config_fpath = None @property def path(self): return 'rl_coach.environments.robosuite_environment:RobosuiteEnvironment' DEFAULT_REWARD_SCALES = { 'Lift': 2.25, 'LiftLab': 2.25, } RobosuiteStepResult = namedtuple('RobosuiteStepResult', ['observation', 'reward', 'done', 'info']) # Environment class RobosuiteEnvironment(Environment): def __init__(self, level: LevelSelection, seed: int, frame_skip: int, human_control: bool, custom_reward_threshold: Union[int, float, None], visualization_parameters: VisualizationParameters, base_parameters: RobosuiteBaseParameters, extra_parameters: Dict[str, Any], robot: str, controller: str, target_success_rate: float = 1.0, apply_dr: bool = False, dr_every_n_steps_min: int = 10, dr_every_n_steps_max: int = 20, use_joint_vel_obs=False, custom_controller_config_fpath=None, **kwargs): super(RobosuiteEnvironment, self).__init__(level, seed, frame_skip, human_control, custom_reward_threshold, visualization_parameters, target_success_rate) # Validate arguments self.frame_skip = max(1, self.frame_skip) def validate_input(input, supported, name): if input not in supported: raise ValueError("Unknown Robosuite {0} passed: '{1}' ; Supported {0}s are: {2}".format( name, input, ' | '.join(supported) )) validate_input(self.env_id, robosuite_environments, 'environment') validate_input(robot, robosuite_robots, 'robot') self.robot = robot if controller is not None: validate_input(controller, robosuite_controllers, 'controller') self.controller = controller self.base_parameters = base_parameters self.base_parameters.has_renderer = self.is_rendered and self.native_rendering self.base_parameters.has_offscreen_renderer = self.base_parameters.use_camera_obs or (self.is_rendered and not self.native_rendering) # Seed if self.seed is not None: np.random.seed(self.seed) random.seed(self.seed) # Load and initialize environment env_args = self.base_parameters.env_kwargs_dict() env_args.update(extra_parameters) if 'reward_scale' not in env_args and self.env_id in DEFAULT_REWARD_SCALES: env_args['reward_scale'] = DEFAULT_REWARD_SCALES[self.env_id] env_args['robots'] = self.robot controller_cfg = None if self.controller is not None: controller_cfg = robosuite.controllers.load_controller_config(default_controller=self.controller) elif custom_controller_config_fpath is not None: controller_cfg = robosuite.controllers.load_controller_config(custom_fpath=custom_controller_config_fpath) env_args['controller_configs'] = controller_cfg self.env = robosuite.make(self.env_id, **env_args) # TODO: Generalize this to filter any observation by name if not use_joint_vel_obs: self.env.modify_observable('robot0_joint_vel', 'active', False) # Wrap with a dummy wrapper so we get a consistent API (there are subtle changes between # wrappers and actual environments in Robosuite, for example action_spec as property vs. function) self.env = Wrapper(self.env) if apply_dr: self.env = DomainRandomizationWrapper(self.env, seed=self.seed, randomize_every_n_steps_min=dr_every_n_steps_min, randomize_every_n_steps_max=dr_every_n_steps_max) # State space self.state_space = self._setup_state_space() # Action space low, high = self.env.unwrapped.action_spec self.action_space = BoxActionSpace(low.shape, low=low, high=high) self.reset_internal_state() if self.is_rendered: image = self.get_rendered_image() self.renderer.create_screen(image.shape[1], image.shape[0]) # TODO: Other environments call rendering here, why? reset_internal_state does it def _setup_state_space(self): state_space = StateSpace({}) dummy_obs = self._process_observation(self.env.observation_spec()) state_space['measurements'] = VectorObservationSpace(dummy_obs['measurements'].shape[0]) if self.base_parameters.use_camera_obs: state_space['camera'] = PlanarMapsObservationSpace(dummy_obs['camera'].shape, 0, 255) return state_space def _process_observation(self, raw_obs): new_obs = {} # TODO: Support multiple cameras, this assumes a single camera camera_name = self.base_parameters.camera_names camera_obs = raw_obs.get(camera_name + '_image', None) if camera_obs is not None: depth_obs = raw_obs.get(camera_name + '_depth', None) if depth_obs is not None: depth_obs = np.expand_dims(depth_obs, axis=2) camera_obs = np.concatenate([camera_obs, depth_obs], axis=2) new_obs['camera'] = camera_obs measurements = raw_obs['robot0_proprio-state'] object_obs = raw_obs.get('object-state', None) if object_obs is not None: measurements = np.concatenate([measurements, object_obs]) new_obs['measurements'] = measurements return new_obs def _take_action(self, action): action = self.action_space.clip_action_to_space(action) # We mimic the "action_repeat" mechanism of RobosuiteWrapper in Surreal. # Same concept as frame_skip, only returning the average reward across repeated actions instead # of the total reward. rewards = [] for _ in range(self.frame_skip): obs, reward, done, info = self.env.step(action) rewards.append(reward) if done: break reward = np.mean(rewards) self.last_result = RobosuiteStepResult(obs, reward, done, info) def _update_state(self): obs = self._process_observation(self.last_result.observation) self.state = {k: obs[k] for k in self.state_space.sub_spaces} self.reward = self.last_result.reward or 0 self.done = self.last_result.done self.info = self.last_result.info def _restart_environment_episode(self, force_environment_reset=False): reset_obs = self.env.reset() self.last_result = RobosuiteStepResult(reset_obs, 0.0, False, {}) def _render(self): self.env.render() def get_rendered_image(self): img: np.ndarray = self.env.sim.render(camera_name=self.base_parameters.render_camera, height=512, width=512, depth=False) return np.flip(img, 0) def close(self): self.env.close() class RobosuiteGoalBasedExpEnvironmentParameters(RobosuiteEnvironmentParameters): @property def path(self): return 'rl_coach.environments.robosuite_environment:RobosuiteGoalBasedExpEnvironment' class RobosuiteGoalBasedExpEnvironment(RobosuiteEnvironment): def _process_observation(self, raw_obs): new_obs = super()._process_observation(raw_obs) new_obs['obs-goal'] = None return new_obs def _setup_state_space(self): state_space = super()._setup_state_space() goal_based_shape = list(state_space['camera'].shape) goal_based_shape[2] *= 2 state_space['obs-goal'] = PlanarMapsObservationSpace(tuple(goal_based_shape), 0, 255) return state_space
kornia/losses/lovasz_softmax.py
YanivHollander/kornia
418
151685
<reponame>YanivHollander/kornia from typing import List import torch import torch.nn as nn from torch import Tensor from kornia.testing import KORNIA_CHECK_SHAPE # based on: # https://github.com/bermanmaxim/LovaszSoftmax def lovasz_softmax_loss(pred: Tensor, target: Tensor) -> Tensor: r"""Criterion that computes a surrogate multi-class intersection-over-union (IoU) loss. According to [1], we compute the IoU as follows: .. math:: \text{IoU}(x, class) = \frac{|X \cap Y|}{|X \cup Y|} [1] approximates this fomular with a surrogate, which is fully differentable. Where: - :math:`X` expects to be the scores of each class. - :math:`Y` expects to be the binary tensor with the class labels. the loss, is finally computed as: .. math:: \text{loss}(x, class) = 1 - \text{IoU}(x, class) Reference: [1] https://arxiv.org/pdf/1705.08790.pdf . note:: This loss function only supports multi-class (C > 1) labels. For binary labels please use the Lovasz-Hinge loss. Args: pred: logits tensor with shape :math:`(N, C, H, W)` where C = number of classes > 1. labels: labels tensor with shape :math:`(N, H, W)` where each value is :math:`0 ≤ targets[i] ≤ C−1`. Return: a scalar with the computed loss. Example: >>> N = 5 # num_classes >>> pred = torch.randn(1, N, 3, 5, requires_grad=True) >>> target = torch.empty(1, 3, 5, dtype=torch.long).random_(N) >>> output = lovasz_softmax_loss(pred, target) >>> output.backward() """ KORNIA_CHECK_SHAPE(pred, ["B", "N", "H", "W"]) KORNIA_CHECK_SHAPE(target, ["B", "H", "W"]) if not pred.shape[1] > 1: raise ValueError(f"Invalid pred shape, we expect BxNxHxW, with N > 1. Got: {pred.shape}") if not pred.shape[-2:] == target.shape[-2:]: raise ValueError(f"pred and target shapes must be the same. Got: {pred.shape} and {target.shape}") if not pred.device == target.device: raise ValueError(f"pred and target must be in the same device. Got: {pred.device} and {target.device}") # flatten pred [B, C, -1] and target [B, -1] and to float pred_flatten: Tensor = pred.reshape(pred.shape[0], pred.shape[1], -1) target_flatten: Tensor = target.reshape(target.shape[0], -1).float() # get shapes B, C, N = pred_flatten.shape # compute softmax over the classes axis pred_soft: Tensor = pred_flatten.softmax(1) # compute actual loss losses: List[Tensor] = [] batch_index: Tensor = torch.arange(B, device=pred.device).reshape(-1, 1).repeat(1, N).reshape(-1) for c in range(C): foreground: Tensor = 1. * (target_flatten == c) class_pred: Tensor = pred_soft[:, c] errors = (class_pred - foreground).abs() errors_sorted, permutation = torch.sort(errors, dim=1, descending=True) target_sorted: Tensor = target_flatten[batch_index, permutation.view(-1)] target_sorted = target_sorted.view(B, N) target_sorted_sum: Tensor = target_sorted.sum(1, keepdim=True) intersection: Tensor = target_sorted_sum - target_sorted.cumsum(1) union: Tensor = target_sorted_sum + (1. - target_sorted).cumsum(1) gradient: Tensor = 1. - intersection / union if N > 1: gradient[..., 1:] = gradient[..., 1:] - gradient[..., :-1] loss: Tensor = (errors_sorted.relu() * gradient).sum(1).mean() losses.append(loss) final_loss: Tensor = torch.stack(losses, dim=0).mean() return final_loss class LovaszSoftmaxLoss(nn.Module): r"""Criterion that computes a surrogate multi-class intersection-over-union (IoU) loss. According to [1], we compute the IoU as follows: .. math:: \text{IoU}(x, class) = \frac{|X \cap Y|}{|X \cup Y|} [1] approximates this fomular with a surrogate, which is fully differentable. Where: - :math:`X` expects to be the scores of each class. - :math:`Y` expects to be the binary tensor with the class labels. the loss, is finally computed as: .. math:: \text{loss}(x, class) = 1 - \text{IoU}(x, class) Reference: [1] https://arxiv.org/pdf/1705.08790.pdf . note:: This loss function only supports multi-class (C > 1) labels. For binary labels please use the Lovasz-Hinge loss. Args: pred: logits tensor with shape :math:`(N, C, H, W)` where C = number of classes > 1. labels: labels tensor with shape :math:`(N, H, W)` where each value is :math:`0 ≤ targets[i] ≤ C−1`. Return: a scalar with the computed loss. Example: >>> N = 5 # num_classes >>> criterion = LovaszSoftmaxLoss() >>> pred = torch.randn(1, N, 3, 5, requires_grad=True) >>> target = torch.empty(1, 3, 5, dtype=torch.long).random_(N) >>> output = criterion(pred, target) >>> output.backward() """ def __init__(self) -> None: super().__init__() def forward(self, pred: Tensor, target: Tensor) -> Tensor: return lovasz_softmax_loss(pred=pred, target=target)
setup.py
antoniogois/entmax
298
151705
from distutils.core import setup from entmax import __version__ setup(name='entmax', version=__version__, url="https://github.com/deep-spin/entmax", author="<NAME>, <NAME>, <NAME>", author_email="<EMAIL>", description=("The entmax mapping and its loss, a family of sparse " "alternatives to softmax."), license="MIT", packages=['entmax'], install_requires=['torch>=1.0'], python_requires=">=3.5")
src/two_heads/RangePadding2D.py
lilin-hitcrt/OverlapNet
441
151799
#!/usr/bin/env python3 # Developed by <NAME> and <NAME> # This file is covered by the LICENSE file in the root of this project. # Brief: A custom keras padding layer. # pad([1 2 3 4], 2) -> [3, 4, 1, 2, 3, 4, 1] import numpy as np from keras.layers import Layer from keras.models import Sequential import keras.backend as K class RangePadding2D(Layer): """ A keras layer which does horizontal padding. The input tensor is padded in the width direction. """ def __init__(self, padding, **kwargs): """ Initialization of the layer. Args: padding: defines how much will be padded "before" and "after" the input. The input is padded in width direction like this: [ padding:end, original, beginning:padding-1] Usually one uses half of the width for this argument to have a symmetric padding """ self.padding = padding super(RangePadding2D, self).__init__(**kwargs) def build(self, input_shape): super(RangePadding2D, self).build(input_shape) def call(self, inputs): if K.backend() == "tensorflow": # only do range padding in width dimension out = K.concatenate([inputs[:, :, self.padding:, :], inputs[:, :, :, :], inputs[:, :, :self.padding-1, :]], axis=2) else: raise Exception("Backend " + K.backend() + "not implemented") return out def compute_output_shape(self, input_shape): return (input_shape[0], input_shape[1], input_shape[2] + input_shape[2] - 1 , input_shape[3]) if __name__ == "__main__": one_channel_test = True two_channel_test = True if two_channel_test: # set test data image_raw = [[1, 6], [2, 5], [3, 4], [4, 3], [5, 2], [6, 1]] image = np.expand_dims(np.expand_dims(np.array(image_raw), 0), 0) print("input image shape: ", image.shape) print("Input:") print(image) # build Keras model model = Sequential() rlayer = RangePadding2D(padding=3, input_shape=(1, 6, 2)) model.add(rlayer) model.build() # simply apply existing filter, we use predict with no training out = model.predict(image) print("Output shape: ",out.shape) print("result of compute_output_shape (should be the same):", rlayer.compute_output_shape(rlayer.input_shape)) print("Output:") print(out) if one_channel_test: # one channel test image_raw = [[1, 2, 3, 4, 5, 6]] # pad to channels_last format # which is [batch, width, height, channels]=[1,1,6,1] image = np.expand_dims(np.expand_dims(np.array(image_raw), 2), 0) print("input image shape: ", image.shape) print("Input:") print(image) # build Keras model model = Sequential() rlayer = RangePadding2D(padding=3, input_shape=(1, 6, 1)) model.add(rlayer) model.build() # simply apply existing filter, we use predict with no training out = model.predict(image) print("Output shape: ",out.shape) print("result of compute_output_shape (should be the same):", rlayer.compute_output_shape(rlayer.input_shape)) print("Output:") print(out)
dashboard/dashboard/pinpoint/models/task.py
Martijnve23/catapult
1,894
151820
<gh_stars>1000+ # Copyright 2019 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. from __future__ import print_function from __future__ import division from __future__ import absolute_import import collections import functools import itertools import logging from dashboard.common import timing from google.appengine.ext import ndb from google.appengine.ext import db __all__ = ( 'PopulateTaskGraph', 'TaskGraph', 'TaskVertex', 'Dependency', 'Evaluate', 'ExtendTaskGraph', 'UpdateTask', 'AppendTasklog', ) TaskVertex = collections.namedtuple('TaskVertex', ('id', 'vertex_type', 'payload')) Dependency = collections.namedtuple('Dependency', ('from_', 'to')) TaskGraph = collections.namedtuple('TaskGraph', ('vertices', 'edges')) # These InMemoryTask instances are meant to isolate the Task model which is # actually persisted in Datastore. InMemoryTask = collections.namedtuple( 'InMemoryTask', ('id', 'task_type', 'payload', 'status', 'dependencies')) VALID_TRANSITIONS = { 'pending': {'ongoing', 'completed', 'failed', 'cancelled'}, 'ongoing': {'completed', 'failed', 'cancelled'}, 'cancelled': {'pending'}, 'completed': {'pending'}, 'failed': {'pending'}, } # Traversal states used in the graph traversal. We use these as marks for when # vertices are traversed, as how we would implement graph colouring in a graph # traversal (like Depth First Search). NOT_EVALUATED, CHILDREN_PENDING, EVALUATION_DONE = (0, 1, 2) ReconstitutedTaskGraph = collections.namedtuple('ReconstitutedTaskGraph', ('terminal_tasks', 'tasks')) class Error(Exception): pass class InvalidAmendment(Error): pass class TaskNotFound(Error): pass class InvalidTransition(Error): pass # These are internal-only models, used as an implementation detail of the # execution engine. class Task(ndb.Model): """A Task associated with a Pinpoint Job. Task instances are always associated with a Job. Tasks represent units of work that are in well-defined states. Updates to Task instances are transactional and need to be. """ task_type = ndb.StringProperty(required=True) status = ndb.StringProperty(required=True, choices=VALID_TRANSITIONS.keys()) payload = ndb.JsonProperty(compressed=True, indexed=False) dependencies = ndb.KeyProperty(repeated=True, kind='Task') created = ndb.DateTimeProperty(required=True, auto_now_add=True) updated = ndb.DateTimeProperty(required=True, auto_now_add=True) def ToInMemoryTask(self): # We isolate the ndb model `Task` from the evaluator, to avoid accidentially # modifying the state in datastore. return InMemoryTask( id=self.key.id(), task_type=self.task_type, payload=self.payload, status=self.status, dependencies=[dep.id() for dep in self.dependencies]) class TaskLog(ndb.Model): """Log entries associated with Task instances. TaskLog instances are always associated with a Task. These entries are immutable once created. """ timestamp = ndb.DateTimeProperty( required=True, auto_now_add=True, indexed=False) message = ndb.TextProperty() payload = ndb.JsonProperty(compressed=True, indexed=False) @ndb.transactional(propagation=ndb.TransactionOptions.INDEPENDENT, retries=0) def PopulateTaskGraph(job, graph): """Populate the Datastore with Task instances associated with a Job. The `graph` argument must have two properties: a collection of `TaskVertex` instances named `vertices` and a collection of `Dependency` instances named `dependencies`. """ if job is None: raise ValueError('job must not be None.') job_key = job.key tasks = { v.id: Task( key=ndb.Key(Task, v.id, parent=job_key), task_type=v.vertex_type, payload=v.payload, status='pending') for v in graph.vertices } dependencies = set() for dependency in graph.edges: dependency_key = ndb.Key(Task, dependency.to, parent=job_key) if dependency not in dependencies: tasks[dependency.from_].dependencies.append(dependency_key) dependencies.add(dependency) ndb.put_multi(tasks.values(), use_cache=True) @ndb.transactional(propagation=ndb.TransactionOptions.INDEPENDENT, retries=0) def ExtendTaskGraph(job, vertices, dependencies): """Add new vertices and dependency links to the graph. Args: job: a dashboard.pinpoint.model.job.Job instance. vertices: an iterable of TaskVertex instances. dependencies: an iterable of Dependency instances. """ if job is None: raise ValueError('job must not be None.') if not vertices and not dependencies: return job_key = job.key amendment_task_graph = { v.id: Task( key=ndb.Key(Task, v.id, parent=job_key), task_type=v.vertex_type, status='pending', payload=v.payload) for v in vertices } # Ensure that the keys we're adding are not in the graph yet. current_tasks = Task.query(ancestor=job_key).fetch() current_task_keys = set(t.key for t in current_tasks) new_task_keys = set(t.key for t in amendment_task_graph.values()) overlap = new_task_keys & current_task_keys if overlap: raise InvalidAmendment('vertices (%r) already in task graph.' % (overlap,)) # Then we add the dependencies. current_task_graph = {t.key.id(): t for t in current_tasks} handled_dependencies = set() update_filter = set(amendment_task_graph) for dependency in dependencies: dependency_key = ndb.Key(Task, dependency.to, parent=job_key) if dependency not in handled_dependencies: current_task = current_task_graph.get(dependency.from_) amendment_task = amendment_task_graph.get(dependency.from_) if current_task is None and amendment_task is None: raise InvalidAmendment('dependency `from` (%s) not in amended graph.' % (dependency.from_,)) if current_task: current_task_graph[dependency.from_].dependencies.append(dependency_key) if amendment_task: amendment_task_graph[dependency.from_].dependencies.append( dependency_key) handled_dependencies.add(dependency) update_filter.add(dependency.from_) ndb.put_multi( itertools.chain( amendment_task_graph.values(), [t for id_, t in current_task_graph.items() if id_ in update_filter]), use_cache=True) @ndb.transactional(propagation=ndb.TransactionOptions.INDEPENDENT, retries=0) def UpdateTask(job, task_id, new_state=None, payload=None): """Update a task. This enforces that the status transitions are semantically correct, where only the transitions defined in the VALID_TRANSITIONS map are allowed. When either new_state or payload are not None, this function performs the update transactionally. At least one of `new_state` or `payload` must be provided in calls to this function. """ if new_state is None and payload is None: raise ValueError('Set one of `new_state` or `payload`.') if new_state and new_state not in VALID_TRANSITIONS: raise InvalidTransition('Unknown state: %s' % (new_state,)) task = Task.get_by_id(task_id, parent=job.key) if not task: raise TaskNotFound('Task with id "%s" not found for job "%s".' % (task_id, job.job_id)) if new_state: valid_transitions = VALID_TRANSITIONS.get(task.status) if new_state not in valid_transitions: raise InvalidTransition( 'Attempting transition from "%s" to "%s" not in %s; task = %s' % (task.status, new_state, valid_transitions, task)) task.status = new_state if payload: task.payload = payload task.put() def LogStateTransitionFailures(wrapped_action): """Decorator to log state transition failures. This is a convenience decorator to handle state transition failures, and suppress further exception propagation of the transition failure. """ @functools.wraps(wrapped_action) def ActionWrapper(*args, **kwargs): try: return wrapped_action(*args, **kwargs) except InvalidTransition as e: logging.error('State transition failed: %s', e) return None except db.TransactionFailedError as e: logging.error('Transaction failed: %s', e) return None return ActionWrapper @ndb.transactional(propagation=ndb.TransactionOptions.INDEPENDENT, retries=0) def AppendTasklog(job, task_id, message, payload): task_log = TaskLog( parent=ndb.Key(Task, task_id, parent=job.key), message=message, payload=payload) task_log.put() @ndb.transactional(propagation=ndb.TransactionOptions.INDEPENDENT, retries=0) def _LoadTaskGraph(job): with timing.WallTimeLogger('ExecutionEngine:_LoadTaskGraph'): tasks = Task.query(ancestor=job.key).fetch() # The way we get the terminal tasks is by looking at tasks where nothing # depends on them. has_dependents = set() for task in tasks: has_dependents |= set(task.dependencies) terminal_tasks = [t.key for t in tasks if t.key not in has_dependents] return ReconstitutedTaskGraph( terminal_tasks=terminal_tasks, tasks={task.key: task for task in tasks}) class NoopAction(object): @staticmethod def __str__(): return 'NoopAction()' @staticmethod def __call__(_): pass @ndb.non_transactional @timing.TimeWall('ExecutionEngine:Evaluate') def Evaluate(job, event, evaluator): """Applies an evaluator given a task in the task graph and an event as input. This function implements a depth-first search traversal of the task graph and applies the `evaluator` given a task and the event input in post-order traversal. We start the DFS from the terminal tasks (those that don't have dependencies) and call the `evaluator` function with a representation of the task in the graph, an `event` as input, and an accumulator argument. The `evaluator` must be a callable which accepts three arguments: - task: an InMemoryTask instance, representing a task in the graph. - event: an object whose shape/type is defined by the caller of the `Evaluate` function and that the evaluator can handle. - accumulator: a dictionary which is mutable which is valid in the scope of a traversal of the graph. The `evaluator` must return either None or an iterable of callables which take a single argument, which is the accumulator at the end of a traversal. Events are free-form but usually are dictionaries which constitute inputs that are external to the task graph evaluation. This could model events in an event-driven evaluation of tasks, or synthetic inputs to the system. It is more important that the `event` information is known to the evaluator implementation, and is provided as-is to the evaluator in this function. The Evaluate function will keep iterating while there are actions still being produced by the evaluator. When there are no more actions to run, the Evaluate function will return the most recent traversal's accumulator. """ if job is None: raise ValueError('job must not be None.') accumulator = {} actions = [NoopAction()] while actions: for action in actions: logging.debug('Running action: %s', action) # Each action should be a callable which takes the accumulator as an # input. We want to run each action in their own transaction as well. # This must not be called in a transaction. with timing.WallTimeLogger('ExecutionEngine:ActionRunner<%s>' % (type(action).__name__,)): action(accumulator) # Clear the actions and accumulator for this traversal. del actions[:] accumulator.clear() # Load the graph transactionally. graph = _LoadTaskGraph(job) if not graph.tasks: logging.debug('Task graph empty for job %s', job.job_id) return # First get all the "terminal" tasks, and traverse the dependencies in a # depth-first-search. task_stack = [graph.tasks[task] for task in graph.terminal_tasks] # If the stack is empty, we should start at an arbitrary point. if not task_stack: task_stack = [graph.tasks.values()[0]] vertex_states = {} while task_stack: task = task_stack[-1] state = vertex_states.get(task.key, NOT_EVALUATED) if state == CHILDREN_PENDING: in_memory_task = task.ToInMemoryTask() result_actions = evaluator(in_memory_task, event, accumulator) if result_actions: actions.extend(result_actions) vertex_states[task.key] = EVALUATION_DONE elif state == NOT_EVALUATED: # This vertex is coloured white, we should traverse the dependencies. vertex_states[task.key] = CHILDREN_PENDING for dependency in task.dependencies: if vertex_states.get(dependency, NOT_EVALUATED) == NOT_EVALUATED: task_stack.append(graph.tasks[dependency]) else: assert state == EVALUATION_DONE task_stack.pop() return accumulator
examples/ssd/callbacks.py
rsketine/neon
4,415
151829
<filename>examples/ssd/callbacks.py<gh_stars>1000+ import numpy as np from neon.callbacks.callbacks import Callback from neon import logger from inference import get_boxes from util.voc_eval import voc_eval as voc_eval from util.util import plot_image as plot_image import os """ We include two callbacks that can be activated during training. 1. The MAP Callback computes the Mean Average Precision at every epoch 2. The ssd_image_callback saves sample inference results at every epoch """ class MAP_Callback(Callback): def __init__(self, eval_set, epoch_freq=1): super(MAP_Callback, self).__init__(epoch_freq=epoch_freq) self.eval_set = eval_set def on_epoch_end(self, callback_data, model, epoch): all_boxes = [] all_gt_boxes = [] logger.info('Calculating Mean AP on eval set') self.eval_set.reset() (all_boxes, all_gt_boxes) = get_boxes(model, self.eval_set) MAP = voc_eval( all_boxes, all_gt_boxes, self.eval_set.CLASSES, use_07_metric=True, verbose=False) logger.info('AP scores: %s' % ' '.join([ky+':' + '%.2f' % val for ky, val in MAP.items()])) logger.info('Mean AP: %.2f' % np.mean([MAP[ky] for ky in MAP])) class ssd_image_callback(Callback): def __init__(self, eval_set, image_dir, classes, plot_labels=True, num_images=5, epoch_freq=1, score_threshold=0.6): super(ssd_image_callback, self).__init__(epoch_freq=epoch_freq) self.eval_set = eval_set self.image_dir = image_dir self.num_images = num_images self.classes = classes self.score_threshold = score_threshold if not os.path.exists(image_dir): os.mkdir(image_dir) logger.info('Creating folder for sample images: {}'.format(image_dir)) def on_epoch_end(self, callback_data, model, epoch): self.eval_set.reset() eval_set = self.eval_set.__iter__() n = 0 while n < self.num_images: (x, t) = eval_set.next() (gt_boxes, gt_classes, num_gt_boxes, difficult, im_shape) = t gt_boxes = gt_boxes.reshape((-1, 4, self.be.bsz)) outputs = model.fprop(x, inference=True) images = x.get() for k, output in enumerate(outputs): ngt = num_gt_boxes[0, k] # creates a PIL image object with the gt_boxes and predicted boxes img = plot_image(img=images[:, k], im_shape=im_shape[:, k], gt_boxes=gt_boxes[:ngt, :, k], boxes=output, score_threshold=self.score_threshold) file_name = os.path.join(self.image_dir, 'image_e{}_{}.jpg'.format(epoch, n)) img.save(file_name) # logger.info('Saved sample images to: {}'.format(file_name)) n = n + 1 if n >= self.num_images: break
platypush/backend/joystick.py
RichardChiang/platypush
228
151881
<gh_stars>100-1000 import time from platypush.backend import Backend from platypush.message.event.joystick import JoystickEvent class JoystickBackend(Backend): """ This backend will listen for events from a joystick device and post a JoystickEvent whenever a new event is captured. Triggers: * :class:`platypush.message.event.joystick.JoystickEvent` when a new joystick event is received Requires: * **inputs** (``pip install inputs``) """ def __init__(self, device, *args, **kwargs): """ :param device: Path to the joystick device (e.g. `/dev/input/js0`) :type device_name: str """ super().__init__(*args, **kwargs) self.device = device def run(self): import inputs super().run() self.logger.info('Initialized joystick backend on device {}'.format(self.device)) while not self.should_stop(): try: events = inputs.get_gamepad() for event in events: if event.ev_type == 'Key' or event.ev_type == 'Absolute': self.bus.post(JoystickEvent(code=event.code, state=event.state)) except Exception as e: self.logger.exception(e) time.sleep(1) # vim:sw=4:ts=4:et:
analysis/aero/aero_ssam.py
leozz37/makani
1,178
151884
# Copyright 2020 Makani Technologies LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the 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 in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Contains the formulation of the SSAM model. Summary: This code calculates the local angle of attack and sideslip on the kite aerodynamic surfaces assuming rigid body mechanics about the c.g. of the kite. """ from makani.analysis.aero.hover_model import hover_model import numpy as np class SSAMModel(object): """Class used to determine local angles of attack on kite sections.""" def __init__(self, wing_model, wing_serial): """Initializes the SSAM model. Args: wing_model: Wing model (e.g. 'm600'). wing_serial: String giving the desired wing serial number (e.g. '01'). """ # Use the hover model to obtain the kite main wing panels. self._kite_params = hover_model.GetParams(wing_model, wing_serial, use_wake_model=False) # Rigid body mechanics require understanding of the c.g. location as the # wing is defined to rotate about the body c.g. and the freestream velocity # is assumed uniform everywhere. self._cg_loc_b = self._kite_params['center_of_mass_pos'] def GetMainWingAlphas(self, angular_rate_b, apparent_wind_b): """Computes the local alpha values on the main wing. Args: angular_rate_b: Array of shape (n,3) containing kite body rates. apparent_wind_b: Array of shape (n,3) containing apparent wind velocity components. Returns: main_wing_alphas_deg: Array of shape (n, x) containing the kite main wing local alpha values, where x is the number of kite main wing panels. """ assert len(np.shape(angular_rate_b)) == 2 assert np.shape(angular_rate_b)[1] assert np.shape(angular_rate_b) == np.shape(apparent_wind_b) # Pitch rate is ignored as it does not participate in the heaving motion of # any of the wing airfoils. angular_rate_b[:, 1] = 0.0 # Compute alpha values for each plane contained in the hover model where the # panel is located on the main wing. main_wing_alphas_deg = np.array([]) for panel in self._kite_params['panels']: if panel['name'].startswith('Wing'): panel_ac_pos_b = panel['pos_b'] panel_relative_incidence_deg = np.rad2deg(panel['relative_incidence']) # It is assumed that the kite rotates about its c.g. r_panel = panel_ac_pos_b - self._cg_loc_b # Expand the stationary r-position and reorient to match the omega # array size to enable the cross product. r_panel = np.repeat(np.expand_dims(r_panel, axis=1).transpose(), np.shape(angular_rate_b)[0], axis=0) panel_alpha_deg, _ = _ComputeRelativeAlphaBeta(angular_rate_b, r_panel, apparent_wind_b) # Account for washout if necessary. panel_alpha_deg += panel_relative_incidence_deg panel_alpha_deg = np.expand_dims(panel_alpha_deg, axis=1) if np.shape(main_wing_alphas_deg)[0] != np.shape(panel_alpha_deg)[0]: main_wing_alphas_deg = panel_alpha_deg else: main_wing_alphas_deg = np.concatenate((main_wing_alphas_deg, panel_alpha_deg), axis=1) return main_wing_alphas_deg def _ComputeRelativeAlphaBeta(omega_b, position_b, apparent_wind_b): """Computes the relative alpha and beta values, in degrees, from kinematics. Args: omega_b: Array of size (n, 3). Body rates of the kite [rad/s]. position_b: Array of size (1, 3). Position of the surface to compute local alpha/beta [m]. apparent_wind_b: Array of size (n,3). Apparent wind vector from the state estimator [m/s]. Returns: local_alpha_deg, local_beta_deg: The values of local alpha and beta. The math for a relative angle of attack at a given section is as follows: (1) Kinematically: v_section_b = apparent_wind_b - omega_b X position_b (2) By definition: alpha_rad = atan2(-v_section_b_z, -v_section_b_x) beta_rad = asin(-v_section_b_y, mag(v_section_b)) where _x, _y, _z denote the unit basis vectors in the body coordinates. """ assert np.shape(omega_b) == np.shape(apparent_wind_b) # The subtraction is because the cross product is the rigid body motion # but the reference frame for the aero has the opposite effect of the # motion of the rigid body motion frame. local_vel = apparent_wind_b - np.cross(omega_b, position_b, axisa=1, axisb=1) local_vel_mag = np.linalg.norm(local_vel, axis=1) local_alpha_deg = np.rad2deg(np.arctan2(-1.0 * local_vel[:, 2], -1.0 * local_vel[:, 0])) local_beta_deg = np.rad2deg(np.arcsin(-1.0 * local_vel[:, 1] / local_vel_mag)) return local_alpha_deg, local_beta_deg
tests/test_packages/test_skills/test_simple_service_registration/test_dialogues.py
bryanchriswhite/agents-aea
126
151885
# -*- coding: utf-8 -*- # ------------------------------------------------------------------------------ # # Copyright 2018-2019 Fetch.AI Limited # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the 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 in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # ------------------------------------------------------------------------------ """This module contains the tests of the dialogue classes of the simple_service_registration skill.""" from pathlib import Path from typing import cast from aea.helpers.search.models import Description from aea.test_tools.test_skill import BaseSkillTestCase from packages.fetchai.protocols.oef_search.message import OefSearchMessage from packages.fetchai.skills.simple_service_registration.dialogues import ( OefSearchDialogue, OefSearchDialogues, ) from tests.conftest import ROOT_DIR class TestDialogues(BaseSkillTestCase): """Test dialogue class of simple_service_registration.""" path_to_skill = Path( ROOT_DIR, "packages", "fetchai", "skills", "simple_service_registration" ) @classmethod def setup(cls): """Setup the test class.""" super().setup() cls.oef_search_dialogues = cast( OefSearchDialogues, cls._skill.skill_context.oef_search_dialogues ) cls.mocked_description = Description({"foo1": 1, "bar1": 2}) def test_oef_search_dialogues(self): """Test the OefSearchDialogue class.""" _, dialogue = self.oef_search_dialogues.create( counterparty=self.skill.skill_context.search_service_address, performative=OefSearchMessage.Performative.REGISTER_SERVICE, service_description=self.mocked_description, ) assert dialogue.role == OefSearchDialogue.Role.AGENT assert dialogue.self_address == str(self.skill.skill_context.skill_id)
ds2/disjointsets/__init__.py
aslisabanci/datastructures
159
151934
<gh_stars>100-1000 from ds2.disjointsets.disjointsets import ( DisjointSetsMapping, DisjointSetsLabels, DisjointSetsForest, DisjointSetsPathCompression, DisjointSetsTwoPassPC, DisjointSetsMergeByHeight, DisjointSetsMergeByWeight, DisjointSets )
tests/integration/testdata/buildcmd/Provided/main.py
renanmontebelo/aws-sam-cli
2,959
151950
import requests def handler(event, context): return requests.__version__
pyleus/cli/commands/run_subcommand.py
earthmine/pyleus
166
151958
<gh_stars>100-1000 """Sub-command base class for commands able to run a topology, as local or submit, starting either from a jar or from a pyleus topology source directory. Args: TOPOLOGY_JAR - The path to the Pyleus jar to run. """ from __future__ import absolute_import from pyleus.cli.commands.subcommand import SubCommand from pyleus.cli.topologies import is_jar class RunSubCommand(SubCommand): """Run subcommand class.""" # Override these in subclass NAME = None DESCRIPTION = None def add_specific_arguments(self, parser): """Override this method in order to add subcommand specific arguments. """ pass def add_arguments(self, parser): parser.add_argument( "topology_jar", metavar="TOPOLOGY_JAR", help="Path to a Pyleus topology jar.") self.add_specific_arguments(parser) def run_topology(jar_path, configs): """Subcommand specific run logic.""" raise NotImplementedError def run(self, configs): jar_path = configs.topology_jar if not is_jar(jar_path): self.error("Invalid jar: {0}".format(jar_path)) self.run_topology(jar_path, configs)
vyapp/plugins/pdb.py
iogf/vy
927
151977
<gh_stars>100-1000 """ Overview ======== This module implements a wrapper around python debugger it is possible to easily debug python applications. It is possible to set breakpoints, run code step by step, remove break points, check variable values etc. Key-Commands ============ Namespace: pdb Mode: PYTHON Event: <Key-1> Description: It starts debugging the opened python application with no command line arguments. Mode: PYTHON Event: <Key-2> Description: It starts the python application with command line arguments that use shlex module to split the arguments. Mode: PYTHON Event: <Key-x> Description: Ask for expression to be sent/evaluated. Mode: PYTHON Event: <Key-c> Description: Send a (c)ontinue to the debug process. Continue execution, only stop when a breakpoint is encountered. Mode: PYTHON Event: <Key-b> Description: Set a break point at the cursor line. Mode: PYTHON Event: <Key-B> Description: Set a temporary break point at the cursor line. Mode: PYTHON Event: <Control-C> Description: Clear all break points. Mode: PYTHON Event: <Control-c> Description: Remove break point that is set at the cursor line. Mode: PYTHON Event: <Key-p> Description: Evaluate selected text. Mode: PYTHON Event: <Key-m> Description: Send a PDB command to be executed. Mode: PYTHON Event: <Key-r> Description: Send restart. Mode: PYTHON Event: <Key-Q> Description: Terminate the process. """ from vyapp.regutils import RegexEvent from untwisted.splits import Terminator from vyapp.ask import Ask from vyapp.dap import DAP from vyapp.app import root import shlex class Pdb(DAP): def __call__(self, area, python='python2'): self.area = area area.install('pdb', ('PYTHON', '<Key-p>', self.evaluate_selection), ('PYTHON', '<Key-x>', self.evaluate_expression), ('PYTHON', '<Key-1>', self.run), ('PYTHON', '<Key-2>', self.run_args), ('PYTHON', '<Key-r>', self.send_restart), ('PYTHON', '<Key-m>', self.send_dcmd), ('PYTHON', '<Key-Q>', self.quit_db), ('PYTHON', '<Key-c>', self.send_continue), ('PYTHON', '<Control-C>', self.dump_clear_all), ('PYTHON', '<Control-c>', self.remove_breakpoint), ('PYTHON', '<Key-B>', self.send_tbreak), ('PYTHON', '<Key-b>', self.send_break)) self.python = python def evaluate_expression(self, event): ask = Ask() self.send("p %s\r\n" % ask.data) root.status.set_msg('(pdb) Sent expression!') def send(self, data): self.expect.send(data.encode(self.encoding)) print('Pdb Cmd: ', data) def send_break(self, event): self.send('break %s:%s\r\n' % (event.widget.filename, event.widget.indexref('insert')[0])) event.widget.chmode('NORMAL') root.status.set_msg('(pdb) Command break sent !') def send_tbreak(self, event): self.send('tbreak %s:%s\r\n' % (event.widget.filename, event.widget.indexref('insert')[0])) event.widget.chmode('NORMAL') root.status.set_msg('(pdb) Command tbreak sent !') def send_continue(self, event): """ """ self.send('continue\r\n') root.status.set_msg('(pdb) Command continue sent !') def send_restart(self, event): """ """ self.send('restart\r\n') root.status.set_msg('(pdb) Sent restart !') def evaluate_selection(self, event): data = event.widget.join_ranges('sel', sep='\r\n') self.send('p %s' % data) event.widget.chmode('NORMAL') root.status.set_msg('(pdb) Sent text selection!') def install_handles(self, device): Terminator(device, delim=b'\n') regstr0 = '\> (.+)\(([0-9]+)\).+' RegexEvent(device, regstr0, 'LINE', self.encoding) device.add_map('LINE', self.handle_line) def run(self, event): self.kill_process() self.create_process([self.python, '-u', '-m', 'pdb', event.widget.filename]) root.status.set_msg('(pdb) Started !') event.widget.chmode('NORMAL') def run_args(self, event): ask = Ask() ARGS = '%s -u -m pdb %s %s' % (self.python, event.widget.filename, ask.data) self.kill_process() ARGS = shlex.split(ARGS) self.create_process(ARGS) root.status.set_msg('(pdb) Started with Args: %s' % ask.data) event.widget.chmode('NORMAL') def dump_clear_all(self, event): self.send('clear\r\nyes\r\n') event.widget.chmode('NORMAL') root.status.set_msg('(pdb) Command clearall sent!') def remove_breakpoint(self, event): """ """ line, col = event.widget.indexref('insert') self.send('clear %s:%s\r\n' % (event.widget.filename, line)) event.widget.chmode('NORMAL') root.status.set_msg('(pdb) Command clear sent!') def send_dcmd(self, event): ask = Ask() self.send('%s\r\n' % ask.data) root.status.set_msg('(pdb) Sent cmd!') pdb = Pdb() install = pdb
tests/unit/test_hideable_query.py
rehee/try_discuz
1,140
151978
from flask_login import login_user from flaskbb.forum.models import Topic def test_guest_user_cannot_see_hidden_posts(guest, topic, user, request_context): topic.hide(user) login_user(guest) assert Topic.query.filter(Topic.id == topic.id).first() is None def test_regular_user_cannot_see_hidden_posts(topic, user, request_context): topic.hide(user) login_user(user) assert Topic.query.filter(Topic.id == topic.id).first() is None def test_moderator_user_can_see_hidden_posts(topic, moderator_user, request_context): topic.hide(moderator_user) login_user(moderator_user) assert Topic.query.filter(Topic.id == topic.id).first() is not None def test_super_moderator_user_can_see_hidden_posts(topic, super_moderator_user, request_context): topic.hide(super_moderator_user) login_user(super_moderator_user) assert Topic.query.filter(Topic.id == topic.id).first() is not None def test_admin_user_can_see_hidden_posts(topic, admin_user, request_context): topic.hide(admin_user) login_user(admin_user) assert Topic.query.filter(Topic.id == topic.id).first() is not None
tests/inputs/oneof_default_value_serialization/test_oneof_default_value_serialization.py
DK99/python-betterproto
708
152005
<filename>tests/inputs/oneof_default_value_serialization/test_oneof_default_value_serialization.py import pytest import datetime import betterproto from tests.output_betterproto.oneof_default_value_serialization import ( Test, Message, NestedMessage, ) def assert_round_trip_serialization_works(message: Test) -> None: assert betterproto.which_one_of(message, "value_type") == betterproto.which_one_of( Test().from_json(message.to_json()), "value_type" ) def test_oneof_default_value_serialization_works_for_all_values(): """ Serialization from message with oneof set to default -> JSON -> message should keep default value field intact. """ test_cases = [ Test(bool_value=False), Test(int64_value=0), Test( timestamp_value=datetime.datetime( year=1970, month=1, day=1, hour=0, minute=0, tzinfo=datetime.timezone.utc, ) ), Test(duration_value=datetime.timedelta(0)), Test(wrapped_message_value=Message(value=0)), # NOTE: Do NOT use betterproto.BoolValue here, it will cause JSON serialization # errors. # TODO: Do we want to allow use of BoolValue directly within a wrapped field or # should we simply hard fail here? Test(wrapped_bool_value=False), ] for message in test_cases: assert_round_trip_serialization_works(message) def test_oneof_no_default_values_passed(): message = Test() assert ( betterproto.which_one_of(message, "value_type") == betterproto.which_one_of(Test().from_json(message.to_json()), "value_type") == ("", None) ) def test_oneof_nested_oneof_messages_are_serialized_with_defaults(): """ Nested messages with oneofs should also be handled """ message = Test( wrapped_nested_message_value=NestedMessage( id=0, wrapped_message_value=Message(value=0) ) ) assert ( betterproto.which_one_of(message, "value_type") == betterproto.which_one_of(Test().from_json(message.to_json()), "value_type") == ( "wrapped_nested_message_value", NestedMessage(id=0, wrapped_message_value=Message(value=0)), ) )
src/utils/utlis.py
vishalsingh17/CNN-Visualizer
6,207
152015
<filename>src/utils/utlis.py import tensorflow as tf from json import dump assert(int(tf.__version__.split('.')[0]) == 2) def convert_h5_to_json(model_h5_file, model_json_file): """ Helper function to convert tf2 stored model h5 file to a customized json format. Args: model_h5_file(string): filename of the stored h5 file model_json_file(string): filename of the output json file """ model = tf.keras.models.load_model(model_h5_file) json_dict = {} for l in model.layers: json_dict[l.name] = { 'input_shape': l.input_shape[1:], 'output_shape': l.output_shape[1:], 'num_neurons': l.output_shape[-1] } if 'conv' in l.name: all_weights = l.weights[0] neuron_weights = [] # Iterate through neurons in that layer for n in range(all_weights.shape[3]): cur_neuron_dict = {} cur_neuron_dict['bias'] = l.bias.numpy()[n].item() # Get the current weights cur_weights = all_weights[:, :, :, n].numpy().astype(float) # Reshape the weights from (height, width, input_c) to # (input_c, height, width) cur_weights = cur_weights.transpose((2, 0, 1)).tolist() cur_neuron_dict['weights'] = cur_weights neuron_weights.append(cur_neuron_dict) json_dict[l.name]['weights'] = neuron_weights elif 'output' in l.name: all_weights = l.weights[0] neuron_weights = [] # Iterate through neurons in that layer for n in range(all_weights.shape[1]): cur_neuron_dict = {} cur_neuron_dict['bias'] = l.bias.numpy()[n].item() # Get the current weights cur_weights = all_weights[:, n].numpy().astype(float).tolist() cur_neuron_dict['weights'] = cur_weights neuron_weights.append(cur_neuron_dict) json_dict[l.name]['weights'] = neuron_weights dump(json_dict, open(model_json_file, 'w'), indent=2)
tests/test_subtract.py
josemolinagarcia/maya-math-nodes
148
152021
# Copyright (c) 2018 <NAME> et al. All rights reserved. # Use of this source code is governed by an MIT license that can be found in the LICENSE file. from node_test_case import NodeTestCase class TestSubtract(NodeTestCase): def test_subtract(self): self.create_node('Subtract', {'input1': 10.0, 'input2': 5.0}, 5.0) def test_subtract_int(self): self.create_node('SubtractInt', {'input1': 10, 'input2': 5}, 5) def test_subtract_angle(self): self.create_node('SubtractAngle', {'input1': 10.0, 'input2': 5.0}, 5.0) def test_subtract_vector(self): self.create_node('SubtractVector', {'input1': [5.0, 5.0, 5.0], 'input2': [2.0, 2.0, 2.0]}, [3.0, 3.0, 3.0])
setup.py
DanNixon/PlayMusicCL
134
152036
<reponame>DanNixon/PlayMusicCL<gh_stars>100-1000 from setuptools import setup setup( name='playmusiccl', version='0.6.2', entry_points = { 'console_scripts': ['playmusiccl=playmusiccl:run'], }, description='Text based command line client for Google Play Music', classifiers=[ 'License :: OSI Approved :: Apache Software License', 'Natural Language :: English', 'Programming Language :: Python :: 2.7', 'Topic :: Multimedia :: Sound/Audio :: Players', ], keywords='google play music command line', url='http://github.com/DanNixon/PlayMusicCL', author='<NAME>', author_email='<EMAIL>', license='Apache', packages=['playmusiccl'], install_requires=[ 'gmusicapi', 'pylast', ], include_package_data=True, zip_safe=False )
sleepypuppy/__init__.py
soffensive/sleepy-puppy
952
152049
<gh_stars>100-1000 from logging import Formatter from logging.handlers import RotatingFileHandler from flask import Flask, redirect, request, abort, send_from_directory from flask.ext import login from flask.ext.bcrypt import Bcrypt from flask.ext.restful import Api from flask.ext.admin import Admin from flask.ext.mail import Mail from functools import wraps from flask.ext.sqlalchemy import SQLAlchemy import flask_wtf import os # Config and App setups app = Flask(__name__, static_folder='static') app.config.from_object('config-default') app.config.update(dict( PREFERRED_URL_SCHEME='https' )) app.debug = app.config.get('DEBUG') # Log handler functionality handler = RotatingFileHandler(app.config.get('LOG_FILE'), maxBytes=10000000, backupCount=100) handler.setFormatter( Formatter( '%(asctime)s %(levelname)s: %(message)s ' '[in %(pathname)s:%(lineno)d]' ) ) handler.setLevel(app.config.get('LOG_LEVEL')) app.logger.addHandler(handler) def ssl_required(fn): """ SSL decorator """ @wraps(fn) def decorated_view(*args, **kwargs): if app.config.get("SSL"): if request.is_secure: return fn(*args, **kwargs) else: return redirect(request.url.replace("http://", "https://")) return fn(*args, **kwargs) return decorated_view # CSRF Protection csrf_protect = flask_wtf.CsrfProtect(app) # Initialize DB object db = SQLAlchemy(app) # Initialize Bcrypt object for password hashing bcrypt = Bcrypt(app) # Initialize flask mail object for email notifications flask_mail = Mail(app) # Decorator for Token Auth on API Requests from sleepypuppy.admin.admin.models import Administrator def require_appkey(view_function): """ Decorator for api using token based authentication """ @wraps(view_function) def decorated_function(*args, **kwargs): # If the user is attempting to get list of puppyscripts # return the puppyscripts without token auth if request.method == "GET" and request.path.split('/')[2] == 'puppyscript_loader': return view_function(*args, **kwargs) if request.headers.get('Token'): for keys in Administrator.query.all(): if request.headers.get('Token') == keys.api_key: return view_function(*args, **kwargs) abort(401) else: abort(401) return decorated_function # Initialize the Flask API flask_api = Api(app, decorators=[csrf_protect.exempt, require_appkey]) def init_login(): """ Initialize the Flask Login manager """ login_manager = login.LoginManager() login_manager.init_app(app) login_manager.session_protection = "strong" # Create user loader function @login_manager.user_loader def load_user(user_id): return db.session.query(Administrator).get(user_id) # Create the Flask Admin object from admin.admin.views import MyAdminIndexView, AdministratorView flask_admin = Admin(app, 'Sleepy Puppy', index_view=MyAdminIndexView(url='/'), base_template='admin/base.html', template_mode='bootstrap3') # Initialize the login manager for sleepy puppy init_login() # Import the collector which is used to collect capture information from collector import views # Import the screenshot upload handler from upload import upload # noqa # Initialize all Flask API views from api.views import PuppyscriptAssociations, CaptureView, CaptureViewList, PuppyscriptView, PuppyscriptViewList, PayloadView, PayloadViewList, AccessLogView, AccessLogViewList, AssessmentView, AssessmentViewList, GenericCollectorView, GenericCollectorViewList, AssessmentPayloads # noqa flask_api.add_resource(AssessmentViewList, '/api/assessments') flask_api.add_resource(AssessmentView, '/api/assessments/<int:id>') flask_api.add_resource(CaptureViewList, '/api/captures') flask_api.add_resource(CaptureView, '/api/captures/<int:id>') flask_api.add_resource(PuppyscriptView, '/api/puppyscript/<int:id>') flask_api.add_resource(PuppyscriptViewList, '/api/puppyscript') flask_api.add_resource(PayloadViewList, '/api/payloads') flask_api.add_resource(PayloadView, '/api/payloads/<int:id>') flask_api.add_resource(AccessLogViewList, '/api/access_log') flask_api.add_resource(AccessLogView, '/api/access_log/<int:id>') flask_api.add_resource(GenericCollectorViewList, '/api/generic_collector') flask_api.add_resource(GenericCollectorView, '/api/generic_collector/<int:id>') flask_api.add_resource(PuppyscriptAssociations, '/api/puppyscript_loader/<int:id>') flask_api.add_resource(AssessmentPayloads, '/api/assessment_payloads/<int:id>') # Initialize all Flask Admin dashboard views from admin.capture.views import CaptureView from admin.access_log.views import AccessLogView from admin.puppyscript.views import PuppyscriptView from admin.payload.views import PayloadView from admin.user.views import UserView from admin.assessment.views import AssessmentView from admin.collector.views import GenericCollectorView # Import the API views from admin import views # noqa # Configure mappers for db associations from sqlalchemy.orm import configure_mappers configure_mappers() # # Add all Flask Admin routes flask_admin.add_view(PuppyscriptView(db.session)) flask_admin.add_view(PayloadView(db.session)) flask_admin.add_view(CaptureView(db.session)) flask_admin.add_view(GenericCollectorView(db.session)) flask_admin.add_view(AccessLogView(db.session)) flask_admin.add_view(UserView(db.session)) flask_admin.add_view(AssessmentView(db.session)) flask_admin.add_view(AdministratorView(Administrator, db.session)) @app.after_request def after_request(response): response.headers.add('Access-Control-Allow-Origin', '*') response.headers.add('Access-Control-Allow-Methods', 'GET,POST') return response # # Route to serve static asset files via Flask @app.route('/static/<filename>') def send_js(filename): return send_from_directory(app.static_folder, filename) @app.route('/favicon.ico') def favicon(): return send_from_directory(os.path.join(app.root_path, 'static'), 'favicon.ico', mimetype='image/vnd.microsoft.icon')
setup/release.py
gamechanger/dusty
421
152080
import os import tarfile from github3 import login token = os.getenv('GITHUB_TOKEN') gh = login(token=token) repo = gh.repository('gamechanger', 'dusty') version = os.getenv('VERSION') prerelease = os.getenv('PRERELEASE') == 'true' release_name = version release = repo.create_release(version, name=release_name, prerelease=prerelease) for setup_file in ['com.gamechanger.dusty.plist', 'install.sh']: with open(os.path.join('setup', setup_file), 'r') as f: release.upload_asset(content_type='text/plain', name=setup_file, asset=f) for binary in ['dusty']: with open(os.path.join('dist', binary), 'r') as f: release.upload_asset(content_type='application/octet-stream', name=binary, asset=f) with tarfile.open('dusty.tar.gz', 'w:gz') as tarball: tarball.add('dist/dusty', arcname='dusty') tarball.add('setup/com.gamechanger.dusty.plist', arcname='com.gamechanger.dusty.plist') tarball.add('setup/brew-install.sh', arcname='brew-install.sh') with open('dusty.tar.gz', 'r') as f: release.upload_asset(content_type='application/octet-stream', name='dusty.tar.gz', asset=f)
caffe2/python/tutorials/py_gen/Image_Pre-Processing_Pipeline.py
AIHGF/caffe2
585
152089
######################################################### # # DO NOT EDIT THIS FILE. IT IS GENERATED AUTOMATICALLY. # # PLEASE LOOK INTO THE README FOR MORE INFORMATION. # # ######################################################### # coding: utf-8 # # Image Loading and Preprocessing # # In this tutorial we're going to look at how we can load in images from a local file or a URL which you can then utilize in other tutorials or examples. Also, we're going to go in depth on the kinds of preprocessing that is necessary to utilize Caffe2 with images. # # #### Mac OSx Prerequisites # # If you don't already have these Python modules installed you'll need to do that now. # # ``` # sudo pip install scikit-image scipy matplotlib # ``` # In[1]: import skimage import skimage.io as io import skimage.transform import sys import numpy as np import math from matplotlib import pyplot import matplotlib.image as mpimg print("Required modules imported.") # ## Test an Image # # In the code block below use IMAGE_LOCATION to load what you would like to test. Just change the comment flags to go through each round of the Tutorial. In this way, you'll get to see what happens with a variety of image formats and some tips on how you might preprocess them. If you want to try your own image, drop it in the images folder or use a remote URL. When you pick a remote URL, make it easy on yourself and try to find a URL that points to a common image file type and extension versus some long identifier or query string which might just break this next step. # # ## Color Issues # # Keep in mind when you load images from smartphone cameras that you may run into color formatting issues. Below we show an example of how flipping between RGB and BGR can impact an image. This would obviously throw off detection in your model. Make sure the image data you're passing around is what you think it is! # # ### Caffe Uses BGR Order # # Due to legacy support of OpenCV in Caffe and how it handles images in Blue-Green-Red (BGR) order instead of the more commonly used Red-Green-Blue (RGB) order, Caffe2 also expects **BGR** order. In many ways this decision helps in the long run as you use different computer vision utilities and libraries, but it also can be the source of confusion. # In[2]: # You can load either local IMAGE_FILE or remote URL # For Round 1 of this tutorial, try a local image. IMAGE_LOCATION = 'images/cat.jpg' # For Round 2 of this tutorial, try a URL image with a flower: # IMAGE_LOCATION = "https://cdn.pixabay.com/photo/2015/02/10/21/28/flower-631765_1280.jpg" # IMAGE_LOCATION = "images/flower.jpg" # For Round 3 of this tutorial, try another URL image with lots of people: # IMAGE_LOCATION = "https://upload.wikimedia.org/wikipedia/commons/1/18/NASA_Astronaut_Group_15.jpg" # IMAGE_LOCATION = "images/astronauts.jpg" # For Round 4 of this tutorial, try a URL image with a portrait! # IMAGE_LOCATION = "https://upload.wikimedia.org/wikipedia/commons/9/9a/Ducreux1.jpg" # IMAGE_LOCATION = "images/Ducreux.jpg" img = skimage.img_as_float(skimage.io.imread(IMAGE_LOCATION)).astype(np.float32) # test color reading # show the original image pyplot.figure() pyplot.subplot(1,2,1) pyplot.imshow(img) pyplot.axis('on') pyplot.title('Original image = RGB') # show the image in BGR - just doing RGB->BGR temporarily for display imgBGR = img[:, :, (2, 1, 0)] #pyplot.figure() pyplot.subplot(1,2,2) pyplot.imshow(imgBGR) pyplot.axis('on') pyplot.title('OpenCV, Caffe2 = BGR') # As you can see in the example above, the difference in order is very important to keep in mind. In the code block below we'll be taking the image and converting to BGR order for Caffe to process it appropriately. # # But wait, there's more color fun... # # ### Caffe Prefers CHW Order # # Now what!? What's CHW, you ask? Well, there's also HWC! Both formats come up in image processing. # # - H: Height # - W: Width # - C: Channel (as in color) # # Digging even deeper into how image data can be stored is the memory allocation order. You might have noticed when we first loaded the image that we forced it through some interesting transformations. These were data transformations that let us play with the image as if it were a cube. What we see is on top of the cube, and manipulating the layers below can change what we view. We can tinker with it's underlying properties and as you saw above, swap colors quite easily. # # For GPU processing, which is what Caffe2 excels at, this order needs to be CHW. For CPU processing, this order is generally HWC. Essentially, you're going to want to use CHW and make sure that step is included in your image pipeline. Tweak RGB to be BGR, which is encapsulated as this "C" payload, then tweak HWC, the "C" being the very same colors you just switched around. # # You may ask why! And the reason points to cuDNN which is what helps accelerate processing on GPUs. It uses only CHW, and we'll sum it up by saying it is faster. # # Give these two transformations, you might think that's enough, but it isn't. We still need to resize and/or crop and potentially look at things like orientation (rotation) and mirroring. # # ## Rotation and Mirroring # # This topic is usually reserved for images that are coming from a smart phone. Phones, in general, take great pictures, but do a horrible job communicating how the image was taken and what orientation it should be in. Then there's the user who does everything under the sun with their phone's cameras, making them do things its designer never expected. Cameras - right, because there are often two cameras and these two cameras take different sized pictures in both pixel count and aspect ratio, and not only that, they sometimes take them mirrored, and they sometimes take them in portrait and landscape modes, and sometimes they don't bother to tell which mode they were in. # # In many ways this is the first thing you need to evaluate in your pipeline, then look at sizing (described below), then figure out the color situation. If you're developing for iOS, then you're in luck, it's going to be relatively easy. If you're a super-hacker wizard developer with lead-lined shorts and developing for Android, then at least you have lead-lined shorts. # # The variability in the Android marketplace is wonderful and horrifying. In an ideal world, you could rely on the EXIF data in pictures coming from any camera and use that to decide orientation and mirroring and you'd have one simple case function to handle your transformations. No such luck, but you're not alone. Many have come before you and suffered for you. # # ### Library for Handling Mobile Images # # Hooray! We're going to give you something to ease your pain. These are not full-proof. Users can and will defy you and every other developers' best attempts to handle their images. Here we'll link to some resources that can be used depending on the platform. # # Image Preprocessing Libraries and/or Snippits # - [iOS](#) # - [Android](#) # - [Python](#) # In the meantime though, let's play with some images and show the basics for manipulations that you might need to do. # In[3]: # Image came in sideways - it should be a portait image! # How you detect this depends on the platform # Could be a flag from the camera object # Could be in the EXIF data # ROTATED_IMAGE = "https://upload.wikimedia.org/wikipedia/commons/8/87/Cell_Phone_Tower_in_Ladakh_India_with_Buddhist_Prayer_Flags.jpg" ROTATED_IMAGE = "images/cell-tower.jpg" imgRotated = skimage.img_as_float(skimage.io.imread(ROTATED_IMAGE)).astype(np.float32) pyplot.figure() pyplot.imshow(imgRotated) pyplot.axis('on') pyplot.title('Rotated image') # Image came in flipped or mirrored - text is backwards! # Again detection depends on the platform # This one is intended to be read by drivers in their rear-view mirror # MIRROR_IMAGE = "https://upload.wikimedia.org/wikipedia/commons/2/27/Mirror_image_sign_to_be_read_by_drivers_who_are_backing_up_-b.JPG" MIRROR_IMAGE = "images/mirror-image.jpg" imgMirror = skimage.img_as_float(skimage.io.imread(MIRROR_IMAGE)).astype(np.float32) pyplot.figure() pyplot.imshow(imgMirror) pyplot.axis('on') pyplot.title('Mirror image') # So you can see that we kind of have some problems. If we're detecting places, landmarks, or objects, a sideways cell tower is no good. If we're detecting text and doing automatic language translation, then mirrored text is no good. But hey, maybe you want to make a model that can detect English both ways. That would be awesome, but not for this tutorial! # # Let's transform these babies into something Caffe2 and the standard detection models we have around can detect. Also, this little trick might save you if, say for example, you really had to detect the cell tower but there's no EXIF data to be found: then you'd cycle through every rotation, and every flip, spawning many derivatives of this photo and run them all through. When the percentage of confidence of detection is high enough, Bam!, you found the orientation you needed and that sneaky cell tower. # # Anyway, to the example code: # In[4]: # Run me to flip the image back and forth imgMirror = np.fliplr(imgMirror) pyplot.figure() pyplot.imshow(imgMirror) pyplot.axis('off') pyplot.title('Mirror image') # In[5]: # Run me to rotate the image 90 degrees imgRotated = np.rot90(imgRotated) pyplot.figure() pyplot.imshow(imgRotated) pyplot.axis('off') pyplot.title('Rotated image') # ## Sizing # # Part of preprocessing is resizing. For reasons we won't get into here, images in the Caffe2 pipeline should be square. Also, to help with performance, they should be resized to a standard height and width which is usually going to be smaller than your original source. In the example below we're resizing to 256 x 256 pixels, however you might notice that the `input_height` and `input_width` is set to 224 x 224 which is then used to specify the crop. This is what several image-based models are expecting. They were trained on images sized to 224 x 224 and in order for the model to properly identify the suspect images you throw at it, these should also be 224 x 224. # # ** Make sure you double-check the input sizes for the model you're using!** # In[6]: # Model is expecting 224 x 224, so resize/crop needed. # Here are the steps we use to preprocess the image. # (1) Resize the image to 256*256, and crop out the center. input_height, input_width = 224, 224 print("Model's input shape is %dx%d") % (input_height, input_width) #print("Original image is %dx%d") % (skimage.) img256 = skimage.transform.resize(img, (256, 256)) pyplot.figure() pyplot.imshow(img256) pyplot.axis('on') pyplot.title('Resized image to 256x256') print("New image shape:" + str(img256.shape)) # Note the resizing has distorted the image a little bit. It is important to recognize this effect during your processing as it can have an effect on the results of your model. Flowers and animals might be ok with a little stretching or squeezing, but facial features may not. # # This can happen when the dimensions of the original image are not proportionally exact to your desired size. In this particular example it would have been better to just resize to 224x224 and not bother cropping. Let's try another strategy of rescaling the image and maintaining the aspect ratio. # # ### Rescaling # # If you imagine portait images versus landscape images you'll know that there are a lot of things that can get messed up by doing a slopping resize. Rescaling is assuming that you're locking down the aspect ratio to prevent distortion in the image. In this case, we'll scale down the image to the shortest side that matches with the model's input size. # # In our example here, the model size is 224 x 224. As you look at your monitor in 1920x1080, it is longer in width than height and if you shrunk it down to 224, you'd run out of height before you ran out of width, so... # # - Landscape: limit resize by the height # - Portrait: limit resize by the width # In[7]: print("Original image shape:" + str(img.shape) + " and remember it should be in H, W, C!") print("Model's input shape is %dx%d") % (input_height, input_width) aspect = img.shape[1]/float(img.shape[0]) print("Orginal aspect ratio: " + str(aspect)) if(aspect>1): # landscape orientation - wide image res = int(aspect * input_height) imgScaled = skimage.transform.resize(img, (input_height, res)) if(aspect<1): # portrait orientation - tall image res = int(input_width/aspect) imgScaled = skimage.transform.resize(img, (res, input_width)) if(aspect == 1): imgScaled = skimage.transform.resize(img, (input_height, input_width)) pyplot.figure() pyplot.imshow(imgScaled) pyplot.axis('on') pyplot.title('Rescaled image') print("New image shape:" + str(imgScaled.shape) + " in HWC") # At this point only one dimension is set to what the model's input requires. We still need to crop one side to make a square. # # ### Cropping # # There are a variety of strategies we could utilize. In fact, we could backpeddle and decide to do a center crop. So instead of scaling down to the smallest we could get on at least one side, we take a chunk out of the middle. If we had done that without scaling we would have ended up with just part of a flower pedal, so we still needed some resizing of the image. # # Below we'll try a few strategies for cropping: # # 1. Just grab the exact dimensions you need from the middle! # 2. Resize to a square that's pretty close then grab from the middle. # 3. Use the rescaled image and grab the middle. # In[8]: # Compare the images and cropping strategies # Try a center crop on the original for giggles print("Original image shape:" + str(img.shape) + " and remember it should be in H, W, C!") def crop_center(img,cropx,cropy): y,x,c = img.shape startx = x//2-(cropx//2) starty = y//2-(cropy//2) return img[starty:starty+cropy,startx:startx+cropx] # yes, the function above should match resize and take a tuple... pyplot.figure() # Original image imgCenter = crop_center(img,224,224) pyplot.subplot(1,3,1) pyplot.imshow(imgCenter) pyplot.axis('on') pyplot.title('Original') # Now let's see what this does on the distorted image img256Center = crop_center(img256,224,224) pyplot.subplot(1,3,2) pyplot.imshow(img256Center) pyplot.axis('on') pyplot.title('Squeezed') # Scaled image imgScaledCenter = crop_center(imgScaled,224,224) pyplot.subplot(1,3,3) pyplot.imshow(imgScaledCenter) pyplot.axis('on') pyplot.title('Scaled') # As you can see that didn't work out so well, except for maybe the last one. The middle one may be just fine too, but you won't know until you try on the model and test a lot of candidate images. # At this point we can look at the difference we have, split it in half and remove some pixels from each side. This does have a drawback, however, as an off-center subject of interest would get clipped. # If you've run this tutorial a few times now and are on Round 3, you'll notice a pretty big problem. You're missing astronaughts! You can still see the issue with the flower from Round 2 as well. Things are missing after the cropping and that could cause you problems. Think of it this way: if you don't know how the model you're using was prepared then you don't know how to conform your images, so take care to test results! If the model used a lot of different aspect ratio images and just squeezed them to conform to a square then there's a good chance that over time and lots of samples it "learned" what things look like squeezed and can make a match. However, if you're looking for details like facial features and landmarks, or really nuanced elements in any image, this could be dangerous and error-prone. # # #### Further Strategies? # # Another strategy would be to rescale to the best size you can, with real data, but then pad the rest of the image with information that you can safely ignore in your model. We'll save that for another tutorial though since you've been through enough here! # # ### Upscaling # # What do you do when the images you want to run are "tiny"? In our example we've been prepping for Input Images with the spec of 224x224. Consider this 128x128 image below. # ![cells at 128x128](images/Cellsx128.png) # Now we're not talking about super-resolution or the CSI-effect where we can take blurry ATM photos and identify the tattoo an a perp's neck. Although, there are [some advances](https://github.com/david-gpu/srez) along these lines that deep learning has provided, and if you're reading this in time (before 3/1/17), go [check this out](https://developer.nvidia.com/zoom-enhance-magic-image-upscaling-using-deep-learning). What we want to do is simple, but, like cropping, it does have a variety of strategies you should consider. # # The most basic approach is going from a small square to a bigger square and using the defauls skimage provides for you. This `resize` method defaults the interpolation order parameter to 1 which happens to be bi-linear if you even cared, but it is worth mentioning because these might be the fine-tuning knobs you need later to fix problems, such as strange visual artifacts, that can be introduced in upscaling images. # In[9]: imgTiny = "images/Cellsx128.png" imgTiny = skimage.img_as_float(skimage.io.imread(imgTiny)).astype(np.float32) print "Original image shape: ", imgTiny.shape imgTiny224 = skimage.transform.resize(imgTiny, (224, 224)) print "Upscaled image shape: ", imgTiny224.shape # Plot original pyplot.figure() pyplot.subplot(1, 2, 1) pyplot.imshow(imgTiny) pyplot.axis('on') pyplot.title('128x128') # Plot upscaled pyplot.subplot(1, 2, 2) pyplot.imshow(imgTiny224) pyplot.axis('on') pyplot.title('224x224') # Great, it worked!. You can see in the shape outputs that you had (128, 128, 4) and you received (224, 224, 4). Wait a minute! 4? In every example so far the last value in shape has been 3! When we used a png file we entered a new reality; one where transparency is possible. This 4th value describes opacity, or transparency, depending if you're a half-glass-empty type. Anyway, we can handle it just fine, but keep an eye on that number. # # It's appropriate to put this discussion towards the end, but before we do further manipulations to the image, it's data order, and its overall payload. You can really mess up your data and the image if you do a simple resample on the image in its current format. Remember that it is currently a cube of data and that there's more going on in there right now than just Red, Green, and Blue (and opacity). Depending on when you decide to resize you'll have to account for that extra data. # # Let's break stuff! Try upscaling the image after you've switched the image to CHW. # In[10]: imgTiny = "images/Cellsx128.png" imgTiny = skimage.img_as_float(skimage.io.imread(imgTiny)).astype(np.float32) print "Image shape before HWC --> CHW conversion: ", imgTiny.shape # swapping the axes to go from HWC to CHW # uncomment the next line and run this block! imgTiny = imgTiny.swapaxes(1, 2).swapaxes(0, 1) print "Image shape after HWC --> CHW conversion: ", imgTiny.shape imgTiny224 = skimage.transform.resize(imgTiny, (224, 224)) print "Image shape after resize: ", imgTiny224.shape # we know this is going to go wrong, so... try: # Plot original pyplot.figure() pyplot.subplot(1, 2, 1) pyplot.imshow(imgTiny) pyplot.axis('on') pyplot.title('128x128') except: print "Here come bad things!" # hands up if you want to see the error (uncomment next line) #raise # Epic fail, right? If you let the code block above swap the axes, then resize the image, you will see this output: # # `Image shape after resize: (224, 224, 128)` # # Now you have 128 where you should still have 4. Oops. Let's revert in the code block below and try something else. We'll show an example where the image is smaller than your Input specification, and not square. Like maybe it came from a new microscope that can only take imagery in rectangular bands. # In[11]: imgTiny = "images/Cellsx128.png" imgTiny = skimage.img_as_float(skimage.io.imread(imgTiny)).astype(np.float32) imgTinySlice = crop_center(imgTiny, 128, 56) # Plot original pyplot.figure() pyplot.subplot(2, 1, 1) pyplot.imshow(imgTiny) pyplot.axis('on') pyplot.title('Original') # Plot slice pyplot.figure() pyplot.subplot(2, 2, 1) pyplot.imshow(imgTinySlice) pyplot.axis('on') pyplot.title('128x56') # Upscale? print "Slice image shape: ", imgTinySlice.shape imgTiny224 = skimage.transform.resize(imgTinySlice, (224, 224)) print "Upscaled slice image shape: ", imgTiny224.shape # Plot upscaled pyplot.subplot(2, 2, 2) pyplot.imshow(imgTiny224) pyplot.axis('on') pyplot.title('224x224') # Alright, this was a bit of a stretch for an example of how upscaling can fail. Get it? Stretch? This could be a life-or-death kind of failure though. What if normal cells are circular and diseased cells are elongated and bent? Sickle cell anemia for example: # ![sickle cells example](images/sickle-cells.jpg) # In this situation, what do you do? It really depends on the model and how it was trained. In some cases it may be ok to pad the rest of the image with white, or maybe black, or maybe noise, or maybe even use png and transparencies and set a mask for the images so the model ignores transparent areas. See how much fun you can have figuring this out and you get to make medical breakthroughs too! # Let's move on to the last step which we've already mentioned and that is to adjust the image input to be in BGR order. There's also another feature that Caffe2 uses, which is a `batch term`. We've already talked about CHW. This is the N, for number of images in NCHW. # # ### Final Preprocessing and the Batch Term # # In the last steps below we are going to switch the image's data order to BGR, stuff that into the Color column, then reoder the columns for GPU processing (HCW-->CHW) and then add a fourth dimension (N) to the image to track the number of images. In theory, you can just keep adding dimensions to your data, but this one is required for Caffe2 as it relays to Caffe how many images to expect in this batch. We set it to one (1) to indicate there's only one image going into Caffe in this batch. Note that in the final output when we check `img.shape` the order is quite different. We've added N for number of images, and changed the order like so: `N, C, H, W` # In[12]: # this next line helps with being able to rerun this section # if you want to try the outputs of the different crop strategies above # swap out imgScaled with img (original) or img256 (squeezed) imgCropped = crop_center(imgScaled,224,224) print "Image shape before HWC --> CHW conversion: ", imgCropped.shape # (1) Since Caffe expects CHW order and the current image is HWC, # we will need to change the order. imgCropped = imgCropped.swapaxes(1, 2).swapaxes(0, 1) print "Image shape after HWC --> CHW conversion: ", imgCropped.shape pyplot.figure() for i in range(3): # For some reason, pyplot subplot follows Matlab's indexing # convention (starting with 1). Well, we'll just follow it... pyplot.subplot(1, 3, i+1) pyplot.imshow(imgCropped[i]) pyplot.axis('off') pyplot.title('RGB channel %d' % (i+1)) # (2) Caffe uses a BGR order due to legacy OpenCV issues, so we # will change RGB to BGR. imgCropped = imgCropped[(2, 1, 0), :, :] print "Image shape after BGR conversion: ", imgCropped.shape # for discussion later - not helpful at this point # (3) We will subtract the mean image. Note that skimage loads # image in the [0, 1] range so we multiply the pixel values # first to get them into [0, 255]. #mean_file = os.path.join(CAFFE_ROOT, 'python/caffe/imagenet/ilsvrc_2012_mean.npy') #mean = np.load(mean_file).mean(1).mean(1) #img = img * 255 - mean[:, np.newaxis, np.newaxis] pyplot.figure() for i in range(3): # For some reason, pyplot subplot follows Matlab's indexing # convention (starting with 1). Well, we'll just follow it... pyplot.subplot(1, 3, i+1) pyplot.imshow(imgCropped[i]) pyplot.axis('off') pyplot.title('BGR channel %d' % (i+1)) # (4) finally, since caffe2 expect the input to have a batch term # so we can feed in multiple images, we will simply prepend a # batch dimension of size 1. Also, we will make sure image is # of type np.float32. imgCropped = imgCropped[np.newaxis, :, :, :].astype(np.float32) print 'Final input shape is:', imgCropped.shape # In the output above you should note these alterations: # 1. Before and after of the HWC to CHW change. The 3, which is the number of color channels moved to the beginning. # 2. In the pictures above you can see that the color order was switched too. RGB became BGR. Blue and Red switched places. # 3. The final input shape, meaning the last change to the image was to add the batch field to the beginning, so that now you have (1, 3, 224, 224) for: # - 1 image in the batch, # - 3 color channels (in BGR), # - 224 height, # - 224 width.
tests/L0/run_optimizers/test_lamb.py
Muflhi01/apex
6,523
152101
import unittest import os import torch from torch.optim import Optimizer import apex from apex.multi_tensor_apply import multi_tensor_applier from itertools import product class RefLAMB(Optimizer): r"""Implements Lamb algorithm. It has been proposed in `Large Batch Optimization for Deep Learning: Training BERT in 76 minutes`_. Arguments: params (iterable): iterable of parameters to optimize or dicts defining parameter groups lr (float, optional): learning rate (default: 1e-3) betas (Tuple[float, float], optional): coefficients used for computing running averages of gradient and its square (default: (0.9, 0.999)) eps (float, optional): term added to the denominator to improve numerical stability (default: 1e-6) weight_decay (float, optional): weight decay (L2 penalty) (default: 0.01) .. _Large Batch Optimization for Deep Learning: Training BERT in 76 minutes: https://arxiv.org/abs/1904.00962 """ def __init__(self, params, lr=1e-3, betas=(0.9, 0.999), eps=1e-6, weight_decay=0.01): if not 0.0 <= lr: raise ValueError("Invalid learning rate: {}".format(lr)) if not 0.0 <= eps: raise ValueError("Invalid epsilon value: {}".format(eps)) if not 0.0 <= betas[0] < 1.0: raise ValueError("Invalid beta parameter at index 0: {}".format(betas[0])) if not 0.0 <= betas[1] < 1.0: raise ValueError("Invalid beta parameter at index 1: {}".format(betas[1])) defaults = dict(lr=lr, betas=betas, eps=eps, weight_decay=weight_decay) super(RefLAMB, self).__init__(params, defaults) if multi_tensor_applier.available: import amp_C self.multi_tensor_l2norm=amp_C.multi_tensor_l2norm # Skip buffer self._dummy_overflow_buf = torch.tensor([0], dtype=torch.int, device=self.param_groups[0]["params"][0].device) self.multi_tensor_lamb = amp_C.multi_tensor_lamb else: raise RuntimeError('apex.optimizers.FusedLAMB requires cuda extensions') def step(self, closure=None): """Performs a single optimization step. Arguments: closure (callable, optional): A closure that reevaluates the model and returns the loss. """ loss = None if closure is not None: loss = closure() # create separate grad lists for fp32 and fp16 params g_all_32, g_all_16 = [], [] for group in self.param_groups: for p in group['params']: if p.grad is None: continue if p.dtype == torch.float32: g_all_32.append(p.grad.data) elif p.dtype == torch.float16: g_all_16.append(p.grad.data) else: raise RuntimeError('FusedLAMB only support fp16 and fp32.') device = self.param_groups[0]["params"][0].device g_norm_32, g_norm_16 = torch.zeros(1, device=device), torch.zeros(1, device=device) # compute grad norm for two lists if len(g_all_32) > 0: g_norm_32 = multi_tensor_applier(self.multi_tensor_l2norm, self._dummy_overflow_buf, [g_all_32], False)[0] if len(g_all_16) > 0: g_norm_16 = multi_tensor_applier(self.multi_tensor_l2norm, self._dummy_overflow_buf, [g_all_16], False)[0] # blend two grad norms to get global grad norm global_grad_norm = multi_tensor_applier(self.multi_tensor_l2norm, self._dummy_overflow_buf, [[g_norm_32, g_norm_16]], False)[0] max_grad_norm = 1.0 clipped_ratio = max_grad_norm / max(global_grad_norm, max_grad_norm) for group in self.param_groups: for p in group['params']: if p.grad is None: continue p.grad.data *= clipped_ratio grad = p.grad.data if grad.is_sparse: raise RuntimeError('Lamb does not support sparse gradients, consider SparseAdam instad.') state = self.state[p] # State initialization if len(state) == 0: state['step'] = 0 # Exponential moving average of gradient values state['m'] = torch.zeros_like(p.data) # Exponential moving average of squared gradient values state['v'] = torch.zeros_like(p.data) m_t, v_t = state['m'], state['v'] beta1, beta2 = group['betas'] state['step'] += 1 # m_t = beta1 * m + (1 - beta1) * g_t m_t.mul_(beta1).add_(grad, alpha=1-beta1) # v_t = beta2 * v + (1 - beta2) * (g_t * g_t) v_t.mul_(beta2).addcmul_(grad, grad, value=1-beta2) # Debiasing m_t_hat = m_t / (1.0 - beta1 ** state['step']) v_t_hat = v_t / (1.0 - beta2 ** state['step']) update = m_t_hat / v_t_hat.sqrt().add(group['eps']) if group['weight_decay'] != 0: update.add_(p.data, alpha=group['weight_decay']) trust_ratio = 1.0 w_norm = p.data.pow(2).sum().sqrt() g_norm = update.pow(2).sum().sqrt() if w_norm > 0 and g_norm > 0: trust_ratio = w_norm / g_norm state['w_norm'] = w_norm state['g_norm'] = g_norm state['trust_ratio'] = trust_ratio step_size = group['lr'] p.data.add_(update, alpha=-step_size*trust_ratio) return loss class TestLamb(unittest.TestCase): def setUp(self, max_abs_diff=1e-3, max_rel_diff=1, iters=7): self.max_abs_diff = max_abs_diff self.max_rel_diff = max_rel_diff self.iters = iters torch.cuda.manual_seed(9876) def tearDown(self): pass def gen_param_optim(self, tensors, lamb_option): ref_param = [] tst_param = [] for tensor in tensors: ref_param.append(torch.nn.Parameter(tensor.clone())) tst_param.append(torch.nn.Parameter(tensor.clone())) ref_optim = self.ref_optim(ref_param, **lamb_option) tst_optim = self.tst_optim(tst_param, use_nvlamb=True, **lamb_option) return (ref_param, tst_param, ref_optim, tst_optim) def gen_grad(self, ref_param, tst_param): for p_ref, p_tst in zip(ref_param, tst_param): p_ref.grad = torch.rand_like(p_ref) p_tst.grad = p_ref.grad def gen_mixed_grad(self, ref_param, tst_param, scale=1.0): half_grads = [] for p_ref, _ in zip(ref_param, tst_param): half_grads.append(torch.rand_like(p_ref).half()) p_ref.grad = half_grads[-1].float() / scale return half_grads def get_max_diff(self, ref_param, tst_param): max_abs_diff = max_rel_diff = 0 for p_ref, p_tst in zip(ref_param, tst_param): max_abs_diff_p = (p_ref - p_tst).abs().max().item() max_rel_diff_p = ((p_ref - p_tst) / p_ref).abs().max().item() if max_abs_diff_p > max_abs_diff: max_abs_diff = max_abs_diff_p if max_rel_diff_p > max_rel_diff: max_rel_diff = max_rel_diff_p return max_abs_diff, max_rel_diff def gen_single_type_test(self, param_type=torch.float, device="cuda"): nelem = 278011 tensor = torch.rand(nelem, dtype=param_type, device=device) weight_decay = [0, 0.01] for wd in weight_decay: lamb_option = {'lr':5e-4, 'betas':(0.9, 0.999), 'eps':1e-08, 'weight_decay':wd} ref_param, tst_param, ref_optim, tst_optim = \ self.gen_param_optim([tensor], lamb_option) for i in range(self.iters): self.gen_grad(ref_param, tst_param) ref_optim.step() torch.cuda.synchronize() tst_optim.step() torch.cuda.synchronize() max_abs_diff, max_rel_diff = self.get_max_diff(ref_param, tst_param) self.assertLessEqual(max_abs_diff, self.max_abs_diff) self.assertLessEqual(max_rel_diff, self.max_rel_diff) class TestFusedLAMB(TestLamb): def __init__(self, *args, **kwargs): super(TestLamb, self).__init__(*args, **kwargs) self.ref_optim = RefLAMB self.tst_optim = apex.optimizers.FusedLAMB def test_float(self): self.gen_single_type_test(param_type=torch.float) @unittest.skip("PyTorch optimizer is not numerically correct for fp16") def test_half(self): self.gen_single_type_test(param_type=torch.float16) @unittest.skipIf(torch.cuda.device_count()<2, "more than 1 GPU required") def test_multi_device(self): devices = ("cuda:0", "cuda:1") for current_dev, tensor_dev in product(devices, devices): with torch.cuda.device(current_dev): self.gen_single_type_test(param_type=torch.float, device=tensor_dev) def test_multi_params(self): sizes = [[4096, 1024], [4096], [4096, 2048], [32320, 1024], [1]] weight_decay = [0, 0.01] for wd in weight_decay: lamb_option = {'lr':5e-4, 'betas':(0.9, 0.999), 'eps':1e-08, 'weight_decay':wd} tensors = [] for size in sizes: tensors.append(torch.rand(size, dtype=torch.float, device='cuda')) ref_param, tst_param, ref_optim, tst_optim = \ self.gen_param_optim(tensors, lamb_option) for i in range(self.iters): self.gen_grad(ref_param, tst_param) ref_optim.step() tst_optim.step() max_abs_diff, max_rel_diff = self.get_max_diff(ref_param, tst_param) self.assertLessEqual(max_abs_diff, self.max_abs_diff) self.assertLessEqual(max_rel_diff, self.max_rel_diff) def test_lamb_option(self): nelem = 1 tensor = torch.rand(nelem, dtype=torch.float, device='cuda') weight_decay = [0, 0.01] for wd in weight_decay: lamb_option = {'lr':0.01, 'betas':(0.6, 0.9), 'eps':3e-06, 'weight_decay':wd} ref_param, tst_param, ref_optim, tst_optim = \ self.gen_param_optim([tensor], lamb_option) for i in range(self.iters): self.gen_grad(ref_param, tst_param) ref_optim.step() tst_optim.step() max_abs_diff, max_rel_diff = self.get_max_diff(ref_param, tst_param) self.assertLessEqual(max_abs_diff, self.max_abs_diff) self.assertLessEqual(max_rel_diff, self.max_rel_diff) class TestFusedMixedPrecisionLamb(TestLamb): def __init__(self, *args, **kwargs): super(TestLamb, self).__init__(*args, **kwargs) self.ref_optim = RefLAMB self.tst_optim = apex.optimizers.FusedMixedPrecisionLamb def test_float(self): self.gen_single_type_test(param_type=torch.float) @unittest.skip("PyTorch optimizer is not numerically correct for fp16") def test_half(self): self.gen_single_type_test(param_type=torch.float16) @unittest.skipIf(torch.cuda.device_count()<2, "more than 1 GPU required") def test_multi_device(self): devices = ("cuda:0", "cuda:1") for current_dev, tensor_dev in product(devices, devices): with torch.cuda.device(current_dev): self.gen_single_type_test(param_type=torch.float, device=tensor_dev) def test_multi_params(self): sizes = [[4096, 1024], [4096], [4096, 2048], [32320, 1024], [1]] weight_decay = [0, 0.01] for wd in weight_decay: lamb_option = {'lr':5e-4, 'betas':(0.9, 0.999), 'eps':1e-08, 'weight_decay':wd} tensors = [] for size in sizes: tensors.append(torch.rand(size, dtype=torch.float, device='cuda')) ref_param, tst_param, ref_optim, tst_optim = \ self.gen_param_optim(tensors, lamb_option) for i in range(self.iters): self.gen_grad(ref_param, tst_param) ref_optim.step() tst_optim.step() max_abs_diff, max_rel_diff = self.get_max_diff(ref_param, tst_param) self.assertLessEqual(max_abs_diff, self.max_abs_diff) self.assertLessEqual(max_rel_diff, self.max_rel_diff) def test_lamb_option(self): nelem = 1 tensor = torch.rand(nelem, dtype=torch.float, device='cuda') weight_decay = [0, 0.01] for wd in weight_decay: lamb_option = {'lr':0.01, 'betas':(0.6, 0.9), 'eps':3e-06, 'weight_decay':wd} ref_param, tst_param, ref_optim, tst_optim = \ self.gen_param_optim([tensor], lamb_option) for i in range(self.iters): self.gen_grad(ref_param, tst_param) ref_optim.step() tst_optim.step() max_abs_diff, max_rel_diff = self.get_max_diff(ref_param, tst_param) self.assertLessEqual(max_abs_diff, self.max_abs_diff) self.assertLessEqual(max_rel_diff, self.max_rel_diff) if __name__ == '__main__': script_path = os.path.dirname(os.path.realpath(__file__)) unittest.main()
sample/pytorch/unit_test/gpt_unit_test.py
dujiangsu/FasterTransformer
777
152104
<gh_stars>100-1000 # Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the 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 in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. ''' This is a sample code compare the difference of results of FasterTransformer-gpt and Megatron-LM by computing the bleu score with some conditioned contexts. ''' from __future__ import print_function import copy import numpy as np import argparse import os import sys import json import random import sacrebleu import unittest VOCAB_FILEPATH = "../models/gpt2-vocab.json" MERGE_FILEPATH = "../models/gpt2-merges.txt" MEGATRON_OUTPUT_FILENAME = ".megatron_output" MEGATRON_CKPT_FILEPATH = "../models/megatron-models/345m" FT_OUTPUT_FILENAME = ".output" def get_megatron_output(args_dict): os.system(" python ../Megatron-LM/tools/generate_samples_gpt.py \ --num-layers {} \ --hidden-size {} \ --num-attention-heads {} \ --seq-length {} \ --max-position-embeddings {} \ --micro-batch-size {} \ --global-batch-size {} \ --vocab-file {} \ --merge-file {} \ --load {} \ --out-seq-length {} \ --temperature {} \ --genfile {} \ --num-samples {} \ --top_k {} \ --top_p {} \ --recompute \ {}".format(args_dict['num_layer'], args_dict['head_number'] * args_dict['size_per_head'], args_dict['head_number'], args_dict['max_seq_len'], args_dict['max_seq_len'], args_dict['request_batch_size'] // 2, args_dict['request_batch_size'], VOCAB_FILEPATH, MERGE_FILEPATH, MEGATRON_CKPT_FILEPATH, 1 + args_dict['request_output_len'], # input_len is 1 args_dict['temperature'], MEGATRON_OUTPUT_FILENAME, args_dict['request_batch_size'], args_dict['sampling_topk'], args_dict['sampling_topp'], "--fp16" if args_dict['data_type'] == "fp16" else "")) res = [] with open(MEGATRON_OUTPUT_FILENAME, 'r') as megatron_file: for i, line in enumerate(megatron_file.readlines()): line_j = json.loads(line) res.append(line_j['text']) i += 1 if i == args_dict['request_batch_size']: break return res def get_ft_pytorch_output(args_dict): os.system("mpirun -n {} --allow-run-as-root python ./pytorch/gpt_sample.py \ --ckpt_path='{}' \ --layer_num={} \ --head_num={} \ --size_per_head={} \ --tensor_para_size={} \ --layer_para_size={} \ --max_batch_size={} \ --top_k={} \ --top_p={} \ --temperature={} \ --vocab_file={} \ --merges_file={} \ --sample_output_file={} \ {}".format(args_dict['gpu_num'], "{}/{}-gpu".format(args_dict['model_path_prefix'], args_dict['tensor_para_size']), args_dict['num_layer'], args_dict['head_number'], args_dict['size_per_head'], args_dict['tensor_para_size'], args_dict['layer_para_size'], args_dict['request_batch_size'], args_dict['sampling_topk'], args_dict['sampling_topp'], args_dict['temperature'], VOCAB_FILEPATH, MERGE_FILEPATH, FT_OUTPUT_FILENAME, "--fp16" if args_dict['data_type'] == "fp16" else "" )) res = [] with open(FT_OUTPUT_FILENAME, 'r') as ft_file: res = ft_file.readlines() return res def get_ft_cpp_output(args_dict, megatron_output): sys.path.append("../sample") from pytorch.utils.convert_gpt_token import convert_token import pytorch.utils.gpt_token_encoder as encoder from pytorch.utils.generate_gpt_config import generate_gpt_config enc = encoder.get_encoder(VOCAB_FILEPATH, MERGE_FILEPATH) with open("../sample/cpp/start_ids.csv", "w") as f: for tokens in megatron_output: # id_list = enc.encode(tokens) # id_str = "{}\n".format(id_list[:args_dict['request_input_len']]) # id_str = id_str.replace("[", "").replace("]", "") id_str = "50256" # eod (unconditional case) f.write(id_str+"\n") generate_gpt_config(args_dict) os.system("rm out") os.system("mpirun -n {} --allow-run-as-root ./bin/gpt_sample .tmp.config.ini".format(args_dict['gpu_num'])) tokens_batch = np.loadtxt("out", dtype=np.int32) tokens_batch = tokens_batch[args_dict['request_input_len']:, :] # exclude context input from the output tokens_batch = tokens_batch.T # (t, b) => (b, t) res = [] for tokens in tokens_batch: res.append(enc.decode(tokens)) return res class GPTUnconditional(unittest.TestCase): args_dict = None def test_default(self): refs = get_megatron_output(self.args_dict) # sys = get_ft_cpp_output(self.args_dict, megatron_output=refs) sys = get_ft_pytorch_output(self.args_dict) bleu = sacrebleu.corpus_bleu(sys, [refs]) print("[INFO] bleu score: {}".format(bleu.score)) def test_fp16(self): self.args_dict['data_type'] = "fp16" refs = get_megatron_output(self.args_dict) # sys = get_ft_cpp_output(self.args_dict, megatron_output=refs) sys = get_ft_pytorch_output(self.args_dict) bleu = sacrebleu.corpus_bleu(sys, [refs]) print("[INFO] bleu score: {}".format(bleu.score)) def test_topk_4(self): self.args_dict['topk'] = 4 refs = get_megatron_output(self.args_dict) # sys = get_ft_cpp_output(self.args_dict, megatron_output=refs) sys = get_ft_pytorch_output(self.args_dict) bleu = sacrebleu.corpus_bleu(sys, [refs]) print("[INFO] bleu score: {}".format(bleu.score)) def test_topp_09_temp03(self): self.args_dict['topp'] = 0.9 self.args_dict['temp'] = 0.3 refs = get_megatron_output(self.args_dict) # sys = get_ft_cpp_output(self.args_dict, megatron_output=refs) sys = get_ft_pytorch_output(self.args_dict) bleu = sacrebleu.corpus_bleu(sys, [refs]) print("[INFO] bleu score: {}".format(bleu.score)) # def test_tp8_lp1(self): # self.args_dict['gpu_num'] = 8 # self.args_dict['tensor_para_size'] = 8 # self.args_dict['layer_para_size'] = 1 # refs = get_megatron_output(self.args_dict) # # sys = get_ft_cpp_output(self.args_dict, megatron_output=refs) # sys = get_ft_pytorch_output(self.args_dict) # bleu = sacrebleu.corpus_bleu(sys, [refs]) # print("[INFO] bleu score: {}".format(bleu.score)) # def test_tp4_lp2(self): # self.args_dict['gpu_num'] = 8 # self.args_dict['tensor_para_size'] = 4 # self.args_dict['layer_para_size'] = 2 # refs = get_megatron_output(self.args_dict) # # sys = get_ft_cpp_output(self.args_dict, megatron_output=refs) # sys = get_ft_pytorch_output(self.args_dict) # bleu = sacrebleu.corpus_bleu(sys, [refs]) # print("[INFO] bleu score: {}".format(bleu.score)) # TODO class GPTConditional(unittest.TestCase): if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument('-max_batch_size', '--max_batch_size', type=int, default=8, metavar='NUMBER', help='batch size (default: 8)') parser.add_argument('-max_seq_len', '--max_seq_len', type=int, default=1024, metavar='NUMBER', help='max sequence length (default: 1024)') parser.add_argument('-n', '--head_number', type=int, default=16, metavar='NUMBER', help='head number (default: 16)') parser.add_argument('-size', '--size_per_head', type=int, default=64, metavar='NUMBER', help='size per head (default: 64)') parser.add_argument('-l', '--num_layer', type=int, default=24, metavar='NUMBER', help='number of layers (default: 24)') parser.add_argument('-v', '--vocab_size', type=int, default=50304, metavar='BOOL', help='vocabulary size. (default: 50304).') parser.add_argument('-d', '--data_type', type=str, default="fp16", metavar='STRING', help='data type (default: fp16)', choices=['fp32', 'fp16']) parser.add_argument('-topk', '--sampling_topk', type=int, default=1, metavar='NUMBER', help='Candidate (k) value of top k sampling in decoding. Default is 1.') parser.add_argument('-topp', '--sampling_topp', type=float, default=0.0, metavar='NUMBER', help='Probability (p) value of top p sampling in decoding. Default is 0.0.') parser.add_argument('-tensor_para_size', '--tensor_para_size', type=int, default=1, metavar='NUMBER', help='tensor parallelism size. Default is 1.') parser.add_argument('-layer_para_size', '--layer_para_size', type=int, default=1, metavar='NUMBER', help='layer parallelism size. Default is 1.') parser.add_argument('-g', '--gpu_num', type=int, default=1, metavar='NUMBER', help='Number of total gpu. Default is 1.') parser.add_argument('-local_batch', '--local_batch_size', type=int, default=8, metavar='NUMBER', help='local batch size for pipeline parallelism. Default is 8.') parser.add_argument('--model_path_prefix', type=str, default="../models/megatron-models/c-model/345m/", metavar='STRING', help='Model path prfix. Default is "../models/megatron-models/c-model/345m/".') parser.add_argument('-temperature', '--temperature', type=float, default=1.0, metavar='NUMBER', help='temperature of penalty. Default is 1.0.') parser.add_argument('-request_batch_size', '--request_batch_size', type=int, default=8, metavar='NUMBER', help='batch size (default: 8)') parser.add_argument('-request_input_len', '--request_input_len', type=int, default=1, metavar='NUMBER', help='input length (default: 1)') parser.add_argument('-request_output_len', '--request_output_len', type=int, default=32, metavar='NUMBER', help='output length (default: 32)') args = parser.parse_args() print("\n=============== Arguments ===============") for arg in vars(args): print ("{}: {}".format(arg, getattr(args, arg))) print("=========================================\n") np.random.seed(1) random.seed(1) GPTUnconditional.args_dict = vars(args) unittest.main()
fias/models/__init__.py
xiva-wgt/django-fias
108
152122
<gh_stars>100-1000 # coding: utf-8 from __future__ import unicode_literals, absolute_import from .version import Status, Version from .socrbase import SocrBase from .normdoc import * from .addrobj import AddrObj from .house import House, HouseInt from .landmark import LandMark from .room import * from .stead import * from .status import * from .address import * from .sphinx import AddrObjIndex
climpred/graphics.py
pangeo-data/climpred
104
152142
<filename>climpred/graphics.py import warnings from collections import OrderedDict import matplotlib as mpl import matplotlib.pyplot as plt import numpy as np import xarray as xr from xarray.coding.times import infer_calendar_name from .checks import DimensionError from .constants import CLIMPRED_DIMS from .metrics import ALL_METRICS, PROBABILISTIC_METRICS from .utils import get_lead_cftime_shift_args, get_metric_class, shift_cftime_index def plot_relative_entropy(rel_ent, rel_ent_threshold=None, **kwargs): """ Plot relative entropy results. Args: rel_ent (xr.Dataset): relative entropy from compute_relative_entropy rel_ent_threshold (xr.Dataset): threshold from bootstrap_relative_entropy **kwargs: for plt.subplots( **kwargs) """ colors = ["royalblue", "indianred", "goldenrod"] _, ax = plt.subplots(ncols=3, **kwargs) for i, dim in enumerate(["R", "S", "D"]): m = rel_ent[dim].median("init") std = rel_ent[dim].std("init") ax[i].plot( rel_ent.lead, rel_ent[dim].to_dataframe().unstack(0), c="gray", label="individual initializations", linewidth=0.5, alpha=0.5, ) ax[i].plot(rel_ent.lead, m, c=colors[i], label=dim, linewidth=2.5) ax[i].plot( rel_ent.lead, (m - std), c=colors[i], label=dim + " median +/- std", linewidth=2.5, ls="--", ) ax[i].plot( rel_ent.lead, (m + std), c=colors[i], label="", linewidth=2.5, ls="--", ) if rel_ent_threshold is not None: ax[i].axhline( y=rel_ent_threshold[dim].values, label="bootstrapped threshold", c="gray", ls="--", ) handles, labels = ax[i].get_legend_handles_labels() by_label = OrderedDict(zip(labels, handles)) ax[i].legend(by_label.values(), by_label.keys(), frameon=False) ax[i].set_xlabel("Lead") ax[0].set_title("Relative Entropy") ax[1].set_title("Signal") ax[2].set_title("Dispersion") ax[0].set_ylabel("Relative Entropy [ ]") ax[0].set_ylim(bottom=0) return ax def plot_bootstrapped_skill_over_leadyear( bootstrapped, ax=None, color_initialized="indianred", color_uninitialized="steelblue", color_persistence="gray", color_climatology="tan", capsize=4, fontsize=8, figsize=(10, 4), fmt="--o", ): """ Plot Ensemble Prediction skill as in Li et al. 2016 Fig.3a-c. Args: bootstrapped (xr.DataArray or xr.Dataset with one variable): from PredictionEnsembleEnsemble.bootstrap() or HindcastEnsemble.bootstrap() ax (plt.axes): plot on ax. Defaults to None. Returns: ax Reference: * <NAME>, <NAME>, <NAME>, and Frank Sienz. “Decadal Predictions of the North Atlantic CO2 Uptake.” Nature Communications 7 (March 30, 2016): 11076. https://doi.org/10/f8wkrs. """ if isinstance(bootstrapped, xr.Dataset): var = list(bootstrapped.data_vars) if len(var) > 1: raise ValueError( "Please provide only xr.Dataset with one variable or xr.DataArray." ) # copy attributes to xr.DataArray elif len(var) == 1: var = var[0] attrs = bootstrapped.attrs bootstrapped = bootstrapped[var] bootstrapped.attrs = attrs assert isinstance(bootstrapped, xr.DataArray) reference = list(bootstrapped.drop_sel(skill="initialized").coords["skill"].values) sig = bootstrapped.attrs["confidence_interval_levels"].split("-") sig = int(100 * (float(sig[0]) - float(sig[1]))) pers_sig = sig init_skill = bootstrapped.sel(skill="initialized", results="verify skill") init_ci = bootstrapped.sel( skill="initialized", results=["low_ci", "high_ci"] ).rename({"results": "quantile"}) if pers_sig != sig: raise NotImplementedError("pers_sig != sig not implemented yet.") if ax is None: _, ax = plt.subplots(figsize=figsize) # plot init ax.errorbar( init_skill.lead, init_skill, yerr=[ init_skill - init_ci.isel(quantile=0), init_ci.isel(quantile=1) - init_skill, ], fmt=fmt, capsize=capsize, c=color_initialized, label="initialized", ) # plot references for r in reference: r_skill = bootstrapped.sel(skill=r, results="verify skill") if (r_skill == np.nan).all(): warnings.warn(f"Found only NaNs in {r} verify skill and skipped.") continue p_r_over_init = bootstrapped.sel(skill=r, results="p") r_ci = bootstrapped.sel(skill=r, results=["low_ci", "high_ci"]).rename( {"results": "quantile"} ) c = eval(f"color_{r}") # add p values over all reference skills for t in init_skill.lead.values: ax.text( r_skill.lead.sel(lead=t), r_ci.isel(quantile=0).sel(lead=t).values, "%.2f" % float(p_r_over_init.sel(lead=t).values), horizontalalignment="center", verticalalignment="bottom", fontsize=fontsize, color=c, ) yerr = [ r_skill - r_ci.isel(quantile=0), r_ci.isel(quantile=1) - r_skill, ] x = r_skill.lead ax.errorbar( x, r_skill, yerr=yerr, fmt=fmt, capsize=capsize, c=c, label=r, ) ax.xaxis.set_ticks(bootstrapped.lead.values) ax.legend(frameon=False, title=f"skill with {sig}% confidence interval:") ax.set_xlabel(f"Lead time [{bootstrapped.lead.attrs['units']}]") ax.set_ylabel(get_metric_class(bootstrapped.attrs["metric"], ALL_METRICS).long_name) return ax def _check_only_climpred_dims(pe): """Warns if dimensions other than `CLIMPRED_DIMS` are in `PredictionEnsemble`.""" additional_dims = set(pe.get_initialized().dims) - set(CLIMPRED_DIMS) if len(additional_dims) != 0: raise DimensionError( f"{type(pe.__name__)}.plot() does not allow dimensions other " f"than {CLIMPRED_DIMS}, found {additional_dims}. " f"Please use .mean({additional_dims}) " f"or .isel() before plot." ) def plot_lead_timeseries_hindcast( he, variable=None, ax=None, show_members=False, cmap="viridis", x="time" ): """Plot datasets from HindcastEnsemble. Args: he (HindcastEnsemble): HindcastEnsemble. variable (str or None): `variable` to plot. Defaults to the first in data_vars. ax (plt.axes): Axis to use in plotting. By default, creates a new axis. show_members (bool): whether to display all members individually. Defaults to False. cmap (str): Name of matplotlib-recognized colorbar. Defaults to 'viridis'. Returns: ax: plt.axes """ if x == "time": x = "valid_time" _check_only_climpred_dims(he) if variable is None: variable = list(he.get_initialized().data_vars)[0] hind = he.get_initialized()[variable] hist = he.get_uninitialized() if isinstance(hist, xr.Dataset): hist = hist[variable] obs = he.get_observations() if isinstance(obs, xr.Dataset): obs = obs[variable] cmap = mpl.cm.get_cmap(cmap, hind.lead.size) if ax is None: _, ax = plt.subplots(figsize=(10, 4)) if isinstance(hist, xr.DataArray) and x == "valid_time": if "member" in hist.dims and not show_members: hist = hist.mean("member") member_alpha = 1 lw = 2 else: member_alpha = 0.4 lw = 1 hist.plot( ax=ax, lw=lw, hue="member", color="gray", alpha=member_alpha, label="uninitialized", zorder=hind.lead.size + 1, ) for i, lead in enumerate(hind.lead.values): h = hind.sel(lead=lead) if not show_members and "member" in h.dims: h = h.mean("member") lead_alpha = 1 else: lead_alpha = 0.5 h.plot( ax=ax, x=x, hue="member", color=cmap(i), label=f"initialized: lead={lead} {hind.lead.attrs['units'][:-1]}", alpha=lead_alpha, zorder=hind.lead.size - i, ) if isinstance(obs, xr.DataArray) and x == "valid_time": obs.plot( ax=ax, x="time", color="k", lw=3, ls="-", label="observations", zorder=hind.lead.size + 2, ) # show only one item per label in legend handles, labels = ax.get_legend_handles_labels() by_label = OrderedDict(zip(labels, handles)) ax.legend( by_label.values(), by_label.keys(), loc="center left", bbox_to_anchor=(1, 0.5) ) ax.set_title("") ax.set_xlabel(he.coords[x].attrs["long_name"]) return ax def plot_ensemble_perfect_model( pm, variable=None, ax=None, show_members=False, cmap="tab10" ): """Plot datasets from PerfectModelEnsemble. Args: pm (PerfectModelEnsemble): PerfectModelEnsemble. variable (str or None): `variable` to plot. Defaults to the first in data_vars. ax (plt.axes): Axis to use in plotting. By default, creates a new axis. show_members (bool): whether to display all members individually. Defaults to False. cmap (str): Name of matplotlib-recognized colorbar. Defaults to 'tab10'. Returns: ax: plt.axes """ x = "valid_time" _check_only_climpred_dims(pm) if variable is None: variable = list(pm.get_initialized().data_vars)[0] initialized = pm.get_initialized()[variable] uninitialized = pm.get_uninitialized() if isinstance(uninitialized, xr.Dataset): uninitialized = uninitialized[variable] uninitialized_present = True else: uninitialized_present = False control = pm.get_control() if isinstance(control, xr.Dataset): control = control[variable] control_color = "gray" if ax is None: _, ax = plt.subplots(figsize=(10, 4)) cmap = mpl.cm.get_cmap(cmap, initialized.init.size) for ii, i in enumerate(initialized.init.values): dsi = initialized.sel(init=i) if uninitialized_present: dsu = uninitialized.sel(init=i) if not show_members: dsi = dsi.mean("member") if uninitialized_present: dsu = dsu.mean("member") member_alpha = 1 lw = 2 labelstr = "ensemble mean" else: member_alpha = 0.5 lw = 1 labelstr = "members" # plot ensemble mean, first white then color to highlight ensemble mean if uninitialized_present: dsu.mean("member").plot( ax=ax, x=x, color="white", lw=3, zorder=8, alpha=0.6 ) dsu.mean("member").plot( ax=ax, x=x, color=control_color, lw=2, zorder=9, alpha=0.6 ) # plot ensemble mean, first white then color to highlight ensemble mean dsi.mean("member").plot(ax=ax, x=x, color="white", lw=3, zorder=10) dsi.mean("member").plot(ax=ax, x=x, color=cmap(ii), lw=2, zorder=11) dsi.plot( ax=ax, x=x, hue="member", color=cmap(ii), alpha=member_alpha, lw=lw, label=labelstr, ) if uninitialized_present: dsu.plot( ax=ax, x=x, hue="member", color=control_color, alpha=member_alpha / 2, lw=lw, label="uninitialized " + labelstr, ) if isinstance(control, xr.DataArray): control.plot(ax=ax, color=control_color, label="control") # show only one item per label in legend handles, labels = ax.get_legend_handles_labels() by_label = OrderedDict(zip(labels, handles)) ax.legend(by_label.values(), by_label.keys()) ax.set_title(" ") ax.set_xlabel(pm.coords[x].attrs["long_name"]) return ax