How to use populate method in wpt

Best JavaScript code snippet using wpt

cropRepository.ts

Source:cropRepository.ts Github

copy

Full Screen

...23 sort,24 populate25 }: any): Promise<any> {26 return Crop.find(query ?? {})27 .populate(populate ?? [])28 .limit(limit ?? 0)29 .skip(skip ?? 0)30 .sort(sort ?? {})31 }32 /**33 * @function findCropsSample34 * Get crops sample.35 * @param object query36 */37 public static async findCropsSample(query) {38 const crops = await Crop.find(query).lean()39 return crops40 }41 public static async findOneSample(query) {42 return Crop.findOne(query).lean()43 }44 /**45 *46 * @param identifier47 */48 public static async findAllCropsByCompanies(identifier: string) {49 const cropsInstance = await Crop.find({50 cancelled: false,51 'members.identifier': identifier52 })53 .populate('lots.data')54 .populate('cropType')55 .populate('unitType')56 .populate({57 path: 'company',58 populate: [59 { path: 'files' },60 { path: 'contacts.user' },61 { path: 'country' }62 ]63 })64 .populate({65 path: 'pending',66 populate: [67 { path: 'collaborators' },68 { path: 'type' },69 { path: 'typeAgreement' },70 { path: 'lots', select: '-area -__v' },71 { path: 'files' },72 {73 path: 'supplies',74 populate: [{ path: 'typeId' }]75 },76 {77 path: 'storages',78 populate: [{ path: 'storageType' }]79 }80 ]81 })82 .populate({83 path: 'toMake',84 populate: [85 { path: 'collaborators' },86 { path: 'type' },87 { path: 'typeAgreement' },88 { path: 'lots', select: '-area -__v' },89 { path: 'files' },90 {91 path: 'supplies',92 populate: [{ path: 'typeId' }]93 },94 {95 path: 'storages',96 populate: [{ path: 'storageType' }]97 }98 ]99 })100 .populate({101 path: 'done',102 populate: [103 { path: 'collaborators' },104 { path: 'type' },105 { path: 'typeAgreement' },106 { path: 'lots', select: '-area -__v' },107 { path: 'files' },108 {109 path: 'achievements',110 populate: [111 { path: 'lots' },112 { path: 'files' },113 { path: 'supplies', populate: [{ path: 'typeId' }] }114 ]115 },116 {117 path: 'supplies',118 populate: [{ path: 'typeId' }]119 },120 {121 path: 'storages',122 populate: [{ path: 'storageType' }]123 },124 { path: 'lotsMade' }125 ]126 })127 .populate({128 path: 'finished',129 populate: [130 { path: 'collaborators' },131 { path: 'type' },132 { path: 'typeAgreement' },133 { path: 'lots', select: '-area -__v' },134 { path: 'files' },135 {136 path: 'supplies',137 populate: [{ path: 'typeId' }]138 },139 {140 path: 'storages',141 populate: [{ path: 'storageType' }]142 },143 {144 path: 'achievements',145 populate: [146 { path: 'lots' },147 { path: 'files' },148 { path: 'supplies', populate: [{ path: 'typeId' }] }149 ]150 }151 ]152 })153 .populate('members.user')154 .lean()155 return cropsInstance.length156 ? cropsInstance.map((crop) => joinActivitiesByCrop(crop))157 : null158 }159 /**160 * Get One crop and json converter.161 *162 * @param id163 */164 public static async getCropWithActivities(id: string) {165 const cropInstance = await Crop.findById(id)166 .populate({167 path: 'lots.data',168 populate: [{ path: 'envImpactIndex', select: 'eiq' }]169 })170 .populate('cropType')171 .populate('unitType')172 .populate('envImpactIndex', 'eiq')173 .populate('badges.badge')174 .populate({175 path: 'pending',176 populate: [177 { path: 'collaborators' },178 { path: 'envImpactIndex', select: 'eiq' },179 { path: 'unitType' },180 { path: 'type' },181 { path: 'typeAgreement' },182 { path: 'files' },183 { path: 'lots', select: '-area -__v -geometryData' },184 {185 path: 'supplies',186 populate: [{ path: 'typeId' }]187 },188 {189 path: 'storages',190 populate: [{ path: 'storageType' }]191 }192 ]193 })194 .populate({195 path: 'toMake',196 populate: [197 { path: 'collaborators' },198 { path: 'envImpactIndex', select: 'eiq' },199 { path: 'unitType' },200 { path: 'type' },201 { path: 'typeAgreement' },202 { path: 'lots', select: '-area -__v -geometryData' },203 { path: 'files' },204 {205 path: 'supplies',206 populate: [{ path: 'typeId' }]207 },208 {209 path: 'storages',210 populate: [{ path: 'storageType' }]211 }212 ]213 })214 .populate({215 path: 'done',216 populate: [217 { path: 'envImpactIndex', select: 'eiq' },218 { path: 'collaborators' },219 { path: 'unitType' },220 { path: 'type' },221 { path: 'typeAgreement' },222 {223 path: 'lots',224 select: '-area -__v -geometryData',225 populate: [{ path: 'envImpactIndex', select: 'eiq' }]226 },227 { path: 'files' },228 {229 path: 'achievements',230 populate: [231 {232 path: 'lots',233 populate: [{ path: 'envImpactIndex', select: 'eiq' }]234 },235 { path: 'envImpactIndex', select: 'eiq' },236 { path: 'files' },237 { path: 'supplies.supply', populate: [{ path: 'typeId' }] },238 { path: 'supplies.typeId' }239 ]240 },241 { path: 'supplies.supply', populate: [{ path: 'typeId' }] },242 { path: 'supplies.typeId' },243 {244 path: 'storages',245 populate: [{ path: 'storageType' }]246 },247 { path: 'lotsMade' }248 ]249 })250 .populate({251 path: 'finished',252 populate: [253 { path: 'envImpactIndex', select: 'eiq' },254 { path: 'collaborators' },255 { path: 'unitType' },256 { path: 'type' },257 { path: 'typeAgreement' },258 {259 path: 'lots',260 select: '-area -__v -geometryData',261 populate: [{ path: 'envImpactIndex', select: 'eiq' }]262 },263 { path: 'files' },264 { path: 'supplies.supply', populate: [{ path: 'typeId' }] },265 { path: 'supplies.typeId' },266 {267 path: 'storages',268 populate: [{ path: 'storageType' }]269 },270 {271 path: 'achievements',272 populate: [273 {274 path: 'lots',275 populate: [{ path: 'envImpactIndex', select: 'eiq' }]276 },277 { path: 'envImpactIndex', select: 'eiq' },278 { path: 'files' },279 { path: 'supplies.supply', populate: [{ path: 'typeId' }] },280 { path: 'supplies.typeId' }281 ]282 }283 ]284 })285 .populate('members.user')286 .lean({ virtuals: true })287 return cropInstance ? joinActivitiesByCrop(cropInstance) : null288 }289 /**290 * Get All crops by identifier and type.291 *292 * @param string id293 */294 public static async findAllCropsByCompanyAndCropType({ cropType, company }) {295 const cropsInstance = await Crop.find({296 cancelled: false,297 cropType,298 company299 })300 .populate('unitType')301 .lean()302 return cropsInstance.length ? cropsInstance : null303 }304 /**305 * Get All crops by identifier and type.306 *307 * @param string id308 */309 public static async findAllCropType({ id }) {310 const cropTypeInstance = await CropType.find({ id }).populate('name').lean()311 return cropTypeInstance.length ? cropTypeInstance : null312 }313 public static async findCropsWithLotsPopulateData(query) {314 const crops = await Crop.find(query).populate('lots.data')315 return crops316 }317 public static async findAllEvidencesByCropId(cropId: string) {318 const cropsInstance = await Crop.findById(cropId)319 .populate({320 path: 'done',321 populate: [322 { path: 'files' },323 { path: 'satelliteImages' },324 {325 path: 'achievements',326 populate: [{ path: 'files' }]327 }328 ]329 })330 .populate('members.user')331 .populate({332 path: 'company',333 populate: [334 { path: 'files' },335 { path: 'contacts.user' },336 { path: 'country' }337 ]338 })339 .populate({340 path: 'finished',341 populate: [342 { path: 'files' },343 { path: 'satelliteImages' },344 {345 path: 'achievements',346 populate: [{ path: 'files' }]347 }348 ]349 })350 .lean({ virtuals: true })351 return cropsInstance ? listEvidencesCrop(cropsInstance) : null352 }353 /**354 * Get crops.355 *356 * @param object pipeline357 */358 public static async findCrops(pipeline: any) {359 const cropsInstance = await Crop.aggregate(pipeline).allowDiskUse(true)360 return cropsInstance.length ? cropsInstance : null361 }362 /**363 *364 * @param query365 * @param dataToUpdate366 *367 * @returns368 */369 public static async updateOneCrop(370 query: any,371 dataToUpdate: any372 ): Promise<any> {373 return Crop.updateOne(query, dataToUpdate)374 }375 /**376 *377 * @param type378 */379 public static async findCropsFilterActivityForBilling(query, type) {380 const cropsInstance = await this.getCropWithPopulates(query, 'find')381 return !!cropsInstance.length382 ? joinActivitiesFilterTypeWithCrop(cropsInstance, type)383 : null384 }385 /**386 *387 * @param query388 * @returns389 */390 private static async getCropWithPopulates(391 query,392 method: string,393 isVirtuals?: boolean394 ) {395 const queryCrops = Crop[method](query)396 .populate('lots.data')397 .populate('cropType')398 .populate('unitType')399 .populate({400 path: 'company',401 populate: [402 { path: 'files' },403 { path: 'contacts.user' },404 { path: 'country' }405 ]406 })407 .populate({408 path: 'pending',409 populate: [410 { path: 'collaborators' },411 { path: 'type' },412 { path: 'typeAgreement' },413 { path: 'lots', select: '-area -__v' },414 { path: 'files' },415 {416 path: 'supplies',417 populate: [{ path: 'typeId' }]418 },419 {420 path: 'storages',421 populate: [{ path: 'storageType' }]422 }423 ]424 })425 .populate({426 path: 'toMake',427 populate: [428 { path: 'collaborators' },429 { path: 'type' },430 { path: 'typeAgreement' },431 { path: 'lots', select: '-area -__v' },432 { path: 'files' },433 {434 path: 'supplies',435 populate: [{ path: 'typeId' }]436 },437 {438 path: 'storages',439 populate: [{ path: 'storageType' }]440 }441 ]442 })443 .populate({444 path: 'done',445 populate: [446 { path: 'collaborators' },447 { path: 'type' },448 { path: 'typeAgreement' },449 { path: 'lots', select: '-area -__v' },450 { path: 'files' },451 {452 path: 'achievements',453 populate: [454 { path: 'lots' },455 { path: 'files' },456 { path: 'supplies', populate: [{ path: 'typeId' }] }457 ]458 },459 {460 path: 'supplies',461 populate: [{ path: 'typeId' }]462 },463 {464 path: 'storages',465 populate: [{ path: 'storageType' }]466 },467 { path: 'lotsMade' }468 ]469 })470 .populate({471 path: 'finished',472 populate: [473 { path: 'collaborators' },474 { path: 'type' },475 { path: 'typeAgreement' },476 { path: 'lots', select: '-area -__v' },477 { path: 'files' },478 {479 path: 'supplies',480 populate: [{ path: 'typeId' }]481 },482 {483 path: 'storages',484 populate: [{ path: 'storageType' }]485 },486 {487 path: 'achievements',488 populate: [489 { path: 'lots' },490 { path: 'files' },491 { path: 'supplies', populate: [{ path: 'typeId' }] }492 ]493 }494 ]495 })496 .populate('members.user')497 if (isVirtuals) {498 return queryCrops.lean({ virtuals: true })499 }500 return queryCrops.lean()501 }...

Full Screen

Full Screen

Query.js

Source:Query.js Github

copy

Full Screen

...8 // check if user loggedIn ?9 if (!userId) throw new Error("User not logged in please login !");10 // if (userId !== args.id) throw new Error("Not Authorized");11 return User.findById(userId)12 .populate({13 path: "subcontracts",14 options: { sort: { createdAt: "asc" } },15 populate: { path: "subcontractCreatorId" },16 })17 .populate({18 path: "hirecontracts",19 options: { sort: { createdAt: "asc" } },20 populate: { path: "hirecontractCreatorId" },21 })22 .populate({23 path: "subcontracts",24 populate: { path: "hirecontractWorkId" },25 })26 .populate({27 path: "hirecontracts",28 populate: { path: "subcontractAcceptHirecontractId" },29 });30 },31 users: (parent, args, context, info) =>32 User.find({})33 .populate({34 path: "subcontracts",35 options: { sort: { createdAt: "asc" } },36 populate: { path: "subcontractCreatorId" },37 })38 .populate({39 path: "hirecontracts",40 options: { sort: { createdAt: "asc" } },41 populate: { path: "hirecontractCreatorId" },42 }),43 // Subcontract44 subcontract: (parent, args, context, info) =>45 Subcontract.findById(args.id)46 .populate({47 path: "subcontractCreatorId",48 populate: { path: "subcontracts" },49 })50 .populate({51 path: "hirecontractWorkId",52 populate: { path: "hirecontracts" },53 }),54 subcontracthasassign: (parent, args, context, info) =>55 Subcontract.find({ subcontractCreatorId: ObjectId(args.id) })56 .populate({57 path: "subcontractCreatorId",58 populate: { path: "subcontracts" },59 })60 .populate({61 path: "hirecontractWorkId",62 populate: { path: "subcontracts" },63 })64 .sort({ createdAt: "asc" }),65 subcontracts: (parent, args, context, info) =>66 Subcontract.find({})67 .populate({68 path: "subcontractCreatorId",69 populate: { path: "subcontracts" },70 })71 .sort({ createdAt: "asc" })72 .populate({73 path: "hirecontractWorkId",74 populate: { path: "hirecontracts" },75 }),76 subcontractswaiting: (parent, args, context, info) =>77 Subcontract.find({ status: "WAITING" })78 .populate({79 path: "subcontractCreatorId",80 populate: { path: "subcontracts" },81 })82 .sort({ createdAt: "asc" })83 .populate({84 path: "hirecontractWorkId",85 populate: { path: "hirecontracts" },86 }),87 subcontractsapprove: (parent, args, context, info) =>88 Subcontract.find({ status: "ยืนยันแล้ว" })89 .populate({90 path: "subcontractCreatorId",91 populate: { path: "subcontracts" },92 })93 .sort({ createdAt: "asc" })94 .populate({95 path: "hirecontractWorkId",96 populate: { path: "hirecontracts" },97 }),98 subcontractsdenied: (parent, args, context, info) =>99 Subcontract.find({ status: "ปฎิเสธ" })100 .populate({101 path: "subcontractCreatorId",102 populate: { path: "subcontracts" },103 })104 .sort({ createdAt: "asc" })105 .populate({106 path: "hirecontractWorkId",107 populate: { path: "hirecontracts" },108 }),109 subcontractspendingcancel: (parent, args, context, info) =>110 Subcontract.find({ status: "กำลังรอการตอบรับจากผู้ประสานงาน" })111 .populate({112 path: "subcontractCreatorId",113 populate: { path: "subcontracts" },114 })115 .sort({ createdAt: "asc" })116 .populate({117 path: "hirecontractWorkId",118 populate: { path: "hirecontracts" },119 }),120 adminapprovesubcontractspendingcancel: (parent, args, context, info) =>121 Subcontract.find({ status: "ผู้ประสานงานยินยอมการยกเลิกเรียบร้อยแล้ว" })122 .populate({123 path: "subcontractCreatorId",124 populate: { path: "subcontracts" },125 })126 .sort({ createdAt: "asc" })127 .populate({128 path: "hirecontractWorkId",129 populate: { path: "hirecontracts" },130 }),131 subcontractswebdevelopment: (parent, args, context, info) =>132 Subcontract.find({133 $and: [134 { status: "ตรวจสอบแล้ว" },135 { natureofwork: { $regex: "web development" } },136 ],137 })138 .populate({139 path: "subcontractCreatorId",140 populate: { path: "subcontracts" },141 })142 .sort({ createdAt: "asc" })143 .populate({144 path: "hirecontractWorkId",145 populate: { path: "hirecontracts" },146 }),147 subcontractswordpress: (parent, args, context, info) =>148 Subcontract.find({149 $and: [150 { status: "ตรวจสอบแล้ว" },151 { natureofwork: { $regex: "wordpress" } },152 ],153 })154 .populate({155 path: "subcontractCreatorId",156 populate: { path: "subcontracts" },157 })158 .sort({ createdAt: "asc" }),159 // Hirecontract160 hirecontract: (parent, args, context, info) =>161 Hirecontract.findById(args.id)162 .populate({163 path: "hirecontractCreatorId",164 populate: { path: "hirecontracts" },165 })166 .populate({167 path: "subcontractAcceptHirecontractId",168 populate: { path: "subcontracts" },169 }),170 hirecontracts: (parent, args, context, info) =>171 Hirecontract.find({})172 .populate({173 path: "hirecontractCreatorId",174 populate: { path: "hirecontracts" },175 })176 .populate({177 path: "subcontractAcceptHirecontractId",178 populate: { path: "subcontracts" },179 })180 .populate({181 path:"subcontractCreatorId",182 populate:{path:"users"}183 })184 .sort({ createdAt: "desc" }),185 hirecontractswaiting: (parent, args, context, info) =>186 Hirecontract.find({ status: "WAITING" })187 .populate({188 path: "hirecontractCreatorId",189 populate: { path: "hirecontracts" },190 })191 .populate({192 path: "subcontractAcceptHirecontractId",193 populate: { path: "subcontracts" },194 }),195 hirecontractswaitingassign: (parent, args, context, info) =>196 Hirecontract.find({ status: "กำลังรอการตอบรับจากผู้รับเหมาช่วง" }).populate(197 {198 path: "hirecontractCreatorId",199 populate: { path: "subcontracts" },200 }201 ),202 hirecontractsapprove: (parent, args, context, info) =>203 Hirecontract.find({ status: "APPROVE" })204 .populate({205 path: "hirecontractCreatorId",206 populate: { path: "hirecontracts" },207 })208 .populate({209 path: "subcontractAcceptHirecontractId",210 populate: { path: "subcontracts" },211 }),212 hirecontractsdenied: (parent, args, context, info) =>213 Hirecontract.find({ status: "DENIED" })214 .populate({215 path: "hirecontractCreatorId",216 populate: { path: "hirecontracts" },217 })218 .populate({219 path: "subcontractAcceptHirecontractId",220 populate: { path: "subcontracts" },221 }),222 hirecontractspendingcancel: (parent, args, context, info) =>223 Hirecontract.find({ status: "HIRECONTRACT-PENDINGCANCEL" })224 .populate({225 path: "hirecontractCreatorId",226 populate: { path: "hirecontracts" },227 })228 .populate({229 path: "subcontractAcceptHirecontractId",230 populate: { path: "subcontracts" },231 }),232 hirecontractspendingcancel: (parent, args, context, info) =>233 Hirecontract.find({ status: "SUBCONTRACT-PENDINGCANCEL" })234 .populate({235 path: "hirecontractCreatorId",236 populate: { path: "hirecontracts" },237 })238 .populate({239 path: "subcontractAcceptHirecontractId",240 populate: { path: "subcontracts" },241 }),242 adminapprovehirecontractscancel: (parent, args, context, info) =>243 Hirecontract.find({ status: "CANCEL" })244 .populate({245 path: "hirecontractCreatorId",246 populate: { path: "hirecontracts" },247 })248 .populate({249 path: "subcontractAcceptHirecontractId",250 populate: { path: "subcontracts" },251 }),...

Full Screen

Full Screen

res_partner.py

Source:res_partner.py Github

copy

Full Screen

...106 [False, self.env.ref('base.main_company').id] + company_ids,107 [1, 1] + [1/(len(company_ids) or 1)]*len(company_ids))),108 ('parent_id', populate.constant(False)), # will be setted in _populate override109 ]110 def _populate(self, size):111 records = super()._populate(size)112 # set parent_ids113 self._populate_set_companies(records)114 return records115 def _populate_set_companies(self, records):116 _logger.info('Setting companies')117 r_company = populate.Random('res.partner+company_has_partners') # 50% change to have partners118 companies = records.filtered(lambda p: p.is_company and r_company.getrandbits(1))119 partners = records - companies120 r_partner = populate.Random('res.partner+partner_has_company')121 r_company_pick = populate.Random('res.partner+partner_company_pick=')122 companies_partners = collections.defaultdict(lambda: self.env['res.partner'])123 for count, partner in enumerate(partners):124 if bool(r_partner.getrandbits(1)): # 50% change to have a company125 companies_partners[r_company_pick.choice(companies)] |= partner...

Full Screen

Full Screen

lunch.py

Source:lunch.py Github

copy

Full Screen

1# -*- coding: utf-8 -*-2# Part of Odoo. See LICENSE file for full copyright and licensing details.3import logging4from dateutil.relativedelta import relativedelta5from itertools import groupby6from odoo import models7from odoo.tools import populate8_logger = logging.getLogger(__name__)9class LunchProductCategory(models.Model):10 _inherit = 'lunch.product.category'11 _populate_sizes = {'small': 5, 'medium': 150, 'large': 400}12 _populate_dependencies = ['res.company']13 def _populate_factories(self):14 # TODO topping_ids_{1,2,3}, toppping_label_{1,2,3}, topping_quantity{1,2,3}15 company_ids = self.env.registry.populated_models['res.company']16 return [17 ('name', populate.constant('lunch_product_category_{counter}')),18 ('company_id', populate.iterate(19 [False, self.env.ref('base.main_company').id] + company_ids,20 [1, 1] + [2/(len(company_ids) or 1)]*len(company_ids))),21 ]22class LunchProduct(models.Model):23 _inherit = 'lunch.product'24 _populate_sizes = {'small': 10, 'medium': 150, 'large': 10000}25 _populate_dependencies = ['lunch.product.category', 'lunch.supplier']26 def _populate_factories(self):27 category_ids = self.env.registry.populated_models['lunch.product.category']28 category_records = self.env['lunch.product.category'].browse(category_ids)29 category_by_company = {k: list(v) for k, v in groupby(category_records, key=lambda rec: rec['company_id'].id)}30 supplier_ids = self.env.registry.populated_models['lunch.supplier']31 company_by_supplier = {rec.id: rec.company_id.id for rec in self.env['lunch.supplier'].browse(supplier_ids)}32 def get_category(random=None, values=None, **kwargs):33 company_id = company_by_supplier[values['supplier_id']]34 return random.choice(category_by_company[company_id]).id35 return [36 ('active', populate.iterate([True, False], [0.9, 0.1])),37 ('name', populate.constant('lunch_product_{counter}')),38 ('price', populate.randfloat(0.1, 50)),39 ('supplier_id', populate.randomize(supplier_ids)),40 ('category_id', populate.compute(get_category)),41 ]42class LunchLocation(models.Model):43 _inherit = 'lunch.location'44 _populate_sizes = {'small': 3, 'medium': 50, 'large': 500}45 _populate_dependencies = ['res.company']46 def _populate_factories(self):47 company_ids = self.env.registry.populated_models['res.company']48 return [49 ('name', populate.constant('lunch_location_{counter}')),50 ('address', populate.constant('lunch_address_location_{counter}')),51 ('company_id', populate.randomize(company_ids))52 ]53class LunchSupplier(models.Model):54 _inherit = 'lunch.supplier'55 _populate_sizes = {'small': 3, 'medium': 50, 'large': 1500}56 _populate_dependencies = ['lunch.location', 'res.partner', 'res.users']57 def _populate_factories(self):58 location_ids = self.env.registry.populated_models['lunch.location']59 partner_ids = self.env.registry.populated_models['res.partner']60 user_ids = self.env.registry.populated_models['res.users']61 def get_location_ids(random=None, **kwargs):62 nb_locations = random.randint(0, len(location_ids))63 return [(6, 0, random.choices(location_ids, k=nb_locations))]64 return [65 ('active', populate.cartesian([True, False])),66 ('send_by', populate.cartesian(['phone', 'mail'])),67 ('delivery', populate.cartesian(['delivery', 'no_delivery'])),68 ('mon', populate.iterate([True, False], [0.9, 0.1])),69 ('tue', populate.iterate([True, False], [0.9, 0.1])),70 ('wed', populate.iterate([True, False], [0.9, 0.1])),71 ('thu', populate.iterate([True, False], [0.9, 0.1])),72 ('fri', populate.iterate([True, False], [0.9, 0.1])),73 ('sat', populate.iterate([False, True], [0.9, 0.1])),74 ('sun', populate.iterate([False, True], [0.9, 0.1])),75 ('available_location_ids', populate.iterate(76 [[], [(6, 0, location_ids)]],77 then=populate.compute(get_location_ids))),78 ('partner_id', populate.randomize(partner_ids)),79 ('responsible_id', populate.randomize(user_ids)),80 ('moment', populate.iterate(['am', 'pm'])),81 ('automatic_email_time', populate.randfloat(0, 12)),82 ]83class LunchOrder(models.Model):84 _inherit = 'lunch.order'85 _populate_sizes = {'small': 20, 'medium': 3000, 'large': 15000}86 _populate_dependencies = ['lunch.product', 'res.users', 'res.company']87 def _populate_factories(self):88 # TODO topping_ids_{1,2,3}, topping_label_{1,3}, topping_quantity_{1,3}89 user_ids = self.env.registry.populated_models['res.users']90 product_ids = self.env.registry.populated_models['lunch.product']91 company_ids = self.env.registry.populated_models['res.company']92 return [93 ('active', populate.cartesian([True, False])),94 ('state', populate.cartesian(['new', 'confirmed', 'ordered', 'cancelled'])),95 ('product_id', populate.randomize(product_ids)),96 ('user_id', populate.randomize(user_ids)),97 ('note', populate.constant('lunch_note_{counter}')),98 ('company_id', populate.randomize(company_ids)),99 ('quantity', populate.randint(0, 10)),100 ]101class LunchAlert(models.Model):102 _inherit = 'lunch.alert'103 _populate_sizes = {'small': 10, 'medium': 40, 'large': 150}104 _populate_dependencies = ['lunch.location']105 def _populate_factories(self):106 location_ids = self.env.registry.populated_models['lunch.location']107 def get_location_ids(random=None, **kwargs):108 nb_max = len(location_ids)109 start = random.randint(0, nb_max)110 end = random.randint(start, nb_max)111 return location_ids[start:end]112 return [113 ('active', populate.cartesian([True, False])),114 ('recipients', populate.cartesian(['everyone', 'last_week', 'last_month', 'last_year'])),115 ('mode', populate.iterate(['alert', 'chat'])),116 ('mon', populate.iterate([True, False], [0.9, 0.1])),117 ('tue', populate.iterate([True, False], [0.9, 0.1])),118 ('wed', populate.iterate([True, False], [0.9, 0.1])),119 ('thu', populate.iterate([True, False], [0.9, 0.1])),120 ('fri', populate.iterate([True, False], [0.9, 0.1])),121 ('sat', populate.iterate([False, True], [0.9, 0.1])),122 ('sun', populate.iterate([False, True], [0.9, 0.1])),123 ('name', populate.constant('alert_{counter}')),124 ('message', populate.constant('<strong>alert message {counter}</strong>')),125 ('notification_time', populate.randfloat(0, 12)),126 ('notification_moment', populate.iterate(['am', 'pm'])),127 ('until', populate.randdatetime(relative_before=relativedelta(years=-2), relative_after=relativedelta(years=2))),128 ('location_ids', populate.compute(get_location_ids))...

Full Screen

Full Screen

test_tag.py

Source:test_tag.py Github

copy

Full Screen

1# Copyright 2012-2016 Canonical Ltd. This software is licensed under the2# GNU Affero General Public License version 3 (see the file LICENSE).3"""Test maasserver models."""4from unittest.mock import ANY5from django.core.exceptions import ValidationError6from twisted.internet import reactor7from maasserver import populate_tags8from maasserver.models import tag as tag_module9from maasserver.models.tag import Tag10from maasserver.testing.factory import factory11from maasserver.testing.testcase import MAASServerTestCase12from maasserver.utils.threads import deferToDatabase13from maastesting.matchers import MockCalledOnceWith, MockNotCalled14class TagTest(MAASServerTestCase):15 def test_factory_make_Tag(self):16 """17 The generated system_id looks good.18 """19 tag = factory.make_Tag("tag-name", "//node[@id=display]")20 self.assertEqual("tag-name", tag.name)21 self.assertEqual("//node[@id=display]", tag.definition)22 self.assertEqual("", tag.comment)23 self.assertEqual(tag.kernel_opts, "")24 self.assertIsNot(None, tag.updated)25 self.assertIsNot(None, tag.created)26 def test_factory_make_Tag_with_hardware_details(self):27 tag = factory.make_Tag("a-tag", "true", kernel_opts="console=ttyS0")28 self.assertEqual("a-tag", tag.name)29 self.assertEqual("true", tag.definition)30 self.assertEqual("", tag.comment)31 self.assertEqual("console=ttyS0", tag.kernel_opts)32 self.assertIsNot(None, tag.updated)33 self.assertIsNot(None, tag.created)34 def test_add_tag_to_node(self):35 node = factory.make_Node()36 tag = factory.make_Tag()37 tag.save()38 node.tags.add(tag)39 self.assertEqual([tag.id], [t.id for t in node.tags.all()])40 self.assertEqual([node.id], [n.id for n in tag.node_set.all()])41 def test_valid_tag_names(self):42 for valid in ["valid-dash", "under_score", "long" * 50]:43 tag = factory.make_Tag(name=valid)44 self.assertEqual(valid, tag.name)45 def test_validate_traps_invalid_tag_name(self):46 for invalid in [47 "invalid:name",48 "no spaces",49 "no\ttabs",50 "no&ampersand",51 "no!shouting",52 "",53 "too-long" * 33,54 "\xb5",55 ]:56 self.assertRaises(ValidationError, factory.make_Tag, name=invalid)57 def test_validate_traps_invalid_tag_definitions(self):58 self.assertRaises(59 ValidationError, factory.make_Tag, definition="invalid::definition"60 )61 def test_applies_tags_to_nodes_on_save(self):62 populate_nodes = self.patch_autospec(Tag, "populate_nodes")63 tag = Tag(name=factory.make_name("tag"), definition="//node/child")64 self.assertThat(populate_nodes, MockNotCalled())65 tag.save()66 self.assertThat(populate_nodes, MockCalledOnceWith(tag))67 def test_will_not_save_invalid_xpath(self):68 tag = factory.make_Tag(definition="//node/foo")69 tag.definition = "invalid::tag"70 self.assertRaises(ValidationError, tag.save)71class TestTagIsDefined(MAASServerTestCase):72 """Tests for the `Tag.is_defined` property."""73 scenarios = (74 ("null", dict(definition=None, expected=False)),75 ("empty", dict(definition="", expected=False)),76 ("whitespace", dict(definition=" \t\n ", expected=False)),77 ("defined", dict(definition="//node", expected=True)),78 )79 def test_is_defined(self):80 tag = Tag(name="tag", definition=self.definition)81 self.assertIs(self.expected, tag.is_defined)82class TestTagPopulateNodesLater(MAASServerTestCase):83 def test_populates_if_tag_is_defined(self):84 post_commit_do = self.patch(tag_module, "post_commit_do")85 tag = Tag(name=factory.make_name("tag"), definition="//foo")86 tag.save(populate=False)87 self.assertTrue(tag.is_defined)88 self.assertThat(post_commit_do, MockNotCalled())89 tag._populate_nodes_later()90 self.assertThat(91 post_commit_do,92 MockCalledOnceWith(93 reactor.callLater,94 0,95 deferToDatabase,96 populate_tags.populate_tags,97 tag,98 ),99 )100 def test_does_nothing_if_tag_is_not_defined(self):101 post_commit_do = self.patch(tag_module, "post_commit_do")102 tag = Tag(name=factory.make_name("tag"), definition="")103 tag.save(populate=False)104 self.assertFalse(tag.is_defined)105 self.assertThat(post_commit_do, MockNotCalled())106 tag._populate_nodes_later()107 self.assertThat(post_commit_do, MockNotCalled())108 def test_does_not_clear_node_set_before_populating(self):109 post_commit_do = self.patch(tag_module, "post_commit_do")110 tag = Tag(name=factory.make_name("tag"), definition="//foo")111 tag.save(populate=False)112 nodes = [factory.make_Node() for _ in range(3)]113 tag.node_set.add(*nodes)114 tag._populate_nodes_later()115 self.assertItemsEqual(nodes, tag.node_set.all())116 self.assertThat(117 post_commit_do,118 MockCalledOnceWith(119 reactor.callLater,120 0,121 deferToDatabase,122 populate_tags.populate_tags,123 tag,124 ),125 )126 def test_later_is_the_default(self):127 tag = Tag(name=factory.make_name("tag"))128 self.patch(tag, "_populate_nodes_later")129 self.assertThat(tag._populate_nodes_later, MockNotCalled())130 tag.save()131 self.assertThat(tag._populate_nodes_later, MockCalledOnceWith())132class TestTagPopulateNodesNow(MAASServerTestCase):133 def test_populates_if_tag_is_defined(self):134 populate_multiple = self.patch_autospec(135 populate_tags, "populate_tag_for_multiple_nodes"136 )137 tag = Tag(name=factory.make_name("tag"), definition="//foo")138 tag.save(populate=False)139 self.assertTrue(tag.is_defined)140 self.assertThat(populate_multiple, MockNotCalled())141 tag._populate_nodes_now()142 self.assertThat(populate_multiple, MockCalledOnceWith(tag, ANY))143 def test_does_nothing_if_tag_is_not_defined(self):144 populate_multiple = self.patch_autospec(145 populate_tags, "populate_tag_for_multiple_nodes"146 )147 tag = Tag(name=factory.make_name("tag"), definition="")148 tag.save(populate=False)149 self.assertFalse(tag.is_defined)150 self.assertThat(populate_multiple, MockNotCalled())151 tag._populate_nodes_now()152 self.assertThat(populate_multiple, MockNotCalled())153 def test_clears_node_set_before_populating(self):154 tag = Tag(name=factory.make_name("tag"), definition="//foo")155 tag.save(populate=False)156 nodes = [factory.make_Node() for _ in range(3)]157 tag.node_set.add(*nodes)158 tag._populate_nodes_now()...

Full Screen

Full Screen

models.py

Source:models.py Github

copy

Full Screen

1# -*- coding: utf-8 -*-2# Part of Odoo. See LICENSE file for full copyright and licensing details.3from odoo import models, fields, api4from odoo.tools import populate, pycompat5class TestPopulateModel(models.Model):6 _name = 'test.populate'7 _description = 'Test Populate'8 name = fields.Char(default='Foo')9 state = fields.Selection([('a', 'A'), ('b', 'B')], default='a')10 active = fields.Boolean('Active', default=True)11 category_id = fields.Many2one('test.populate.category', 'Category')12 some_ref = fields.Integer('Reference')13 dependant_field_1 = fields.Char('Dependant 1')14 dependant_field_2 = fields.Char('Dependant 2')15 sequence = fields.Integer("Sequence")16 _populate_dependencies = ['test.populate.category']17 _populate_sizes = {18 'small': 20,19 'medium': 30,20 'large': 100,21 }22 def _populate_factories(self):23 # cross dependant field in a sub generator, cartesian product of two fields24 dependant_factories = [25 ('dependant_field_1', populate.cartesian(['d1_1', 'd1_2'])),26 ('dependant_field_2', populate.cartesian(['d2_1', 'd2_2', 'd2_3_{counter}'])),27 ]28 def generate_dependant(iterator, *args):29 dependants_generator = populate.chain_factories(dependant_factories, self._name)30 for dependant_values in dependants_generator:31 values = next(iterator)32 yield {**dependant_values, **values, '__complete': values['__complete'] and dependant_values['__complete']}33 def get_name(values=None, counter=0, **kwargs):34 active = 'active' if values['active'] else 'inactive'35 cat = 'filling' if values['__complete'] else 'corner'36 return '%s_%s_%s' % (active, cat, counter)37 category_ids = self.env.registry.populated_models['test.populate.category']38 return [39 ('active', populate.cartesian([True, False], [3, 1])),40 ('state', populate.cartesian([False] + self.env['test.populate']._fields['state'].get_values(self.env))),41 ('some_ref', populate.iterate([False, 1, 2, 3, 4])),42 ('_dependant', generate_dependant),43 ('name', populate.compute(get_name)),44 ('category_id', populate.randomize([False] + category_ids)),45 ('sequence', populate.randint(1, 10))46 ]47class TestPopulateDependencyModel(models.Model):48 _name = 'test.populate.category'49 _description = 'Test Populate Category'50 _populate_sizes = {51 'small': 3,52 'medium': 10,53 'large': 20,54 }55 name = fields.Char('Name', required=True, default='Cat1')56 active = fields.Boolean('Active', default=True)57 def _populate_factories(self):58 return [59 ('active', populate.cartesian([True, False], [9, 1])),60 ('name', populate.cartesian(['Cat1', 'Cat2', 'Cat3'])),61 ]62class TestNoPopulateModelInherit(models.Model):63 _name = 'test.populate.inherit'64 _inherit = 'test.populate'65 _description = 'Test populate inherit'66 additionnal_field = fields.Char(required=True)67 def _populate_factories(self):68 return super()._populate_factories() + [69 ('additionnal_field', populate.iterate(['V1', 'V2', 'V3'])),70 ]71class TestNoPopulateModel(models.Model):72 _name = 'test.no.populate'73 _description = 'A model with no populate method and a required field, should not crash'...

Full Screen

Full Screen

activityRepository.ts

Source:activityRepository.ts Github

copy

Full Screen

...24 * @returns25 */26 public static findActivityByIdWithPopulateAndVirtuals(id: string) {27 return Activity.findById(id)28 .populate('type')29 .populate('typeAgreement')30 .populate({31 path: 'crop',32 populate: [33 { path: 'cropType' },34 { path: 'unitType' },35 { path: 'company' },36 { path: 'owner' }37 ]38 })39 .populate('lots')40 .populate({41 path: 'lotsWithSurface',42 populate: [{ path: 'lot' }]43 })44 .populate('lotsMade')45 .populate('files')46 .populate({47 path: 'achievements',48 populate: [49 { path: 'lots' },50 {51 path: 'lotsWithSurface',52 populate: [{ path: 'lot' }]53 },54 { path: 'files' },55 {56 path: 'supplies',57 populate: [{ path: 'typeId' }, { path: 'supply' }]58 }59 ]60 })61 .populate('approvalRegister')62 .populate('user')63 .populate({64 path: 'supplies',65 populate: [{ path: 'typeId' }, { path: 'supply' }]66 })67 .populate('subTypeActivity')68 .lean({ virtuals: true })69 }70 /**71 *72 * @param string lotId73 *74 * @returns75 */76 public static findById(lotId: string) {77 return Activity.findById(lotId)78 }79 /**80 * Get all Activities filter by type activity.81 *82 * @param TypeActivity type83 */84 public static async getActivitiesFilterByName(name: NameActivity) {85 const activities = await Activity.find({ name: name })86 .populate('type')87 .populate({88 path: 'achievements',89 populate: [{ path: 'supplies.supply' }]90 })91 .lean({ virtuals: true })92 return !!activities ? activities : null93 }94 /**95 * Find All Activities.96 *97 * @param Generic query98 * @param Generic populate99 *100 * @returns101 */102 public static async findAll<T>(query: T, populate?: T) {103 return Activity.find(query).populate(populate ?? [])104 }105 /**106 * Get Activities.107 *108 * @returns109 */110 public static async getActivities({111 query,112 limit,113 skip,114 sort,115 populate116 }: any): Promise<any> {117 return Activity.find(query ?? {})118 .populate(populate ?? [])119 .limit(limit ?? 0)120 .skip(skip ?? 0)121 .sort(sort ?? {})122 }123 /**124 * Update Activity.125 *126 * @param update127 * @param string id128 */129 static async updateActivity<T>(update: T, id: string) {130 return Activity.updateOne({ _id: id }, { $set: update })131 }132 /**...

Full Screen

Full Screen

PopulateDBRoute.py

Source:PopulateDBRoute.py Github

copy

Full Screen

1from flask import Blueprint2from ..system_functions import populate_database3populate_db = Blueprint("populate_db", __name__)4@populate_db.route('/populate_users')5def populate_users():6 populate_database.populateUsers()7 return "check user's table in db"8@populate_db.route('/populate_units')9def populate_units():10 populate_database.populateUnits()11 return "check units table in db"12@populate_db.route('/populate_recipes')13def populate_recipes():14 populate_database.populateRecipes()...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1var wptools = require('wptools');2var page = wptools.page('Barack Obama');3page.populate(function(err, resp) {4 if (err) { console.log(err); }5 console.log(resp);6});7var wptools = require('wptools');8var page = wptools.page('Barack Obama');9page.get(function(err, resp) {10 if (err) { console.log(err); }11 console.log(resp);12});13var wptools = require('wptools');14var page = wptools.page('Barack Obama');15page.get(function(err, resp) {16 if (err) { console.log(err); }17 console.log(resp);18});19var wptools = require('wptools');20var page = wptools.page('Barack Obama');21page.get(function(err, resp) {22 if (err) { console.log(err); }23 console.log(resp);24});25var wptools = require('wptools');26var page = wptools.page('Barack Obama');27page.get(function(err, resp) {28 if (err) { console.log(err); }29 console.log(resp);30});31var wptools = require('wptools');32var page = wptools.page('Barack Obama');33page.get(function(err, resp) {34 if (err) { console.log(err); }35 console.log(resp);36});37var wptools = require('wptools');38var page = wptools.page('Barack Obama');39page.get(function(err, resp) {40 if (err) { console.log(err); }41 console.log(resp);42});43var wptools = require('wptools');44var page = wptools.page('Barack Obama');45page.get(function(err, resp) {46 if (err) { console.log(err); }

Full Screen

Using AI Code Generation

copy

Full Screen

1var wptoolkit = require('wptoolkit');2wptoolkit.populate('test', function (err, result) {3 if (err) {4 console.log(err);5 }6 else {7 console.log(result);8 }9});10var wptoolkit = require('wptoolkit');11wptoolkit.populate('test', function (err, result) {12 if (err) {13 console.log(err);14 }15 else {16 console.log(result);17 }18});19var wptoolkit = require('wptoolkit');20wptoolkit.populate('test', function (err, result) {21 if (err) {22 console.log(err);23 }24 else {25 console.log(result);26 }27});28var wptoolkit = require('wptoolkit');29wptoolkit.populate('test', function (err, result) {30 if (err) {31 console.log(err);32 }33 else {34 console.log(result);35 }36});37var wptoolkit = require('wptoolkit');38wptoolkit.populate('test', function (err, result) {39 if (err) {40 console.log(err);41 }42 else {43 console.log(result);44 }45});46var wptoolkit = require('wptoolkit');47wptoolkit.populate('test', function (err, result) {48 if (err) {49 console.log(err);50 }51 else {52 console.log(result);53 }54});55var wptoolkit = require('wptoolkit');56wptoolkit.populate('test', function (err, result) {57 if (err) {58 console.log(err);59 }60 else {61 console.log(result);62 }63});

Full Screen

Using AI Code Generation

copy

Full Screen

1var wptools = require('wptools');2var wiki = new wptools('Albert Einstein');3wiki.populate(function(err, resp) {4 console.log(resp.data);5});6var wptools = require('wptools');7var wiki = new wptools('Albert Einstein');8wiki.get(function(err, resp) {9 console.log(resp.data);10});11var wptools = require('wptools');12var wiki = new wptools('Albert Einstein');13wiki.get({info: 1, lang: 'es', format: 'json'}, function(err, resp) {14 console.log(resp.data);15});16var wptools = require('wptools');17var wiki = new wptools('Albert Einstein');18wiki.get({info: 1, lang: 'es', format: 'json'}, function(err, resp) {19 console.log(resp.data);20});21var wptools = require('wptools');22var wiki = new wptools('Albert Einstein');23wiki.get({info: 1, lang: 'es', format: 'json'}, function(err, resp) {24 console.log(resp.data);25});26var wptools = require('wptools');27var wiki = new wptools('Albert Einstein');28wiki.get({info: 1, lang: 'es', format: 'json'}, function(err, resp) {29 console.log(resp.data);30});31var wptools = require('wptools');32var wiki = new wptools('Albert Einstein');33wiki.get({info: 1, lang: 'es', format: 'json'}, function(err, resp) {34 console.log(resp.data);35});36var wptools = require('wptools');37var wiki = new wptools('Albert Einstein');38wiki.get({info:

Full Screen

Using AI Code Generation

copy

Full Screen

1var wptools = require('wptools');2var page = wptools.page('Barack Obama');3page.populate(function(err, resp) {4 console.log(resp);5});6var wptools = require('wptools');7var page = wptools.page('Barack Obama');8page.get(function(err, resp) {9 console.log(resp);10});11var wptools = require('wptools');12var page = wptools.page('Barack Obama');13page.get(function(err, resp) {14 console.log(resp);15});16var wptools = require('wptools');17var page = wptools.page('Barack Obama');18page.get(function(err, resp) {19 console.log(resp);20});21var wptools = require('wptools');22var page = wptools.page('Barack Obama');23page.get(function(err, resp) {24 console.log(resp);25});26var wptools = require('wptools');27var page = wptools.page('Barack Obama');28page.get(function(err, resp) {29 console.log(resp);30});31var wptools = require('wptools');32var page = wptools.page('Barack Obama');33page.get(function(err, resp) {34 console.log(resp);35});36var wptools = require('wptools');37var page = wptools.page('Barack Obama');38page.get(function(err, resp) {39 console.log(resp);40});

Full Screen

Using AI Code Generation

copy

Full Screen

1var wptool = require('wptool');2var wp = new wptool();3wp.populate(function(err, result) {4 console.log(result);5});6{ '0': 'wp-admin',

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