addSentence: (state) => {
const obj = state;
// next line is correct;
obj.sentences.push({ ...obj.current });
// change to next line, get error
// obj.sentences.push(obj.current);
obj.current = new Sentence();
},
import Constants from './Constants';
export default class Sentence {
constructor(config) {
this.text = '';
this.fontFamily = 'KaiTi';
this.fontSize = 16;
this.fontStyle = '';
this.appearStyle = {
name: 'type',
speed: 40,
startDelay: 0,
};
this.disappearStyle = {
name: 'backspace',
speed: 80,
startDelay: 0,
smartBackspace: true,
};
}
play(context) {
}
drawText() {
}
}
state.cuurent is an object of type Sentence.
And state.sentences = [Sentence]
This is a mutation handler.
Error:
[vuex] Do not mutate vuex store state outside mutation handlers.
Related
I have this code:
circular = () => { //fix circular stuff for json.stringify
seen = new WeakSet();
return (key, value) => {
if (typeof value === 'object' && value !== null) {
if (seen.has(value)) {
return;
}
seen.add(value);
}
return value;
};
};
var gameon = 1;
var fighter1 = {"userid":"97","username":"john","items":{},"ailments":{}};
var fighter2 = {"userid":"91","username":"james","items":{},"ailments":{}};
var resume = 30;
all = {gameon:gameon,fighter1:fighter1,fighter2:fighter2,resume:resume,inturn:fighter1,outturn:fighter2};
fs.writeFileSync(file,JSON.stringify(all,circular()),{encoding:'utf8',flag:'w'});
I expect to have the next output written to file:
{
"gameon":1,
"fighter1":{
"userid":"97",
"username":"john",
"items": {},
"ailments":{}
},
"fighter2":{
"userid":"91",
"username":"james",
"items":{},
"ailments":{}
},
"resume":"",
"inturn":{
"userid":"97",
"username":"john",
"items":{},
"ailments":{}
},
"outturn":{
"userid":"91",
"username":"james",
"items":{},
"ailments":{}
}
but this is what I get instead:
{
"gameon":1,
"fighter1":{
"userid":"97",
"username":"john",
"items":{},
"ailments":{}
},
"fighter2":{
"userid":"91",
"username":"james",
"items":{},
"ailments":{}
},
"resume":""
}
Please notice how the string truncates after "resume" like it couldn't read the variables fighter1 and fighter2 despite it could do it for the first iteration.
Why is that?
Thank you.
Basically what I need is generate one single file that contain all vendors and dependencies for each entry..
export default defineConfig({
plugins: [ react() ],
build: {
rollupOptions: {
input: {
popup: path.resolve(pagesDirectory, 'popup', 'index.html'),
background: path.resolve(pagesDirectory, 'background', 'index.ts'),
content_script: path.resolve(pagesDirectory, 'content_script', 'ContentScript.tsx')
},
output: {
entryFileNames: 'src/pages/[name]/index.js',
chunkFileNames: isDevelopment ? 'assets/js/[name].js' : 'assets/js/[name].[hash].js',
assetFileNames: (assetInfo) => {
const { dir, name: _name } = path.parse(assetInfo.name);
const assetFolder = getLastElement(dir.split('/'));
const name = assetFolder + firstUpperCase(_name);
return `assets/[ext]/${name}.chunk.[ext]`;
}
}
}
}})
In this case.. will be one file for popup, background and content_script
Here is one example of ContentScript.tsx file...
import * as React from 'react';
import { createRoot } from 'react-dom/client';
import Badge from './badge';
function init(query: string) {
const appContainer = document.querySelector('#search') as HTMLElement;
if (!appContainer) {
throw new Error('Can not find AppContainer');
}
const rootElement = document.createElement('div');
rootElement.setAttribute('id', 'web-answer-content-script');
appContainer.insertBefore(rootElement, appContainer.firstChild);
const root = createRoot(rootElement, {});
root.render(
<React.StrictMode>
<Badge query={query} />
</React.StrictMode>
);
}
const searchParameters = new URLSearchParams(window.location.search);
if (searchParameters.has('q')) {
const query = searchParameters.get('q');
init(query);
}
import MessageSender = chrome.runtime.MessageSender;
function handleMessageReceived(message: string, sender: MessageSender) {
console.log('>>> MESSAGE RECEIVED', message, sender);
}
chrome.runtime.onMessage.addListener(handleMessageReceived);
With this configuration I'm getting this..
and my content_scripts/index.js ..
import { j as n, c as a, r as c } from '../../../assets/jsx-dev-runtime.a077470a.js';
// ..rest of the code...
As you can see.. I don't want this import... statement ..
I'm trying to retrieve data from MondoDB and print result to console.
The data are not visualized and the script does not return.
where is the problem?
Thanks.
import * as mongoProxy from "mongodb";
import { exists } from "fs";
namespace code {
interface ICountry{
TestIField1: string;
TestIField266A3: string;
}
interface IProjection{
projection: {"TestIField1": number, "TestIField2": number}
};
interface IFilter {
filter: {
"this_is_valid": {$ne: boolean}
}
};
class CreateMembers {
private mongo_username = "mongo_credentials";
private mongo_password = "mongo_credentials";
private mongo_db = "DB_NAME";
private mongo_host ="mongo_host:27017";
private mongo_replica_set = "mongodev";
private mongo_url = `mongodb://${this.mongo_username}:${this.mongo_password}#${this.mongo_host}/${this.mongo_db}?replicaSet=${this.mongo_replica_set}`;
private env = "development";
private async getDataFromDb(collectionName: string, filter: IFilter, projection:IProjection) {
console.log("Connecting...");
const dbConn = await mongoProxy.connect(this.mongo_url);
const db = dbConn.db(this.mongo_db);
if (dbConn.isConnected()) {
console.log("Connected!");
const mongoResult=db.collection(collectionName).find<ICountry>(
{"this_is_valid":{ $ne: true }},
{projection: {"TestIField1": 1, "TestIField2": 1}}
);
mongoResult.map((r)=>{
console.log(`DEBUG-->: ${r}`);
});
console.log("Data retrieved... returning to run.");
return mongoResult;
}
else{console.log("CONNECTON FAILED!");
}
}
public async run(){
console.log("RUN1");
const projection : IProjection = {projection: {"TestIField1": 1, "TestIField2": 1}};
const filter : IFilter = {filter: {"this_is_valid": {$ne: true}}};
const collectionName="country";
// const filter={"this_is_valid":{ $ne: true }};
// const projection={projection: {"TestIField1": 1, "TestIField2": 1}};
let countryRecords=await this.getDataFromDb(collectionName, filter, projection);
console.log("RUN2");
if (countryRecords){
countryRecords.forEach((r)=>{
console.log(`DEBUG-->: ${r}`);
});
}
console.log("RUN3");
}
}
let myClass=new CreateMembers();
myClass.run();
}
The output on console:
RUN1
Connecting...
Connected!
Data retrieved... returning to run.
RUN2
RUN3
//here the script is still running; no return to the console.
.find return a promise so you should wait for it:
const mongoResult = await db.collection(collectionName).find<ICountry>(
{ "this_is_valid": { $ne: true } },
{ projection: { "TestIField1": 1, "TestIField2": 1 } }
).toArray();
And the script is still running because you need to close the mongo connection with:
dbConn.close()
I'm using Threejs for a project of mine, i render an Object file using OBJ loader and it displays the object on the screen. But I don't know how to map a SVG image to that object how to apply texture on that object file.
please help me this is my current code.
I'm new to this platform and don't know much about THREE.js i've seen some examples but it didn't worked out for me.
One person on my recent post told me how to apply material on the object but it didn't worked for me.
When i apply material i got this error.
ERROR TypeError: Cannot set property 'map' of undefined
Here is my complete code file.
import { Component, AfterViewInit, ViewChild, Input, ElementRef } from '#angular/core';
import * as THREE from 'three';
import { OrbitControls } from '#avatsaev/three-orbitcontrols-ts';
import {OBJLoader} from 'three-obj-mtl-loader';
import { TextureLoader } from 'three';
#Component({
selector: 'app-scene',
templateUrl: './scene.component.html',
styleUrls: ['./scene.component.css']
})
export class SceneComponent implements AfterViewInit {
#Input() name: string;
#ViewChild('canvas', {static:true}) canvasRef: ElementRef;
renderer = new THREE.WebGLRenderer;
scene = null;
camera = null;
controls = null;
mesh = null;
light = null;
loader;
svgLoader;
private calculateAspectRatio(): number {
const height = this.canvas.clientHeight;
if (height === 0) {
return 0;
}
return this.canvas.clientWidth / this.canvas.clientHeight;
}
private get canvas(): HTMLCanvasElement {
return this.canvasRef.nativeElement;
}
constructor() {
// this.loader = new OBJLoader();
this.scene = new THREE.Scene();
this.loader = new OBJLoader();
this.camera = new THREE.PerspectiveCamera(15, window.innerWidth / window.innerHeight, 0.1, 1000)
}
ngAfterViewInit() {
this.configScene();
this.configCamera();
this.configRenderer();
this.configControls();
this.createLight();
this.createMesh();
this.animate();
}
configScene() {
// this.scene.background = new THREE.Color( 0xdddddd );
}
configCamera() {
this.camera.aspect = this.calculateAspectRatio();
this.camera.updateProjectionMatrix();
this.camera.position.set( 0, 0, 3 );
this.camera.lookAt( this.scene.position );
}
configRenderer() {
this.renderer = new THREE.WebGLRenderer({
canvas: this.canvas,
antialias: true,
alpha: true
});
this.renderer.setPixelRatio(devicePixelRatio);
// setClearColor for transparent background
// i.e. scene or canvas background shows through
this.renderer.setClearColor( 0x000000, 0 );
this.renderer.setSize((window.innerWidth/2), (window.innerHeight/2));
window.addEventListener('resize', ()=>{
this.renderer.setSize((window.innerWidth/2), (window.innerHeight)/2);
this.camera.aspect = window.innerWidth / window.innerHeight;
this.camera.updateProjectionMatrix();
})
console.log('clientWidth', this.canvas.clientWidth);
console.log('clientHeight', this.canvas.clientHeight);
}
configControls() {
this.controls = new OrbitControls(this.camera);
this.controls.autoRotate = false;
this.controls.enableZoom = false;
// this.controls.maxDistance = 5;
// this.controls.minDistance = 10;
this.controls.enablePan = false;
this.controls.update();
}
createLight() {
this.light = new THREE.PointLight( 0xffffff );
this.light.position.set( -10, 10, 10 );
this.scene.add( this.light );
}
createMesh() {
const url ='../../../../assets/abc.svg';
this.loader.load('../../../../assets/nonunified.obj', (object)=>{
object.traverse( function ( child ) {
if ( child instanceof THREE.Mesh ) {
child.geometry.center();
}
} );
object.material.map = new TextureLoader().load(url)
this.scene.add(object)
},
// called when loading is in progresses
function (xhr) {
console.log( ( xhr.loaded / xhr.total * 100 ) + '% loaded' );
},
// called when loading has errors
function ( error ) {
console.log( 'An error happened' );
}
)}
animate() {
window.requestAnimationFrame(() => this.animate());
this.controls.update();
this.renderer.render(this.scene, this.camera);
}
}
You have not created a material. If you do console.log(object.material); it will show undefined. You first need to create a material. Please check the threejs doc for different materials that can be used. For this example I am using MeshPhongMaterial. So your createMesh function will look like this.
createMesh() {
const url = '../../../../assets/abc.svg';
this.loader.load('../../../../assets/nonunified.obj', (object) => {
object.traverse(function (child) {
if (child instanceof THREE.Mesh) {
child.geometry.center();
}
});
const material = new THREE.MeshPhongMaterial({
map: new TextureLoader().load(url)
});
object.material = material;
this.scene.add(object)
},
// called when loading is in progresses
function (xhr) {
console.log((xhr.loaded / xhr.total * 100) + '% loaded');
},
// called when loading has errors
function (error) {
console.log('An error happened');
}
)
}
This should work.
Im getting the following error when I try to use jqueru autocomplete together with require js:
'cannot call methods on autocomplete prior to initialization; attempted to call method '/recruiter/temp-search/api/locations/get''
I have a module which initilizes my autocomplete:
define(['jqueryUi'],function($) {
function Location() {
this.autocompleteUrl = "/recruiter/temp-search/api/locations/get";
};
Location.prototype.initAutocomplete = function($txtTown, onSuccessDelegate, countryId, regionId, ignoredInputHandler, includeCountries) {
///<param name="$txtTown" type="jQuery">input text element to decorate with autocomplete</param>
///<param name="onSuccessDelegate" type="function">Invoked with upon item selection with selected value passed as a parameter</param>
///<param name="regionId" type="int">Region constraint. Defaults to null</param>
///<param name="countryId" type="int">Country Id. Defaults to UK id</param>
///<param name="ignoredInputHandler" type="function">
/// function(string term, function success(string term, {data, result, value}[] data), function failure(string term)) delegate
/// that is invoked on autocomplete requests before user input at leaset 2 chars
///</param>
var cId = countryId ? countryId : null;
var rId = regionId ? regionId : null;
var inclCountries = includeCountries === undefined ? false : includeCountries;
var onSuccess = onSuccessDelegate ? onSuccessDelegate : function() {};
$txtTown.autocomplete(this.autocompleteUrl, {
dataType: 'json',
parse: function(data) {
/* validation Location*/
/*To remove error field check on the parentsearch.js self.elements.searchLocation.on('keyup'*/
if ($txtTown.selector === "#Location") {
if (data.Locations.length == 0 && !data.IsPostcode && $txtTown.val().length > 0) {
var locationError = "We couldn't find the location you entered";
jQuery("[data-valmsg-for = 'Location']").text(locationError);
$('#Location').closest('.search-row').find('.search-error').show();
} else {
jQuery("[data-valmsg-for = 'Location']").text("");
}
}
/**/
var rows = [];
if ($.isArray(data.Locations)) {
var locations = data.Locations;
if (locations !== null) {
for (var i = 0; i < locations.length; i++) {
rows[i] = { data: locations[i], value: locations[i], result: locations[i] };
}
}
} else {
if (data.IsPostcode) {
onSuccess(data.Location, data.Postcode);
}
}
return rows;
},
extraParams: { countryId: cId, regionId: rId, includeCountries: inclCountries },
formatItem: function(row) { return row; },
width: 'auto',
minChars: 2,
delay: 100,
max: 10,
ignoredInputHandler: ignoredInputHandler,
selectFirst: false,
cacheLength: 1,
scroll: false
}).result(function(event, row) {
onSuccess(row);
});
};
return new Location();
});
It is being called like this:
location.initAutocomplete(this.elements.searchLocation, onSuccessAutocomplete, undefined, undefined, undefined, true);
here is my config file:
require.config({
paths: {
"JqueryAutocomplete": "../scripts/jquery/plugins/jquery.autocomplete",
"jqueryValidate": "../scripts/jquery/plugins/jquery.validate",
"jqueryUi": "../scripts/jquery/plugins/jquery-ui-1.10.3.custom",
"jquery": "../scripts/jquery/jquery-1.9.1",
"knockout": "../scripts/knockout/knockout-2.3.0",
"ko": "common/knockout-extensions"
},
shim: {
"JqueryAutocomplete": {
exports: "$",
deps: ['jquery']
},
"jqueryValidate": {
exports: "$",
deps: ['jquery']
},
"jqueryUi": {
exports: "$",
deps: ['jquery']
},
"knockout-extensions": {
exports: "knockout",
deps: ['knockout']
}
}
});