How to use flatten method in wpt

Best JavaScript code snippet using wpt

character.js

Source:character.js Github

copy

Full Screen

...56 if (name)7 spr.name = name;8 else9 spr.name = grammar.flatten("#name#");1011 spr.row = row;12 spr.col = col;13 spr.char_type = char_type; // NPC, enemy14 spr.ai = ai;15 spr.chunk = chunk;16 spr.depth = NPC_INDEX;1718 spr.mood = grammar.flatten("#mood#");19 spr.vipTitle = grammar.flatten("#vipTitle#");20 spr.occupation = grammar.flatten("#occupation#");21 spr.speed = 2;//speed;22 spr.chunk = chunk;2324 if ((questGiver !== undefined) && (questGiver)) {25 spr.questGiver = true;26 if (name === "Mike the Fisherman") {27 spr.dialogue_index = 0;28 spr.name = "Mike";29 spr.occupation = "Fisherman";30 spr.quest = {31 "quest": "fish", // make this a list?32 "questDialogue": [33 "Hey there",34 /*event_grammar.flatten("#campfire1#"),35 event_grammar.flatten("#campfire2#"),36 event_grammar.flatten("#campfire3#"),37 event_grammar.flatten("#campfire4#"),38 event_grammar.flatten("#campfire5#"),39 event_grammar.flatten("#campfire6#"),40 event_grammar.flatten("#campfire7#"),*/41 ],42 "thanks": "Thank you!",43 "done": false44 };45 }46 }47 //spr.quest = quest;48 //spr.questGiver = questGiver;495051 // npc.name = npc_grammar.flatten("#name#");52 // npc.mood = npc_grammar.flatten("#mood#");53 // npc.vipTitle = npc_grammar.flatten("#vipTitle#");54 // npc.occupation = npc_grammar.flatten("#occupation#");55 // ///56 // npc.depth = NPC_INDEX;57 // //npc.addImage = npcImg;58 // npc.chunk = getRandomInteger(0, NUM_CHUNKS); //1;59 // npc.speed = 2; // tbd60 // npc.dialogue_index = 0;6162 // if (_n == questGiver) {63 // npc.questGiver = true;64 // npc.ai = "follow";65 // console.log("Questy McQuesterson on: " + npc.chunk);66 // npc.quest = {67 // "quest": "Have you seen my BLUE CRAB?", // make this a list?68 // "thanks": "Thanks m8",69 // "done": false70 // };71 // } else if (_n == numGenericNPCs) { // last one hangs by the campfire72 // npc.questGiver = true;73 // npc.ai = "loiter";74 // npc.chunk = _campfireChunk;75 // npc.quest = {76 // "quest": "body", // make this a list?77 // "questDialogue": [78 // event_grammar.flatten("#campfire1#"),79 // event_grammar.flatten("#campfire2#"),80 // event_grammar.flatten("#campfire3#"),81 // event_grammar.flatten("#campfire4#"),82 // event_grammar.flatten("#campfire5#"),83 // event_grammar.flatten("#campfire6#"),84 // event_grammar.flatten("#campfire7#"),85 // ],86 // "thanks": "Thanks m8",87 // "done": false88 // };89 // console.log(npc.quest["questDialogue"]);90 // } else if (_n == numGenericNPCs + 1) { // mike the fisherman91 // npc.name = "Mike the Fisherman";92 // npc.questGiver = true;93 // npc.ai = "loiter";94 // npc.chunk = NUM_CHUNKS + TOWN_CHUNKS.FRILL;95 // npc.quest = {96 // "quest": "fish", // make this a list?97 // "questDialogue": [98 // "Hey there",99 // /*event_grammar.flatten("#campfire1#"),100 // event_grammar.flatten("#campfire2#"),101 // event_grammar.flatten("#campfire3#"),102 // event_grammar.flatten("#campfire4#"),103 // event_grammar.flatten("#campfire5#"),104 // event_grammar.flatten("#campfire6#"),105 // event_grammar.flatten("#campfire7#"),*/106 // ],107 // "thanks": "Thank you!",108 // "done": false109 // };110 // } else {111 // npc.questGiver = false;112 // npc.ai = "wander";113 // }114115 // npc.draw = function () {116 // if (chunkIndex == this.chunk) {117118119120121122123124125126127 spr.draw = function () {128 if (chunkIndex == spr.chunk) {129 image(spr.image, spr.deltaX * 2, spr.deltaY * 2);130 }131 }132 spr.update = function () {133 if ((chunkIndex == this.chunk) && (CURRENT_SCENE == SCENES.GAME)) { // only update on current chunk / not paused134 chunkNPCSprites.add(this);135136 // update based on AI type137 if (spr.ai == "wander") {138 if (random() > 0.9) { // decide to move139140 // pick a direction141 let _dirs = ["up", "down", "left", "right"];142 let _move = {};143 _move[_dirs[Math.floor(Math.random() * _dirs.length)]] = true;144 let _retval = checkMove(spr.position, chunkIndex, _move);145 //_dirs[Math.floor(Math.random() * _dirs.length)]);146 if (_retval['state']) { // true -- move147 spr.position.x = _retval['pos']['dx'];148 spr.position.y = _retval['pos']['dy'];149 }150 }151 } else if (spr.ai == "loiter") {152 ;153 } else if (spr.ai == "follow") {154 // https://stackoverflow.com/questions/20044791/how-to-make-an-enemy-follow-the-player-in-pygame155 if (random() > 0.8) { // move towards player156 // direction vector157 let dx = player.position.x - spr.position.x;158 let dy = player.position.y - spr.position.y;159 let dist = Math.hypot(dx, dy);160161 // normalize162 dx /= dist;163 dy /= dist;164165 if (!(dist == 16)) {166 if (random() > 0.5) { // move x167 if (dx > 0)168 spr.position.x += TILE_WIDTH;169 else if (dx < 0)170 spr.position.x -= TILE_WIDTH;171 } else { // move y172 if (dy > 0)173 spr.position.y += TILE_HEIGHT;174 else if (dy < 0)175 spr.position.y -= TILE_HEIGHT;176 }177 }178 //spr.position.x += dx * spr.speed;179 //spr.position.y += dy * spr.speed;180 }181 }182 } else183 chunkNPCSprites.remove(this);184 }185186 return spr;187}188189/*190class Character {191 constructor(name, sprite, row, col, char_type, ai, image, chunk) {192193 }194 setNPC(mood, vipTitle, occupation, speed, questGiver, quest) {195 this.mood = mood;196 this.vipTitle = vipTitle;197 this.occupation = occupation;198 this.speed = speed;199 this.chunk = chunk;200 this.quest = quest;201 this.questGiver = questGiver;202 }203}204*/205206/*207 // npc208 let questGiver = getRandomInteger(0, numGenericNPCs);209 for (let _n = 0; _n < numGenericNPCs + 2; _n++) {210 let _c = getRandomInteger(1, MAP_COLS - 1);211 let _r = getRandomInteger(1, MAP_ROWS - 1);212213 if (_n == numGenericNPCs) { // campfire friend214 _r = _cf_row;215 _c = _cf_col;216 } else if (_n == numGenericNPCs+1) { // fisherman friend217 _r = 50;218 _c = 61;219 }220221 npc = createSprite((TILE_WIDTH * _c) + (TILE_WIDTH / 2), (TILE_HEIGHT * _r) + (TILE_HEIGHT / 2), TILE_WIDTH, TILE_HEIGHT);222 /// generative:223 npc.name = npc_grammar.flatten("#name#");224 npc.mood = npc_grammar.flatten("#mood#");225 npc.vipTitle = npc_grammar.flatten("#vipTitle#");226 npc.occupation = npc_grammar.flatten("#occupation#");227 ///228 npc.depth = NPC_INDEX;229 //npc.addImage = npcImg;230 npc.chunk = getRandomInteger(0, NUM_CHUNKS); //1;231 npc.speed = 2; // tbd232 npc.dialogue_index = 0;233234 if (_n == questGiver) {235 npc.questGiver = true;236 npc.ai = "follow";237 console.log("Questy McQuesterson on: " + npc.chunk);238 npc.quest = {239 "quest": "Have you seen my BLUE CRAB?", // make this a list?240 "thanks": "Thanks m8",241 "done": false242 };243 } else if (_n == numGenericNPCs) { // last one hangs by the campfire244 npc.questGiver = true;245 npc.ai = "loiter";246 npc.chunk = _campfireChunk;247 npc.quest = {248 "quest": "body", // make this a list?249 "questDialogue": [250 event_grammar.flatten("#campfire1#"),251 event_grammar.flatten("#campfire2#"),252 event_grammar.flatten("#campfire3#"),253 event_grammar.flatten("#campfire4#"),254 event_grammar.flatten("#campfire5#"),255 event_grammar.flatten("#campfire6#"),256 event_grammar.flatten("#campfire7#"),257 ],258 "thanks": "Thanks m8",259 "done": false260 };261 console.log(npc.quest["questDialogue"]);262 } else if (_n == numGenericNPCs+1) { // mike the fisherman263 npc.name = "Mike the Fisherman";264 npc.questGiver = true;265 npc.ai = "loiter";266 npc.chunk = NUM_CHUNKS+TOWN_CHUNKS.FRILL;267 npc.quest = {268 "quest": "fish", // make this a list?269 "questDialogue": [270 "Hey there", ...

Full Screen

Full Screen

fcos_loss.py

Source:fcos_loss.py Github

copy

Full Screen

...34 if channel_first:35 input_channel_last = paddle.transpose(inputs, perm=[0, 2, 3, 1])36 else:37 input_channel_last = inputs38 output_channel_last = paddle.flatten(39 input_channel_last, start_axis=0, stop_axis=2)40 return output_channel_last41@register42class FCOSLoss(nn.Layer):43 """44 FCOSLoss45 Args:46 loss_alpha (float): alpha in focal loss47 loss_gamma (float): gamma in focal loss48 iou_loss_type (str): location loss type, IoU/GIoU/LINEAR_IoU49 reg_weights (float): weight for location loss50 """51 def __init__(self,52 loss_alpha=0.25,...

Full Screen

Full Screen

inject_cube.py

Source:inject_cube.py Github

copy

Full Screen

...15 X_og = np.linspace(x,x+leng,leng*400)16 Y_og = np.linspace(y,y+leng,leng*400)17 Z_og = np.linspace(z,z+leng,leng*400)18 X, Y = np.meshgrid(X_og, Y_og)19 cube_1 = np.array([X.flatten(), Y.flatten(), np.ones_like(X.flatten())*np.min(Z_og), np.ones_like(X.flatten())*144./255.]).transpose()20 cube_2 = np.array([X.flatten(), Y.flatten(), np.ones_like(X.flatten())*np.max(Z_og), np.ones_like(X.flatten())*144./255.]).transpose()21 X, Z = np.meshgrid(X_og, Z_og)22 cube_3 = np.array([X.flatten(), np.ones_like(X.flatten())*np.min(Y_og), Z.flatten(), np.ones_like(X.flatten())*144./255.]).transpose()23 cube_4 = np.array([X.flatten(), np.ones_like(X.flatten())*np.max(Y_og), Z.flatten(), np.ones_like(X.flatten())*144./255.]).transpose()24 Y, Z = np.meshgrid(Y_og, Z_og)25 cube_5 = np.array([np.ones_like(Y.flatten())*np.min(X_og), Y.flatten(), Z.flatten(), np.ones_like(Y.flatten())*144./255.]).transpose()26 cube_6 = np.array([np.ones_like(Y.flatten())*np.max(X_og), Y.flatten(), Z.flatten(), np.ones_like(Y.flatten())*144./255.]).transpose()27 cube = np.concatenate((cube_1, cube_2, cube_3, cube_4, cube_5, cube_6), axis=0)28 cube = appendSpherical_np(cube)29 h_granularity = 0.2 / 180 * np.pi30 v_granularity = 26.8 / 63 / 180 * np.pi31 min_h = np.min(cube[:,6])32 max_h = np.max(cube[:,6])33 min_v = np.min(cube[:,5])34 max_v = np.max(cube[:,5])35 36 PC_w,PC_wo = processPC(PC,min_h,max_h,min_v,max_v)37 totalsub = np.concatenate((PC_w,cube), axis=0)38 h_grids = round((max_h - min_h) / h_granularity)39 v_grids = round((max_v - min_v) / v_granularity)40 cube_project = []41 for h in range(int(h_grids)):42 for v in range(int(v_grids)):43 subset = totalsub44 subset = subset[subset[:,5] > min_v + v * v_granularity]45 subset = subset[subset[:,5] < min_v + (v + 1) * v_granularity]46 subset = subset[subset[:,6] > min_h + h * h_granularity]47 subset = subset[subset[:,6] < min_h + (h + 1) * h_granularity]48 if subset.size != 0:49 cube_project.append(subset[np.argmin(subset[:,4])])50 cube_project = np.array(cube_project)51 total = np.concatenate((PC_wo,cube_project), axis=0)52 return total53def injectCylinder(PC,h,r,x,y,z):54 PC = appendSpherical_np(PC)55 C_og = np.linspace(0,2*np.pi,400)56 Z_og = np.linspace(z,z+h,400)57 R_og = np.linspace(0,r,400)58 C, Z = np.meshgrid(C_og, Z_og)59 surface_1 = np.array([np.ones_like(C.flatten())*r, C.flatten(), Z.flatten(), np.ones_like(C.flatten())*144./255.]).transpose()60 61 C, R = np.meshgrid(C_og, R_og)62 surface_2 = np.array([R.flatten(), C.flatten(), np.ones_like(R.flatten())*np.min(Z_og), np.ones_like(C.flatten())*144./255.]).transpose()63 surface_3 = np.array([R.flatten(), C.flatten(), np.ones_like(R.flatten())*np.max(Z_og), np.ones_like(C.flatten())*144./255.]).transpose()64 65 cylinder = np.concatenate((surface_1, surface_2, surface_3), axis=0)66 cylinder = replaceCoord_np(cylinder)67 cylinder[:,0] += x68 cylinder[:,1] += y69 cylinder = appendSpherical_np(cylinder)70 h_granularity = 0.2 / 180 * np.pi71 v_granularity = 26.8 / 63 / 180 * np.pi72 min_h = np.min(cylinder[:,6])73 max_h = np.max(cylinder[:,6])74 min_v = np.min(cylinder[:,5])75 max_v = np.max(cylinder[:,5])76 77 PC_w,PC_wo = processPC(PC,min_h,max_h,min_v,max_v)78 totalsub = np.concatenate((PC_w,cylinder), axis=0)79 h_grids = round((max_h - min_h) / h_granularity)80 v_grids = round((max_v - min_v) / v_granularity)81 cylinder_project = []82 for h in range(int(h_grids)):83 for v in range(int(v_grids)):84 subset = totalsub85 subset = subset[subset[:,5] > min_v + v * v_granularity]86 subset = subset[subset[:,5] < min_v + (v + 1) * v_granularity]87 subset = subset[subset[:,6] > min_h + h * h_granularity]88 subset = subset[subset[:,6] < min_h + (h + 1) * h_granularity]89 if subset.size != 0:90 cylinder_project.append(subset[np.argmin(subset[:,4])])91 cylinder_project = np.array(cylinder_project)92 total = np.concatenate((PC_wo,cylinder_project), axis=0)93 return total94def injectPyramid(PC,h,r1,r2,x,y,z):95 PC = appendSpherical_np(PC)96 C_og = np.linspace(0,2*np.pi,400)97 Z_og = np.linspace(z,z+h,400)98 R1_og = np.linspace(0,r1,400)99 R2_og = np.linspace(0,r2,400)100 R3_og = np.linspace(r1,r2,400)101 C, Z = np.meshgrid(C_og, Z_og)102 _,R3 = np.meshgrid(C_og, R3_og) 103 surface_1 = np.array([R3.flatten(), C.flatten(), Z.flatten(), np.ones_like(C.flatten())*144./255.]).transpose()104 105 C, R1 = np.meshgrid(C_og, R1_og)106 surface_2 = np.array([R1.flatten(), C.flatten(), np.ones_like(R1.flatten())*np.min(Z_og), np.ones_like(C.flatten())*144./255.]).transpose()107 108 C, R2 = np.meshgrid(C_og, R2_og)109 surface_3 = np.array([R2.flatten(), C.flatten(), np.ones_like(R2.flatten())*np.max(Z_og), np.ones_like(C.flatten())*144./255.]).transpose()110 111 pyramid = np.concatenate((surface_1, surface_2, surface_3), axis=0)112 pyramid = replaceCoord_np(pyramid)113 pyramid[:,0] += x114 pyramid[:,1] += y115 pyramid = appendSpherical_np(pyramid)116 h_granularity = 0.2 / 180 * np.pi117 v_granularity = 26.8 / 63 / 180 * np.pi118 min_h = np.min(pyramid[:,6])119 max_h = np.max(pyramid[:,6])120 min_v = np.min(pyramid[:,5])121 max_v = np.max(pyramid[:,5])122 123 PC_w,PC_wo = processPC(PC,min_h,max_h,min_v,max_v)...

Full Screen

Full Screen

0001_migrate_metadata.py

Source:0001_migrate_metadata.py Github

copy

Full Screen

1# Generated by Django 2.2.9 on 2020-02-07 07:322from django.db import migrations3def flatten_model_metadata(model_with_metadata):4 updated_fields = []5 public_meta = model_with_metadata.metadata6 private_meta = model_with_metadata.private_metadata7 if public_meta:8 model_with_metadata.metadata = flatten_metadata(public_meta)9 updated_fields.append("metadata")10 if private_meta:11 model_with_metadata.private_metadata = flatten_metadata(private_meta)12 updated_fields.append("private_metadata")13 if updated_fields:14 model_with_metadata.save(update_fields=updated_fields)15def flatten_metadata(metadata):16 flattened_metadata = {}17 for _, namespace in metadata.items():18 for client_name, client in namespace.items():19 for key, value in client.items():20 flattened_key = client_name + "." + key21 if flattened_key in flattened_metadata:22 raise Exception(f"Meta key {flattened_key} is duplicated.")23 flattened_metadata[flattened_key] = value24 return flattened_metadata25def flatten_attributes_metadata(apps, _schema_editor):26 Attribute = apps.get_model("product", "Attribute")27 for attribute in Attribute.objects.iterator():28 flatten_model_metadata(attribute)29def flatten_categories_metadata(apps, _schema_editor):30 Category = apps.get_model("product", "Category")31 for category in Category.objects.iterator():32 flatten_model_metadata(category)33def flatten_checkouts_metadata(apps, _schema_editor):34 Checkout = apps.get_model("checkout", "Checkout")35 for checkout in Checkout.objects.iterator():36 flatten_model_metadata(checkout)37def flatten_collections_metadata(apps, _schema_editor):38 Collection = apps.get_model("product", "Collection")39 for collection in Collection.objects.iterator():40 flatten_model_metadata(collection)41def flatten_digital_contents_metadata(apps, _schema_editor):42 DigitalContent = apps.get_model("product", "DigitalContent")43 for digital_content in DigitalContent.objects.iterator():44 flatten_model_metadata(digital_content)45def flatten_fulfillments_metadata(apps, _schema_editor):46 Fulfillment = apps.get_model("order", "Fulfillment")47 for fulfillment in Fulfillment.objects.iterator():48 flatten_model_metadata(fulfillment)49def flatten_orders_metadata(apps, _schema_editor):50 Order = apps.get_model("order", "Order")51 for order in Order.objects.iterator():52 flatten_model_metadata(order)53def flatten_products_metadata(apps, _schema_editor):54 Product = apps.get_model("product", "Product")55 for product in Product.objects.iterator():56 flatten_model_metadata(product)57def flatten_product_types_metadata(apps, _schema_editor):58 ProductType = apps.get_model("product", "ProductType")59 for product_type in ProductType.objects.iterator():60 flatten_model_metadata(product_type)61def flatten_product_variants_metadata(apps, _schema_editor):62 ProductVariant = apps.get_model("product", "ProductVariant")63 for product_variant in ProductVariant.objects.iterator():64 flatten_model_metadata(product_variant)65def flatten_service_accounts_metadata(apps, _schema_editor):66 ServiceAccount = apps.get_model("account", "ServiceAccount")67 for service_account in ServiceAccount.objects.iterator():68 flatten_model_metadata(service_account)69def flatten_users_metadata(apps, _schema_editor):70 User = apps.get_model("account", "User")71 for user in User.objects.iterator():72 flatten_model_metadata(user)73class Migration(migrations.Migration):74 dependencies = [75 ("account", "0039_auto_20200221_0257"),76 ("checkout", "0025_auto_20200221_0257"),77 ("order", "0078_auto_20200221_0257"),78 ("product", "0115_auto_20200221_0257"),79 ]80 run_before = [("attribute", "0001_initial")]81 operations = [82 migrations.RunPython(flatten_attributes_metadata),83 migrations.RunPython(flatten_categories_metadata),84 migrations.RunPython(flatten_checkouts_metadata),85 migrations.RunPython(flatten_collections_metadata),86 migrations.RunPython(flatten_digital_contents_metadata),87 migrations.RunPython(flatten_fulfillments_metadata),88 migrations.RunPython(flatten_orders_metadata),89 migrations.RunPython(flatten_products_metadata),90 migrations.RunPython(flatten_product_types_metadata),91 migrations.RunPython(flatten_product_variants_metadata),92 migrations.RunPython(flatten_service_accounts_metadata),93 migrations.RunPython(flatten_users_metadata),...

Full Screen

Full Screen

flatten-methods.js

Source:flatten-methods.js Github

copy

Full Screen

...8 var array = [1, [2, [3, [4]], 5]],9 methodNames = ['flatten', 'flattenDeep', 'flattenDepth'];10 it('should flatten `arguments` objects', function() {11 var array = [args, [args]];12 assert.deepStrictEqual(flatten(array), [1, 2, 3, args]);13 assert.deepStrictEqual(flattenDeep(array), [1, 2, 3, 1, 2, 3]);14 assert.deepStrictEqual(flattenDepth(array, 2), [1, 2, 3, 1, 2, 3]);15 });16 it('should treat sparse arrays as dense', function() {17 var array = [[1, 2, 3], Array(3)],18 expected = [1, 2, 3];19 expected.push(undefined, undefined, undefined);20 lodashStable.each(methodNames, function(methodName) {21 var actual = _[methodName](array);22 assert.deepStrictEqual(actual, expected);23 assert.ok('4' in actual);24 });25 });26 it('should flatten objects with a truthy `Symbol.isConcatSpreadable` value', function() {27 if (Symbol && Symbol.isConcatSpreadable) {28 var object = { '0': 'a', 'length': 1 },29 array = [object],30 expected = lodashStable.map(methodNames, lodashStable.constant(['a']));31 object[Symbol.isConcatSpreadable] = true;32 var actual = lodashStable.map(methodNames, function(methodName) {33 return _[methodName](array);34 });35 assert.deepStrictEqual(actual, expected);36 }37 });38 it('should work with extremely large arrays', function() {39 lodashStable.times(3, function(index) {40 var expected = Array(5e5);41 try {42 var func = flatten;43 if (index == 1) {44 func = flattenDeep;45 } else if (index == 2) {46 func = flattenDepth;47 }48 assert.deepStrictEqual(func([expected]), expected);49 } catch (e) {50 assert.ok(false, e.message);51 }52 });53 });54 it('should work with empty arrays', function() {55 var array = [[], [[]], [[], [[[]]]]];56 assert.deepStrictEqual(flatten(array), [[], [], [[[]]]]);57 assert.deepStrictEqual(flattenDeep(array), []);58 assert.deepStrictEqual(flattenDepth(array, 2), [[[]]]);59 });60 it('should support flattening of nested arrays', function() {61 assert.deepStrictEqual(flatten(array), [1, 2, [3, [4]], 5]);62 assert.deepStrictEqual(flattenDeep(array), [1, 2, 3, 4, 5]);63 assert.deepStrictEqual(flattenDepth(array, 2), [1, 2, 3, [4], 5]);64 });65 it('should return an empty array for non array-like objects', function() {66 var expected = [],67 nonArray = { '0': 'a' };68 assert.deepStrictEqual(flatten(nonArray), expected);69 assert.deepStrictEqual(flattenDeep(nonArray), expected);70 assert.deepStrictEqual(flattenDepth(nonArray, 2), expected);71 });72 it('should return a wrapped value when chaining', function() {73 var wrapped = _(array),74 actual = wrapped.flatten();75 assert.ok(actual instanceof _);76 assert.deepEqual(actual.value(), [1, 2, [3, [4]], 5]);77 actual = wrapped.flattenDeep();78 assert.ok(actual instanceof _);79 assert.deepEqual(actual.value(), [1, 2, 3, 4, 5]);80 actual = wrapped.flattenDepth(2);81 assert.ok(actual instanceof _);82 assert.deepEqual(actual.value(), [1, 2, 3, [4], 5]);83 });...

Full Screen

Full Screen

parse_bert.py

Source:parse_bert.py Github

copy

Full Screen

1import argparse2import json3import copy4import pathlib5from distutils.util import strtobool6from run_bert import main7from utils import is_num8f = open("config_bert.json", "r")9config = json.load(f)10f.close()11flatten_config = {}12for key in config.keys():13 flatten_config.update(config[key])14# print(flatten_config)15parser = argparse.ArgumentParser(description="subprocess for grid search")16parser.add_argument("--name", default="")17for key in flatten_config.keys():18 if type(flatten_config[key])==bool:19 parser.add_argument("--{}".format(key), default=flatten_config[key], type=strtobool)20 elif type(flatten_config[key])==list:21 parser.add_argument("--{}".format(key), default=flatten_config[key], type=type(flatten_config[key][0]) if len(flatten_config[key])>0 else None, nargs="*")22 elif type(flatten_config[key])==str and "/" in flatten_config[key]:23 parser.add_argument("--{}".format(key), default=flatten_config[key], type=pathlib.Path)24 elif flatten_config[key] is None or type(flatten_config[key])==int:25 parser.add_argument("--{}".format(key), default=flatten_config[key])26 else:27 parser.add_argument("--{}".format(key), default=flatten_config[key], type=type(flatten_config[key]))28new_flatten_config = vars(parser.parse_args())29new_config = copy.deepcopy(config)30for top_key in config.keys():31 for key in config[top_key].keys():32 if type(config[top_key][key])==bool:33 new_config[top_key][key] = bool(new_flatten_config[key])34 elif type(config[top_key][key])==str and "/" in config[top_key][key]:35 new_config[top_key][key] = str(new_flatten_config[key])36 elif new_flatten_config[key]=="None" or new_flatten_config[key] is None:37 new_config[top_key][key] = None38 elif type(new_flatten_config[key])==str:39 if str.isdigit(new_flatten_config[key]):40 new_config[top_key][key] = int(new_flatten_config[key])41 elif is_num(new_flatten_config[key]):42 new_config[top_key][key] = float(new_flatten_config[key])43 else:44 new_config[top_key][key] = new_flatten_config[key]45 else:46 new_config[top_key][key] = new_flatten_config[key]47 ...

Full Screen

Full Screen

array-flatten.js

Source:array-flatten.js Github

copy

Full Screen

1'use strict'2/**3 * Expose `arrayFlatten`.4 */5module.exports = flatten6module.exports.from = flattenFrom7module.exports.depth = flattenDepth8module.exports.fromDepth = flattenFromDepth9/**10 * Flatten an array.11 *12 * @param {Array} array13 * @return {Array}14 */15function flatten (array) {16 if (!Array.isArray(array)) {17 throw new TypeError('Expected value to be an array')18 }19 return flattenFrom(array)20}21/**22 * Flatten an array-like structure.23 *24 * @param {Array} array25 * @return {Array}26 */27function flattenFrom (array) {28 return flattenDown(array, [])29}30/**31 * Flatten an array-like structure with depth.32 *33 * @param {Array} array34 * @param {number} depth35 * @return {Array}36 */37function flattenDepth (array, depth) {38 if (!Array.isArray(array)) {39 throw new TypeError('Expected value to be an array')40 }41 return flattenFromDepth(array, depth)42}43/**44 * Flatten an array-like structure with depth.45 *46 * @param {Array} array47 * @param {number} depth48 * @return {Array}49 */50function flattenFromDepth (array, depth) {51 if (typeof depth !== 'number') {52 throw new TypeError('Expected the depth to be a number')53 }54 return flattenDownDepth(array, [], depth)55}56/**57 * Flatten an array indefinitely.58 *59 * @param {Array} array60 * @param {Array} result61 * @return {Array}62 */63function flattenDown (array, result) {64 for (var i = 0; i < array.length; i++) {65 var value = array[i]66 if (Array.isArray(value)) {67 flattenDown(value, result)68 } else {69 result.push(value)70 }71 }72 return result73}74/**75 * Flatten an array with depth.76 *77 * @param {Array} array78 * @param {Array} result79 * @param {number} depth80 * @return {Array}81 */82function flattenDownDepth (array, result, depth) {83 depth--84 for (var i = 0; i < array.length; i++) {85 var value = array[i]86 if (depth > -1 && Array.isArray(value)) {87 flattenDownDepth(value, result, depth)88 } else {89 result.push(value)90 }91 }92 return result...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1const wptoolkit = require('wptoolkit');2var arr = [1, 2, [3, 4, [5, 6]]];3var flattened = wptoolkit.flatten(arr);4console.log(flattened);5### `wptoolkit.unflatten(array, depth)`6const wptoolkit = require('wptoolkit');7var arr = [1, 2, 3, 4, 5, 6];8var unflattened = wptoolkit.unflatten(arr, 2);9console.log(unflattened);10### `wptoolkit.getArrayMax(array)`11const wptoolkit = require('wptoolkit');12var arr = [1, 2, 3, 4, 5, 6];13var max = wptoolkit.getArrayMax(arr);14console.log(max);15### `wptoolkit.getArrayMin(array)`16const wptoolkit = require('wptoolkit');17var arr = [1, 2, 3, 4, 5, 6];18var min = wptoolkit.getArrayMin(arr);19console.log(min);20### `wptoolkit.getArraySum(array)`21const wptoolkit = require('wptoolkit');22var arr = [1, 2, 3, 4, 5, 6];23var sum = wptoolkit.getArraySum(arr);24console.log(sum);25### `wptoolkit.getArrayAverage(array)`

Full Screen

Using AI Code Generation

copy

Full Screen

1var wptools = require('wptools');2var flatten = require('flat');3wptools.page('Barack Obama').get(function(err, resp) {4 console.log(resp);5});6{ title: 'Barack Obama',7 extract: 'Barack Hussein Obama II (/bəˈrɑːk huːˈseɪn oʊˈbɑːmə/; born August 4, 1961) is an American politician and attorney who served as the 44th president of the United States from 2009 to 2017. A member of the Democratic Party, he was the first African American to be elected to the presidency. He previously served as a U.S. senator from Illinois from 2005 to 2008 and an Illinois state senator from 1997 to 2004. Born in Honolulu, Hawaii, Obama is a graduate of Columbia University and Harvard Law School, where he was president of the Harvard Law Review. He was a community organizer in Chicago before earning his law degree. He worked as a civil rights attorney and taught constitutional law at the University of Chicago Law School from 1992 to 2004. He served three terms representing the 13th District in the Illinois Senate from 1997 until 2004, when he ran for the U.S. Senate.',

Full Screen

Using AI Code Generation

copy

Full Screen

1var wptools = require('wptools');2var wiki = wptools.page('Barack Obama');3wiki.get(function(err,resp){4 var data = resp.data;5 var flattenedData = data.flatten();6 console.log(flattenedData);7});

Full Screen

Using AI Code Generation

copy

Full Screen

1const wptools = require('wptools')2wptools.page('Barack Obama').get().then((page) => {3}).catch((error) => {4 console.log(error)5})6### wptools.page(page, [options])

Full Screen

Using AI Code Generation

copy

Full Screen

1const wptools = require('wptools');2const fs = require('fs');3function flatten(data) {4 return Object.keys(data).reduce((acc, key) => {5 if (typeof data[key] === 'object' && data[key] !== null) {6 return { ...acc, ...flatten(data[key]) };7 }8 return { ...acc, [key]: data[key] };9 }, {});10}11function getDataFromWikipedia() {12 .page('Barack Obama')13 .then((page) => page.get())14 .then((page) => page.json())15 .then((page) => {16 const data = flatten(page);17 return data;18 });19}20function writeDataToFile() {21 getDataFromWikipedia().then((data) => {22 fs.writeFile('data.json', JSON.stringify(data), 'utf8', (err) => {23 if (err) {24 console.log(err);25 }26 });27 });28}29writeDataToFile();30function readDataFromFile() {31 fs.readFile('data.json', 'utf8', (err, data) => {32 if (err) {33 console.log(err);34 } else {35 console.log(data);36 }37 });38}39readDataFromFile();

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