How to use iter method in wpt

Best JavaScript code snippet using wpt

nasnet.py

Source:nasnet.py Github

copy

Full Screen

1import torch2import torch.nn as nn3import torch.nn.functional as F4import torch.utils.model_zoo as model_zoo5from torch.autograd import Variable6pretrained_settings = {7 'nasnetalarge': {8 'imagenet': {9 'url': 'http://data.lip6.fr/cadene/pretrainedmodels/nasnetalarge-a1897284.pth',10 'input_space': 'RGB',11 'input_size': [3, 331, 331], # resize 35412 'input_range': [0, 1],13 'mean': [0.5, 0.5, 0.5],14 'std': [0.5, 0.5, 0.5],15 'num_classes': 100016 },17 'imagenet+background': {18 'url': 'http://data.lip6.fr/cadene/pretrainedmodels/nasnetalarge-a1897284.pth',19 'input_space': 'RGB',20 'input_size': [3, 331, 331], # resize 35421 'input_range': [0, 1],22 'mean': [0.5, 0.5, 0.5],23 'std': [0.5, 0.5, 0.5],24 'num_classes': 100125 }26 }27}28class MaxPoolPad(nn.Module):29 def __init__(self):30 super(MaxPoolPad, self).__init__()31 self.pad = nn.ZeroPad2d((1, 0, 1, 0))32 self.pool = nn.MaxPool2d(3, stride=2, padding=1)33 def forward(self, x):34 x = self.pad(x)35 x = self.pool(x)36 x = x[:, :, 1:, 1:]37 return x38class AvgPoolPad(nn.Module):39 def __init__(self, stride=2, padding=1):40 super(AvgPoolPad, self).__init__()41 self.pad = nn.ZeroPad2d((1, 0, 1, 0))42 self.pool = nn.AvgPool2d(3, stride=stride, padding=padding, count_include_pad=False)43 def forward(self, x):44 x = self.pad(x)45 x = self.pool(x)46 x = x[:, :, 1:, 1:]47 return x48class SeparableConv2d(nn.Module):49 def __init__(self, in_channels, out_channels, dw_kernel, dw_stride, dw_padding, bias=False):50 super(SeparableConv2d, self).__init__()51 self.depthwise_conv2d = nn.Conv2d(in_channels, in_channels, dw_kernel,52 stride=dw_stride,53 padding=dw_padding,54 bias=bias,55 groups=in_channels)56 self.pointwise_conv2d = nn.Conv2d(in_channels, out_channels, 1, stride=1, bias=bias)57 def forward(self, x):58 x = self.depthwise_conv2d(x)59 x = self.pointwise_conv2d(x)60 return x61class BranchSeparables(nn.Module):62 def __init__(self, in_channels, out_channels, kernel_size, stride, padding, bias=False):63 super(BranchSeparables, self).__init__()64 self.relu = nn.ReLU()65 self.separable_1 = SeparableConv2d(in_channels, in_channels, kernel_size, stride, padding, bias=bias)66 self.bn_sep_1 = nn.BatchNorm2d(in_channels, eps=0.001, momentum=0.1, affine=True)67 self.relu1 = nn.ReLU()68 self.separable_2 = SeparableConv2d(in_channels, out_channels, kernel_size, 1, padding, bias=bias)69 self.bn_sep_2 = nn.BatchNorm2d(out_channels, eps=0.001, momentum=0.1, affine=True)70 def forward(self, x):71 x = self.relu(x)72 x = self.separable_1(x)73 x = self.bn_sep_1(x)74 x = self.relu1(x)75 x = self.separable_2(x)76 x = self.bn_sep_2(x)77 return x78class BranchSeparablesStem(nn.Module):79 def __init__(self, in_channels, out_channels, kernel_size, stride, padding, bias=False):80 super(BranchSeparablesStem, self).__init__()81 self.relu = nn.ReLU()82 self.separable_1 = SeparableConv2d(in_channels, out_channels, kernel_size, stride, padding, bias=bias)83 self.bn_sep_1 = nn.BatchNorm2d(out_channels, eps=0.001, momentum=0.1, affine=True)84 self.relu1 = nn.ReLU()85 self.separable_2 = SeparableConv2d(out_channels, out_channels, kernel_size, 1, padding, bias=bias)86 self.bn_sep_2 = nn.BatchNorm2d(out_channels, eps=0.001, momentum=0.1, affine=True)87 def forward(self, x):88 x = self.relu(x)89 x = self.separable_1(x)90 x = self.bn_sep_1(x)91 x = self.relu1(x)92 x = self.separable_2(x)93 x = self.bn_sep_2(x)94 return x95class BranchSeparablesReduction(BranchSeparables):96 def __init__(self, in_channels, out_channels, kernel_size, stride, padding, z_padding=1, bias=False):97 BranchSeparables.__init__(self, in_channels, out_channels, kernel_size, stride, padding, bias)98 self.padding = nn.ZeroPad2d((z_padding, 0, z_padding, 0))99 def forward(self, x):100 x = self.relu(x)101 x = self.padding(x)102 x = self.separable_1(x)103 x = x[:, :, 1:, 1:].contiguous()104 x = self.bn_sep_1(x)105 x = self.relu1(x)106 x = self.separable_2(x)107 x = self.bn_sep_2(x)108 return x109class CellStem0(nn.Module):110 def __init__(self):111 super(CellStem0, self).__init__()112 self.conv_1x1 = nn.Sequential()113 self.conv_1x1.add_module('relu', nn.ReLU())114 self.conv_1x1.add_module('conv', nn.Conv2d(96, 42, 1, stride=1, bias=False))115 self.conv_1x1.add_module('bn', nn.BatchNorm2d(42, eps=0.001, momentum=0.1, affine=True))116 self.comb_iter_0_left = BranchSeparables(42, 42, 5, 2, 2)117 self.comb_iter_0_right = BranchSeparablesStem(96, 42, 7, 2, 3, bias=False)118 self.comb_iter_1_left = nn.MaxPool2d(3, stride=2, padding=1)119 self.comb_iter_1_right = BranchSeparablesStem(96, 42, 7, 2, 3, bias=False)120 self.comb_iter_2_left = nn.AvgPool2d(3, stride=2, padding=1, count_include_pad=False)121 self.comb_iter_2_right = BranchSeparablesStem(96, 42, 5, 2, 2, bias=False)122 self.comb_iter_3_right = nn.AvgPool2d(3, stride=1, padding=1, count_include_pad=False)123 self.comb_iter_4_left = BranchSeparables(42, 42, 3, 1, 1, bias=False)124 self.comb_iter_4_right = nn.MaxPool2d(3, stride=2, padding=1)125 def forward(self, x):126 x1 = self.conv_1x1(x)127 x_comb_iter_0_left = self.comb_iter_0_left(x1)128 x_comb_iter_0_right = self.comb_iter_0_right(x)129 x_comb_iter_0 = x_comb_iter_0_left + x_comb_iter_0_right130 x_comb_iter_1_left = self.comb_iter_1_left(x1)131 x_comb_iter_1_right = self.comb_iter_1_right(x)132 x_comb_iter_1 = x_comb_iter_1_left + x_comb_iter_1_right133 x_comb_iter_2_left = self.comb_iter_2_left(x1)134 x_comb_iter_2_right = self.comb_iter_2_right(x)135 x_comb_iter_2 = x_comb_iter_2_left + x_comb_iter_2_right136 x_comb_iter_3_right = self.comb_iter_3_right(x_comb_iter_0)137 x_comb_iter_3 = x_comb_iter_3_right + x_comb_iter_1138 x_comb_iter_4_left = self.comb_iter_4_left(x_comb_iter_0)139 x_comb_iter_4_right = self.comb_iter_4_right(x1)140 x_comb_iter_4 = x_comb_iter_4_left + x_comb_iter_4_right141 x_out = torch.cat([x_comb_iter_1, x_comb_iter_2, x_comb_iter_3, x_comb_iter_4], 1)142 return x_out143class CellStem1(nn.Module):144 def __init__(self):145 super(CellStem1, self).__init__()146 self.conv_1x1 = nn.Sequential()147 self.conv_1x1.add_module('relu', nn.ReLU())148 self.conv_1x1.add_module('conv', nn.Conv2d(168, 84, 1, stride=1, bias=False))149 self.conv_1x1.add_module('bn', nn.BatchNorm2d(84, eps=0.001, momentum=0.1, affine=True))150 self.relu = nn.ReLU()151 self.path_1 = nn.Sequential()152 self.path_1.add_module('avgpool', nn.AvgPool2d(1, stride=2, count_include_pad=False))153 self.path_1.add_module('conv', nn.Conv2d(96, 42, 1, stride=1, bias=False))154 self.path_2 = nn.ModuleList()155 self.path_2.add_module('pad', nn.ZeroPad2d((0, 1, 0, 1)))156 self.path_2.add_module('avgpool', nn.AvgPool2d(1, stride=2, count_include_pad=False))157 self.path_2.add_module('conv', nn.Conv2d(96, 42, 1, stride=1, bias=False))158 self.final_path_bn = nn.BatchNorm2d(84, eps=0.001, momentum=0.1, affine=True)159 self.comb_iter_0_left = BranchSeparables(84, 84, 5, 2, 2, bias=False)160 self.comb_iter_0_right = BranchSeparables(84, 84, 7, 2, 3, bias=False)161 self.comb_iter_1_left = nn.MaxPool2d(3, stride=2, padding=1)162 self.comb_iter_1_right = BranchSeparables(84, 84, 7, 2, 3, bias=False)163 self.comb_iter_2_left = nn.AvgPool2d(3, stride=2, padding=1, count_include_pad=False)164 self.comb_iter_2_right = BranchSeparables(84, 84, 5, 2, 2, bias=False)165 self.comb_iter_3_right = nn.AvgPool2d(3, stride=1, padding=1, count_include_pad=False)166 self.comb_iter_4_left = BranchSeparables(84, 84, 3, 1, 1, bias=False)167 self.comb_iter_4_right = nn.MaxPool2d(3, stride=2, padding=1)168 def forward(self, x_conv0, x_stem_0):169 x_left = self.conv_1x1(x_stem_0)170 x_relu = self.relu(x_conv0)171 # path 1172 x_path1 = self.path_1(x_relu)173 # path 2174 x_path2 = self.path_2.pad(x_relu)175 x_path2 = x_path2[:, :, 1:, 1:]176 x_path2 = self.path_2.avgpool(x_path2)177 x_path2 = self.path_2.conv(x_path2)178 # final path179 x_right = self.final_path_bn(torch.cat([x_path1, x_path2], 1))180 x_comb_iter_0_left = self.comb_iter_0_left(x_left)181 x_comb_iter_0_right = self.comb_iter_0_right(x_right)182 x_comb_iter_0 = x_comb_iter_0_left + x_comb_iter_0_right183 x_comb_iter_1_left = self.comb_iter_1_left(x_left)184 x_comb_iter_1_right = self.comb_iter_1_right(x_right)185 x_comb_iter_1 = x_comb_iter_1_left + x_comb_iter_1_right186 x_comb_iter_2_left = self.comb_iter_2_left(x_left)187 x_comb_iter_2_right = self.comb_iter_2_right(x_right)188 x_comb_iter_2 = x_comb_iter_2_left + x_comb_iter_2_right189 x_comb_iter_3_right = self.comb_iter_3_right(x_comb_iter_0)190 x_comb_iter_3 = x_comb_iter_3_right + x_comb_iter_1191 x_comb_iter_4_left = self.comb_iter_4_left(x_comb_iter_0)192 x_comb_iter_4_right = self.comb_iter_4_right(x_left)193 x_comb_iter_4 = x_comb_iter_4_left + x_comb_iter_4_right194 x_out = torch.cat([x_comb_iter_1, x_comb_iter_2, x_comb_iter_3, x_comb_iter_4], 1)195 return x_out196class FirstCell(nn.Module):197 def __init__(self, in_channels_left, out_channels_left, in_channels_right, out_channels_right):198 super(FirstCell, self).__init__()199 self.conv_1x1 = nn.Sequential()200 self.conv_1x1.add_module('relu', nn.ReLU())201 self.conv_1x1.add_module('conv', nn.Conv2d(in_channels_right, out_channels_right, 1, stride=1, bias=False))202 self.conv_1x1.add_module('bn', nn.BatchNorm2d(out_channels_right, eps=0.001, momentum=0.1, affine=True))203 self.relu = nn.ReLU()204 self.path_1 = nn.Sequential()205 self.path_1.add_module('avgpool', nn.AvgPool2d(1, stride=2, count_include_pad=False))206 self.path_1.add_module('conv', nn.Conv2d(in_channels_left, out_channels_left, 1, stride=1, bias=False))207 self.path_2 = nn.ModuleList()208 self.path_2.add_module('pad', nn.ZeroPad2d((0, 1, 0, 1)))209 self.path_2.add_module('avgpool', nn.AvgPool2d(1, stride=2, count_include_pad=False))210 self.path_2.add_module('conv', nn.Conv2d(in_channels_left, out_channels_left, 1, stride=1, bias=False))211 self.final_path_bn = nn.BatchNorm2d(out_channels_left * 2, eps=0.001, momentum=0.1, affine=True)212 self.comb_iter_0_left = BranchSeparables(out_channels_right, out_channels_right, 5, 1, 2, bias=False)213 self.comb_iter_0_right = BranchSeparables(out_channels_right, out_channels_right, 3, 1, 1, bias=False)214 self.comb_iter_1_left = BranchSeparables(out_channels_right, out_channels_right, 5, 1, 2, bias=False)215 self.comb_iter_1_right = BranchSeparables(out_channels_right, out_channels_right, 3, 1, 1, bias=False)216 self.comb_iter_2_left = nn.AvgPool2d(3, stride=1, padding=1, count_include_pad=False)217 self.comb_iter_3_left = nn.AvgPool2d(3, stride=1, padding=1, count_include_pad=False)218 self.comb_iter_3_right = nn.AvgPool2d(3, stride=1, padding=1, count_include_pad=False)219 self.comb_iter_4_left = BranchSeparables(out_channels_right, out_channels_right, 3, 1, 1, bias=False)220 def forward(self, x, x_prev):221 x_relu = self.relu(x_prev)222 # path 1223 x_path1 = self.path_1(x_relu)224 # path 2225 x_path2 = self.path_2.pad(x_relu)226 x_path2 = x_path2[:, :, 1:, 1:]227 x_path2 = self.path_2.avgpool(x_path2)228 x_path2 = self.path_2.conv(x_path2)229 # final path230 x_left = self.final_path_bn(torch.cat([x_path1, x_path2], 1))231 x_right = self.conv_1x1(x)232 x_comb_iter_0_left = self.comb_iter_0_left(x_right)233 x_comb_iter_0_right = self.comb_iter_0_right(x_left)234 x_comb_iter_0 = x_comb_iter_0_left + x_comb_iter_0_right235 x_comb_iter_1_left = self.comb_iter_1_left(x_left)236 x_comb_iter_1_right = self.comb_iter_1_right(x_left)237 x_comb_iter_1 = x_comb_iter_1_left + x_comb_iter_1_right238 x_comb_iter_2_left = self.comb_iter_2_left(x_right)239 x_comb_iter_2 = x_comb_iter_2_left + x_left240 x_comb_iter_3_left = self.comb_iter_3_left(x_left)241 x_comb_iter_3_right = self.comb_iter_3_right(x_left)242 x_comb_iter_3 = x_comb_iter_3_left + x_comb_iter_3_right243 x_comb_iter_4_left = self.comb_iter_4_left(x_right)244 x_comb_iter_4 = x_comb_iter_4_left + x_right245 x_out = torch.cat([x_left, x_comb_iter_0, x_comb_iter_1, x_comb_iter_2, x_comb_iter_3, x_comb_iter_4], 1)246 return x_out247class NormalCell(nn.Module):248 def __init__(self, in_channels_left, out_channels_left, in_channels_right, out_channels_right):249 super(NormalCell, self).__init__()250 self.conv_prev_1x1 = nn.Sequential()251 self.conv_prev_1x1.add_module('relu', nn.ReLU())252 self.conv_prev_1x1.add_module('conv', nn.Conv2d(in_channels_left, out_channels_left, 1, stride=1, bias=False))253 self.conv_prev_1x1.add_module('bn', nn.BatchNorm2d(out_channels_left, eps=0.001, momentum=0.1, affine=True))254 self.conv_1x1 = nn.Sequential()255 self.conv_1x1.add_module('relu', nn.ReLU())256 self.conv_1x1.add_module('conv', nn.Conv2d(in_channels_right, out_channels_right, 1, stride=1, bias=False))257 self.conv_1x1.add_module('bn', nn.BatchNorm2d(out_channels_right, eps=0.001, momentum=0.1, affine=True))258 self.comb_iter_0_left = BranchSeparables(out_channels_right, out_channels_right, 5, 1, 2, bias=False)259 self.comb_iter_0_right = BranchSeparables(out_channels_left, out_channels_left, 3, 1, 1, bias=False)260 self.comb_iter_1_left = BranchSeparables(out_channels_left, out_channels_left, 5, 1, 2, bias=False)261 self.comb_iter_1_right = BranchSeparables(out_channels_left, out_channels_left, 3, 1, 1, bias=False)262 self.comb_iter_2_left = nn.AvgPool2d(3, stride=1, padding=1, count_include_pad=False)263 self.comb_iter_3_left = nn.AvgPool2d(3, stride=1, padding=1, count_include_pad=False)264 self.comb_iter_3_right = nn.AvgPool2d(3, stride=1, padding=1, count_include_pad=False)265 self.comb_iter_4_left = BranchSeparables(out_channels_right, out_channels_right, 3, 1, 1, bias=False)266 def forward(self, x, x_prev):267 x_left = self.conv_prev_1x1(x_prev)268 x_right = self.conv_1x1(x)269 x_comb_iter_0_left = self.comb_iter_0_left(x_right)270 x_comb_iter_0_right = self.comb_iter_0_right(x_left)271 x_comb_iter_0 = x_comb_iter_0_left + x_comb_iter_0_right272 x_comb_iter_1_left = self.comb_iter_1_left(x_left)273 x_comb_iter_1_right = self.comb_iter_1_right(x_left)274 x_comb_iter_1 = x_comb_iter_1_left + x_comb_iter_1_right275 x_comb_iter_2_left = self.comb_iter_2_left(x_right)276 x_comb_iter_2 = x_comb_iter_2_left + x_left277 x_comb_iter_3_left = self.comb_iter_3_left(x_left)278 x_comb_iter_3_right = self.comb_iter_3_right(x_left)279 x_comb_iter_3 = x_comb_iter_3_left + x_comb_iter_3_right280 x_comb_iter_4_left = self.comb_iter_4_left(x_right)281 x_comb_iter_4 = x_comb_iter_4_left + x_right282 x_out = torch.cat([x_left, x_comb_iter_0, x_comb_iter_1, x_comb_iter_2, x_comb_iter_3, x_comb_iter_4], 1)283 return x_out284class ReductionCell0(nn.Module):285 def __init__(self, in_channels_left, out_channels_left, in_channels_right, out_channels_right):286 super(ReductionCell0, self).__init__() 287 self.conv_prev_1x1 = nn.Sequential()288 self.conv_prev_1x1.add_module('relu', nn.ReLU())289 self.conv_prev_1x1.add_module('conv', nn.Conv2d(in_channels_left, out_channels_left, 1, stride=1, bias=False))290 self.conv_prev_1x1.add_module('bn', nn.BatchNorm2d(out_channels_left, eps=0.001, momentum=0.1, affine=True))291 self.conv_1x1 = nn.Sequential()292 self.conv_1x1.add_module('relu', nn.ReLU())293 self.conv_1x1.add_module('conv', nn.Conv2d(in_channels_right, out_channels_right, 1, stride=1, bias=False))294 self.conv_1x1.add_module('bn', nn.BatchNorm2d(out_channels_right, eps=0.001, momentum=0.1, affine=True))295 self.comb_iter_0_left = BranchSeparablesReduction(out_channels_right, out_channels_right, 5, 2, 2, bias=False)296 self.comb_iter_0_right = BranchSeparablesReduction(out_channels_right, out_channels_right, 7, 2, 3, bias=False)297 self.comb_iter_1_left = MaxPoolPad()298 self.comb_iter_1_right = BranchSeparablesReduction(out_channels_right, out_channels_right, 7, 2, 3, bias=False)299 self.comb_iter_2_left = AvgPoolPad()300 self.comb_iter_2_right = BranchSeparablesReduction(out_channels_right, out_channels_right, 5, 2, 2, bias=False)301 self.comb_iter_3_right = nn.AvgPool2d(3, stride=1, padding=1, count_include_pad=False)302 self.comb_iter_4_left = BranchSeparablesReduction(out_channels_right, out_channels_right, 3, 1, 1, bias=False)303 self.comb_iter_4_right = MaxPoolPad()304 def forward(self, x, x_prev):305 x_left = self.conv_prev_1x1(x_prev)306 x_right = self.conv_1x1(x)307 x_comb_iter_0_left = self.comb_iter_0_left(x_right)308 x_comb_iter_0_right = self.comb_iter_0_right(x_left)309 x_comb_iter_0 = x_comb_iter_0_left + x_comb_iter_0_right310 x_comb_iter_1_left = self.comb_iter_1_left(x_right)311 x_comb_iter_1_right = self.comb_iter_1_right(x_left)312 x_comb_iter_1 = x_comb_iter_1_left + x_comb_iter_1_right313 x_comb_iter_2_left = self.comb_iter_2_left(x_right)314 x_comb_iter_2_right = self.comb_iter_2_right(x_left)315 x_comb_iter_2 = x_comb_iter_2_left + x_comb_iter_2_right316 x_comb_iter_3_right = self.comb_iter_3_right(x_comb_iter_0)317 x_comb_iter_3 = x_comb_iter_3_right + x_comb_iter_1318 x_comb_iter_4_left = self.comb_iter_4_left(x_comb_iter_0)319 x_comb_iter_4_right = self.comb_iter_4_right(x_right)320 x_comb_iter_4 = x_comb_iter_4_left + x_comb_iter_4_right321 x_out = torch.cat([x_comb_iter_1, x_comb_iter_2, x_comb_iter_3, x_comb_iter_4], 1)322 return x_out323class ReductionCell1(nn.Module):324 def __init__(self, in_channels_left, out_channels_left, in_channels_right, out_channels_right):325 super(ReductionCell1, self).__init__()326 self.conv_prev_1x1 = nn.Sequential()327 self.conv_prev_1x1.add_module('relu', nn.ReLU())328 self.conv_prev_1x1.add_module('conv', nn.Conv2d(in_channels_left, out_channels_left, 1, stride=1, bias=False))329 self.conv_prev_1x1.add_module('bn', nn.BatchNorm2d(out_channels_left, eps=0.001, momentum=0.1, affine=True))330 self.conv_1x1 = nn.Sequential()331 self.conv_1x1.add_module('relu', nn.ReLU())332 self.conv_1x1.add_module('conv', nn.Conv2d(in_channels_right, out_channels_right, 1, stride=1, bias=False))333 self.conv_1x1.add_module('bn', nn.BatchNorm2d(out_channels_right, eps=0.001, momentum=0.1, affine=True))334 self.comb_iter_0_left = BranchSeparables(out_channels_right, out_channels_right, 5, 2, 2, bias=False)335 self.comb_iter_0_right = BranchSeparables(out_channels_right, out_channels_right, 7, 2, 3, bias=False)336 self.comb_iter_1_left = nn.MaxPool2d(3, stride=2, padding=1)337 self.comb_iter_1_right = BranchSeparables(out_channels_right, out_channels_right, 7, 2, 3, bias=False)338 self.comb_iter_2_left = nn.AvgPool2d(3, stride=2, padding=1, count_include_pad=False)339 self.comb_iter_2_right = BranchSeparables(out_channels_right, out_channels_right, 5, 2, 2, bias=False)340 self.comb_iter_3_right = nn.AvgPool2d(3, stride=1, padding=1, count_include_pad=False)341 self.comb_iter_4_left = BranchSeparables(out_channels_right, out_channels_right, 3, 1, 1, bias=False)342 self.comb_iter_4_right = nn.MaxPool2d(3, stride=2, padding=1)343 def forward(self, x, x_prev):344 x_left = self.conv_prev_1x1(x_prev)345 x_right = self.conv_1x1(x)346 x_comb_iter_0_left = self.comb_iter_0_left(x_right)347 x_comb_iter_0_right = self.comb_iter_0_right(x_left)348 x_comb_iter_0 = x_comb_iter_0_left + x_comb_iter_0_right349 x_comb_iter_1_left = self.comb_iter_1_left(x_right)350 x_comb_iter_1_right = self.comb_iter_1_right(x_left)351 x_comb_iter_1 = x_comb_iter_1_left + x_comb_iter_1_right352 x_comb_iter_2_left = self.comb_iter_2_left(x_right)353 x_comb_iter_2_right = self.comb_iter_2_right(x_left)354 x_comb_iter_2 = x_comb_iter_2_left + x_comb_iter_2_right355 x_comb_iter_3_right = self.comb_iter_3_right(x_comb_iter_0)356 x_comb_iter_3 = x_comb_iter_3_right + x_comb_iter_1357 x_comb_iter_4_left = self.comb_iter_4_left(x_comb_iter_0)358 x_comb_iter_4_right = self.comb_iter_4_right(x_right)359 x_comb_iter_4 = x_comb_iter_4_left + x_comb_iter_4_right360 x_out = torch.cat([x_comb_iter_1, x_comb_iter_2, x_comb_iter_3, x_comb_iter_4], 1)361 return x_out362class NASNetALarge(nn.Module):363 def __init__(self, use_classifier=False, num_classes=1001):364 super(NASNetALarge, self).__init__()365 self.use_classifier,self.num_classes = use_classifier,num_classes366 self.conv0 = nn.Sequential()367 self.conv0.add_module('conv', nn.Conv2d(in_channels=3, out_channels=96, kernel_size=3, padding=0, stride=2,368 bias=False))369 self.conv0.add_module('bn', nn.BatchNorm2d(96, eps=0.001, momentum=0.1, affine=True))370 self.cell_stem_0 = CellStem0()371 self.cell_stem_1 = CellStem1()372 self.cell_0 = FirstCell(in_channels_left=168, out_channels_left=84,373 in_channels_right=336, out_channels_right=168)374 self.cell_1 = NormalCell(in_channels_left=336, out_channels_left=168,375 in_channels_right=1008, out_channels_right=168)376 self.cell_2 = NormalCell(in_channels_left=1008, out_channels_left=168,377 in_channels_right=1008, out_channels_right=168)378 self.cell_3 = NormalCell(in_channels_left=1008, out_channels_left=168,379 in_channels_right=1008, out_channels_right=168)380 self.cell_4 = NormalCell(in_channels_left=1008, out_channels_left=168,381 in_channels_right=1008, out_channels_right=168)382 self.cell_5 = NormalCell(in_channels_left=1008, out_channels_left=168,383 in_channels_right=1008, out_channels_right=168)384 self.reduction_cell_0 = ReductionCell0(in_channels_left=1008, out_channels_left=336,385 in_channels_right=1008, out_channels_right=336)386 self.cell_6 = FirstCell(in_channels_left=1008, out_channels_left=168,387 in_channels_right=1344, out_channels_right=336)388 self.cell_7 = NormalCell(in_channels_left=1344, out_channels_left=336,389 in_channels_right=2016, out_channels_right=336)390 self.cell_8 = NormalCell(in_channels_left=2016, out_channels_left=336,391 in_channels_right=2016, out_channels_right=336)392 self.cell_9 = NormalCell(in_channels_left=2016, out_channels_left=336,393 in_channels_right=2016, out_channels_right=336)394 self.cell_10 = NormalCell(in_channels_left=2016, out_channels_left=336,395 in_channels_right=2016, out_channels_right=336)396 self.cell_11 = NormalCell(in_channels_left=2016, out_channels_left=336,397 in_channels_right=2016, out_channels_right=336)398 self.reduction_cell_1 = ReductionCell1(in_channels_left=2016, out_channels_left=672,399 in_channels_right=2016, out_channels_right=672)400 self.cell_12 = FirstCell(in_channels_left=2016, out_channels_left=336,401 in_channels_right=2688, out_channels_right=672)402 self.cell_13 = NormalCell(in_channels_left=2688, out_channels_left=672,403 in_channels_right=4032, out_channels_right=672)404 self.cell_14 = NormalCell(in_channels_left=4032, out_channels_left=672,405 in_channels_right=4032, out_channels_right=672)406 self.cell_15 = NormalCell(in_channels_left=4032, out_channels_left=672,407 in_channels_right=4032, out_channels_right=672)408 self.cell_16 = NormalCell(in_channels_left=4032, out_channels_left=672,409 in_channels_right=4032, out_channels_right=672)410 self.cell_17 = NormalCell(in_channels_left=4032, out_channels_left=672,411 in_channels_right=4032, out_channels_right=672)412 self.relu = nn.ReLU()413 self.dropout = nn.Dropout()414 self.last_linear = nn.Linear(4032, self.num_classes)415 def features(self, x):416 x_conv0 = self.conv0(x)417 x_stem_0 = self.cell_stem_0(x_conv0)418 x_stem_1 = self.cell_stem_1(x_conv0, x_stem_0)419 x_cell_0 = self.cell_0(x_stem_1, x_stem_0)420 x_cell_1 = self.cell_1(x_cell_0, x_stem_1)421 x_cell_2 = self.cell_2(x_cell_1, x_cell_0)422 x_cell_3 = self.cell_3(x_cell_2, x_cell_1)423 x_cell_4 = self.cell_4(x_cell_3, x_cell_2)424 x_cell_5 = self.cell_5(x_cell_4, x_cell_3)425 x_reduction_cell_0 = self.reduction_cell_0(x_cell_5, x_cell_4)426 x_cell_6 = self.cell_6(x_reduction_cell_0, x_cell_4)427 x_cell_7 = self.cell_7(x_cell_6, x_reduction_cell_0)428 x_cell_8 = self.cell_8(x_cell_7, x_cell_6)429 x_cell_9 = self.cell_9(x_cell_8, x_cell_7)430 x_cell_10 = self.cell_10(x_cell_9, x_cell_8)431 x_cell_11 = self.cell_11(x_cell_10, x_cell_9)432 x_reduction_cell_1 = self.reduction_cell_1(x_cell_11, x_cell_10)433 x_cell_12 = self.cell_12(x_reduction_cell_1, x_cell_10)434 x_cell_13 = self.cell_13(x_cell_12, x_reduction_cell_1)435 x_cell_14 = self.cell_14(x_cell_13, x_cell_12)436 x_cell_15 = self.cell_15(x_cell_14, x_cell_13)437 x_cell_16 = self.cell_16(x_cell_15, x_cell_14)438 x_cell_17 = self.cell_17(x_cell_16, x_cell_15)439 return self.relu(x_cell_17)440 def classifier(self, x):441 x = F.adaptive_max_pool2d(x, 1)442 x = x.view(x.size(0), -1)443 x = self.dropout(x)444 return F.log_softmax(self.linear(x))445 def forward(self, x):446 x = self.features(x)447 if self.use_classifier: x = self.classifier(x)448 return x449def nasnetalarge(num_classes=1000, pretrained='imagenet'):450 r"""NASNetALarge model architecture from the451 `"NASNet" <https://arxiv.org/abs/1707.07012>`_ paper.452 """453 if pretrained:454 settings = pretrained_settings['nasnetalarge'][pretrained]455 assert num_classes == settings['num_classes'], \456 "num_classes should be {}, but is {}".format(settings['num_classes'], num_classes)457 # both 'imagenet'&'imagenet+background' are loaded from same parameters458 model = NASNetALarge(num_classes=1001)459 model.load_state_dict(model_zoo.load_url(settings['url']))460 if pretrained == 'imagenet':461 new_last_linear = nn.Linear(model.last_linear.in_features, 1000)462 new_last_linear.weight.data = model.last_linear.weight.data[1:]463 new_last_linear.bias.data = model.last_linear.bias.data[1:]464 model.last_linear = new_last_linear465 model.input_space = settings['input_space']466 model.input_size = settings['input_size']467 model.input_range = settings['input_range']468 model.mean = settings['mean']469 model.std = settings['std']470 else:471 model = NASNetALarge(num_classes=num_classes)...

Full Screen

Full Screen

cppclass_container.py

Source:cppclass_container.py Github

copy

Full Screen

1"""2Add container iteration powers to wrapped C++ classes3"""4from typehandlers.base import ForwardWrapperBase5from typehandlers import codesink6from pytypeobject import PyTypeObject7import utils8class IterNextWrapper(ForwardWrapperBase):9 '''10 tp_iternext wrapper11 '''12 HAVE_RETURN_VALUE = True13 def __init__(self, container):14 """15 value_type -- a ReturnValue object handling the value type;16 container -- the L{Container}17 """18 super(IterNextWrapper, self).__init__(19 None, [], "return NULL;", "return NULL;", no_c_retval=True)20 assert isinstance(container, CppClassContainerTraits)21 self.container = container22 self.c_function_name = "_wrap_%s__tp_iternext" % (self.container.iter_pystruct)23 self.iter_variable_name = None24 self.reset_code_generation_state()25 def reset_code_generation_state(self):26 super(IterNextWrapper, self).reset_code_generation_state()27 self.iter_variable_name = self.declarations.declare_variable(28 "%s::%s" % (self.container.cppclass.full_name, self.container.iterator_type), 'iter')29 def generate_call(self):30 self.before_call.write_code("%s = *self->iterator;" % (self.iter_variable_name,))31 self.before_call.write_error_check(32 "%s == self->container->obj->%s()" % (self.iter_variable_name, self.container.end_method),33 "PyErr_SetNone(PyExc_StopIteration);")34 self.before_call.write_code("++(*self->iterator);")35 if self.container.key_type is None:36 self.container.value_type.value = "(*%s)" % self.iter_variable_name37 self.container.value_type.convert_c_to_python(self)38 else:39 self.container.value_type.value = "%s->second" % self.iter_variable_name40 self.container.value_type.convert_c_to_python(self)41 self.container.key_type.value = "%s->first" % self.iter_variable_name42 self.container.key_type.convert_c_to_python(self)43 def generate(self, code_sink):44 """45 code_sink -- a CodeSink instance that will receive the generated code46 """47 48 tmp_sink = codesink.MemoryCodeSink()49 self.generate_body(tmp_sink)50 code_sink.writeln("static PyObject* %s(%s *self)" % (self.c_function_name,51 self.container.iter_pystruct))52 code_sink.writeln('{')53 code_sink.indent()54 tmp_sink.flush_to(code_sink)55 code_sink.unindent()56 code_sink.writeln('}')57class CppClassContainerTraits(object):58 def __init__(self, cppclass, value_type, begin_method='begin', end_method='end', iterator_type='iterator', is_mapping=False):59 """60 :param cppclass: the L{CppClass} object that receives the container traits61 :param value_type: a ReturnValue of the element type: note,62 for mapping containers, value_type is a tuple with two63 ReturnValue's: (key, element).64 """65 self.cppclass = cppclass66 self.begin_method = begin_method67 self.end_method = end_method68 self.iterator_type = iterator_type69 self.iter_pytype = PyTypeObject()70 self._iter_pystruct = None71 if is_mapping:72 (key_type, value_type) = value_type73 self.key_type = utils.eval_retval(key_type, self)74 self.value_type = utils.eval_retval(value_type, self)75 else:76 self.key_type = None77 self.value_type = utils.eval_retval(value_type, self)78 def get_iter_pystruct(self):79 return "%s_Iter" % self.cppclass.pystruct80 iter_pystruct = property(get_iter_pystruct)81 def get_iter_pytypestruct(self):82 return "%s_IterType" % self.cppclass.pystruct83 iter_pytypestruct = property(get_iter_pytypestruct)84 def generate_forward_declarations(self, code_sink, dummy_module):85 """86 Generates forward declarations for the instance and type87 structures.88 """89 # container iterator pystruct90 code_sink.writeln('''91typedef struct {92 PyObject_HEAD93 %s *container;94 %s::%s *iterator;95} %s;96 ''' % (self.cppclass.pystruct, self.cppclass.full_name, self.iterator_type, self.iter_pystruct))97 code_sink.writeln()98 code_sink.writeln('extern PyTypeObject %s;' % (self.iter_pytypestruct,))99 code_sink.writeln()100 def get_iter_python_name(self):101 return "%sIter" % self.cppclass.get_python_name()102 def get_iter_python_full_name(self, module):103 if self.cppclass.outer_class is None:104 mod_path = module.get_module_path()105 mod_path.append(self.get_iter_python_name())106 return '.'.join(mod_path)107 else:108 return '%s.%s' % (self.cppclass.outer_class.pytype.slots['tp_name'],109 self.get_iter_python_name())110 def generate(self, code_sink, module, docstring=None):111 """Generates the class to a code sink"""112 ## --- register the iter type in the module ---113 module.after_init.write_code("/* Register the '%s' class iterator*/" % self.cppclass.full_name)114 module.after_init.write_error_check('PyType_Ready(&%s)' % (self.iter_pytypestruct,))115 if self.cppclass.outer_class is None:116 module.after_init.write_code(117 'PyModule_AddObject(m, (char *) \"%s\", (PyObject *) &%s);' % (118 self.get_iter_python_name(), self.iter_pytypestruct))119 else:120 module.after_init.write_code(121 'PyDict_SetItemString((PyObject*) %s.tp_dict, (char *) \"%s\", (PyObject *) &%s);' % (122 self.cppclass.outer_class.pytypestruct, self.cppclass.get_iter_python_name(), self.iter_pytypestruct))123 self._generate_gc_methods(code_sink)124 self._generate_destructor(code_sink)125 self._generate_iter_methods(code_sink)126 self._generate_type_structure(code_sink, module, docstring)127 128 def _generate_type_structure(self, code_sink, module, docstring):129 """generate the type structure"""130 self.iter_pytype.slots.setdefault("tp_basicsize", "sizeof(%s)" % (self.iter_pystruct,))131 self.iter_pytype.slots.setdefault("tp_flags", ("Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_GC"))132 self.iter_pytype.slots.setdefault("typestruct", self.iter_pytypestruct)133 self.iter_pytype.slots.setdefault("tp_name", self.get_iter_python_full_name(module))134 if docstring:135 self.iter_pytype.slots.setdefault("tp_doc", '"%s"' % docstring)136 self.iter_pytype.generate(code_sink)137 def _get_iter_delete_code(self):138 delete_code = ("delete self->iterator;\n"139 " self->iterator = NULL;\n")140 return delete_code141 def _get_container_delete_code(self):142 delete_code = ("delete self->obj;\n"143 " self->obj = NULL;\n")144 return delete_code145 def _generate_gc_methods(self, code_sink):146 """Generate tp_clear and tp_traverse"""147 ## --- iterator tp_clear ---148 tp_clear_function_name = "%s__tp_clear" % (self.iter_pystruct,)149 self.iter_pytype.slots.setdefault("tp_clear", tp_clear_function_name )150 code_sink.writeln(r'''151static void152%s(%s *self)153{154 Py_CLEAR(self->container);155 %s156}157''' % (tp_clear_function_name, self.iter_pystruct, self._get_iter_delete_code()))158 ## --- iterator tp_traverse ---159 tp_traverse_function_name = "%s__tp_traverse" % (self.iter_pystruct,)160 self.iter_pytype.slots.setdefault("tp_traverse", tp_traverse_function_name )161 code_sink.writeln(r'''162static int163%s(%s *self, visitproc visit, void *arg)164{165 Py_VISIT((PyObject *) self->container);166 return 0;167}168''' % (tp_traverse_function_name, self.iter_pystruct))169 def _generate_destructor(self, code_sink):170 """Generate a tp_dealloc function and register it in the type"""171 # -- iterator --172 iter_tp_dealloc_function_name = "_wrap_%s__tp_dealloc" % (self.iter_pystruct,)173 code_sink.writeln(r'''174static void175%s(%s *self)176{177 Py_CLEAR(self->container);178 %s179 self->ob_type->tp_free((PyObject*)self);180}181''' % (iter_tp_dealloc_function_name, self.iter_pystruct, self._get_iter_delete_code()))182 self.iter_pytype.slots.setdefault("tp_dealloc", iter_tp_dealloc_function_name )183 def _generate_iter_methods(self, code_sink):184 container_tp_iter_function_name = "_wrap_%s__tp_iter" % (self.cppclass.pystruct,)185 iterator_tp_iter_function_name = "_wrap_%s__tp_iter" % (self.iter_pystruct,)186 subst_vars = {187 'CONTAINER_ITER_FUNC': container_tp_iter_function_name,188 'ITERATOR_ITER_FUNC': iterator_tp_iter_function_name,189 'PYSTRUCT': self.cppclass.pystruct,190 'ITER_PYSTRUCT': self.iter_pystruct,191 'ITER_PYTYPESTRUCT': self.iter_pytypestruct,192 'CTYPE': self.cppclass.full_name,193 'BEGIN_METHOD': self.begin_method,194 'ITERATOR_TYPE': self.iterator_type,195 }196 # -- container --197 code_sink.writeln(r'''198static PyObject*199%(CONTAINER_ITER_FUNC)s(%(PYSTRUCT)s *self)200{201 %(ITER_PYSTRUCT)s *iter = PyObject_GC_New(%(ITER_PYSTRUCT)s, &%(ITER_PYTYPESTRUCT)s);202 Py_INCREF(self);203 iter->container = self;204 iter->iterator = new %(CTYPE)s::%(ITERATOR_TYPE)s(self->obj->%(BEGIN_METHOD)s());205 return (PyObject*) iter;206}207''' % subst_vars)208 self.cppclass.pytype.slots.setdefault("tp_iter", container_tp_iter_function_name)209 210 # -- iterator --211 container_tp_iter_function_name = "_wrap_%s__tp_iter" % (self.cppclass.pystruct,)212 code_sink.writeln(r'''213static PyObject*214%(ITERATOR_ITER_FUNC)s(%(ITER_PYSTRUCT)s *self)215{216 Py_INCREF(self);217 return (PyObject*) self;218}219''' % subst_vars)220 self.iter_pytype.slots.setdefault("tp_iter", iterator_tp_iter_function_name)221 # -- iterator tp_iternext222 iternext = IterNextWrapper(self)223 iternext.generate(code_sink)224 self.iter_pytype.slots.setdefault("tp_iternext", iternext.c_function_name)...

Full Screen

Full Screen

test_parser_pddl_simple.py

Source:test_parser_pddl_simple.py Github

copy

Full Screen

1#!/usr/bin/python32from pddl.parser import *3from pddl.lisp_parser import parse_lisp_iterator4from pddl.errors import BraceError, ParseError5from py.test import raises6## helper functions7def varListTest(varList):8 assert [k.name for k in varList] == ['?x', '?y', '?z']9 assert len([k for k in varList if k.typed]) == 310 assert [k.types[0] for k in varList] == ['block', 'foo', 'block']11def keywordListTest(keyList):12 assert [k.name for k in keyList] == ['name', 'parameters', 'foo']13## the tests14def test_parseKeywordSimple():15 test = ['(:parameters )']16 iter = parse_lisp_iterator(test)17 key = parse_keyword(next(iter))18 assert key.name == 'parameters'19def test_parseKeywordComplex():20 test = [' ( :name)']21 iter = parse_lisp_iterator(test)22 key = parse_keyword(next(iter))23 assert key.name == 'name'24def test_parseKeywordList():25 test = ['(:name :parameters :foo )']26 iter = parse_lisp_iterator(test)27 keys = parse_keyword_list(iter)28 assert iter.empty()29 keywordListTest(keys)30def test_parseRequirements():31 test = ['(:requirements :name :parameters :foo )']32 iter = parse_lisp_iterator(test)33 req = parse_requirements_stmt(iter)34 assert iter.empty()35 keywordListTest(req.keywords)36def test_parseRequirements2():37 test = ['(:predicates :name :parameters :foo )']38 iter = parse_lisp_iterator(test)39 with raises(ValueError):40 parse_requirements_stmt(iter)41def test_parseVariableNoTyping():42 test = [' ( ?x)']43 iter = parse_lisp_iterator(test)44 key = parse_variable(next(iter))45 assert key.name == '?x'46 assert key.typed == False47 assert key.types == None48def test_parseVariableTyping():49 test = [' ( ?x - block)']50 iter = parse_lisp_iterator(test)51 vlist = parse_typed_var_list(iter)52 assert len(vlist) == 153 assert vlist[0].name == '?x'54 assert vlist[0].typed == True55 assert vlist[0].types[0] == 'block'56def test_parseVariableList():57 test = [' ( ?x - block ?y - foo ?z - block )']58 iter = parse_lisp_iterator(test)59 key = parse_typed_var_list(iter)60 varListTest(key)61def test_parseParameters():62 test = ['(:parameters ( ?x - block ?y - foo ?z - block ))']63 iter = parse_lisp_iterator(test)64 key = parse_parameters(iter)65 varListTest(key)66def test_parseParameters2():67 test = ['(:predicates ( ?x - block ?y - foo ?z - block ))']68 iter = parse_lisp_iterator(test)69 with raises(ValueError):70 parse_parameters(iter)71def test_parseTypes():72 test = ['(:types block plane key)']73 iter = parse_lisp_iterator(test)74 tlist = parse_types_stmt(iter)75 assert [t.name for t in tlist] == ['block', 'plane', 'key']76def test_parseTypesFail():77 test = ['(:types :block plane key)']78 iter = parse_lisp_iterator(test)79 with raises(ValueError):80 parse_types_stmt(iter)81def test_parseTypesFail2():82 test = ['(:predicates :block plane key)']83 iter = parse_lisp_iterator(test)84 with raises(ValueError):85 parse_types_stmt(iter)86def test_parseDomainStatement():87 test = ['(domain supertest-23-v0)']88 iter = parse_lisp_iterator(test)89 dom = parse_domain_stmt(iter)90 assert dom.name == 'supertest-23-v0'91def test_parseDomainStatementFail():92 test = ['(domaiin supertest-23-v0)']93 iter = parse_lisp_iterator(test)94 with raises(ValueError):95 parse_domain_stmt(iter)96def test_parsePredicate():97 test = ['(on ?x ?y)']98 iter = parse_lisp_iterator(test)99 pred = parse_predicate(iter)100 assert pred.name == 'on'101 assert [x.name for x in pred.parameters] == ['?x', '?y']102def test_parsePredicateMixed():103 test = ['(on ?x - block ?y)']104 iter = parse_lisp_iterator(test)105 pred = parse_predicate(iter)106 assert pred.name == 'on'107 assert [x.name for x in pred.parameters] == ['?x', '?y']108 assert [x.types[0] for x in pred.parameters109 if x.types != None] == ['block']110def test_parsePredicateList():111 test = ['((on ?x - block ?y) (put ?x ?z) (true))']112 iter = parse_lisp_iterator(test)113 predlist = parse_predicate_list(iter)114 assert [x.name for x in predlist] == ['on', 'put', 'true']115def test_parseFormula():116 test = ['(and (on ?x table) (true) (free ?x))']117 iter = parse_lisp_iterator(test)118 print(iter)119 formula = parse_formula(iter)120 assert formula.key == 'and'121 assert [c.key for c in formula.children] == ['on', 'true', 'free']122 assert [c.key.name for c in formula.children[0].children123 if c.type == TypeVariable] == ['?x']124 assert [c.key for c in formula.children[0].children125 if c.type == TypeConstant] == ['table']126 assert [c.key.name for c in formula.children[2].children127 if c.type == TypeVariable] == ['?x']128 assert [c for c in formula.children[1].children] == []129def test_parseFormulaFail():130 test = ['(and (on ?x table) (:true) (free ?x))']131 iter = parse_lisp_iterator(test)132 with raises(ValueError):133 parse_formula(iter)134def test_parseFormulaLispFail2():135 test = ['(and (on ?x table) (true) (free( ?x))']136 with raises(ParseError):137 iter = parse_lisp_iterator(test)138def test_parse_variable():139 test = ['(x)']140 iter = parse_lisp_iterator(test)141 with raises(ValueError):142 parse_variable(next(iter))143def test_lisp_parser_start_brace():144 test = ['test string)']145 with raises(ParseError):146 iter = parse_lisp_iterator(test)147def test_parse_keyword_raise():148 test = ['(?test)']149 iter = parse_lisp_iterator(test)150 with raises(ValueError):151 parse_keyword(next(iter))152def test_parse_objects_stmt_fail():153 test = ['(:predicates blubb blubb)']154 iter = parse_lisp_iterator(test)155 with raises(ValueError):156 parse_objects_stmt(iter)157def test_parse_constants_stmt_fail():158 test = ['(:predicates blubb blubb)']159 iter = parse_lisp_iterator(test)160 with raises(ValueError):161 parse_constants_stmt(iter)162def test_parse_problem_domain_stmt_fail():163 test = ['(:predicates blubb blubb)']164 iter = parse_lisp_iterator(test)165 with raises(ValueError):166 parse_problem_domain_stmt(iter)167def test_parse_precondition_stmt_fail():168 test = ['(:predicates blubb blubb)']169 iter = parse_lisp_iterator(test)170 with raises(ValueError):171 parse_precondition_stmt(iter)172def test_parse_effect_stmt_fail():173 test = ['(:predicates blubb blubb)']174 iter = parse_lisp_iterator(test)175 with raises(ValueError):176 parse_effect_stmt(iter)177def test_parse_action_stmt_fail():178 test = ['(:predicates blubb blubb)']179 iter = parse_lisp_iterator(test)180 with raises(ValueError):181 parse_action_stmt(iter)182def test_parse_predicates_stmt_fail():183 test = ['(:actions blubb blubb)']184 iter = parse_lisp_iterator(test)185 with raises(ValueError):186 parse_predicates_stmt(iter)187def test_parse_domain_def_fail():188 test = ['(definiere (domain BLOCKS))']189 iter = parse_lisp_iterator(test)190 with raises(ValueError):191 parse_domain_def(iter)192def test_parse_problem_def_fail():193 test = ['(definiere problem)']194 iter = parse_lisp_iterator(test)195 with raises(ValueError):196 parse_problem_def(iter)197def test_parse_problem_name_fail():198 test = ['(domain test)']199 iter = parse_lisp_iterator(test)200 with raises(ValueError):201 parse_problem_name(iter)202def test_parse_init_stmt_fail():203 test = ['(:goal ssdfsdf)']204 iter = parse_lisp_iterator(test)205 with raises(ValueError):206 parse_init_stmt(iter)207def test_parse_goal_stmt_fail():208 test = ['(:init ssdfsdf)']209 iter = parse_lisp_iterator(test)210 with raises(ValueError):...

Full Screen

Full Screen

xml-fold.js

Source:xml-fold.js Github

copy

Full Screen

1(function(mod) {2 if (typeof exports == "object" && typeof module == "object") // CommonJS3 mod(require("../../lib/codemirror"));4 else if (typeof define == "function" && define.amd) // AMD5 define(["../../lib/codemirror"], mod);6 else // Plain browser env7 mod(CodeMirror);8})(function(CodeMirror) {9 "use strict";10 var Pos = CodeMirror.Pos;11 function cmp(a, b) { return a.line - b.line || a.ch - b.ch; }12 var nameStartChar = "A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD";13 var nameChar = nameStartChar + "\-\:\.0-9\\u00B7\\u0300-\\u036F\\u203F-\\u2040";14 var xmlTagStart = new RegExp("<(/?)([" + nameStartChar + "][" + nameChar + "]*)", "g");15 function Iter(cm, line, ch, range) {16 this.line = line; this.ch = ch;17 this.cm = cm; this.text = cm.getLine(line);18 this.min = range ? range.from : cm.firstLine();19 this.max = range ? range.to - 1 : cm.lastLine();20 }21 function tagAt(iter, ch) {22 var type = iter.cm.getTokenTypeAt(Pos(iter.line, ch));23 return type && /\btag\b/.test(type);24 }25 function nextLine(iter) {26 if (iter.line >= iter.max) return;27 iter.ch = 0;28 iter.text = iter.cm.getLine(++iter.line);29 return true;30 }31 function prevLine(iter) {32 if (iter.line <= iter.min) return;33 iter.text = iter.cm.getLine(--iter.line);34 iter.ch = iter.text.length;35 return true;36 }37 function toTagEnd(iter) {38 for (;;) {39 var gt = iter.text.indexOf(">", iter.ch);40 if (gt == -1) { if (nextLine(iter)) continue; else return; }41 if (!tagAt(iter, gt + 1)) { iter.ch = gt + 1; continue; }42 var lastSlash = iter.text.lastIndexOf("/", gt);43 var selfClose = lastSlash > -1 && !/\S/.test(iter.text.slice(lastSlash + 1, gt));44 iter.ch = gt + 1;45 return selfClose ? "selfClose" : "regular";46 }47 }48 function toTagStart(iter) {49 for (;;) {50 var lt = iter.ch ? iter.text.lastIndexOf("<", iter.ch - 1) : -1;51 if (lt == -1) { if (prevLine(iter)) continue; else return; }52 if (!tagAt(iter, lt + 1)) { iter.ch = lt; continue; }53 xmlTagStart.lastIndex = lt;54 iter.ch = lt;55 var match = xmlTagStart.exec(iter.text);56 if (match && match.index == lt) return match;57 }58 }59 function toNextTag(iter) {60 for (;;) {61 xmlTagStart.lastIndex = iter.ch;62 var found = xmlTagStart.exec(iter.text);63 if (!found) { if (nextLine(iter)) continue; else return; }64 if (!tagAt(iter, found.index + 1)) { iter.ch = found.index + 1; continue; }65 iter.ch = found.index + found[0].length;66 return found;67 }68 }69 function toPrevTag(iter) {70 for (;;) {71 var gt = iter.ch ? iter.text.lastIndexOf(">", iter.ch - 1) : -1;72 if (gt == -1) { if (prevLine(iter)) continue; else return; }73 if (!tagAt(iter, gt + 1)) { iter.ch = gt; continue; }74 var lastSlash = iter.text.lastIndexOf("/", gt);75 var selfClose = lastSlash > -1 && !/\S/.test(iter.text.slice(lastSlash + 1, gt));76 iter.ch = gt + 1;77 return selfClose ? "selfClose" : "regular";78 }79 }80 function findMatchingClose(iter, tag) {81 var stack = [];82 for (;;) {83 var next = toNextTag(iter), end, startLine = iter.line, startCh = iter.ch - (next ? next[0].length : 0);84 if (!next || !(end = toTagEnd(iter))) return;85 if (end == "selfClose") continue;86 if (next[1]) { // closing tag87 for (var i = stack.length - 1; i >= 0; --i) if (stack[i] == next[2]) {88 stack.length = i;89 break;90 }91 if (i < 0 && (!tag || tag == next[2])) return {92 tag: next[2],93 from: Pos(startLine, startCh),94 to: Pos(iter.line, iter.ch)95 };96 } else { // opening tag97 stack.push(next[2]);98 }99 }100 }101 function findMatchingOpen(iter, tag) {102 var stack = [];103 for (;;) {104 var prev = toPrevTag(iter);105 if (!prev) return;106 if (prev == "selfClose") { toTagStart(iter); continue; }107 var endLine = iter.line, endCh = iter.ch;108 var start = toTagStart(iter);109 if (!start) return;110 if (start[1]) { // closing tag111 stack.push(start[2]);112 } else { // opening tag113 for (var i = stack.length - 1; i >= 0; --i) if (stack[i] == start[2]) {114 stack.length = i;115 break;116 }117 if (i < 0 && (!tag || tag == start[2])) return {118 tag: start[2],119 from: Pos(iter.line, iter.ch),120 to: Pos(endLine, endCh)121 };122 }123 }124 }125 CodeMirror.registerHelper("fold", "xml", function(cm, start) {126 var iter = new Iter(cm, start.line, 0);127 for (;;) {128 var openTag = toNextTag(iter), end;129 if (!openTag || iter.line != start.line || !(end = toTagEnd(iter))) return;130 if (!openTag[1] && end != "selfClose") {131 var start = Pos(iter.line, iter.ch);132 var close = findMatchingClose(iter, openTag[2]);133 return close && {from: start, to: close.from};134 }135 }136 });137 CodeMirror.findMatchingTag = function(cm, pos, range) {138 var iter = new Iter(cm, pos.line, pos.ch, range);139 if (iter.text.indexOf(">") == -1 && iter.text.indexOf("<") == -1) return;140 var end = toTagEnd(iter), to = end && Pos(iter.line, iter.ch);141 var start = end && toTagStart(iter);142 if (!end || end == "selfClose" || !start || cmp(iter, pos) > 0) return;143 var here = {from: Pos(iter.line, iter.ch), to: to, tag: start[2]};144 if (start[1]) { // closing tag145 return {open: findMatchingOpen(iter, start[2]), close: here, at: "close"};146 } else { // opening tag147 iter = new Iter(cm, to.line, to.ch, range);148 return {open: here, close: findMatchingClose(iter, start[2]), at: "open"};149 }150 };151 CodeMirror.findEnclosingTag = function(cm, pos, range) {152 var iter = new Iter(cm, pos.line, pos.ch, range);153 for (;;) {154 var open = findMatchingOpen(iter);155 if (!open) break;156 var forward = new Iter(cm, pos.line, pos.ch, range);157 var close = findMatchingClose(forward, open.tag);158 if (close) return {open: open, close: close};159 }160 };161 // Used by addon/edit/closetag.js162 CodeMirror.scanForClosingTag = function(cm, pos, name, end) {163 var iter = new Iter(cm, pos.line, pos.ch, end ? {from: 0, to: end} : null);164 return !!findMatchingClose(iter, name);165 };...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1var wpt = require('webpagetest');2var wpt = new WebPageTest('www.webpagetest.org');3 if (err) return console.error(err);4 console.log('Test submitted. Polling for results...');5 wpt.getTestResults(data.data.testId, function(err, data) {6 if (err) return console.error(err);7 console.log('Test completed!');8 console.log(data);9 });10});11var wpt = require('webpagetest');12var wpt = new WebPageTest('www.webpagetest.org');13var options = {14};15 if (err) return console.error(err);16 console.log('Test submitted. Polling for results...');17 wpt.getTestResults(data.data.testId, function(err, data) {18 if (err) return console.error(err);19 console.log('Test completed!');20 console.log(data);21 });22});23var wpt = require('webpagetest');24var wpt = new WebPageTest('www.webpagetest.org');25 if (err) return console.error(err);26 console.log('Test submitted. Polling for results...');27 wpt.getTestResults(data.data.testId, function(err, data) {28 if (err) return console.error(err);29 console.log('Test completed!');30 console.log(data);31 });32});33var wpt = require('webpagetest');34var wpt = new WebPageTest('www.webpagetest.org');35var options = {36};37 if (err) return console.error(err);38 console.log('Test submitted. Polling for results...');

Full Screen

Using AI Code Generation

copy

Full Screen

1const wpt = require('webpagetest');2 if (err) {3 console.log(err);4 } else {5 console.log(data);6 }7});8const wpt = require('webpagetest');9### WPT.runTest(url, options, callback)10### WPT.getTestResults(testId, callback)11### WPT.getLocations(callback)12### WPT.getTesters(callback)13### WPT.getVersion(callback)

Full Screen

Using AI Code Generation

copy

Full Screen

1const wptools = require('wptools');2const fs = require('fs');3const path = require('path');4const json2csv = require('json2csv').parse;5const csv = require('csvtojson');6const csvWriter = require('csv-write-stream');7const writer = csvWriter({sendHeaders: false});8const fields = ['Title', 'Description'];9const opts = { fields };10const csvFilePath = path.join(__dirname, 'output.csv');11const jsonFilePath = path.join(__dirname, 'output.json');12const getWiki = async (name) => {13 const page = wptools.page(name);14 const data = await page.get();15 return data;16}17const getWikiInfo = async (name) => {18 const page = wptools.page(name);19 const data = await page.get();20 return data;21}22const getWikiInfoIter = async (name) => {23 const page = wptools.page(name);24 const data = await page.get();25 return data;26}27const getWikiInfoIter2 = async (name) => {28 const page = wptools.page(name);29 const data = await page.get();30 return data;31}32const getWikiInfoIter3 = async (name) => {33 const page = wptools.page(name);34 const data = await page.get();35 return data;36}37const getWikiInfoIter4 = async (name) => {38 const page = wptools.page(name);39 const data = await page.get();40 return data;41}42const getWikiInfoIter5 = async (name) => {43 const page = wptools.page(name);44 const data = await page.get();45 return data;46}47const getWikiInfoIter6 = async (name) => {48 const page = wptools.page(name);49 const data = await page.get();50 return data;51}52const getWikiInfoIter7 = async (name) => {53 const page = wptools.page(name);54 const data = await page.get();55 return data;56}57const getWikiInfoIter8 = async (name) => {58 const page = wptools.page(name);59 const data = await page.get();60 return data;61}62const getWikiInfoIter9 = async (name) => {63 const page = wptools.page(name);64 const data = await page.get();

Full Screen

Using AI Code Generation

copy

Full Screen

1const wptools = require('wptools');2const fs = require('fs');3const async = require('async');4const path = require('path');5const csv = require('fast-csv');6const _ = require('lodash');7const csvWriter = require('csv-write-stream');8const writer = csvWriter();9 .fromPath('./data/2018-05-01.csv')10 .on('data', function (data) {11 console.log(data);12 })13 .on('end', function () {14 console.log('done');15 });

Full Screen

Using AI Code Generation

copy

Full Screen

1var wptools = require('wptools');2var fs = require('fs');3var options = {4};5var iter = wptools.page('Albert Einstein', options).iter('links');6var link;7while (link = iter()) {8 console.log(link);9}10var wptools = require('wptools');11var fs = require('fs');12var options = {13};14var iter = wptools.page('Albert Einstein', options).iter('links');15var link;16while (link = iter()) {17 console.log(link);18}19var wptools = require('wptools');20var fs = require('fs');21var options = {22};23var iter = wptools.page('Albert Einstein', options).iter('links');24var link;25while (link = iter()) {26 console.log(link);27}28var wptools = require('wptools');29var fs = require('fs');30var options = {31};32var iter = wptools.page('Albert Einstein', options).iter('links');33var link;34while (link = iter()) {35 console.log(link);36}37var wptools = require('wptools');38var fs = require('fs');39var options = {40};41var iter = wptools.page('Albert Einstein', options).iter('links');42var link;43while (link = iter()) {44 console.log(link);45}46var wptools = require('wptools');47var fs = require('fs');48var options = {

Full Screen

Using AI Code Generation

copy

Full Screen

1var wptools = require('wptools');2var fs = require('fs');3var path = require('path');4var file = path.join(__dirname, 'test.txt');5var file2 = path.join(__dirname, 'test2.txt');6var readStream = fs.createReadStream(file);7var writeStream = fs.createWriteStream(file2);8wptools.iter(readStream, writeStream, function(err, result){9 if (err) throw err;10 console.log(result);11});

Full Screen

Using AI Code Generation

copy

Full Screen

1var wptools = require('wptools');2var page = wptools.page('Barack Obama');3page.iter('infobox', function(err, data) {4 console.log(data);5});6var wptools = require('wptools');7var page = wptools.page('Barack Obama');8page.iter('links', function(err, data) {9 console.log(data);10});11var wptools = require('wptools');12var page = wptools.page('Barack Obama');13page.iter('categories', function(err, data) {14 console.log(data);15});16var wptools = require('wptools');17var page = wptools.page('Barack Obama');18page.iter('coordinates', function(err, data) {19 console.log(data);20});21var wptools = require('wptools');22var page = wptools.page('Barack Obama');23page.iter('images', function(err, data) {24 console.log(data);25});26var wptools = require('wptools');27var page = wptools.page('Barack Obama');28page.iter('langlinks', function(err, data) {29 console.log(data);30});31var wptools = require('wptools');32var page = wptools.page('Barack Obama');33page.iter('pageprops', function(err, data) {34 console.log(data);35});36var wptools = require('wptools');37var page = wptools.page('Barack Obama');38page.iter('revisions', function(err, data) {39 console.log(data);40});41var wptools = require('wptools');42var page = wptools.page('Barack Obama');43page.iter('templates', function

Full Screen

Using AI Code Generation

copy

Full Screen

1const wptools = require('wptools');2const fs = require('fs');3const _ = require('lodash');4wptools.page('Barack Obama').then(page => {5 page.iter('links').then(links => {6 fs.writeFileSync('links.json', JSON.stringify(links, null, 2));7 });8});9### wptools.page()10const wptools = require('wptools');11wptools.page('Barack Obama').then(page => {12 page.data().then(data => {13 console.log(data);14 });15});16### page.data()17const wptools = require('wptools');18wptools.page('Barack Obama').then(page => {19 page.data().then(data => {20 console.log(data);21 });22});23### page.iter()24const wptools = require('wptools');25wptools.page('Barack Obama').then(page => {26 page.iter('links').then(links => {27 console.log(links);28 });29});30### page.get()31const wptools = require('wptools');32wptools.page('Barack Obama').then(page => {33 page.get('infobox').then(infobox => {34 console.log(infobox);35 });36});37### page.getImages()38const wptools = require('wptools');39wptools.page('Barack Obama').then(page => {40 page.getImages().then(images => {41 console.log(images);42 });43});44### page.getLinks()45const wptools = require('wptools');46wptools.page('Barack Obama').then(page => {47 page.getLinks().then(links => {48 console.log(links);49 });50});51### page.getReferences()52const wptools = require('wptools');53wptools.page('Barack Obama').then(page => {54 page.getReferences().then(references => {55 console.log(references);56 });57});58### page.getSections()59const wptools = require('wptools');60wptools.page('Barack Obama').then(page => {61 page.getSections().then(sections => {62 console.log(sections);63 });64});65### page.getSummary()

Full Screen

Using AI Code Generation

copy

Full Screen

1var wpt = require('webpagetest')('www.webpagetest.org', 'A.5f6e7c1d1f1d8d2c9c9b7f86c4e6f4b6');2var fs = require('fs');3var request = require('request');4var wptJson = {};5var wptJson1 = {};6var wptJson2 = {};7var wptJson3 = {};8var wptJson4 = {};9var wptJson5 = {};

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run wpt automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful