How to access arrays using bracket notation in Nuxt 3? - vuejs3

In Nuxt 2 using composition api I could use:
setup(props) {
const vm = getCurrentInstance().proxy
const selectedFeatures = ref([])
const selectedGames = ref([])
const selectedTVChannels = ref([])
const filtered = computed(() => {
const filterArray = [
{selected: "selectedFeatures", dbField: "features"},
{selected: "selectedGames", dbField: "games"},
{selected: "selectedTVChannels", dbField: "tvChannels"}
]
for (let i = 0; i < filterArray.length; i++) {
if (vm[filterArray[i].selected].length > 0) {
temp = temp.filter(item => {
if (item.hasOwnProperty(filterArray[i].dbField)) {
let t = 0
for (let j = 0; j < vm[filterArray[i].selected].length; j++) {
for (let k = 0; k < item[filterArray[i].dbField].length; k++) {
if (item[filterArray[i].dbField][k] === vm[filterArray[i].selected][j]) t++
}
}
if (t === vm[filterArray[i].selected].length) return true
}
})
}
}
})
I am trying to get this code to work inside <script setup> in Nuxt 3. But I can not work out a way to access arrays by bracket notation in this configuration. How can I achieve this?

I've tried to find refs values through vm but they're really empty.
I wonder what stops you from using
const arrays = reactive({
selectedFeatures: [],
selectedGames:[],
selectedTVChannels:[],
})
so you could access them with bracket notation
arrays[filterArray[i].selected]

Related

How do you update a component again straight after an update in react

So i'm trying to make a bar turn green then afterwards go back to its original color of black but it seems like it takes the later line as what it updates.
const [color, setColor] = useState("black")
const bubbleSort = async () => {
const sleep = ms => new Promise(res => setTimeout(res, ms));
let len = arr.length;
for (let i = 0; i < len; i++) {
for (let j = 0; j < len; j++) {
setCurrentIndex(j)
console.log(j)
console.log(currentIndex)
if (arr[j] > arr[j + 1]) {
setColor("green")
console.log(color)
document.getElementById(`bar${j + 1}`).style.backgroundColor = color
let tmp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = tmp;
setArr([...arr])
}
setColor("black")
await sleep(200)
}
}
This seems like it could be easily done with an useEffect hook.
something like this...
const FooComponent = () => {
const [color, setColor] = useState("black")
useEffect(()=> {
if(color === "green") {
setTimeout(function(){
setColor("black");
}, 3000);
}
}, [color, setColor])
return <div onClick={() => setColor("green")}> HI </div>
}
So the useEffect works like that. Every time color changes it will run that func.
In our example, when you click the div the color will be set to green and it will run the useEffect hook that will wait for 3 seconds and than set the color back to black,

Logic in if else statement to divide path if path shape is two or more '0'

Hi all trying to write some logic in paper.js (also using opentype.js for font data) so that when a number contains two or more consecutive zeros' the zero path is divided so that it is solid.
Things i know a zero path, using my particular font, is made up of an outer path with 19 segments and an inner path made up of 18 segments
So I thought would try to iterate over all paths check if a path has 19 segments and the next path has 18 segments and call path.unite() which kind of works. But I only want it to do this with consecutive '0' eg '100', '1000' but not 10.
So i was trying to do an if else statment where if-else (the current path has 18 segments and the next path is less than 18 segments) if true then do nothin or call path.divide()?
Im sure there is a way better way of doing this. Can you help please.
link to codepen
paper.install(window);
window.onload = () => {
paper.setup("canvas");
opentype.load(
"https://assets.codepen.io/1070/pphatton-ultralight-webfont.woff",
(err, font) => {
if (err) {
console.log(err);
} else {
const fontPath = font.getPath("10k", 0, 100, 100).toSVG();
const count = new paper.CompoundPath(fontPath);
count.unite();
count.children.forEach((child, i) => {
if (
child.segments.length === 19 &&
count.children[i + 1].segments.length === 18
) {
const eye = child.unite();
eye.selected = true;
} else if(
count.children[i + 1].segments.length === 18
&& child.segments.length < 18
) {
console.log('hello');
// const target = child.divide();
count.children[i].fillColor = 'black'
} else{
}
});
// const flatCount = count.children[1].unite()
// console.log(count.children[2].segments.length)
// const flatCountTwo = count.children[5].unite()
// flatCount.translate(5,0)
count.fillColor = "red";
project.activeLayer.fitBounds(view.bounds.scale(0.6));
}
}
);
};
I think that rather than using Font.getPath to retrieve a single svg path for the whole text, you should use Font.getPaths to retrieve an svg path for each character.
This way you can quite simply do your analysis on the input string directly and handle the consecutive 0 differently than other characters.
Edit
In order to detect the consecutive zeros, yes, you could use a regex or loop over the characters, like I did in the following example.
Here's a fiddle showcasing a possible solution.
const handleZero = (path) => {
path.children = path.children.slice(0, 1);
};
const getConsecutiveZerosIndices = (content) => {
const zero = '0';
return [...content]
.map((char, i) => ({ char, i }))
.filter(({ char, i }) => {
const previousCharacter = content?.[i - 1];
const nextCharacter = content?.[i + 1];
return char === zero && (previousCharacter === zero || nextCharacter === zero);
})
.map(({ i }) => i);
};
const drawText = (content, font) => {
const fontPaths = font.getPaths(content, 0, 100, 100);
const consecutiveZerosIndices = getConsecutiveZerosIndices(content);
const paths = fontPaths.map((fontPath, i) => {
const path = new paper.CompoundPath(fontPath.toSVG());
if (consecutiveZerosIndices.includes(i)) {
handleZero(path);
}
return path;
});
const group = new paper.Group(paths);
group.fillColor = 'red';
return group;
};
const draw = (font) => {
const path1 = drawText('10k', font);
const path2 = drawText('100k', font);
const path3 = drawText('1000k', font);
path2.position = path1.position.add(0, path1.bounds.height * 1.2);
path3.position = path2.position.add(0, path2.bounds.height * 1.2);
paper.project.activeLayer.fitBounds(paper.view.bounds.scale(0.6));
};
paper.setup('canvas');
opentype.load(
'https://assets.codepen.io/1070/pphatton-ultralight-webfont.woff',
(err, font) => draw(font)
);

Properly Reading Firebase data, using it, and Writing using React Native

I'm trying to utilize my Google firebase to hold data such a equipment details, work details, and work orders. The idea I had was to hold it all on firebase firestore. In react-native, I wanted to be able to use a separate function file to be able to access the data on firebase, then process it, and then write new information on the firestore. I'm having a bit of trouble temporarily saving the data in an array using the async function with push, and being able to regularly use that information for a variety of functions. The code below just results with too many promises exceptions. Is there a better way to write a script? Or, do you have a way to be able to simplify this?
import firestore from '#react-native-firebase/firestore';
class Worker {
constructor(name, certifications, shift, location) {
this.name = name;
this.certifications = certifications;
this.shift = shift;
this.location = location;
this.currentPosition = location;
this.timeLeftinShift = 8;
this.schedule = [];
this.doneScheduling = false;
}
}
class WorkOrder {
constructor(
eID,
eType,
facility,
location,
priority,
timeStamp,
timeToComplete,
) {
this.eID = eID;
this.eType = eType;
this.facility = facility;
this.location = location;
this.priority = priority;
this.timeStamp = timeStamp;
this.timeToComplete = timeToComplete;
this.done = false;
}
}
class Facility {
constructor(name, location, maxOcc) {
this.name = name;
this.location = location;
this.maxOcc = maxOcc;
this.curOcc = 0;
}
}
//assigns a worker
export function assignWorker() {
var tempWorkers = [];
async function workers() {
const workersCollection = await firestore()
.collection('workers')
.get()
.then(async (querySnapshot) => {
querySnapshot.forEach(async (documentSnapshot) => {
let temp = new Worker(
documentSnapshot.id,
documentSnapshot.data().Certifications,
documentSnapshot.data().Shift,
[
documentSnapshot.data().Location.longitude,
documentSnapshot.data().Location.latitude,
],
);
tempWorkers.push(temp);
});
});
return tempWorkers;
}
var tempFacilities = [];
async function Facilities() {
var tempFacilities = [];
const facilitiesCollection = await firestore()
.collection('facility')
.get()
.then(async (querySnapshot) => {
querySnapshot.forEach(async (documentSnapshot) => {
let temp = new Facility(
documentSnapshot.id,
[
documentSnapshot.data().Location.longitude,
documentSnapshot.data().Location.latitude,
],
documentSnapshot.data()['Max Occupancy'],
);
tempFacilities.push(temp);
});
});
return tempFacilities;
}
var tempWorkOrders = [];
async function workOrders() {
var tempWorkOrders = [];
const workOrdersCollection = await firestore()
.collection('sample work order')
.get()
.then(async (querySnapshot) => {
querySnapshot.forEach(async (documentSnapshot) => {
let temp = new WorkOrder(
documentSnapshot.data()['Equipment ID'],
documentSnapshot.data()['Equipment Type'],
documentSnapshot.data().Facility,
getFCoord(documentSnapshot.data().Facility, tempFacilities),
documentSnapshot.data()['Priority(1-5)'],
documentSnapshot.data()['Submission Timestamp'],
documentSnapshot.data()['Time to Complete'],
);
tempWorkOrders.push(temp);
});
});
return tempWorkOrders;
}
// final part
console.log('Reached Assigned Schedule');
workOrders().then((y) => {
workers().then((z) => {
assignSchedule(z, y);
for (let i = 0; i < z.length; ++i) {
firestore()
.collection('schedules')
.doc(tempWorkers[i].name)
.set({
schedule: tempWorkers[i].schedule,
})
.then(() => {});
}
});
});
console.log('Reached Assigned Schedule');
function getFCoord(inFacility) {
Facilities().then((x) => {
for (let i = 0; i < x.length; ++i) {
if (inFacility === x[i].name) {
// //console.log(
// // 'fCoord lat: ',
// // x[i].location[0],
// // ', fCoord long: ',
// x[i].location[1],
// );
return [x[i].location[0], x[i].location[1]];
}
}
});
}
// if a task is completed, we remove the work order
// if a task isn't completed by shift end, we subtract the time spent on the task and change the work order to reflect that
// two points (long, lat) distance function
function distBetweenTwoGeoPoints(lat, long, lat2, long2) {
const earthRadius = 6371;
let deltaPhi = ((lat2 - lat) * Math.PI) / 180;
let deltaLambda = ((long2 - long) * Math.PI) / 180;
let phi1 = (lat * Math.PI) / 180;
let phi2 = (lat2 * Math.PI) / 180;
let a =
Math.sin(deltaPhi / 2) ** 2 +
Math.cos(phi1) * Math.cos(phi2) * Math.sin(deltaLambda / 2) ** 2;
let c = 2 * Math.atan(Math.sqrt(a), Math.sqrt(1 - a));
return earthRadius * c;
}
// initial schedule for the day will come from all work orders that haven't been completed before their shift
//based upon technician certification we'd filter the work orders applicable
// letiables for optimization
// probability of failure
// location distance
// priority
// function -> ()
//filter each task by worker which can complete them
//for each worker, filter tasks that they can complete
// urgency score will be function of priority and time since task has been requested
// real time will be time takes to complete + travel time
// multiplier will be a function of how long a task will take and how much time is left in that person's shift
function score(workorder) {
//return workorder.priority * timeSinceRequest(workorder.timeStamp);
return workorder.priority;
}
function listOfTasksPerWorker() {
workOrders().then((Workers) => {
workers().then((workorders) => {
let numWorkers = Workers.length;
let numTasks = workorders.length;
let possibleTasks = [];
for (let i = 0; i < numWorkers; ++i) {
let taskList = [];
for (let j = 0; j < numTasks; ++j) {
//console.log("equipment " + workorders[j].eType);
for (let k = 0; k < workers[i].certifications.length; ++k) {
//console.log("certif " + workers[i].certifications[k]);
if (workorders[j].eType === workers[i].certifications[k]) {
//check certifications
taskList.push(workorders[j]);
}
}
}
possibleTasks.push(taskList);
}
return possibleTasks;
});
});
}
//given task will be apart of taskList
function removeTask(task, taskList) {
let newArr = [];
for (let i = 0; i < taskList.length; ++i) {
if (task.eID === taskList[i].eID) {
newArr = taskList.slice(i, i + 1);
return newArr;
}
}
}
// while workers have shift
// go through workorders
// terminates either when all the workers shifts are full or when there are no work orders
function assignSchedule() {
workOrders().then((Workers) => {
workers().then((workorders) => {
let numDone = 0;
while (numDone < Workers.length && workorders.length > 0) {
console.log('before choose workers');
chooseWorkers(Workers, workorders);
console.log('pass choose workers');
for (let i = 0; i < Workers.length; ++i) {
if (Workers[i].timeLeftinShift <= 0) {
++numDone;
}
}
}
});
});
}
//change time left in workshift
//change location of worker
//say task is assigned, and remove from workorder IF COMPLETED
function assignTask(worker, workorder) {
workOrders().then((workorders) => {
let taskTime =
workorder.timeToComplete +
timeToGetFacility(worker.location, workorder.location);
if (worker.timeLeftinShift < taskTime) {
worker.timeLeftinShift = 0;
workorder.timeToComplete =
worker.timeToComplete - worker.timeLeftinShift;
} else {
worker.timeLeftinShift = worker.timeLeftinShift - taskTime;
workorder.timeToComplete = 0;
workorders = removeTask(workorder, workorders);
}
worker.location = workorder.location;
worker.schedule.push(workorder);
console.log('assign task');
});
}
function chooseWorkers() {
workOrders().then((Workers) => {
workers().then((workorders) => {
for (let i = 0; i < Workers.length; ++i) {
let keep = true;
let bestTaskw1;
let bestTaskw2;
let worker1Tasks = listOfTasksPerWorker(Workers, workorders)[i];
console.log('tasks: ', worker1Tasks);
let schedule = oneSchedule(Workers[i], worker1Tasks);
if (!schedule[0].length) {
break;
} else {
bestTaskw1 = schedule[0][0];
}
console.log('pass schedule');
if (!Workers[i].doneScheduling) {
for (let j = i + 1; j < Workers.length; ++j) {
if (!Workers[j].doneScheduling) {
let worker2Tasks = listOfTasksPerWorker(Workers, workorders)[j];
let schedule2 = oneSchedule(Workers[j], worker2Tasks);
if (!schedule2[0].length) {
break;
} else {
bestTaskw2 = schedule[0][0];
if (bestTaskw1.eID === bestTaskw2.eID) {
let w1SecondSchedule = oneSchedule(
Workers[i],
removeTask(bestTaskw1, worker1Tasks),
);
let w2SecondSchedule = oneSchedule(
Workers[j],
removeTask(bestTaskw1, worker1Tasks),
);
if (
bestTaskw1[1] - w1SecondSchedule[1] <
bestTaskw2[1] - w2SecondSchedule[1]
) {
keep = false;
i = i - 1;
//fix next line
worker1Tasks = removeTask(bestTaskw1, worker1Tasks);
break;
}
}
}
}
}
if (keep) {
assignTask(Workers[i], bestTaskw1, workorders);
}
}
}
});
});
}
function timeToGetFacility(point1, point2) {
const avgSpdKm = 70;
let timeToGetThere =
distBetweenTwoGeoPoints(point1[0], point1[1], point2[0], point2[1]) /
avgSpdKm;
return timeToGetThere;
}
function oneSchedule(worker1, worker1Tasks) {
let time1 = worker1.timeLeftinShift;
let total1 = 0;
let tasks1 = [];
let tempLocation = worker1.location;
while (time1 > 0) {
let bestOrder;
let bestOrderInd;
let bestScorePerHour = 0;
let travelTime = 0;
let bestTravelTime = 0;
console.log('before for');
console.log(worker1Tasks.length.toString());
for (let i = 0; i < worker1Tasks.length; ++i) {
console.log('before if');
console.log('test: ', i, worker1Tasks.length);
if (!worker1Tasks[i].done) {
console.log('after if');
let tempScorePerHour = 0;
console.log('location: ', tempLocation[0], tempLocation[1]);
travelTime = timeToGetFacility(
tempLocation,
worker1Tasks[i].location,
);
console.log('travel time: ', travelTime);
if (time1 - (worker1Tasks[i].timeToComplete + travelTime) < 0) {
tempScorePerHour =
(score(worker1Tasks[i]) *
((time1 - travelTime) / worker1Tasks[i].timeToComplete)) /
time1;
} else {
tempScorePerHour =
score(worker1Tasks[i]) /
(worker1Tasks[i].timeToComplete + travelTime);
}
console.log('score: ', score(worker1Tasks[i]));
console.log('temp: ', tempScorePerHour);
if (tempScorePerHour > bestScorePerHour) {
bestScorePerHour = tempScorePerHour;
bestOrder = worker1Tasks[i];
bestOrderInd = i;
bestTravelTime = travelTime;
}
}
}
if (bestScorePerHour > 0) {
worker1Tasks.splice(bestOrderInd, 1);
//bestOrder.done = true;
tasks1.push(bestOrder);
console.log(bestOrder.eID);
console.log(bestScorePerHour);
if (time1 - (bestOrder.timeToComplete + bestTravelTime) < 0) {
total1 += bestScorePerHour * time1;
time1 = 0;
} else {
total1 += score(bestOrder);
time1 -= bestOrder.timeToComplete + bestTravelTime;
}
console.log(bestOrder.timeToComplete);
tempLocation = bestOrder.location;
} else {
break;
}
}
return [tasks1, total1];
}
}

Cannot read property 'unsubscribe' of undefined

i have a ionic project.
I want to unsubscribe when i get the cities from subscription of firebase return.
But something goes wrong and it throws following error when i try to unsubscribe.
How can is solve that?
My code.
getCities() {
let i: any;
let a = this.firebaseProvider.getOtoparks()
.subscribe(data => {
for (i = 0; i < data.length; i++) {
this.cities.push({
name: data[i]['details']['sehir'],
value: i,
}
);
}
// try to unsubscribe
a.unsubscribe();
});
}
The best practice is to use take(1) when you want to unsubscribe without a condition.
getCities() {
let i: any;
let a = this.firebaseProvider.getOtoparks()
.take(1)
.subscribe(data => {
for (i = 0; i < data.length; i++) {
this.cities.push({
name: data[i]['details']['sehir'],
value: i,
});
}
});
}

How to set results retried from sqlite db table to array in react native?

Here is my code
var employeeList = [] ;
let db = SQLite.openDatabase({name: 'test.db', createFromLocation : "~example.db", location: 'Library'}, false,false);
db.transaction((tx) => {
tx.executeSql('SELECT * FROM Employees', [], (tx, results) => {
console.log("Query completed");
var len = results.rows.length;
for (let i = 0; i < len; i++) {
let row = results.rows.item(i);
employeeList.push(row.name);
}
this.setState({employees:employeeList});
db.closeDatabase();
});
});
alert(this.state.employees);
I am able to set result to employeeList inside a transaction.But When I am checking employeeList outside the transaction,it is getting blank...
What I have to do to set results.row to employees object..
It's asynchronous. You're asking for a value before the DB transaction has been performed. You need to use promises or callbacks to know when the query has executed.
As Gabriel mentioned, you need to wrap the call in a Promise. I provided an example of how you might want to do it.
const getEmployees = new Promise(function(resolve, reject) {
var employeeList = [] ;
let db = SQLite.openDatabase({name: 'test.db', createFromLocation : "~example.db", location: 'Library'}, false,false);
db.transaction((tx) => {
tx.executeSql('SELECT * FROM Employees', [], (tx, results) => {
console.log("Query completed");
var len = results.rows.length;
for (let i = 0; i < len; i++) {
let row = results.rows.item(i);
employeeList.push(row.name);
}
db.closeDatabase();
// resolve promise
resolve(employeeList)
});
});
getEmployees.then(data => {
this.setState({
employees:employeeList
})
})

Resources