content
stringlengths
86
88.9k
title
stringlengths
0
150
question
stringlengths
1
35.8k
answers
list
answers_scores
list
non_answers
list
non_answers_scores
list
tags
list
name
stringlengths
30
130
Q: How do I substract/add currency to balance with quick.db? The bot says that I robbed someone but does not add/substract the currency from neither of the users. Another issue I found is that I can rob myself. Code I used: const Discord = require("discord.js"); const db = require("quick.db"); const ms = require("parse-ms"); module.exports.run = async (bot, message, args) => { if(!message.content.startsWith('db!'))return; let user = message.mentions.members.first() let targetuser = await db.fetch(`money_${message.guild.id}_${user.id}`) let author = await db.fetch(`rob_${message.guild.id}_${user.id}`) let author2 = await db.fetch(`money_${message.guild.id}_${user.id}`) let timeout = 600000; if (author !== null && timeout - (Date.now() - author) > 0) { let time = ms(timeout - (Date.now() - author)); let timeEmbed = new Discord.RichEmbed() .setColor("#FFFFFF") .setDescription(`❌ You have already robbed someone\n\nTry again in ${time.minutes}m ${time.seconds}s `); message.channel.send(timeEmbed) } else { let moneyEmbed = new Discord.RichEmbed() .setColor("#FFFFFF") .setDescription(`❌ You need atleast 200 dabloons in your wallet to rob someone`); if (author2 < 200) { return message.channel.send(moneyEmbed) } let moneyEmbed2 = new Discord.RichEmbed() .setColor("#FFFFFF") .setDescription(`❌ ${user.user.username} does not have anything you can rob`); if (targetuser < 0) { return message.channel.send(moneyEmbed2) } let vip = await db.fetch(`bronze_${user.id}`) if(vip === true) random = Math.floor(Math.random() * 200) + 1; if (vip === null) random = Math.floor(Math.random() * 100) + 1; let embed = new Discord.RichEmbed() .setDescription(`✔️ You robbed ${user} and got away with ${random} dabloons!`) .setColor("#FFFFFF") message.channel.send(embed) db.subtract(`money_${message.guild.id}_${user.id}`, random) db.add(`money_${message.guild.id}_${user.id}`, random) db.set(`rob_${message.guild.id}_${user.id}`, Date.now()) }; } module.exports.help = { name:"rob", aliases: [""] } I tried using code from other people, but the code I used did not work and just broke the bot A: To solve the db issue, you can see Elitezen's comment To solve the issue where you can rob yourself, you can simply check if the person getting robbed is the author of the message if(message.mentions.members.first().id === message.member.id) return message.channel.send(errorEmbed) Also, this is a super outdated version of discord.js and is highly recommended to update.
How do I substract/add currency to balance with quick.db?
The bot says that I robbed someone but does not add/substract the currency from neither of the users. Another issue I found is that I can rob myself. Code I used: const Discord = require("discord.js"); const db = require("quick.db"); const ms = require("parse-ms"); module.exports.run = async (bot, message, args) => { if(!message.content.startsWith('db!'))return; let user = message.mentions.members.first() let targetuser = await db.fetch(`money_${message.guild.id}_${user.id}`) let author = await db.fetch(`rob_${message.guild.id}_${user.id}`) let author2 = await db.fetch(`money_${message.guild.id}_${user.id}`) let timeout = 600000; if (author !== null && timeout - (Date.now() - author) > 0) { let time = ms(timeout - (Date.now() - author)); let timeEmbed = new Discord.RichEmbed() .setColor("#FFFFFF") .setDescription(`❌ You have already robbed someone\n\nTry again in ${time.minutes}m ${time.seconds}s `); message.channel.send(timeEmbed) } else { let moneyEmbed = new Discord.RichEmbed() .setColor("#FFFFFF") .setDescription(`❌ You need atleast 200 dabloons in your wallet to rob someone`); if (author2 < 200) { return message.channel.send(moneyEmbed) } let moneyEmbed2 = new Discord.RichEmbed() .setColor("#FFFFFF") .setDescription(`❌ ${user.user.username} does not have anything you can rob`); if (targetuser < 0) { return message.channel.send(moneyEmbed2) } let vip = await db.fetch(`bronze_${user.id}`) if(vip === true) random = Math.floor(Math.random() * 200) + 1; if (vip === null) random = Math.floor(Math.random() * 100) + 1; let embed = new Discord.RichEmbed() .setDescription(`✔️ You robbed ${user} and got away with ${random} dabloons!`) .setColor("#FFFFFF") message.channel.send(embed) db.subtract(`money_${message.guild.id}_${user.id}`, random) db.add(`money_${message.guild.id}_${user.id}`, random) db.set(`rob_${message.guild.id}_${user.id}`, Date.now()) }; } module.exports.help = { name:"rob", aliases: [""] } I tried using code from other people, but the code I used did not work and just broke the bot
[ "To solve the db issue, you can see Elitezen's comment\nTo solve the issue where you can rob yourself,\nyou can simply check if the person getting robbed is the author of the message\nif(message.mentions.members.first().id === message.member.id) return message.channel.send(errorEmbed)\nAlso, this is a super outdated version of discord.js and is highly recommended to update.\n" ]
[ 0 ]
[]
[]
[ "discord.js" ]
stackoverflow_0074647316_discord.js.txt
Q: Can a variable be associated to two different names? Working in Google AppsScript, specifically for an add-on, and I'm defining the SHEET_NAME as a const. Specifically: const SHEET_NAME="Values" Since Google Sheets has a default name of "Sheet1" for all worksheets can I also make SHEET_NAME be associated to either "Values" or "Sheet1"? Basically, if someone doesn't choose to name their file "Values" then the variable will still know to run SHEET_NAME without breaking. Right now I have a function that is trying to use the SHEET_NAME variable, but again, trying to see if I can have it look for either "Values" or "Sheet1" Is something like const SHEET_NAME="Values" OR "Sheet1" doable? A: You could just check if the SpreadsheetApp.getActiveSpreadsheet().getSheetByName() returns not null. If so you assign value: const sheet1 = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet1") const SHEET_NAME = sheet1 ? "Sheet1" : "Value" But in my country it is Blad1 instead of Sheet1 so i suggest rethink you're logic. I would suggest something like this: const ss = SpreadsheetApp.getActiveSpreadsheet() let SHEET const sheetCheck = ss.getSheetByName("TheSheetName") if(sheetCheck){ //Assign the founded sheet to the variable SHEET SHEET = sheetCheck } else { //Create the sheet and assign to SHEET SHEET = ss.insertSheet("TheSheetName") } //Do something with SHEET A: You can get the active like this: const sheet = SpreadsheetApp.getActiveSheet(); This way, there is no need to meddle with sheet names. If you need the sheet name for some reason, you can get it like this: const sheetName = sheet.getName(); When there are multiple tabs in the spreadsheet, you can get the sheet that shows first in the tab bar like this: const sheet = SpreadsheetApp.getActive().getSheets()[0];
Can a variable be associated to two different names?
Working in Google AppsScript, specifically for an add-on, and I'm defining the SHEET_NAME as a const. Specifically: const SHEET_NAME="Values" Since Google Sheets has a default name of "Sheet1" for all worksheets can I also make SHEET_NAME be associated to either "Values" or "Sheet1"? Basically, if someone doesn't choose to name their file "Values" then the variable will still know to run SHEET_NAME without breaking. Right now I have a function that is trying to use the SHEET_NAME variable, but again, trying to see if I can have it look for either "Values" or "Sheet1" Is something like const SHEET_NAME="Values" OR "Sheet1" doable?
[ "You could just check if the SpreadsheetApp.getActiveSpreadsheet().getSheetByName() returns not null. If so you assign value:\nconst sheet1 = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(\"Sheet1\")\nconst SHEET_NAME = sheet1 ? \"Sheet1\" : \"Value\"\n\nBut in my country it is Blad1 instead of Sheet1 so i suggest rethink you're logic.\nI would suggest something like this:\nconst ss = SpreadsheetApp.getActiveSpreadsheet()\nlet SHEET\n\nconst sheetCheck = ss.getSheetByName(\"TheSheetName\")\n\nif(sheetCheck){\n //Assign the founded sheet to the variable SHEET\n SHEET = sheetCheck\n} else {\n //Create the sheet and assign to SHEET\n SHEET = ss.insertSheet(\"TheSheetName\")\n}\n\n//Do something with SHEET\n\n", "You can get the active like this:\n const sheet = SpreadsheetApp.getActiveSheet();\nThis way, there is no need to meddle with sheet names. If you need the sheet name for some reason, you can get it like this:\n const sheetName = sheet.getName();\nWhen there are multiple tabs in the spreadsheet, you can get the sheet that shows first in the tab bar like this:\n const sheet = SpreadsheetApp.getActive().getSheets()[0];\n" ]
[ 0, 0 ]
[]
[]
[ "google_apps_script", "javascript" ]
stackoverflow_0074660815_google_apps_script_javascript.txt
Q: Customizing only selected radio button, if button selection changes, previously selected button returns to original I used radio buttons to allow for only 1 button being selected That worked I customised the original look I managed to customise the selected button But when I change the selection, the first button still keeps the selected colors along with the new selection I can't seem to only allow one to be the selected colors <fieldset class="numbers-container"> <div class="number"> <input type="radio" id="no1" name="numbers" value="1" /> <label for="no1">1</label> </div> <div class="number"> <input type="radio" id="no2" name="numbers" value="2" /> <label for="no2">2</label> </div> <div class="number"> <input type="radio" id="no3" name="numbers" value="3" /> <label for="no3">3</label> </div> <div class="number"> <input type="radio" id="no4" name="numbers" value="4" /> <label for="no4">4</label> </div> <div class="number"> <input type="radio" id="no5" name="numbers" value="5" /> <label for="no5">5</label> </div> </fieldset> .numbers-container { display: flex; gap: 1rem; justify-content: center; border: none; } input[type="radio"] { opacity: 0; position: fixed; width: 0; } .number { border-radius: 50%; height: 3rem; width: 3rem; display: flex; align-items: center; justify-content: center; color: hsl(217, 12%, 63%); background-color: hsl(213, 25%, 25%); border: none; } .number:hover { background-color: hsl(25, 97%, 53%); color: white; } .selected { background-color: hsl(217, 12%, 63%); color: white; } const ratingState = document.querySelector(".rating-state"); const thanksState = document.querySelector(".thanks-state"); const btnSubmit = document.querySelector(".btn-submit"); const numberSelect = document.querySelectorAll(".number"); for (let i = 0; i < numberSelect.length; i++) numberSelect[i].addEventListener("click", function () { console.log("button clicked", numberSelect[i]); numberSelect[i].classList.add("selected"); }); A: You don't remove your .selected class for every radio button in the fieldset: const ratingState = document.querySelector(".rating-state"); const thanksState = document.querySelector(".thanks-state"); const btnSubmit = document.querySelector(".btn-submit"); const numberSelect = document.querySelectorAll(".number"); for (let i = 0; i < numberSelect.length; i++) numberSelect[i].addEventListener("click", function() { console.log("button clicked", numberSelect[i]); if (numberSelect[i].classList.contains("selected")) numberSelect[i].classList.remove("selected"); else { numberSelect.forEach((select) => select.classList.remove("selected")); numberSelect[i].classList.add("selected"); } }); .numbers-container { display: flex; gap: 1rem; justify-content: center; border: none; } input[type="radio"] { opacity: 0; position: fixed; width: 0; } .number { border-radius: 50%; height: 3rem; width: 3rem; display: flex; align-items: center; justify-content: center; color: hsl(217, 12%, 63%); background-color: hsl(213, 25%, 25%); border: none; } .number:hover { background-color: hsl(25, 97%, 53%); color: white; } .selected { background-color: hsl(217, 12%, 63%); color: white; } <fieldset class="numbers-container"> <div class="number"> <input type="radio" id="no1" name="numbers" value="1" /> <label for="no1">1</label> </div> <div class="number"> <input type="radio" id="no2" name="numbers" value="2" /> <label for="no2">2</label> </div> <div class="number"> <input type="radio" id="no3" name="numbers" value="3" /> <label for="no3">3</label> </div> <div class="number"> <input type="radio" id="no4" name="numbers" value="4" /> <label for="no4">4</label> </div> <div class="number"> <input type="radio" id="no5" name="numbers" value="5" /> <label for="no5">5</label> </div> </fieldset> On a side note, what you are trying to achieve is totally possible using just CSS: .numbers-container { display: flex; gap: 1rem; justify-content: center; border: none; } input[type="radio"] { /* hide checkbox so that we only have to worry about label */ display: none; } /* select sibling label */ input[type="radio"]:checked+label { background-color: hsl(217, 12%, 63%); color: white; } label:hover { background-color: hsl(25, 97%, 53%); color: white; } label { /* label size of div */ width: 3rem; height: 3rem; border-radius: 50%; /* center label text */ text-align: center; vertical-align: middle; line-height: 3rem; /* your other styling */ background-color: hsl(213, 25%, 25%); color: hsl(217, 12%, 63%); } <fieldset class="numbers-container"> <input type="radio" id="no1" name="numbers" value="1" /> <label for="no1">1</label> <input type="radio" id="no2" name="numbers" value="2" /> <label for="no2">2</label> <input type="radio" id="no3" name="numbers" value="3" /> <label for="no3">3</label> <input type="radio" id="no4" name="numbers" value="4" /> <label for="no4">4</label> <input type="radio" id="no5" name="numbers" value="5" /> <label for="no5">5</label> </fieldset>
Customizing only selected radio button, if button selection changes, previously selected button returns to original
I used radio buttons to allow for only 1 button being selected That worked I customised the original look I managed to customise the selected button But when I change the selection, the first button still keeps the selected colors along with the new selection I can't seem to only allow one to be the selected colors <fieldset class="numbers-container"> <div class="number"> <input type="radio" id="no1" name="numbers" value="1" /> <label for="no1">1</label> </div> <div class="number"> <input type="radio" id="no2" name="numbers" value="2" /> <label for="no2">2</label> </div> <div class="number"> <input type="radio" id="no3" name="numbers" value="3" /> <label for="no3">3</label> </div> <div class="number"> <input type="radio" id="no4" name="numbers" value="4" /> <label for="no4">4</label> </div> <div class="number"> <input type="radio" id="no5" name="numbers" value="5" /> <label for="no5">5</label> </div> </fieldset> .numbers-container { display: flex; gap: 1rem; justify-content: center; border: none; } input[type="radio"] { opacity: 0; position: fixed; width: 0; } .number { border-radius: 50%; height: 3rem; width: 3rem; display: flex; align-items: center; justify-content: center; color: hsl(217, 12%, 63%); background-color: hsl(213, 25%, 25%); border: none; } .number:hover { background-color: hsl(25, 97%, 53%); color: white; } .selected { background-color: hsl(217, 12%, 63%); color: white; } const ratingState = document.querySelector(".rating-state"); const thanksState = document.querySelector(".thanks-state"); const btnSubmit = document.querySelector(".btn-submit"); const numberSelect = document.querySelectorAll(".number"); for (let i = 0; i < numberSelect.length; i++) numberSelect[i].addEventListener("click", function () { console.log("button clicked", numberSelect[i]); numberSelect[i].classList.add("selected"); });
[ "You don't remove your .selected class for every radio button in the fieldset:\n\n\nconst ratingState = document.querySelector(\".rating-state\");\nconst thanksState = document.querySelector(\".thanks-state\");\nconst btnSubmit = document.querySelector(\".btn-submit\");\nconst numberSelect = document.querySelectorAll(\".number\");\n\nfor (let i = 0; i < numberSelect.length; i++)\n numberSelect[i].addEventListener(\"click\", function() {\n console.log(\"button clicked\", numberSelect[i]);\n if (numberSelect[i].classList.contains(\"selected\")) numberSelect[i].classList.remove(\"selected\");\n else {\n numberSelect.forEach((select) => select.classList.remove(\"selected\"));\n numberSelect[i].classList.add(\"selected\");\n }\n });\n.numbers-container {\n display: flex;\n gap: 1rem;\n justify-content: center;\n border: none;\n}\n\ninput[type=\"radio\"] {\n opacity: 0;\n position: fixed;\n width: 0;\n}\n\n.number {\n border-radius: 50%;\n height: 3rem;\n width: 3rem;\n display: flex;\n align-items: center;\n justify-content: center;\n color: hsl(217, 12%, 63%);\n background-color: hsl(213, 25%, 25%);\n border: none;\n}\n\n.number:hover {\n background-color: hsl(25, 97%, 53%);\n color: white;\n}\n\n.selected {\n background-color: hsl(217, 12%, 63%);\n color: white;\n}\n<fieldset class=\"numbers-container\">\n <div class=\"number\">\n <input type=\"radio\" id=\"no1\" name=\"numbers\" value=\"1\" />\n <label for=\"no1\">1</label>\n </div>\n <div class=\"number\">\n <input type=\"radio\" id=\"no2\" name=\"numbers\" value=\"2\" />\n <label for=\"no2\">2</label>\n </div>\n <div class=\"number\">\n <input type=\"radio\" id=\"no3\" name=\"numbers\" value=\"3\" />\n <label for=\"no3\">3</label>\n </div>\n <div class=\"number\">\n <input type=\"radio\" id=\"no4\" name=\"numbers\" value=\"4\" />\n <label for=\"no4\">4</label>\n </div>\n <div class=\"number\">\n <input type=\"radio\" id=\"no5\" name=\"numbers\" value=\"5\" />\n <label for=\"no5\">5</label>\n </div>\n</fieldset>\n\n\n\nOn a side note, what you are trying to achieve is totally possible using just CSS:\n\n\n.numbers-container {\n display: flex;\n gap: 1rem;\n justify-content: center;\n border: none;\n}\n\ninput[type=\"radio\"] {\n /* hide checkbox so that we only have to worry about label */\n display: none;\n}\n\n\n/* select sibling label */\n\ninput[type=\"radio\"]:checked+label {\n background-color: hsl(217, 12%, 63%);\n color: white;\n}\n\nlabel:hover {\n background-color: hsl(25, 97%, 53%);\n color: white;\n}\n\nlabel {\n /* label size of div */\n width: 3rem;\n height: 3rem;\n border-radius: 50%;\n /* center label text */\n text-align: center;\n vertical-align: middle;\n line-height: 3rem;\n /* your other styling */\n background-color: hsl(213, 25%, 25%);\n color: hsl(217, 12%, 63%);\n}\n<fieldset class=\"numbers-container\">\n <input type=\"radio\" id=\"no1\" name=\"numbers\" value=\"1\" />\n <label for=\"no1\">1</label>\n <input type=\"radio\" id=\"no2\" name=\"numbers\" value=\"2\" />\n <label for=\"no2\">2</label>\n <input type=\"radio\" id=\"no3\" name=\"numbers\" value=\"3\" />\n <label for=\"no3\">3</label>\n <input type=\"radio\" id=\"no4\" name=\"numbers\" value=\"4\" />\n <label for=\"no4\">4</label>\n <input type=\"radio\" id=\"no5\" name=\"numbers\" value=\"5\" />\n <label for=\"no5\">5</label>\n</fieldset>\n\n\n\n" ]
[ 0 ]
[]
[]
[ "css", "html", "javascript" ]
stackoverflow_0074668212_css_html_javascript.txt
Q: How to run complex exponential "cexpf" or "cexp" in the RawKernel of cupy? As title, I was calculating the exponential of an array of complex numbers in the RawKernel provided by cupy. But I don't know how to include or invoke the function "cexpf" or "cexp" correctly. The error message always shows me that "cexpf" is undefined. Does anybody know how to invoke the function in the correct way? Thank you a lot for the answer. import cupy as cp import time add_kernel = cp.RawKernel(r''' #include <cupy/complex.cuh> #include <cupy/complex/cexpf.h> extern "C" __global__ void test(double* x, double* y, complex<float>* z){ int tId_x = blockDim.x*blockIdx.x + threadIdx.x; int tId_y = blockDim.y*blockIdx.y + threadIdx.y; complex<float> value = complex<float>(x[tId_x],y[tId_y]); z[tId_x*blockDim.y*gridDim.y+tId_y] = cexpf(value); }''',"test") x = cp.random.rand(1,8,4096,dtype = cp.float32) #x = cp.arange(0,4096,dtype = cp.uint32) y = cp.random.rand(1,8,4096,dtype = cp.float32) #y = cp.arange(4096,8192,dtype = cp.uint32) z = cp.zeros((4096,4096), dtype = cp.complex64) t1 = time.time() add_kernel((128,128),(32,32),(x,y,z)) print(time.time()-t1) print(z) A: Looking at the headers it seems like you are supposed to just call exp and you don't need to include cupy/complex/cexpf.h yourself, as it is already included implicitly via cupy/complex.cuh. add_kernel = cp.RawKernel(r''' #include <cupy/complex.cuh> extern "C" __global__ void test(double* x, double* y, complex<float>* z){ int tId_x = blockDim.x*blockIdx.x + threadIdx.x; int tId_y = blockDim.y*blockIdx.y + threadIdx.y; complex<float> value = complex<float>(x[tId_x],y[tId_y]); z[tId_x*blockDim.y*gridDim.y+tId_y] = exp(value); }''',"test") Generally Cupy's custome kernel C++ complex number API is taken from Thrust, so you can consult the Thrust documentation. Just skip using the thrust:: namespace. Thrusts API in turn tries to implement the C++ std::complex API for the most part, so looking at the C++ standard library documentation might also be helpful when the Thrust documentation does not go deep enough. Just be careful because Thrust might no give all the same guarantees to avoid performance problems on the GPU.
How to run complex exponential "cexpf" or "cexp" in the RawKernel of cupy?
As title, I was calculating the exponential of an array of complex numbers in the RawKernel provided by cupy. But I don't know how to include or invoke the function "cexpf" or "cexp" correctly. The error message always shows me that "cexpf" is undefined. Does anybody know how to invoke the function in the correct way? Thank you a lot for the answer. import cupy as cp import time add_kernel = cp.RawKernel(r''' #include <cupy/complex.cuh> #include <cupy/complex/cexpf.h> extern "C" __global__ void test(double* x, double* y, complex<float>* z){ int tId_x = blockDim.x*blockIdx.x + threadIdx.x; int tId_y = blockDim.y*blockIdx.y + threadIdx.y; complex<float> value = complex<float>(x[tId_x],y[tId_y]); z[tId_x*blockDim.y*gridDim.y+tId_y] = cexpf(value); }''',"test") x = cp.random.rand(1,8,4096,dtype = cp.float32) #x = cp.arange(0,4096,dtype = cp.uint32) y = cp.random.rand(1,8,4096,dtype = cp.float32) #y = cp.arange(4096,8192,dtype = cp.uint32) z = cp.zeros((4096,4096), dtype = cp.complex64) t1 = time.time() add_kernel((128,128),(32,32),(x,y,z)) print(time.time()-t1) print(z)
[ "Looking at the headers it seems like you are supposed to just call exp and you don't need to include cupy/complex/cexpf.h yourself, as it is already included implicitly via cupy/complex.cuh.\nadd_kernel = cp.RawKernel(r'''\n#include <cupy/complex.cuh>\nextern \"C\" __global__\nvoid test(double* x, double* y, complex<float>* z){\n int tId_x = blockDim.x*blockIdx.x + threadIdx.x;\n int tId_y = blockDim.y*blockIdx.y + threadIdx.y;\n \n complex<float> value = complex<float>(x[tId_x],y[tId_y]);\n\n z[tId_x*blockDim.y*gridDim.y+tId_y] = exp(value);\n}''',\"test\")\n\nGenerally Cupy's custome kernel C++ complex number API is taken from Thrust, so you can consult the Thrust documentation. Just skip using the thrust:: namespace.\nThrusts API in turn tries to implement the C++ std::complex API for the most part, so looking at the C++ standard library documentation might also be helpful when the Thrust documentation does not go deep enough. Just be careful because Thrust might no give all the same guarantees to avoid performance problems on the GPU.\n" ]
[ 3 ]
[]
[]
[ "complex_numbers", "cuda", "cupy", "python_3.x" ]
stackoverflow_0074666710_complex_numbers_cuda_cupy_python_3.x.txt
Q: Applying Riemann–Liouville derivative to Lorenz 3D equation I am using a module in python differint to solve the system of Lorenz 3D equation. After running my 3D system over differint ==> Riemann-Liouville operator for alpha value 1 the original equation and Riemann-Liouville results are not same . The code is mentioned below from scipy.integrate import odeint import numpy as np import matplotlib.pyplot as plt import differint.differint as df t = np.arange(1 , 50, 0.01) def Lorenz(state,t): # unpack the state vector x = state[0] y = state[1] z = state[2] a=10;b=8/3;c=28 xd = a*(y -x) yd = - y +c*x - x*z zd = -b*z + x*y return [xd,yd,zd] state0 = [1,1,1] state = odeint(Lorenz, state0, t) #Simple lorentz eqaution plot plt.subplot(2, 2, 1) plt.plot(state[:,0],state[:,1]) plt.subplot(2, 2, 2) plt.plot(state[:,0],state[:,2]) plt.subplot(2, 2, 3) plt.plot(state[:,1],state[:,2]) plt.show() DF = df.RL(1, state, 0, len(t), len(t)) # Riemann-Liouville plots state=DF plt.subplot(2, 2, 1) plt.plot(state[:,0],state[:,1]) plt.subplot(2,2, 2) plt.plot(state[:,0],state[:,2]) plt.subplot(2, 2, 3) plt.plot(state[:,1],state[:,2]) plt.show() Am i making mistake anywhere or this is the true result? as you can see in eqaution (2) when we put α = 1 we will get the results same as of non fractional system (1). Interested in calculating equation (3) for different values of alpha I think this perhaps the idea of mine is incorrect, because what i am doing is first calculating the system of differential equation using state = odeint(Lorenz, state0, t) followed by the differint module DF = df.RL(1, state, 0, len(t), len(t)) Graphs for lorenz eqaution Graphs for RL fractional for alpha = 1 in these graphs as u can see that the trajectories are absolutely same but the scaling become different A: The call to DF.RL requires a function of the differential equation, however, you used the solution to a differential equation - state (output of odeint call). From the package site https://pypi.org/project/differint/ def f(x): return x**0.5 DF = df.RL(0.5, f) print(DF) Can you try DF = df.RL(1, Lorenz, 0, len(t), len(t)) ?
Applying Riemann–Liouville derivative to Lorenz 3D equation
I am using a module in python differint to solve the system of Lorenz 3D equation. After running my 3D system over differint ==> Riemann-Liouville operator for alpha value 1 the original equation and Riemann-Liouville results are not same . The code is mentioned below from scipy.integrate import odeint import numpy as np import matplotlib.pyplot as plt import differint.differint as df t = np.arange(1 , 50, 0.01) def Lorenz(state,t): # unpack the state vector x = state[0] y = state[1] z = state[2] a=10;b=8/3;c=28 xd = a*(y -x) yd = - y +c*x - x*z zd = -b*z + x*y return [xd,yd,zd] state0 = [1,1,1] state = odeint(Lorenz, state0, t) #Simple lorentz eqaution plot plt.subplot(2, 2, 1) plt.plot(state[:,0],state[:,1]) plt.subplot(2, 2, 2) plt.plot(state[:,0],state[:,2]) plt.subplot(2, 2, 3) plt.plot(state[:,1],state[:,2]) plt.show() DF = df.RL(1, state, 0, len(t), len(t)) # Riemann-Liouville plots state=DF plt.subplot(2, 2, 1) plt.plot(state[:,0],state[:,1]) plt.subplot(2,2, 2) plt.plot(state[:,0],state[:,2]) plt.subplot(2, 2, 3) plt.plot(state[:,1],state[:,2]) plt.show() Am i making mistake anywhere or this is the true result? as you can see in eqaution (2) when we put α = 1 we will get the results same as of non fractional system (1). Interested in calculating equation (3) for different values of alpha I think this perhaps the idea of mine is incorrect, because what i am doing is first calculating the system of differential equation using state = odeint(Lorenz, state0, t) followed by the differint module DF = df.RL(1, state, 0, len(t), len(t)) Graphs for lorenz eqaution Graphs for RL fractional for alpha = 1 in these graphs as u can see that the trajectories are absolutely same but the scaling become different
[ "The call to DF.RL requires a function of the differential equation, however, you used the solution to a differential equation - state (output of odeint call). From the package site https://pypi.org/project/differint/\ndef f(x):\n return x**0.5\n\nDF = df.RL(0.5, f)\nprint(DF)\n\nCan you try DF = df.RL(1, Lorenz, 0, len(t), len(t)) ?\n" ]
[ 0 ]
[]
[]
[ "derivative", "differential_equations", "python", "python_3.x" ]
stackoverflow_0070625237_derivative_differential_equations_python_python_3.x.txt
Q: VBA Selenium: How to Extract <!-- p> non-displayed comment text, from a Web Page Element I am doing a county property survey. The mailing address is included on each record/webpage as a non-displayed comment <!-- p> with a p tag I am trying to extract those non non-displayed comments which contain the mailing and physical address of the property (see attached jpeg) I have tried various forms of comment and attribute schemes to add on to the CSS and xPath Selectors for the h2 header above the comments - but no go so far Set Mailing = MyBrowser.FindElementsByCss("#lxT413 > table > tbody > tr:nth-child(2) > td > h2) Set Mailing = MyBrowser.FindElementByXPath("//*[@id="lxT413"]/table/tbody/tr[2]/td/h2") A: I got it!!! Set Mailing = MyBrowser.FindElementByCss("#lxT413 > table > tbody > tr:nth-child(2) > td") Debug.Print Mailing.Attribute("outerHTML") A: Have a look here. Also looking at the screenshot you've provided, it seems that the commented portion of the DOM is not inside the h2 element but rather inside the td element, maybe that is the reason why you can't reach it?
VBA Selenium: How to Extract <!-- p> non-displayed comment text, from a Web Page Element
I am doing a county property survey. The mailing address is included on each record/webpage as a non-displayed comment <!-- p> with a p tag I am trying to extract those non non-displayed comments which contain the mailing and physical address of the property (see attached jpeg) I have tried various forms of comment and attribute schemes to add on to the CSS and xPath Selectors for the h2 header above the comments - but no go so far Set Mailing = MyBrowser.FindElementsByCss("#lxT413 > table > tbody > tr:nth-child(2) > td > h2) Set Mailing = MyBrowser.FindElementByXPath("//*[@id="lxT413"]/table/tbody/tr[2]/td/h2")
[ "I got it!!!\nSet Mailing = MyBrowser.FindElementByCss(\"#lxT413 > table > tbody > tr:nth-child(2) > td\")\nDebug.Print Mailing.Attribute(\"outerHTML\")\n", "Have a look here. Also looking at the screenshot you've provided, it seems that the commented portion of the DOM is not inside the h2 element but rather inside the td element, maybe that is the reason why you can't reach it?\n" ]
[ 1, 0 ]
[]
[]
[ "excel", "getelementsbytagname", "selenium", "vba", "web_scraping" ]
stackoverflow_0074666170_excel_getelementsbytagname_selenium_vba_web_scraping.txt
Q: Wagtail SteamFields for community user generated content instead of editor, author workflow I really like StreamFields, but I don't want the baggage of Wagtail's Publishing system. For example, consider a Forum community site. Instead of using CK Editor or BBCode, Markdown etc form input. I want to give users the option of StreamField based input to construct posts or replies Is this possible? If yes, what steps would I need to take or edits to Wagtail do I need to do? I'm guessing using a permission system while keeping the user as a limited admin would be the thing to do, since removing the user from admin doesn't seem to be possible since Wagtail is heavily reliant on Django Admin. A: I'm guessing using a permission system while keeping the user as a limited admin would be the thing to do, since removing the user from admin doesn't seem to be possible since Wagtail is heavily reliant on Django Admin. If you want to reuse StreamFields, you probably want to use the Wagtail admin interface; doing otherwise is likely to be quite a bit of work. So users will need to be able to log in and have the wagtail_admin permission so they can access the admin interface. If you tried to use Page models for your forum, you are going to end up crossways of the way Wagtail's page permissions cascade. You could probably write your own admin views for regular users to add certain kinds of content. But honestly, unless you have quite a bit of experience with Wagtail in its normal content management mode, I wouldn't suggest you try using it for this use case.
Wagtail SteamFields for community user generated content instead of editor, author workflow
I really like StreamFields, but I don't want the baggage of Wagtail's Publishing system. For example, consider a Forum community site. Instead of using CK Editor or BBCode, Markdown etc form input. I want to give users the option of StreamField based input to construct posts or replies Is this possible? If yes, what steps would I need to take or edits to Wagtail do I need to do? I'm guessing using a permission system while keeping the user as a limited admin would be the thing to do, since removing the user from admin doesn't seem to be possible since Wagtail is heavily reliant on Django Admin.
[ "\nI'm guessing using a permission system while keeping the user as a\nlimited admin would be the thing to do, since removing the user from\nadmin doesn't seem to be possible since Wagtail is heavily reliant on\nDjango Admin.\n\nIf you want to reuse StreamFields, you probably want to use the Wagtail admin interface; doing otherwise is likely to be quite a bit of work. So users will need to be able to log in and have the wagtail_admin permission so they can access the admin interface. If you tried to use Page models for your forum, you are going to end up crossways of the way Wagtail's page permissions cascade. You could probably write your own admin views for regular users to add certain kinds of content.\nBut honestly, unless you have quite a bit of experience with Wagtail in its normal content management mode, I wouldn't suggest you try using it for this use case.\n" ]
[ 0 ]
[]
[]
[ "django", "wagtail", "wagtail_streamfield" ]
stackoverflow_0074656302_django_wagtail_wagtail_streamfield.txt
Q: The line isnt showing in the navbar? I was following a YouTube tutorial, in which a CSS hover and after effect was used so that when you bring you cursor on the navbar items, a line emerged gradually from the center. But the line isn't showing at all not when I bring the cursor on the navbar items and it didn't show when I wrote the :: after code either I don't understand what is wrong ? So this is the CSS code nav { display: flex; padding: 2% 6%; justify-content: space-between; align-items: center; position: sticky; } nav img { width: 150px; } .nav-links { flex: 1; text-align: right; } .nav-links ul li { list-style: none; display: inline-block; padding: 8px 12px; position: relative; } .nav-links ul li a { color: #fff; text-decoration: none; font-size: 13px; } .nav-liks ul li::after { content: ''; width: 100%; height: 2px; background: #a85d58; display: block; margin: auto; transition: 0.5s; } .nav-liks ul li:hover::after { width: 100%; } And this is the Html <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>University</title> <link rel="stylesheet" href="style.css"> <link rel="preconnect" href="https://fonts.googleapis.com"> <link href="https://fonts.googleapis.com/css2?family=Poppins:ital,wght@0,700;1,700&display=swap" rel="stylesheet"> </head> <body> <section class="header"> <nav> <a href="index.html"><img src="img/logo.png"></a> <div class="nav-links"> <ul> <li><a href="">HOME</a></li> <li><a href="">ABOUT</a></li> <li><a href="">COURSE</a></li> <li><a href="">BLOG</a></li> <li><a href="">CONTACT</a></li> </ul> </div> </nav> </section> </body> </html> A: Based on the code you provided, it looks like there is a typo in the following line: .nav-liks ul li::after { The class .nav-liks does not exist, so this line of code is not being applied. Instead, it should be .nav-links like this: .nav-links ul li::after { This will apply the ::after pseudo-element to the li elements that are children of the ul element that is a child of an element with the nav-links class. I would also recommend changing the display property for the ::after element from block to inline-block, so that it doesn't take up the full width of its parent and will only affect the width of the text it is applied to. .nav-links ul li::after { content: ''; width: 100%; height: 2px; background: #a85d58; display: inline-block; margin: auto; transition: 0.5s; } This answer was generated using OpenAI. I hope it helps.
The line isnt showing in the navbar?
I was following a YouTube tutorial, in which a CSS hover and after effect was used so that when you bring you cursor on the navbar items, a line emerged gradually from the center. But the line isn't showing at all not when I bring the cursor on the navbar items and it didn't show when I wrote the :: after code either I don't understand what is wrong ? So this is the CSS code nav { display: flex; padding: 2% 6%; justify-content: space-between; align-items: center; position: sticky; } nav img { width: 150px; } .nav-links { flex: 1; text-align: right; } .nav-links ul li { list-style: none; display: inline-block; padding: 8px 12px; position: relative; } .nav-links ul li a { color: #fff; text-decoration: none; font-size: 13px; } .nav-liks ul li::after { content: ''; width: 100%; height: 2px; background: #a85d58; display: block; margin: auto; transition: 0.5s; } .nav-liks ul li:hover::after { width: 100%; } And this is the Html <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>University</title> <link rel="stylesheet" href="style.css"> <link rel="preconnect" href="https://fonts.googleapis.com"> <link href="https://fonts.googleapis.com/css2?family=Poppins:ital,wght@0,700;1,700&display=swap" rel="stylesheet"> </head> <body> <section class="header"> <nav> <a href="index.html"><img src="img/logo.png"></a> <div class="nav-links"> <ul> <li><a href="">HOME</a></li> <li><a href="">ABOUT</a></li> <li><a href="">COURSE</a></li> <li><a href="">BLOG</a></li> <li><a href="">CONTACT</a></li> </ul> </div> </nav> </section> </body> </html>
[ "Based on the code you provided, it looks like there is a typo in the following line:\n.nav-liks ul li::after {\n\nThe class .nav-liks does not exist, so this line of code is not being applied. Instead, it should be .nav-links like this:\n.nav-links ul li::after {\n\nThis will apply the ::after pseudo-element to the li elements that are children of the ul element that is a child of an element with the nav-links class.\nI would also recommend changing the display property for the ::after element from block to inline-block, so that it doesn't take up the full width of its parent and will only affect the width of the text it is applied to.\n.nav-links ul li::after {\n content: '';\n width: 100%;\n height: 2px;\n background: #a85d58;\n display: inline-block;\n margin: auto;\n transition: 0.5s;\n}\n\nThis answer was generated using OpenAI. I hope it helps.\n" ]
[ 0 ]
[]
[]
[ "css", "html" ]
stackoverflow_0074668638_css_html.txt
Q: My for loop doesn't count values from another column in dataframe I'm completely lost why my for loop doesn't append the value from another column. My dataframe looks like this and my code is like this i = -1 open_line = [] for line in df["line 1"]: idx = i + 1 if (0 < line < 1000 and df.iloc[idx]["line 2"] < 0): open_line.append(df.iloc[idx]["line 2"]) elif line == 1000 and df.iloc[idx]["line 2"] == 1000: open_line.append("NAN") elif line == 1000 and 0 < df.iloc[idx]["line 2"] < 1000: open_line.append("NAN") elif line < 0: open_line.append(line) When I print open_line I get ['NAN', 'NAN', -1] The problem is when first if statement is passed at row 3 it doesn't append -9 to my list but it just goes on. Thanks for the help. A: The problem comes from the fact that idx is never incremented. Replace: i = -1 with idx = -1 and idx = i + 1 with idx = idx + 1 Then print(open_line) outputs ['NAN', 'NAN', -9, -1, -3, -3] A more efficient way to do it would be like this: df.loc[(df["line 1"] > 0) & (df["line 1"] < 1_000), "open_line"] = df.loc[ (df["line 1"] > 0) & (df["line 1"] < 1_000), "line 2" ] df.loc[ (df["line 1"] == 1_000) & (df["line 2"] > 0) & (df["line 2"] <= 1_000), "open_line" ] = "NAN" df.loc[df["line 1"] < 0, "open_line"] = df.loc[df["line 1"] < 0, "line 1"] open_line = [i if isinstance(i, str) else int(i) for i in df["open_line"]] Then print(open_line) outputs ['NAN', 'NAN', -9, -1, -3, -3]
My for loop doesn't count values from another column in dataframe
I'm completely lost why my for loop doesn't append the value from another column. My dataframe looks like this and my code is like this i = -1 open_line = [] for line in df["line 1"]: idx = i + 1 if (0 < line < 1000 and df.iloc[idx]["line 2"] < 0): open_line.append(df.iloc[idx]["line 2"]) elif line == 1000 and df.iloc[idx]["line 2"] == 1000: open_line.append("NAN") elif line == 1000 and 0 < df.iloc[idx]["line 2"] < 1000: open_line.append("NAN") elif line < 0: open_line.append(line) When I print open_line I get ['NAN', 'NAN', -1] The problem is when first if statement is passed at row 3 it doesn't append -9 to my list but it just goes on. Thanks for the help.
[ "The problem comes from the fact that idx is never incremented.\nReplace:\n\ni = -1 with idx = -1\n\nand idx = i + 1 with idx = idx + 1\n\n\nThen print(open_line) outputs ['NAN', 'NAN', -9, -1, -3, -3]\nA more efficient way to do it would be like this:\ndf.loc[(df[\"line 1\"] > 0) & (df[\"line 1\"] < 1_000), \"open_line\"] = df.loc[\n (df[\"line 1\"] > 0) & (df[\"line 1\"] < 1_000), \"line 2\"\n]\ndf.loc[\n (df[\"line 1\"] == 1_000) & (df[\"line 2\"] > 0) & (df[\"line 2\"] <= 1_000), \"open_line\"\n] = \"NAN\"\ndf.loc[df[\"line 1\"] < 0, \"open_line\"] = df.loc[df[\"line 1\"] < 0, \"line 1\"]\n\nopen_line = [i if isinstance(i, str) else int(i) for i in df[\"open_line\"]]\n\nThen print(open_line) outputs ['NAN', 'NAN', -9, -1, -3, -3]\n" ]
[ 1 ]
[]
[]
[ "pandas", "python_3.x" ]
stackoverflow_0074645293_pandas_python_3.x.txt
Q: How to set Custom height for Widget in GridView in Flutter? Even after specifying the height for Container GridView, my code is producing square widgets. class MyHomePage extends StatefulWidget { MyHomePage({Key key, this.title}) : super(key: key); final String title; @override _MyHomePageState createState() => new _MyHomePageState(); } class _MyHomePageState extends State<MyHomePage> { List<String> widgetList = ['A', 'B', 'C']; @override Widget build(BuildContext context) { return new Scaffold( appBar: new AppBar( title: new Text(widget.title), ), body: new Container( child: new GridView.count( crossAxisCount: 2, controller: new ScrollController(keepScrollOffset: false), shrinkWrap: true, scrollDirection: Axis.vertical, children: widgetList.map((String value) { return new Container( height: 250.0, color: Colors.green, margin: new EdgeInsets.all(1.0), child: new Center( child: new Text( value, style: new TextStyle(fontSize: 50.0,color: Colors.white), ), ), ); }).toList(), ), ), ); } } The output of the code above is as shown on the left. How can I get a GridView with custom height widget as shown on the right? A: The key is the childAspectRatio. This value is use to determine the layout in GridView. In order to get the desired aspect you have to set it to the (itemWidth / itemHeight). The solution would be this: class MyHomePage extends StatefulWidget { MyHomePage({Key key, this.title}) : super(key: key); final String title; @override _MyHomePageState createState() => new _MyHomePageState(); } class _MyHomePageState extends State<MyHomePage> { List<String> widgetList = ['A', 'B', 'C']; @override Widget build(BuildContext context) { var size = MediaQuery.of(context).size; /*24 is for notification bar on Android*/ final double itemHeight = (size.height - kToolbarHeight - 24) / 2; final double itemWidth = size.width / 2; return new Scaffold( appBar: new AppBar( title: new Text(widget.title), ), body: new Container( child: new GridView.count( crossAxisCount: 2, childAspectRatio: (itemWidth / itemHeight), controller: new ScrollController(keepScrollOffset: false), shrinkWrap: true, scrollDirection: Axis.vertical, children: widgetList.map((String value) { return new Container( color: Colors.green, margin: new EdgeInsets.all(1.0), child: new Center( child: new Text( value, style: new TextStyle( fontSize: 50.0, color: Colors.white, ), ), ), ); }).toList(), ), ), ); } } A: Few days ago I came here to find a way to dynamically change height when images are loaded from internet and using childAspectRatio cannot do that because its apply to all widget in GridView(same height for each). This answer may help someone who want different height according to each and every widget content: I found a package called Flutter Staggered GridView by Romain Rastel. Using this package we can do so many things check examples here. To get what we want we can use StaggeredGridView.count() and its property staggeredTiles: and for its value you can map all widget and apply StaggeredTile.fit(2). Example code: StaggeredGridView.count( crossAxisCount: 4, // I only need two card horizontally padding: const EdgeInsets.all(2.0), children: yourList.map<Widget>((item) { //Do you need to go somewhere when you tap on this card, wrap using InkWell and add your route return new Card( child: Column( children: <Widget>[ Image.network(item.yourImage), Text(yourList.yourText),//may be the structure of your data is different ], ), ); }).toList(), //Here is the place that we are getting flexible/ dynamic card for various images staggeredTiles: yourList.map<StaggeredTile>((_) => StaggeredTile.fit(2)) .toList(), mainAxisSpacing: 3.0, crossAxisSpacing: 4.0, // add some space ), ); You can find complete example(copy,paste and run) here. A: just use childAspectRatio: (1 / .4) where 1 is width and 0.4 is height customize according to your self full code here return GridView.count( crossAxisCount: 2, childAspectRatio: (1 / .4), shrinkWrap: true, children: List.generate(6, (index) { return Padding( padding: const EdgeInsets.all(10.0), child: Container( color: Colors.grey[600], child: Row( children: [ ], ), ), ); }), ); A: All credit goes to @ayRatul on Github for this answer, which is by far the best and simplest I've seen to achieve a fixed item height in a GridView: Create your own custom delegate: class SliverGridDelegateWithFixedCrossAxisCountAndFixedHeight extends SliverGridDelegate { /// Creates a delegate that makes grid layouts with a fixed number of tiles in /// the cross axis. /// /// All of the arguments must not be null. The `mainAxisSpacing` and /// `crossAxisSpacing` arguments must not be negative. The `crossAxisCount` /// and `childAspectRatio` arguments must be greater than zero. const SliverGridDelegateWithFixedCrossAxisCountAndFixedHeight({ @required this.crossAxisCount, this.mainAxisSpacing = 0.0, this.crossAxisSpacing = 0.0, this.height = 56.0, }) : assert(crossAxisCount != null && crossAxisCount > 0), assert(mainAxisSpacing != null && mainAxisSpacing >= 0), assert(crossAxisSpacing != null && crossAxisSpacing >= 0), assert(height != null && height > 0); /// The number of children in the cross axis. final int crossAxisCount; /// The number of logical pixels between each child along the main axis. final double mainAxisSpacing; /// The number of logical pixels between each child along the cross axis. final double crossAxisSpacing; /// The height of the crossAxis. final double height; bool _debugAssertIsValid() { assert(crossAxisCount > 0); assert(mainAxisSpacing >= 0.0); assert(crossAxisSpacing >= 0.0); assert(height > 0.0); return true; } @override SliverGridLayout getLayout(SliverConstraints constraints) { assert(_debugAssertIsValid()); final double usableCrossAxisExtent = constraints.crossAxisExtent - crossAxisSpacing * (crossAxisCount - 1); final double childCrossAxisExtent = usableCrossAxisExtent / crossAxisCount; final double childMainAxisExtent = height; return SliverGridRegularTileLayout( crossAxisCount: crossAxisCount, mainAxisStride: childMainAxisExtent + mainAxisSpacing, crossAxisStride: childCrossAxisExtent + crossAxisSpacing, childMainAxisExtent: childMainAxisExtent, childCrossAxisExtent: childCrossAxisExtent, reverseCrossAxis: axisDirectionIsReversed(constraints.crossAxisDirection), ); } @override bool shouldRelayout( SliverGridDelegateWithFixedCrossAxisCountAndFixedHeight oldDelegate) { return oldDelegate.crossAxisCount != crossAxisCount || oldDelegate.mainAxisSpacing != mainAxisSpacing || oldDelegate.crossAxisSpacing != crossAxisSpacing || oldDelegate.height != height; } } You can then use your custom delegate as so: ... GridView.builder( shrinkWrap: true, itemCount: list.length, gridDelegate: SliverGridDelegateWithFixedCrossAxisCountAndFixedHeight( crossAxisCount: 5, crossAxisSpacing: 5, mainAxisSpacing: 5, height: 48.0, //48 dp of height ... A: crossAxisCount, crossAxisSpacing and screen width determine width, and childAspectRatio determines height. I did bit of calculation to figure out relation between them. var width = (screenWidth - ((_crossAxisCount - 1) * _crossAxisSpacing)) / _crossAxisCount; var height = width / _aspectRatio; Full example: double _crossAxisSpacing = 8, _mainAxisSpacing = 12, _aspectRatio = 2; int _crossAxisCount = 2; @override Widget build(BuildContext context) { double screenWidth = MediaQuery.of(context).size.width; var width = (screenWidth - ((_crossAxisCount - 1) * _crossAxisSpacing)) / _crossAxisCount; var height = width / _aspectRatio; return Scaffold( body: GridView.builder( itemCount: 10, itemBuilder: (context, index) => Container(color: Colors.blue[((index) % 9) * 100]), gridDelegate: SliverGridDelegateWithFixedCrossAxisCount( crossAxisCount: _crossAxisCount, crossAxisSpacing: _crossAxisSpacing, mainAxisSpacing: _mainAxisSpacing, childAspectRatio: _aspectRatio, ), ), ); } A: It's working for me. Example code: var _crossAxisSpacing = 8; var _screenWidth = MediaQuery.of(context).size.width; var _crossAxisCount = 2; var _width = ( _screenWidth - ((_crossAxisCount - 1) * _crossAxisSpacing)) / _crossAxisCount; var cellHeight = 60; var _aspectRatio = _width /cellHeight; GridView: GridView.builder( padding: EdgeInsets.only( left: 5.0, right: 5.0, top: 10, bottom: 10), shrinkWrap: false, itemCount: searchList.length, gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: _crossAxisCount,childAspectRatio: _aspectRatio), itemBuilder: (context, index) { final item = searchList[index]; return Card( child: ListTile( title: Text(item.name,maxLines: 1,overflow: TextOverflow.ellipsis), trailing: Container( width: 15, height: 15, decoration: BoxDecoration( color: item.isActive == true ? Theme.of(context).primaryColor : Colors.red, borderRadius: BorderRadius.all( Radius.circular(50))), ), onTap: () { }, ), elevation: 0.5, ); }, ) A: mainAxisExtent: 150, // here set custom Height You Want NOT: dynamic Height like: ( size.height or other) is Not Going to Work Container( padding: EdgeInsets.all(10), color: Colors.grey.shade300, child: GridView.builder( gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount( crossAxisCount: 2, crossAxisSpacing: 10, mainAxisSpacing: 10, mainAxisExtent: 150, // here set custom Height You Want ), itemCount: 10, itemBuilder: (BuildContext context, int index) { return Container( decoration: BoxDecoration( borderRadius: BorderRadius.circular(5), color: Colors.white, ), child: Text('150px'), ); }, ), ), A: Gridview build with selected highlighted and other unhighlighted mainAxisExtent: 200 (desired height) GridView.builder( shrinkWrap: true, itemCount: _images.length, gridDelegate: SliverGridDelegateWithFixedCrossAxisCount( crossAxisCount: 2, crossAxisSpacing: 10, mainAxisSpacing: 10, mainAxisExtent: 200), itemBuilder: (BuildContext context, int index) { return InkWell( onTap: () { setState(() { _selectedTasteIndex = index; }); }, child: Container( decoration: BoxDecoration( color: _selectedTasteIndex == index ? Colors.green : Colors.white, borderRadius: BorderRadius.circular(WodlDimens.SPACE10), border: Border.all( color: Colors.grey, width: 1, ), ), alignment: Alignment.center, child: Row( mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.center, children: [ Container( height: 30, width: 30, child: Image.asset(_images[index]), ), SizedBox( width: 10, ), Text( _tastes[index], style: TextStyle( fontSize: 20, color: _selectedTasteIndex == index ? Colors.white : Colors.black, ), ), ], ), ), ); //return Image.network(images[index]); }, )) A: You can use mainAxisExtent instead of childAspectRatio GridView.builder( physics: BouncingScrollPhysics(), itemCount: resumes.length, gridDelegate: SliverGridDelegateWithFixedCrossAxisCount( crossAxisCount: 2, mainAxisExtent: 256, ), itemBuilder: (_, index) => Container(), ), A: use childAspectRatio: .7 (or something you can change it and update your view) in GridView.builder use like this gridDelegate: SliverGridDelegateWithFixedCrossAxisCount( crossAxisCount: 2, crossAxisSpacing: 8, mainAxisSpacing: 10, childAspectRatio: .7, ), in GridView.count use like this GridView.count( crossAxisCount: 2, crossAxisSpacing: 8, mainAxisSpacing: 10, childAspectRatio: .7, ) A: Well, the first solution I could see everywhere was using childAspectRatio But aspect ratio was giving different height of the container inside GridView for different screen sizes devices! But then, I finally got the perfect solution: Instead of using childAspectRatio, Use mainAxisExtent which defines the fixed height of the container GridView.builder( gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount( mainAxisSpacing: CommonDimens.MARGIN_20, crossAxisSpacing: CommonDimens.MARGIN_20, crossAxisCount: 2, mainAxisExtent: 152, // childAspectRatio: 1.1, DONT USE THIS when using mainAxisExtent ), shrinkWrap: true, padding: EdgeInsets.zero, itemCount: itemList.length, physics: const NeverScrollableScrollPhysics(), itemBuilder: (_, position) => itemList[position], ), A: Inside the GridView, use this code: gridDelegate: SliverGridDelegateWithFixedCrossAxisCount( crossAxisCount: 3, //Number of columns you want childAspectRatio: (1 / .4) //height & width for the GridTile ), A: Paste this line in GridView.count childAspectRatio: 2/4, A: This question was one of my problems, But I found that if we put the repetitive widget in the SingleChildScrollView widget, the height of the repetitive widget will be in the minimum size! that's it! A: The only built-in easy solution is, to use childAspectRatio and set it to something like 1 / .6 or 1 / .7 depending on your widget size. By default, Flutter GridView.count sets height and width the same size and it causes excess padding if the design requires different shape output. With childAspectRatio way we can assign half value of the width to the height and get what we want to achieve. GridView.count( childAspectRatio: (1 / .7), // this line is the one determines the width-height ratio crossAxisCount: 2, crossAxisSpacing: gScreenWidth / 40, mainAxisSpacing: gScreenWidth / 40, children: List.generate( yourList.length, (index) { return Center( child: Container( child: Text('Hello World. Finally I fixed the height issue'))), }, )), A: gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount( childAspectRatio: 2/1.6 <<<< you just this line and play with the the ratio crossAxisCount: 2, crossAxisSpacing: 15, mainAxisSpacing: 15, ),
How to set Custom height for Widget in GridView in Flutter?
Even after specifying the height for Container GridView, my code is producing square widgets. class MyHomePage extends StatefulWidget { MyHomePage({Key key, this.title}) : super(key: key); final String title; @override _MyHomePageState createState() => new _MyHomePageState(); } class _MyHomePageState extends State<MyHomePage> { List<String> widgetList = ['A', 'B', 'C']; @override Widget build(BuildContext context) { return new Scaffold( appBar: new AppBar( title: new Text(widget.title), ), body: new Container( child: new GridView.count( crossAxisCount: 2, controller: new ScrollController(keepScrollOffset: false), shrinkWrap: true, scrollDirection: Axis.vertical, children: widgetList.map((String value) { return new Container( height: 250.0, color: Colors.green, margin: new EdgeInsets.all(1.0), child: new Center( child: new Text( value, style: new TextStyle(fontSize: 50.0,color: Colors.white), ), ), ); }).toList(), ), ), ); } } The output of the code above is as shown on the left. How can I get a GridView with custom height widget as shown on the right?
[ "The key is the childAspectRatio. This value is use to determine the layout in GridView. In order to get the desired aspect you have to set it to the (itemWidth / itemHeight). The solution would be this:\nclass MyHomePage extends StatefulWidget {\n MyHomePage({Key key, this.title}) : super(key: key);\n\n final String title;\n\n @override\n _MyHomePageState createState() => new _MyHomePageState();\n}\n\nclass _MyHomePageState extends State<MyHomePage> {\n List<String> widgetList = ['A', 'B', 'C'];\n\n @override\n Widget build(BuildContext context) {\n var size = MediaQuery.of(context).size;\n\n /*24 is for notification bar on Android*/\n final double itemHeight = (size.height - kToolbarHeight - 24) / 2;\n final double itemWidth = size.width / 2;\n\n return new Scaffold(\n appBar: new AppBar(\n title: new Text(widget.title),\n ),\n body: new Container(\n child: new GridView.count(\n crossAxisCount: 2,\n childAspectRatio: (itemWidth / itemHeight),\n controller: new ScrollController(keepScrollOffset: false),\n shrinkWrap: true,\n scrollDirection: Axis.vertical,\n children: widgetList.map((String value) {\n return new Container(\n color: Colors.green,\n margin: new EdgeInsets.all(1.0),\n child: new Center(\n child: new Text(\n value,\n style: new TextStyle(\n fontSize: 50.0,\n color: Colors.white,\n ),\n ),\n ),\n );\n }).toList(),\n ),\n ),\n );\n }\n}\n\n", "Few days ago I came here to find a way to dynamically change height when images are loaded from internet and using childAspectRatio cannot do that because its apply to all widget in GridView(same height for each).\nThis answer may help someone who want different height according to each and every widget content:\nI found a package called Flutter Staggered GridView by Romain Rastel. Using this package we can do so many things check examples here.\nTo get what we want we can use StaggeredGridView.count() and its property staggeredTiles: and for its value you can map all widget and apply StaggeredTile.fit(2).\nExample code:\nStaggeredGridView.count(\n crossAxisCount: 4, // I only need two card horizontally\n padding: const EdgeInsets.all(2.0),\n children: yourList.map<Widget>((item) {\n //Do you need to go somewhere when you tap on this card, wrap using InkWell and add your route\n return new Card(\n child: Column(\n children: <Widget>[\n Image.network(item.yourImage),\n Text(yourList.yourText),//may be the structure of your data is different\n ],\n ),\n );\n }).toList(),\n\n //Here is the place that we are getting flexible/ dynamic card for various images\n staggeredTiles: yourList.map<StaggeredTile>((_) => StaggeredTile.fit(2))\n .toList(),\n mainAxisSpacing: 3.0,\n crossAxisSpacing: 4.0, // add some space\n ),\n);\n\nYou can find complete example(copy,paste and run) here.\n", "just use\n childAspectRatio: (1 / .4)\n\nwhere 1 is width and 0.4 is height customize according to your self\nfull code here\n return GridView.count(\n crossAxisCount: 2,\n childAspectRatio: (1 / .4),\n shrinkWrap: true,\n children: List.generate(6, (index) {\n return Padding(\n padding: const EdgeInsets.all(10.0),\n child: Container(\n color: Colors.grey[600],\n child: Row(\n children: [\n\n ],\n ),\n ),\n );\n }),\n);\n\n\n", "All credit goes to @ayRatul on Github for this answer, which is by far the best and simplest I've seen to achieve a fixed item height in a GridView:\nCreate your own custom delegate:\nclass SliverGridDelegateWithFixedCrossAxisCountAndFixedHeight\n extends SliverGridDelegate {\n /// Creates a delegate that makes grid layouts with a fixed number of tiles in\n /// the cross axis.\n ///\n /// All of the arguments must not be null. The `mainAxisSpacing` and\n /// `crossAxisSpacing` arguments must not be negative. The `crossAxisCount`\n /// and `childAspectRatio` arguments must be greater than zero.\n const SliverGridDelegateWithFixedCrossAxisCountAndFixedHeight({\n @required this.crossAxisCount,\n this.mainAxisSpacing = 0.0,\n this.crossAxisSpacing = 0.0,\n this.height = 56.0,\n }) : assert(crossAxisCount != null && crossAxisCount > 0),\n assert(mainAxisSpacing != null && mainAxisSpacing >= 0),\n assert(crossAxisSpacing != null && crossAxisSpacing >= 0),\n assert(height != null && height > 0);\n\n /// The number of children in the cross axis.\n final int crossAxisCount;\n\n /// The number of logical pixels between each child along the main axis.\n final double mainAxisSpacing;\n\n /// The number of logical pixels between each child along the cross axis.\n final double crossAxisSpacing;\n\n /// The height of the crossAxis.\n final double height;\n\n bool _debugAssertIsValid() {\n assert(crossAxisCount > 0);\n assert(mainAxisSpacing >= 0.0);\n assert(crossAxisSpacing >= 0.0);\n assert(height > 0.0);\n return true;\n }\n\n @override\n SliverGridLayout getLayout(SliverConstraints constraints) {\n assert(_debugAssertIsValid());\n final double usableCrossAxisExtent =\n constraints.crossAxisExtent - crossAxisSpacing * (crossAxisCount - 1);\n final double childCrossAxisExtent = usableCrossAxisExtent / crossAxisCount;\n final double childMainAxisExtent = height;\n return SliverGridRegularTileLayout(\n crossAxisCount: crossAxisCount,\n mainAxisStride: childMainAxisExtent + mainAxisSpacing,\n crossAxisStride: childCrossAxisExtent + crossAxisSpacing,\n childMainAxisExtent: childMainAxisExtent,\n childCrossAxisExtent: childCrossAxisExtent,\n reverseCrossAxis: axisDirectionIsReversed(constraints.crossAxisDirection),\n );\n }\n\n @override\n bool shouldRelayout(\n SliverGridDelegateWithFixedCrossAxisCountAndFixedHeight oldDelegate) {\n return oldDelegate.crossAxisCount != crossAxisCount ||\n oldDelegate.mainAxisSpacing != mainAxisSpacing ||\n oldDelegate.crossAxisSpacing != crossAxisSpacing ||\n oldDelegate.height != height;\n }\n}\n\nYou can then use your custom delegate as so:\n...\nGridView.builder(\n shrinkWrap: true,\n itemCount: list.length,\n gridDelegate: SliverGridDelegateWithFixedCrossAxisCountAndFixedHeight(\n crossAxisCount: 5,\n crossAxisSpacing: 5,\n mainAxisSpacing: 5,\n height: 48.0, //48 dp of height \n...\n\n", "crossAxisCount, crossAxisSpacing and screen width determine width, and childAspectRatio determines height. \nI did bit of calculation to figure out relation between them. \nvar width = (screenWidth - ((_crossAxisCount - 1) * _crossAxisSpacing)) / _crossAxisCount;\nvar height = width / _aspectRatio;\n\n\nFull example: \ndouble _crossAxisSpacing = 8, _mainAxisSpacing = 12, _aspectRatio = 2;\nint _crossAxisCount = 2;\n\n@override\nWidget build(BuildContext context) {\n double screenWidth = MediaQuery.of(context).size.width;\n\n var width = (screenWidth - ((_crossAxisCount - 1) * _crossAxisSpacing)) / _crossAxisCount;\n var height = width / _aspectRatio;\n\n return Scaffold(\n body: GridView.builder(\n itemCount: 10,\n itemBuilder: (context, index) => Container(color: Colors.blue[((index) % 9) * 100]),\n gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(\n crossAxisCount: _crossAxisCount,\n crossAxisSpacing: _crossAxisSpacing,\n mainAxisSpacing: _mainAxisSpacing,\n childAspectRatio: _aspectRatio,\n ),\n ),\n );\n}\n\n", "\nIt's working for me. \nExample code:\nvar _crossAxisSpacing = 8;\nvar _screenWidth = MediaQuery.of(context).size.width;\nvar _crossAxisCount = 2;\nvar _width = ( _screenWidth - ((_crossAxisCount - 1) * _crossAxisSpacing)) / _crossAxisCount;\nvar cellHeight = 60;\nvar _aspectRatio = _width /cellHeight;\n\nGridView: \n GridView.builder(\n padding: EdgeInsets.only(\n left: 5.0, right: 5.0, top: 10, bottom: 10),\n shrinkWrap: false,\n itemCount: searchList.length,\n gridDelegate:\n SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: _crossAxisCount,childAspectRatio: _aspectRatio),\n itemBuilder: (context, index) {\n final item = searchList[index];\n return Card(\n child: ListTile(\n title: Text(item.name,maxLines: 1,overflow: TextOverflow.ellipsis),\n trailing: Container(\n width: 15,\n height: 15,\n decoration: BoxDecoration(\n color: item.isActive == true\n ? Theme.of(context).primaryColor\n : Colors.red,\n borderRadius: BorderRadius.all(\n Radius.circular(50))),\n ),\n onTap: () {\n\n },\n ),\n elevation: 0.5,\n );\n },\n ) \n\n", "mainAxisExtent: 150, // here set custom Height You Want\nNOT: dynamic Height like: ( size.height or other) is Not Going to Work\nContainer(\n padding: EdgeInsets.all(10),\n color: Colors.grey.shade300,\n child: GridView.builder(\n gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(\n crossAxisCount: 2,\n crossAxisSpacing: 10,\n mainAxisSpacing: 10,\n mainAxisExtent: 150, // here set custom Height You Want\n ),\n itemCount: 10,\n itemBuilder: (BuildContext context, int index) {\n return Container(\n decoration: BoxDecoration(\n borderRadius: BorderRadius.circular(5),\n color: Colors.white,\n ),\n child: Text('150px'),\n );\n },\n ),\n ),\n\n\n", "Gridview build with selected highlighted and other unhighlighted\nmainAxisExtent: 200 (desired height)\nGridView.builder(\n shrinkWrap: true,\n itemCount: _images.length,\n gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(\n crossAxisCount: 2,\n crossAxisSpacing: 10,\n mainAxisSpacing: 10,\n mainAxisExtent: 200),\n itemBuilder: (BuildContext context, int index) {\n return InkWell(\n onTap: () {\n setState(() {\n _selectedTasteIndex = index;\n });\n },\n child: Container(\n decoration: BoxDecoration(\n color: _selectedTasteIndex == index\n ? Colors.green\n : Colors.white,\n borderRadius: BorderRadius.circular(WodlDimens.SPACE10),\n border: Border.all(\n color: Colors.grey,\n width: 1,\n ),\n ),\n alignment: Alignment.center,\n child: Row(\n mainAxisAlignment: MainAxisAlignment.center,\n crossAxisAlignment: CrossAxisAlignment.center,\n children: [\n Container(\n height: 30,\n width: 30,\n child: Image.asset(_images[index]),\n ),\n SizedBox(\n width: 10,\n ),\n Text(\n _tastes[index],\n style: TextStyle(\n fontSize: 20,\n color: _selectedTasteIndex == index\n ? Colors.white\n : Colors.black,\n ),\n ),\n ],\n ),\n ),\n );\n //return Image.network(images[index]);\n },\n ))\n\n", "You can use mainAxisExtent instead of childAspectRatio\n GridView.builder(\n physics: BouncingScrollPhysics(),\n itemCount: resumes.length,\n gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(\n crossAxisCount: 2,\n mainAxisExtent: 256,\n ),\n itemBuilder: (_, index) => Container(),\n ),\n\n", "use\nchildAspectRatio: .7 (or something you can change it and update your view)\n\nin GridView.builder\nuse like this\ngridDelegate: SliverGridDelegateWithFixedCrossAxisCount(\n crossAxisCount: 2,\n crossAxisSpacing: 8,\n mainAxisSpacing: 10,\n childAspectRatio: .7,\n ),\n\nin GridView.count use like this\nGridView.count(\n crossAxisCount: 2,\n crossAxisSpacing: 8,\n mainAxisSpacing: 10,\n childAspectRatio: .7,\n)\n\n", "Well, the first solution I could see everywhere was using childAspectRatio\nBut aspect ratio was giving different height of the container inside GridView for different screen sizes devices!\nBut then, I finally got the perfect solution:\nInstead of using childAspectRatio, Use mainAxisExtent which defines the fixed height of the container\nGridView.builder(\n gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(\n mainAxisSpacing: CommonDimens.MARGIN_20,\n crossAxisSpacing: CommonDimens.MARGIN_20,\n crossAxisCount: 2,\n mainAxisExtent: 152,\n // childAspectRatio: 1.1, DONT USE THIS when using mainAxisExtent\n ),\n shrinkWrap: true,\n padding: EdgeInsets.zero,\n itemCount: itemList.length,\n physics: const NeverScrollableScrollPhysics(),\n itemBuilder: (_, position) => itemList[position],\n ),\n\n", "Inside the GridView, use this code:\ngridDelegate: SliverGridDelegateWithFixedCrossAxisCount(\ncrossAxisCount: 3, //Number of columns you want\nchildAspectRatio: (1 / .4) //height & width for the GridTile\n),\n\n", "Paste this line in GridView.count\nchildAspectRatio: 2/4,\n", "This question was one of my problems, But I found that if we put the repetitive widget in the SingleChildScrollView widget, the height of the repetitive widget will be in the minimum size!\nthat's it!\n", "The only built-in easy solution is, to use childAspectRatio and set it to something like 1 / .6 or 1 / .7 depending on your widget size. By default, Flutter GridView.count sets height and width the same size and it causes excess padding if the design requires different shape output. With childAspectRatio way we can assign half value of the width to the height and get what we want to achieve.\nGridView.count(\n childAspectRatio: (1 / .7), // this line is the one determines the width-height ratio\n crossAxisCount: 2,\n crossAxisSpacing: gScreenWidth / 40,\n mainAxisSpacing: gScreenWidth / 40,\n children: List.generate(\n yourList.length, (index) {\n return Center(\n child: Container(\n child: Text('Hello World. Finally I fixed the height issue'))),\n},\n)),\n\n", "gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(\nchildAspectRatio: 2/1.6 <<<< you just this line and play with\nthe the ratio\ncrossAxisCount: 2,\ncrossAxisSpacing: 15,\nmainAxisSpacing: 15,\n),\n" ]
[ 308, 29, 26, 21, 19, 11, 11, 5, 4, 4, 3, 1, 1, 0, 0, 0 ]
[]
[]
[ "dart", "flutter", "gridview", "height" ]
stackoverflow_0048405123_dart_flutter_gridview_height.txt
Q: Convert Early Bind Outlook to Late Bind Outlook Ich have a specific code for Outlook that I would like to convert into late binding. However I am comparing some types, so I don't know how to make that comparison without having the dll loaded already. var ol = (dynamic)Marshal.GetActiveObject("Outlook.Application"); dynamic windowType = ol.Application.ActiveWindow(); if (windowType is Microsoft.Office.Interop.Outlook.Explorer) { Console.WriteLine("success") } I am not able to compile the code if I have not loaded the interop dll for Outlook. So I will have to add using Microsoft.Office.Interop.Outlook Which I do not want to use because I won't know exactly what outlook version will be installed on the machine. This is also the reason why I would want to use late Binding. I tried to get the type with Console.WriteLine($"This is my type {windowType.GetType()}"); But I would only get the result This is my type System.__ComObject Any Ideas how I can late bind outlook and still make type comparisons? Can specific types be loaded for comparison? A: It sounds like you want to use late binding to avoid having to compile your code with a specific version of the Outlook interop assembly. Late binding allows you to avoid specifying the type of an object at compile time, but instead determine the type at runtime. To compare the type of an object using late binding, you can use the Type.GetType() method. This method takes the name of the type you want to compare the object to, and returns a Type object representing that type. You can then use the Type.IsInstanceOfType() method to compare the object to the type you specified. Here is an example of how you could use late binding to compare the type of the windowType object: Type outlookExplorerType = Type.GetType("Microsoft.Office.Interop.Outlook.Explorer, Outlook"); if (outlookExplorerType.IsInstanceOfType(windowType)) { Console.WriteLine("success"); } In this example, the Type.GetType() method is used to get the Type object representing the Microsoft.Office.Interop.Outlook.Explorer type. The Type.IsInstanceOfType() method is then used to compare the windowType object to the Microsoft.Office.Interop.Outlook.Explorer type. It's worth noting that using late binding in this way can make your code more difficult to read and maintain, so it's generally recommended to avoid it if possible. It may be better to use a version of the Outlook interop assembly that is compatible with the version of Outlook installed on the machine where your code will be running. EDIT: You will need to make sure you have loaded the assembly into the domain... To load an assembly into the current AppDomain, you can use the Assembly.Load method. This method takes the name of the assembly as an argument, and returns an Assembly object representing the loaded assembly. Here's an example of how you can use the Assembly.Load method to load the Outlook interop assembly into the current AppDomain: // Load the Outlook interop assembly into the current AppDomain Assembly outlookAssembly = Assembly.Load("Microsoft.Office.Interop.Outlook"); // Use the loaded assembly to get the Type of the Explorer class Type explorerType = outlookAssembly.GetType("Microsoft.Office.Interop.Outlook.Explorer"); Once the assembly is loaded into the AppDomain, you can use the Assembly.GetType method to get the Type of the desired class. This allows you to use reflection to compare types without having to reference the Outlook interop assembly in your code. Note that you can also use the Assembly.LoadFrom method to load an assembly from a specific file path. This can be useful if the assembly is not located in the current application's bin directory or the global assembly cache. For example: // Load the Outlook interop assembly from a specific file path Assembly outlookAssembly = Assembly.LoadFrom("C:\path\to\Microsoft.Office.Interop.Outlook.dll"); By using the Assembly.Load or Assembly.LoadFrom methods, you can load the Outlook interop assembly into the current AppDomain, which allows you to use reflection to compare types without referencing the assembly in your code. A: Use the interop dll of the oldest version of Outlook you are planning to support (e.g., Outlook 2013). If you need to access functionality only available in the newer versions, use late binding. There is no reason to access all Outlook objects using late binding only.
Convert Early Bind Outlook to Late Bind Outlook
Ich have a specific code for Outlook that I would like to convert into late binding. However I am comparing some types, so I don't know how to make that comparison without having the dll loaded already. var ol = (dynamic)Marshal.GetActiveObject("Outlook.Application"); dynamic windowType = ol.Application.ActiveWindow(); if (windowType is Microsoft.Office.Interop.Outlook.Explorer) { Console.WriteLine("success") } I am not able to compile the code if I have not loaded the interop dll for Outlook. So I will have to add using Microsoft.Office.Interop.Outlook Which I do not want to use because I won't know exactly what outlook version will be installed on the machine. This is also the reason why I would want to use late Binding. I tried to get the type with Console.WriteLine($"This is my type {windowType.GetType()}"); But I would only get the result This is my type System.__ComObject Any Ideas how I can late bind outlook and still make type comparisons? Can specific types be loaded for comparison?
[ "It sounds like you want to use late binding to avoid having to compile your code with a specific version of the Outlook interop assembly. Late binding allows you to avoid specifying the type of an object at compile time, but instead determine the type at runtime.\nTo compare the type of an object using late binding, you can use the Type.GetType() method. This method takes the name of the type you want to compare the object to, and returns a Type object representing that type. You can then use the Type.IsInstanceOfType() method to compare the object to the type you specified.\nHere is an example of how you could use late binding to compare the type of the windowType object:\nType outlookExplorerType = Type.GetType(\"Microsoft.Office.Interop.Outlook.Explorer, Outlook\");\nif (outlookExplorerType.IsInstanceOfType(windowType)) {\n Console.WriteLine(\"success\");\n}\n\nIn this example, the Type.GetType() method is used to get the Type object representing the Microsoft.Office.Interop.Outlook.Explorer type. The Type.IsInstanceOfType() method is then used to compare the windowType object to the Microsoft.Office.Interop.Outlook.Explorer type.\nIt's worth noting that using late binding in this way can make your code more difficult to read and maintain, so it's generally recommended to avoid it if possible. It may be better to use a version of the Outlook interop assembly that is compatible with the version of Outlook installed on the machine where your code will be running.\nEDIT: You will need to make sure you have loaded the assembly into the domain...\nTo load an assembly into the current AppDomain, you can use the Assembly.Load method. This method takes the name of the assembly as an argument, and returns an Assembly object representing the loaded assembly.\nHere's an example of how you can use the Assembly.Load method to load the Outlook interop assembly into the current AppDomain:\n// Load the Outlook interop assembly into the current AppDomain\nAssembly outlookAssembly = Assembly.Load(\"Microsoft.Office.Interop.Outlook\");\n\n// Use the loaded assembly to get the Type of the Explorer class\nType explorerType = outlookAssembly.GetType(\"Microsoft.Office.Interop.Outlook.Explorer\");\n\nOnce the assembly is loaded into the AppDomain, you can use the Assembly.GetType method to get the Type of the desired class. This allows you to use reflection to compare types without having to reference the Outlook interop assembly in your code.\nNote that you can also use the Assembly.LoadFrom method to load an assembly from a specific file path. This can be useful if the assembly is not located in the current application's bin directory or the global assembly cache. For example:\n// Load the Outlook interop assembly from a specific file path\nAssembly outlookAssembly = Assembly.LoadFrom(\"C:\\path\\to\\Microsoft.Office.Interop.Outlook.dll\");\n\nBy using the Assembly.Load or Assembly.LoadFrom methods, you can load the Outlook interop assembly into the current AppDomain, which allows you to use reflection to compare types without referencing the assembly in your code.\n", "Use the interop dll of the oldest version of Outlook you are planning to support (e.g., Outlook 2013). If you need to access functionality only available in the newer versions, use late binding. There is no reason to access all Outlook objects using late binding only.\n" ]
[ 0, 0 ]
[]
[]
[ "c#", "com_interop", "interop", "office_interop", "outlook" ]
stackoverflow_0074642845_c#_com_interop_interop_office_interop_outlook.txt
Q: formGroupName cannot be set to null I'm trying to create a dynamic angular form with RxFormBuilder (Angular 13.x). I would like to set the formGroupName to null if my input doesn't belong to a nested field, otherwise set it. I expected this attributes to be removed if set to null, but I ended up getting the error below: Cannot read properties of null (reading '_rawValidators') Here is a simple example to illustrate: Component class A { @prop() id!: number; } @Component({ ... }) model: A; form: FormGroup; constructor( private _formBuilder: RxFormBuilder ) { this.model = new A(); this.form = this._formBuilder.formGroup(A, this.model); } } HTML <form [formGroup]="form" *ngIf="form"> <ng-container [formGroupName]="null"> <-- here <mat-form-field> <input matInput name="id" formControlName="id" type="text" /> </mat-form-field> </ng-container> </form> For me, this <ng-container [formGroupName]="null"> should become <ng-container> and not raising this error because it hasn't been set. Is there something I'm missing, or it's a default behavior ? A: If Ashot's comment didn't help, consider using *ngIf like this: <form [formGroup]="form" *ngIf="form"> <ng-container *ngIf="!belongsToNestedField"> <mat-form-field> <input matInput name="id" formControlName="id" type="text" /> </mat-form-field> </ng-container> </form> <form [formGroup]="form" *ngIf="form"> <ng-container *ngIf="belongsToNestedField" [formGroupName]="whatever"> <mat-form-field> <input matInput name="id" formControlName="id" type="text" /> </mat-form-field> </ng-container> </form> Something else you could try, although I'm not sure if it would work, is setting the formGroupName to an empty string conditionally with a ternary operator: <form [formGroup]="form" *ngIf="form"> <ng-container [formGroupName]="belongsToNestedField ? 'whatever' : ''"> <mat-form-field> <input matInput name="id" formControlName="id" type="text" /> </mat-form-field> </ng-container> </form> You could also look at conditional validation in the component instead: link to docs A: For all the folks who encountered the same problem - just use [formControl] instead of formControlName. Here's code example TS: getFormControl(fieldName: string, nestedObjectName: string) { const name = (nestedObjectName ? `${nestedObjectName}.` : '') + fieldName; return this.form.get(name); } HTML: <mat-form-field> <input matInput name="id" [formControl]="getFormControl('fieldName', 'parrentName')" type="text"/> </mat-form-field> Newer versions of angular allows you to pick nested variables by get operator. For instance you have formGroup with values like this: { Client: 'John Smith', Address: { Street: 'Whatever 5' } } You can pick the Client variable via comment form.get('Client'), and Street via form.get('Address.Street')
formGroupName cannot be set to null
I'm trying to create a dynamic angular form with RxFormBuilder (Angular 13.x). I would like to set the formGroupName to null if my input doesn't belong to a nested field, otherwise set it. I expected this attributes to be removed if set to null, but I ended up getting the error below: Cannot read properties of null (reading '_rawValidators') Here is a simple example to illustrate: Component class A { @prop() id!: number; } @Component({ ... }) model: A; form: FormGroup; constructor( private _formBuilder: RxFormBuilder ) { this.model = new A(); this.form = this._formBuilder.formGroup(A, this.model); } } HTML <form [formGroup]="form" *ngIf="form"> <ng-container [formGroupName]="null"> <-- here <mat-form-field> <input matInput name="id" formControlName="id" type="text" /> </mat-form-field> </ng-container> </form> For me, this <ng-container [formGroupName]="null"> should become <ng-container> and not raising this error because it hasn't been set. Is there something I'm missing, or it's a default behavior ?
[ "If Ashot's comment didn't help, consider using *ngIf like this:\n<form [formGroup]=\"form\" *ngIf=\"form\">\n <ng-container *ngIf=\"!belongsToNestedField\">\n <mat-form-field>\n <input matInput name=\"id\" formControlName=\"id\" type=\"text\" />\n </mat-form-field>\n </ng-container>\n</form>\n\n<form [formGroup]=\"form\" *ngIf=\"form\">\n <ng-container *ngIf=\"belongsToNestedField\" [formGroupName]=\"whatever\">\n <mat-form-field>\n <input matInput name=\"id\" formControlName=\"id\" type=\"text\" />\n </mat-form-field>\n </ng-container>\n</form>\n\n\nSomething else you could try, although I'm not sure if it would work, is setting the formGroupName to an empty string conditionally with a ternary operator:\n<form [formGroup]=\"form\" *ngIf=\"form\">\n <ng-container [formGroupName]=\"belongsToNestedField ? 'whatever' : ''\">\n <mat-form-field>\n <input matInput name=\"id\" formControlName=\"id\" type=\"text\" />\n </mat-form-field>\n </ng-container>\n</form>\n\nYou could also look at conditional validation in the component instead: link to docs\n", "For all the folks who encountered the same problem - just use [formControl] instead of formControlName. Here's code example\nTS:\ngetFormControl(fieldName: string, nestedObjectName: string) {\n const name = (nestedObjectName ? `${nestedObjectName}.` : '') + fieldName;\n return this.form.get(name);\n}\n\nHTML:\n<mat-form-field>\n <input\n matInput\n name=\"id\"\n [formControl]=\"getFormControl('fieldName', 'parrentName')\"\n type=\"text\"/>\n</mat-form-field>\n\nNewer versions of angular allows you to pick nested variables by get operator. For instance you have formGroup with values like this:\n{\n Client: 'John Smith',\n Address: {\n Street: 'Whatever 5'\n }\n}\n\nYou can pick the Client variable via comment form.get('Client'),\nand Street via form.get('Address.Street')\n" ]
[ 0, 0 ]
[]
[]
[ "angular", "angular_reactive_forms" ]
stackoverflow_0073717168_angular_angular_reactive_forms.txt
Q: Arithmetic with Chars in Julia Julia REPL tells me that the output of 'c'+2 is 'e': ASCII/Unicode U+0065 (category Ll: Letter, lowercase) but that the output of 'c'+2-'a' is 4. I'm fine with the fact that Chars are identified as numbers via their ASCII code. But I'm confused about the type inference here: why is the first output a char and the second an integer? A: Regarding the motivation for conventions, it’s similar to time stamps and intervals. The difference between time stamps is an interval and accordingly you can add an interval to a time stamp to get another time stamp. You cannot, however, add two time stamps because that doesn’t make sense (what is the sum of two points in time Supposed to be?). The difference between two chars is their distance in code point space (an integer); accordingly you can add an integer to a char to get another char that’s offset by that many code points. You can’t add two chars because adding two code points is not a meaningful operation. Why allow comparisons of chars and differences in the first place? Because it’s common to use that kind of arithmetic and comparison to implement parsing code, eg for parsing numbers in various bases and formats. A: The reason is: julia> @which 'a' - 1 -(x::T, y::Integer) where T<:AbstractChar in Base at char.jl:227 julia> @which 'a' - 'b' -(x::AbstractChar, y::AbstractChar) in Base at char.jl:226 Subtraction of Char and integer is Char. This is e.g. 'a' - 1. However, subtraction of two Char is integer. This is e.g. 'a' - 'b'. Note that for Char and integer both addition and subtraction are defined, but for two Char only subtraction works: julia> 'a' + 'a' ERROR: MethodError: no method matching +(::Char, ::Char) This indeed can lead to tricky cases at times that rely of order of operations, as in this example: julia> 'a' + ('a' - 'a') 'a': ASCII/Unicode U+0061 (category Ll: Letter, lowercase) julia> 'a' + 'a' - 'a' ERROR: MethodError: no method matching +(::Char, ::Char) Also note that when working with Char and integer you cannot subtract Char from integer: julia> 2 - 'a' ERROR: MethodError: no method matching -(::Int64, ::Char) Motivation: subtraction of two char - this is sometimes useful if you want to get a relative position of a char with reference to other char, e.g. c - '0' to convert char to its decimal representation if you know char is a digit; adding or subtracting an integer and char - the same but in reverse e.g. you want to convert digit to char and write '0' + d. I have been using Julia for years now, and I used this feature maybe once or twice, so I would not say it is super commonly needed.
Arithmetic with Chars in Julia
Julia REPL tells me that the output of 'c'+2 is 'e': ASCII/Unicode U+0065 (category Ll: Letter, lowercase) but that the output of 'c'+2-'a' is 4. I'm fine with the fact that Chars are identified as numbers via their ASCII code. But I'm confused about the type inference here: why is the first output a char and the second an integer?
[ "Regarding the motivation for conventions, it’s similar to time stamps and intervals. The difference between time stamps is an interval and accordingly you can add an interval to a time stamp to get another time stamp. You cannot, however, add two time stamps because that doesn’t make sense (what is the sum of two points in time\nSupposed to be?). The difference between two chars is their distance in code point space (an integer); accordingly you can add an integer to a char to get another char that’s offset by that many code points. You can’t add two chars because adding two code points is not a meaningful operation.\nWhy allow comparisons of chars and differences in the first place? Because it’s common to use that kind of arithmetic and comparison to implement parsing code, eg for parsing numbers in various bases and formats.\n", "The reason is:\njulia> @which 'a' - 1\n-(x::T, y::Integer) where T<:AbstractChar in Base at char.jl:227\n\njulia> @which 'a' - 'b'\n-(x::AbstractChar, y::AbstractChar) in Base at char.jl:226\n\nSubtraction of Char and integer is Char. This is e.g. 'a' - 1.\nHowever, subtraction of two Char is integer. This is e.g. 'a' - 'b'.\nNote that for Char and integer both addition and subtraction are defined, but for two Char only subtraction works:\njulia> 'a' + 'a'\nERROR: MethodError: no method matching +(::Char, ::Char)\n\nThis indeed can lead to tricky cases at times that rely of order of operations, as in this example:\njulia> 'a' + ('a' - 'a')\n'a': ASCII/Unicode U+0061 (category Ll: Letter, lowercase)\n\njulia> 'a' + 'a' - 'a'\nERROR: MethodError: no method matching +(::Char, ::Char)\n\nAlso note that when working with Char and integer you cannot subtract Char from integer:\njulia> 2 - 'a'\nERROR: MethodError: no method matching -(::Int64, ::Char)\n\nMotivation:\n\nsubtraction of two char - this is sometimes useful if you want to get a relative position of a char with reference to other char, e.g. c - '0' to convert char to its decimal representation if you know char is a digit;\nadding or subtracting an integer and char - the same but in reverse e.g. you want to convert digit to char and write '0' + d.\n\nI have been using Julia for years now, and I used this feature maybe once or twice, so I would not say it is super commonly needed.\n" ]
[ 7, 5 ]
[]
[]
[ "ascii", "char", "julia" ]
stackoverflow_0074668300_ascii_char_julia.txt
Q: How to get JSON data from a post in grequests library (async-requests) python so im trying to make an async-requests thingy and i cant get the json data from a post import grequests as requests headers = {SOME HEADERS} data = { SOME DATA... } r = requests.post( "some url (NOT A REAL URL)", headers=headers, data=data ) var = r.json["SOME VALUE"] NOTE: THE VALUES IN TH IS CODE AREN'T REAL I tried to get the json value from r and it didnt work, i expected a json value from the r.json["SOME VALUE"] but instead i got an error: " 'builtin_function_or_method' object is not subscriptable " A: r.json is a method. So you need to call it with parentheses first: var = r.json() #type(var) -- > dictionary var = var['SOME VALUE'] #or (shorter) var = r.json()['SOME VALUE']
How to get JSON data from a post in grequests library (async-requests) python
so im trying to make an async-requests thingy and i cant get the json data from a post import grequests as requests headers = {SOME HEADERS} data = { SOME DATA... } r = requests.post( "some url (NOT A REAL URL)", headers=headers, data=data ) var = r.json["SOME VALUE"] NOTE: THE VALUES IN TH IS CODE AREN'T REAL I tried to get the json value from r and it didnt work, i expected a json value from the r.json["SOME VALUE"] but instead i got an error: " 'builtin_function_or_method' object is not subscriptable "
[ "r.json is a method. So you need to call it with parentheses first:\nvar = r.json() #type(var) -- > dictionary\nvar = var['SOME VALUE']\n\n#or (shorter)\nvar = r.json()['SOME VALUE']\n\n" ]
[ 2 ]
[]
[]
[ "grequests", "python" ]
stackoverflow_0074664802_grequests_python.txt
Q: how to run selenium script from a bash file I have a windows laptop in which i have written a selenium script written in python which creates a github repository. It works fine when a run the python file but it gives error when i try to run the script from a bash file. what should i do my bash file: python3 login.py my python file which i am calling from bash: def login(): chr_options = Options() chr_options.add_experimental_option("detach", True) driver = webdriver.Chrome(ChromeDriverManager().install(), options=chr_options) driver.get('https://github.com/new') this is what i get when i try to run the python file with bash from my ubuntu terminal and i have a windows machine and the python file works fine when i try to run it from the windows terminal selenium.common.exceptions.WebDriverException: Message: unknown error: cannot find Chrome binaryStacktrace:#0 0x55de662442a3 <unknown>#1 0x55de66002f77 <unknown>#2 0x55de66029047 <unknown>#3 0x55de660277d0 <unknown>#4 0x55de660680b7 <unknown>#5 0x55de66067a5f <unknown>#6 0x55de6605f903 <unknown>#7 0x55de66032ece <unknown>#8 0x55de66033fde <unknown>#9 0x55de6629463e <unknown>#10 0x55de66297b79 <unknown>#11 0x55de6627a89e <unknown>#12 0x55de66298a83 <unknown>#13 0x55de6626d505 <unknown>#14 0x55de662b9ca8 <unknown>#15 0x55de662b9e36 <unknown>#16 0x55de662d5333 <unknown>#17 0x7f87539e4b43 <unknown> i have a windows 10 laptop in which my selenium script works fine, but when i run the file through the bash terminal it gives this error selenium.common.exceptions.WebDriverException: Message: unknown error: cannot find Chrome binary Stacktrace: #0 0x55de662442a3 <unknown> #1 0x55de66002f77 <unknown> #2 0x55de66029047 <unknown> #3 0x55de660277d0 <unknown> #4 0x55de660680b7 <unknown> A: When you run the python file in windows it uses Chrome installed in you Windows machine, but when you work in a bash terminal you do it on a Linux machine that runs as a virtual machine in you Windows. So it is a separate machine and it cannot use Chrome from your Windows. It needs to have its own Chrome. Additionally this virtual machine does not have a GUI so you will need to run selenium in the headless mode.
how to run selenium script from a bash file
I have a windows laptop in which i have written a selenium script written in python which creates a github repository. It works fine when a run the python file but it gives error when i try to run the script from a bash file. what should i do my bash file: python3 login.py my python file which i am calling from bash: def login(): chr_options = Options() chr_options.add_experimental_option("detach", True) driver = webdriver.Chrome(ChromeDriverManager().install(), options=chr_options) driver.get('https://github.com/new') this is what i get when i try to run the python file with bash from my ubuntu terminal and i have a windows machine and the python file works fine when i try to run it from the windows terminal selenium.common.exceptions.WebDriverException: Message: unknown error: cannot find Chrome binaryStacktrace:#0 0x55de662442a3 <unknown>#1 0x55de66002f77 <unknown>#2 0x55de66029047 <unknown>#3 0x55de660277d0 <unknown>#4 0x55de660680b7 <unknown>#5 0x55de66067a5f <unknown>#6 0x55de6605f903 <unknown>#7 0x55de66032ece <unknown>#8 0x55de66033fde <unknown>#9 0x55de6629463e <unknown>#10 0x55de66297b79 <unknown>#11 0x55de6627a89e <unknown>#12 0x55de66298a83 <unknown>#13 0x55de6626d505 <unknown>#14 0x55de662b9ca8 <unknown>#15 0x55de662b9e36 <unknown>#16 0x55de662d5333 <unknown>#17 0x7f87539e4b43 <unknown> i have a windows 10 laptop in which my selenium script works fine, but when i run the file through the bash terminal it gives this error selenium.common.exceptions.WebDriverException: Message: unknown error: cannot find Chrome binary Stacktrace: #0 0x55de662442a3 <unknown> #1 0x55de66002f77 <unknown> #2 0x55de66029047 <unknown> #3 0x55de660277d0 <unknown> #4 0x55de660680b7 <unknown>
[ "When you run the python file in windows it uses Chrome installed in you Windows machine, but when you work in a bash terminal you do it on a Linux machine that runs as a virtual machine in you Windows.\nSo it is a separate machine and it cannot use Chrome from your Windows. It needs to have its own Chrome. Additionally this virtual machine does not have a GUI so you will need to run selenium in the headless mode.\n" ]
[ 0 ]
[]
[]
[ "automation", "bash", "python", "selenium", "selenium_chromedriver" ]
stackoverflow_0074666192_automation_bash_python_selenium_selenium_chromedriver.txt
Q: How to combine 3 tables using SQL? How can I combine results of 2 table into 3rd table? These are 3 different tables Table A AC_ID IDNT_ID ID_DESC 123 a1000 mhyed 456 b2000 DL 769 c2000 246 2000d BCD 357 3000f 567 600d uhj Table B: b_id b_no b2000 7000001 d78987 909898 Table C: c_id c_no 2000d 678987 6789 09876 Table D: it is a table of all records from table A and common between A& B and A&C AC_ID IDNT_ID No ID_DESC 123 a1000 mhyed 456 b2000 7000001 DL 769 c3000 246 2000d 678987 BCD 357 3000f 567 600d uhj What would be SQL to get the result of table D ? Table E: is the combination of Table B& C header 1 header 2 b2000 700001 d78987 909898 2000d 678987 6789 09876 What would be SQL to get the result of table D ? also what would be SQL table E? I tried using union and joins but was not able to get desired result A: With your sample data for tbl_a, tbl_b and tbl_c use Left Joins for tbl_b and tbl_c to get the result shown as "Table D": -- Table D SQL Select a.AC_ID "AC_ID", a.IDNT_ID "IDNT_ID", COALESCE(b.B_NO, c.C_NO) "B_C_NO", a.ID_DESC "ID_DESC" From tbl_a a Left Join tbl_b b ON(b.B_ID = a.IDNT_ID) Left Join tbl_c c ON(c.C_ID = a.IDNT_ID) Order By a.AC_ID /* R e s u l t : | AC_ID |IDNT_ID |B_C_NO |ID_DESC| |---------- |------- |------- |-------| | 123 |a1000 | |mhyed | | 246 |2000d |678987 |BCD | | 357 |3000f | | | | 456 |b2000 |7000001 |DL | | 567 |600d | |uhj | | 769 |c2000 | | | */ ... and for "Table E" you just need to union tables tbl_b and tbl_c: -- Table E SQL Select B_ID "HEADER_1", B_NO "HEADER_2" From tbl_b Union All Select C_ID "HEADER_1", C_NO "HEADER_2" From tbl_c /* R e s u l t : HEADER_1 HEADER_2 -------- -------- b2000 7000001 d78987 909898 2000d 678987 6789 09876 */ Regards...
How to combine 3 tables using SQL?
How can I combine results of 2 table into 3rd table? These are 3 different tables Table A AC_ID IDNT_ID ID_DESC 123 a1000 mhyed 456 b2000 DL 769 c2000 246 2000d BCD 357 3000f 567 600d uhj Table B: b_id b_no b2000 7000001 d78987 909898 Table C: c_id c_no 2000d 678987 6789 09876 Table D: it is a table of all records from table A and common between A& B and A&C AC_ID IDNT_ID No ID_DESC 123 a1000 mhyed 456 b2000 7000001 DL 769 c3000 246 2000d 678987 BCD 357 3000f 567 600d uhj What would be SQL to get the result of table D ? Table E: is the combination of Table B& C header 1 header 2 b2000 700001 d78987 909898 2000d 678987 6789 09876 What would be SQL to get the result of table D ? also what would be SQL table E? I tried using union and joins but was not able to get desired result
[ "With your sample data for tbl_a, tbl_b and tbl_c use Left Joins for tbl_b and tbl_c to get the result shown as \"Table D\":\n-- Table D SQL\nSelect\n a.AC_ID \"AC_ID\",\n a.IDNT_ID \"IDNT_ID\",\n COALESCE(b.B_NO, c.C_NO) \"B_C_NO\",\n a.ID_DESC \"ID_DESC\"\nFrom\n tbl_a a\nLeft Join\n tbl_b b ON(b.B_ID = a.IDNT_ID)\nLeft Join\n tbl_c c ON(c.C_ID = a.IDNT_ID)\nOrder By\n a.AC_ID\n \n/* R e s u l t :\n| AC_ID |IDNT_ID |B_C_NO |ID_DESC|\n|---------- |------- |------- |-------|\n| 123 |a1000 | |mhyed | \n| 246 |2000d |678987 |BCD | \n| 357 |3000f | | | \n| 456 |b2000 |7000001 |DL | \n| 567 |600d | |uhj | \n| 769 |c2000 | | | \n*/\n\n... and for \"Table E\" you just need to union tables tbl_b and tbl_c:\n-- Table E SQL\nSelect B_ID \"HEADER_1\", B_NO \"HEADER_2\" From tbl_b Union All\nSelect C_ID \"HEADER_1\", C_NO \"HEADER_2\" From tbl_c\n\n/* R e s u l t :\nHEADER_1 HEADER_2\n-------- --------\nb2000 7000001 \nd78987 909898 \n2000d 678987 \n6789 09876 \n*/\n\nRegards...\n" ]
[ 0 ]
[]
[]
[ "sql" ]
stackoverflow_0074663364_sql.txt
Q: Auto click button inside iframe I'm trying to automate the join event, it's a groove page with a default form. I need to skip "join button" and automatically redirect people to another page. The only way is to trigger an auto click using js. But it's not working in my case function myFunction() { var data = document.getElementById("count_id").value; var datacount = (parseInt(data) + 1); document.getElementById("count_id").value = datacount; document.getElementById("clickbutton").value = "Clicked"; } setInterval(function(){ document.getElementById("clickbutton").click(); }, 3000); This code works well, but the button is inside an iframe, and it is added using inspect element. Using document.getElementsByClassName I get the error document.getElementsByClassName(...).click is not a function A: You can use this: document.getElementById('iFrameId').contentDocument.getElementById('clickbutton').click()
Auto click button inside iframe
I'm trying to automate the join event, it's a groove page with a default form. I need to skip "join button" and automatically redirect people to another page. The only way is to trigger an auto click using js. But it's not working in my case function myFunction() { var data = document.getElementById("count_id").value; var datacount = (parseInt(data) + 1); document.getElementById("count_id").value = datacount; document.getElementById("clickbutton").value = "Clicked"; } setInterval(function(){ document.getElementById("clickbutton").click(); }, 3000); This code works well, but the button is inside an iframe, and it is added using inspect element. Using document.getElementsByClassName I get the error document.getElementsByClassName(...).click is not a function
[ "You can use this:\ndocument.getElementById('iFrameId').contentDocument.getElementById('clickbutton').click()\n" ]
[ 0 ]
[]
[]
[ "automation", "iframe", "javascript", "jquery" ]
stackoverflow_0074668642_automation_iframe_javascript_jquery.txt
Q: Java 11 issue with adding dependency jars at runtime When migrated from Java 8 to Java 11, got the following error: Caused by: java.lang.ClassCastException: class jdk.internal.loader.ClassLoaders$AppClassLoader cannot be cast to class java.net.URLClassLoader (jdk.internal.loader.ClassLoaders$AppClassLoader and java.net.URLClassLoader are in module java.base of loader 'bootstrap') Code that thrown error: URLClassLoader urlClassLoader = (URLClassLoader) Thread.currentThread().getContextClassLoader(); ... //URLClassLoader urlClassLoader = (URLClassLoader) ClassLoader.getSystemClassLoader(); ... getMethod().invoke(urlClassLoader, new Object[] { url }); The above error fixed when loaded jars by creating a ClassLoader as per this link: Java 9, compatability issue with ClassLoader.getSystemClassLoader Here is the code: public class DynamicClassLoader extends URLClassLoader { public DynamicClassLoader(URL[] urls, ClassLoader parent) { super(urls, parent); } public void addURL(URL url) { super.addURL(url); } public DynamicClassLoader(String name, ClassLoader parent) { super(name, new URL[0], parent); } /* * Required when this classloader is used as the system classloader */ public DynamicClassLoader(ClassLoader parent) { this("classpath", parent); } public DynamicClassLoader() { this(Thread.currentThread().getContextClassLoader()); } public static DynamicClassLoader findAncestor(ClassLoader cl) { do { if (cl instanceof DynamicClassLoader) return (DynamicClassLoader) cl; cl = cl.getParent(); } while (cl != null); return null; } /* * Required for Java Agents when this classloader is used as the system classloader */ @SuppressWarnings("unused") private void appendToClassPathForInstrumentation(String jarfile) throws IOException { addURL(Paths.get(jarfile).toRealPath().toUri().toURL()); } } Loaded the jars using: urlClassLoader.addURL(url); Run the jar with -Djava.system.class.loader=com.ltchie.util.DynamicClassLoader But the utility jar (jpf.jar - Java plugin framework) added at compile time unable to find the class in dynamically loaded jar at runtime and got ClassNotFoundException. Code: Plugin plugin = pluginManager.getPlugin(pluginDescriptor.getId()); Error: 15:25:54,015 INFO [AppApplication] >>>>>>>> loadLibraries() - ClassLoader: com.app.util.DynamicClassLoader@2f67b837 ... java.lang.NoClassDefFoundError: org/app/plugin/AppCommandPlugin at java.base/java.lang.ClassLoader.defineClass1(Native Method) at java.base/java.lang.ClassLoader.defineClass(ClassLoader.java:1016) at java.base/java.security.SecureClassLoader.defineClass(SecureClassLoader.java:174) at java.base/java.net.URLClassLoader.defineClass(URLClassLoader.java:550) at java.base/java.net.URLClassLoader$1.run(URLClassLoader.java:458) at java.base/java.net.URLClassLoader$1.run(URLClassLoader.java:452) at java.base/java.security.AccessController.doPrivileged(Native Method) at java.base/java.net.URLClassLoader.findClass(URLClassLoader.java:451) at org.java.plugin.standard.StandardPluginClassLoader.loadLocalClass(StandardPluginClassLoader.java:395) at org.java.plugin.standard.StandardPluginClassLoader.loadPluginClass(StandardPluginClassLoader.java:464) at org.java.plugin.standard.StandardPluginClassLoader.loadClass(StandardPluginClassLoader.java:372) at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:521) at org.java.plugin.standard.StandardPluginLifecycleHandler.createPluginInstance(StandardPluginLifecycleHandler.java:113) at org.java.plugin.standard.StandardPluginManager.activatePlugin(StandardPluginManager.java:402) at org.java.plugin.standard.StandardPluginManager.getPlugin(StandardPluginManager.java:217) at org.app.command.AppApplication.getPlugin(AppApplication.java:253) at org.app.command.AppApplication.execute(AppApplication.java:228) at org.app.command.AppApplication.execute(AppApplication.java:221) at org.app.command.AppApplication.startApplication(AppApplication.java:113) at org.java.plugin.boot.Boot.boot(Boot.java:346) at org.java.plugin.boot.Boot.main(Boot.java:243) at org.app.plugin.boot.TPFBoot.main(TPFBoot.java:112) Caused by: java.lang.ClassNotFoundException: org.app.plugin.AppCommandPlugin at org.java.plugin.standard.StandardPluginClassLoader.loadClass(StandardPluginClassLoader.java:378) at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:521) ... 22 more When I add this jar in the manifest of my jar, it works. But I need to load at runtime since this java command line application is based on JPF and there are a lot of jars we need to load when we run the application jar which uses JPF. While checking further, noticed that pluginManager class is with another class loader: 16:57:14,000 INFO [AppApplication] ############ pluginManager.getPlugin: jdk.internal.loader.ClassLoaders$AppClassLoader@799f7e29 This pluginManager instance is from the parent class available in jpf.jar which is defined in the compile-time jar dependency of my application jar manifest. So my application is running with class loader DynamicClassLoader and loads run time jars into that. But the dependency jar added in the manifest is using the default AppClassLoader which causes this unable to find my class. Anyone, please suggest a solution. A: Java 11 introduced a new security feature that prevents the loading of certain classes from untrusted sources, such as JAR files located outside of the application classpath. To solve this issue, you will need to add the JAR files to the application's classpath, either manually or using a build tool such as Maven or Gradle. Additionally, you will need to make sure that the JAR files you are using are signed with a trusted digital signature. This will ensure that the JAR files are trusted by the Java runtime and can be loaded. Example: First, add the dependency to your pom.xml file: <dependency> <groupId>org.example</groupId> <artifactId>example-dependency</artifactId> <version>1.0</version> </dependency> Then, run the following command to add the dependency to the classpath: mvn dependency:copy-dependencies Finally, make sure that the JAR file is signed with a trusted digital signature.
Java 11 issue with adding dependency jars at runtime
When migrated from Java 8 to Java 11, got the following error: Caused by: java.lang.ClassCastException: class jdk.internal.loader.ClassLoaders$AppClassLoader cannot be cast to class java.net.URLClassLoader (jdk.internal.loader.ClassLoaders$AppClassLoader and java.net.URLClassLoader are in module java.base of loader 'bootstrap') Code that thrown error: URLClassLoader urlClassLoader = (URLClassLoader) Thread.currentThread().getContextClassLoader(); ... //URLClassLoader urlClassLoader = (URLClassLoader) ClassLoader.getSystemClassLoader(); ... getMethod().invoke(urlClassLoader, new Object[] { url }); The above error fixed when loaded jars by creating a ClassLoader as per this link: Java 9, compatability issue with ClassLoader.getSystemClassLoader Here is the code: public class DynamicClassLoader extends URLClassLoader { public DynamicClassLoader(URL[] urls, ClassLoader parent) { super(urls, parent); } public void addURL(URL url) { super.addURL(url); } public DynamicClassLoader(String name, ClassLoader parent) { super(name, new URL[0], parent); } /* * Required when this classloader is used as the system classloader */ public DynamicClassLoader(ClassLoader parent) { this("classpath", parent); } public DynamicClassLoader() { this(Thread.currentThread().getContextClassLoader()); } public static DynamicClassLoader findAncestor(ClassLoader cl) { do { if (cl instanceof DynamicClassLoader) return (DynamicClassLoader) cl; cl = cl.getParent(); } while (cl != null); return null; } /* * Required for Java Agents when this classloader is used as the system classloader */ @SuppressWarnings("unused") private void appendToClassPathForInstrumentation(String jarfile) throws IOException { addURL(Paths.get(jarfile).toRealPath().toUri().toURL()); } } Loaded the jars using: urlClassLoader.addURL(url); Run the jar with -Djava.system.class.loader=com.ltchie.util.DynamicClassLoader But the utility jar (jpf.jar - Java plugin framework) added at compile time unable to find the class in dynamically loaded jar at runtime and got ClassNotFoundException. Code: Plugin plugin = pluginManager.getPlugin(pluginDescriptor.getId()); Error: 15:25:54,015 INFO [AppApplication] >>>>>>>> loadLibraries() - ClassLoader: com.app.util.DynamicClassLoader@2f67b837 ... java.lang.NoClassDefFoundError: org/app/plugin/AppCommandPlugin at java.base/java.lang.ClassLoader.defineClass1(Native Method) at java.base/java.lang.ClassLoader.defineClass(ClassLoader.java:1016) at java.base/java.security.SecureClassLoader.defineClass(SecureClassLoader.java:174) at java.base/java.net.URLClassLoader.defineClass(URLClassLoader.java:550) at java.base/java.net.URLClassLoader$1.run(URLClassLoader.java:458) at java.base/java.net.URLClassLoader$1.run(URLClassLoader.java:452) at java.base/java.security.AccessController.doPrivileged(Native Method) at java.base/java.net.URLClassLoader.findClass(URLClassLoader.java:451) at org.java.plugin.standard.StandardPluginClassLoader.loadLocalClass(StandardPluginClassLoader.java:395) at org.java.plugin.standard.StandardPluginClassLoader.loadPluginClass(StandardPluginClassLoader.java:464) at org.java.plugin.standard.StandardPluginClassLoader.loadClass(StandardPluginClassLoader.java:372) at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:521) at org.java.plugin.standard.StandardPluginLifecycleHandler.createPluginInstance(StandardPluginLifecycleHandler.java:113) at org.java.plugin.standard.StandardPluginManager.activatePlugin(StandardPluginManager.java:402) at org.java.plugin.standard.StandardPluginManager.getPlugin(StandardPluginManager.java:217) at org.app.command.AppApplication.getPlugin(AppApplication.java:253) at org.app.command.AppApplication.execute(AppApplication.java:228) at org.app.command.AppApplication.execute(AppApplication.java:221) at org.app.command.AppApplication.startApplication(AppApplication.java:113) at org.java.plugin.boot.Boot.boot(Boot.java:346) at org.java.plugin.boot.Boot.main(Boot.java:243) at org.app.plugin.boot.TPFBoot.main(TPFBoot.java:112) Caused by: java.lang.ClassNotFoundException: org.app.plugin.AppCommandPlugin at org.java.plugin.standard.StandardPluginClassLoader.loadClass(StandardPluginClassLoader.java:378) at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:521) ... 22 more When I add this jar in the manifest of my jar, it works. But I need to load at runtime since this java command line application is based on JPF and there are a lot of jars we need to load when we run the application jar which uses JPF. While checking further, noticed that pluginManager class is with another class loader: 16:57:14,000 INFO [AppApplication] ############ pluginManager.getPlugin: jdk.internal.loader.ClassLoaders$AppClassLoader@799f7e29 This pluginManager instance is from the parent class available in jpf.jar which is defined in the compile-time jar dependency of my application jar manifest. So my application is running with class loader DynamicClassLoader and loads run time jars into that. But the dependency jar added in the manifest is using the default AppClassLoader which causes this unable to find my class. Anyone, please suggest a solution.
[ "Java 11 introduced a new security feature that prevents the loading of certain classes from untrusted sources, such as JAR files located outside of the application classpath. To solve this issue, you will need to add the JAR files to the application's classpath, either manually or using a build tool such as Maven or Gradle. Additionally, you will need to make sure that the JAR files you are using are signed with a trusted digital signature. This will ensure that the JAR files are trusted by the Java runtime and can be loaded.\nExample:\nFirst, add the dependency to your pom.xml file:\n<dependency>\n <groupId>org.example</groupId>\n <artifactId>example-dependency</artifactId>\n <version>1.0</version>\n</dependency>\n\nThen, run the following command to add the dependency to the classpath:\nmvn dependency:copy-dependencies\nFinally, make sure that the JAR file is signed with a trusted digital signature.\n" ]
[ 0 ]
[]
[]
[ "java", "java_11" ]
stackoverflow_0068380968_java_java_11.txt
Q: Copy every n columns from one row of data and paste to multiple rows Problem: Our company receives a data set that summarizes invoices to be paid. For each outstanding invoice, there is a single row of data. Each invoice has a variable number of items to be paid and are listed on the same row. Each item has four columns listed on the invoice row. As a result, the number of columns per invoice can become unwieldy. We need to upload this data with one row per item and it currently requires an accounting clerk to manually copy/paste each item to a new row. Request: Please help me find a way to copy every item (four columns) and paste to a new row with the invoice listed first. Attachments: "RAW" Worksheet is the original data. Columns A-D, highlighted in Gray are the invoice detail. Columns J-M highlighted in Orange are the first item, Columns N-Q highlighted in Blue are the second item, etc. "RAW" Screenshot "Output" Worksheet is the desired outcome (currently done by manually copy/paste) "Output" Screenshot Link to Google Doc for data Attempts: I am a fairly inexperienced Excel user, but I tried a series of if/then, transpositions, pivots, and Offsets with no success. I think that this problem requires a VBA that reviews each row and identifies if there is a non-zero four column item. For each non-zero four column item, it will paste the invoice summary (columns A-D) and the non-zero item (ex. columns J-M) on a new row. If there is a zero-value four column item, the VBA will move to the next row (invoice). That is my best guess, and I haven't a clue how to script this VBA. Thanks for any insight here!! A: Yes it can be done with formulas alone: Starting Data: Output Data: ... First I start with 3 helper columns: A) #s (this could be substituted for just ROW() but I found this easier. 1 to 1000 but feel free to continue at least 5 times larger than your largest expected data set. B) Counts how may cells are not empty on the RAW sheet to the right of "Posting Status" Column C) This is a bit less clear. the first cell (C2) must be just the number one, then each following cell, down to row 1000, has this formula: =IF(COUNTIF($C$1:C2,C2)=INDEX(B:B,MATCH(C2,A:A,0)),C2+1,C2) Next we start with repeating the General Dataset: =IF($C2<INDEX($A:$A,MATCH(0,$B:$B,0)),INDEX(RAW!A:A,$C2+1),"") (this formula is exactly the same through the entire blue section: D2:K1000 ) Now! the really fun part: In the invoice column: =IF($C3<INDEX($A:$A,MATCH(0,$B:$B,0)),OFFSET(RAW!$I$1,$C3,((COUNTIF($C$1:$C3,$C3)-1)*4),1,4),"") Make sure everything is filled all the way down to row 1000 (or whatever your row of choice is) and bob's your Aunty! To Note: I'm assuming your column A (count) on the RAW sheet was added by you. If not you will either need to note copy it over, or adjust all the formulas to pull from one cell to the right. Let me know if you have any troubles with it. A: Transform Data (VBA) Option Explicit Sub TransformData() ' Define constants. Const SRC_NAME As String = "RAW" Const SRC_FIRST_CELL As String = "A3" Const SRC_REPEAT_COLUMNS As Long = 9 Const SRC_CHANGE_COLUMNS As Long = 4 Const DST_NAME As String = "Output" Const DST_FIRST_CELL As String = "A2" Dim wb As Workbook: Set wb = ThisWorkbook ' workbook containing this code ' Reference the Source range. Dim sws As Worksheet: Set sws = wb.Worksheets(SRC_NAME) Dim sfCell As Range: Set sfCell = sws.Range(SRC_FIRST_CELL) Dim srg As Range, srOffset As Long, srCount As Long, scCount As Long With sws.UsedRange scCount = .Columns.Count srOffset = sfCell.Row - 1 srCount = .Rows.Count - srOffset If srCount < 1 Then MsgBox "No data in the Source worksheet.", vbExclamation Exit Sub End If Set srg = .Resize(srCount).Offset(srOffset) End With ' Write the values from the Source range to the Source array. Dim sData() As Variant: sData = srg.Value ' Define the Destination array. Dim scaCount As Long scaCount = (scCount - SRC_REPEAT_COLUMNS) / SRC_CHANGE_COLUMNS Dim drCount As Long: drCount = scaCount * scCount ' could be to many Dim dcCount As Long: dcCount = SRC_REPEAT_COLUMNS + SRC_CHANGE_COLUMNS Dim dData() As Variant: ReDim dData(1 To drCount, 1 To dcCount) ' Transform the data from the Source array ' into the Destination array. Dim sr As Long, sc As Long, scFirst As Long, scLast As Long, sca As Long Dim dr As Long, dc As Long For sr = 1 To srCount For sca = 1 To scaCount ' Determine the Source Change columns. scFirst = 1 + SRC_REPEAT_COLUMNS + (sca - 1) * SRC_CHANGE_COLUMNS scLast = scFirst + SRC_CHANGE_COLUMNS - 1 ' Check if the Source Area is not blank. For sc = scFirst To scLast If Len(CStr(sData(sr, sc))) > 0 Then Exit For Next sc ' Write the Source data. If sc <= scLast Then ' Source Area is not blank dr = dr + 1 For sc = 1 To SRC_REPEAT_COLUMNS dData(dr, sc) = sData(sr, sc) Next sc dc = SRC_REPEAT_COLUMNS For sc = scFirst To scLast dc = dc + 1 dData(dr, dc) = sData(sr, sc) Next sc 'Else ' Source Area is blank; do nothing End If Next sca Next sr If dr = 0 Then MsgBox "No data found.", vbExclamation Exit Sub End If Erase sData ' Reference the Destination range. Dim dws As Worksheet: Set dws = wb.Worksheets(DST_NAME) Dim dfCell As Range: Set dfCell = dws.Range(DST_FIRST_CELL) Dim drg As Range: Set drg = dfCell.Resize(dr, dcCount) ' Write the values from the Destination array to the Destination range. drg.Value = dData drg.Resize(dws.Rows.Count - drg.Row - dr + 1).Offset(dr).Clear ' Inform. MsgBox "Data transformed.", vbInformation End Sub
Copy every n columns from one row of data and paste to multiple rows
Problem: Our company receives a data set that summarizes invoices to be paid. For each outstanding invoice, there is a single row of data. Each invoice has a variable number of items to be paid and are listed on the same row. Each item has four columns listed on the invoice row. As a result, the number of columns per invoice can become unwieldy. We need to upload this data with one row per item and it currently requires an accounting clerk to manually copy/paste each item to a new row. Request: Please help me find a way to copy every item (four columns) and paste to a new row with the invoice listed first. Attachments: "RAW" Worksheet is the original data. Columns A-D, highlighted in Gray are the invoice detail. Columns J-M highlighted in Orange are the first item, Columns N-Q highlighted in Blue are the second item, etc. "RAW" Screenshot "Output" Worksheet is the desired outcome (currently done by manually copy/paste) "Output" Screenshot Link to Google Doc for data Attempts: I am a fairly inexperienced Excel user, but I tried a series of if/then, transpositions, pivots, and Offsets with no success. I think that this problem requires a VBA that reviews each row and identifies if there is a non-zero four column item. For each non-zero four column item, it will paste the invoice summary (columns A-D) and the non-zero item (ex. columns J-M) on a new row. If there is a zero-value four column item, the VBA will move to the next row (invoice). That is my best guess, and I haven't a clue how to script this VBA. Thanks for any insight here!!
[ "Yes it can be done with formulas alone:\nStarting Data:\n\nOutput Data:\n\n\n...\n\nFirst I start with 3 helper columns:\n\nA) #s (this could be substituted for just ROW() but I found this easier. 1 to 1000 but feel free to continue at least 5 times larger than your largest expected data set.\nB) Counts how may cells are not empty on the RAW sheet to the right of \"Posting Status\" Column\nC) This is a bit less clear. the first cell (C2) must be just the number one, then each following cell, down to row 1000, has this formula:\n=IF(COUNTIF($C$1:C2,C2)=INDEX(B:B,MATCH(C2,A:A,0)),C2+1,C2)\n\nNext we start with repeating the General Dataset:\n=IF($C2<INDEX($A:$A,MATCH(0,$B:$B,0)),INDEX(RAW!A:A,$C2+1),\"\")\n\n(this formula is exactly the same through the entire blue section: D2:K1000 )\nNow! the really fun part:\nIn the invoice column:\n=IF($C3<INDEX($A:$A,MATCH(0,$B:$B,0)),OFFSET(RAW!$I$1,$C3,((COUNTIF($C$1:$C3,$C3)-1)*4),1,4),\"\")\n\nMake sure everything is filled all the way down to row 1000 (or whatever your row of choice is) and bob's your Aunty!\nTo Note:\n\nI'm assuming your column A (count) on the RAW sheet was added by you. If not you will either need to note copy it over, or adjust all the formulas to pull from one cell to the right.\nLet me know if you have any troubles with it.\n\n", "Transform Data (VBA)\nOption Explicit\n\nSub TransformData()\n \n ' Define constants.\n \n Const SRC_NAME As String = \"RAW\"\n Const SRC_FIRST_CELL As String = \"A3\"\n Const SRC_REPEAT_COLUMNS As Long = 9\n Const SRC_CHANGE_COLUMNS As Long = 4\n \n Const DST_NAME As String = \"Output\"\n Const DST_FIRST_CELL As String = \"A2\"\n \n Dim wb As Workbook: Set wb = ThisWorkbook ' workbook containing this code\n \n ' Reference the Source range.\n \n Dim sws As Worksheet: Set sws = wb.Worksheets(SRC_NAME)\n Dim sfCell As Range: Set sfCell = sws.Range(SRC_FIRST_CELL)\n \n Dim srg As Range, srOffset As Long, srCount As Long, scCount As Long\n \n With sws.UsedRange\n scCount = .Columns.Count\n srOffset = sfCell.Row - 1\n srCount = .Rows.Count - srOffset\n If srCount < 1 Then\n MsgBox \"No data in the Source worksheet.\", vbExclamation\n Exit Sub\n End If\n Set srg = .Resize(srCount).Offset(srOffset)\n End With\n \n ' Write the values from the Source range to the Source array.\n \n Dim sData() As Variant: sData = srg.Value\n \n ' Define the Destination array.\n \n Dim scaCount As Long\n scaCount = (scCount - SRC_REPEAT_COLUMNS) / SRC_CHANGE_COLUMNS\n \n Dim drCount As Long: drCount = scaCount * scCount ' could be to many\n Dim dcCount As Long: dcCount = SRC_REPEAT_COLUMNS + SRC_CHANGE_COLUMNS\n \n Dim dData() As Variant: ReDim dData(1 To drCount, 1 To dcCount)\n \n ' Transform the data from the Source array\n ' into the Destination array.\n \n Dim sr As Long, sc As Long, scFirst As Long, scLast As Long, sca As Long\n Dim dr As Long, dc As Long\n \n For sr = 1 To srCount\n For sca = 1 To scaCount\n ' Determine the Source Change columns.\n scFirst = 1 + SRC_REPEAT_COLUMNS + (sca - 1) * SRC_CHANGE_COLUMNS\n scLast = scFirst + SRC_CHANGE_COLUMNS - 1\n ' Check if the Source Area is not blank.\n For sc = scFirst To scLast\n If Len(CStr(sData(sr, sc))) > 0 Then Exit For\n Next sc\n ' Write the Source data.\n If sc <= scLast Then ' Source Area is not blank\n dr = dr + 1\n For sc = 1 To SRC_REPEAT_COLUMNS\n dData(dr, sc) = sData(sr, sc)\n Next sc\n dc = SRC_REPEAT_COLUMNS\n For sc = scFirst To scLast\n dc = dc + 1\n dData(dr, dc) = sData(sr, sc)\n Next sc\n 'Else ' Source Area is blank; do nothing\n End If\n Next sca\n Next sr\n \n If dr = 0 Then\n MsgBox \"No data found.\", vbExclamation\n Exit Sub\n End If\n \n Erase sData\n \n ' Reference the Destination range.\n \n Dim dws As Worksheet: Set dws = wb.Worksheets(DST_NAME)\n \n Dim dfCell As Range: Set dfCell = dws.Range(DST_FIRST_CELL)\n Dim drg As Range: Set drg = dfCell.Resize(dr, dcCount)\n \n ' Write the values from the Destination array to the Destination range.\n \n drg.Value = dData\n drg.Resize(dws.Rows.Count - drg.Row - dr + 1).Offset(dr).Clear\n \n ' Inform.\n \n MsgBox \"Data transformed.\", vbInformation\n \nEnd Sub\n\n" ]
[ 0, 0 ]
[]
[]
[ "copy_paste", "excel", "loops", "vba" ]
stackoverflow_0074660427_copy_paste_excel_loops_vba.txt
Q: Angular Material Snackbar Change Color I'm using Angular 7 with Material Snackbar. I want to changes the color of Snackbar to green. In app.component.ts, I have: this.snackBarRef = this.snackBar.open(result.localized_message, 'X', { duration: 4000, verticalPosition: 'top', panelClass: 'notif-success' }); this.snackBarRef.onAction().subscribe(() => { this.snackBarRef.dismiss(); }); In app.component.scss, I have: .notif-success { color: #155724 !important; // green background-color: #d4edda !important; border-color: #c3e6cb !important; .mat-simple-snackbar-action { color: #155724 !important; } } But the Snackbar is still shown in its default colors. I can see that the notif-success class has been applied to the snackbar <snack-bar-container class="mat-snack-bar-container ng-tns-c18-84 ng-trigger ng-trigger-state notif-success mat-snack-bar-center mat-snack-bar-top ng-star-inserted" role="status" style="transform: scale(1); opacity: 1;"> Why is the custom css not working? A: You should write that .notif-success CSS class on your main styles.scss, instead of the app.component.scss. If you are wondering, it is the one which is on the same directory level as your index.html, package.json, etc. A: ::ng-deep is deprecated as stated by @Akber Iqbal. Put the following code in the global css or scss snack-bar-container.mat-snack-bar-container { color: #155724 !important; background-color: #d4edda !important; border-color: #c3e6cb !important; } div.mat-simple-snackbar-action { color: red !important; } This styling code worked on @angular/[email protected] with @angular/[email protected] Note: It doesn't work in the component css or scss A: Instead of: panelClass: 'notif-success' Try: extraClasses: ['notif-success'] I had the same issue and stumbled across this Stackblitz that had a working example. Just realized extraClasses is deprecated, the accepted answer is probably better here. A: This is what you're looking for: ::ng-deep .mat-snack-bar-container{ color: #155724 !important; background-color: #d4edda !important; border-color: #c3e6cb !important; } ::ng-deep .mat-simple-snackbar-action { color: red; } complete working demo here A: MatSnackBar colors can be customized by adding this CSS rule to the styles.css file. Tested for Angular Material 15. .mat-mdc-snack-bar-container { --mat-mdc-snack-bar-button-color: red; --mdc-snackbar-container-color: black; --mdc-snackbar-supporting-text-color: yellow; }
Angular Material Snackbar Change Color
I'm using Angular 7 with Material Snackbar. I want to changes the color of Snackbar to green. In app.component.ts, I have: this.snackBarRef = this.snackBar.open(result.localized_message, 'X', { duration: 4000, verticalPosition: 'top', panelClass: 'notif-success' }); this.snackBarRef.onAction().subscribe(() => { this.snackBarRef.dismiss(); }); In app.component.scss, I have: .notif-success { color: #155724 !important; // green background-color: #d4edda !important; border-color: #c3e6cb !important; .mat-simple-snackbar-action { color: #155724 !important; } } But the Snackbar is still shown in its default colors. I can see that the notif-success class has been applied to the snackbar <snack-bar-container class="mat-snack-bar-container ng-tns-c18-84 ng-trigger ng-trigger-state notif-success mat-snack-bar-center mat-snack-bar-top ng-star-inserted" role="status" style="transform: scale(1); opacity: 1;"> Why is the custom css not working?
[ "You should write that .notif-success CSS class on your main styles.scss, instead of the app.component.scss.\nIf you are wondering, it is the one which is on the same directory level as your index.html, package.json, etc.\n", "::ng-deep is deprecated as stated by @Akber Iqbal. Put the following code in the global css or scss\nsnack-bar-container.mat-snack-bar-container {\n color: #155724 !important;\n background-color: #d4edda !important;\n border-color: #c3e6cb !important;\n}\n\ndiv.mat-simple-snackbar-action {\n color: red !important;\n}\n\nThis styling code worked on @angular/[email protected] with @angular/[email protected] \nNote: It doesn't work in the component css or scss\n", "Instead of:\npanelClass: 'notif-success'\n\nTry: \nextraClasses: ['notif-success']\n\nI had the same issue and stumbled across this Stackblitz that had a working example.\nJust realized extraClasses is deprecated, the accepted answer is probably better here.\n", "This is what you're looking for: \n::ng-deep .mat-snack-bar-container{\n color: #155724 !important;\n background-color: #d4edda !important;\n border-color: #c3e6cb !important;\n}\n::ng-deep .mat-simple-snackbar-action {\n color: red;\n}\n\ncomplete working demo here\n", "MatSnackBar colors can be customized by adding this CSS rule to the styles.css file. Tested for Angular Material 15.\n.mat-mdc-snack-bar-container {\n --mat-mdc-snack-bar-button-color: red;\n --mdc-snackbar-container-color: black;\n --mdc-snackbar-supporting-text-color: yellow;\n}\n\n\n" ]
[ 13, 1, 0, 0, 0 ]
[]
[]
[ "angular", "angular_material", "css" ]
stackoverflow_0056389290_angular_angular_material_css.txt
Q: Spliting string twice with 2 separators in javascript Let's say I need to split the string a.b.c.d#.e.f.g.h#.i.j.k.l with separator as # and then ".". str = a.b.c.d#.e.f.g.h#.i.j.k.l res = str.split("#") res[0] will store a.b.c.d when I use split for the 1st time . I need to split this again and save the data. can anyone help ? A: I think the simplest way to do it is using a regex: var str = "a.b.c.d#.e.f.g.h#.i.j.k.l"; var res = str.split(/[.#]/); A: If I may, if you have to split a string with character a then character b, the simplest in my mind would be : string.split('a').join('b').split('b') A: I know this post is a bit old, but came across it, and fell like there was a better, perhaps more modern, solution. Excluding comments, this is a neat solution to this problem, and is a bit more flexible. It uses the reduce prototype, which works pretty well. This can be modified to output an object with key/value pairs as well. const input = 'a.b.c#.e.f.g#.h.i.j' const firstDelimiter = '#'; const secondDelimiter = '.'; // This will prevent sub arrays from containing empty values, i.e. ['','e','f','g'] const cleanInput = input.replace(/#./g, '#'); //First split by the firstDelimiter const output = cleanInput.split(firstDelimiter).reduce( (newArr, element, i) => { // By this point, you will have an array like ['a.b.c', 'e.f.g', 'h.i.j'] // Each element is passed into the callback, into the element variable let subArr = element.split(secondDelimiter); // split that element by the second delimiter, created another array like ['a', 'b', 'c'], etc. console.log(i, newArr) // newArr is the accumulator, and will maintain it's values newArr[i] = subArr; return newArr; }, []); //It's important to include the [] for the initial value of the accumulator console.log('final:', output); A: If you want to split by '#' and then for each item split by '.' Input:'a.b.c.d#.e.f.g.h#.i.j.k' Output:[ a b c d e f g h i j k] var str = 'a.b.c.d#.e.f.g.h#.i.j.k.l'; var ar = []; var sp = str.split('#'); for (var i = 0; i < sp.length; i++) { var sub = sp[i].split('.'); for (var j = 0; j < sub.length; j++) { ar.push(sub[j]); } } alert(ar); A: Here's a function I made that splits an array: function splitArray(array, delimiter) { let returnValue = []; for(let i = 0; i < array.length; i++) { array[i] = array[i].split(delimiter); array[i].forEach(elem => { returnValue.push(elem); }); }; return returnValue; }; In your case, use it like this: str = "a.b.c.d#.e.f.g.h#.i.j.k.l"; console.log( splitArray (str.split ("#"), "." ) );
Spliting string twice with 2 separators in javascript
Let's say I need to split the string a.b.c.d#.e.f.g.h#.i.j.k.l with separator as # and then ".". str = a.b.c.d#.e.f.g.h#.i.j.k.l res = str.split("#") res[0] will store a.b.c.d when I use split for the 1st time . I need to split this again and save the data. can anyone help ?
[ "I think the simplest way to do it is using a regex:\n var str = \"a.b.c.d#.e.f.g.h#.i.j.k.l\";\n\n var res = str.split(/[.#]/);\n\n", "If I may, if you have to split a string with character a then character b, the simplest in my mind would be : string.split('a').join('b').split('b')\n", "I know this post is a bit old, but came across it, and fell like there was a better, perhaps more modern, solution. Excluding comments, this is a neat solution to this problem, and is a bit more flexible. It uses the reduce prototype, which works pretty well. This can be modified to output an object with key/value pairs as well.\n\n\nconst input = 'a.b.c#.e.f.g#.h.i.j'\r\nconst firstDelimiter = '#';\r\nconst secondDelimiter = '.';\r\n\r\n// This will prevent sub arrays from containing empty values, i.e. ['','e','f','g']\r\nconst cleanInput = input.replace(/#./g, '#');\r\n\r\n//First split by the firstDelimiter\r\nconst output = cleanInput.split(firstDelimiter).reduce( (newArr, element, i) => {\r\n // By this point, you will have an array like ['a.b.c', 'e.f.g', 'h.i.j']\r\n // Each element is passed into the callback, into the element variable\r\n let subArr = element.split(secondDelimiter); // split that element by the second delimiter, created another array like ['a', 'b', 'c'], etc.\r\n console.log(i, newArr)\r\n // newArr is the accumulator, and will maintain it's values\r\n newArr[i] = subArr;\r\n\r\n return newArr;\r\n\r\n}, []); //It's important to include the [] for the initial value of the accumulator\r\n\r\nconsole.log('final:', output);\n\n\n\n", "If you want to split by '#' and then for each item split by '.'\nInput:'a.b.c.d#.e.f.g.h#.i.j.k'\nOutput:[ a b c d e f g h i j k]\nvar str = 'a.b.c.d#.e.f.g.h#.i.j.k.l';\n var ar = [];\n var sp = str.split('#');\n for (var i = 0; i < sp.length; i++) {\n var sub = sp[i].split('.');\n for (var j = 0; j < sub.length; j++) {\n ar.push(sub[j]);\n }\n }\n alert(ar);\n\n", "Here's a function I made that splits an array:\nfunction splitArray(array, delimiter) {\n let returnValue = [];\n for(let i = 0; i < array.length; i++) {\n array[i] = array[i].split(delimiter);\n array[i].forEach(elem => {\n returnValue.push(elem);\n });\n };\n return returnValue;\n};\n\nIn your case, use it like this:\nstr = \"a.b.c.d#.e.f.g.h#.i.j.k.l\";\nconsole.log( splitArray (str.split (\"#\"), \".\" ) );\n\n" ]
[ 5, 2, 1, 0, 0 ]
[ "You can use the explode function similar to php\n// example 1: explode(' ', 'Kevin van Zonneveld');\n// returns 1: {0: 'Kevin', 1: 'van', 2: 'Zonneveld'}\n\nfunction explode(delimiter, string, limit) {\n // discuss at: http://phpjs.org/functions/explode/\n // original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)\n\n if (arguments.length < 2 || typeof delimiter === 'undefined' || typeof string === 'undefined') return null;\n if (delimiter === '' || delimiter === false || delimiter === null) return false;\n if (typeof delimiter === 'function' || typeof delimiter === 'object' || typeof string === 'function' || typeof string ===\n 'object') {\n return {\n 0: ''\n };\n }\n if (delimiter === true) delimiter = '1';\n\n // Here we go...\n delimiter += '';\n string += '';\n\n var s = string.split(delimiter);\n\n if (typeof limit === 'undefined') return s;\n\n // Support for limit\n if (limit === 0) limit = 1;\n\n // Positive limit\n if (limit > 0) {\n if (limit >= s.length) return s;\n return s.slice(0, limit - 1)\n .concat([s.slice(limit - 1)\n .join(delimiter)\n ]);\n }\n\n // Negative limit\n if (-limit >= s.length) return [];\n\n s.splice(s.length + limit);\n return s;\n}\n\nFor more functions visit http://phpjs.org/\n" ]
[ -1 ]
[ "arrays", "javascript", "split" ]
stackoverflow_0024043869_arrays_javascript_split.txt
Q: XMLHttpRequest: How do I pass 'POST' parameters safely (username, password)? I have this code: function RequestLogin() { var request = new XMLHttpRequest(); request.onreadystatechange = function() { if (this.readyState == 4) { alert(this.responseURL); } }; request.open('POST', 'http://myserver/login'); request.setRequestHeader('Content-type', 'multipart/form-data'); request.send('user=myUsername&password=myPassword'); } Is this considered "safe" If I use HTTPS instead of http://myserver/login? What it's not clear to me are the parameters that I have to bind in the request.send, what am I doing there? Am I appending them in the URL, therefore they're visible if someone sniffs the request? I used to create Form Object and pass it there, but it's not working in this case. It's the only way I found to pass parameters to POST request, but am I not exposing the parameters anyway by doing 'user=myUsername&password=myPassword'? Thanks A: If you POST to an HTTPS endpoint, yes, that'll be safe. What it's not clear to me are the parameters that I have to bind in the request.send, what am I doing there? You are sending that string as the request body., and you're sending it to the URL specified, request.open('POST', 'http://myserver/login');. With HTTPS, both the path (/login) and request body are encrypted; snoopers will not be able to see the actual contents of either of them. Am I appending them in the URL, therefore they're visible if someone sniffs the request? No, they're not appended in the URL - if that was being done, the code would instead look something like request.open('POST', 'http://myserver/login?foo=bar&baz=buzz'); Which would be quite strange for a POST - but if it was over HTTPS, it's still be safe, because all snoopers would be able to see is that you and https://myserver are having a conversation. They wouldn't be able to see which endpoint on myserver you're talking to (so, the /login? and everything that follows would be private), and they wouldn't be able to see the contents of the request either. That said, it'd be better to .send the data as you're doing now request.send(sensitiveInfo) than to append the info to the URL because URLs are sometimes stored in the server logs. It's nowhere near as vulnerable as allowing any observer to see what's going on, but it's still not a good idea. You also might consider whether you could use fetch instead of XMLHttpRequest - fetch is considered the more modern way of making requests. It uses Promises, is arguably more intuitive, and has been generally supported by browsers since 2015.
XMLHttpRequest: How do I pass 'POST' parameters safely (username, password)?
I have this code: function RequestLogin() { var request = new XMLHttpRequest(); request.onreadystatechange = function() { if (this.readyState == 4) { alert(this.responseURL); } }; request.open('POST', 'http://myserver/login'); request.setRequestHeader('Content-type', 'multipart/form-data'); request.send('user=myUsername&password=myPassword'); } Is this considered "safe" If I use HTTPS instead of http://myserver/login? What it's not clear to me are the parameters that I have to bind in the request.send, what am I doing there? Am I appending them in the URL, therefore they're visible if someone sniffs the request? I used to create Form Object and pass it there, but it's not working in this case. It's the only way I found to pass parameters to POST request, but am I not exposing the parameters anyway by doing 'user=myUsername&password=myPassword'? Thanks
[ "If you POST to an HTTPS endpoint, yes, that'll be safe.\n\nWhat it's not clear to me are the parameters that I have to bind in the request.send, what am I doing there?\n\nYou are sending that string as the request body., and you're sending it to the URL specified, request.open('POST', 'http://myserver/login');.\nWith HTTPS, both the path (/login) and request body are encrypted; snoopers will not be able to see the actual contents of either of them.\n\nAm I appending them in the URL, therefore they're visible if someone sniffs the request?\n\nNo, they're not appended in the URL - if that was being done, the code would instead look something like\nrequest.open('POST', 'http://myserver/login?foo=bar&baz=buzz');\n\nWhich would be quite strange for a POST - but if it was over HTTPS, it's still be safe, because all snoopers would be able to see is that you and https://myserver are having a conversation. They wouldn't be able to see which endpoint on myserver you're talking to (so, the /login? and everything that follows would be private), and they wouldn't be able to see the contents of the request either.\nThat said, it'd be better to .send the data as you're doing now\nrequest.send(sensitiveInfo)\n\nthan to append the info to the URL because URLs are sometimes stored in the server logs. It's nowhere near as vulnerable as allowing any observer to see what's going on, but it's still not a good idea.\nYou also might consider whether you could use fetch instead of XMLHttpRequest - fetch is considered the more modern way of making requests. It uses Promises, is arguably more intuitive, and has been generally supported by browsers since 2015.\n" ]
[ 1 ]
[]
[]
[ "authentication", "javascript", "post", "xmlhttprequest" ]
stackoverflow_0074668641_authentication_javascript_post_xmlhttprequest.txt
Q: Angular template inside reactive form In our application I noticed lots of duplicate code in the HTML of our forms, most input elements have the same structure so I want to create a generic input component that we can use instead to keep the files clean. The problem I currently have is that there is 1 form that has 2 nested formGroups inside, example: this.addressForm = this.fb.group({ postalAddress: this.fb.group({ street: ["", [Validators.required]], }), visitorAddress: this.fb.group({ street: [""], }) }); This leads to my new component's HTML to also have duplicate code due to some forms requiring a formGroupName. <div [formGroup]="form" *ngIf="form && controlPath && controlName"> <div *ngIf="groupName" [formGroupName]="groupName"> <mat-form-field class="w-full"> <mat-label>{{ label }}</mat-label> <input type="text" matInput [formControlName]="controlName" *ngIf="type === 'text'"> <input type="number" matInput [formControlName]="controlName" *ngIf="type === 'number'"> <mat-error *ngFor="let message of form.get(controlPath)?.errors?.['messages']">{{ message | i18n }}</mat-error> </mat-form-field> </div> <div *ngIf="!groupName"> <mat-form-field class="w-full"> <mat-label>{{ label }}</mat-label> <input type="text" matInput [formControlName]="controlName" *ngIf="type === 'text'"> <input type="number" matInput [formControlName]="controlName" *ngIf="type === 'number'"> <mat-error *ngFor="let message of form.get(controlPath)?.errors?.['messages']">{{ message | i18n }}</mat-error> </mat-form-field> </div> The code above works fine but as mentioned, I would like to get rid of the duplicate code. I figured this would be a good case for a ng-template but it appears when using a template the nested controls can no longer find the surrounding FormGroup. Example <div [formGroup]="form" *ngIf="form && controlPath && controlName"> <div *ngIf="groupName" [formGroupName]="groupName"> <ng-content *ngTemplateOutlet="content"></ng-content> </div> <div *ngIf="!groupName"> <ng-content *ngTemplateOutlet="content"></ng-content> </div> <ng-template #content> <mat-form-field class="w-full"> <mat-label>{{ label }}</mat-label> <input type="text" matInput [formControlName]="controlName" *ngIf="type === 'text'"> <input type="number" matInput [formControlName]="controlName" *ngIf="type === 'number'"> <mat-error *ngFor="let message of form.get(controlPath)?.errors?.['messages']">{{ message | i18n }}</mat-error> </mat-form-field> </ng-template> Error: Has anyone encountered such a situation and if so, what would be a good way to go about this? UPDATE After Garbage Collectors answer I refactored my code to the following: <div [formGroup]="form" *ngIf="form && controlPath && controlName"> <div *ngIf="groupName" [formGroupName]="groupName"> <ng-container [ngTemplateOutlet]="inputTemplate" [ngTemplateOutletContext]="{ templateForm: form, templateFormGroup: groupName, templateControlName: controlName }"></ng-container> </div> <div *ngIf="!groupName"> <ng-container [ngTemplateOutlet]="inputTemplate" [ngTemplateOutletContext]="{ templateForm: form, templateControlName: controlName }"></ng-container> </div> <ng-template #inputTemplate let-form="templateForm" let-groupName="templateFormGroup" let-controlName="templateControlName"> <div [formGroup]="form" [formGroupName]="groupName"> <mat-form-field class="w-full"> <mat-label>{{ label }}</mat-label> <input type="text" matInput [formControlName]="controlName" *ngIf="type === 'text'"> <input type="number" matInput [formControlName]="controlName" *ngIf="type === 'number'"> <mat-error *ngIf="form.get(controlPath)?.errors?.['required']">{{ 'error.required' | i18n }}</mat-error> <mat-error *ngIf="form.get(controlPath)?.errors?.['email']">{{ 'error.email' | i18n }}</mat-error> <mat-error *ngIf="form.get(controlPath)?.errors?.['invalid']">{{ 'error.form.invalid' | i18n }}</mat-error> <mat-error *ngIf="form.get(controlPath)?.errors?.['minlength']">{{ minLengthError }}</mat-error> <mat-error *ngIf="form.get(controlPath)?.errors?.['pattern']">{{ patternError }}</mat-error> <mat-error *ngFor="let message of form.get(controlPath)?.errors?.['messages']">{{ message | i18n }}</mat-error> </mat-form-field> </div> </ng-template> Though the template now has all variables correctly, it cannot find the control path for non-nested forms. I outputted controlName in the template as a test and it is correct. I expect the error occurring due to the formGroupName being null for non-nested forms. Error: A: As far as I remember, every isolated piece of code displaying form controls should have a reference to the form where those controls were defined. Actions Use ng-container instead of ng-content to include your templates Pass form as a parameter to your template Assign form parameter to [formGroup] attribute inside your template Template <ng-template #demoTemplate let-form="demoForm"> <div [formGroup]="form"> <!-- Insert the rest of your template here --> </div> </ng-template> Main component using template <div [formGroup]="form" *ngIf="form"> <ng-container [ngTemplateOutlet]="demoTemplate" [ngTemplateOutletContext]="{ demoForm: form }"> </ng-container> </div> Notice that attribute formGroup is added in both places, in the template and in the parent. A: Use [formControl] instead of formControlName You can pick nested variables via the get command, for instance form.get('Address.Street') More explanations: https://stackoverflow.com/a/74668699/6019056
Angular template inside reactive form
In our application I noticed lots of duplicate code in the HTML of our forms, most input elements have the same structure so I want to create a generic input component that we can use instead to keep the files clean. The problem I currently have is that there is 1 form that has 2 nested formGroups inside, example: this.addressForm = this.fb.group({ postalAddress: this.fb.group({ street: ["", [Validators.required]], }), visitorAddress: this.fb.group({ street: [""], }) }); This leads to my new component's HTML to also have duplicate code due to some forms requiring a formGroupName. <div [formGroup]="form" *ngIf="form && controlPath && controlName"> <div *ngIf="groupName" [formGroupName]="groupName"> <mat-form-field class="w-full"> <mat-label>{{ label }}</mat-label> <input type="text" matInput [formControlName]="controlName" *ngIf="type === 'text'"> <input type="number" matInput [formControlName]="controlName" *ngIf="type === 'number'"> <mat-error *ngFor="let message of form.get(controlPath)?.errors?.['messages']">{{ message | i18n }}</mat-error> </mat-form-field> </div> <div *ngIf="!groupName"> <mat-form-field class="w-full"> <mat-label>{{ label }}</mat-label> <input type="text" matInput [formControlName]="controlName" *ngIf="type === 'text'"> <input type="number" matInput [formControlName]="controlName" *ngIf="type === 'number'"> <mat-error *ngFor="let message of form.get(controlPath)?.errors?.['messages']">{{ message | i18n }}</mat-error> </mat-form-field> </div> The code above works fine but as mentioned, I would like to get rid of the duplicate code. I figured this would be a good case for a ng-template but it appears when using a template the nested controls can no longer find the surrounding FormGroup. Example <div [formGroup]="form" *ngIf="form && controlPath && controlName"> <div *ngIf="groupName" [formGroupName]="groupName"> <ng-content *ngTemplateOutlet="content"></ng-content> </div> <div *ngIf="!groupName"> <ng-content *ngTemplateOutlet="content"></ng-content> </div> <ng-template #content> <mat-form-field class="w-full"> <mat-label>{{ label }}</mat-label> <input type="text" matInput [formControlName]="controlName" *ngIf="type === 'text'"> <input type="number" matInput [formControlName]="controlName" *ngIf="type === 'number'"> <mat-error *ngFor="let message of form.get(controlPath)?.errors?.['messages']">{{ message | i18n }}</mat-error> </mat-form-field> </ng-template> Error: Has anyone encountered such a situation and if so, what would be a good way to go about this? UPDATE After Garbage Collectors answer I refactored my code to the following: <div [formGroup]="form" *ngIf="form && controlPath && controlName"> <div *ngIf="groupName" [formGroupName]="groupName"> <ng-container [ngTemplateOutlet]="inputTemplate" [ngTemplateOutletContext]="{ templateForm: form, templateFormGroup: groupName, templateControlName: controlName }"></ng-container> </div> <div *ngIf="!groupName"> <ng-container [ngTemplateOutlet]="inputTemplate" [ngTemplateOutletContext]="{ templateForm: form, templateControlName: controlName }"></ng-container> </div> <ng-template #inputTemplate let-form="templateForm" let-groupName="templateFormGroup" let-controlName="templateControlName"> <div [formGroup]="form" [formGroupName]="groupName"> <mat-form-field class="w-full"> <mat-label>{{ label }}</mat-label> <input type="text" matInput [formControlName]="controlName" *ngIf="type === 'text'"> <input type="number" matInput [formControlName]="controlName" *ngIf="type === 'number'"> <mat-error *ngIf="form.get(controlPath)?.errors?.['required']">{{ 'error.required' | i18n }}</mat-error> <mat-error *ngIf="form.get(controlPath)?.errors?.['email']">{{ 'error.email' | i18n }}</mat-error> <mat-error *ngIf="form.get(controlPath)?.errors?.['invalid']">{{ 'error.form.invalid' | i18n }}</mat-error> <mat-error *ngIf="form.get(controlPath)?.errors?.['minlength']">{{ minLengthError }}</mat-error> <mat-error *ngIf="form.get(controlPath)?.errors?.['pattern']">{{ patternError }}</mat-error> <mat-error *ngFor="let message of form.get(controlPath)?.errors?.['messages']">{{ message | i18n }}</mat-error> </mat-form-field> </div> </ng-template> Though the template now has all variables correctly, it cannot find the control path for non-nested forms. I outputted controlName in the template as a test and it is correct. I expect the error occurring due to the formGroupName being null for non-nested forms. Error:
[ "As far as I remember, every isolated piece of code displaying form controls should have a reference to the form where those controls were defined.\nActions\n\nUse ng-container instead of ng-content to include your templates\nPass form as a parameter to your template\nAssign form parameter to [formGroup] attribute inside your template\n\nTemplate\n<ng-template #demoTemplate let-form=\"demoForm\">\n <div [formGroup]=\"form\">\n <!-- Insert the rest of your template here -->\n </div>\n</ng-template>\n\nMain component using template\n<div [formGroup]=\"form\" *ngIf=\"form\">\n <ng-container \n [ngTemplateOutlet]=\"demoTemplate\" \n [ngTemplateOutletContext]=\"{ demoForm: form }\">\n </ng-container>\n</div>\n\nNotice that attribute formGroup is added in both places, in the template and in the parent.\n", "Use [formControl] instead of formControlName\nYou can pick nested variables via the get command, for instance form.get('Address.Street')\nMore explanations: https://stackoverflow.com/a/74668699/6019056\n" ]
[ 1, 0 ]
[]
[]
[ "angular", "angular_reactive_forms", "forms", "html" ]
stackoverflow_0071598445_angular_angular_reactive_forms_forms_html.txt
Q: Custom metrics calculation HPA I was wondering regarding Kubernetes HPA custom metrics HPA how it is calculated with targetAverageValue. If for example I’m using the metric that scales pods based on the number of nginx request then each pod now have is own specific metric and I was wondering if it takes each pod and check regarding its value or if it takes all of their metrics and divide this by the number of the pods? A: In Kubernetes HPA, the custom metrics calculation is based on the average value of the metric across all pods. So, if you are using a custom metric that scales pods based on the number of nginx requests, the HPA will take the sum of the metrics from all pods and divide it by the total number of pods to calculate the average value of the metric. This average value will then be compared with the targetAverageValue to determine if the number of pods needs to be scaled up or down. A: HPA uses the targetAverageValue to determine how to scale the number of pods in a deployment. The HPA calculates the average value of the metric across all pods in the deployment, and compares it to the targetAverageValue. If the average value is greater than the targetAverageValue, the HPA will scale up the number of pods. If the average value is less than the targetAverageValue, the HPA will scale down the number of pods. For example, if you have a deployment with 10 pods and a targetAverageValue of 50 for the number of nginx requests, the HPA will calculate the average number of nginx requests across all 10 pods. If the average is greater than 50, the HPA will scale up the number of pods to handle the increased load. If the average is less than 50, the HPA will scale down the number of pods to reduce resource usage. In summary, the HPA calculates the average value of the metric across all pods in the deployment, and uses that value to determine how to scale the number of pods. Read more: https://kubernetes.io/docs/tasks/run-application/horizontal-pod-autoscale/ A: The Kubernetes Horizontal Pod Autoscaler (HPA) calculates the average value of the metric that you specify as the target value. This means that if you are using a custom metric that scales pods based on the number of nginx requests, the HPA will calculate the average value of that metric across all of the pods in the deployment. For example, let's say you have a deployment with three pods, and each pod is receiving a different number of nginx requests. The HPA will calculate the average value of the metric across all three pods, and use that value to determine whether to scale the deployment up or down. Here's an example of how this might work: Pod 1 receives 10 nginx requests per minute Pod 2 receives 20 nginx requests per minute Pod 3 receives 30 nginx requests per minute The total number of nginx requests for the deployment is 60 (10 + 20 + 30). The average value of the metric is 20 (60 / 3), which is the value that the HPA will use to determine whether to scale the deployment up or down. I hope this helps!
Custom metrics calculation HPA
I was wondering regarding Kubernetes HPA custom metrics HPA how it is calculated with targetAverageValue. If for example I’m using the metric that scales pods based on the number of nginx request then each pod now have is own specific metric and I was wondering if it takes each pod and check regarding its value or if it takes all of their metrics and divide this by the number of the pods?
[ "In Kubernetes HPA, the custom metrics calculation is based on the average value of the metric across all pods. So, if you are using a custom metric that scales pods based on the number of nginx requests, the HPA will take the sum of the metrics from all pods and divide it by the total number of pods to calculate the average value of the metric. This average value will then be compared with the targetAverageValue to determine if the number of pods needs to be scaled up or down.\n", "HPA uses the targetAverageValue to determine how to scale the number of pods in a deployment. The HPA calculates the average value of the metric across all pods in the deployment, and compares it to the targetAverageValue. If the average value is greater than the targetAverageValue, the HPA will scale up the number of pods. If the average value is less than the targetAverageValue, the HPA will scale down the number of pods.\nFor example, if you have a deployment with 10 pods and a targetAverageValue of 50 for the number of nginx requests, the HPA will calculate the average number of nginx requests across all 10 pods. If the average is greater than 50, the HPA will scale up the number of pods to handle the increased load. If the average is less than 50, the HPA will scale down the number of pods to reduce resource usage.\nIn summary, the HPA calculates the average value of the metric across all pods in the deployment, and uses that value to determine how to scale the number of pods.\nRead more: https://kubernetes.io/docs/tasks/run-application/horizontal-pod-autoscale/\n", "The Kubernetes Horizontal Pod Autoscaler (HPA) calculates the average value of the metric that you specify as the target value. This means that if you are using a custom metric that scales pods based on the number of nginx requests, the HPA will calculate the average value of that metric across all of the pods in the deployment.\nFor example, let's say you have a deployment with three pods, and each pod is receiving a different number of nginx requests. The HPA will calculate the average value of the metric across all three pods, and use that value to determine whether to scale the deployment up or down.\nHere's an example of how this might work:\nPod 1 receives 10 nginx requests per minute\nPod 2 receives 20 nginx requests per minute\nPod 3 receives 30 nginx requests per minute\nThe total number of nginx requests for the deployment is 60 (10 + 20 + 30). The average value of the metric is 20 (60 / 3), which is the value that the HPA will use to determine whether to scale the deployment up or down.\nI hope this helps!\n" ]
[ 1, 1, 1 ]
[]
[]
[ "horizontalpodautoscaler", "hpa", "kubernetes" ]
stackoverflow_0074668585_horizontalpodautoscaler_hpa_kubernetes.txt
Q: c++ recursive macro wont compile on MSVC? I got this source code from [https://www.scs.stanford.edu/~dm/blog/va-opt.html]. Using MSVC with C++20 it doesn't compile, but it does compile on other compilers. Why? And how can I fix that? `/* compile with: c++ -std=c++20 -Wall -Werror make_enum.cc -o make_enum */ #include <iostream> #define PARENS () // Rescan macro tokens 256 times #define EXPAND(arg) EXPAND1(EXPAND1(EXPAND1(EXPAND1(arg)))) #define EXPAND1(arg) EXPAND2(EXPAND2(EXPAND2(EXPAND2(arg)))) #define EXPAND2(arg) EXPAND3(EXPAND3(EXPAND3(EXPAND3(arg)))) #define EXPAND3(arg) EXPAND4(EXPAND4(EXPAND4(EXPAND4(arg)))) #define EXPAND4(arg) arg #define FOR_EACH(macro, ...) \ __VA_OPT__(EXPAND(FOR_EACH_HELPER(macro, __VA_ARGS__))) #define FOR_EACH_HELPER(macro, a1, ...) \ macro(a1) \ __VA_OPT__(FOR_EACH_AGAIN PARENS (macro, __VA_ARGS__)) #define FOR_EACH_AGAIN() FOR_EACH_HELPER #define ENUM_CASE(name) case name: return #name; #define MAKE_ENUM(type, ...) \ enum type { \ __VA_ARGS__ \ }; \ constexpr const char * \ to_cstring(type _e) \ { \ using enum type; \ switch (_e) { \ FOR_EACH(ENUM_CASE, __VA_ARGS__) \ default: \ return "unknown"; \ } \ } MAKE_ENUM(MyType, ZERO, ONE, TWO, THREE); void test(MyType e) { std::cout << to_cstring(e) << " = " << e << std::endl; } int main() { test(ZERO); test(ONE); test(TWO); test(THREE); } /* Local Variables: c-macro-pre-processor: "c++ -x c++ -std=c++20 -E -" End: */` I cant figure out for the life of me what the problem is. I've tried modifying the code, to me it seems that __VA_ARGS__ isn't accepted when it should be, or that it can't accept the way the macros are ordered. Here are the errors: 1>make_enum.cc 1>C:\Users\Thomas\source\repos\outoftouch\outoftouch\make_enum.cc(40,1): warning C4003: not enough arguments for function-like macro invocation 'FOR_EACH_HELPER' 1>C:\Users\Thomas\source\repos\outoftouch\outoftouch\make_enum.cc(40,1): warning C4003: not enough arguments for function-like macro invocation 'ENUM_CASE' 1>C:\Users\Thomas\source\repos\outoftouch\outoftouch\make_enum.cc(40,1): error C2059: syntax error: 'case' 1>C:\Users\Thomas\source\repos\outoftouch\outoftouch\make_enum.cc(40,1): error C2065: 'ENUM_CASE': undeclared identifier 1>C:\Users\Thomas\source\repos\outoftouch\outoftouch\make_enum.cc(40,1): error C3861: 'FOR_EACH_HELPER': identifier not found 1>C:\Users\Thomas\source\repos\outoftouch\outoftouch\make_enum.cc(40,1): error C2059: syntax error: ')' 1>C:\Users\Thomas\source\repos\outoftouch\outoftouch\make_enum.cc(40,1): error C2146: syntax error: missing ';' before identifier 'default' 1>C:\Users\Thomas\source\repos\outoftouch\outoftouch\make_enum.cc(40,1): warning C4065: switch statement contains 'default' but no 'case' labels 1>Done building project "outoftouch.vcxproj" -- FAILED. A: The old preprocessor in MSVC is known to contain many problems, see e.g. this article by Microsoft. Their new preprocessor can be used via the /Zc:preprocessor flag, causing the preprocessor to be more standard conform and also closer to what other major compilers do. In this specific case, I think the problem is that the old preprocessor incorrectly expands FOR_EACH_AGAIN in FOR_EACH_HELPER early; it shouldn't, because it is not followed by parentheses. Compare the corresponding section "Rescanning replacement list for macros" in the above mentioned article. The warning "not enough arguments for function-like macro invocation 'FOR_EACH_HELPER'" also hints at that. With /Zc:preprocessor, the code compiles without issues. Example on godbolt.
c++ recursive macro wont compile on MSVC?
I got this source code from [https://www.scs.stanford.edu/~dm/blog/va-opt.html]. Using MSVC with C++20 it doesn't compile, but it does compile on other compilers. Why? And how can I fix that? `/* compile with: c++ -std=c++20 -Wall -Werror make_enum.cc -o make_enum */ #include <iostream> #define PARENS () // Rescan macro tokens 256 times #define EXPAND(arg) EXPAND1(EXPAND1(EXPAND1(EXPAND1(arg)))) #define EXPAND1(arg) EXPAND2(EXPAND2(EXPAND2(EXPAND2(arg)))) #define EXPAND2(arg) EXPAND3(EXPAND3(EXPAND3(EXPAND3(arg)))) #define EXPAND3(arg) EXPAND4(EXPAND4(EXPAND4(EXPAND4(arg)))) #define EXPAND4(arg) arg #define FOR_EACH(macro, ...) \ __VA_OPT__(EXPAND(FOR_EACH_HELPER(macro, __VA_ARGS__))) #define FOR_EACH_HELPER(macro, a1, ...) \ macro(a1) \ __VA_OPT__(FOR_EACH_AGAIN PARENS (macro, __VA_ARGS__)) #define FOR_EACH_AGAIN() FOR_EACH_HELPER #define ENUM_CASE(name) case name: return #name; #define MAKE_ENUM(type, ...) \ enum type { \ __VA_ARGS__ \ }; \ constexpr const char * \ to_cstring(type _e) \ { \ using enum type; \ switch (_e) { \ FOR_EACH(ENUM_CASE, __VA_ARGS__) \ default: \ return "unknown"; \ } \ } MAKE_ENUM(MyType, ZERO, ONE, TWO, THREE); void test(MyType e) { std::cout << to_cstring(e) << " = " << e << std::endl; } int main() { test(ZERO); test(ONE); test(TWO); test(THREE); } /* Local Variables: c-macro-pre-processor: "c++ -x c++ -std=c++20 -E -" End: */` I cant figure out for the life of me what the problem is. I've tried modifying the code, to me it seems that __VA_ARGS__ isn't accepted when it should be, or that it can't accept the way the macros are ordered. Here are the errors: 1>make_enum.cc 1>C:\Users\Thomas\source\repos\outoftouch\outoftouch\make_enum.cc(40,1): warning C4003: not enough arguments for function-like macro invocation 'FOR_EACH_HELPER' 1>C:\Users\Thomas\source\repos\outoftouch\outoftouch\make_enum.cc(40,1): warning C4003: not enough arguments for function-like macro invocation 'ENUM_CASE' 1>C:\Users\Thomas\source\repos\outoftouch\outoftouch\make_enum.cc(40,1): error C2059: syntax error: 'case' 1>C:\Users\Thomas\source\repos\outoftouch\outoftouch\make_enum.cc(40,1): error C2065: 'ENUM_CASE': undeclared identifier 1>C:\Users\Thomas\source\repos\outoftouch\outoftouch\make_enum.cc(40,1): error C3861: 'FOR_EACH_HELPER': identifier not found 1>C:\Users\Thomas\source\repos\outoftouch\outoftouch\make_enum.cc(40,1): error C2059: syntax error: ')' 1>C:\Users\Thomas\source\repos\outoftouch\outoftouch\make_enum.cc(40,1): error C2146: syntax error: missing ';' before identifier 'default' 1>C:\Users\Thomas\source\repos\outoftouch\outoftouch\make_enum.cc(40,1): warning C4065: switch statement contains 'default' but no 'case' labels 1>Done building project "outoftouch.vcxproj" -- FAILED.
[ "The old preprocessor in MSVC is known to contain many problems, see e.g. this article by Microsoft. Their new preprocessor can be used via the /Zc:preprocessor flag, causing the preprocessor to be more standard conform and also closer to what other major compilers do.\nIn this specific case, I think the problem is that the old preprocessor incorrectly expands FOR_EACH_AGAIN in FOR_EACH_HELPER early; it shouldn't, because it is not followed by parentheses. Compare the corresponding section \"Rescanning replacement list for macros\" in the above mentioned article. The warning \"not enough arguments for function-like macro invocation 'FOR_EACH_HELPER'\" also hints at that.\nWith /Zc:preprocessor, the code compiles without issues. Example on godbolt.\n" ]
[ 6 ]
[]
[]
[ "c++", "c++20", "preprocessor" ]
stackoverflow_0074668523_c++_c++20_preprocessor.txt
Q: Filter chain questions I have the following configuration in my Spring application for filter chain: @Configuration protected static class SecurityConfiguration { @Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { http .httpBasic() .and() .authorizeHttpRequests() .requestMatchers("/createuser", "/index.html", "/", "/home", "/login", "/*.css", "/*.js", "/favico.ico").permitAll() .anyRequest().authenticated() .and() .csrf() .csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse()); return http.build(); } } I don't undrestand how it works, and i'd like to add other security constraints, for example match the path /api/admin/* and require the role ADMIN for those requests. How could I do? I've seen the method hasRole(String role) but I don't understand how to use it in my case? A: To add additional security constraints to your Spring application, you can use the FilterChainProxy to specify the rules that should be applied to incoming requests. For example, if you want to require the ADMIN role for requests to the /api/admin/* path, you could add the following configuration to your FilterChainProxy: http.authorizeRequests() .antMatchers("/api/admin/*").hasRole("ADMIN") .anyRequest().authenticated(); In this configuration, the antMatchers method is used to specify the path pattern that should be matched by the security constraint. The hasRole method is then used to specify that only users with the ADMIN role should be allowed to access the matching path. Finally, the anyRequest method is used to apply the authenticated constraint to all other requests, which means that they must be authenticated (but not necessarily have a specific role). You can also use the hasAuthority method instead of hasRole if you want to specify a specific authority (such as a permission or privilege) that a user must have in order to access the matching path.
Filter chain questions
I have the following configuration in my Spring application for filter chain: @Configuration protected static class SecurityConfiguration { @Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { http .httpBasic() .and() .authorizeHttpRequests() .requestMatchers("/createuser", "/index.html", "/", "/home", "/login", "/*.css", "/*.js", "/favico.ico").permitAll() .anyRequest().authenticated() .and() .csrf() .csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse()); return http.build(); } } I don't undrestand how it works, and i'd like to add other security constraints, for example match the path /api/admin/* and require the role ADMIN for those requests. How could I do? I've seen the method hasRole(String role) but I don't understand how to use it in my case?
[ "To add additional security constraints to your Spring application, you can use the FilterChainProxy to specify the rules that should be applied to incoming requests. For example, if you want to require the ADMIN role for requests to the /api/admin/* path, you could add the following configuration to your FilterChainProxy:\nhttp.authorizeRequests()\n.antMatchers(\"/api/admin/*\").hasRole(\"ADMIN\")\n.anyRequest().authenticated();\n\nIn this configuration, the antMatchers method is used to specify the path pattern that should be matched by the security constraint. The hasRole method is then used to specify that only users with the ADMIN role should be allowed to access the matching path. Finally, the anyRequest method is used to apply the authenticated constraint to all other requests, which means that they must be authenticated (but not necessarily have a specific role).\nYou can also use the hasAuthority method instead of hasRole if you want to specify a specific authority (such as a permission or privilege) that a user must have in order to access the matching path.\n" ]
[ 0 ]
[]
[]
[ "spring", "spring_security" ]
stackoverflow_0074668689_spring_spring_security.txt
Q: JavaScript - React useEffect I want to call a component and render it once on button click. So if I pressed the button again it would render however does not constantly try and re render itself. At the moment, I am passing a function to the component and calling at the end of the useEffect. However this seems to not render anything. Here is what I have in my App.js function App() { const [open, setOpen] = React.useState(false); const [dataFormat, setDataFormat] = React.useState(""); const openData = () => { setOpen(true); }; const closeData = () =>{ setOpen(false); } const changeDataFormat = (selectedOption) => { console.log(selectedOption); setDataFormat(selectedOption); }; return ( <main className="App"> <h1>Film Management</h1> <SelectDataFormat changeDataFormat={changeDataFormat} /> <button onClick={openData}>Show Films</button> <table border="1"> <thead> <tr> <th>Title</th> <th>Year</th> <th>Director</th> <th>Stars</th> <th>Review</th> </tr> </thead> <tbody>{open && <FilmTableRows closeData={closeData} dataFormat={dataFormat} />}</tbody> </table> </main> ); } And this is the component I want to render function FilmTableRows(props) { const convert = require("xml-js"); const dataFormat = props.dataFormat; const [filmList, setFilmList] = useState([]); const baseURL = "http://localhost:8080/FilmRestful/filmapi"; const getJson = () => { let config = { headers: { "data-type": "json", "Content-type": "application/json", }, }; axios .get(baseURL, config) .then((res) => { const resData = res.data; setFilmList(resData); }) .catch((err) => {}); }; const getXML = () => { let config = { headers: { "data-type": "xml", "Content-type": "application/xml", // accept: "application/xml", }, }; axios .get(baseURL, config) .then((res) => { let newList = []; const resData = JSON.parse( convert.xml2json(res.data, { compact: true, spaces: 2 }) ); resData.films.film.forEach((f) => { const film = new Film( f.id, f.title, f.year, f.director, f.stars, f.review ); newList = newList.concat(film); }); setFilmList(newList); }) .catch((err) => {}); }; const getString = () => { let config = { headers: { "data-type": "string", "Content-type": "application/html", // accept: "application/xml", }, }; axios .get(baseURL, config) .then((res) => { setFilmList(res.data); }) .catch((err) => {}); }; useEffect(() => { switch (dataFormat.value) { case "json": getJson(); break; case "xml": getXML(); break; default: getString(); } }); const child = filmList.map((el, index) => { return ( <tr key={index}> <td>{el.title}</td> <td>{el.year}</td> <td>{el.director}</td> <td>{el.stars}</td> <td>{el.review}</td> </tr> ); }); return <>{filmList && child}</>; } A: Quick fix const [reload, setReload] = useState(false); // toggle reload const refresh = () => { setReload(r => !r); }; const openData = () => { setOpen(true); // if you want the same button "Show Films" to refersh if (open) { refresh(); } }; return ( ... <button onClick={toggleOpen}>Show Films</button> // if you want to use seperate refresh button // <button onClick={refresh}>Refresh</button> ... <tbody>{open && <FilmTableRows reload={reload} closeData={closeData} dataFormat={dataFormat} />}</tbody> Inside FilmTableRows use reload to trigger fetch // include depedency to stop fetching on every render useEffect(() => { switch (dataFormat.value) { case "json": getJson(); break; case "xml": getXML(); break; default: getString(); } }, [dataFormat.value, props.reload]); Ideally you should move the fetch function in the parent, so that on refresh fetch data can be called from the event handler You can also use a filter state instead of reload flag and use the filter as a param when making an api call Hope it helps you towards finding better solution, you can also read the new React beta docs, they will help you to write better code. Cheers A: Here is an Example Code import * as React from 'react'; function App() { //toggle the state (false by default) const [toggle, setToggle] = React.useState(false) //Component to be displayed on button click const FilmTableRows = () =>{ return( <div> <h1>Film</h1> <p>FilmTableRows</p> </div> ) } return ( <div> <h1>Hello StackBlitz!</h1> {/* basically switches the value of toggle on every click */} <button onClick={() => setToggle(!toggle)}>Click Me</button> {toggle && <FilmTableRows/>} </div> ); } export default App
JavaScript - React useEffect
I want to call a component and render it once on button click. So if I pressed the button again it would render however does not constantly try and re render itself. At the moment, I am passing a function to the component and calling at the end of the useEffect. However this seems to not render anything. Here is what I have in my App.js function App() { const [open, setOpen] = React.useState(false); const [dataFormat, setDataFormat] = React.useState(""); const openData = () => { setOpen(true); }; const closeData = () =>{ setOpen(false); } const changeDataFormat = (selectedOption) => { console.log(selectedOption); setDataFormat(selectedOption); }; return ( <main className="App"> <h1>Film Management</h1> <SelectDataFormat changeDataFormat={changeDataFormat} /> <button onClick={openData}>Show Films</button> <table border="1"> <thead> <tr> <th>Title</th> <th>Year</th> <th>Director</th> <th>Stars</th> <th>Review</th> </tr> </thead> <tbody>{open && <FilmTableRows closeData={closeData} dataFormat={dataFormat} />}</tbody> </table> </main> ); } And this is the component I want to render function FilmTableRows(props) { const convert = require("xml-js"); const dataFormat = props.dataFormat; const [filmList, setFilmList] = useState([]); const baseURL = "http://localhost:8080/FilmRestful/filmapi"; const getJson = () => { let config = { headers: { "data-type": "json", "Content-type": "application/json", }, }; axios .get(baseURL, config) .then((res) => { const resData = res.data; setFilmList(resData); }) .catch((err) => {}); }; const getXML = () => { let config = { headers: { "data-type": "xml", "Content-type": "application/xml", // accept: "application/xml", }, }; axios .get(baseURL, config) .then((res) => { let newList = []; const resData = JSON.parse( convert.xml2json(res.data, { compact: true, spaces: 2 }) ); resData.films.film.forEach((f) => { const film = new Film( f.id, f.title, f.year, f.director, f.stars, f.review ); newList = newList.concat(film); }); setFilmList(newList); }) .catch((err) => {}); }; const getString = () => { let config = { headers: { "data-type": "string", "Content-type": "application/html", // accept: "application/xml", }, }; axios .get(baseURL, config) .then((res) => { setFilmList(res.data); }) .catch((err) => {}); }; useEffect(() => { switch (dataFormat.value) { case "json": getJson(); break; case "xml": getXML(); break; default: getString(); } }); const child = filmList.map((el, index) => { return ( <tr key={index}> <td>{el.title}</td> <td>{el.year}</td> <td>{el.director}</td> <td>{el.stars}</td> <td>{el.review}</td> </tr> ); }); return <>{filmList && child}</>; }
[ "Quick fix\n const [reload, setReload] = useState(false);\n\n // toggle reload \n const refresh = () => {\n setReload(r => !r);\n };\n\n const openData = () => {\n setOpen(true);\n // if you want the same button \"Show Films\" to refersh\n if (open) {\n refresh();\n }\n };\n\n return (\n ...\n <button onClick={toggleOpen}>Show Films</button>\n // if you want to use seperate refresh button\n // <button onClick={refresh}>Refresh</button>\n ...\n <tbody>{open && <FilmTableRows reload={reload} closeData={closeData} dataFormat={dataFormat} />}</tbody>\n \n\nInside FilmTableRows use reload to trigger fetch\n // include depedency to stop fetching on every render\n useEffect(() => {\n switch (dataFormat.value) {\n case \"json\":\n getJson();\n break;\n case \"xml\":\n getXML();\n break;\n default:\n getString();\n }\n }, [dataFormat.value, props.reload]);\n\n\nIdeally you should move the fetch function in the parent,\nso that on refresh fetch data can be called from the event handler\n\nYou can also use a filter state instead of reload flag and use the filter as a param when making an api call\n\n\nHope it helps you towards finding better solution, you can also read the new React beta docs, they will help you to write better code.\nCheers\n", "Here is an Example Code\nimport * as React from 'react';\n\nfunction App() {\n //toggle the state (false by default)\n const [toggle, setToggle] = React.useState(false)\n\n //Component to be displayed on button click\n const FilmTableRows = () =>{\n return(\n <div>\n <h1>Film</h1>\n <p>FilmTableRows</p>\n </div>\n )\n }\n return (\n <div>\n <h1>Hello StackBlitz!</h1>\n {/* basically switches the value of toggle on every click */}\n <button onClick={() => setToggle(!toggle)}>Click Me</button>\n {toggle && <FilmTableRows/>}\n </div>\n );\n}\nexport default App\n\n" ]
[ 0, 0 ]
[]
[]
[ "javascript", "reactjs" ]
stackoverflow_0074668211_javascript_reactjs.txt
Q: CMake `add_executable` and `target_link_libraries` throwing linking error I am following Asio tutorial by javidx9 and using CMake to link my executables and libraries. Complete source code is available in this repository. I am facing a linking error with the executables Server.cpp and Client.cpp in folder - Source ---- Main -------- Server.cpp -------- Client.cpp In the main function if I create the class object CustomServer which inherits from ServerInterface int main () { CustomServer server(60000); return 0; } I get following linking error: Undefined symbols for architecture x86_64: "Tachys::Networking::ServerInterface<CustomMessageTypes>::ServerInterface(unsigned short)", referenced from: CustomServer::CustomServer(unsigned short) in Server.cpp.o "Tachys::Networking::ServerInterface<CustomMessageTypes>::~ServerInterface()", referenced from: CustomServer::~CustomServer() in Server.cpp.o ld: symbol(s) not found for architecture x86_64 clang: error: linker command failed with exit code 1 (use -v to see invocation) make[2]: *** [Source/Main/exe_server] Error 1 make[1]: *** [Source/Main/CMakeFiles/exe_server.dir/all] Error 2 make: *** [all] Error 2 But I have used add_executable in the CMakeList.txt at: - Source ---- Main -------- CMakeLists.txt and target_link_libraries in the main CMakeLists.txt at: - CMakeLists.txt It seems like these are the only two functions required to create an executable and link it to a created library but I am still getting this linking error and not able to figure out what to change. Please help. A: You have template ServerInterface<CustomMessageTypes> implemented in a source file. Either move the implementation to a header, which is usually what you do, or provide the symbol ServerInterface<CustomMessageTypes> by explicitly instantianting the template in source file. See Why can templates only be implemented in the header file? and other endless online resources. __Start__ Identifiers starting with double underscores are reserved. You are can't use them in your code.
CMake `add_executable` and `target_link_libraries` throwing linking error
I am following Asio tutorial by javidx9 and using CMake to link my executables and libraries. Complete source code is available in this repository. I am facing a linking error with the executables Server.cpp and Client.cpp in folder - Source ---- Main -------- Server.cpp -------- Client.cpp In the main function if I create the class object CustomServer which inherits from ServerInterface int main () { CustomServer server(60000); return 0; } I get following linking error: Undefined symbols for architecture x86_64: "Tachys::Networking::ServerInterface<CustomMessageTypes>::ServerInterface(unsigned short)", referenced from: CustomServer::CustomServer(unsigned short) in Server.cpp.o "Tachys::Networking::ServerInterface<CustomMessageTypes>::~ServerInterface()", referenced from: CustomServer::~CustomServer() in Server.cpp.o ld: symbol(s) not found for architecture x86_64 clang: error: linker command failed with exit code 1 (use -v to see invocation) make[2]: *** [Source/Main/exe_server] Error 1 make[1]: *** [Source/Main/CMakeFiles/exe_server.dir/all] Error 2 make: *** [all] Error 2 But I have used add_executable in the CMakeList.txt at: - Source ---- Main -------- CMakeLists.txt and target_link_libraries in the main CMakeLists.txt at: - CMakeLists.txt It seems like these are the only two functions required to create an executable and link it to a created library but I am still getting this linking error and not able to figure out what to change. Please help.
[ "You have template ServerInterface<CustomMessageTypes> implemented in a source file. Either move the implementation to a header, which is usually what you do, or provide the symbol ServerInterface<CustomMessageTypes> by explicitly instantianting the template in source file. See Why can templates only be implemented in the header file? and other endless online resources.\n\n__Start__ \n\n\nIdentifiers starting with double underscores are reserved. You are can't use them in your code.\n" ]
[ 0 ]
[]
[]
[ "c++", "cmake", "linker", "target_link_libraries" ]
stackoverflow_0074668614_c++_cmake_linker_target_link_libraries.txt
Q: How to consume an XML feed and store into database? How do I consume such an XML file from the web (it comes from a link): <XmlSports CreateDate="2022-12-03T14:19:44.7683754Z"> <Sport Name="eSports" ID="2357"> <Event Name="NBA2K, NBA League" ID="66838" IsLive="false" CategoryID="9357"> <Match Name="Boston Celtics (ADONIS)" ID="2710124" StartDate="2022-12-03T13:52:00" MatchType="Live"> <Bet Name="Spread" ID="43825125" IsLive="true"> <Odd Name="1" ID="297296222" Value="1.90" SpecialBetValue="5.5"/> <Odd Name="2" ID="297296223" Value="1.83" SpecialBetValue="5.5"/> <Odd Name="1" ID="297294470" Value="1.83" SpecialBetValue="6.5"/> <Odd Name="2" ID="297294469" Value="1.90" SpecialBetValue="6.5"/> </Bet> </Match> <Match Name="Phoenix Suns (ADONIS)" ID="2710163" StartDate="2022-12-03T14:24:00" MatchType="PreMatch"> <Bet Name="Money Line" ID="43825684" IsLive="false"> <Odd Name="1" ID="297292684" Value="1.43"/> <Odd Name="2" ID="297292685" Value="2.65"/> </Bet> <Bet Name="Spread" ID="43825682" IsLive="false"> <Odd Name="1" ID="297295228" Value="1.83" SpecialBetValue="-4.5"/> <Odd Name="2" ID="297295227" Value="1.89" SpecialBetValue="-4.5"/> </Bet> <Bet Name="Total" ID="43825683" IsLive="false"> <Odd Name="Over" ID="297292687" Value="1.83" SpecialBetValue="119.5"/> <Odd Name="Under" ID="297292686" Value="1.89" SpecialBetValue="119.5"/> </Bet> </Match> </Event> </Sport> </XmlSports> I need to pull it every minute and store the data in a SQL database... should I also delete the old data and store the new data every 60 seconds? Honestly, I don't know how to do that since I'm still a newbie in programming. I guess I need to use some kind of xml serialization but I have no idea where to start from. I looked up around the web for solutions about converting xml into C# models which to store into the database afterwards. Any help and advice would be highly appreciated! Thank you! A: Open visual studio 2022. Create a new project as Worker Service with name xmlstore Create a new class with name Sports and paste below code using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Xml.Serialization; namespace XmlParser.Models; [XmlRoot(ElementName = "Odd")] public class Odd { [XmlAttribute(AttributeName = "Name")] public string Name { get; set; } [XmlAttribute(AttributeName = "ID")] public string ID { get; set; } [XmlAttribute(AttributeName = "Value")] public string Value { get; set; } [XmlAttribute(AttributeName = "SpecialBetValue")] public string SpecialBetValue { get; set; } } [XmlRoot(ElementName = "Bet")] public class Bet { [XmlElement(ElementName = "Odd")] public List<Odd> Odd { get; set; } [XmlAttribute(AttributeName = "Name")] public string Name { get; set; } [XmlAttribute(AttributeName = "ID")] public string ID { get; set; } [XmlAttribute(AttributeName = "IsLive")] public string IsLive { get; set; } } [XmlRoot(ElementName = "Match")] public class Match { [XmlElement(ElementName = "Bet")] public List<Bet> Bet { get; set; } [XmlAttribute(AttributeName = "Name")] public string Name { get; set; } [XmlAttribute(AttributeName = "ID")] public string ID { get; set; } [XmlAttribute(AttributeName = "StartDate")] public string StartDate { get; set; } [XmlAttribute(AttributeName = "MatchType")] public string MatchType { get; set; } } [XmlRoot(ElementName = "Event")] public class Event { [XmlElement(ElementName = "Match")] public List<Match> Match { get; set; } [XmlAttribute(AttributeName = "Name")] public string Name { get; set; } [XmlAttribute(AttributeName = "ID")] public string ID { get; set; } [XmlAttribute(AttributeName = "IsLive")] public string IsLive { get; set; } [XmlAttribute(AttributeName = "CategoryID")] public string CategoryID { get; set; } } [XmlRoot(ElementName = "Sport")] public class Sport { [XmlElement(ElementName = "Event")] public Event Event { get; set; } [XmlAttribute(AttributeName = "Name")] public string Name { get; set; } [XmlAttribute(AttributeName = "ID")] public string ID { get; set; } } [XmlRoot(ElementName = "XmlSports")] public class Sports { [XmlElement(ElementName = "Sport")] public Sport Sport { get; set; } [XmlAttribute(AttributeName = "CreateDate")] public string CreateDate { get; set; } } Open class Worker.cs and paste below code using System.Xml.Serialization; using XmlParser.Models; namespace XmlParser { public class Worker : BackgroundService { private readonly ILogger<Worker> _logger; private string xml = @"<XmlSports CreateDate=""2022-12-03T14:19:44.7683754Z""> <Sport Name=""eSports"" ID=""2357""> <Event Name=""NBA2K, NBA League"" ID=""66838"" IsLive=""false"" CategoryID=""9357""> <Match Name=""Boston Celtics (ADONIS)"" ID=""2710124"" StartDate=""2022-12-03T13:52:00"" MatchType=""Live""> <Bet Name=""Spread"" ID=""43825125"" IsLive=""true""> <Odd Name=""1"" ID=""297296222"" Value=""1.90"" SpecialBetValue=""5.5""/> <Odd Name=""2"" ID=""297296223"" Value=""1.83"" SpecialBetValue=""5.5""/> <Odd Name=""1"" ID=""297294470"" Value=""1.83"" SpecialBetValue=""6.5""/> <Odd Name=""2"" ID=""297294469"" Value=""1.90"" SpecialBetValue=""6.5""/> </Bet> </Match> <Match Name=""Phoenix Suns (ADONIS)"" ID=""2710163"" StartDate=""2022-12-03T14:24:00"" MatchType=""PreMatch""> <Bet Name=""Money Line"" ID=""43825684"" IsLive=""false""> <Odd Name=""1"" ID=""297292684"" Value=""1.43""/> <Odd Name=""2"" ID=""297292685"" Value=""2.65""/> </Bet> <Bet Name=""Spread"" ID=""43825682"" IsLive=""false""> <Odd Name=""1"" ID=""297295228"" Value=""1.83"" SpecialBetValue=""-4.5""/> <Odd Name=""2"" ID=""297295227"" Value=""1.89"" SpecialBetValue=""-4.5""/> </Bet> <Bet Name=""Total"" ID=""43825683"" IsLive=""false""> <Odd Name=""Over"" ID=""297292687"" Value=""1.83"" SpecialBetValue=""119.5""/> <Odd Name=""Under"" ID=""297292686"" Value=""1.89"" SpecialBetValue=""119.5""/> </Bet> </Match> </Event> </Sport> </XmlSports>"; public Worker(ILogger<Worker> logger) { _logger = logger; } protected override async Task ExecuteAsync(CancellationToken stoppingToken) { while (!stoppingToken.IsCancellationRequested) { // convert your xml to class type XmlSerializer serializer = new XmlSerializer(typeof(Sports)); using (StringReader reader = new StringReader(xml)) { var sports = (Sports)serializer.Deserialize(reader); await StoreIntoDatabaseAsync(sports); } _logger.LogInformation("Worker running at: {time}", DateTimeOffset.Now); //every 60 second await Task.Delay(60000, stoppingToken); } } private async Task StoreIntoDatabaseAsync(Sports sports) { // store data into database } } }
How to consume an XML feed and store into database?
How do I consume such an XML file from the web (it comes from a link): <XmlSports CreateDate="2022-12-03T14:19:44.7683754Z"> <Sport Name="eSports" ID="2357"> <Event Name="NBA2K, NBA League" ID="66838" IsLive="false" CategoryID="9357"> <Match Name="Boston Celtics (ADONIS)" ID="2710124" StartDate="2022-12-03T13:52:00" MatchType="Live"> <Bet Name="Spread" ID="43825125" IsLive="true"> <Odd Name="1" ID="297296222" Value="1.90" SpecialBetValue="5.5"/> <Odd Name="2" ID="297296223" Value="1.83" SpecialBetValue="5.5"/> <Odd Name="1" ID="297294470" Value="1.83" SpecialBetValue="6.5"/> <Odd Name="2" ID="297294469" Value="1.90" SpecialBetValue="6.5"/> </Bet> </Match> <Match Name="Phoenix Suns (ADONIS)" ID="2710163" StartDate="2022-12-03T14:24:00" MatchType="PreMatch"> <Bet Name="Money Line" ID="43825684" IsLive="false"> <Odd Name="1" ID="297292684" Value="1.43"/> <Odd Name="2" ID="297292685" Value="2.65"/> </Bet> <Bet Name="Spread" ID="43825682" IsLive="false"> <Odd Name="1" ID="297295228" Value="1.83" SpecialBetValue="-4.5"/> <Odd Name="2" ID="297295227" Value="1.89" SpecialBetValue="-4.5"/> </Bet> <Bet Name="Total" ID="43825683" IsLive="false"> <Odd Name="Over" ID="297292687" Value="1.83" SpecialBetValue="119.5"/> <Odd Name="Under" ID="297292686" Value="1.89" SpecialBetValue="119.5"/> </Bet> </Match> </Event> </Sport> </XmlSports> I need to pull it every minute and store the data in a SQL database... should I also delete the old data and store the new data every 60 seconds? Honestly, I don't know how to do that since I'm still a newbie in programming. I guess I need to use some kind of xml serialization but I have no idea where to start from. I looked up around the web for solutions about converting xml into C# models which to store into the database afterwards. Any help and advice would be highly appreciated! Thank you!
[ "\nOpen visual studio 2022. Create a new project as Worker Service with name xmlstore\n\nCreate a new class with name Sports and paste below code\nusing System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Threading.Tasks;\nusing System.Xml.Serialization;\n\nnamespace XmlParser.Models;\n\n[XmlRoot(ElementName = \"Odd\")]\npublic class Odd\n{\n [XmlAttribute(AttributeName = \"Name\")]\n public string Name { get; set; }\n [XmlAttribute(AttributeName = \"ID\")]\n public string ID { get; set; }\n [XmlAttribute(AttributeName = \"Value\")]\n public string Value { get; set; }\n [XmlAttribute(AttributeName = \"SpecialBetValue\")]\n public string SpecialBetValue { get; set; }\n}\n\n[XmlRoot(ElementName = \"Bet\")]\npublic class Bet\n{\n [XmlElement(ElementName = \"Odd\")]\n public List<Odd> Odd { get; set; }\n [XmlAttribute(AttributeName = \"Name\")]\n public string Name { get; set; }\n [XmlAttribute(AttributeName = \"ID\")]\n public string ID { get; set; }\n [XmlAttribute(AttributeName = \"IsLive\")]\n public string IsLive { get; set; }\n}\n\n[XmlRoot(ElementName = \"Match\")]\npublic class Match\n{\n [XmlElement(ElementName = \"Bet\")]\n public List<Bet> Bet { get; set; }\n [XmlAttribute(AttributeName = \"Name\")]\n public string Name { get; set; }\n [XmlAttribute(AttributeName = \"ID\")]\n public string ID { get; set; }\n [XmlAttribute(AttributeName = \"StartDate\")]\n public string StartDate { get; set; }\n [XmlAttribute(AttributeName = \"MatchType\")]\n public string MatchType { get; set; }\n}\n\n[XmlRoot(ElementName = \"Event\")]\npublic class Event\n{\n [XmlElement(ElementName = \"Match\")]\n public List<Match> Match { get; set; }\n [XmlAttribute(AttributeName = \"Name\")]\n public string Name { get; set; }\n [XmlAttribute(AttributeName = \"ID\")]\n public string ID { get; set; }\n [XmlAttribute(AttributeName = \"IsLive\")]\n public string IsLive { get; set; }\n [XmlAttribute(AttributeName = \"CategoryID\")]\n public string CategoryID { get; set; }\n}\n\n[XmlRoot(ElementName = \"Sport\")]\npublic class Sport\n{\n [XmlElement(ElementName = \"Event\")]\n public Event Event { get; set; }\n [XmlAttribute(AttributeName = \"Name\")]\n public string Name { get; set; }\n [XmlAttribute(AttributeName = \"ID\")]\n public string ID { get; set; }\n}\n\n[XmlRoot(ElementName = \"XmlSports\")]\npublic class Sports\n{\n [XmlElement(ElementName = \"Sport\")]\n public Sport Sport { get; set; }\n [XmlAttribute(AttributeName = \"CreateDate\")]\n public string CreateDate { get; set; }\n}\n\n\n\n\nOpen class Worker.cs and paste below code\n\n\nusing System.Xml.Serialization;\nusing XmlParser.Models;\n\nnamespace XmlParser\n{\n public class Worker : BackgroundService\n {\n private readonly ILogger<Worker> _logger;\n private string xml = @\"<XmlSports CreateDate=\"\"2022-12-03T14:19:44.7683754Z\"\">\n <Sport Name=\"\"eSports\"\" ID=\"\"2357\"\">\n <Event Name=\"\"NBA2K, NBA League\"\" ID=\"\"66838\"\" IsLive=\"\"false\"\" CategoryID=\"\"9357\"\">\n <Match Name=\"\"Boston Celtics (ADONIS)\"\" ID=\"\"2710124\"\" StartDate=\"\"2022-12-03T13:52:00\"\" MatchType=\"\"Live\"\">\n <Bet Name=\"\"Spread\"\" ID=\"\"43825125\"\" IsLive=\"\"true\"\">\n <Odd Name=\"\"1\"\" ID=\"\"297296222\"\" Value=\"\"1.90\"\" SpecialBetValue=\"\"5.5\"\"/>\n <Odd Name=\"\"2\"\" ID=\"\"297296223\"\" Value=\"\"1.83\"\" SpecialBetValue=\"\"5.5\"\"/>\n <Odd Name=\"\"1\"\" ID=\"\"297294470\"\" Value=\"\"1.83\"\" SpecialBetValue=\"\"6.5\"\"/>\n <Odd Name=\"\"2\"\" ID=\"\"297294469\"\" Value=\"\"1.90\"\" SpecialBetValue=\"\"6.5\"\"/>\n </Bet>\n </Match>\n <Match Name=\"\"Phoenix Suns (ADONIS)\"\" ID=\"\"2710163\"\" StartDate=\"\"2022-12-03T14:24:00\"\" MatchType=\"\"PreMatch\"\">\n <Bet Name=\"\"Money Line\"\" ID=\"\"43825684\"\" IsLive=\"\"false\"\">\n <Odd Name=\"\"1\"\" ID=\"\"297292684\"\" Value=\"\"1.43\"\"/>\n <Odd Name=\"\"2\"\" ID=\"\"297292685\"\" Value=\"\"2.65\"\"/>\n </Bet>\n <Bet Name=\"\"Spread\"\" ID=\"\"43825682\"\" IsLive=\"\"false\"\">\n <Odd Name=\"\"1\"\" ID=\"\"297295228\"\" Value=\"\"1.83\"\" SpecialBetValue=\"\"-4.5\"\"/>\n <Odd Name=\"\"2\"\" ID=\"\"297295227\"\" Value=\"\"1.89\"\" SpecialBetValue=\"\"-4.5\"\"/>\n </Bet>\n <Bet Name=\"\"Total\"\" ID=\"\"43825683\"\" IsLive=\"\"false\"\">\n <Odd Name=\"\"Over\"\" ID=\"\"297292687\"\" Value=\"\"1.83\"\" SpecialBetValue=\"\"119.5\"\"/>\n <Odd Name=\"\"Under\"\" ID=\"\"297292686\"\" Value=\"\"1.89\"\" SpecialBetValue=\"\"119.5\"\"/>\n </Bet>\n </Match>\n </Event>\n </Sport>\n</XmlSports>\";\n\n public Worker(ILogger<Worker> logger)\n {\n _logger = logger;\n }\n\n protected override async Task ExecuteAsync(CancellationToken stoppingToken)\n {\n while (!stoppingToken.IsCancellationRequested)\n {\n // convert your xml to class type\n XmlSerializer serializer = new XmlSerializer(typeof(Sports));\n using (StringReader reader = new StringReader(xml))\n {\n var sports = (Sports)serializer.Deserialize(reader);\n await StoreIntoDatabaseAsync(sports);\n }\n _logger.LogInformation(\"Worker running at: {time}\", DateTimeOffset.Now);\n\n //every 60 second\n await Task.Delay(60000, stoppingToken);\n }\n }\n\n private async Task StoreIntoDatabaseAsync(Sports sports)\n {\n // store data into database\n }\n }\n}\n\n" ]
[ 1 ]
[]
[]
[ "api", "c#", "web", "xml" ]
stackoverflow_0074667730_api_c#_web_xml.txt
Q: Incorrect Output to .csv file I am getting an error when I try to export the output to a .csv file. import csv import random header = ['Results'] file = open("populationModel5.csv", "w") import random startPopulation = 50 infantMortality = 25 agriculture = 5 disasterChance = 10 fertilityx = 18 fertilityy = 35 food = 0 peopleDictionary = [] class Person: def __init__(self, age): self.gender = random.randint(0,1) self.age = age def harvest(food, agriculture): ablePeople = 0 for person in peopleDictionary: if person.age > 8: ablePeople +=1 food += ablePeople * agriculture if food < len(peopleDictionary): del peopleDictionary[0:int(len(peopleDictionary)-food)] food = 0 else: food -= len(peopleDictionary) def reproduce(fertilityx, fertilityy): for person in peopleDictionary: if person.gender == 1: if person.age > fertilityx: if person.age < fertilityy: if random.randint(0,5)==1: peopleDictionary.append(Person(0)) def beginSim(): for x in range(startPopulation): peopleDictionary.append(Person(random.randint(18,50))) def runYear(food, agriculture, fertilityx, fertilityy): harvest(food, agriculture) reproduce(fertilityx, fertilityy) for person in peopleDictionary: if person.age > 80: peopleDictionary.remove(person) else: person.age +=1 print(len(peopleDictionary)) beginSim() while len(peopleDictionary)<100000 and len(peopleDictionary) > 1: runYear(food, agriculture, fertilityx, fertilityy) print(peopleDictionary) db = csv.writer(file) db.writerow(header) for person in peopleDictionary: db.writerow([person]) file.close() I expected the output to export to a .csv file. The code outputs perfectly in the interpreter but it gives the following error when I export it: [<main.Person object at 0x0000025895762278>, <main.Person object at 0x0000025895770C18>, <main.Person object at 0x0000025894F37940>, A: It looks like the error is happening because you're trying to write an object of the Person class to the CSV file, but the csv.writerow method expects a string or a list of strings as input. To fix the error, you can modify your code to convert the Person object to a string before writing it to the CSV file. One way to do this is to define a str method for the Person class, which will be called whenever you try to convert an instance of the class to a string. Here's an example of how you could define the str method for the Person class: class Person: def __init__(self, age): self.gender = random.randint(0,1) self.age = age def __str__(self): return "age: {}, gender: {}".format(self.age, self.gender) With this method defined, you can write the Person objects to the CSV file like this: for person in peopleDictionary: db.writerow([str(person)]) This will convert the Person objects to strings using the str method, and then write the strings to the CSV file.
Incorrect Output to .csv file
I am getting an error when I try to export the output to a .csv file. import csv import random header = ['Results'] file = open("populationModel5.csv", "w") import random startPopulation = 50 infantMortality = 25 agriculture = 5 disasterChance = 10 fertilityx = 18 fertilityy = 35 food = 0 peopleDictionary = [] class Person: def __init__(self, age): self.gender = random.randint(0,1) self.age = age def harvest(food, agriculture): ablePeople = 0 for person in peopleDictionary: if person.age > 8: ablePeople +=1 food += ablePeople * agriculture if food < len(peopleDictionary): del peopleDictionary[0:int(len(peopleDictionary)-food)] food = 0 else: food -= len(peopleDictionary) def reproduce(fertilityx, fertilityy): for person in peopleDictionary: if person.gender == 1: if person.age > fertilityx: if person.age < fertilityy: if random.randint(0,5)==1: peopleDictionary.append(Person(0)) def beginSim(): for x in range(startPopulation): peopleDictionary.append(Person(random.randint(18,50))) def runYear(food, agriculture, fertilityx, fertilityy): harvest(food, agriculture) reproduce(fertilityx, fertilityy) for person in peopleDictionary: if person.age > 80: peopleDictionary.remove(person) else: person.age +=1 print(len(peopleDictionary)) beginSim() while len(peopleDictionary)<100000 and len(peopleDictionary) > 1: runYear(food, agriculture, fertilityx, fertilityy) print(peopleDictionary) db = csv.writer(file) db.writerow(header) for person in peopleDictionary: db.writerow([person]) file.close() I expected the output to export to a .csv file. The code outputs perfectly in the interpreter but it gives the following error when I export it: [<main.Person object at 0x0000025895762278>, <main.Person object at 0x0000025895770C18>, <main.Person object at 0x0000025894F37940>,
[ "It looks like the error is happening because you're trying to write an object of the Person class to the CSV file, but the csv.writerow method expects a string or a list of strings as input.\nTo fix the error, you can modify your code to convert the Person object to a string before writing it to the CSV file. One way to do this is to define a str method for the Person class, which will be called whenever you try to convert an instance of the class to a string.\nHere's an example of how you could define the str method for the Person class:\nclass Person:\ndef __init__(self, age):\n self.gender = random.randint(0,1)\n self.age = age\n\ndef __str__(self):\n return \"age: {}, gender: {}\".format(self.age, self.gender)\n\nWith this method defined, you can write the Person objects to the CSV file like this:\nfor person in peopleDictionary:\ndb.writerow([str(person)])\n\nThis will convert the Person objects to strings using the str method, and then write the strings to the CSV file.\n" ]
[ 0 ]
[]
[]
[ "csv", "python" ]
stackoverflow_0074667718_csv_python.txt
Q: Loop through outlook mails with python I receive a daily mail with the subject “XYZ” containing a CSV file with some information. I also got this python code which goes into my outlook account, looks for the mail with the subject “XYZ” and extracts the attachment and finally extends a certain database with the new information from the attachment. However, this code only gets the most recent email so that I need to run that code daily to keep it updated. If I’m not able to do that daily, lets say because I am on vacation, my database is going to miss some information from previous days. outlook = Dispatch("Outlook.Application").GetNamespace("MAPI") inbox = outlook.GetDefaultFolder("6") all_inbox = inbox.Items val_date = date.date.today() sub_today = 'XYZ' att_today = 'XYZ.csv' """ Look for the email with the given subject and the attachment name """ for msg in all_inbox: if msg.Subject == sub_today: break for att in msg.Attachments: if att.FileName == att_today: break """ save the update and extend the database """ att.SaveAsFile('U:/' + 'XYZ.csv') read_path = "U:/" write_path = "V:/Special_Path/" df_Update = pd.read_csv(read_path + 'XYZ.csv',parse_dates=['Date'],skiprows=2) del df_Update['Unnamed: 14'] df_DB_Old = pd.read_csv(write_path + 'DataBase_XYZ.csv',parse_dates=['Date']) DB_DatumMax = df_DB_Old['Date'].max() Upd_DatumMax = df_Update['Date'].max() if df_DB_Old['Date'].isin(pd.Series(Upd_DatumMax)).sum()>0: print(' ') print('Date already exists!') print(' ') input("press enter to continue...") # exit() sys.exit() else: df_DB_New = pd.concat([df_DB_Old, df_Update]) df_DB_New.to_csv(write_path + 'XYZ.csv',index=False) Now I would like to extend that code, so that it checks when the last time was the database was updated and then it should extract the information from all the emails with subject “XYZ” starting from the day it was last updated. Example: I run the code on the 01.10.2022 Im on vacation for 2 days The database was last updated on 01.10 On 04.10 im back and I run the code again. The code will look for the email from 02.10 & from 03.10 and of course also for the latest mail 04.10 extract the csv and extend the database My first idea is to create a new folder where all the mails with subject “XYZ” automatically are moved. [Done!] Now I would check for the latest Date in my database. And now I have no clue how to proceed. I guess I need to loop though my new folder but only starting with mails which havent been extracted to the databse. A: Firstly, there is no reason to loop though all messages in a folder - that would be extremely slow in folders with thousands of messages, especially if the cached mode is off. Use Items.Restrict or Items.Find/FindNext - let the store provider do the heavy lifting for you. You will be able to specify a restriction on the Subject and/or ReceivedTime property". See the examples at https://learn.microsoft.com/en-us/office/vba/api/outlook.items.restrict
Loop through outlook mails with python
I receive a daily mail with the subject “XYZ” containing a CSV file with some information. I also got this python code which goes into my outlook account, looks for the mail with the subject “XYZ” and extracts the attachment and finally extends a certain database with the new information from the attachment. However, this code only gets the most recent email so that I need to run that code daily to keep it updated. If I’m not able to do that daily, lets say because I am on vacation, my database is going to miss some information from previous days. outlook = Dispatch("Outlook.Application").GetNamespace("MAPI") inbox = outlook.GetDefaultFolder("6") all_inbox = inbox.Items val_date = date.date.today() sub_today = 'XYZ' att_today = 'XYZ.csv' """ Look for the email with the given subject and the attachment name """ for msg in all_inbox: if msg.Subject == sub_today: break for att in msg.Attachments: if att.FileName == att_today: break """ save the update and extend the database """ att.SaveAsFile('U:/' + 'XYZ.csv') read_path = "U:/" write_path = "V:/Special_Path/" df_Update = pd.read_csv(read_path + 'XYZ.csv',parse_dates=['Date'],skiprows=2) del df_Update['Unnamed: 14'] df_DB_Old = pd.read_csv(write_path + 'DataBase_XYZ.csv',parse_dates=['Date']) DB_DatumMax = df_DB_Old['Date'].max() Upd_DatumMax = df_Update['Date'].max() if df_DB_Old['Date'].isin(pd.Series(Upd_DatumMax)).sum()>0: print(' ') print('Date already exists!') print(' ') input("press enter to continue...") # exit() sys.exit() else: df_DB_New = pd.concat([df_DB_Old, df_Update]) df_DB_New.to_csv(write_path + 'XYZ.csv',index=False) Now I would like to extend that code, so that it checks when the last time was the database was updated and then it should extract the information from all the emails with subject “XYZ” starting from the day it was last updated. Example: I run the code on the 01.10.2022 Im on vacation for 2 days The database was last updated on 01.10 On 04.10 im back and I run the code again. The code will look for the email from 02.10 & from 03.10 and of course also for the latest mail 04.10 extract the csv and extend the database My first idea is to create a new folder where all the mails with subject “XYZ” automatically are moved. [Done!] Now I would check for the latest Date in my database. And now I have no clue how to proceed. I guess I need to loop though my new folder but only starting with mails which havent been extracted to the databse.
[ "Firstly, there is no reason to loop though all messages in a folder - that would be extremely slow in folders with thousands of messages, especially if the cached mode is off.\nUse Items.Restrict or Items.Find/FindNext - let the store provider do the heavy lifting for you. You will be able to specify a restriction on the Subject and/or ReceivedTime property\". See the examples at https://learn.microsoft.com/en-us/office/vba/api/outlook.items.restrict\n" ]
[ 0 ]
[]
[]
[ "email", "office_automation", "outlook", "python", "python_3.x" ]
stackoverflow_0074640759_email_office_automation_outlook_python_python_3.x.txt
Q: Why do I get a TypeError: unsupported operand type(s) for /: 'NoneType' and 'int' Sorry for the short essay but I think context is important here. This is for a course but I have struggled the entire semester with grasping this and the teacher hasn't been much help to me personally. I have a dataset with 30 categories and 500 images in each category (google maps stills of specific terrain). The goal is to process the image features (I'm using opencv SIFT) and conduct PCA on the features. I need to run the images through a deep learning model using fisher vectors and then plot some information based on the model. The problem is I keep getting random errors that I don't believe trace to the original problem. I know there is a crucial issue with my code, but I don't know what I don't know about it so I'm hoping the geniuses on stack can help identify my foible(s). Here is the snippet where I am currently getting stuck: #Ugly code, very sorry for ind, label in enumerate(os.listdir(img_direc)): #labels is storing the integer values of each category of the images ('swamp_lands', 'mountain', etc) labels.append(ind) #temporary list to store features desc_list = [] for i in os.listdir(f"{img_direc}\\{label}")[:400]: #process_image reads each file, converts to grayscale and resizes to a 224,224 image img = process_image(f"{img_direc}\\{label}\\{i}") _, desc = SIFT_Process_Keypoints(img) #first real point of confusion. I know there is a need to create either a 0's or 1's matrix #to fill in any none-type gaps but I'm struggling with the theory and code behind that feat_mtx = np.ones((224,224)) try: feat_mtx = np.zeros(desc.shape) for int, j in enumerate(desc): feat_mtx[int] = j except: pass #Do I need the mean? When trying to conduct PCA on the features I kept getting errors until #I reduced the values to a single number but it still wasn't giving me the right information desc_list.append(np.mean(feat_mtx)) desc_list = np.array(desc_list, dtype='object') desc_list = desc_list.flatten() train.append(desc_list) Does it just feel like my code is out of order? Or I'm missing a certain middle function somewhere. Any help with clarification would be greatly appreciated, I will be working actively on this code to try and gain some further understanding. Currently, the above code is yielding line 55, in <module> desc_list.append(np.mean(desc)) File "<__array_function__ internals>", line 180, in mean line 3432, in mean return _methods._mean(a, axis=axis, dtype=dtype, line 192, in _mean ret = ret / rcount TypeError: unsupported operand type(s) for /: 'NoneType' and 'int' after processing like 10 categories of images without an error. A: One issue with your code is that you are using the mean function on the desc array, which is not a valid input for the mean function because it is not a numerical array. The desc array is a 2D array of shape (N, 128), where N is the number of keypoints detected by the SIFT algorithm, and 128 is the length of the feature vector for each keypoint. To compute the mean of the desc array, you can use the mean function along one of the axes, for example: desc_mean = np.mean(desc, axis=0) This will compute the mean of each column in the desc array, and return a 1D array of shape (128,) with the mean feature vector. Another issue with your code is that you are trying to create a feat_mtx array of shape (224, 224) and fill it with the feature vectors from the desc array. This will not work because the desc array has a different shape than the feat_mtx array ((N, 128) vs (224, 224)), and it is not possible to directly fill the feat_mtx array with the feature vectors from the desc array. Instead, you can create a feat_mtx array of shape (N, 128) and fill it with the feature vectors from the desc array, like this: feat_mtx = np.zeros((desc.shape[0], desc.shape[1])) for int, j in enumerate(desc): feat_mtx[int] = j This will create a feat_mtx array with the same shape as the desc array, and fill it with the feature vectors from the desc array. Once you have fixed these issues with your code, you should be able to compute the mean of the feat_mtx array and append it to the desc_list array, like this: # compute the mean of the feat_mtx array feat_mtx_mean = np.mean(feat_mtx, axis=0) # append the mean of the feat_mtx array to the desc_list array desc_list.append(feat_mtx_mean) With these changes, your code should be able to process all of the images in the dataset and compute the mean feature vectors for each category. You can then use these mean feature vectors as input for the PCA and deep learning model.
Why do I get a TypeError: unsupported operand type(s) for /: 'NoneType' and 'int'
Sorry for the short essay but I think context is important here. This is for a course but I have struggled the entire semester with grasping this and the teacher hasn't been much help to me personally. I have a dataset with 30 categories and 500 images in each category (google maps stills of specific terrain). The goal is to process the image features (I'm using opencv SIFT) and conduct PCA on the features. I need to run the images through a deep learning model using fisher vectors and then plot some information based on the model. The problem is I keep getting random errors that I don't believe trace to the original problem. I know there is a crucial issue with my code, but I don't know what I don't know about it so I'm hoping the geniuses on stack can help identify my foible(s). Here is the snippet where I am currently getting stuck: #Ugly code, very sorry for ind, label in enumerate(os.listdir(img_direc)): #labels is storing the integer values of each category of the images ('swamp_lands', 'mountain', etc) labels.append(ind) #temporary list to store features desc_list = [] for i in os.listdir(f"{img_direc}\\{label}")[:400]: #process_image reads each file, converts to grayscale and resizes to a 224,224 image img = process_image(f"{img_direc}\\{label}\\{i}") _, desc = SIFT_Process_Keypoints(img) #first real point of confusion. I know there is a need to create either a 0's or 1's matrix #to fill in any none-type gaps but I'm struggling with the theory and code behind that feat_mtx = np.ones((224,224)) try: feat_mtx = np.zeros(desc.shape) for int, j in enumerate(desc): feat_mtx[int] = j except: pass #Do I need the mean? When trying to conduct PCA on the features I kept getting errors until #I reduced the values to a single number but it still wasn't giving me the right information desc_list.append(np.mean(feat_mtx)) desc_list = np.array(desc_list, dtype='object') desc_list = desc_list.flatten() train.append(desc_list) Does it just feel like my code is out of order? Or I'm missing a certain middle function somewhere. Any help with clarification would be greatly appreciated, I will be working actively on this code to try and gain some further understanding. Currently, the above code is yielding line 55, in <module> desc_list.append(np.mean(desc)) File "<__array_function__ internals>", line 180, in mean line 3432, in mean return _methods._mean(a, axis=axis, dtype=dtype, line 192, in _mean ret = ret / rcount TypeError: unsupported operand type(s) for /: 'NoneType' and 'int' after processing like 10 categories of images without an error.
[ "One issue with your code is that you are using the mean function on the desc array, which is not a valid input for the mean function because it is not a numerical array. The desc array is a 2D array of shape (N, 128), where N is the number of keypoints detected by the SIFT algorithm, and 128 is the length of the feature vector for each keypoint.\nTo compute the mean of the desc array, you can use the mean function along one of the axes, for example:\ndesc_mean = np.mean(desc, axis=0)\n\nThis will compute the mean of each column in the desc array, and return a 1D array of shape (128,) with the mean feature vector.\nAnother issue with your code is that you are trying to create a feat_mtx array of shape (224, 224) and fill it with the feature vectors from the desc array. This will not work because the desc array has a different shape than the feat_mtx array ((N, 128) vs (224, 224)), and it is not possible to directly fill the feat_mtx array with the feature vectors from the desc array.\nInstead, you can create a feat_mtx array of shape (N, 128) and fill it with the feature vectors from the desc array, like this:\nfeat_mtx = np.zeros((desc.shape[0], desc.shape[1]))\nfor int, j in enumerate(desc):\n feat_mtx[int] = j\n\nThis will create a feat_mtx array with the same shape as the desc array, and fill it with the feature vectors from the desc array.\nOnce you have fixed these issues with your code, you should be able to compute the mean of the feat_mtx array and append it to the desc_list array, like this:\n# compute the mean of the feat_mtx array\nfeat_mtx_mean = np.mean(feat_mtx, axis=0)\n\n# append the mean of the feat_mtx array to the desc_list array\ndesc_list.append(feat_mtx_mean)\n\nWith these changes, your code should be able to process all of the images in the dataset and compute the mean feature vectors for each category. You can then use these mean feature vectors as input for the PCA and deep learning model.\n" ]
[ 1 ]
[]
[]
[ "python", "typeerror" ]
stackoverflow_0074668707_python_typeerror.txt
Q: Trying to write a user_defined function in python that multiplies a formula of constants and coeff by the median of dataframe columns? I am trying to write a user defined function that takes median col values from a dataframe and places those values in a formula of constants and coefficients. I need the median col values to be multiplied one by one by the constants and coefficients. Below is what I need the function to do. median = data[['col 1','col 2','col 3']].median() col 1: 31.65 col 2: 87 col 3: 21.55 const_coeff = [(-.5447 + .1712 * 31.65 + -.5447 + .9601 * 87 + -.5447 + .8474 * 21.55)] print(constants_coefficients) total sum of constants_coefficients ......................................................................................................... I have attempted many variations on the def function but unable to get the answer I get when plugging the values in manually. One example is below. def i(median): const_coeff = 1 for x in median: const_coeff = const_coeff * i return const_coeff print(i(median)) The answer I get is negative number, which is wrong. Obviously, I used generic variables to show what I need/have done rather than my actual data so please forgive if that complicates things. Fairly new to coding and first-time poster. Thanks in advance for any help. A: Separate the values and plug them into the formula. a,b,c = median.array calc = [(-.5447 + .1712 * a + -.5447 + .9601 * b + -.5447 + .8474 * c)] Add parenthesis around the terms to ensure order of operations. Or q = median.array * (.1712,.9601,.8474) # q = median.to_numpy() * (.1712,.9601,.8474) q = q + (-.5447,-.5447,-.5447) r = q.sum() Pandas Series
Trying to write a user_defined function in python that multiplies a formula of constants and coeff by the median of dataframe columns?
I am trying to write a user defined function that takes median col values from a dataframe and places those values in a formula of constants and coefficients. I need the median col values to be multiplied one by one by the constants and coefficients. Below is what I need the function to do. median = data[['col 1','col 2','col 3']].median() col 1: 31.65 col 2: 87 col 3: 21.55 const_coeff = [(-.5447 + .1712 * 31.65 + -.5447 + .9601 * 87 + -.5447 + .8474 * 21.55)] print(constants_coefficients) total sum of constants_coefficients ......................................................................................................... I have attempted many variations on the def function but unable to get the answer I get when plugging the values in manually. One example is below. def i(median): const_coeff = 1 for x in median: const_coeff = const_coeff * i return const_coeff print(i(median)) The answer I get is negative number, which is wrong. Obviously, I used generic variables to show what I need/have done rather than my actual data so please forgive if that complicates things. Fairly new to coding and first-time poster. Thanks in advance for any help.
[ "Separate the values and plug them into the formula.\na,b,c = median.array\ncalc = [(-.5447 + .1712 * a + -.5447 + .9601 * b + -.5447 + .8474 * c)]\n\n\nAdd parenthesis around the terms to ensure order of operations.\n\nOr\nq = median.array * (.1712,.9601,.8474)\n# q = median.to_numpy() * (.1712,.9601,.8474)\nq = q + (-.5447,-.5447,-.5447)\nr = q.sum()\n\n\nPandas Series\n" ]
[ 0 ]
[]
[]
[ "array_formulas", "for_loop", "function", "python" ]
stackoverflow_0074667892_array_formulas_for_loop_function_python.txt
Q: is it okay to re-create someone else's app and make it open source? this is more of a copyright question i guess. in this case, i use notion a lot, but there's some things i would definitely like to change if i could. if i tried to re-create most of its features but change a lot of it, would there be any problems if i made the program open source? i assume that because it has paid options, i wouldn't be able to re-create it 1:1, but how similar could i make it? also i don't know if i would be able to it in terms of actually writing it, i haven't tried to start a project that big yet. lastly if this is off-topic for this site, where should i go to ask about it? A: It is not okay to re-create someone else's app and make it open source without permission from the original creator. This would likely be considered copyright infringement. Additionally, even if you make changes to the app and make it open source, it is still derived from the original app and may still be considered infringement. If you have ideas for changes or additions to the app, it would be best to contact the original creator and ask if they would be willing to incorporate your ideas into their app. Alternatively, you could create a completely new app that is not based on the original app and is not infringing on their copyright. If you have specific questions about copyright laws and how they apply to your situation, it would be best to consult with a lawyer who specializes in intellectual property law.
is it okay to re-create someone else's app and make it open source?
this is more of a copyright question i guess. in this case, i use notion a lot, but there's some things i would definitely like to change if i could. if i tried to re-create most of its features but change a lot of it, would there be any problems if i made the program open source? i assume that because it has paid options, i wouldn't be able to re-create it 1:1, but how similar could i make it? also i don't know if i would be able to it in terms of actually writing it, i haven't tried to start a project that big yet. lastly if this is off-topic for this site, where should i go to ask about it?
[ "It is not okay to re-create someone else's app and make it open source without permission from the original creator. This would likely be considered copyright infringement. Additionally, even if you make changes to the app and make it open source, it is still derived from the original app and may still be considered infringement.\nIf you have ideas for changes or additions to the app, it would be best to contact the original creator and ask if they would be willing to incorporate your ideas into their app. Alternatively, you could create a completely new app that is not based on the original app and is not infringing on their copyright.\nIf you have specific questions about copyright laws and how they apply to your situation, it would be best to consult with a lawyer who specializes in intellectual property law.\n" ]
[ 0 ]
[]
[]
[ "notion" ]
stackoverflow_0074668739_notion.txt
Q: The wagtail example of using entities isn't working for me The Wagtail example of using entities as given in this page of documentation isn't working for me. I am following the third example of using Entities which is supposed to create a button for stock price but no button is appearing for me in the rich text field in the admin editor. I have created a minimum reproducible example which demonstrates just this problem. https://github.com/kiwiheretic/stockentity. I am using Wagtail 4.1.1 which I understand is the latest version. Can anyone help me see what I have missed and why the button doesn't appear as expected? A: This or a similar question was asked in the Wagtail Slack. To get the button to appear, it either needs to be included in the features list when you create a new RichTextField OR you need to add it to the default configuration using the WAGTAILADMIN_RICH_TEXT_EDITORS setting.
The wagtail example of using entities isn't working for me
The Wagtail example of using entities as given in this page of documentation isn't working for me. I am following the third example of using Entities which is supposed to create a button for stock price but no button is appearing for me in the rich text field in the admin editor. I have created a minimum reproducible example which demonstrates just this problem. https://github.com/kiwiheretic/stockentity. I am using Wagtail 4.1.1 which I understand is the latest version. Can anyone help me see what I have missed and why the button doesn't appear as expected?
[ "This or a similar question was asked in the Wagtail Slack. To get the button to appear, it either needs to be included in the features list when you create a new RichTextField OR you need to add it to the default configuration using the WAGTAILADMIN_RICH_TEXT_EDITORS setting.\n" ]
[ 0 ]
[]
[]
[ "draftail", "wagtail" ]
stackoverflow_0074649998_draftail_wagtail.txt
Q: Rotate a google maps mark without changing it's position Hi i have a problem with rotating a mark, roation works fine but it changes its position when its rotated, is there any way to fix this const image = { path: "M14 8.947L22 14v2l-8-2.526v5.36l3 1.666V22l-4.5-1L8 22v-1.5l3-1.667v-5.36L3 16v-2l8-5.053V3.5a1.5 1.5 0 0 1 3 0v5.447z", fillColor: "#ffd400", fillOpacity: 1, strokeColor: "000", strokeOpacity: 0.4, scale: 1, rotation: 0, }; const aircraft = new google.maps.Marker({ position: { lat: 51.9189046, lng: 19.1343786 }, map, icon: image, }); A: The rotation for an SVG symbol is around the anchor position. The default anchor for an SVG Symbol is the upper left corner. To rotate the marker around the center, set the anchor to be the center of the image, which for your icon is: anchor: new google.maps.Point(13, 13) complete marker definition: const image = { path: "M14 8.947L22 14v2l-8-2.526v5.36l3 1.666V22l-4.5-1L8 22v-1.5l3-1.667v-5.36L3 16v-2l8-5.053V3.5a1.5 1.5 0 0 1 3 0v5.447z", fillColor: "#ffd400", fillOpacity: 1, strokeColor: "000", strokeOpacity: 0.4, scale: 1, rotation: 0, anchor: new google.maps.Point(13, 13) }; const aircraft = new google.maps.Marker({ position: { lat: 51.9189046, lng: 19.1343786 }, map, icon: image, }); proof of concept fiddle code snippet: let map; function initMap() { map = new google.maps.Map(document.getElementById("map"), { center: { lat: 51.9189046, lng: 19.1343786 }, zoom: 15, }); var ptMarker = new google.maps.Marker({ position: map.getCenter(), map: map, icon: { url: "https://maps.gstatic.com/intl/en_us/mapfiles/markers2/measle.png", size: new google.maps.Size(7, 7), anchor: new google.maps.Point(4, 4) } }); const image = { path: "M14 8.947L22 14v2l-8-2.526v5.36l3 1.666V22l-4.5-1L8 22v-1.5l3-1.667v-5.36L3 16v-2l8-5.053V3.5a1.5 1.5 0 0 1 3 0v5.447z", fillColor: "#ffd400", fillOpacity: 1, strokeColor: "000", strokeOpacity: 0.4, scale: 1, rotation: 0, anchor: new google.maps.Point(13, 13) }; const aircraft = new google.maps.Marker({ position: { lat: 51.9189046, lng: 19.1343786 }, map, icon: image, }); var angle = 0; setInterval(function() { angle += 10; var image = aircraft.getIcon(); image.rotation = angle; aircraft.setIcon(image); }, 500) } window.initMap = initMap; /* * Always set the map height explicitly to define the size of the div element * that contains the map. */ #map { height: 100%; } /* * Optional: Makes the sample page fill the window. */ html, body { height: 100%; margin: 0; padding: 0; } <!DOCTYPE html> <html> <head> <title>Simple Map</title> <script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script> <!-- jsFiddle will insert css and js --> </head> <body> <div id="map"></div> <!-- The `defer` attribute causes the callback to execute after the full HTML document has been parsed. For non-blocking uses, avoiding race conditions, and consistent behavior across browsers, consider loading using Promises with https://www.npmjs.com/package/@googlemaps/js-api-loader. --> <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap&v=weekly" defer ></script> </body> </html>
Rotate a google maps mark without changing it's position
Hi i have a problem with rotating a mark, roation works fine but it changes its position when its rotated, is there any way to fix this const image = { path: "M14 8.947L22 14v2l-8-2.526v5.36l3 1.666V22l-4.5-1L8 22v-1.5l3-1.667v-5.36L3 16v-2l8-5.053V3.5a1.5 1.5 0 0 1 3 0v5.447z", fillColor: "#ffd400", fillOpacity: 1, strokeColor: "000", strokeOpacity: 0.4, scale: 1, rotation: 0, }; const aircraft = new google.maps.Marker({ position: { lat: 51.9189046, lng: 19.1343786 }, map, icon: image, });
[ "The rotation for an SVG symbol is around the anchor position. The default anchor for an SVG Symbol is the upper left corner. To rotate the marker around the center, set the anchor to be the center of the image, which for your icon is:\nanchor: new google.maps.Point(13, 13)\n\ncomplete marker definition:\n const image = {\n path: \"M14 8.947L22 14v2l-8-2.526v5.36l3 1.666V22l-4.5-1L8 22v-1.5l3-1.667v-5.36L3 16v-2l8-5.053V3.5a1.5 1.5 0 0 1 3 0v5.447z\",\n fillColor: \"#ffd400\",\n fillOpacity: 1,\n strokeColor: \"000\",\n strokeOpacity: 0.4,\n scale: 1,\n rotation: 0,\n anchor: new google.maps.Point(13, 13)\n };\n const aircraft = new google.maps.Marker({\n position: { lat: 51.9189046, lng: 19.1343786 },\n map,\n icon: image,\n });\n\nproof of concept fiddle\n \ncode snippet:\n\n\nlet map;\n\nfunction initMap() {\n map = new google.maps.Map(document.getElementById(\"map\"), {\n center: { lat: 51.9189046, lng: 19.1343786 },\n zoom: 15,\n });\n var ptMarker = new google.maps.Marker({\n position: map.getCenter(),\n map: map,\n icon: {\n url: \"https://maps.gstatic.com/intl/en_us/mapfiles/markers2/measle.png\",\n size: new google.maps.Size(7, 7),\n anchor: new google.maps.Point(4, 4)\n }\n });\n const image = {\n path: \"M14 8.947L22 14v2l-8-2.526v5.36l3 1.666V22l-4.5-1L8 22v-1.5l3-1.667v-5.36L3 16v-2l8-5.053V3.5a1.5 1.5 0 0 1 3 0v5.447z\",\n fillColor: \"#ffd400\",\n fillOpacity: 1,\n strokeColor: \"000\",\n strokeOpacity: 0.4,\n scale: 1,\n rotation: 0,\n anchor: new google.maps.Point(13, 13)\n };\n const aircraft = new google.maps.Marker({\n position: { lat: 51.9189046, lng: 19.1343786 },\n map,\n icon: image,\n });\n var angle = 0;\n setInterval(function() {\n angle += 10;\n var image = aircraft.getIcon();\n image.rotation = angle;\n aircraft.setIcon(image);\n }, 500)\n}\n\nwindow.initMap = initMap;\n/* \n * Always set the map height explicitly to define the size of the div element\n * that contains the map. \n */\n#map {\n height: 100%;\n}\n\n/* \n * Optional: Makes the sample page fill the window. \n */\nhtml,\nbody {\n height: 100%;\n margin: 0;\n padding: 0;\n}\n<!DOCTYPE html>\n<html>\n <head>\n <title>Simple Map</title>\n <script src=\"https://polyfill.io/v3/polyfill.min.js?features=default\"></script>\n <!-- jsFiddle will insert css and js -->\n </head>\n <body>\n <div id=\"map\"></div>\n\n <!-- \n The `defer` attribute causes the callback to execute after the full HTML\n document has been parsed. For non-blocking uses, avoiding race conditions,\n and consistent behavior across browsers, consider loading using Promises\n with https://www.npmjs.com/package/@googlemaps/js-api-loader.\n -->\n <script\n src=\"https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap&v=weekly\"\n defer\n ></script>\n </body>\n</html>\n\n\n\n" ]
[ 0 ]
[]
[]
[ "google_maps", "google_maps_markers", "javascript" ]
stackoverflow_0074668373_google_maps_google_maps_markers_javascript.txt
Q: Optimizing Loop for memory def getWhiteLightLength(n, m, lights): lt_nv = [] ctd = 0 for clr, inic, fim in lights: for num in range(inic, fim+1): lt_nv.append(num) c = Counter(lt_nv) for ch, vl in c.items(): if vl == m: ctd += 1 return(ctd) I'm doing this HackerRank solution, it passed on half of the tests, but for the others, I get a memory usage error. I'm new to python so don`t know how to optimize these loops for minor memory usage. A: One way to optimize the memory usage in this code is to avoid using a list to store the numbers of the lightbulbs that are turned on. Instead, you can use a Python set to store the numbers of the lightbulbs, which is more memory-efficient. Here is an updated version of the code that uses a set to store the numbers of the lightbulbs: from collections import Counter def getWhiteLightLength(n, m, lights): lt_nv = set() ctd = 0 for clr, inic, fim in lights: for num in range(inic, fim+1): lt_nv.add(num) c = Counter(lt_nv) for ch, vl in c.items(): if vl == m: ctd += 1 return ctd In this code, the lt_nv set is used to store the numbers of the lightbulbs that are turned on. The add() method is used to add each number to the set, and the Counter() function is used to count the number of times each lightbulb number appears in the set. This updated code should be more memory-efficient and should be able to pass the tests on HackerRank without a memory usage error.
Optimizing Loop for memory
def getWhiteLightLength(n, m, lights): lt_nv = [] ctd = 0 for clr, inic, fim in lights: for num in range(inic, fim+1): lt_nv.append(num) c = Counter(lt_nv) for ch, vl in c.items(): if vl == m: ctd += 1 return(ctd) I'm doing this HackerRank solution, it passed on half of the tests, but for the others, I get a memory usage error. I'm new to python so don`t know how to optimize these loops for minor memory usage.
[ "One way to optimize the memory usage in this code is to avoid using a list to store the numbers of the lightbulbs that are turned on. Instead, you can use a Python set to store the numbers of the lightbulbs, which is more memory-efficient.\nHere is an updated version of the code that uses a set to store the numbers of the lightbulbs:\nfrom collections import Counter\n\ndef getWhiteLightLength(n, m, lights):\n lt_nv = set()\n ctd = 0\n for clr, inic, fim in lights:\n for num in range(inic, fim+1):\n lt_nv.add(num)\n c = Counter(lt_nv)\n for ch, vl in c.items():\n if vl == m:\n ctd += 1\n return ctd\n\nIn this code, the lt_nv set is used to store the numbers of the lightbulbs that are turned on. The add() method is used to add each number to the set, and the Counter() function is used to count the number of times each lightbulb number appears in the set.\nThis updated code should be more memory-efficient and should be able to pass the tests on HackerRank without a memory usage error.\n" ]
[ 0 ]
[]
[]
[ "loops", "memory", "memory_management", "python" ]
stackoverflow_0074668660_loops_memory_memory_management_python.txt
Q: How to make Titlebar height fit new Title Font size increase in WxPython? I've increased the custon AddPrivateFont pointsize to self.label_font.SetPointSize(27) of the Title bar of the sample_one.py script from this shared project: https://wiki.wxpython.org/How%20to%20add%20a%20menu%20bar%20in%20the%20title%20bar%20%28Phoenix%29 From the script of my previous question here: https://web.archive.org/web/20221202192613/https://paste.c-net.org/HondoPrairie AddPrivateFont to App Title / Title bar in WxPython? My problem is I can't figure out how to make the Title bar's height larger so the Title text displays its top part correctly. Currently the top of the Title text is truncated. I tried adjusting the height and textHeight values from this statement: textWidth, textHeight = gcdc.GetTextExtent(self.label) tposx, tposy = ((width / 2) - (textWidth / 2), (height / 1) - (textHeight / 1)) from previous ones (in the sample_one.py script): textWidth, textHeight = gcdc.GetTextExtent(self.label) tposx, tposy = ((width / 2) - (textWidth / 2), (height / 3) - (textHeight / 3)) Because it truncated the bottom (now the bottom shows up correctly but not the top of the Title text). There is also this method I'm not sure how to handle: def DoGetBestSize(self): """ ... """ dc = wx.ClientDC(self) dc.SetFont(self.GetFont()) textWidth, textHeight = dc.GetTextExtent(self.label) spacing = 10 totalWidth = textWidth + (spacing) totalHeight = textHeight + (spacing) best = wx.Size(totalWidth, totalHeight) self.CacheBestSize(best) return best I tried tweaking it and printing results but to no avail. Here's a preview of the Truncated Title text: What would be the correct approach to finding out what controls the height of the title bar object to fix the truncated title text? A: Thanks to @Rolf of Saxony headsup I figured it out! It took the following 3 steps: 1st Step: Top Title Text Display from: class MyTitleBarPnl(wx.Panel): def CreateCtrls(self): self.titleBar.SetSize((w, 54)) def OnResize(self, event): self.titleBar.SetSize((w, 54)) 2nd Step: Vertical Spacing Below Title Text Without Text Display: class MyFrame(wx.Frame): def CreateCtrls(self): self.titleBarPnl = MyTitleBarPnl(self, -1, (w, 54)) def OnResize(self, event): self.titleBarPnl.SetSize((w, 24)) 3rd Step: Vertical Spacing Below Title Text WithText Display: class MyFrame(wx.Frame): def CreateCtrls(self): self.titleBarPnl = MyTitleBarPnl(self, -1, (w, 54)) def OnResize(self, event): self.titleBarPnl.SetSize((w, 54)) EDIT: 4th Step: Status Bar Display: class MyFrame(wx.Frame): def CreateCtrls(self): self.titleBarPnl = MyTitleBarPnl(self, -1, (w, 54)) def OnResize(self, event): self.titleBarPnl.SetSize((w, 54)) self.mainPnl.SetSize((w, h - 55)) # 25
How to make Titlebar height fit new Title Font size increase in WxPython?
I've increased the custon AddPrivateFont pointsize to self.label_font.SetPointSize(27) of the Title bar of the sample_one.py script from this shared project: https://wiki.wxpython.org/How%20to%20add%20a%20menu%20bar%20in%20the%20title%20bar%20%28Phoenix%29 From the script of my previous question here: https://web.archive.org/web/20221202192613/https://paste.c-net.org/HondoPrairie AddPrivateFont to App Title / Title bar in WxPython? My problem is I can't figure out how to make the Title bar's height larger so the Title text displays its top part correctly. Currently the top of the Title text is truncated. I tried adjusting the height and textHeight values from this statement: textWidth, textHeight = gcdc.GetTextExtent(self.label) tposx, tposy = ((width / 2) - (textWidth / 2), (height / 1) - (textHeight / 1)) from previous ones (in the sample_one.py script): textWidth, textHeight = gcdc.GetTextExtent(self.label) tposx, tposy = ((width / 2) - (textWidth / 2), (height / 3) - (textHeight / 3)) Because it truncated the bottom (now the bottom shows up correctly but not the top of the Title text). There is also this method I'm not sure how to handle: def DoGetBestSize(self): """ ... """ dc = wx.ClientDC(self) dc.SetFont(self.GetFont()) textWidth, textHeight = dc.GetTextExtent(self.label) spacing = 10 totalWidth = textWidth + (spacing) totalHeight = textHeight + (spacing) best = wx.Size(totalWidth, totalHeight) self.CacheBestSize(best) return best I tried tweaking it and printing results but to no avail. Here's a preview of the Truncated Title text: What would be the correct approach to finding out what controls the height of the title bar object to fix the truncated title text?
[ "Thanks to @Rolf of Saxony headsup I figured it out!\nIt took the following 3 steps:\n1st Step:\nTop Title Text Display from:\nclass MyTitleBarPnl(wx.Panel):\n def CreateCtrls(self):\n self.titleBar.SetSize((w, 54))\n\n def OnResize(self, event):\n self.titleBar.SetSize((w, 54))\n\n\n2nd Step:\nVertical Spacing Below Title Text Without Text Display:\nclass MyFrame(wx.Frame):\n def CreateCtrls(self):\n self.titleBarPnl = MyTitleBarPnl(self, -1, (w, 54))\n\n def OnResize(self, event):\n self.titleBarPnl.SetSize((w, 24))\n\n\n3rd Step:\nVertical Spacing Below Title Text WithText Display:\nclass MyFrame(wx.Frame):\n def CreateCtrls(self):\n self.titleBarPnl = MyTitleBarPnl(self, -1, (w, 54))\n\n def OnResize(self, event):\n self.titleBarPnl.SetSize((w, 54))\n\n\nEDIT:\n4th Step:\nStatus Bar Display:\nclass MyFrame(wx.Frame):\n def CreateCtrls(self):\n self.titleBarPnl = MyTitleBarPnl(self, -1, (w, 54))\n\n def OnResize(self, event):\n self.titleBarPnl.SetSize((w, 54))\n self.mainPnl.SetSize((w, h - 55)) # 25\n\n\n" ]
[ 1 ]
[]
[]
[ "height", "python", "python_3.x", "wxpython", "wxwidgets" ]
stackoverflow_0074663982_height_python_python_3.x_wxpython_wxwidgets.txt
Q: Laravel Blade - get template path I'm using Laravel 8. Is there any way to find out the blade template path from within the template? I want to pass this to a directive because I want to do something that is dependent on the directory structure of the templates. Made up example below. Say I have five templates: home.blade.php store/list.blade.php store/buy.blade.php news/stories.blade.php news/story.blade.php From within each template, I would like the template to be able to find out its own path, whether that's the full path or just, for example, "store/list.blade.php". Or just get the directory. Ultimately, I want to make the the path to the template have meaning and do configuration based on that. For example, currently, to define the layout to be used only once, I have code like this: @extends(config('custom.layout')) What if I could configure a different layout for each directory of the templates? That way, I would only have to change the configuration in one place instead of changing many templates. That would require the template be able to know what directory it's in. There are other things I may want to configure based on directory as well. I like to do things by configuration when possible and I like to avoid defining things more than once, and I'm trying to determine what's possible. A: Yes, there is a way to find out the blade template path from within the template. You can use the @yield directive and pass the name of the section as the first argument, followed by the path of the template as the second argument. For example, if you want to find out the path of the main section, you can use the following code: @yield('main', 'path.to.template') This will output the path of the main section as a string. You can then pass this to a function and use it in any way you want. Note that the @yield directive is only available in the main layout file, and not in the individual blade templates. So, you will need to place this code in the main layout file, and not in the individual blade templates. Also, make sure to replace path.to.template with the actual path of the blade template that you want to find the path for.
Laravel Blade - get template path
I'm using Laravel 8. Is there any way to find out the blade template path from within the template? I want to pass this to a directive because I want to do something that is dependent on the directory structure of the templates. Made up example below. Say I have five templates: home.blade.php store/list.blade.php store/buy.blade.php news/stories.blade.php news/story.blade.php From within each template, I would like the template to be able to find out its own path, whether that's the full path or just, for example, "store/list.blade.php". Or just get the directory. Ultimately, I want to make the the path to the template have meaning and do configuration based on that. For example, currently, to define the layout to be used only once, I have code like this: @extends(config('custom.layout')) What if I could configure a different layout for each directory of the templates? That way, I would only have to change the configuration in one place instead of changing many templates. That would require the template be able to know what directory it's in. There are other things I may want to configure based on directory as well. I like to do things by configuration when possible and I like to avoid defining things more than once, and I'm trying to determine what's possible.
[ "Yes, there is a way to find out the blade template path from within the template. You can use the @yield directive and pass the name of the section as the first argument, followed by the path of the template as the second argument.\nFor example, if you want to find out the path of the main section, you can use the following code:\n@yield('main', 'path.to.template')\n\nThis will output the path of the main section as a string. You can then pass this to a function and use it in any way you want.\nNote that the @yield directive is only available in the main layout file, and not in the individual blade templates. So, you will need to place this code in the main layout file, and not in the individual blade templates.\nAlso, make sure to replace path.to.template with the actual path of the blade template that you want to find the path for.\n" ]
[ 0 ]
[]
[]
[ "laravel", "laravel_8", "php" ]
stackoverflow_0074668756_laravel_laravel_8_php.txt
Q: A simple Map and select React I try to fetch 4 categories from my DB. I get the category, everything is ok but when I submit my form, I get this data : [object%20Object],[object%20Object],[object%20Object],[object%20Object] Here the code : //State const [cates, setCates] = useState([]); // Fetch 4 categories useEffect(() => { const getCates = async () => { const res = await axios.get("http://localhost:8080/api/categories"); setCates(res.data); }; getCates(); }, []) //Map the categories from the State : cates const Categorie = cates.map((c) => ( <option value={c.name}>{c.name}</option> )) My component : <Select> <option value="" hidden>Choisissez une catégorie</option> {Categorie} </Select> The console.log(Categorie) return an Array of object : (4) [{…}, {…}, {…}, {…}] 0 : {$$typeof: Symbol(react.element), type: 'option', key: null, ref: null, props: {…}, …} 1 : {$$typeof: Symbol(react.element), type: 'option', key: null, ref: null, props: {…}, …} 2 : {$$typeof: Symbol(react.element), type: 'option', key: null, ref: null, props: {…}, …} 3 : {$$typeof: Symbol(react.element), type: 'option', key: null, ref: null, props: {…}, …} length : 4 [[Prototype]] : Array(0) And the console.log(cates[0].name) give me the result I'm looking for. But even when I try to put manually the categories like that : cates[0].name, cates[1].names etc... I get a blank page when I save my code and reload the page. I just want to get my the categorie selected. A: I can see the Categorie return an array of react components, not the data you fetch from the API So you can write like this const Component = () => { const [categories, setCategories] = useState([]) useEffect(() => { const getCates = async () => { const res = await axios.get("http://localhost:8080/api/categories"); setCategories(res.data); }; getCates(); }, []) const List = () => { return categories.map(c => ( <option value={c.name}>{c.name}</option> )) } return ( <select> <option value="" hidden>Choisissez une catégorie</option> <List /> </select> ) } the List will be an array of react components, to use it just simply add <List /> A: Hi @Romain Plantureux You could try this as you disrobe in above. And I notice that <Select> is not should be capital. It's must like that <select>. Maybe that why your page showing blank. Code Sandbox A: I solved my problem : Code + comments : //UseEffect + state (nothing changed, I just rename the const) : //for saved the categorie I fecth. const [cats, setCats] = useState([]); // for save the value selected in my select : const [catSelect, setCatSelect] = useState("") useEffect(() => { const getCats = async () => { const res = await axios.get("http://localhost:8080/api/categories"); setCats(res.data); }; getCats(); }, []) The map component, I added a key : const CatSelect = cats.map((c) => ( <option key={c.name} value={c.name} >{c.name}</option> )) And the most important changes on the Select : (I use react-styled-components, this is why my Select have a Capital). I have add the value='null' For the OnChange, it save the value selected in a new state. <Select value={null} onChange={e => setCatSelect(e.target.value)}> //This first option is important because the default value is not saved automatically in the new state... <option value="" hidden> Votre choix</option> {CatSelect} </Select>
A simple Map and select React
I try to fetch 4 categories from my DB. I get the category, everything is ok but when I submit my form, I get this data : [object%20Object],[object%20Object],[object%20Object],[object%20Object] Here the code : //State const [cates, setCates] = useState([]); // Fetch 4 categories useEffect(() => { const getCates = async () => { const res = await axios.get("http://localhost:8080/api/categories"); setCates(res.data); }; getCates(); }, []) //Map the categories from the State : cates const Categorie = cates.map((c) => ( <option value={c.name}>{c.name}</option> )) My component : <Select> <option value="" hidden>Choisissez une catégorie</option> {Categorie} </Select> The console.log(Categorie) return an Array of object : (4) [{…}, {…}, {…}, {…}] 0 : {$$typeof: Symbol(react.element), type: 'option', key: null, ref: null, props: {…}, …} 1 : {$$typeof: Symbol(react.element), type: 'option', key: null, ref: null, props: {…}, …} 2 : {$$typeof: Symbol(react.element), type: 'option', key: null, ref: null, props: {…}, …} 3 : {$$typeof: Symbol(react.element), type: 'option', key: null, ref: null, props: {…}, …} length : 4 [[Prototype]] : Array(0) And the console.log(cates[0].name) give me the result I'm looking for. But even when I try to put manually the categories like that : cates[0].name, cates[1].names etc... I get a blank page when I save my code and reload the page. I just want to get my the categorie selected.
[ "I can see the Categorie return an array of react components, not the data you fetch from the API\nSo you can write like this\nconst Component = () => {\n const [categories, setCategories] = useState([])\n\n useEffect(() => {\n const getCates = async () => {\n const res = await axios.get(\"http://localhost:8080/api/categories\");\n setCategories(res.data);\n };\n getCates();\n }, [])\n\n const List = () => {\n return categories.map(c => (\n <option value={c.name}>{c.name}</option>\n ))\n }\n\n return (\n <select>\n <option value=\"\" hidden>Choisissez une catégorie</option>\n <List />\n </select>\n )\n}\n\nthe List will be an array of react components, to use it just simply add <List />\n", "Hi @Romain Plantureux\nYou could try this as you disrobe in above.\nAnd I notice that <Select> is not should be capital. It's must like that <select>. Maybe that why your page showing blank.\nCode Sandbox\n", "I solved my problem :\nCode + comments :\n//UseEffect + state (nothing changed, I just rename the const) :\n//for saved the categorie I fecth.\nconst [cats, setCats] = useState([]);\n\n// for save the value selected in my select : \nconst [catSelect, setCatSelect] = useState(\"\")\n\nuseEffect(() => {\n const getCats = async () => {\n const res = await axios.get(\"http://localhost:8080/api/categories\");\n setCats(res.data);\n };\n getCats();\n}, [])\n\nThe map component, I added a key :\nconst CatSelect = cats.map((c) => (\n <option key={c.name} value={c.name} >{c.name}</option>\n ))\n\nAnd the most important changes on the Select :\n(I use react-styled-components, this is why my Select have a Capital).\nI have add the value='null'\nFor the OnChange, it save the value selected in a new state.\n<Select value={null} onChange={e => setCatSelect(e.target.value)}>\n\n //This first option is important because the default value is not saved automatically in the new state... \n <option value=\"\" hidden> Votre choix</option>\n {CatSelect}\n</Select>\n\n" ]
[ 0, 0, 0 ]
[]
[]
[ "javascript", "reactjs" ]
stackoverflow_0074667546_javascript_reactjs.txt
Q: 4 digit decimal number to 7 segment display I am using the Nexys 7 board. It has 8 7 segment displays but I only want to us four of them. I have created a binary to bcd converter. It converts a 16 bit binary number to a 4 digit decmial number. I am trying to display that 4 digit decmial number on the four 7 segment displays. I am writing this in Verilog. Please let me know if i need to explain something better. I want to be able to input a binary number that converts to decimal and is displayed on the 7 segment displays. I want to be able to input a number from 0-9999 and it display properly on the 7 segments. This is my binary to bcd code. module BinaryToBCD( in,out ); input [15:0]in; output [15:0]out; reg [15:0]out; integer i; always @ (in) begin out=0; for(i=0;i<16;i=i+1) begin if(out[3:0]>=5) out[3:0]=out[3:0]+3; if(out[7:4]>=5) out[7:4]=out[7:4]+3; if(out[11:8]>=5)out[11:8]=out[11:8]+3; if(out[15:12]>=5)out[15:12]=out[15:12]+3; out={out[14:0],in[15-i]}; end end endmodule A: To display a 4-digit decimal number on the Nexys 7 board using four 7-segment displays, you can use the bcd_to_7seg_hex module from the Xilinx IP library. This module converts a 4-bit binary-coded decimal (BCD) value to a 7-segment display code, which can be used to control the segments of a 7-segment display. Here is an example of how you can use the bcd_to_7seg_hex module in Verilog to display a 4-digit decimal number on the Nexys 7 board: // Declare the input and output wires for the bcd_to_7seg_hex module wire [3:0] bcd; wire [6:0] seg_hex; // Instantiate the bcd_to_7seg_hex module bcd_to_7seg_hex bcd_to_7seg_hex_inst ( .bcd(bcd), .seg_hex(seg_hex) ); // Define a 4-digit decimal number and convert it to BCD integer decimal_number = 1234; reg [3:0] bcd_number = {decimal_number[3], decimal_number[2], decimal_number[1], decimal_number[0]}; // Drive the bcd input with the BCD number always @(*) begin bcd = bcd_number; end // Connect the seg_hex output to the 7-segment displays assign seg[0] = seg_hex[0]; assign seg[1] = seg_hex[1]; assign seg[2] = seg_hex[2]; assign
4 digit decimal number to 7 segment display
I am using the Nexys 7 board. It has 8 7 segment displays but I only want to us four of them. I have created a binary to bcd converter. It converts a 16 bit binary number to a 4 digit decmial number. I am trying to display that 4 digit decmial number on the four 7 segment displays. I am writing this in Verilog. Please let me know if i need to explain something better. I want to be able to input a binary number that converts to decimal and is displayed on the 7 segment displays. I want to be able to input a number from 0-9999 and it display properly on the 7 segments. This is my binary to bcd code. module BinaryToBCD( in,out ); input [15:0]in; output [15:0]out; reg [15:0]out; integer i; always @ (in) begin out=0; for(i=0;i<16;i=i+1) begin if(out[3:0]>=5) out[3:0]=out[3:0]+3; if(out[7:4]>=5) out[7:4]=out[7:4]+3; if(out[11:8]>=5)out[11:8]=out[11:8]+3; if(out[15:12]>=5)out[15:12]=out[15:12]+3; out={out[14:0],in[15-i]}; end end endmodule
[ "To display a 4-digit decimal number on the Nexys 7 board using four 7-segment displays, you can use the bcd_to_7seg_hex module from the Xilinx IP library. This module converts a 4-bit binary-coded decimal (BCD) value to a 7-segment display code, which can be used to control the segments of a 7-segment display.\nHere is an example of how you can use the bcd_to_7seg_hex module in Verilog to display a 4-digit decimal number on the Nexys 7 board:\n// Declare the input and output wires for the bcd_to_7seg_hex module\nwire [3:0] bcd;\nwire [6:0] seg_hex;\n\n// Instantiate the bcd_to_7seg_hex module\nbcd_to_7seg_hex bcd_to_7seg_hex_inst (\n .bcd(bcd),\n .seg_hex(seg_hex)\n);\n\n// Define a 4-digit decimal number and convert it to BCD\ninteger decimal_number = 1234;\nreg [3:0] bcd_number = {decimal_number[3], decimal_number[2], \ndecimal_number[1], decimal_number[0]};\n\n// Drive the bcd input with the BCD number\nalways @(*) begin\n bcd = bcd_number;\nend\n\n// Connect the seg_hex output to the 7-segment displays\nassign seg[0] = seg_hex[0];\nassign seg[1] = seg_hex[1];\nassign seg[2] = seg_hex[2];\nassign\n\n" ]
[ 0 ]
[]
[]
[ "system_verilog", "verilog" ]
stackoverflow_0074668347_system_verilog_verilog.txt
Q: Docker: SvelteKit app cannot be accessed from browser I've got a Svelte (with Sveltekit) app which I just containerized. It builds correctly and there are no errors when running, but I cannot access it from the browser. I tried accessing http://localhost:5050/ and also http://0.0.0.0:5050/ but I'm getting: This page isn’t working localhost didn’t send any data. ERR_EMPTY_RESPONSE This is the Dockerfile I'm using: # Our Node base image FROM node:19-alpine # Set the Node environment to development to ensure all packages are installed ENV NODE_ENV development # Change our current working directory WORKDIR /app # Copy over `package.json` and lock files to optimize the build process COPY package.json package-lock.json ./ # Install Node modules RUN npm install # Copy over rest of the project files COPY . . RUN npm run build # Expose port ENV PORT 5050 EXPOSE 5050 # Run `yarn dev` and set the host to 0.0.0.0 so we can access the web app from outside CMD ["npm", "run", "dev"] This is how I'm building it: docker build -t sveltekit:node --network=host . And this is how I'm running it: docker run -d -p 5050:5050 --name sveltekit-app sveltekit:node And this is the output of running docker ps: a9e241b09fd3 IMAGE sveltekit:node COMMAND "docker-entrypoint.s…" CREATED About a minute ago STATUS Up About a minute PORTS 0.0.0.0:5050->5050/tcp NAMES sveltekit-app What am I missing? UPDATE Container Logs 2022-11-30 19:09:18 2022-11-30 19:09:18 > [email protected] start 2022-11-30 19:09:18 > export PORT=8080 && node ./build 2022-11-30 19:09:18 2022-11-30 19:09:18 Listening on 0.0.0.0:8080 why it is listening to port 8080? I updated my package.json to be: "dev": "vite dev --port=5050" meaning that I'm enforcing port 5050, isn't that right? A: Are you sure that sveltekit listens on port 5050? Because when I start it up with npm run dev (vite dev) it usually takes port 5173 and if it is already used it counts 1 up until it reaches a free port. Add in the package.json at the dev command a --port=5050. Full string: "dev": "vite dev --port=5050", A: I assume you could simply map the 5050 to 8080 in that case: docker run -d -p 5050:8080 --name sveltekit-app sveltekit:node A: Your container has no web server running to serve your files. As you are just wanting to serve static files, node http-server would probably do. Try running this somewhere in your dockerfile.. npm install --global http-server && http-server ./app -p 5050 EDIT: Sveltekit seems to run @sveltejs/adapter-node to serve files. A: In the Dockerfile try to change: CMD ["npm", "run", "dev"] to CMD ["npm", "run", "dev", "--", "-p", "5050] Then rebuild your docker image and run it again. A: It looks like the app is trying to listen on port 8080 instead of 5050. This could be because the PORT environment variable is being set to 8080 in the start script in package.json, or because PORT is being set to 8080 somewhere else in the code. To fix this issue, you can try one of the following: Modify the start script in package.json to specify the correct port, like this: "scripts": { "start": "export PORT=5050 && node ./build" } Set the PORT environment variable when running the container, like this: Copy code docker run -d -p 5050:5050 -e PORT=5050 --name sveltekit-app sveltekit:node Modify the code to use the correct port number, which should be specified in the process.env.PORT variable. After making the necessary changes, you should be able to access the app at http://localhost:5050/ or http://0.0.0.0:5050/. Alternatively, to word this slightly differently, It also looks like you're specifying the correct port number in the dev script in package.json, so the app should be listening on port 5050 when you run npm run dev. However, it looks like the start script is still trying to listen on port 8080, which is likely why you're still seeing the error message. To fix this, you can update the start script in package.json to specify the correct port, like this: "scripts": { "start": "export PORT=5050 && node ./build" } This will ensure that the app listens on port 5050 when you run npm start. Note that you may need to rebuild the Docker image after making this change in order for it to take effect. You can do this by running docker build -t sveltekit:node . and then starting the container again using docker run -d -p 5050:5050 --name sveltekit-app sveltekit:node. After making these changes, you should be able to access the app at http://localhost:5050/ or http://0.0.0.0:5050/. A: The issue might be with the --network=host flag that you are using when building the Docker image. This flag tells Docker to use the host's networking stack, which means that the container will not be isolated from the host network and will use the same IP address and network interfaces as the host. When you run the container with the --network=host flag, the container will bind to port 5050 on the host's network interface, and you should be able to access the app at http://localhost:5050/. However, if the host's network interface is not accessible from the host machine (for example, if you are running Docker inside a virtual machine), then you will not be able to access the app. To fix this, you can remove the --network=host flag when building the Docker image, and specify the network interface and IP address that the container should bind to when running the container. For example, you can use the --network=bridge flag to create a new bridge network for the container, and the --ip flag to specify the IP address that the container should use on the bridge network. Here is an example of how you can run the container with these flags: # create a new bridge network for the container docker network create my-bridge # run the container on the my-bridge network and bind to IP address 172.17.0.2 docker run -d --name sveltekit-app --network=my-bridge --ip=172.17.0.2 -p 5050:5050 sveltekit:node With these flags, the container will bind to port 5050 on the IP address 172.17.0.2 on the my-bridge network. You can then access the app at http://172.17.0.2:5050/. Alternatively, you can use the --publish flag to publish the container's port to the host's network interface. This will allow the container to bind to port 5050 on the host's network interface, and you can access the app at http://localhost:5050/. Here is an example of how you can run the container with the --publish flag: # run the container and publish port 5050 to the host's network interface docker run -d --name sveltekit-app --publish 5050:5050 sveltekit:node With this flag, the container will bind to port 5050 on the host's network interface, and you can access the app at http://localhost:5050/.
Docker: SvelteKit app cannot be accessed from browser
I've got a Svelte (with Sveltekit) app which I just containerized. It builds correctly and there are no errors when running, but I cannot access it from the browser. I tried accessing http://localhost:5050/ and also http://0.0.0.0:5050/ but I'm getting: This page isn’t working localhost didn’t send any data. ERR_EMPTY_RESPONSE This is the Dockerfile I'm using: # Our Node base image FROM node:19-alpine # Set the Node environment to development to ensure all packages are installed ENV NODE_ENV development # Change our current working directory WORKDIR /app # Copy over `package.json` and lock files to optimize the build process COPY package.json package-lock.json ./ # Install Node modules RUN npm install # Copy over rest of the project files COPY . . RUN npm run build # Expose port ENV PORT 5050 EXPOSE 5050 # Run `yarn dev` and set the host to 0.0.0.0 so we can access the web app from outside CMD ["npm", "run", "dev"] This is how I'm building it: docker build -t sveltekit:node --network=host . And this is how I'm running it: docker run -d -p 5050:5050 --name sveltekit-app sveltekit:node And this is the output of running docker ps: a9e241b09fd3 IMAGE sveltekit:node COMMAND "docker-entrypoint.s…" CREATED About a minute ago STATUS Up About a minute PORTS 0.0.0.0:5050->5050/tcp NAMES sveltekit-app What am I missing? UPDATE Container Logs 2022-11-30 19:09:18 2022-11-30 19:09:18 > [email protected] start 2022-11-30 19:09:18 > export PORT=8080 && node ./build 2022-11-30 19:09:18 2022-11-30 19:09:18 Listening on 0.0.0.0:8080 why it is listening to port 8080? I updated my package.json to be: "dev": "vite dev --port=5050" meaning that I'm enforcing port 5050, isn't that right?
[ "Are you sure that sveltekit listens on port 5050?\nBecause when I start it up with npm run dev (vite dev) it usually takes port 5173 and if it is already used it counts 1 up until it reaches a free port.\nAdd in the package.json at the dev command a --port=5050.\nFull string:\n\n\"dev\": \"vite dev --port=5050\",\n\n", "I assume you could simply map the 5050 to 8080 in that case:\ndocker run -d -p 5050:8080 --name sveltekit-app sveltekit:node\n\n", "Your container has no web server running to serve your files.\nAs you are just wanting to serve static files, node http-server would probably do.\nTry running this somewhere in your dockerfile..\nnpm install --global http-server && http-server ./app -p 5050\nEDIT:\nSveltekit seems to run @sveltejs/adapter-node to serve files.\n", "In the Dockerfile try to change:\nCMD [\"npm\", \"run\", \"dev\"]\nto\nCMD [\"npm\", \"run\", \"dev\", \"--\", \"-p\", \"5050]\nThen rebuild your docker image and run it again.\n", "It looks like the app is trying to listen on port 8080 instead of 5050. This could be because the PORT environment variable is being set to 8080 in the start script in package.json, or because PORT is being set to 8080 somewhere else in the code.\nTo fix this issue, you can try one of the following:\nModify the start script in package.json to specify the correct port, like this:\n\"scripts\": {\n \"start\": \"export PORT=5050 && node ./build\"\n}\nSet the PORT environment variable when running the container, like this:\nCopy code\ndocker run -d -p 5050:5050 -e PORT=5050 --name sveltekit-app sveltekit:node\n\nModify the code to use the correct port number, which should be specified in the process.env.PORT variable.\nAfter making the necessary changes, you should be able to access the app at http://localhost:5050/ or http://0.0.0.0:5050/.\n\nAlternatively, to word this slightly differently, It also looks like you're specifying the correct port number in the dev script in package.json, so the app should be listening on port 5050 when you run npm run dev.\nHowever, it looks like the start script is still trying to listen on port 8080, which is likely why you're still seeing the error message. To fix this, you can update the start script in package.json to specify the correct port, like this:\n\"scripts\": {\n \"start\": \"export PORT=5050 && node ./build\"\n}\n\nThis will ensure that the app listens on port 5050 when you run npm start. Note that you may need to rebuild the Docker image after making this change in order for it to take effect. You can do this by running docker build -t sveltekit:node . and then starting the container again using docker run -d -p 5050:5050 --name sveltekit-app sveltekit:node.\nAfter making these changes, you should be able to access the app at http://localhost:5050/ or http://0.0.0.0:5050/.\n", "The issue might be with the --network=host flag that you are using when building the Docker image. This flag tells Docker to use the host's networking stack, which means that the container will not be isolated from the host network and will use the same IP address and network interfaces as the host.\nWhen you run the container with the --network=host flag, the container will bind to port 5050 on the host's network interface, and you should be able to access the app at http://localhost:5050/. However, if the host's network interface is not accessible from the host machine (for example, if you are running Docker inside a virtual machine), then you will not be able to access the app.\nTo fix this, you can remove the --network=host flag when building the Docker image, and specify the network interface and IP address that the container should bind to when running the container. For example, you can use the --network=bridge flag to create a new bridge network for the container, and the --ip flag to specify the IP address that the container should use on the bridge network.\nHere is an example of how you can run the container with these flags:\n# create a new bridge network for the container\ndocker network create my-bridge\n\n# run the container on the my-bridge network and bind to IP address 172.17.0.2\ndocker run -d --name sveltekit-app --network=my-bridge --ip=172.17.0.2 -p 5050:5050 sveltekit:node\n\nWith these flags, the container will bind to port 5050 on the IP address 172.17.0.2 on the my-bridge network. You can then access the app at http://172.17.0.2:5050/.\nAlternatively, you can use the --publish flag to publish the container's port to the host's network interface. This will allow the container to bind to port 5050 on the host's network interface, and you can access the app at http://localhost:5050/. Here is an example of how you can run the container with the --publish flag:\n# run the container and publish port 5050 to the host's network interface\ndocker run -d --name sveltekit-app --publish 5050:5050 sveltekit:node\n\nWith this flag, the container will bind to port 5050 on the host's network interface, and you can access the app at http://localhost:5050/.\n" ]
[ 2, 2, 1, 0, 0, 0 ]
[]
[]
[ "docker", "dockerfile", "node.js", "svelte", "sveltekit" ]
stackoverflow_0074566341_docker_dockerfile_node.js_svelte_sveltekit.txt
Q: React app with react-router-dom not working in WordPress and ReactPress plugin I am trying to get a simple react app (create react app) with react-router-dom to work inside a WordPress site using the ReactPress plugin. Taking code straight from the ReactPress documentation, I have the React app working on localhost, but cannot get the routing to work within Wordpress. I have tried everything I've been able to find on the web -- fiddling with .htaccess, adding actions to stop WordPress routing, adding "homepage" to package.json, clearing the permalink cache, etc, but nothing has worked. The pages render fine if I place it straight in the App function. But when they are in Routes/Route, it stops working. I don't get any errors in production; I just get an empty div where the pages should render and a noscript message like below: Inspecting WordPress site: <noscript>You need to enable JavaScript to run this app.</noscript> <div id="root"> <div class="App"> <h1 id="root">Welcome to ReactPress with React Router!!!</h1> </div> </div> Any ideas what is wrong? index.js import React from 'react'; import ReactDOM from 'react-dom/client'; import App from './App'; import { BrowserRouter } from 'react-router-dom'; const root = ReactDOM.createRoot(document.getElementById('root')); root.render( <React.StrictMode> <BrowserRouter> <App /> </BrowserRouter> </React.StrictMode> ); App.js import React, { Component } from 'react'; import { Routes, Route, Link } from 'react-router-dom'; function Home() { return ( <> <main> <h2>Welcome to the homepage!</h2> <p>You can do this, I believe in you.</p> </main> <nav> <Link to="/about">About</Link> </nav> </> ); } function About() { return ( <> <main> <h2>Who are we?</h2> <p> That feels like an existential question, don't you think? </p> </main> <nav> <Link to="/">Home</Link> </nav> </> ); } export default function App() { return ( <div className="App"> <h1>Welcome to ReactPress with React Router!!!</h1> <Routes> <Route path="/" element={<Home />} /> <Route path="/about" element={<About />} /> </Routes> </div> ); } package.json { "name": "wp-react-test-react", "version": "0.1.0", "private": true, "dependencies": { "@reduxjs/toolkit": "^1.9.0", "@testing-library/jest-dom": "^5.16.5", "@testing-library/react": "^13.4.0", "@testing-library/user-event": "^13.5.0", "axios": "^1.1.3", "lodash": "^4.17.21", "react": "^18.2.0", "react-dom": "^18.2.0", "react-redux": "^8.0.5", "react-router-dom": "^6.4.3", "react-scripts": "^5.0.1", "redux": "^4.2.0", "web-vitals": "^2.1.4" }, "scripts": { "start": "react-scripts start", "build": "PUBLIC_URL=/wp-content/reactpress/apps/wp-react-test-react/build react-scripts build", "test": "react-scripts test", "eject": "react-scripts eject" }, "eslintConfig": { "extends": [ "react-app", "react-app/jest" ] }, "browserslist": { "production": [ ">0.2%", "not dead", "not op_mini all" ], "development": [ "last 1 chrome version", "last 1 firefox version", "last 1 safari version" ] } } A: You probably need to set the basePath in the BrowserRouter component. <BrowserRouter basename='/...'> ... </BrowserRouter> A: You are using a forward slash in the path, use the it like below without slashes. Also for the first/default route use index prop instead of path="/". <Routes> <Route index element={<Home />} /> <Route path="home" element={<Home />} /> <Route path="about" element={<About />} /> <Route path="*" element={<p>There's nothing here: 404!</p>} /> </Routes> Also instead of Link, I would recommend to use Navlink component as it automatically inherit an active class when clicked.
React app with react-router-dom not working in WordPress and ReactPress plugin
I am trying to get a simple react app (create react app) with react-router-dom to work inside a WordPress site using the ReactPress plugin. Taking code straight from the ReactPress documentation, I have the React app working on localhost, but cannot get the routing to work within Wordpress. I have tried everything I've been able to find on the web -- fiddling with .htaccess, adding actions to stop WordPress routing, adding "homepage" to package.json, clearing the permalink cache, etc, but nothing has worked. The pages render fine if I place it straight in the App function. But when they are in Routes/Route, it stops working. I don't get any errors in production; I just get an empty div where the pages should render and a noscript message like below: Inspecting WordPress site: <noscript>You need to enable JavaScript to run this app.</noscript> <div id="root"> <div class="App"> <h1 id="root">Welcome to ReactPress with React Router!!!</h1> </div> </div> Any ideas what is wrong? index.js import React from 'react'; import ReactDOM from 'react-dom/client'; import App from './App'; import { BrowserRouter } from 'react-router-dom'; const root = ReactDOM.createRoot(document.getElementById('root')); root.render( <React.StrictMode> <BrowserRouter> <App /> </BrowserRouter> </React.StrictMode> ); App.js import React, { Component } from 'react'; import { Routes, Route, Link } from 'react-router-dom'; function Home() { return ( <> <main> <h2>Welcome to the homepage!</h2> <p>You can do this, I believe in you.</p> </main> <nav> <Link to="/about">About</Link> </nav> </> ); } function About() { return ( <> <main> <h2>Who are we?</h2> <p> That feels like an existential question, don't you think? </p> </main> <nav> <Link to="/">Home</Link> </nav> </> ); } export default function App() { return ( <div className="App"> <h1>Welcome to ReactPress with React Router!!!</h1> <Routes> <Route path="/" element={<Home />} /> <Route path="/about" element={<About />} /> </Routes> </div> ); } package.json { "name": "wp-react-test-react", "version": "0.1.0", "private": true, "dependencies": { "@reduxjs/toolkit": "^1.9.0", "@testing-library/jest-dom": "^5.16.5", "@testing-library/react": "^13.4.0", "@testing-library/user-event": "^13.5.0", "axios": "^1.1.3", "lodash": "^4.17.21", "react": "^18.2.0", "react-dom": "^18.2.0", "react-redux": "^8.0.5", "react-router-dom": "^6.4.3", "react-scripts": "^5.0.1", "redux": "^4.2.0", "web-vitals": "^2.1.4" }, "scripts": { "start": "react-scripts start", "build": "PUBLIC_URL=/wp-content/reactpress/apps/wp-react-test-react/build react-scripts build", "test": "react-scripts test", "eject": "react-scripts eject" }, "eslintConfig": { "extends": [ "react-app", "react-app/jest" ] }, "browserslist": { "production": [ ">0.2%", "not dead", "not op_mini all" ], "development": [ "last 1 chrome version", "last 1 firefox version", "last 1 safari version" ] } }
[ "You probably need to set the basePath in the BrowserRouter component.\n<BrowserRouter basename='/...'>\n ...\n</BrowserRouter>\n\n", "You are using a forward slash in the path, use the it like below without slashes. Also for the first/default route use index prop instead of path=\"/\".\n <Routes>\n <Route index element={<Home />} />\n <Route path=\"home\" element={<Home />} />\n <Route path=\"about\" element={<About />} />\n <Route path=\"*\" element={<p>There's nothing here: 404!</p>} />\n </Routes>\n\nAlso instead of Link, I would recommend to use Navlink component as it automatically inherit an active class when clicked.\n" ]
[ 0, 0 ]
[]
[]
[ "javascript", "react_router_dom", "reactjs", "wordpress" ]
stackoverflow_0074397278_javascript_react_router_dom_reactjs_wordpress.txt
Q: How to implement own hashing function for strings? So this is the default algorithm that generates the hashcode for Strings: s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1] However, I wanna use something different and much more simple like adding the ASCII values of each character and then adding them all up. How do I make it so that it uses the algorithm I created, instead of using the default one when I use the put() method for hashtables? As of now I don't know what to do other than implementing a hash table from scratch. A: Create a new class, and use String type field in it. For example: public class MyString { private final String value; public MyString(String value) { this.value = value; } public String getValue() { return value; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; MyString myString = (MyString) o; return Objects.equals(value, myString.value); } @Override public int hashCode() { // use your own implementation return value.codePoints().sum(); } } Add equals() and hashCode() methods with @Override annotation. Note: here hashCode() operates only with ASCII values. After that, you will be able to use new class objects in the desired data structure. Here you can find a detailed explanation of these methods and a contract between equals() and hashCode().
How to implement own hashing function for strings?
So this is the default algorithm that generates the hashcode for Strings: s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1] However, I wanna use something different and much more simple like adding the ASCII values of each character and then adding them all up. How do I make it so that it uses the algorithm I created, instead of using the default one when I use the put() method for hashtables? As of now I don't know what to do other than implementing a hash table from scratch.
[ "Create a new class, and use String type field in it. For example:\npublic class MyString {\n private final String value;\n\n public MyString(String value) {\n this.value = value;\n }\n\n public String getValue() {\n return value;\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o) return true;\n if (o == null || getClass() != o.getClass()) return false;\n MyString myString = (MyString) o;\n return Objects.equals(value, myString.value);\n }\n\n @Override\n public int hashCode() {\n // use your own implementation\n return value.codePoints().sum();\n }\n}\n\nAdd equals() and hashCode() methods with @Override annotation.\nNote: here hashCode() operates only with ASCII values.\nAfter that, you will be able to use new class objects in the desired data structure. Here you can find a detailed explanation of these methods and a contract between equals() and hashCode().\n" ]
[ 5 ]
[]
[]
[ "hash", "hashtable", "java", "overriding" ]
stackoverflow_0074668731_hash_hashtable_java_overriding.txt
Q: Wagtail CMS(Django) - Display Inline Model Fields in Related Model I have two custom models(not inheriting from Page) that are specific to the admin in a Wagtail CMS website. I can get this working in regular Django, but in Wagtail I can't get the inline model fields to appear. I get a key error. The code... On model.py: from django.db import models from wagtail.admin.panels import ( FieldPanel, MultiFieldPanel, FieldRowPanel, InlinePanel, ) from author.models import Author class Book(models.Model): author = models.ForeignKey(Author, on_delete=models.CASCADE) date = models.DateField("Date released") panels = [ MultiFieldPanel([ InlinePanel('book_review'), ], heading="Book reviews"), ] class BookReview(models.Model): book = models.ForeignKey( Book, on_delete=models.CASCADE, related_name='book_review') title = models.CharField(max_length=250) content = models.TextField() panels = [ FieldRowPanel([ FieldPanel('title'), FieldPanel('content'), ]) ] and wagtail_hooks.py: from wagtail.contrib.modeladmin.options import ( ModelAdmin, modeladmin_register, ) from .models import Book, BookReview class BookAdmin(ModelAdmin): model = Book add_to_settings_menu = False add_to_admin_menu = True inlines = [BookReview] # only added this after key error, but it didn't help modeladmin_register(BookAdmin) How can I get the InlinePanel('book_review'), line to show up in the admin. It all works until I try add the inline model fields. I looked around online and it was mentioning a third party Django modelcluster package. Is this still required? Those post were quite old(5 years or so). Or instead of using ForeignKey use ParentalKey, but that's only if inheriting from Page model. A: Try changing your Book model to inherit from ClusterableModel (which itself inherits from models.Model) from modelcluster.models import ClusterableModel class Book(ClusterableModel):
Wagtail CMS(Django) - Display Inline Model Fields in Related Model
I have two custom models(not inheriting from Page) that are specific to the admin in a Wagtail CMS website. I can get this working in regular Django, but in Wagtail I can't get the inline model fields to appear. I get a key error. The code... On model.py: from django.db import models from wagtail.admin.panels import ( FieldPanel, MultiFieldPanel, FieldRowPanel, InlinePanel, ) from author.models import Author class Book(models.Model): author = models.ForeignKey(Author, on_delete=models.CASCADE) date = models.DateField("Date released") panels = [ MultiFieldPanel([ InlinePanel('book_review'), ], heading="Book reviews"), ] class BookReview(models.Model): book = models.ForeignKey( Book, on_delete=models.CASCADE, related_name='book_review') title = models.CharField(max_length=250) content = models.TextField() panels = [ FieldRowPanel([ FieldPanel('title'), FieldPanel('content'), ]) ] and wagtail_hooks.py: from wagtail.contrib.modeladmin.options import ( ModelAdmin, modeladmin_register, ) from .models import Book, BookReview class BookAdmin(ModelAdmin): model = Book add_to_settings_menu = False add_to_admin_menu = True inlines = [BookReview] # only added this after key error, but it didn't help modeladmin_register(BookAdmin) How can I get the InlinePanel('book_review'), line to show up in the admin. It all works until I try add the inline model fields. I looked around online and it was mentioning a third party Django modelcluster package. Is this still required? Those post were quite old(5 years or so). Or instead of using ForeignKey use ParentalKey, but that's only if inheriting from Page model.
[ "Try changing your Book model to inherit from ClusterableModel (which itself inherits from models.Model)\nfrom modelcluster.models import ClusterableModel\n\nclass Book(ClusterableModel):\n\n" ]
[ 0 ]
[]
[]
[ "django", "django_models", "python", "wagtail", "wagtail_admin" ]
stackoverflow_0074576306_django_django_models_python_wagtail_wagtail_admin.txt
Q: BAD USB Atmega32u4 - Problem with performing various activities on one USB I have a problem with the Atmega32u4 board. I'm creating a program on BadUSB, which, according to assumptions, should do 3 different things. The problem is that in between these activities the computer shuts down. My idea was a simple counter with if statements, but the board doesn't save the current state permanently. I was thinking about detecting the situation he is currently in, but I have no idea how to do it. Could you please help me? Functionality 1 - locked computer, opening CMD, entering the command. Turning off the computer Functionality 2 - unlocked computer, opening CMD, entering the command. Logging out of the account/unplugging the USB. Functionality 3 - locked computer, opening CMD, entering the command. Do you have any ideas how to detect these situations? Or possibly how to save the counter state "permanently" I made something like this: int i = 0; if (i == 0){ //Opening CMD Keyboard.press(KEY_LEFT_GUI); Keyboard.press('r'); Keyboard.releaseAll(); delay(1000); Keyboard.print("cmd.exe"); Keyboard.press(KEY_RETURN); Keyboard.releaseAll(); delay(1000); //First functionality Keyboard.print("echo Task 1"); Keyboard.press(KEY_RETURN); Keyboard.releaseAll(); delay(1000); i++; return; } else if (i == 1){ //Opening CMD Keyboard.press(KEY_LEFT_GUI); Keyboard.press('r'); Keyboard.releaseAll(); delay(1000); Keyboard.print("cmd.exe"); Keyboard.press(KEY_RETURN); Keyboard.releaseAll(); delay(1000); //Second functionality Keyboard.print("echo Task 2"); Keyboard.press(KEY_RETURN); Keyboard.releaseAll(); delay(1000); i++; return; } A: The ATmega32U4 has a 1 kB builtin EEPROM (See Datasheeet here). You can use that to store a persistent state when the chip is turned off. You tagged your question as Arduino, so here is a guide to using EEPROM with Arduino Libraries.
BAD USB Atmega32u4 - Problem with performing various activities on one USB
I have a problem with the Atmega32u4 board. I'm creating a program on BadUSB, which, according to assumptions, should do 3 different things. The problem is that in between these activities the computer shuts down. My idea was a simple counter with if statements, but the board doesn't save the current state permanently. I was thinking about detecting the situation he is currently in, but I have no idea how to do it. Could you please help me? Functionality 1 - locked computer, opening CMD, entering the command. Turning off the computer Functionality 2 - unlocked computer, opening CMD, entering the command. Logging out of the account/unplugging the USB. Functionality 3 - locked computer, opening CMD, entering the command. Do you have any ideas how to detect these situations? Or possibly how to save the counter state "permanently" I made something like this: int i = 0; if (i == 0){ //Opening CMD Keyboard.press(KEY_LEFT_GUI); Keyboard.press('r'); Keyboard.releaseAll(); delay(1000); Keyboard.print("cmd.exe"); Keyboard.press(KEY_RETURN); Keyboard.releaseAll(); delay(1000); //First functionality Keyboard.print("echo Task 1"); Keyboard.press(KEY_RETURN); Keyboard.releaseAll(); delay(1000); i++; return; } else if (i == 1){ //Opening CMD Keyboard.press(KEY_LEFT_GUI); Keyboard.press('r'); Keyboard.releaseAll(); delay(1000); Keyboard.print("cmd.exe"); Keyboard.press(KEY_RETURN); Keyboard.releaseAll(); delay(1000); //Second functionality Keyboard.print("echo Task 2"); Keyboard.press(KEY_RETURN); Keyboard.releaseAll(); delay(1000); i++; return; }
[ "The ATmega32U4 has a 1 kB builtin EEPROM (See Datasheeet here). You can use that to store a persistent state when the chip is turned off. You tagged your question as Arduino, so here is a guide to using EEPROM with Arduino Libraries.\n" ]
[ 0 ]
[]
[]
[ "arduino", "arduino_c++", "atmega", "if_statement" ]
stackoverflow_0074668157_arduino_arduino_c++_atmega_if_statement.txt
Q: Removing special characters from a text file My input.txt is as below \n\n \n \n\n \n\n\r\n\r\n \r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n \r\n \r\n \r\n\r\n\r\n \r\n\r\n\r\n\r\n \r\n\r\n\r\n\r\n\r\n\r\n\r\n hello boys\r\n boys\r\n boys\r\n\r\n Download PDF\r\n PDF\r\n X\r\n Close Window\r\n\r\n\r\n\r\n This boys text has undergone conversion so that it is mobile and web-friendly. This may have created formatting or alignment issues. Please refer to the PDF copy for a print-friendly version. \r\n\r\n\r\n\r\n\r\n\r\n\r\n \r\n BOYS CLUB AUSTRALIA \r\n 26 July 2019 \r\n hello boys \r\n \r\nhello boys \r\n -------------------------------------------------------------------------------------------------------------------------------------- \r\n Introduction \r\n\r\n 1. \r\n This letter to let you know that your application has been successful with our school \r\n I am trying to remove unnecessary patterns like "\n\n", "\r\r", "\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n" While parsing, I want to remove all the special patterns and want to have only text and numbers. I have tried as below. with open (data, "r", encoding='utf-8') as myfile: for line in myfile: line.rstrip() line = re.sub(r'\r\n', '', line) with open("out.txt", "a", encoding='utf-8') as output: output.write(line) But even '\r\n' is not getting removed in output file. Thanks. A: To remove special characters, such as newline characters (\n), from a text file in Python, you can use the replace() method of the str class. This method allows you to replace a specific character or string of characters with another character or string. A: You can use the replace() method to to replace the \r\n substrings with an empty string. with open(data, 'r', encoding='utf-8') as myfile: with open('out.txt', 'a', encoding='utf-8') as output: for line in myfile: output.write(line.replace('\r\n', '').rstrip()) A: You can use replace but also str.isprintable to filter out not printable characters: input_file = 'input.txt' output_file = 'output.txt' with open (input_file, "r", encoding='utf-8') as infile: with open(output_file, "w", encoding='utf-8') as outfile: for line in infile: outfile.write( ''.join(filter(str.isprintable, line.replace('\\n', '').replace('\\r', ''))) + '\n' ) So, the output is: hello boys boys boys Download PDF PDF X Close Window This boys text has undergone conversion so that it is mobile and web-friendly. This may have created formatting or alignment issues. Please refer to the PDF copy for a print-friendly version. BOYS CLUB AUSTRALIA 26 July 2019 hello boys hello boys -------------------------------------------------------------------------------------------------------------------------------------- Introduction 1. This letter to let you know that your application has been successful with our school
Removing special characters from a text file
My input.txt is as below \n\n \n \n\n \n\n\r\n\r\n \r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n \r\n \r\n \r\n\r\n\r\n \r\n\r\n\r\n\r\n \r\n\r\n\r\n\r\n\r\n\r\n\r\n hello boys\r\n boys\r\n boys\r\n\r\n Download PDF\r\n PDF\r\n X\r\n Close Window\r\n\r\n\r\n\r\n This boys text has undergone conversion so that it is mobile and web-friendly. This may have created formatting or alignment issues. Please refer to the PDF copy for a print-friendly version. \r\n\r\n\r\n\r\n\r\n\r\n\r\n \r\n BOYS CLUB AUSTRALIA \r\n 26 July 2019 \r\n hello boys \r\n \r\nhello boys \r\n -------------------------------------------------------------------------------------------------------------------------------------- \r\n Introduction \r\n\r\n 1. \r\n This letter to let you know that your application has been successful with our school \r\n I am trying to remove unnecessary patterns like "\n\n", "\r\r", "\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n" While parsing, I want to remove all the special patterns and want to have only text and numbers. I have tried as below. with open (data, "r", encoding='utf-8') as myfile: for line in myfile: line.rstrip() line = re.sub(r'\r\n', '', line) with open("out.txt", "a", encoding='utf-8') as output: output.write(line) But even '\r\n' is not getting removed in output file. Thanks.
[ "To remove special characters, such as newline characters (\\n), from a text file in Python, you can use the replace() method of the str class. This method allows you to replace a specific character or string of characters with another character or string.\n", "You can use the replace() method to to replace the \\r\\n substrings with an empty string.\nwith open(data, 'r', encoding='utf-8') as myfile:\n with open('out.txt', 'a', encoding='utf-8') as output:\n for line in myfile:\n output.write(line.replace('\\r\\n', '').rstrip())\n\n", "You can use replace but also str.isprintable to filter out not printable characters:\ninput_file = 'input.txt'\noutput_file = 'output.txt'\n\nwith open (input_file, \"r\", encoding='utf-8') as infile:\n with open(output_file, \"w\", encoding='utf-8') as outfile:\n for line in infile:\n outfile.write(\n ''.join(filter(str.isprintable, line.replace('\\\\n', '').replace('\\\\r', '')))\n + '\\n'\n )\n\nSo, the output is:\n hello boys boys boys Download PDF PDF X Close Window \nThis boys text has undergone conversion so that it is mobile and web-friendly. This may have created formatting or alignment issues. Please refer to the PDF copy for a print-friendly version.\n \nBOYS CLUB AUSTRALIA\n\n26 July 2019\n\nhello boys\n\nhello boys\n\n--------------------------------------------------------------------------------------------------------------------------------------\n\nIntroduction\n \n1. \nThis letter to let you know that your application has been successful with our school\n\n" ]
[ 1, 1, 1 ]
[]
[]
[ "parsing", "python_3.x" ]
stackoverflow_0074667821_parsing_python_3.x.txt
Q: v-Select active selection I'm using Vuetify (Vue 2.0) and have the following component : (https://vuetifyjs.com/en/components/selects/) <v-select v-model="mail" :items="mails" dense clearable chips menu-props="auto" label="..." v-on:change="..." prepend-icon="mdi-email-check"> <template slot="selection" slot-scope="data"> <v-chip small color="primary" text-color="white">{{data.item.dt_local}}</v-chip> </template> <template slot="item" slot-scope="data"> <v-list-item-avatar> <v-icon>mdi-timeline-clock-outline</v-icon> </v-list-item-avatar> <v-list-item-content> <span v-if="(data.item.subject == null)">Aucun objet</span> <span v-else>{{ data.item.subject }}</span> <v-list-item-title>{{ data.item.dt_local }} </v-list-item-title> </v-list-item-content> </template> </v-select> As a toy example : this.mails = [ { "subject": "Factures", "dt_local": "2022-12-03 09:54:48", }, { "subject": "Factures", "dt_local": "2022-12-03 09:39:39", }, { "subject": null, "dt_local": "2022-12-02 19:27:28", } ] The problem i'm having is the following. When i select any item i get the following output The image above is obtained after i select the last element of the v-select component. (the one with subject = null).All items look active. The expected output is as follows : A: You need to use the item-value prop in order to work with the active select element. You can do this like this- <v-select v-model="mail" :items="mails" dense clearable chips item-value="dt_local" menu-props="auto" prepend-icon="mdi-email-check" label="Select" return-object > YOUR CODE HERE </v-select>
v-Select active selection
I'm using Vuetify (Vue 2.0) and have the following component : (https://vuetifyjs.com/en/components/selects/) <v-select v-model="mail" :items="mails" dense clearable chips menu-props="auto" label="..." v-on:change="..." prepend-icon="mdi-email-check"> <template slot="selection" slot-scope="data"> <v-chip small color="primary" text-color="white">{{data.item.dt_local}}</v-chip> </template> <template slot="item" slot-scope="data"> <v-list-item-avatar> <v-icon>mdi-timeline-clock-outline</v-icon> </v-list-item-avatar> <v-list-item-content> <span v-if="(data.item.subject == null)">Aucun objet</span> <span v-else>{{ data.item.subject }}</span> <v-list-item-title>{{ data.item.dt_local }} </v-list-item-title> </v-list-item-content> </template> </v-select> As a toy example : this.mails = [ { "subject": "Factures", "dt_local": "2022-12-03 09:54:48", }, { "subject": "Factures", "dt_local": "2022-12-03 09:39:39", }, { "subject": null, "dt_local": "2022-12-02 19:27:28", } ] The problem i'm having is the following. When i select any item i get the following output The image above is obtained after i select the last element of the v-select component. (the one with subject = null).All items look active. The expected output is as follows :
[ "You need to use the item-value prop in order to work with the active select element.\nYou can do this like this-\n<v-select \n v-model=\"mail\" \n :items=\"mails\" \n dense \n clearable \n chips \n item-value=\"dt_local\"\n menu-props=\"auto\"\n prepend-icon=\"mdi-email-check\" \n label=\"Select\"\n return-object\n>\n YOUR CODE HERE\n</v-select>\n\n" ]
[ 0 ]
[]
[]
[ "vue.js", "vuetify.js" ]
stackoverflow_0074665423_vue.js_vuetify.js.txt
Q: EditText.contains not working with Array List List Array.asList with bad words, if a person enters one of the bad words, an error will be thrown. But for some reason the List with bad words is ignored and the error is not displayed. String nick = EditText.getText().toString().trim(); List<String> bad_words = Arrays.asList("bad_word1", "bad_word2"); if (nick.contains(bad_words.toString())){ EditText.setError("Don't use bad words!"); } A: import java.util.*; import java.util.stream.*; public class MyClass { List<String> badWords = Arrays.asList("BadWord", "OtherBadWord"); public boolean containsBadWord(String input) { return badWords.stream().anyMatch(badWord -> input.contains(badWord)); } public static void main(String args[]) { String input = "ThereIsABadWordHere"; String input2 = "ThisDoesNotHaveAnythingBad"; MyClass mc = new MyClass(); System.out.println("Does input contain a bad word? " + mc.containsBadWord(input)); System.out.println("Does input2 contain a bad word? " + mc.containsBadWord(input2)); } } Output: Does input contain a bad word? true Does input2 contain a bad word? false Building on what @krankkk suggested, you can check if any word in the banned words list is contained in the input string like this. Simply stream over the list of banned words, see if each banned word is contained in the input string, and if the count of times that happened is greater than zero, at least one bad word was contained in the input.
EditText.contains not working with Array List
List Array.asList with bad words, if a person enters one of the bad words, an error will be thrown. But for some reason the List with bad words is ignored and the error is not displayed. String nick = EditText.getText().toString().trim(); List<String> bad_words = Arrays.asList("bad_word1", "bad_word2"); if (nick.contains(bad_words.toString())){ EditText.setError("Don't use bad words!"); }
[ "import java.util.*;\nimport java.util.stream.*;\npublic class MyClass {\n List<String> badWords = Arrays.asList(\"BadWord\", \"OtherBadWord\");\n \n public boolean containsBadWord(String input) {\n return badWords.stream().anyMatch(badWord -> input.contains(badWord));\n }\n \n public static void main(String args[]) {\n String input = \"ThereIsABadWordHere\";\n String input2 = \"ThisDoesNotHaveAnythingBad\";\n MyClass mc = new MyClass();\n System.out.println(\"Does input contain a bad word? \" + mc.containsBadWord(input));\n System.out.println(\"Does input2 contain a bad word? \" + mc.containsBadWord(input2));\n }\n}\n\nOutput:\nDoes input contain a bad word? true\nDoes input2 contain a bad word? false\nBuilding on what @krankkk suggested, you can check if any word in the banned words list is contained in the input string like this. Simply stream over the list of banned words, see if each banned word is contained in the input string, and if the count of times that happened is greater than zero, at least one bad word was contained in the input.\n" ]
[ 0 ]
[]
[]
[ "android", "android_edittext", "arrays", "java", "list" ]
stackoverflow_0074668570_android_android_edittext_arrays_java_list.txt
Q: Getting a client token from Identity Duende Server in Angular For a project I am running a .NET API server, Duende Identity Server, and the client side is an Angular app. When there is a user logged in, the client app can do all the CRUD operations, when there is no user logged in it can only do the read operations. I first did this by putting the [Authorize] decorator on the endpoints only a logged in user can access. But this means that anybody that knows the urls to the endpoints can access that information. This is not considered good practice, so if there is no user logged in, I want to send a client token with my request, so in my API server I can respond correctly on my endpoints. I am able to do this in Postman, by configuring my new token as follows: PostMan Screenshot And then using the token it gets to do the read operation on the API. But I am unable to reproduce this in Angular. This is my code so far: ` getToken() { const headers = new HttpHeaders(); headers.set('Authorization', `Basic client:secret`); headers.set("Content-Type", "application/json"); const requestOptions = { headers: headers }; let body = { "grant_type": "client_credentials", "client_id": "client", "client_secret": "secret", "scopes": "api", "response_type": "id_token token" } this.http.post("https://localhost:5001/connect/token", body, requestOptions).subscribe( result => { console.log(result); }) } ` I have tried endless variations, but I keep getting a status code 400 error:"invalid_request" A: When you make requests from JavaScript, you also need to configure CORS correctly. Postman does not need CORS, but browsers do. I would look at the failing request and response using a tool like https://www.telerik.com/fiddler Also, perhaps post a sample response in your request? I would also see the logs in IdentityServer for clues why the request fails.
Getting a client token from Identity Duende Server in Angular
For a project I am running a .NET API server, Duende Identity Server, and the client side is an Angular app. When there is a user logged in, the client app can do all the CRUD operations, when there is no user logged in it can only do the read operations. I first did this by putting the [Authorize] decorator on the endpoints only a logged in user can access. But this means that anybody that knows the urls to the endpoints can access that information. This is not considered good practice, so if there is no user logged in, I want to send a client token with my request, so in my API server I can respond correctly on my endpoints. I am able to do this in Postman, by configuring my new token as follows: PostMan Screenshot And then using the token it gets to do the read operation on the API. But I am unable to reproduce this in Angular. This is my code so far: ` getToken() { const headers = new HttpHeaders(); headers.set('Authorization', `Basic client:secret`); headers.set("Content-Type", "application/json"); const requestOptions = { headers: headers }; let body = { "grant_type": "client_credentials", "client_id": "client", "client_secret": "secret", "scopes": "api", "response_type": "id_token token" } this.http.post("https://localhost:5001/connect/token", body, requestOptions).subscribe( result => { console.log(result); }) } ` I have tried endless variations, but I keep getting a status code 400 error:"invalid_request"
[ "When you make requests from JavaScript, you also need to configure CORS correctly. Postman does not need CORS, but browsers do.\nI would look at the failing request and response using a tool like https://www.telerik.com/fiddler\nAlso, perhaps post a sample response in your request?\nI would also see the logs in IdentityServer for clues why the request fails.\n" ]
[ 0 ]
[]
[]
[ "angular", "angular14", "duende_identity_server", "jwt", "token" ]
stackoverflow_0074655611_angular_angular14_duende_identity_server_jwt_token.txt
Q: Unable to access to a fragment that have nullable argument using navigation components My OrdersFragment has one nullable argument called Option: <argument android:name="option" app:argType="string" app:nullable="true" /> To work with nullable args I have declared a variable of this way above of the onViewCreated method private val args : OrdersFragmentArgs? by navArgs() And inside the onViewCreated of this fragment I have: args?.let { if(it.option.equals("Completada")){ getCompletedOrders() }else if (it.option.equals("Cancelada")){ getCanceledOrders() } } Then when I compile the app and I went to the ordesFragment the app got crash: E/AndroidRuntime: FATAL EXCEPTION: main Process: com.example.elrestaurante, PID: 3388 java.lang.RuntimeException: java.lang.reflect.InvocationTargetException at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:581) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1135) Caused by: java.lang.reflect.InvocationTargetException at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:571) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1135) Caused by: java.lang.reflect.InvocationTargetException at java.lang.reflect.Method.invoke(Native Method) at androidx.navigation.NavArgsLazy.getValue(NavArgsLazy.kt:54) at androidx.navigation.NavArgsLazy.getValue(NavArgsLazy.kt:35) at com.example.elrestaurante.ui.orders.OrdersFragment.getArgs(OrdersFragment.kt:62) at com.example.elrestaurante.ui.orders.OrdersFragment.onViewCreated(OrdersFragment.kt:83) at androidx.fragment.app.Fragment.performViewCreated(Fragment.java:3128) at androidx.fragment.app.FragmentStateManager.createView(FragmentStateManager.java:552) at androidx.fragment.app.FragmentStateManager.moveToExpectedState(FragmentStateManager.java:261) at androidx.fragment.app.FragmentManager.executeOpsTogether(FragmentManager.java:1890) at androidx.fragment.app.FragmentManager.removeRedundantOperationsAndExecute(FragmentManager.java:1814) at androidx.fragment.app.FragmentManager.execPendingActions(FragmentManager.java:1751) at androidx.fragment.app.FragmentManager$5.run(FragmentManager.java:538) at android.os.Handler.handleCallback(Handler.java:938) at android.os.Handler.dispatchMessage(Handler.java:99) at android.os.Looper.loopOnce(Looper.java:226) at android.os.Looper.loop(Looper.java:313) at android.app.ActivityThread.main(ActivityThread.java:8669) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:571) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1135) Caused by: java.lang.IllegalArgumentException: Required argument "option" is missing and does not have an android:defaultValue at com.example.elrestaurante.ui.orders.OrdersFragmentArgs.fromBundle(OrdersFragmentArgs.java:36) at java.lang.reflect.Method.invoke(Native Method) at androidx.navigation.NavArgsLazy.getValue(NavArgsLazy.kt:54) at androidx.navigation.NavArgsLazy.getValue(NavArgsLazy.kt:35) at com.example.elrestaurante.ui.orders.OrdersFragment.getArgs(OrdersFragment.kt:62) at com.example.elrestaurante.ui.orders.OrdersFragment.onViewCreated(OrdersFragment.kt:83) at androidx.fragment.app.Fragment.performViewCreated(Fragment.java:3128) at androidx.fragment.app.FragmentStateManager.createView(FragmentStateManager.java:552) at androidx.fragment.app.FragmentStateManager.moveToExpectedState(FragmentStateManager.java:261) at androidx.fragment.app.FragmentManager.executeOpsTogether(FragmentManager.java:1890) at androidx.fragment.app.FragmentManager.removeRedundantOperationsAndExecute(FragmentManager.java:1814) at androidx.fragment.app.FragmentManager.execPendingActions(FragmentManager.java:1751) at androidx.fragment.app.FragmentManager$5.run(FragmentManager.java:538) at android.os.Handler.handleCallback(Handler.java:938) at android.os.Handler.dispatchMessage(Handler.java:99) at android.os.Looper.loopOnce(Looper.java:226) at android.os.Looper.loop(Looper.java:313) at android.app.ActivityThread.main(ActivityThread.java:8669) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:571) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1135) I/Process: Sending signal. PID: 3388 SIG: 9 The error points to the condition args?.let { ... I don't know what to do, please dears if you have some idea to fix this problem I will appreciate it. I just want send a parameter called option from "EditOrderFragment" to "OrdersFragment" but now I can't access to OrdersFragment, I don't know why happens this error, maybe is a bug? thanks so much. PD: I'm using this versions: id 'androidx.navigation.safeargs' version '2.5.3' apply false //Navigation components implementation "androidx.navigation:navigation-fragment-ktx:2.5.0" implementation "androidx.navigation:navigation-ui-ktx:2.5.0" A: When using the navigation components in Android, you can pass arguments to a destination fragment. However, if the argument is nullable then you will get an error when trying to access the fragment. To solve this issue, you can use a Bundle object instead of the nullable argument. You can store the parameter (option) in a bundle and then pass that bundle to the destination fragment. This way, you can ensure that the argument is not null and it can be passed safely to the destination fragment. For example, you can do the following: //Store the parameter in a bundle val bundle = Bundle() bundle.putString("option", option) //pass the bundle to the destination fragment navController.navigate(R.id.ordersFragment, bundle) This way, you can pass the parameter (option) safely to the destination fragment.
Unable to access to a fragment that have nullable argument using navigation components
My OrdersFragment has one nullable argument called Option: <argument android:name="option" app:argType="string" app:nullable="true" /> To work with nullable args I have declared a variable of this way above of the onViewCreated method private val args : OrdersFragmentArgs? by navArgs() And inside the onViewCreated of this fragment I have: args?.let { if(it.option.equals("Completada")){ getCompletedOrders() }else if (it.option.equals("Cancelada")){ getCanceledOrders() } } Then when I compile the app and I went to the ordesFragment the app got crash: E/AndroidRuntime: FATAL EXCEPTION: main Process: com.example.elrestaurante, PID: 3388 java.lang.RuntimeException: java.lang.reflect.InvocationTargetException at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:581) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1135) Caused by: java.lang.reflect.InvocationTargetException at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:571) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1135) Caused by: java.lang.reflect.InvocationTargetException at java.lang.reflect.Method.invoke(Native Method) at androidx.navigation.NavArgsLazy.getValue(NavArgsLazy.kt:54) at androidx.navigation.NavArgsLazy.getValue(NavArgsLazy.kt:35) at com.example.elrestaurante.ui.orders.OrdersFragment.getArgs(OrdersFragment.kt:62) at com.example.elrestaurante.ui.orders.OrdersFragment.onViewCreated(OrdersFragment.kt:83) at androidx.fragment.app.Fragment.performViewCreated(Fragment.java:3128) at androidx.fragment.app.FragmentStateManager.createView(FragmentStateManager.java:552) at androidx.fragment.app.FragmentStateManager.moveToExpectedState(FragmentStateManager.java:261) at androidx.fragment.app.FragmentManager.executeOpsTogether(FragmentManager.java:1890) at androidx.fragment.app.FragmentManager.removeRedundantOperationsAndExecute(FragmentManager.java:1814) at androidx.fragment.app.FragmentManager.execPendingActions(FragmentManager.java:1751) at androidx.fragment.app.FragmentManager$5.run(FragmentManager.java:538) at android.os.Handler.handleCallback(Handler.java:938) at android.os.Handler.dispatchMessage(Handler.java:99) at android.os.Looper.loopOnce(Looper.java:226) at android.os.Looper.loop(Looper.java:313) at android.app.ActivityThread.main(ActivityThread.java:8669) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:571) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1135) Caused by: java.lang.IllegalArgumentException: Required argument "option" is missing and does not have an android:defaultValue at com.example.elrestaurante.ui.orders.OrdersFragmentArgs.fromBundle(OrdersFragmentArgs.java:36) at java.lang.reflect.Method.invoke(Native Method) at androidx.navigation.NavArgsLazy.getValue(NavArgsLazy.kt:54) at androidx.navigation.NavArgsLazy.getValue(NavArgsLazy.kt:35) at com.example.elrestaurante.ui.orders.OrdersFragment.getArgs(OrdersFragment.kt:62) at com.example.elrestaurante.ui.orders.OrdersFragment.onViewCreated(OrdersFragment.kt:83) at androidx.fragment.app.Fragment.performViewCreated(Fragment.java:3128) at androidx.fragment.app.FragmentStateManager.createView(FragmentStateManager.java:552) at androidx.fragment.app.FragmentStateManager.moveToExpectedState(FragmentStateManager.java:261) at androidx.fragment.app.FragmentManager.executeOpsTogether(FragmentManager.java:1890) at androidx.fragment.app.FragmentManager.removeRedundantOperationsAndExecute(FragmentManager.java:1814) at androidx.fragment.app.FragmentManager.execPendingActions(FragmentManager.java:1751) at androidx.fragment.app.FragmentManager$5.run(FragmentManager.java:538) at android.os.Handler.handleCallback(Handler.java:938) at android.os.Handler.dispatchMessage(Handler.java:99) at android.os.Looper.loopOnce(Looper.java:226) at android.os.Looper.loop(Looper.java:313) at android.app.ActivityThread.main(ActivityThread.java:8669) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:571) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1135) I/Process: Sending signal. PID: 3388 SIG: 9 The error points to the condition args?.let { ... I don't know what to do, please dears if you have some idea to fix this problem I will appreciate it. I just want send a parameter called option from "EditOrderFragment" to "OrdersFragment" but now I can't access to OrdersFragment, I don't know why happens this error, maybe is a bug? thanks so much. PD: I'm using this versions: id 'androidx.navigation.safeargs' version '2.5.3' apply false //Navigation components implementation "androidx.navigation:navigation-fragment-ktx:2.5.0" implementation "androidx.navigation:navigation-ui-ktx:2.5.0"
[ "When using the navigation components in Android, you can pass arguments to a destination fragment. However, if the argument is nullable then you will get an error when trying to access the fragment.\nTo solve this issue, you can use a Bundle object instead of the nullable argument. You can store the parameter (option) in a bundle and then pass that bundle to the destination fragment. This way, you can ensure that the argument is not null and it can be passed safely to the destination fragment.\nFor example, you can do the following:\n//Store the parameter in a bundle\nval bundle = Bundle()\nbundle.putString(\"option\", option)\n\n//pass the bundle to the destination fragment\nnavController.navigate(R.id.ordersFragment, bundle)\n\nThis way, you can pass the parameter (option) safely to the destination fragment.\n" ]
[ -1 ]
[]
[]
[ "android", "android_fragments", "android_safe_args", "kotlin" ]
stackoverflow_0074668658_android_android_fragments_android_safe_args_kotlin.txt
Q: nodejs express ReferenceError: next is not defined I am trying to control the input I took from a form with joi validation. The function validateCampgrount is a middleware to check it but when I try to write the next function it says next is not defined.* Where I am using next() const validateCampground = (req, res, next) => { const { error } = campgroundSchema.validate(req.body); if (error) { const msg = error.details.map((el) => el.message).join(","); throw new ExpressError(msg, 400); } else { next(); } }; Error Message next(); ^ ReferenceError: next is not defined Where I am using function app.post( "/campgrounds", validateCampground( catchAsync(async (req, res, next) => { // if(!req.body.campground) throw new ExpressError('Invalid Data', 400) const campground = new Campground(req.body.campground); await campground.save(); res.redirect(`/campgrounds/${campground._id}`); }) ) ); A: It seems that you are using middleware wrong. See this tutorial for a full guide. In your code, you are wrapping a function in your middleware. Instead, you need to pass the middleware as a parameter to app.post(). Like this: app.post("/campgrounds", validateCampground, async (req, res, next) => { const campground = new Campground(req.body.campground); await campground.save(); res.redirect(`/campgrounds/${campground._id}`); }); A: The error message "next is not defined" indicates that the next() function is not available in the current scope. In your code, you are calling the validateCampground() function and passing the result of this function (which is a middleware function that takes three arguments: req, res, and next) to the catchAsync() function. However, the catchAsync() function expects a callback function as its argument, not the result of calling a function. To fix this error, you need to pass the callback function directly to the catchAsync() function, without calling ``validateCampground() first. Here is an updated version of the code that should fix the error: app.post( "/campgrounds", catchAsync(async (req, res, next) => { validateCampground(req, res, next); // if(!req.body.campground) throw new ExpressError('Invalid Data', 400) const campground = new Campground(req.body.campground); await campground.save(); res.redirect(`/campgrounds/${campground._id}`); }) ); In this updated code, the validateCampground() function is called within the callback function passed to the catchAsync() function, so the next() function is available in the correct scope. This should fix the "next is not defined" error.
nodejs express ReferenceError: next is not defined
I am trying to control the input I took from a form with joi validation. The function validateCampgrount is a middleware to check it but when I try to write the next function it says next is not defined.* Where I am using next() const validateCampground = (req, res, next) => { const { error } = campgroundSchema.validate(req.body); if (error) { const msg = error.details.map((el) => el.message).join(","); throw new ExpressError(msg, 400); } else { next(); } }; Error Message next(); ^ ReferenceError: next is not defined Where I am using function app.post( "/campgrounds", validateCampground( catchAsync(async (req, res, next) => { // if(!req.body.campground) throw new ExpressError('Invalid Data', 400) const campground = new Campground(req.body.campground); await campground.save(); res.redirect(`/campgrounds/${campground._id}`); }) ) );
[ "It seems that you are using middleware wrong. See this tutorial for a full guide.\nIn your code, you are wrapping a function in your middleware. Instead, you need to pass the middleware as a parameter to app.post(). Like this:\napp.post(\"/campgrounds\", validateCampground, async (req, res, next) => {\n const campground = new Campground(req.body.campground);\n await campground.save();\n res.redirect(`/campgrounds/${campground._id}`);\n});\n\n", "The error message \"next is not defined\" indicates that the next() function is not available in the current scope.\nIn your code, you are calling the validateCampground() function and passing the result of this function (which is a middleware function that takes three arguments: req, res, and next) to the catchAsync() function. However, the catchAsync() function expects a callback function as its argument, not the result of calling a function.\nTo fix this error, you need to pass the callback function directly to the catchAsync() function, without calling ``validateCampground() first. Here is an updated version of the code that should fix the error:\napp.post(\n \"/campgrounds\",\n catchAsync(async (req, res, next) => {\n validateCampground(req, res, next);\n\n // if(!req.body.campground) throw new ExpressError('Invalid Data', 400)\n const campground = new Campground(req.body.campground);\n await campground.save();\n res.redirect(`/campgrounds/${campground._id}`);\n })\n);\n\nIn this updated code, the validateCampground() function is called within the callback function passed to the catchAsync() function, so the next() function is available in the correct scope. This should fix the \"next is not defined\" error.\n" ]
[ 2, 1 ]
[]
[]
[ "express", "javascript", "node.js" ]
stackoverflow_0074668626_express_javascript_node.js.txt
Q: How to deal with "ValueError: Domain error in arguments" while using sklearn.model_selection.RandomizedSearchCV? I am applying a randomized search on hyper parameters of anSGDClassifier. However, I am not sure why randomizedsearch_estimator.fit(x_train, y_train) is not outputting correct values. from constants import (SPLITS_NUM, SEED, N_JOBS, PROBLEM_METRIC) from sklearn.linear_model import SGDClassifier from sklearn.model_selection import (KFold, RandomizedSearchCV) from scipy.stats import (randint, uniform) def randomized_search(estimator, param_distributions, x_train, y_train, x_validation, y_validation): kfold = KFold(n_splits=SPLITS_NUM, shuffle=True, random_state=SEED) randomizedsearch_estimator = RandomizedSearchCV(estimator, param_distributions, cv=kfold, return_train_score=True, n_jobs=N_JOBS, scoring=PROBLEM_METRIC) search = randomizedsearch_estimator.fit(x_train, y_train) print(f"Best estimator:\n{search.best_estimator_} \ \nBest parameters:\n{search.best_params_} \ \nBest cross-validation score: {search.best_score_:.3f} \ \nBest test score: {search.score(x_validation, y_validation):.3f}\n\n") def searching_list(): return [(SGDClassifier(random_state=SEED, learning_rate='optimal', class_weight='balanced'), { 'alpha': uniform(0.15, 0.25), 'l1_ratio': uniform(0.002, 0.008), 'max_iter': randint(45000, 55000), 'tol': uniform(0.04, 0.12), 'epsilon': uniform(45000, 55000), 'power_t': uniform(-100000, -50000), 'loss': [ 'hinge', 'log_loss', 'modified_huber', 'squared_hinge', 'perceptron', 'squared_error', 'huber', 'epsilon_insensitive', 'squared_epsilon_insensitive' ], 'penalty': ['l2', 'l1', 'elasticnet'] })] def parameter_initializer(features_train, target_train, features_validation, target_validation): for model, distribution in searching_list(): randomized_search(model, distribution, features_train, target_train, features_validation, target_validation) Traceback (most recent call last): File "c:\Users\username\Desktop\some-calculator\graph-analyzer\graph_analyzer.py", line 197, in <module> main() File "c:\Users\username\Desktop\some-calculator\graph-analyzer\graph_analyzer.py", line 191, in main predicted_class = node_class_predictor(new_graph) File "c:\Users\username\Desktop\some-calculator\graph-analyzer\utilities_module.py", line 3379, in node_class_predictor x_test, y_test, clf = custom_classifier(emb_df) File "c:\Users\username\Desktop\some-calculator\graph-analyzer\utilities_module.py", line 3337, in custom_classifier parameter_initializer(x_train, y_train, x_test, y_test) File "c:\Users\username\Desktop\some-calculator\graph-analyzer\utilities_module.py", line 3129, in parameter_initializer randomized_search(model, distribution, features_train, target_train, features_validation, File "c:\Users\username\Desktop\some-calculator\graph-analyzer\utilities_module.py", line 3079, in randomized_search search = randomizedsearch_estimator.fit(x_train, y_train) File "C:\ProgramData\Anaconda3\envs\tf\lib\site-packages\sklearn\model_selection\_search.py", line 875, in fit self._run_search(evaluate_candidates) File "C:\ProgramData\Anaconda3\envs\tf\lib\site-packages\sklearn\model_selection\_search.py", line 1749, in _run_search evaluate_candidates( File "C:\ProgramData\Anaconda3\envs\tf\lib\site-packages\sklearn\model_selection\_search.py", line 811, in evaluate_candidatesates candidate_params = list(candidate_params) File "C:\ProgramData\Anaconda3\envs\tf\lib\site-packages\sklearn\model_selection\_search.py", line 324, in __iter__ params[k] = v.rvs(random_state=rng) File "C:\ProgramData\Anaconda3\envs\tf\lib\site-packages\scipy\stats\_distn_infrastructure.py", line 473, in rvs return self.dist.rvs(*self.args, **kwds) File "C:\ProgramData\Anaconda3\envs\tf\lib\site-packages\scipy\stats\_distn_infrastructure.py", line 1068, in rvs raise ValueError("Domain error in arguments.") ValueError: Domain error in arguments. A: when i got domain error it was due to me entering hyperparameter ranges in reverse order e.g., optimize__lr:reciprocal(3e-3,3e-4) and when changed to reciprocal(3e-4,3e-1) it was solved. so i suggest tinkering with the hyperparameter values and reversing them
How to deal with "ValueError: Domain error in arguments" while using sklearn.model_selection.RandomizedSearchCV?
I am applying a randomized search on hyper parameters of anSGDClassifier. However, I am not sure why randomizedsearch_estimator.fit(x_train, y_train) is not outputting correct values. from constants import (SPLITS_NUM, SEED, N_JOBS, PROBLEM_METRIC) from sklearn.linear_model import SGDClassifier from sklearn.model_selection import (KFold, RandomizedSearchCV) from scipy.stats import (randint, uniform) def randomized_search(estimator, param_distributions, x_train, y_train, x_validation, y_validation): kfold = KFold(n_splits=SPLITS_NUM, shuffle=True, random_state=SEED) randomizedsearch_estimator = RandomizedSearchCV(estimator, param_distributions, cv=kfold, return_train_score=True, n_jobs=N_JOBS, scoring=PROBLEM_METRIC) search = randomizedsearch_estimator.fit(x_train, y_train) print(f"Best estimator:\n{search.best_estimator_} \ \nBest parameters:\n{search.best_params_} \ \nBest cross-validation score: {search.best_score_:.3f} \ \nBest test score: {search.score(x_validation, y_validation):.3f}\n\n") def searching_list(): return [(SGDClassifier(random_state=SEED, learning_rate='optimal', class_weight='balanced'), { 'alpha': uniform(0.15, 0.25), 'l1_ratio': uniform(0.002, 0.008), 'max_iter': randint(45000, 55000), 'tol': uniform(0.04, 0.12), 'epsilon': uniform(45000, 55000), 'power_t': uniform(-100000, -50000), 'loss': [ 'hinge', 'log_loss', 'modified_huber', 'squared_hinge', 'perceptron', 'squared_error', 'huber', 'epsilon_insensitive', 'squared_epsilon_insensitive' ], 'penalty': ['l2', 'l1', 'elasticnet'] })] def parameter_initializer(features_train, target_train, features_validation, target_validation): for model, distribution in searching_list(): randomized_search(model, distribution, features_train, target_train, features_validation, target_validation) Traceback (most recent call last): File "c:\Users\username\Desktop\some-calculator\graph-analyzer\graph_analyzer.py", line 197, in <module> main() File "c:\Users\username\Desktop\some-calculator\graph-analyzer\graph_analyzer.py", line 191, in main predicted_class = node_class_predictor(new_graph) File "c:\Users\username\Desktop\some-calculator\graph-analyzer\utilities_module.py", line 3379, in node_class_predictor x_test, y_test, clf = custom_classifier(emb_df) File "c:\Users\username\Desktop\some-calculator\graph-analyzer\utilities_module.py", line 3337, in custom_classifier parameter_initializer(x_train, y_train, x_test, y_test) File "c:\Users\username\Desktop\some-calculator\graph-analyzer\utilities_module.py", line 3129, in parameter_initializer randomized_search(model, distribution, features_train, target_train, features_validation, File "c:\Users\username\Desktop\some-calculator\graph-analyzer\utilities_module.py", line 3079, in randomized_search search = randomizedsearch_estimator.fit(x_train, y_train) File "C:\ProgramData\Anaconda3\envs\tf\lib\site-packages\sklearn\model_selection\_search.py", line 875, in fit self._run_search(evaluate_candidates) File "C:\ProgramData\Anaconda3\envs\tf\lib\site-packages\sklearn\model_selection\_search.py", line 1749, in _run_search evaluate_candidates( File "C:\ProgramData\Anaconda3\envs\tf\lib\site-packages\sklearn\model_selection\_search.py", line 811, in evaluate_candidatesates candidate_params = list(candidate_params) File "C:\ProgramData\Anaconda3\envs\tf\lib\site-packages\sklearn\model_selection\_search.py", line 324, in __iter__ params[k] = v.rvs(random_state=rng) File "C:\ProgramData\Anaconda3\envs\tf\lib\site-packages\scipy\stats\_distn_infrastructure.py", line 473, in rvs return self.dist.rvs(*self.args, **kwds) File "C:\ProgramData\Anaconda3\envs\tf\lib\site-packages\scipy\stats\_distn_infrastructure.py", line 1068, in rvs raise ValueError("Domain error in arguments.") ValueError: Domain error in arguments.
[ "when i got domain error it was due to me entering hyperparameter ranges in reverse order e.g., optimize__lr:reciprocal(3e-3,3e-4) and when changed to reciprocal(3e-4,3e-1) it was solved. so i suggest tinkering with the hyperparameter values and reversing them\n" ]
[ 0 ]
[]
[]
[ "machine_learning", "python_3.x", "scikit_learn", "scipy", "sgdclassifier" ]
stackoverflow_0072944733_machine_learning_python_3.x_scikit_learn_scipy_sgdclassifier.txt
Q: Vue js $vm0 is not defined Can someone help real quick. I'm trying to test something with Vue instance in console, but in console when I write $vm0 or $vm0.$children Uncaught ReferenceError: $vm0 is not definedat :1:1 A: This only works if you have vue dev tools installed. Make sure you select the component first. It should look something like this: Then you can inspect it in the console tab of chrome dev tools. A: The question was initially asked for Vue2 I suppose, where you could use $vm0.$route.query to get access to various objects on the $vm0 Vue instance, here: router queries. In Vue3, that one has changed in favor of $vm0.proxy.$route.query
Vue js $vm0 is not defined
Can someone help real quick. I'm trying to test something with Vue instance in console, but in console when I write $vm0 or $vm0.$children Uncaught ReferenceError: $vm0 is not definedat :1:1
[ "This only works if you have vue dev tools installed. Make sure you select the component first. It should look something like this: \n\nThen you can inspect it in the console tab of chrome dev tools.\n", "The question was initially asked for Vue2 I suppose, where you could use\n$vm0.$route.query\n\nto get access to various objects on the $vm0 Vue instance, here: router queries.\n\nIn Vue3, that one has changed in favor of\n$vm0.proxy.$route.query\n\n" ]
[ 10, 0 ]
[]
[]
[ "laravel", "vue.js" ]
stackoverflow_0047073610_laravel_vue.js.txt
Q: Power Bi Plot dataset with x-axis dates I am working with a dataset with which I am creating a dashboard. My dataset is very simple, a first column of [yyyy-mm-dd-hh-mm], and a second column with many values. I read in many threads and forum about the difficulty to plot dates on x-axis (including hours and minuts). As reference I am using this dashboard built in PowerBi https://www.terna.it/it/sistema-elettrico/transparency-report/total-load .(Public data of Italian electric energy generation) This is exactly the outcome I would like to obtain, but by now I cannot display the hours and minuts. I used their data to reproduce the dashboard. I tried to switch from a "dates" x-axis to a "text" x-axis, but the result is not the same, and furthermore the plot does not occupy the whole page but I have to move to the right. enter image description here I really cannot understand how the linked dashboard was built. Any idea? A: I guess your problem is that you have been using Date Hierarchy on the x-Axis you instead of Date only.
Power Bi Plot dataset with x-axis dates
I am working with a dataset with which I am creating a dashboard. My dataset is very simple, a first column of [yyyy-mm-dd-hh-mm], and a second column with many values. I read in many threads and forum about the difficulty to plot dates on x-axis (including hours and minuts). As reference I am using this dashboard built in PowerBi https://www.terna.it/it/sistema-elettrico/transparency-report/total-load .(Public data of Italian electric energy generation) This is exactly the outcome I would like to obtain, but by now I cannot display the hours and minuts. I used their data to reproduce the dashboard. I tried to switch from a "dates" x-axis to a "text" x-axis, but the result is not the same, and furthermore the plot does not occupy the whole page but I have to move to the right. enter image description here I really cannot understand how the linked dashboard was built. Any idea?
[ "I guess your problem is that you have been using Date Hierarchy on the x-Axis you instead of Date only.\n\n\n" ]
[ 0 ]
[]
[]
[ "date", "plot", "powerbi" ]
stackoverflow_0074667931_date_plot_powerbi.txt
Q: Meaning of SumOffsetLag in MsK cloudwatch data? We have kafka which we are monitoring using grafana dashboad provided by aws cloud watch. From the past few days we are seeing some abnormality. I dont have Idea much about SumOffsetLag metric parameter. How this spiked value can degrade the performance and how we can improve it A: Consumer-lag monitoring Monitoring consumer lag allows you to identify slow or stuck consumers that aren't keeping up with the latest data available in a topic. When necessary, you can then take remedial actions, such as scaling or rebooting those consumers. To monitor consumer lag, you can use Amazon CloudWatch or open monitoring with Prometheus. Consumer lag metrics quantify the difference between the latest data written to your topics and the data read by your applications. Amazon MSK provides the following consumer-lag metrics, which you can get through Amazon CloudWatch or through open monitoring with Prometheus: EstimatedMaxTimeLag, EstimatedTimeLag, MaxOffsetLag, OffsetLag, and SumOffsetLag.Amazon MSK supports consumer for cluster with Apache Kafka 2.2.1 or latest version.
Meaning of SumOffsetLag in MsK cloudwatch data?
We have kafka which we are monitoring using grafana dashboad provided by aws cloud watch. From the past few days we are seeing some abnormality. I dont have Idea much about SumOffsetLag metric parameter. How this spiked value can degrade the performance and how we can improve it
[ "Consumer-lag monitoring\nMonitoring consumer lag allows you to identify slow or stuck consumers that aren't keeping up with the latest data available in a topic. When necessary, you can then take remedial actions, such as scaling or rebooting those consumers. To monitor consumer lag, you can use Amazon CloudWatch or open monitoring with Prometheus.\nConsumer lag metrics quantify the difference between the latest data written to your topics and the data read by your applications. Amazon MSK provides the following consumer-lag metrics, which you can get through Amazon CloudWatch or through open monitoring with Prometheus: EstimatedMaxTimeLag, EstimatedTimeLag, MaxOffsetLag, OffsetLag, and SumOffsetLag.Amazon MSK supports consumer for cluster with Apache Kafka 2.2.1 or latest version.\n" ]
[ 0 ]
[]
[]
[ "amazon_msk", "apache_kafka", "aws_msk" ]
stackoverflow_0074668647_amazon_msk_apache_kafka_aws_msk.txt
Q: Override PageLinkHandler in wagtail I have a site that has custom JS for handling link clicks, so that only part of the page reloads and audio playback isn't interrupted. This requires each link to have an onclick attribute. All of the hard coded links in the site have this, but links in page content created in the wagtail CMS don't. I know there's a couple different ways to achieve this, but I felt like the most elegant would be with wagtail's rewrite handlers. I followed the steps and added a hook to register my rewrite handler, but it seems that since links with the identifier "page" are already handled by PageLinkHandler, this is ignored. I can't find a hook provided by wagtail to override this handler, so I've ended up monkeypatching in the functionality: from wagtail.models import Page from wagtail.rich_text.pages import PageLinkHandler from django.utils.html import escape @classmethod def custom_expand_db_attributes(cls, attrs): try: page = cls.get_instance(attrs) return '<a onclick="navigate(event, \'{s}\')" href="{s}">'.format(s=escape(page.localized.specific.url)) except Page.DoesNotExist: return "<a>" PageLinkHandler.expand_db_attributes = custom_expand_db_attributes This code is just placed in the views.py of my frontend. It works, but I want to know if there's an officially supported way to do this without monkeypatching A: I think since you want to replace rather than extend some functionality, monkey patching is the correct approach.
Override PageLinkHandler in wagtail
I have a site that has custom JS for handling link clicks, so that only part of the page reloads and audio playback isn't interrupted. This requires each link to have an onclick attribute. All of the hard coded links in the site have this, but links in page content created in the wagtail CMS don't. I know there's a couple different ways to achieve this, but I felt like the most elegant would be with wagtail's rewrite handlers. I followed the steps and added a hook to register my rewrite handler, but it seems that since links with the identifier "page" are already handled by PageLinkHandler, this is ignored. I can't find a hook provided by wagtail to override this handler, so I've ended up monkeypatching in the functionality: from wagtail.models import Page from wagtail.rich_text.pages import PageLinkHandler from django.utils.html import escape @classmethod def custom_expand_db_attributes(cls, attrs): try: page = cls.get_instance(attrs) return '<a onclick="navigate(event, \'{s}\')" href="{s}">'.format(s=escape(page.localized.specific.url)) except Page.DoesNotExist: return "<a>" PageLinkHandler.expand_db_attributes = custom_expand_db_attributes This code is just placed in the views.py of my frontend. It works, but I want to know if there's an officially supported way to do this without monkeypatching
[ "I think since you want to replace rather than extend some functionality, monkey patching is the correct approach.\n" ]
[ 0 ]
[]
[]
[ "python", "wagtail" ]
stackoverflow_0074553383_python_wagtail.txt
Q: Sending multiple messages socket c I am writing this post because I have a problem with my C socket. When I send messages very quickly in a loop from the server to the clients, the client displays all the messages in one string and I don't know why. However, when I send a message followed by a sleep, I do not have this problem. Would it be possible to have an explanation please? Serveur code without sleep: int nombreDeJoueurs = joueurs + robots; int taille; for(i = 1; i<= nombreDeJoueurs; i++){ sprintf(saisie,"Le joueur %d a %d têtes de boeufs", i, vie[i]); for (j = 1; j <= joueurs; j++){ taille = write(pollfds[j].fd,saisie,strlen(saisie)); } } Output client : Le joueur 1 a 1 têtes de boeufsLe joueur 2 a 0 têtes de boeufsLe joueur 3 a 0 têtes de boeufsLe joueur 4 a 0 têtes de boeufs Serveur code with sleep: int nombreDeJoueurs = joueurs + robots; int taille; for(i = 1; i<= nombreDeJoueurs; i++){ sprintf(saisie,"Le joueur %d a %d têtes de boeufs", i, vie[i]); for (j = 1; j <= joueurs; j++){ taille = write(pollfds[j].fd,saisie,strlen(saisie)); sleep(1); } } Output client Le joueur 1 a 1 têtes de boeufs Le joueur 2 a 0 têtes de boeufs Le joueur 3 a 0 têtes de boeufs Le joueur 4 a 0 têtes de boeufs A: Your assumption, that you would send multiple messages is wrong. From man write: write() writes up to count bytes from the buffer starting at buf to the file referred to by the file descriptor fd. To be more specifically: all you're doing is to write a number of bytes into the underlying stream. The number of calls of the function write does not determine the number of 'messages'. If the socket buffer is full, the socket implementation will flush the remaining bytes and send them over the network to the client. If you wait too long, the socket implementation will automatically flush the buffer in certain time intervals. That's why your sleep version works. But it is the wrong approach. You have to implement a protocol between the server and client. An example would be to send the length of the message (either as text or binary), so that the client would first read the length and then read only that much from the stream to form a message (string).
Sending multiple messages socket c
I am writing this post because I have a problem with my C socket. When I send messages very quickly in a loop from the server to the clients, the client displays all the messages in one string and I don't know why. However, when I send a message followed by a sleep, I do not have this problem. Would it be possible to have an explanation please? Serveur code without sleep: int nombreDeJoueurs = joueurs + robots; int taille; for(i = 1; i<= nombreDeJoueurs; i++){ sprintf(saisie,"Le joueur %d a %d têtes de boeufs", i, vie[i]); for (j = 1; j <= joueurs; j++){ taille = write(pollfds[j].fd,saisie,strlen(saisie)); } } Output client : Le joueur 1 a 1 têtes de boeufsLe joueur 2 a 0 têtes de boeufsLe joueur 3 a 0 têtes de boeufsLe joueur 4 a 0 têtes de boeufs Serveur code with sleep: int nombreDeJoueurs = joueurs + robots; int taille; for(i = 1; i<= nombreDeJoueurs; i++){ sprintf(saisie,"Le joueur %d a %d têtes de boeufs", i, vie[i]); for (j = 1; j <= joueurs; j++){ taille = write(pollfds[j].fd,saisie,strlen(saisie)); sleep(1); } } Output client Le joueur 1 a 1 têtes de boeufs Le joueur 2 a 0 têtes de boeufs Le joueur 3 a 0 têtes de boeufs Le joueur 4 a 0 têtes de boeufs
[ "Your assumption, that you would send multiple messages is wrong.\nFrom man write:\n\nwrite() writes up to count bytes from the buffer starting at buf to the file referred to by the file descriptor fd.\n\nTo be more specifically: all you're doing is to write a number of bytes into the underlying stream. The number of calls of the function write does not determine the number of 'messages'.\nIf the socket buffer is full, the socket implementation will flush the remaining bytes and send them over the network to the client. If you wait too long, the socket implementation will automatically flush the buffer in certain time intervals.\nThat's why your sleep version works. But it is the wrong approach. You have to implement a protocol between the server and client. An example would be to send the length of the message (either as text or binary), so that the client would first read the length and then read only that much from the stream to form a message (string).\n" ]
[ 0 ]
[]
[]
[ "c", "client_server", "message", "sockets" ]
stackoverflow_0074668081_c_client_server_message_sockets.txt
Q: Unable to assign value to an array I'm trying to clear values in the sheets that are present in a workbook. I have a list of all possible (valid) sheets, but I won't know which sheet is currently present in the workbook. So, I need to get the worksheets' name, see if it's valid and then clear its contents. Here's what I have so far: Sub testclear() Dim validsheets() As Variant, sheetstoclear() As Variant Dim i as Integer, j As Integer, k As Integer, m as Integer validsheets() = Array ("Sheet1", "Sheet2", "Sheet3", "Sheet4", "Sheet5") For i = 1 To Worksheets.count For j = LBound(validsheets) to UBound(validsheets) If Worksheets(i).Name = validsheets(J) Then sheetstoclear(k) = Worksheets(i).Name k = k +1 End If Next j Next i For m = LBound(sheetstoclear) to UBound(sheetstoclear) Sheets(sheetstoclear(m+1)).Cells.clear Next m End Sub If I execute the above code, I get the following error - Run-time error'9': Subscript out of range A: Iterate the sheets collection and clear the sheet directly without creating a sheetstoclear array first. Option Explicit Sub testclear() Dim ws As Worksheet, validsheets, var validsheets = Array("Sheet1", "Sheet2", "Sheet3", "Sheet4") For Each ws In ThisWorkbook.Sheets For Each var In validsheets If var = ws.Name Then ws.Cells.Clear Exit For End If Next Next End Sub A: Please, try the next simple way: Dim ws As Worksheet For Each ws In Worksheets(Array("Sheet1", "Sheet2", "Sheet3", "Sheet4", "Sheet5")) ws.UsedRange.Clear Next
Unable to assign value to an array
I'm trying to clear values in the sheets that are present in a workbook. I have a list of all possible (valid) sheets, but I won't know which sheet is currently present in the workbook. So, I need to get the worksheets' name, see if it's valid and then clear its contents. Here's what I have so far: Sub testclear() Dim validsheets() As Variant, sheetstoclear() As Variant Dim i as Integer, j As Integer, k As Integer, m as Integer validsheets() = Array ("Sheet1", "Sheet2", "Sheet3", "Sheet4", "Sheet5") For i = 1 To Worksheets.count For j = LBound(validsheets) to UBound(validsheets) If Worksheets(i).Name = validsheets(J) Then sheetstoclear(k) = Worksheets(i).Name k = k +1 End If Next j Next i For m = LBound(sheetstoclear) to UBound(sheetstoclear) Sheets(sheetstoclear(m+1)).Cells.clear Next m End Sub If I execute the above code, I get the following error - Run-time error'9': Subscript out of range
[ "Iterate the sheets collection and clear the sheet directly without creating a sheetstoclear array first.\nOption Explicit\n\nSub testclear()\n\n Dim ws As Worksheet, validsheets, var\n validsheets = Array(\"Sheet1\", \"Sheet2\", \"Sheet3\", \"Sheet4\")\n \n For Each ws In ThisWorkbook.Sheets\n For Each var In validsheets\n If var = ws.Name Then\n ws.Cells.Clear\n Exit For\n End If\n Next\n Next\n\nEnd Sub\n\n", "Please, try the next simple way:\n Dim ws As Worksheet\n For Each ws In Worksheets(Array(\"Sheet1\", \"Sheet2\", \"Sheet3\", \"Sheet4\", \"Sheet5\"))\n ws.UsedRange.Clear\n Next\n\n" ]
[ 1, 1 ]
[]
[]
[ "excel", "vba" ]
stackoverflow_0074668183_excel_vba.txt
Q: How can I fix this python simple recursion problem I have a function that prints the first multiples of a number (n) starting with zero and stopping at num_multiples, but it keeps printing out one too many multiples. I'm hoping someone can explain what I'm doing wrong so I can understand recursion a bit more. def print_first_multiples(n, num_multiples): if num_multiples < 0: return else: print_first_multiples(n, num_multiples - 1) print(n * num_multiples, end=' ') for example, passing 5 as n and 10 as num_multiples, it should print: 0 5 10 15 20 25 30 35 40 45 but is instead printing an extra "50" at the end. A: First, 0 is not a multiple of 5. The first multiple of 5 is 5 (5*1). The problem with your code is that you only stop when num_multiples is negative (less than 0). Instead, you want to stop when it is zero. Like this: def print_first_multiples(n, num_multiples): if num_multiples == 0: return else: print_first_multiples(n, num_multiples - 1) print(n * num_multiples, end=' ') print_first_multiples(5, 10) If you do want to start at 0 and go up to 45, then you can subtract one from num_multiples. Like this: def print_first_multiples(n, num_multiples): if num_multiples == 0: return else: print_first_multiples(n, num_multiples - 1) print(n * (num_multiples-1), end=' ') print_first_multiples(5, 10) A: Try if num_multiples <= 0: instead A: It prints until it doesn't enter if num_multiples < 0. So e.x. with the initial value num_multiples = 3 you print for num_multiples=3, num_multiples=2, num_multiples=1, and num_multiples=0 so 4 times. Replace if num_multiples < 0 with if num_multiples == 0 and you'd get what you expect
How can I fix this python simple recursion problem
I have a function that prints the first multiples of a number (n) starting with zero and stopping at num_multiples, but it keeps printing out one too many multiples. I'm hoping someone can explain what I'm doing wrong so I can understand recursion a bit more. def print_first_multiples(n, num_multiples): if num_multiples < 0: return else: print_first_multiples(n, num_multiples - 1) print(n * num_multiples, end=' ') for example, passing 5 as n and 10 as num_multiples, it should print: 0 5 10 15 20 25 30 35 40 45 but is instead printing an extra "50" at the end.
[ "First, 0 is not a multiple of 5. The first multiple of 5 is 5 (5*1). The problem with your code is that you only stop when num_multiples is negative (less than 0). Instead, you want to stop when it is zero. Like this:\ndef print_first_multiples(n, num_multiples): \n if num_multiples == 0:\n return\n else:\n print_first_multiples(n, num_multiples - 1)\n print(n * num_multiples, end=' ')\n\n\nprint_first_multiples(5, 10)\n\nIf you do want to start at 0 and go up to 45, then you can subtract one from num_multiples. Like this:\ndef print_first_multiples(n, num_multiples): \n if num_multiples == 0:\n return\n else:\n print_first_multiples(n, num_multiples - 1)\n print(n * (num_multiples-1), end=' ')\n\n\nprint_first_multiples(5, 10)\n\n", "Try if num_multiples <= 0: instead\n", "It prints until it doesn't enter if num_multiples < 0. So e.x. with the initial value num_multiples = 3 you print for num_multiples=3, num_multiples=2, num_multiples=1, and num_multiples=0 so 4 times. Replace if num_multiples < 0 with if num_multiples == 0 and you'd get what you expect\n" ]
[ 1, 0, 0 ]
[]
[]
[ "function", "python", "recursion" ]
stackoverflow_0074668764_function_python_recursion.txt
Q: How to enter file path? How can I do to type something in the field of the image below? I've tried without success: from threading import local import pandas as pd import pyautogui from time import sleep from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.common.keys import Keys from selenium.webdriver.support.ui import Select from selenium.webdriver.chrome.service import Service from webdriver_manager.chrome import ChromeDriverManager from selenium.webdriver.common.action_chains import ActionChains from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC wait.until(EC.presence_of_element_located((By.XPATH,"//input[@type='file']"))send_keys("C:/Users/my_user/Downloads/doch.jpeg") for index, row in df.iterrows(): actions.send_keys((row["message"])) actions.perform() The only palliative solution was: pyautogui.write((row["photo"])) pyautogui.press("enter") I don't want to use pyautogui as it uses the keyboard command and I can't do anything on the computer while the code is running. A: Selenium can't upload files using the Windows select file option, so you'll have to do something else - you might be able to use the send_keys function, i.e.: elem = driver.find_element(By.XPATH, "//input[@type='file']") elem.send_keys('C:\\Path\\To\\File') Note that this may not work, depending on the type of input, and you may be able to instead simulate a drag-and-drop operation if the website supports this. See How to upload file ( picture ) with selenium, python for more info A: For windows path you need double backslashes. Try this: wait.until(EC.presence_of_element_located((By.XPATH,"//input[@type='file']"))send_keys("C:\\Users\\my_user\\Downloads\\doch.jpeg")
How to enter file path?
How can I do to type something in the field of the image below? I've tried without success: from threading import local import pandas as pd import pyautogui from time import sleep from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.common.keys import Keys from selenium.webdriver.support.ui import Select from selenium.webdriver.chrome.service import Service from webdriver_manager.chrome import ChromeDriverManager from selenium.webdriver.common.action_chains import ActionChains from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC wait.until(EC.presence_of_element_located((By.XPATH,"//input[@type='file']"))send_keys("C:/Users/my_user/Downloads/doch.jpeg") for index, row in df.iterrows(): actions.send_keys((row["message"])) actions.perform() The only palliative solution was: pyautogui.write((row["photo"])) pyautogui.press("enter") I don't want to use pyautogui as it uses the keyboard command and I can't do anything on the computer while the code is running.
[ "Selenium can't upload files using the Windows select file option, so you'll have to do something else - you might be able to use the send_keys function, i.e.:\nelem = driver.find_element(By.XPATH, \"//input[@type='file']\")\nelem.send_keys('C:\\\\Path\\\\To\\\\File')\n\nNote that this may not work, depending on the type of input, and you may be able to instead simulate a drag-and-drop operation if the website supports this.\nSee How to upload file ( picture ) with selenium, python for more info\n", "For windows path you need double backslashes. Try this:\nwait.until(EC.presence_of_element_located((By.XPATH,\"//input[@type='file']\"))send_keys(\"C:\\\\Users\\\\my_user\\\\Downloads\\\\doch.jpeg\")\n\n" ]
[ 0, 0 ]
[]
[]
[ "python", "selenium" ]
stackoverflow_0074663050_python_selenium.txt
Q: \t didn't appear in the for loop I'm practicing format fuction and when I use this code with \t in it, the first 9 output did not have any big space ` import random lst = [random.randint(1,100) for i in range(51)] for index, val in enumerate(lst): print(f'{index=}\t{val=}') ` It works with \n but not \t, I don't know why. Can anyone explain it? A: It's just the terminal following tab(4 spaces in your case) convention. So add spaces before and after \t. A: All results has \t Run your code with python yourcode.py | cat -T This is the results. ^I is the tab. $ python yourcode.py | cat -T index=0^Ival=14 index=1^Ival=46 index=2^Ival=87 index=3^Ival=83 index=4^Ival=28 index=5^Ival=77 index=6^Ival=34 index=7^Ival=66 index=8^Ival=64 index=9^Ival=80 index=10^Ival=28 index=11^Ival=21 index=12^Ival=64 index=13^Ival=79 index=14^Ival=92 index=15^Ival=67 index=16^Ival=69 index=17^Ival=50 Man page of cat says -T, --show-tabs display TAB characters as ^I You may change the length of TAB. Check this article A: The behavior you're seeing is because the \t escape sequence inserts a tab character, which is typically used for indenting text. By default, most text editors and terminals use a tab stop of 8 characters, which means that a tab character will move the cursor to the next multiple of 8 characters. In your code, the first nine values in the list don't have any big spaces because they are not aligned with a multiple of 8 characters. This is because the {index=} and {val=} expressions in the format string each add 3 characters to the output, and the = character adds an additional 1 character, for a total of 7 characters. This means that the first nine values are not aligned with a multiple of 8 characters, and the tab character does not insert any extra spaces. If you want to insert a fixed number of spaces in your output, rather than using a tab character, you can use the {:<N} format specifier, where N is the total number of characters you want the output to occupy. For example, you could use the following code to insert 10 spaces between the index and val values in your output: import random lst = [random.randint(1,100) for i in range(51)] for index, val in enumerate(last): print(f'{index:<10}{val=}') In this code, the {index:<10} format specifier tells the format function to left-align the index value within a field of 10 characters. This ensures that there are always 10 spaces between the index and val values, regardless of their actual values. Overall, the \t escape sequence is useful for indenting text, but it may not always produce the results you expect if the text is not aligned
\t didn't appear in the for loop
I'm practicing format fuction and when I use this code with \t in it, the first 9 output did not have any big space ` import random lst = [random.randint(1,100) for i in range(51)] for index, val in enumerate(lst): print(f'{index=}\t{val=}') ` It works with \n but not \t, I don't know why. Can anyone explain it?
[ "It's just the terminal following tab(4 spaces in your case) convention. So add spaces before and after \\t.\n", "All results has \\t\nRun your code with python yourcode.py | cat -T\nThis is the results. ^I is the tab.\n$ python yourcode.py | cat -T\nindex=0^Ival=14\nindex=1^Ival=46\nindex=2^Ival=87\nindex=3^Ival=83\nindex=4^Ival=28\nindex=5^Ival=77\nindex=6^Ival=34\nindex=7^Ival=66\nindex=8^Ival=64\nindex=9^Ival=80\nindex=10^Ival=28\nindex=11^Ival=21\nindex=12^Ival=64\nindex=13^Ival=79\nindex=14^Ival=92\nindex=15^Ival=67\nindex=16^Ival=69\nindex=17^Ival=50\n\nMan page of cat says\n\n -T, --show-tabs\n display TAB characters as ^I\n\n\nYou may change the length of TAB. Check this article\n", "The behavior you're seeing is because the \\t escape sequence inserts a tab character, which is typically used for indenting text. By default, most text editors and terminals use a tab stop of 8 characters, which means that a tab character will move the cursor to the next multiple of 8 characters.\nIn your code, the first nine values in the list don't have any big spaces because they are not aligned with a multiple of 8 characters. This is because the {index=} and {val=} expressions in the format string each add 3 characters to the output, and the = character adds an additional 1 character, for a total of 7 characters. This means that the first nine values are not aligned with a multiple of 8 characters, and the tab character does not insert any extra spaces.\nIf you want to insert a fixed number of spaces in your output, rather than using a tab character, you can use the {:<N} format specifier, where N is the total number of characters you want the output to occupy. For example, you could use the following code to insert 10 spaces between the index and val values in your output:\nimport random\n\nlst = [random.randint(1,100) for i in range(51)]\nfor index, val in enumerate(last):\n print(f'{index:<10}{val=}')\n\nIn this code, the {index:<10} format specifier tells the format function to left-align the index value within a field of 10 characters. This ensures that there are always 10 spaces between the index and val values, regardless of their actual values.\nOverall, the \\t escape sequence is useful for indenting text, but it may not always produce the results you expect if the text is not aligned\n" ]
[ 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074667173_python.txt
Q: Rails 7 sharing stimulus controller functions I'm trying to share stimulus controller functions with other controllers but the files are not being found because of the asset pipeline digest. Parent (app/javascript/controllers/a_shared_controller.js) import {Controller} from "@hotwired/stimulus" export default class extends Controller { // some shared functions } Child import Controller from "./a_shared_controller" This works fine in development. What's the best way to do this? Thanks! A: Don't use relative imports. When you pin all controllers like this: pin_all_from "app/javascript/controllers", under: "controllers" You get these import-maps generated: <script type="importmap" data-turbo-track="reload">{ "imports": { "controllers/application": "/assets/controllers/application-368d98631bccbf2349e0d4f8269afb3fe9625118341966de054759d96ea86c7e.js", "controllers/hello_controller": "/assets/controllers/hello_controller-549135e8e7c683a538c3d6d517339ba470fcfb79d62f738a0a089ba41851a554.js", "controllers": "/assets/controllers/index-ed00704a3bfd9aebb7c818233ee5411c3ce8050f411b77ec27c4252ded99a59c.js", } <!-- ^ this is what you can import --> }</script> application.js would be an example of a shared file, it is imported in index.js: import { application } from "controllers/application" // ^ // NOTE: the name of the generated importmap is used to import If you add another file, don't add _controller.js as it would load automatically in index.js (unless that's what you want). I have another answer explaining why relative paths don't work and how to maybe make them work: https://stackoverflow.com/a/73136675/207090
Rails 7 sharing stimulus controller functions
I'm trying to share stimulus controller functions with other controllers but the files are not being found because of the asset pipeline digest. Parent (app/javascript/controllers/a_shared_controller.js) import {Controller} from "@hotwired/stimulus" export default class extends Controller { // some shared functions } Child import Controller from "./a_shared_controller" This works fine in development. What's the best way to do this? Thanks!
[ "Don't use relative imports. When you pin all controllers like this:\npin_all_from \"app/javascript/controllers\", under: \"controllers\"\n\nYou get these import-maps generated:\n<script type=\"importmap\" data-turbo-track=\"reload\">{\n \"imports\": {\n \"controllers/application\": \"/assets/controllers/application-368d98631bccbf2349e0d4f8269afb3fe9625118341966de054759d96ea86c7e.js\",\n \"controllers/hello_controller\": \"/assets/controllers/hello_controller-549135e8e7c683a538c3d6d517339ba470fcfb79d62f738a0a089ba41851a554.js\",\n \"controllers\": \"/assets/controllers/index-ed00704a3bfd9aebb7c818233ee5411c3ce8050f411b77ec27c4252ded99a59c.js\",\n }\n<!-- ^ this is what you can import -->\n}</script>\n\napplication.js would be an example of a shared file, it is imported in index.js:\nimport { application } from \"controllers/application\"\n// ^\n// NOTE: the name of the generated importmap is used to import\n\nIf you add another file, don't add _controller.js as it would load automatically in index.js (unless that's what you want).\n\nI have another answer explaining why relative paths don't work and how to maybe make them work:\nhttps://stackoverflow.com/a/73136675/207090\n" ]
[ 0 ]
[]
[]
[ "asset_pipeline", "import_maps", "ruby_on_rails", "stimulusjs" ]
stackoverflow_0074662131_asset_pipeline_import_maps_ruby_on_rails_stimulusjs.txt
Q: Caesar Cipher-Why is it when I enter a key value of for eg 5, the character encryption shifts by 11? Why is it when I enter a key value of 5 for eg, the character shifts by 11 not 5? string ciphertext = ""; Console.WriteLine("Enter ur text "); string plaintext = Console.ReadLine(); Console.WriteLine("Enter ur key "); int key = Convert.ToInt32(Console.ReadLine()); foreach(char number in plaintext) { int value = Convert.ToInt32(number); if(value + key > 90) { Console.WriteLine(char.ConvertFromUtf32(value + key - 26)); } else { Console.WriteLine(char.ConvertFromUtf32(value + key)); } } I am expecting a shift of characters according to the key value A: Convert.ToInt32(number) will try to interpret the the character as decimal digit. E.g., Convert.ToInt32('4') => 4. This is not what you want. To get its character code you can simply cast to int. E.g. (int)'A' => 65. You can treat characters as numbers and add the key directly and cast the int result back to char. Console.Write("Enter ur text: "); string plaintext = Console.ReadLine(); Console.Write("Enter ur key: "); int key = Convert.ToInt32(Console.ReadLine()); foreach (char character in plaintext) { int shiftedCharCode = character + key; if (shiftedCharCode > 'z' || (shiftedCharCode > 'Z' && shiftedCharCode < 'a')) { shiftedCharCode -= 26; } Console.WriteLine((char)shiftedCharCode); }
Caesar Cipher-Why is it when I enter a key value of for eg 5, the character encryption shifts by 11?
Why is it when I enter a key value of 5 for eg, the character shifts by 11 not 5? string ciphertext = ""; Console.WriteLine("Enter ur text "); string plaintext = Console.ReadLine(); Console.WriteLine("Enter ur key "); int key = Convert.ToInt32(Console.ReadLine()); foreach(char number in plaintext) { int value = Convert.ToInt32(number); if(value + key > 90) { Console.WriteLine(char.ConvertFromUtf32(value + key - 26)); } else { Console.WriteLine(char.ConvertFromUtf32(value + key)); } } I am expecting a shift of characters according to the key value
[ "Convert.ToInt32(number) will try to interpret the the character as decimal digit. E.g., Convert.ToInt32('4') => 4. This is not what you want. To get its character code you can simply cast to int. E.g. (int)'A' => 65.\nYou can treat characters as numbers and add the key directly and cast the int result back to char.\nConsole.Write(\"Enter ur text: \");\nstring plaintext = Console.ReadLine();\nConsole.Write(\"Enter ur key: \");\nint key = Convert.ToInt32(Console.ReadLine());\n\nforeach (char character in plaintext) {\n int shiftedCharCode = character + key;\n if (shiftedCharCode > 'z' || (shiftedCharCode > 'Z' && shiftedCharCode < 'a')) {\n shiftedCharCode -= 26;\n }\n Console.WriteLine((char)shiftedCharCode);\n}\n\n" ]
[ 0 ]
[]
[]
[ "c#", "caesar_cipher" ]
stackoverflow_0074668466_c#_caesar_cipher.txt
Q: Macbook M1 assembly lldb displays only 3 source lines then switches to object code display First attempt at ARM64 (apple M1) assembly coding. Have basic 'hello world' code which assembles and runs correctly but when I run it in lldb, only the first three lines are displayed in full source code format like this: Abenaki:hello jiml$ ~/llvm/clang+llvm-15.0.2-arm64-apple-darwin21.0/bin/lldb hello (lldb) target create "hello" Current executable set to '/Users/jiml/Projects/GitRepos/ARM/hello/hello/hello/hello' (arm64). (lldb) b main Breakpoint 1: where = hello`main + 4, address = 0x0000000100003f7c (lldb) r Process 5017 launched: '/Users/jiml/Projects/GitRepos/ARM/hello/hello/hello/hello' (arm64) Process 5017 stopped * thread #1, queue = 'com.apple.main-thread', stop reason = breakpoint 1.1 frame #0: 0x0000000100003f7c hello`main at hello.s:19 16 17 _main: 18 mov x0, #0x0 // stdout -> 19 adrp x1, msg@PAGE // pointer to string 20 add x1, x1, msg@PAGEOFF 21 ldr x2, =msg_len // bytes to output 22 mov x16, #0x04 // sys_write warning: This version of LLDB has no plugin for the language "assembler". Inspection of frame variables will be limited. (lldb) After three steps, the display reverts to bare object code like this: (lldb) s Process 5017 stopped * thread #1, queue = 'com.apple.main-thread', stop reason = step in frame #0: 0x0000000100003f88 hello`main + 16 hello`main: -> 0x100003f88 <+16>: mov x16, #0x4 0x100003f8c <+20>: svc #0x80 0x100003f90 <+24>: adrp x1, 1 0x100003f94 <+28>: mov x2, #0x0 dwarfdump -a shows that all source lines are present in the .o; same behavior for .dSYM assembly. Using the 'list' command in lldb however displays all source lines correctly. Is this a known issue for LLVM (clang, lldb) development? Any help appreciated... I have tried LLVM version 14 and 15, same behavior, searched for similar issues but no help. I did find this https://stackoverflow.com/questions/73778648/why-is-it-that-assembling-linking-in-one-step-loses-debug-info-for-my-assembly-s but it did not solve my issue. A: So I think I have this resolved but not sure if it is actual compiler bug. I wrote hello world in C, compiled and confirmed complete source display in lldb. I then reran clang with -S to generate the assembler source. I then assembled that source... clang -g -c -o hello.o hello.s clang -o hello hello.o -lSystem -arch arm64 and confirmed it also runs in lldb with complete source display. Then I moved my hand written code line-by-line in order to figure out where the problem occurs. Seems my string data and length calculation is problematic. In the data section I originally had: msg: ascii "Hello ARM64\n" msg_len = . - msg Coming from Intel world this seems perfectly natural ;-) Adding that length calculation caused some sort of corruption of the debug data. However, the executable has a proper OSO statement pointing at hello.o (nm -ap hello) and further the object file has references for all source statements in the source file (dwarfdump --debug-line hello.o) but still doesn't display source code after the third step. Curious that 'source info -f hello.s' within lldb only listed four lines. I found three work-arounds. First adding a label between the two statements seems to allow correct behavior: msg: ascii "Hello ARM64\n" nothing: msg_len = . - msg Second, using equate: msg: ascii "Hello ARM64\n" .equ msg_len, . - msg Third, using two labels: msg: ascii "Hello ARM64\n" msg_end: msg_len = msg_end - msg Will file report with llvm and see what they say.
Macbook M1 assembly lldb displays only 3 source lines then switches to object code display
First attempt at ARM64 (apple M1) assembly coding. Have basic 'hello world' code which assembles and runs correctly but when I run it in lldb, only the first three lines are displayed in full source code format like this: Abenaki:hello jiml$ ~/llvm/clang+llvm-15.0.2-arm64-apple-darwin21.0/bin/lldb hello (lldb) target create "hello" Current executable set to '/Users/jiml/Projects/GitRepos/ARM/hello/hello/hello/hello' (arm64). (lldb) b main Breakpoint 1: where = hello`main + 4, address = 0x0000000100003f7c (lldb) r Process 5017 launched: '/Users/jiml/Projects/GitRepos/ARM/hello/hello/hello/hello' (arm64) Process 5017 stopped * thread #1, queue = 'com.apple.main-thread', stop reason = breakpoint 1.1 frame #0: 0x0000000100003f7c hello`main at hello.s:19 16 17 _main: 18 mov x0, #0x0 // stdout -> 19 adrp x1, msg@PAGE // pointer to string 20 add x1, x1, msg@PAGEOFF 21 ldr x2, =msg_len // bytes to output 22 mov x16, #0x04 // sys_write warning: This version of LLDB has no plugin for the language "assembler". Inspection of frame variables will be limited. (lldb) After three steps, the display reverts to bare object code like this: (lldb) s Process 5017 stopped * thread #1, queue = 'com.apple.main-thread', stop reason = step in frame #0: 0x0000000100003f88 hello`main + 16 hello`main: -> 0x100003f88 <+16>: mov x16, #0x4 0x100003f8c <+20>: svc #0x80 0x100003f90 <+24>: adrp x1, 1 0x100003f94 <+28>: mov x2, #0x0 dwarfdump -a shows that all source lines are present in the .o; same behavior for .dSYM assembly. Using the 'list' command in lldb however displays all source lines correctly. Is this a known issue for LLVM (clang, lldb) development? Any help appreciated... I have tried LLVM version 14 and 15, same behavior, searched for similar issues but no help. I did find this https://stackoverflow.com/questions/73778648/why-is-it-that-assembling-linking-in-one-step-loses-debug-info-for-my-assembly-s but it did not solve my issue.
[ "So I think I have this resolved but not sure if it is actual compiler bug.\nI wrote hello world in C, compiled and confirmed complete source display in lldb. I then reran clang with -S to generate the assembler source.\nI then assembled that source...\nclang -g -c -o hello.o hello.s\nclang -o hello hello.o -lSystem -arch arm64\n\nand confirmed it also runs in lldb with complete source display. Then I moved my hand written code line-by-line in order to figure out where the problem occurs. Seems my string data and length calculation is problematic. In the data section I originally had:\nmsg: ascii \"Hello ARM64\\n\"\nmsg_len = . - msg\n\nComing from Intel world this seems perfectly natural ;-) Adding that length calculation caused some sort of corruption of the debug data. However, the executable has a proper OSO statement pointing at hello.o (nm -ap hello) and further the object file has references for all source statements in the source file (dwarfdump --debug-line hello.o) but still doesn't display source code after the third step. Curious that 'source info -f hello.s' within lldb only listed four lines.\nI found three work-arounds. First adding a label between the two statements seems to allow correct behavior:\nmsg: ascii \"Hello ARM64\\n\"\nnothing:\nmsg_len = . - msg\n\nSecond, using equate:\nmsg: ascii \"Hello ARM64\\n\"\n.equ msg_len, . - msg\n\nThird, using two labels:\nmsg: ascii \"Hello ARM64\\n\"\nmsg_end:\nmsg_len = msg_end - msg\n\nWill file report with llvm and see what they say.\n" ]
[ 0 ]
[]
[]
[ "arm64", "lldb" ]
stackoverflow_0074660261_arm64_lldb.txt
Q: How to convert isometric to cartesian movement? I'm coding a 2d game and I decided to use isometric system for it. However I don't like that player movement is also rotated. The blue arrow I what I want and the red arrow is what I get I tried converting movement back to cartesian but when I did that the player wasn't moving in parallel to the edges A: If you are drawing a grid, you know how to translate the grid directions (u,v) into pixel directions (x,y) So have your player move by one unit in both (u,v) directions to move diagonally up. up: (u,v) = (u+1,v+1) down: (u,v) = (u-1,v-1) right: (u,v) = (u+1,v-1) left: (u,v) = (u-1,v+1) and then translate the new coordinates into pixels
How to convert isometric to cartesian movement?
I'm coding a 2d game and I decided to use isometric system for it. However I don't like that player movement is also rotated. The blue arrow I what I want and the red arrow is what I get I tried converting movement back to cartesian but when I did that the player wasn't moving in parallel to the edges
[ "If you are drawing a grid, you know how to translate the grid directions (u,v) into pixel directions (x,y)\n\nSo have your player move by one unit in both (u,v) directions to move diagonally up.\nup: (u,v) = (u+1,v+1)\ndown: (u,v) = (u-1,v-1)\nright: (u,v) = (u+1,v-1)\nleft: (u,v) = (u-1,v+1)\n\nand then translate the new coordinates into pixels\n" ]
[ 0 ]
[]
[]
[ "isometric", "math" ]
stackoverflow_0074667059_isometric_math.txt
Q: Problem in Oracle 19c installation on Windows 10 I am trying to Run setup.exe as part of Oracle 19c installation on windows 10. I have downloaded the zip file and extracted it in a folder inside C drive. When I try to run setup.exe by right click and run as administrator option, a command prompt just flashes for a split of a second and nothings starts after that. A: I have found the solution: After extraction, rename the extracted directory to db_home Move the db_home directory to the root of your Hard Drive ( in my case its C:\db_home ) run setup.exe as an administrator. You will see a cmd window pop up and then the red window with the Oracle symbol in it. Do NOT skip step 2nd step as that is how I was finally able to get it to install. This also worked with 19c. A: I also faced the problem. After seeing this thread, in a while, I figured it out. Apparently, keeping the db_home folder inside a folder that has space in its name caused me the same issue. A: I had the same problem and read something about problems with extremely long paths in packages and using the native Windows unzip utility. I unzipped the package using 7-zip instead and it solved the problem. A: I was trying to install from d partition and does not work. Then I just move all the installation folder to c partition and it works fine. A: I'm an Oracle DBA and I don't know when the change happened or what the source of issue is, but when installing the Oracle client you can no longer have a space " " in the path for the Oracle setup.exe file. It doesn't matter what utility extracted the files or what drive or path is used (except there is and always has been an issue with very long path names) - it just cannot have a space in the path. I hope this helps. A: This issue has a simple solution: When we run the Setup file we see a flash CMD in the background... Your System Environment variable path(DB home) has Space in it. It should be no space(db_home) This personally works for me to install.
Problem in Oracle 19c installation on Windows 10
I am trying to Run setup.exe as part of Oracle 19c installation on windows 10. I have downloaded the zip file and extracted it in a folder inside C drive. When I try to run setup.exe by right click and run as administrator option, a command prompt just flashes for a split of a second and nothings starts after that.
[ "I have found the solution:\n\nAfter extraction, rename the extracted directory to db_home\nMove the db_home directory to the root of your Hard Drive ( in my case its C:\\db_home )\nrun setup.exe as an administrator.\n\nYou will see a cmd window pop up and then the red window with the Oracle symbol in it.\nDo NOT skip step 2nd step as that is how I was finally able to get it to install.\nThis also worked with 19c.\n", "I also faced the problem. After seeing this thread, in a while, I figured it out. Apparently, keeping the db_home folder inside a folder that has space in its name caused me the same issue.\n", "I had the same problem and read something about problems with extremely long paths in packages and using the native Windows unzip utility. I unzipped the package using 7-zip instead and it solved the problem.\n", "I was trying to install from d partition and does not work. Then I just move all the installation folder to c partition and it works fine.\n", "I'm an Oracle DBA and I don't know when the change happened or what the source of issue is, but when installing the Oracle client you can no longer have a space \" \" in the path for the Oracle setup.exe file.\nIt doesn't matter what utility extracted the files or what drive or path is used (except there is and always has been an issue with very long path names) - it just cannot have a space in the path.\nI hope this helps.\n", "This issue has a simple solution:\n\nWhen we run the Setup file we see a flash CMD in the background...\nYour System Environment variable path(DB home) has Space in it.\nIt should be no space(db_home)\n\nThis personally works for me to install.\n" ]
[ 6, 1, 0, 0, 0, 0 ]
[]
[]
[ "installation", "oracle", "windows_10" ]
stackoverflow_0063872316_installation_oracle_windows_10.txt
Q: How can I get query parameters from a URL in Vue.js? How can I fetch query parameters in Vue.js? E.g. http://somesite.com?test=yay Can’t find a way to fetch or do I need to use pure JS or some library for this? A: According to the docs of route object, you have access to a $route object from your components, which exposes what you need. In this case //from your component console.log(this.$route.query.test) // outputs 'yay' A: Without vue-router, split the URL var vm = new Vue({ .... created() { let uri = window.location.href.split('?'); if(uri.length == 2) { let vars = uri[1].split('&'); let getVars = {}; let tmp = ''; vars.forEach(function(v) { tmp = v.split('='); if(tmp.length == 2) getVars[tmp[0]] = tmp[1]; }); console.log(getVars); // do } }, updated() { }, .... Another solution https://developer.mozilla.org/en-US/docs/Web/API/HTMLHyperlinkElementUtils/search: var vm = new Vue({ .... created() { let uri = window.location.search.substring(1); let params = new URLSearchParams(uri); console.log(params.get("var_name")); }, updated() { }, .... A: Try this code var vm = new Vue({ created() { let urlParams = new URLSearchParams(window.location.search); console.log(urlParams.has('yourParam')); // true console.log(urlParams.get('yourParam')); // "MyParam" }, }); A: More detailed answer to help the newbies of VueJS: First define your router object, select the mode you seem fit. You can declare your routes inside the routes list. Next you would want your main app to know router exists, so declare it inside the main app declaration. Lastly the $route instance holds all the information about the current route. The code will console log just the parameter passed in the url. (*Mounted is similar to document.ready, i.e. it's called as soon as the app is ready) And the code itself: <script src="https://unpkg.com/vue-router"></script> var router = new VueRouter({ mode: 'history', routes: [] }); var vm = new Vue({ router, el: '#app', mounted: function() { q = this.$route.query.q console.log(q) }, }); A: Another way (assuming you are using vue-router), is to map the query param to a prop in your router. Then you can treat it like any other prop in your component code. For example, add this route; { path: '/mypage', name: 'mypage', component: MyPage, props: (route) => ({ foo: route.query.foo }), } Then in your component you can add the prop as normal; props: { foo: { type: String, default: null, } }, Then it will be available as this.foo and you can do anything you want with it (like set a watcher, etc.) A: Vue 3 Composition API (as far as now 2021, vue-router 4) import {useRoute} from "vue-router"; //can use only in setup() useRoute().query.test or //somewhere in your src files import router from "~/router"; //can use everywhere router.currentRoute.value.query.test or import {useRouter} from "vue-router"; //can use only in setup() useRouter().currentRoute.value.query.test A: As of this date, the correct way according to the dynamic routing docs is: this.$route.params.yourProperty instead of this.$route.query.yourProperty A: You can use vue-router.I have an example below: url: www.example.com?name=john&lastName=doe new Vue({ el: "#app", data: { name: '', lastName: '', }, beforeRouteEnter(to, from, next) { if(Object.keys(to.query).length !== 0) { //if the url has query (?query) next(vm => { vm.name = to.query.name; vm.lastName = to.query.lastName; }); } next(); } }) Note: In beforeRouteEnter function we cannot access the component's properties like: this.propertyName.That's why i have pass the vm to next function.It is the recommented way to access the vue instance.Actually the vm it stands for vue instance A: If your url looks something like this: somesite.com/something/123 Where '123' is a parameter named 'id' (url like /something/:id), try with: this.$route.params.id A: Here is how to do it if you are using vue-router with vue3 composition api import { useRoute } from 'vue-router' export default { setup() { const route = useRoute() console.log(route.query) } } A: Example url: http://localhost:9528/#/course/outline/1439990638887137282 Below codes output: 1439990638887137282 this.courseId = this.$route.params.id console.log('courseId', this.courseId) A: one thing to keep in mind if you are using Hash mode then don't use this.$route.params.name only use url search param A: On top of the answers here, I recommend that you use the Vue devtools for further debugging. Given this snippet of code <template> <div> {{ showOrNotTheMessage }} </div> </template> <script> export default { computed: { showOrNotTheMessage() { return this.$route.query?.lookingforthis ? 'Show this message' : 'Dont show this message' }, }, } </script> This one will mainly display a conditional string as an example. If you want to further debug what you're doing (with either Options or Composition API), you can select the root component in your Vue devtools and then access the whole Vue instance in your console with $vm0.$route.query PS: in Vue3, you need to use the following $vm0.proxy.$route.query That can help you debug your code faster and potentially find cool stuff to play with.
How can I get query parameters from a URL in Vue.js?
How can I fetch query parameters in Vue.js? E.g. http://somesite.com?test=yay Can’t find a way to fetch or do I need to use pure JS or some library for this?
[ "According to the docs of route object, you have access to a $route object from your components, which exposes what you need. In this case\n//from your component\nconsole.log(this.$route.query.test) // outputs 'yay'\n\n", "Without vue-router, split the URL\nvar vm = new Vue({\n ....\n created() {\n let uri = window.location.href.split('?');\n if(uri.length == 2) {\n let vars = uri[1].split('&');\n let getVars = {};\n let tmp = '';\n vars.forEach(function(v) {\n tmp = v.split('=');\n if(tmp.length == 2)\n getVars[tmp[0]] = tmp[1];\n });\n console.log(getVars);\n // do \n }\n },\n updated() {\n },\n....\n\nAnother solution https://developer.mozilla.org/en-US/docs/Web/API/HTMLHyperlinkElementUtils/search:\nvar vm = new Vue({\n ....\n created() {\n let uri = window.location.search.substring(1); \n let params = new URLSearchParams(uri);\n console.log(params.get(\"var_name\"));\n },\n updated() {\n },\n....\n\n", "Try this code\nvar vm = new Vue({\n created() {\n let urlParams = new URLSearchParams(window.location.search);\n console.log(urlParams.has('yourParam')); // true\n console.log(urlParams.get('yourParam')); // \"MyParam\"\n },\n});\n\n", "More detailed answer to help the newbies of VueJS:\n\nFirst define your router object, select the mode you seem fit.\nYou can declare your routes inside the routes list.\nNext you would want your main app to know router exists, so declare it inside the main app declaration.\nLastly the $route instance holds all the information about the current route. The code will console log just the parameter passed in the url. (*Mounted is similar to document.ready, i.e. it's called as soon as the app is ready)\n\nAnd the code itself:\n<script src=\"https://unpkg.com/vue-router\"></script>\nvar router = new VueRouter({\n mode: 'history',\n routes: []\n});\nvar vm = new Vue({\n router,\n el: '#app',\n mounted: function() {\n q = this.$route.query.q\n console.log(q)\n },\n});\n\n", "Another way (assuming you are using vue-router), is to map the query param to a prop in your router. Then you can treat it like any other prop in your component code. For example, add this route;\n{ \n path: '/mypage', \n name: 'mypage', \n component: MyPage, \n props: (route) => ({ foo: route.query.foo }), \n}\n\nThen in your component you can add the prop as normal;\nprops: {\n foo: {\n type: String,\n default: null,\n }\n},\n\nThen it will be available as this.foo and you can do anything you want with it (like set a watcher, etc.)\n", "Vue 3 Composition API\n(as far as now 2021, vue-router 4)\nimport {useRoute} from \"vue-router\";\n\n//can use only in setup()\nuseRoute().query.test\n\nor\n//somewhere in your src files\nimport router from \"~/router\";\n\n//can use everywhere \nrouter.currentRoute.value.query.test \n\nor\nimport {useRouter} from \"vue-router\";\n\n//can use only in setup()\nuseRouter().currentRoute.value.query.test\n\n", "As of this date, the correct way according to the dynamic routing docs is:\nthis.$route.params.yourProperty\n\ninstead of\nthis.$route.query.yourProperty\n\n", "\nYou can use vue-router.I have an example below:\n\nurl: www.example.com?name=john&lastName=doe\nnew Vue({\n el: \"#app\",\n data: {\n name: '',\n lastName: '',\n },\n beforeRouteEnter(to, from, next) {\n if(Object.keys(to.query).length !== 0) { //if the url has query (?query)\n next(vm => {\n vm.name = to.query.name;\n vm.lastName = to.query.lastName;\n });\n }\n next();\n }\n})\n\nNote: In beforeRouteEnter function we cannot access the component's properties like: this.propertyName.That's why i have pass the vm to next function.It is the recommented way to access the vue instance.Actually the vm it stands for vue instance\n", "If your url looks something like this:\nsomesite.com/something/123\n\nWhere '123' is a parameter named 'id' (url like /something/:id), try with:\nthis.$route.params.id\n\n", "Here is how to do it if you are using vue-router with vue3 composition api\nimport { useRoute } from 'vue-router'\n\nexport default {\n setup() {\n const route = useRoute()\n console.log(route.query)\n }\n}\n\n", "Example url: http://localhost:9528/#/course/outline/1439990638887137282\nBelow codes output: 1439990638887137282\nthis.courseId = this.$route.params.id\nconsole.log('courseId', this.courseId)\n\n", "one thing to keep in mind if you are using Hash mode then don't use this.$route.params.name only use url search param\n", "On top of the answers here, I recommend that you use the Vue devtools for further debugging.\nGiven this snippet of code\n<template>\n <div>\n {{ showOrNotTheMessage }}\n </div>\n</template>\n\n<script>\nexport default {\n computed: {\n showOrNotTheMessage() {\n return this.$route.query?.lookingforthis\n ? 'Show this message'\n : 'Dont show this message'\n },\n },\n}\n</script>\n\nThis one will mainly display a conditional string as an example.\n\nIf you want to further debug what you're doing (with either Options or Composition API), you can select the root component in your Vue devtools and then access the whole Vue instance in your console with\n$vm0.$route.query\n\nPS: in Vue3, you need to use the following\n$vm0.proxy.$route.query\n\n\nThat can help you debug your code faster and potentially find cool stuff to play with.\n" ]
[ 683, 95, 79, 52, 46, 25, 17, 6, 6, 5, 2, 1, 0 ]
[]
[]
[ "javascript", "query_parameters", "url_parameters", "vue.js", "vue_router" ]
stackoverflow_0035914069_javascript_query_parameters_url_parameters_vue.js_vue_router.txt
Q: When a SIGTSTP signal is encountered by the readline and the user has a callback, will the process be sent background after callback? [NODE JS] import * as readline from 'node:readline/promises'; import { stdin as input, stdout as output } from 'node:process'; const rl = readline.createInterface({ input, output }); rl.on('SIGTSTP', () => { console.log(process.pid); }); Will the process be sent to background after the PID is printed? A: As per the documentation: If there are no 'SIGTSTP' event listeners registered when the input stream receives a SIGTSTP, the Node.js process will be sent to the background. The process is sent to background if there are no event listeners. So because you have attached a listener here, it will prevent the process from being sent to the background. See the comment in the example from the docs: rl.on('SIGTSTP', () => { // This will override SIGTSTP and prevent the program from going to the // background. console.log('Caught SIGTSTP.'); });
When a SIGTSTP signal is encountered by the readline and the user has a callback, will the process be sent background after callback? [NODE JS]
import * as readline from 'node:readline/promises'; import { stdin as input, stdout as output } from 'node:process'; const rl = readline.createInterface({ input, output }); rl.on('SIGTSTP', () => { console.log(process.pid); }); Will the process be sent to background after the PID is printed?
[ "As per the documentation:\n\nIf there are no 'SIGTSTP' event listeners registered when the input stream receives a SIGTSTP, the Node.js process will be sent to the background.\n\nThe process is sent to background if there are no event listeners.\nSo because you have attached a listener here, it will prevent the process from being sent to the background.\nSee the comment in the example from the docs:\nrl.on('SIGTSTP', () => {\n // This will override SIGTSTP and prevent the program from going to the\n // background.\n console.log('Caught SIGTSTP.');\n});\n\n" ]
[ 0 ]
[]
[]
[ "child_process", "node.js", "readline" ]
stackoverflow_0074668722_child_process_node.js_readline.txt
Q: Get data from 2 tables with a foreign key using Laravel model relationships I have 2 tables 1) users 2) user_companies. A user belongs to or has one company, A company has many users. This is how I determined my relationships. How can I pull company data for each user? Attempt to read property "company" on string - is the error I am receiving with my setup. Here is what I have tried so far and many other combinations but cant seem to figure out how to show the company name which is stored in the user_companies table under the company column. Not sure what I am missing here. user model // Relationship between User and Company public function company() { return $this->hasOne(Company::class, 'id','company_id'); //return $this->belongsTo(Company::class, 'company_id'); } company model public function user() { return $this->hasMany(User::class); } userController public function profile(User $user, Company $company) { $company = Users::with(['company']); //$company = Company::with('user')->find('33'); return view('admin.users.profile', compact('user', 'company')); } blade file {{ $user->company->company }} migration file (just added new column FK) Schema::table('users', function (Blueprint $table) { $table->integer('company_id')->nullable()->unsigned(); $table->foreign('company_id') ->references('id') ->on('user_companies') ->onDelete('cascade'); }); A: First of all, you should change the relationship of user to company to belongsTo : // User.php public function company() :BelongsTo { return $this->belongsTo(Company:;class, 'company_id'); } then eager load it by using with() User::with('company')->get();
Get data from 2 tables with a foreign key using Laravel model relationships
I have 2 tables 1) users 2) user_companies. A user belongs to or has one company, A company has many users. This is how I determined my relationships. How can I pull company data for each user? Attempt to read property "company" on string - is the error I am receiving with my setup. Here is what I have tried so far and many other combinations but cant seem to figure out how to show the company name which is stored in the user_companies table under the company column. Not sure what I am missing here. user model // Relationship between User and Company public function company() { return $this->hasOne(Company::class, 'id','company_id'); //return $this->belongsTo(Company::class, 'company_id'); } company model public function user() { return $this->hasMany(User::class); } userController public function profile(User $user, Company $company) { $company = Users::with(['company']); //$company = Company::with('user')->find('33'); return view('admin.users.profile', compact('user', 'company')); } blade file {{ $user->company->company }} migration file (just added new column FK) Schema::table('users', function (Blueprint $table) { $table->integer('company_id')->nullable()->unsigned(); $table->foreign('company_id') ->references('id') ->on('user_companies') ->onDelete('cascade'); });
[ "First of all, you should change the relationship of user to company to belongsTo :\n// User.php\npublic function company() :BelongsTo\n{\n return $this->belongsTo(Company:;class, 'company_id');\n}\n\nthen eager load it by using with()\nUser::with('company')->get();\n\n" ]
[ 0 ]
[]
[]
[ "laravel", "php", "postgresql" ]
stackoverflow_0074668695_laravel_php_postgresql.txt
Q: what does "bool operator()(huffManNodeTree* a, huffManNodeTree* b)" mean? can someone answer for me plz what does bool operator()(huffManNodeTree* a, huffManNodeTree* b) mean? can someone answer for me plz here are my code in c++ class huffManNodeTree { public: char data;//storage character int freq;// frequency of character huffManNodeTree* right; huffManNodeTree* left; huffManNodeTree(char character,int frequency)// Initializing the current node { data = character; freq = frequency; left = right = NULL; } }; class Compare { public: bool operator()(huffManNodeTree* a, huffManNodeTree* b) { // Defining priority on the basis of frequency return a->freq > b->freq; } }; A: bool operator()(huffManNodeTree* a, huffManNodeTree* b) is a function call operator for a class or struct. This operator allows an object of the class to be called like a function, and it specifies the behavior of the function call. In the case of huffManNodeTree, this operator compares two pointers to huffManNodeTree objects and returns true if the first one should be considered "less than" the second one. Here is an example of how this operator might be used: int main() { huffManNodeTree node1('a', 10), node2('b', 20); Compare comparator; if (comparator(&node1, &node2)) { // node1 is less than node2 } else { // node1 is not less than node2 } return 0; } In this code, the huffManNodeTree struct has a frequency member and Compare uses its operator() to compare the frequency of two huffManNodeTree objects. An instance of Compare is then created and used like a function to compare the two node objects. The comparator object will return true if the frequency of node1 is less than the frequency of node2, and false otherwise.
what does "bool operator()(huffManNodeTree* a, huffManNodeTree* b)" mean? can someone answer for me plz
what does bool operator()(huffManNodeTree* a, huffManNodeTree* b) mean? can someone answer for me plz here are my code in c++ class huffManNodeTree { public: char data;//storage character int freq;// frequency of character huffManNodeTree* right; huffManNodeTree* left; huffManNodeTree(char character,int frequency)// Initializing the current node { data = character; freq = frequency; left = right = NULL; } }; class Compare { public: bool operator()(huffManNodeTree* a, huffManNodeTree* b) { // Defining priority on the basis of frequency return a->freq > b->freq; } };
[ "bool operator()(huffManNodeTree* a, huffManNodeTree* b) is a function call operator for a class or struct. This operator allows an object of the class to be called like a function, and it specifies the behavior of the function call. In the case of huffManNodeTree, this operator compares two pointers to huffManNodeTree objects and returns true if the first one should be considered \"less than\" the second one.\nHere is an example of how this operator might be used:\nint main()\n{\n huffManNodeTree node1('a', 10), node2('b', 20);\n Compare comparator;\n\n if (comparator(&node1, &node2))\n {\n // node1 is less than node2\n }\n else\n {\n // node1 is not less than node2\n }\n\n return 0;\n}\n\nIn this code, the huffManNodeTree struct has a frequency member and Compare uses its operator() to compare the frequency of two huffManNodeTree objects. An instance of Compare is then created and used like a function to compare the two node objects. The comparator object will return true if the frequency of node1 is less than the frequency of node2, and false otherwise.\n" ]
[ 0 ]
[]
[]
[ "c++", "class", "huffman_code", "operators", "queue" ]
stackoverflow_0074668618_c++_class_huffman_code_operators_queue.txt
Q: Swift await/async - how to wait synchronously for an async task to complete? I'm bridging the sync/async worlds in Swift and doing incremental adoption of async/await. I'm trying to invoke an async function that returns a value from a non async function. I understand that explicit use of Task is the way to do that, as described, for instance, here. The example doesn't really fit as that task doesn't return a value. After much searching, I haven't been able to find any description of what I'd think was a pretty common ask: synchronous invocation of an asynchronous task (and yes, I understand that that can freeze up the main thread). What I theoretically would like to write in my synchronous function is this: let x = Task { return await someAsyncFunction() }.result However, when I try to do that, I get this compiler error due to trying to access result: 'async' property access in a function that does not support concurrency One alternative I found was something like: Task.init { self.myResult = await someAsyncFunction() } where myResult has to be attributed as a @State member variable. However, that doesn't work the way I want it to, because there's no guarantee of completing that task prior to Task.init() completing and moving onto the next statement. So how can I wait synchronously for that Task to be complete? A: You should not wait synchronously for an async task. One may come up with a solution similar to this: func updateDatabase(_ asyncUpdateDatabase: @Sendable @escaping () async -> Void) { let semaphore = DispatchSemaphore(value: 0) Task { await asyncUpdateDatabase() semaphore.signal() } semaphore.wait() } Although it works in some simple conditions, according to WWDC 2021 Swift Concurrency: Behind the scenes, this is unsafe. The reason is the system expects you to conform to a runtime contract. The contract requires that Threads are always able to make forward progress. That means threads are never blocking. When an asynchronous function reaches a suspension point (e.g. an await expression), the function can be suspended, but the thread does not block, it can do other works. Based on this contract, the new cooperative thread pool is able to only spawn as many threads as there are CPU cores, avoiding excessive thread context switches. This contract is also the key reason why actors won't cause deadlocks. The above semaphore pattern violates this contract. The semaphore.wait() function blocks the thread. This can cause problems. For example func testGroup() { Task { await withTaskGroup(of: Void.self) { group in for _ in 0 ..< 100 { group.addTask { syncFunc() } } } NSLog("Complete") } } func syncFunc() { let semaphore = DispatchSemaphore(value: 0) Task { try? await Task.sleep(nanoseconds: 1_000_000_000) semaphore.signal() } semaphore.wait() } Here we add 100 concurrent child tasks in the testGroup function, unfortunately the task group will never complete. In my Mac, the system spawns 4 cooperative threads, adding only 4 child tasks is enough to block all 4 threads indefinitely. Because after all 4 threads are blocked by the wait function, there is no more thread available to execute the inner task that signals the semaphore. Another example of unsafe use is actor deadlock: func testActor() { Task { let d = Database() await d.updateSettings() NSLog("Complete") } } func updateDatabase(_ asyncUpdateDatabase: @Sendable @escaping () async -> Void) { let semaphore = DispatchSemaphore(value: 0) Task { await asyncUpdateDatabase() semaphore.signal() } semaphore.wait() } actor Database { func updateSettings() { updateDatabase { await self.updateUser() } } func updateUser() { } } Here calling the updateSettings function will deadlock. Because it waits synchronously for the updateUser function, while the updateUser function is isolated to the same actor, so it waits for updateSettings to complete first. The above two examples use DispatchSemaphore. Using NSCondition in a similar way is unsafe for the same reason. Basically waiting synchronously means blocking the current thread. Avoid this pattern unless you only want a temporary solution and fully understand the risks. A: Other than using semaphore, you can wrap your asynchronous task inside an operation like here. You can signal the operation finish once the underlying async task finishes and wait for operation completion using waitUntilFinished(): let op = TaskOperation { try await Task.sleep(nanoseconds: 1_000_000_000) } op.waitUntilFinished() Note that using semaphore.wait() or op.waitUntilFinished() blocks the current thread and blocking the thread can cause undefined runtime behaviors in modern concurrency as modern concurrency assumes all threads are always making forward progress. If you are planning to use this method only in contexts where you are not using modern concurrency, with Swift 5.7 you can provide attribute mark method unavailable in asynchronous context: @available(*, noasync, message: "this method blocks thread use the async version instead") func yourBlockingFunc() { // do work that can block thread } By using this attribute you can only invoke this method from a non-async context. But some caution is needed as you can invoke non-async methods that call this method from an async context if that method doesn't specify noasync availability.
Swift await/async - how to wait synchronously for an async task to complete?
I'm bridging the sync/async worlds in Swift and doing incremental adoption of async/await. I'm trying to invoke an async function that returns a value from a non async function. I understand that explicit use of Task is the way to do that, as described, for instance, here. The example doesn't really fit as that task doesn't return a value. After much searching, I haven't been able to find any description of what I'd think was a pretty common ask: synchronous invocation of an asynchronous task (and yes, I understand that that can freeze up the main thread). What I theoretically would like to write in my synchronous function is this: let x = Task { return await someAsyncFunction() }.result However, when I try to do that, I get this compiler error due to trying to access result: 'async' property access in a function that does not support concurrency One alternative I found was something like: Task.init { self.myResult = await someAsyncFunction() } where myResult has to be attributed as a @State member variable. However, that doesn't work the way I want it to, because there's no guarantee of completing that task prior to Task.init() completing and moving onto the next statement. So how can I wait synchronously for that Task to be complete?
[ "You should not wait synchronously for an async task.\nOne may come up with a solution similar to this:\nfunc updateDatabase(_ asyncUpdateDatabase: @Sendable @escaping () async -> Void) {\n let semaphore = DispatchSemaphore(value: 0)\n\n Task {\n await asyncUpdateDatabase()\n semaphore.signal()\n }\n\n semaphore.wait()\n}\n\nAlthough it works in some simple conditions, according to WWDC 2021 Swift Concurrency: Behind the scenes, this is unsafe. The reason is the system expects you to conform to a runtime contract. The contract requires that\n\nThreads are always able to make forward progress.\n\nThat means threads are never blocking. When an asynchronous function reaches a suspension point (e.g. an await expression), the function can be suspended, but the thread does not block, it can do other works. Based on this contract, the new cooperative thread pool is able to only spawn as many threads as there are CPU cores, avoiding excessive thread context switches. This contract is also the key reason why actors won't cause deadlocks.\nThe above semaphore pattern violates this contract. The semaphore.wait() function blocks the thread. This can cause problems. For example\nfunc testGroup() {\n Task {\n await withTaskGroup(of: Void.self) { group in\n for _ in 0 ..< 100 {\n group.addTask {\n syncFunc()\n }\n }\n }\n NSLog(\"Complete\")\n }\n}\n\nfunc syncFunc() {\n let semaphore = DispatchSemaphore(value: 0)\n Task {\n try? await Task.sleep(nanoseconds: 1_000_000_000)\n semaphore.signal()\n }\n semaphore.wait()\n}\n\nHere we add 100 concurrent child tasks in the testGroup function, unfortunately the task group will never complete. In my Mac, the system spawns 4 cooperative threads, adding only 4 child tasks is enough to block all 4 threads indefinitely. Because after all 4 threads are blocked by the wait function, there is no more thread available to execute the inner task that signals the semaphore.\nAnother example of unsafe use is actor deadlock:\nfunc testActor() {\n Task {\n let d = Database()\n await d.updateSettings()\n NSLog(\"Complete\")\n }\n}\n\nfunc updateDatabase(_ asyncUpdateDatabase: @Sendable @escaping () async -> Void) {\n let semaphore = DispatchSemaphore(value: 0)\n\n Task {\n await asyncUpdateDatabase()\n semaphore.signal()\n }\n\n semaphore.wait()\n}\n\nactor Database {\n func updateSettings() {\n updateDatabase {\n await self.updateUser()\n }\n }\n\n func updateUser() {\n\n }\n}\n\nHere calling the updateSettings function will deadlock. Because it waits synchronously for the updateUser function, while the updateUser function is isolated to the same actor, so it waits for updateSettings to complete first.\nThe above two examples use DispatchSemaphore. Using NSCondition in a similar way is unsafe for the same reason. Basically waiting synchronously means blocking the current thread. Avoid this pattern unless you only want a temporary solution and fully understand the risks.\n", "Other than using semaphore, you can wrap your asynchronous task inside an operation like here. You can signal the operation finish once the underlying async task finishes and wait for operation completion using waitUntilFinished():\nlet op = TaskOperation {\n try await Task.sleep(nanoseconds: 1_000_000_000)\n}\nop.waitUntilFinished()\n\nNote that using semaphore.wait() or op.waitUntilFinished() blocks the current thread and blocking the thread can cause undefined runtime behaviors in modern concurrency as modern concurrency assumes all threads are always making forward progress. If you are planning to use this method only in contexts where you are not using modern concurrency, with Swift 5.7 you can provide attribute mark method unavailable in asynchronous context:\n@available(*, noasync, message: \"this method blocks thread use the async version instead\")\nfunc yourBlockingFunc() {\n // do work that can block thread\n}\n\nBy using this attribute you can only invoke this method from a non-async context. But some caution is needed as you can invoke non-async methods that call this method from an async context if that method doesn't specify noasync availability.\n" ]
[ 6, 3 ]
[ "I wrote simple functions that can run asynchronous code as synchronous similar as Kotlin does, you can see code here. It's only for test purposes, though. DO NOT USE IT IN PRODUCTION as async code must be run only asynchronous\nExample:\nlet result = runBlocking {\n try? await Task.sleep(nanoseconds: 1_000_000_000)\n return \"Some result\"\n}\nprint(result) // prints \"Some result\"\n\n", "I've been wondering about this too. How can you start a Task (or several) and wait for them to be done in your main thread, for example? This may be C++ like thinking but there must be a way to do it in Swift as well. For better or worse, I came up with using a global variable to check if the work is done:\nimport Foundation\n\nvar isDone = false\n\nfunc printIt() async {\n try! await Task.sleep(nanoseconds: 200000000)\n print(\"hello world\")\n isDone = true\n}\n\nTask {\n await printIt()\n}\n\nwhile !isDone {\n Thread.sleep(forTimeInterval: 0.1)\n}\n\n" ]
[ -1, -5 ]
[ "swift", "swift_concurrency" ]
stackoverflow_0070962534_swift_swift_concurrency.txt
Q: How to make bottom sheet with "Apply" button which does not move until top sheet content gone This bottom sheet is normal as others but it has the button at the very bottom which does not move on swiping down until the top content disappearing. A: You can create a bottom sheet with an "Apply" button using a custom BottomSheetDialogFragment. The "Apply" button can remain visible until the content of the top sheet has been dismissed by overriding the onDismiss() callback. In the onCreateView() method of the BottomSheetDialogFragment, create the view for the bottom sheet and add the "Apply" button. In the onDismiss() callback, check if the top sheet content is gone and if so, make the "Apply" button visible. Otherwise, hide the "Apply" button. This way, the "Apply" button will remain visible until the content of the top sheet is gone. See the example: Here is an example of a custom BottomSheetDialogFragment with an "Apply" button that remains visible until the content of the top sheet is gone. class MyBottomSheetDialogFragment : BottomSheetDialogFragment() { private lateinit var btnApply: Button override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { val view = inflater.inflate(R.layout.bottom_sheet_layout, container, false) btnApply = view.findViewById(R.id.btn_apply) return view } override fun onDismiss(dialog: DialogInterface?) { super.onDismiss(dialog) if (dialog != null && dialog.isShowing) { btnApply.visibility = View.VISIBLE } else { btnApply.visibility = View.GONE } } }
How to make bottom sheet with "Apply" button which does not move until top sheet content gone
This bottom sheet is normal as others but it has the button at the very bottom which does not move on swiping down until the top content disappearing.
[ "You can create a bottom sheet with an \"Apply\" button using a custom BottomSheetDialogFragment. The \"Apply\" button can remain visible until the content of the top sheet has been dismissed by overriding the onDismiss() callback.\nIn the onCreateView() method of the BottomSheetDialogFragment, create the view for the bottom sheet and add the \"Apply\" button.\nIn the onDismiss() callback, check if the top sheet content is gone and if so, make the \"Apply\" button visible. Otherwise, hide the \"Apply\" button.\nThis way, the \"Apply\" button will remain visible until the content of the top sheet is gone.\nSee the example:\nHere is an example of a custom BottomSheetDialogFragment with an \"Apply\" button that remains visible until the content of the top sheet is gone.\nclass MyBottomSheetDialogFragment : BottomSheetDialogFragment() {\n\nprivate lateinit var btnApply: Button\n\noverride fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {\n\nval view = inflater.inflate(R.layout.bottom_sheet_layout, container, false)\n\nbtnApply = view.findViewById(R.id.btn_apply)\n\nreturn view\n\n}\n\noverride fun onDismiss(dialog: DialogInterface?) {\n\nsuper.onDismiss(dialog)\n\nif (dialog != null && dialog.isShowing) {\n\nbtnApply.visibility = View.VISIBLE\n\n} else {\n\nbtnApply.visibility = View.GONE\n\n}\n\n}\n\n}\n\n" ]
[ 0 ]
[]
[]
[ "android", "android_jetpack_compose", "kotlin", "xml" ]
stackoverflow_0074667862_android_android_jetpack_compose_kotlin_xml.txt
Q: eloquent laravel: How to get a row count from a ->get() I'm having a lot of trouble figuring out how to use this collection to count rows. $wordlist = \DB::table('wordlist')->where('id', '<=', $correctedComparisons) ->get(); I have tried adding->count() but didn't work. I have tried doing count($wordlist). I'm not really sure what to do without needing a second request as a->count() method. A: Answer has been updated count is a Collection method. The query builder returns an array. So in order to get the count, you would just count it like you normally would with an array: $wordCount = count($wordlist); If you have a wordlist model, then you can use Eloquent to get a Collection and then use the Collection's count method. Example: $wordlist = Wordlist::where('id', '<=', $correctedComparisons)->get(); $wordCount = $wordlist->count(); There is/was a discussion on having the query builder return a collection here: https://github.com/laravel/framework/issues/10478 However as of now, the query builder always returns an array. Edit: As linked above, the query builder now returns a collection (not an array). As a result, what JP Foster was trying to do initially will work: $wordlist = \DB::table('wordlist')->where('id', '<=', $correctedComparisons) ->get(); $wordCount = $wordlist->count(); However, as indicated by Leon in the comments, if all you want is the count, then querying for it directly is much faster than fetching an entire collection and then getting the count. In other words, you can do this: // Query builder $wordCount = \DB::table('wordlist')->where('id', '<=', $correctedComparisons) ->count(); // Eloquent $wordCount = Wordlist::where('id', '<=', $correctedComparisons)->count(); A: Direct get a count of row Using Eloquent //Useing Eloquent $count = Model::count(); //example $count1 = Wordlist::count(); Using query builder //Using query builder $count = \DB::table('table_name')->count(); //example $count2 = \DB::table('wordlist')->where('id', '<=', $correctedComparisons)->count(); A: Its better to access the count with the laravels count method $count = Model::where('status','=','1')->count(); or $count = Model::count(); A: also, you can fetch all data and count in the blade file. for example: your code in the controller $posts = Post::all(); return view('post', compact('posts')); your code in the blade file. {{ $posts->count() }} finally, you can see the total of your posts. A: //controller $count = Post::count(); return view('post', compact('count')); //blade {{$count}} or //controller $posts = Post::all(); return view('post', compact('posts')); //blade{{count($posts)}}
eloquent laravel: How to get a row count from a ->get()
I'm having a lot of trouble figuring out how to use this collection to count rows. $wordlist = \DB::table('wordlist')->where('id', '<=', $correctedComparisons) ->get(); I have tried adding->count() but didn't work. I have tried doing count($wordlist). I'm not really sure what to do without needing a second request as a->count() method.
[ "Answer has been updated\ncount is a Collection method. The query builder returns an array. So in order to get the count, you would just count it like you normally would with an array:\n$wordCount = count($wordlist);\n\nIf you have a wordlist model, then you can use Eloquent to get a Collection and then use the Collection's count method. Example:\n$wordlist = Wordlist::where('id', '<=', $correctedComparisons)->get();\n$wordCount = $wordlist->count();\n\nThere is/was a discussion on having the query builder return a collection here: https://github.com/laravel/framework/issues/10478\nHowever as of now, the query builder always returns an array.\nEdit: As linked above, the query builder now returns a collection (not an array). As a result, what JP Foster was trying to do initially will work:\n$wordlist = \\DB::table('wordlist')->where('id', '<=', $correctedComparisons)\n ->get();\n$wordCount = $wordlist->count();\n\nHowever, as indicated by Leon in the comments, if all you want is the count, then querying for it directly is much faster than fetching an entire collection and then getting the count. In other words, you can do this:\n// Query builder\n$wordCount = \\DB::table('wordlist')->where('id', '<=', $correctedComparisons)\n ->count();\n\n// Eloquent\n$wordCount = Wordlist::where('id', '<=', $correctedComparisons)->count();\n\n", "Direct get a count of row \nUsing Eloquent\n //Useing Eloquent\n $count = Model::count(); \n\n //example \n $count1 = Wordlist::count();\n\nUsing query builder\n //Using query builder\n $count = \\DB::table('table_name')->count();\n\n //example\n $count2 = \\DB::table('wordlist')->where('id', '<=', $correctedComparisons)->count();\n\n", "Its better to access the count with the laravels count method \n$count = Model::where('status','=','1')->count();\n\nor\n$count = Model::count();\n\n", "also, you can fetch all data and count in the blade file.\nfor example:\nyour code in the controller\n$posts = Post::all();\nreturn view('post', compact('posts'));\n\nyour code in the blade file.\n{{ $posts->count() }}\n\nfinally, you can see the total of your posts.\n", "//controller $count = Post::count(); return view('post', compact('count'));\n//blade {{$count}} \nor\n//controller $posts = Post::all(); return view('post', compact('posts'));\n//blade{{count($posts)}}\n" ]
[ 188, 118, 40, 5, 0 ]
[]
[]
[ "eloquent", "laravel", "php", "sql" ]
stackoverflow_0033676576_eloquent_laravel_php_sql.txt
Q: Copy a string to another string I am following this algorithm that will copy one string to another string: [S is a source string and T is a target string] 1. Set I = 0 2. Repeat step 3 while S[I] ≠ Null do 3. T[I] = S[I] 4. I = I + 1 [End of loop] 5. Set T[I] = Null 6. Return I have attempted it but it instead removes the first n characters from source string relative to length of target string. For example: #include <stdio.h> #include <stdlib.h> char const* stringCopy(char* T, char const* S){ while(*S){ *T++ = *S++; } //*T = 0; return T; } int main(void){ char sentence[100] = "some sentence"; char* again = "another"; printf("%s", stringCopy(sentence, again)); return EXIT_SUCCESS; } A: You return the incremented original pointer T. Make a copy of T for the copy loop and return the original pointer. #include <stdio.h> #include <stdlib.h> char const* stringCopy(char* T, char const* S){ char *ptr = T; while(*ptr++ = *S++); return T; } int main(void){ char sentence[100] = "some sentence"; char* again = "another"; printf("%s", stringCopy(sentence, again)); return EXIT_SUCCESS; }
Copy a string to another string
I am following this algorithm that will copy one string to another string: [S is a source string and T is a target string] 1. Set I = 0 2. Repeat step 3 while S[I] ≠ Null do 3. T[I] = S[I] 4. I = I + 1 [End of loop] 5. Set T[I] = Null 6. Return I have attempted it but it instead removes the first n characters from source string relative to length of target string. For example: #include <stdio.h> #include <stdlib.h> char const* stringCopy(char* T, char const* S){ while(*S){ *T++ = *S++; } //*T = 0; return T; } int main(void){ char sentence[100] = "some sentence"; char* again = "another"; printf("%s", stringCopy(sentence, again)); return EXIT_SUCCESS; }
[ "You return the incremented original pointer T. Make a copy of T for the copy loop and return the original pointer.\n#include <stdio.h>\n#include <stdlib.h>\n\nchar const* stringCopy(char* T, char const* S){\n char *ptr = T;\n\n while(*ptr++ = *S++);\n\n return T;\n}\n\nint main(void){\n char sentence[100] = \"some sentence\";\n char* again = \"another\";\n\n printf(\"%s\", stringCopy(sentence, again));\n return EXIT_SUCCESS;\n}\n\n" ]
[ 0 ]
[]
[]
[ "c" ]
stackoverflow_0074668810_c.txt
Q: Could not find a version that satisfies the requirement in python I am trying to create virtual env with python2 in mac os from here. While running pip install virtualenv command in terminal I am getting following error. Could not find a version that satisfies the requirement virtualenv (from versions: ) No matching distribution found for virtualenv A: If you are using python 3.x, Please try this commands sudo pip3 install --upgrade pip sudo pip3 install virtualenv A: Run this command and try again curl https://bootstrap.pypa.io/get-pip.py | python The detailed description can be found in the link shared by Anupam in the comments. A: Please try below commands pip install --upgrade virtualenv A: We tried the above but they didn't work in our case because we had two versions of python3 on the systems. One via a normal install a few months back and one via brew (on a Mac). When we discovered that, we downloaded and installed the latest version from python.org and as a result the pip was updated too. Once the pip was installed the sudo pip3 install virturaenv command worked fine. A: Try Below commands: pip install --upgrade pip pip install <'package-name'> example: pip install locust_plugins To check the list of packages installed, use below command: pip list I tried the same and it worked for me A: It is sometimes because of connectivity issue. Re-running the same command when connectivity is okay solves it. pip install virtualenv Initial Output: WARNING: Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NewConnectionError('<pip._vendor.urllib3.connection.HTTPSConnection object at 0x0000023A91A94190>: Failed to establish a new connection: [Errno 11001] getaddrinfo failed')': /simple/virtualenv/ WARNING: Retrying (Retry(total=3, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NewConnectionError('<pip._vendor.urllib3.connection.HTTPSConnection object at 0x0000023A922B3390>: Failed to establish a new connection: [Errno 11001] getaddrinfo failed')': /simple/virtualenv/ WARNING: Retrying (Retry(total=2, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NewConnectionError('<pip._vendor.urllib3.connection.HTTPSConnection object at 0x0000023A922B0850>: Failed to establish a new connection: [Errno 11001] getaddrinfo failed')': /simple/virtualenv/ WARNING: Retrying (Retry(total=1, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NewConnectionError('<pip._vendor.urllib3.connection.HTTPSConnection object at 0x0000023A922C5990>: Failed to establish a new connection: [Errno 11001] getaddrinfo failed')': /simple/virtualenv/ WARNING: Retrying (Retry(total=0, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NewConnectionError('<pip._vendor.urllib3.connection.HTTPSConnection object at 0x0000023A922C64D0>: Failed to establish a new connection: [Errno 11001] getaddrinfo failed')': /simple/virtualenv/ ERROR: Could not find a version that satisfies the requirement virtualenv (from versions: none) ERROR: No matching distribution found for virtualenv WARNING: There was an error checking the latest version of pip. Output after re-run when connectivity is okay: Collecting virtualenv Using cached virtualenv-20.17.0-py3-none-any.whl (8.8 MB) WARNING: Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ReadTimeoutError("HTTPSConnectionPool(host='pypi.org', port=443): Read timed out. (read timeout=15)")': /simple/distlib/ Collecting distlib<1,>=0.3.6 Using cached distlib-0.3.6-py2.py3-none-any.whl (468 kB) Collecting filelock<4,>=3.4.1 Using cached filelock-3.8.0-py3-none-any.whl (10 kB) Collecting platformdirs<3,>=2.4 Using cached platformdirs-2.5.4-py3-none-any.whl (14 kB) Installing collected packages: distlib, platformdirs, filelock, virtualenv Successfully installed distlib-0.3.6 filelock-3.8.0 platformdirs-2.5.4 virtualenv-20.17.0 [notice] A new release of pip available: 22.3 -> 22.3.1 [notice] To update, run: python.exe -m pip install --upgrade pip
Could not find a version that satisfies the requirement in python
I am trying to create virtual env with python2 in mac os from here. While running pip install virtualenv command in terminal I am getting following error. Could not find a version that satisfies the requirement virtualenv (from versions: ) No matching distribution found for virtualenv
[ "If you are using python 3.x, Please try this commands\n\nsudo pip3 install --upgrade pip\nsudo pip3 install virtualenv\n\n", "Run this command and try again\ncurl https://bootstrap.pypa.io/get-pip.py | python\n\nThe detailed description can be found in the link shared by Anupam in the comments.\n", "Please try below commands\npip install --upgrade virtualenv\n\n", "We tried the above but they didn't work in our case because we had two versions of python3 on the systems. One via a normal install a few months back and one via brew (on a Mac). When we discovered that, we downloaded and installed the latest version from python.org and as a result the pip was updated too. Once the pip was installed the sudo pip3 install virturaenv command worked fine. \n", "Try Below commands:\n\npip install --upgrade pip\n\n\npip install <'package-name'>\n\nexample: pip install locust_plugins\nTo check the list of packages installed, use below command:\n\npip list\n\nI tried the same and it worked for me\n", "It is sometimes because of connectivity issue. Re-running the same command when connectivity is okay solves it.\npip install virtualenv\n\nInitial Output:\nWARNING: Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NewConnectionError('<pip._vendor.urllib3.connection.HTTPSConnection object at 0x0000023A91A94190>: Failed to establish a new connection: [Errno 11001] getaddrinfo failed')': /simple/virtualenv/\nWARNING: Retrying (Retry(total=3, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NewConnectionError('<pip._vendor.urllib3.connection.HTTPSConnection object at 0x0000023A922B3390>: Failed to establish a new connection: [Errno 11001] getaddrinfo failed')': /simple/virtualenv/\nWARNING: Retrying (Retry(total=2, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NewConnectionError('<pip._vendor.urllib3.connection.HTTPSConnection object at 0x0000023A922B0850>: Failed to establish a new connection: [Errno 11001] getaddrinfo failed')': /simple/virtualenv/\nWARNING: Retrying (Retry(total=1, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NewConnectionError('<pip._vendor.urllib3.connection.HTTPSConnection object at 0x0000023A922C5990>: Failed to establish a new connection: [Errno 11001] getaddrinfo failed')': /simple/virtualenv/\nWARNING: Retrying (Retry(total=0, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NewConnectionError('<pip._vendor.urllib3.connection.HTTPSConnection object at 0x0000023A922C64D0>: Failed to establish a new connection: [Errno 11001] getaddrinfo failed')': /simple/virtualenv/\nERROR: Could not find a version that satisfies the requirement virtualenv (from versions: none)\nERROR: No matching distribution found for virtualenv\nWARNING: There was an error checking the latest version of pip.\n\nOutput after re-run when connectivity is okay:\nCollecting virtualenv\n Using cached virtualenv-20.17.0-py3-none-any.whl (8.8 MB)\nWARNING: Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ReadTimeoutError(\"HTTPSConnectionPool(host='pypi.org', port=443): Read timed out. (read timeout=15)\")': /simple/distlib/\nCollecting distlib<1,>=0.3.6\n Using cached distlib-0.3.6-py2.py3-none-any.whl (468 kB)\nCollecting filelock<4,>=3.4.1\n Using cached filelock-3.8.0-py3-none-any.whl (10 kB)\nCollecting platformdirs<3,>=2.4\n Using cached platformdirs-2.5.4-py3-none-any.whl (14 kB)\nInstalling collected packages: distlib, platformdirs, filelock, virtualenv\nSuccessfully installed distlib-0.3.6 filelock-3.8.0 platformdirs-2.5.4 virtualenv-20.17.0\n\n[notice] A new release of pip available: 22.3 -> 22.3.1\n[notice] To update, run: python.exe -m pip install --upgrade pip\n\n" ]
[ 15, 14, 13, 1, 0, 0 ]
[ "pip install --upgrade virtualenv\nThis solution works for me in Centos8\n", "If you are using Windows, you have to run cmd as admin.\n" ]
[ -1, -5 ]
[ "pip", "python", "virtualenv" ]
stackoverflow_0049745105_pip_python_virtualenv.txt
Q: .gitpod.yml doesn't seem to run For a school assignment I have to use gitpod and I have to use "gitpod/workspace-node" as base image. Then after that I have to run docker-compse up on startup. This is my .gitpod.yml image: file: .gitpod.Dockerfile tasks: - name: Docker compose command: docker-compose up -d ports: - port: 80 onOpen: open-browser - port: 3306 onOpen: ignore vscode: extensions: - "dbaeumer.vscode-eslint" - "ms-azuretools.vscode-docker" and this is my .gitpod.Dockerfile FROM gitpod/workspace-node WORKDIR /usr/src/app COPY package*.json ./ COPY . . When I start up the workspace nothing happens it doesn't even pull the image. I seriously don't know what I'm doing wrong. I know for a fact that the docker-compose up works as expected so there's no issues there. I just can't get the .gitpod.yml to run A: Nvm I solved it. I just had to make a new workspace
.gitpod.yml doesn't seem to run
For a school assignment I have to use gitpod and I have to use "gitpod/workspace-node" as base image. Then after that I have to run docker-compse up on startup. This is my .gitpod.yml image: file: .gitpod.Dockerfile tasks: - name: Docker compose command: docker-compose up -d ports: - port: 80 onOpen: open-browser - port: 3306 onOpen: ignore vscode: extensions: - "dbaeumer.vscode-eslint" - "ms-azuretools.vscode-docker" and this is my .gitpod.Dockerfile FROM gitpod/workspace-node WORKDIR /usr/src/app COPY package*.json ./ COPY . . When I start up the workspace nothing happens it doesn't even pull the image. I seriously don't know what I'm doing wrong. I know for a fact that the docker-compose up works as expected so there's no issues there. I just can't get the .gitpod.yml to run
[ "Nvm I solved it. I just had to make a new workspace\n" ]
[ 0 ]
[]
[]
[ "docker", "dockerfile", "gitpod", "linux" ]
stackoverflow_0074641396_docker_dockerfile_gitpod_linux.txt
Q: How do I disable username annotations in PyCharm I'm not sure if it was an update or I enabled a setting but I am seeing my code annotated with git blame usernames inline with the code. The git blame action says it is turned off. When I click on the username the column with the line numbers expands and shows the timestamps. How to I disable the usernames from appearing? After Clicking A: I had the same problem. Solved it by right-clicking the line number column. There's an option in the menu to turn off code change information. I don't remember the exact menu option name because I don't know how to turn it back on to check. A: This can be solved by navigating to Preferences > Editor > Inlay Hints and then within Code vision they have an option (enabled by default for me) for Code author. Just disable this and it goes away.
How do I disable username annotations in PyCharm
I'm not sure if it was an update or I enabled a setting but I am seeing my code annotated with git blame usernames inline with the code. The git blame action says it is turned off. When I click on the username the column with the line numbers expands and shows the timestamps. How to I disable the usernames from appearing? After Clicking
[ "I had the same problem. Solved it by right-clicking the line number column. There's an option in the menu to turn off code change information. I don't remember the exact menu option name because I don't know how to turn it back on to check.\n", "\nThis can be solved by navigating to Preferences > Editor > Inlay Hints and then within Code vision they have an option (enabled by default for me) for Code author. Just disable this and it goes away.\n" ]
[ 11, 0 ]
[ "Right-click any line number. Then uncheck Annotate with Git Blame\n\nYou cannot get there by right-clicking the annotation itself. Eye-roll emoji. The same option is buried in the Git submenu if you right-click the line of code.\n" ]
[ -1 ]
[ "annotations", "git_blame", "pycharm" ]
stackoverflow_0073158239_annotations_git_blame_pycharm.txt
Q: Python's chr() and ord() in Rust In Python you can convert an integer into a character and a character into an integer with ord() and chr(): >>>a = "a" >>>b = ord(a) + 1 >>>b = chr(b) I am looking for a way to do the same thing in Rust, but I have found nothing similar yet. A: You can use the available Into and TryInto implementations: fn main() { let mut a: char = 'a'; let mut b: u32 = a.into(); // char implements Into<u32> b += 1; a = b.try_into().unwrap(); // We have to use TryInto trait here because not every valid u32 is a valid unicode scalar value println!("{}", a); } A: ord can be done using the as keyword: let c = 'c'; assert_eq!(99, c as u32); While chr using the char::from_u32() function: let c = char::from_u32(0x2728); assert_eq!(Some('✨'), c); Note that char::from_u32() returns an Option<char> in case the number isn't a valid codepoint. There's also char::from_u32_unchecked().
Python's chr() and ord() in Rust
In Python you can convert an integer into a character and a character into an integer with ord() and chr(): >>>a = "a" >>>b = ord(a) + 1 >>>b = chr(b) I am looking for a way to do the same thing in Rust, but I have found nothing similar yet.
[ "You can use the available Into and TryInto implementations:\nfn main() {\n let mut a: char = 'a';\n let mut b: u32 = a.into(); // char implements Into<u32>\n b += 1;\n a = b.try_into().unwrap(); // We have to use TryInto trait here because not every valid u32 is a valid unicode scalar value\n println!(\"{}\", a);\n}\n\n", "ord can be done using the as keyword:\nlet c = 'c';\nassert_eq!(99, c as u32);\n\nWhile chr using the char::from_u32() function:\nlet c = char::from_u32(0x2728);\nassert_eq!(Some('✨'), c);\n\nNote that char::from_u32() returns an Option<char> in case the number isn't a valid codepoint. There's also char::from_u32_unchecked().\n" ]
[ 9, 1 ]
[]
[]
[ "chr", "ord", "rust" ]
stackoverflow_0071368937_chr_ord_rust.txt
Q: Cannot preview in this file - active scheme does not build this file : SwiftUI on Xcode 11 in CatalinaOS I opened Landmark App using SwiftUI on Xcode 11 in macOS Catalina(10.15) and while opening the Canvas Editor for .swift files containing SwiftUI is showing Cannot preview in this file - active scheme does not build this file Try Again, Diagonistics option or restarting Xcode not solving the problem. A: If this is a new project coming from a copied folder and inside an iCloud folder, just close Xcode and relaunch it. The sync was not yet done. A: Select the Scheme that has the current file to Preview A: You should go through Xcode and Apple SDKs Agreement and you can do it by running the following in terminal in mac: sudo xcodebuild -license After doing that reopen your project. A: I experienced the same issue. All I did was to copy the "StartingPoint" folder out of the downloaded folder and relaunched the project. It worked!!! A: I bumped into this too, following the Landmarks tutorial. When I created the 'CircleImage.swift' it was not letting me preview it, with the above error message. You can see the current Scheme you're using by going to Product > Scheme. I've got macOS selected. Clicking on the CircleImage.swift file loads it, and in the rightmost sidebar it shows the Attributes inspector. A few buttons to the left of that is "Show the File inspector". There, you can see this file's chosen "Target Membership". My problem was that "Landmarks (macOS)" was not checked. Checking this immediately got the Preview working. I imagine I could also have changed my Product's Scheme to iOS and it would have worked, as that was already checked. A: I encountered the same error for some of my SwiftUI View files when trying to preview on Canvas. What fixed the issue was I copied the code within the current file, deleted the file, created a new SwiftUI View file under the same name and pasted the original code. Hope that helps! Creating a new folder in Documents/Desktop and copying the files over also resolves the issue. A: This problem happened to me when I copied a folder into my project with the "Create folder reference" option instead of the "Create groups" option. The problem was solved when I deleted the folder from project and copied the folder again with the latter option. A: I just upgraded to both Monterey 12.3, and Xcode 13.3, and boom ran into this issue. Things were fine before the upgrade. Nothing above helped. Creating a new project does help. So the only thing I found is to create a new project, and just add the files from the old project to the new one. Yuk. EDIT: I hadn't rebooted the computer (mac mini), after reboot things were fine again. A: In the schemes I was able to select, it contained only one scheme. Reopening the folder in a folder that's not in the Downloads directory made live editing work for me A: Restarting my PC worked for me. A: The described issue happened to me after cloning a project via git (no iCloud syncing as described in another answer - so I definitely know that the sync itself was completely done). Funny enough restarting Xcode did the trick. Just closing and opening the project isn't enough. A: I found that the file I was trying to preview was not listed in Target -> Build Phases -> Compile Sources. Once I manually added the file, Preview worked. I had drag and dropped a directory into the project, and for some reason Xcode had not added those files to that list. A: Try About this mac -> Storage -> Manage -> Developer, Then delete Xcode cache from here then restart Xcode...This worked out for me A: Make sure the file you are trying to preview is in your app (the folder with the same name as your project). I was able to fix newly created files not previewing by moving the file into my project. A: Another solution: Make sure you select file type Swift UI instead of Swift File when you create the file.
Cannot preview in this file - active scheme does not build this file : SwiftUI on Xcode 11 in CatalinaOS
I opened Landmark App using SwiftUI on Xcode 11 in macOS Catalina(10.15) and while opening the Canvas Editor for .swift files containing SwiftUI is showing Cannot preview in this file - active scheme does not build this file Try Again, Diagonistics option or restarting Xcode not solving the problem.
[ "If this is a new project coming from a copied folder and inside an iCloud folder, just close Xcode and relaunch it. The sync was not yet done.\n", "Select the Scheme that has the current file to Preview\n\n", "You should go through Xcode and Apple SDKs Agreement and you can do it by running the following in terminal in mac:\nsudo xcodebuild -license\n\nAfter doing that reopen your project.\n", "I experienced the same issue. All I did was to copy the \"StartingPoint\" folder out of the downloaded folder and relaunched the project. It worked!!!\n", "I bumped into this too, following the Landmarks tutorial. When I created the 'CircleImage.swift' it was not letting me preview it, with the above error message.\nYou can see the current Scheme you're using by going to Product > Scheme. I've got macOS selected.\n\nClicking on the CircleImage.swift file loads it, and in the rightmost sidebar it shows the Attributes inspector. A few buttons to the left of that is \"Show the File inspector\".\nThere, you can see this file's chosen \"Target Membership\". My problem was that \"Landmarks (macOS)\" was not checked. Checking this immediately got the Preview working.\n\nI imagine I could also have changed my Product's Scheme to iOS and it would have worked, as that was already checked.\n", "I encountered the same error for some of my SwiftUI View files when trying to preview on Canvas. What fixed the issue was I copied the code within the current file, deleted the file, created a new SwiftUI View file under the same name and pasted the original code. Hope that helps!\nCreating a new folder in Documents/Desktop and copying the files over also resolves the issue.\n", "This problem happened to me when I copied a folder into my project with the \"Create folder reference\" option instead of the \"Create groups\" option.\nThe problem was solved when I deleted the folder from project and copied the folder again with the latter option.\n", "I just upgraded to both Monterey 12.3, and Xcode 13.3, and boom ran into this issue. Things were fine before the upgrade. Nothing above helped.\nCreating a new project does help. So the only thing I found is to create a new project, and just add the files from the old project to the new one. Yuk.\nEDIT: I hadn't rebooted the computer (mac mini), after reboot things were fine again.\n", "In the schemes I was able to select, it contained only one scheme. Reopening the folder in a folder that's not in the Downloads directory made live editing work for me\n", "Restarting my PC worked for me.\n", "The described issue happened to me after cloning a project via git (no iCloud syncing as described in another answer - so I definitely know that the sync itself was completely done).\nFunny enough restarting Xcode did the trick.\nJust closing and opening the project isn't enough.\n", "I found that the file I was trying to preview was not listed in Target -> Build Phases -> Compile Sources. Once I manually added the file, Preview worked. I had drag and dropped a directory into the project, and for some reason Xcode had not added those files to that list.\n", "Try About this mac -> Storage -> Manage -> Developer, Then delete Xcode cache from here then restart Xcode...This worked out for me\n", "Make sure the file you are trying to preview is in your app (the folder with the same name as your project).\nI was able to fix newly created files not previewing by moving the file into my project.\n", "Another solution:\nMake sure you select file type Swift UI instead of Swift File when you create the file.\n" ]
[ 29, 16, 9, 6, 4, 3, 2, 1, 0, 0, 0, 0, 0, 0, 0 ]
[]
[]
[ "ios", "macos_catalina", "swiftui", "xcode11" ]
stackoverflow_0058416469_ios_macos_catalina_swiftui_xcode11.txt
Q: Call to undefined function mysqli_connect on PHP for windows I have the following code: <?php DEFINE ('DB_USER', 'test'); DEFINE ('DB_PASSWORD', 'test'); DEFINE ('DB_HOST', 'localhost'); DEFINE ('DB_NAME', 'site'); $dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME) OR die('Could not connect to MYSQL ' . mysqli_connect_error()); ?> If I run this I will get this error message: Fatal error: Uncaught Error: Call to undefined function mysqli_connect() I'm using PHP for Windows downloaded From what I have read, you're supposed to uncomment parts in your php.ini file. There is no php.ini in my PHP folder, but only php.ini-development and php.ini-production. I've tried renaming one of the files to php.ini and uncommenting extension=mysqli, but the problem is still there. How can I solve this issue? A: I was having this same issue, and most stackoverflow answers didn't really clearly address this other step you need to take in setting up your php.ini. If you just uncomment extension=mysqli php still has no idea where any of your extensions are actually located, so it will fail to load them. Locate the section of your php.ini that looks something like: ; Directory in which the loadable extensions (modules) reside. ; http://php.net/extension-dir ; extension_dir = "./" ; On windows: ; extension_dir = "ext" And then uncomment the bottom "extension_dir" value and fill in the value with the absolute path of your "ext" directory, ie: extension_dir = "<absolute-path-to-ext-folder>" Once I completed these two steps (uncommenting extension=mysqli and then adding the absolute path in extension_dir), mysqli loaded correctly A: As the setup say you have to rename one of those 2 you have, if you don't PHP will go with defaults. So change one of them to php.ini and uncomment the line - this should not really be needed as far as i recall. A: For Windows, you can find the file in the C:\xampp\php\php.ini-Folder (Windows) or in the etc-Folder (within the xampp-Folder). Under Linux, most distributions put lampp under /opt/lampp, so the file can be found under /opt/lampp/etc/php.ini. If you can't find it. Then you should rename one of those to php.ini file. A: There are two files php.ini-development and php.ini-production There is no php.ini file in the php directory so you have to create one Step1: Copy the php.ini-development into new file named php.ini Step2: Uncomment ;extension=mysqli by removing ; from the starting of line no: 928 Step3: Replace the ext with exact location of ext folder of php in line no:763 extension_dir = "ext" Ex: extension_dir = "C:/Program Files/php/ext" and save the file Step4: php -m run in terminal and look for mysqli, it its there then everything is working fine
Call to undefined function mysqli_connect on PHP for windows
I have the following code: <?php DEFINE ('DB_USER', 'test'); DEFINE ('DB_PASSWORD', 'test'); DEFINE ('DB_HOST', 'localhost'); DEFINE ('DB_NAME', 'site'); $dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME) OR die('Could not connect to MYSQL ' . mysqli_connect_error()); ?> If I run this I will get this error message: Fatal error: Uncaught Error: Call to undefined function mysqli_connect() I'm using PHP for Windows downloaded From what I have read, you're supposed to uncomment parts in your php.ini file. There is no php.ini in my PHP folder, but only php.ini-development and php.ini-production. I've tried renaming one of the files to php.ini and uncommenting extension=mysqli, but the problem is still there. How can I solve this issue?
[ "I was having this same issue, and most stackoverflow answers didn't really clearly address this other step you need to take in setting up your php.ini. If you just uncomment extension=mysqli php still has no idea where any of your extensions are actually located, so it will fail to load them. Locate the section of your php.ini that looks something like:\n; Directory in which the loadable extensions (modules) reside.\n; http://php.net/extension-dir\n; extension_dir = \"./\"\n; On windows:\n; extension_dir = \"ext\"\n\nAnd then uncomment the bottom \"extension_dir\" value and fill in the value with the absolute path of your \"ext\" directory, ie:\nextension_dir = \"<absolute-path-to-ext-folder>\"\n\nOnce I completed these two steps (uncommenting extension=mysqli and then adding the absolute path in extension_dir), mysqli loaded correctly\n", "As the setup say you have to rename one of those 2 you have, if you don't PHP will go with defaults.\nSo change one of them to php.ini and uncomment the line - this should not really be needed as far as i recall.\n", "For Windows, you can find the file in the C:\\xampp\\php\\php.ini-Folder (Windows) or in the etc-Folder (within the xampp-Folder).\nUnder Linux, most distributions put lampp under /opt/lampp, so the file can be found under /opt/lampp/etc/php.ini.\nIf you can't find it. Then you should rename one of those to php.ini file.\n", "There are two files php.ini-development and php.ini-production \nThere is no php.ini file in the php directory \nso you have to create one \nStep1: Copy the php.ini-development into new file named php.ini \nStep2: Uncomment ;extension=mysqli by removing ; from the starting of line no: 928\n\nStep3: Replace the ext with exact location of ext folder of php in line no:763 extension_dir = \"ext\" Ex: extension_dir = \"C:/Program Files/php/ext\" and save the file\nStep4: php -m run in terminal and look for mysqli, it its there then everything is working fine\n" ]
[ 3, 0, 0, 0 ]
[]
[]
[ "mysql", "php" ]
stackoverflow_0049178288_mysql_php.txt
Q: How to create this title style? looking to create a title style where the text breaks in-between the line, not sure if this would be considered a border or what. Any ideas? Haven't tried anything yet - have been playing around but can't figure it out A: I have come up with one valid for different text widths and any possible background without adding extra markup. Also, I tried matching the image by adding a few extra stylings and font colors. h1 { overflow: hidden; text-align: center; color: #9cb69c; font-family: sans-serif; font-size: 16px; font-weight: normal; letter-spacing: 2.5px; } h1:before, h1:after { background-color: #9cb69c; content: ""; display: inline-block; height: 1px; position: relative; vertical-align: middle; width: 50%; } h1:before { right: 1.5em; margin-left: -50%; } h1:after { left: 1.5em; margin-right: -50%; } <h1>STAY INSPIRED</h1> A: Another way of solving it, using flex, padding and linear-gradient. body { --background-color: #fcfbfa; background-color: var(--background-color); } h2.decorated { color: #9ba592; display: flex; justify-content: center; background: linear-gradient(to bottom, transparent calc(50% - 1px), currentcolor 50%, transparent calc(50% + 1px)); } h2.decorated > div { padding: 1rem 2rem; background-color: var(--background-color); font-family: sans-serif; font-size: 10px; letter-spacing: 2px; text-transform: uppercase; } <h2 class="decorated"><div>Stay Inspired</div></h2> A: HTML supports for adding lines with ::before and ::after CSS Selectors. The ::before selector inserts content before a selected element. ::after inserts content after a specified element. These pseudo-elements in CSS allows you to insert content onto a page without it needing to be in the HTML. Ex: HTML <h2 class="hr-lines"> Stay Inspired</h2> CSS .hr-lines{ position: relative; max-width: 500px; margin: 100px auto; text-align: center; } .hr-lines:before, .hr-lines:after{ content:" "; height: 2px; width: 130px; background: red; display: block; position: absolute; top: 50%; left: 0; } A: I hope this solution attached can help you. .container{ display: flex; align-items: center; justify-content: center; flex-direction: row; } .divider{ border-top:1px solid gray; width: 45%; margin: 10px <div class="container"> <div class="divider"></div> <h3>Hello</h3> <div class="divider"></div> </div>
How to create this title style?
looking to create a title style where the text breaks in-between the line, not sure if this would be considered a border or what. Any ideas? Haven't tried anything yet - have been playing around but can't figure it out
[ "I have come up with one valid for different text widths and any possible background without adding extra markup. Also, I tried matching the image by adding a few extra stylings and font colors.\n\n\nh1 {\n overflow: hidden;\n text-align: center;\n color: #9cb69c;\n font-family: sans-serif;\n font-size: 16px;\n font-weight: normal;\n letter-spacing: 2.5px;\n}\n\nh1:before,\nh1:after {\n background-color: #9cb69c;\n content: \"\";\n display: inline-block;\n height: 1px;\n position: relative;\n vertical-align: middle;\n width: 50%;\n}\n\nh1:before {\n right: 1.5em;\n margin-left: -50%;\n}\n\nh1:after {\n left: 1.5em;\n margin-right: -50%;\n}\n<h1>STAY INSPIRED</h1>\n\n\n\n", "Another way of solving it, using flex, padding and linear-gradient.\n\n\nbody {\n --background-color: #fcfbfa;\n \n background-color: var(--background-color);\n}\n\nh2.decorated {\n color: #9ba592;\n display: flex;\n justify-content: center;\n background: linear-gradient(to bottom, transparent calc(50% - 1px), currentcolor 50%, transparent calc(50% + 1px));\n}\n\nh2.decorated > div {\n padding: 1rem 2rem;\n background-color: var(--background-color);\n\n font-family: sans-serif;\n font-size: 10px;\n letter-spacing: 2px;\n text-transform: uppercase;\n}\n<h2 class=\"decorated\"><div>Stay Inspired</div></h2>\n\n\n\n", "HTML supports for adding lines with ::before and ::after CSS Selectors. The ::before selector inserts content before a selected element. ::after inserts content after a specified element.\nThese pseudo-elements in CSS allows you to insert content onto a page without it needing to be in the HTML.\nEx:\nHTML\n<h2 class=\"hr-lines\"> Stay Inspired</h2>\n\nCSS\n.hr-lines{\n position: relative;\n max-width: 500px;\n margin: 100px auto;\n text-align: center;\n}\n\n.hr-lines:before, .hr-lines:after{\n content:\" \";\n height: 2px;\n width: 130px;\n background: red;\n display: block;\n position: absolute;\n top: 50%;\n left: 0;\n}\n\n\n", "I hope this solution attached can help you.\n\n\n.container{\n display: flex;\n align-items: center;\n justify-content: center;\n flex-direction: row;\n}\n.divider{\n border-top:1px solid gray;\n width: 45%;\n margin: 10px \n<div class=\"container\">\n <div class=\"divider\"></div>\n <h3>Hello</h3>\n <div class=\"divider\"></div>\n</div>\n\n\n\n" ]
[ 0, 0, 0, 0 ]
[]
[]
[ "css", "html", "liquid", "shopify" ]
stackoverflow_0074668477_css_html_liquid_shopify.txt
Q: How to rename JSON key I have a JSON object with the following content: [ { "_id":"5078c3a803ff4197dc81fbfb", "email":"[email protected]", "image":"some_image_url", "name":"Name 1" }, { "_id":"5078c3a803ff4197dc81fbfc", "email":"[email protected]", "image":"some_image_url", "name":"Name 2" } ] I want to change the "_id" key to "id" so it would become [ { "id":"5078c3a803ff4197dc81fbfb", "email":"[email protected]", "image":"some_image_url", "name":"Name 1" }, { "id":"5078c3a803ff4197dc81fbfc", "email":"[email protected]", "image":"some_image_url", "name":"Name 2" } ] How would I do that either with Javascript, jQuery or Ruby, Rails? Thanks. A: Parse the JSON const arr = JSON.parse(json); For each object in the JSON, rename the key: obj.id = obj._id; delete obj._id; Stringify the result All together: function renameKey ( obj, oldKey, newKey ) { obj[newKey] = obj[oldKey]; delete obj[oldKey]; } const json = ` [ { "_id":"5078c3a803ff4197dc81fbfb", "email":"[email protected]", "image":"some_image_url", "name":"Name 1" }, { "_id":"5078c3a803ff4197dc81fbfc", "email":"[email protected]", "image":"some_image_url", "name":"Name 2" } ] `; const arr = JSON.parse(json); arr.forEach( obj => renameKey( obj, '_id', 'id' ) ); const updatedJson = JSON.stringify( arr ); console.log( updatedJson ); A: In this case it would be easiest to use string replace. Serializing the JSON won't work well because _id will become the property name of the object and changing a property name is no simple task (at least not in most langauges, it's not so bad in javascript). Instead just do; jsonString = jsonString.replace("\"_id\":", "\"id\":"); A: As mentioned by evanmcdonnal, the easiest solution is to process this as string instead of JSON, var json = [{"_id":"5078c3a803ff4197dc81fbfb","email":"[email protected]","image":"some_image_url","name":"Name 1"},{"_id":"5078c3a803ff4197dc81fbfc","email":"[email protected]","image":"some_image_url","name":"Name 2"}]; json = JSON.parse(JSON.stringify(json).split('"_id":').join('"id":')); document.write(JSON.stringify(json)); This will convert given JSON data to string and replace "_id" to "id" then converting it back to the required JSON format. But I used split and join instead of replace, because replace will replace only the first occurrence of the string. A: JSON.parse has two parameters. The second parameter, reviver, is a transform function that can format the output format we want. See ECMA specification here. In reviver function: if we return undefined, the original property will be deleted. this is the object containing the property being processed as this function, and the property name as a string, the property value as arguments of this function. const json = '[{"_id":"5078c3a803ff4197dc81fbfb","email":"[email protected]","image":"some_image_url","name":"Name 1"},{"_id":"5078c3a803ff4197dc81fbfc","email":"[email protected]","image":"some_image_url","name":"Name 2"}]'; const obj = JSON.parse(json, function(k, v) { if (k === "_id") { this.id = v; return; // if return undefined, orignal property will be removed } return v; }); const res = JSON.stringify(obj); console.log(res) output: [{"email":"[email protected]","image":"some_image_url","name":"Name 1","id":"5078c3a803ff4197dc81fbfb"},{"email":"[email protected]","image":"some_image_url","name":"Name 2","id":"5078c3a803ff4197dc81fbfc"}] A: Try this: let jsonArr = [ { "_id":"5078c3a803ff4197dc81fbfb", "email":"[email protected]", "image":"some_image_url", "name":"Name 1" }, { "_id":"5078c3a803ff4197dc81fbfc", "email":"[email protected]", "image":"some_image_url", "name":"Name 2" } ] let idModified = jsonArr.map( obj => { return { "id" : obj._id, "email":obj.email, "image":obj.image, "name":obj.name } } ); console.log(idModified); A: If you want to rename all occurrences of some key you can use a regex with the g option. For example: var json = [{"_id":"1","email":"[email protected]","image":"some_image_url","name":"Name 1"},{"_id":"2","email":"[email protected]","image":"some_image_url","name":"Name 2"}]; str = JSON.stringify(json); now we have the json in string format in str. Replace all occurrences of "_id" to "id" using regex with the g option: str = str.replace(/\"_id\":/g, "\"id\":"); and return to json format: json = JSON.parse(str); now we have our json with the wanted key name. A: Is possible, using typeScript function renameJson(json,oldkey,newkey) { return Object.keys(json).reduce((s,item) => item == oldkey ? ({...s,[newkey]:json[oldkey]}) : ({...s,[item]:json[item]}),{}) } Example: https://codepen.io/lelogualda/pen/BeNwWJ A: If your object looks like this: obj = { "_id":"5078c3a803ff4197dc81fbfb", "email":"[email protected]", "image":"some_image_url", "name":"Name 1" } Probably the simplest method in JavaScript is: obj.id = obj._id del object['_id'] As a result, you will get: obj = { "id":"5078c3a803ff4197dc81fbfb", "email":"[email protected]", "image":"some_image_url", "name":"Name 1" } A: By using map function you can do that. Please refer below code. var userDetails = [{ "_id":"5078c3a803ff4197dc81fbfb", "email":"[email protected]", "image":"some_image_url", "name":"Name 1" },{ "_id":"5078c3a803ff4197dc81fbfc", "email":"[email protected]", "image":"some_image_url", "name":"Name 2" }]; var formattedUserDetails = userDetails.map(({ _id:id, email, image, name }) => ({ id, email, image, name })); console.log(formattedUserDetails); A: If anyone needs to do this dynamically: const keys = Object.keys(jsonObject); keys.forEach((key) => { // CREATE A NEW KEY HERE var newKey = key.replace(' ', '_'); jsonObject[newKey] = jsonObject[key]; delete jsonObject[key]; }); jsonObject will now have the new keys. IMPORTANT: If your key is not changed by the replace function, it will just take it out of the array. You may want to put some if statements in there. A: If you want replace the key of JSON object, use below logic const student= { "key": "b9ed-9c1a04247482", "name": "Devaraju", "DOB" : "01/02/2000", "score" : "A+" } let {key, ...new_student} = {...student} new_student.id= key console.log(new_student) A: To update oldKey with a newKey in a nested json at any deeper level. function transformKeys(object, newKey, oldKey) { if(Array.isArray(object)){ object.map((item) => { transformKeys(item, newKey, oldKey) }) } if(typeof object === 'object' && !Array.isArray(object)){ Object.keys(object).forEach(key => { if (typeof object[key] === 'object') { transformKeys(object[key], newKey, oldKey) } if (key === oldKey) { object[newKey] = object[key] delete object[key] } }) } } A: My answer works for nested json like this, [ { "id": 1, "name": "1111111111", "children": [ { "id": 2, "name": "2222", } ] }, { "id": 3, "name": "1", }, ] I want replace key 'id' to 'value', and 'name' to 'label' for select componet. Function: function renameKeyInJson(json, keys) { let dataStr = JSON.stringify(json); keys.forEach(e => { dataStr = dataStr.replace(new RegExp(`"${e.oldKey}":`, "g"), `"${e.newKey}":`); }); return JSON.parse(dataStr); } Usage: const response = await getAll(bookId); return renameKeyInJson(response.data, [ {oldKey: 'name', newKey: 'label'}, {oldKey: 'id', newKey: 'value'}, ]);
How to rename JSON key
I have a JSON object with the following content: [ { "_id":"5078c3a803ff4197dc81fbfb", "email":"[email protected]", "image":"some_image_url", "name":"Name 1" }, { "_id":"5078c3a803ff4197dc81fbfc", "email":"[email protected]", "image":"some_image_url", "name":"Name 2" } ] I want to change the "_id" key to "id" so it would become [ { "id":"5078c3a803ff4197dc81fbfb", "email":"[email protected]", "image":"some_image_url", "name":"Name 1" }, { "id":"5078c3a803ff4197dc81fbfc", "email":"[email protected]", "image":"some_image_url", "name":"Name 2" } ] How would I do that either with Javascript, jQuery or Ruby, Rails? Thanks.
[ "\nParse the JSON\n\nconst arr = JSON.parse(json);\n\n\nFor each object in the JSON, rename the key:\n\nobj.id = obj._id;\ndelete obj._id;\n\n\nStringify the result\n\nAll together:\n\n\nfunction renameKey ( obj, oldKey, newKey ) {\n obj[newKey] = obj[oldKey];\n delete obj[oldKey];\n}\n\nconst json = `\n [\n {\n \"_id\":\"5078c3a803ff4197dc81fbfb\",\n \"email\":\"[email protected]\",\n \"image\":\"some_image_url\",\n \"name\":\"Name 1\"\n },\n {\n \"_id\":\"5078c3a803ff4197dc81fbfc\",\n \"email\":\"[email protected]\",\n \"image\":\"some_image_url\",\n \"name\":\"Name 2\"\n }\n ]\n`;\n \nconst arr = JSON.parse(json);\narr.forEach( obj => renameKey( obj, '_id', 'id' ) );\nconst updatedJson = JSON.stringify( arr );\n\nconsole.log( updatedJson );\n\n\n\n", "In this case it would be easiest to use string replace. Serializing the JSON won't work well because _id will become the property name of the object and changing a property name is no simple task (at least not in most langauges, it's not so bad in javascript). Instead just do;\njsonString = jsonString.replace(\"\\\"_id\\\":\", \"\\\"id\\\":\");\n\n", "As mentioned by evanmcdonnal, the easiest solution is to process this as string instead of JSON,\n\n\nvar json = [{\"_id\":\"5078c3a803ff4197dc81fbfb\",\"email\":\"[email protected]\",\"image\":\"some_image_url\",\"name\":\"Name 1\"},{\"_id\":\"5078c3a803ff4197dc81fbfc\",\"email\":\"[email protected]\",\"image\":\"some_image_url\",\"name\":\"Name 2\"}];\r\n \r\njson = JSON.parse(JSON.stringify(json).split('\"_id\":').join('\"id\":'));\r\n\r\ndocument.write(JSON.stringify(json));\n\n\n\nThis will convert given JSON data to string and replace \"_id\" to \"id\" then converting it back to the required JSON format. But I used split and join instead of replace, because replace will replace only the first occurrence of the string.\n", "JSON.parse has two parameters. The second parameter, reviver, is a transform function that can format the output format we want. See ECMA specification here.\nIn reviver function:\n\nif we return undefined, the original property will be deleted.\nthis is the object containing the property being processed as this function, and the property name as a string, the property value as arguments of this function.\n\nconst json = '[{\"_id\":\"5078c3a803ff4197dc81fbfb\",\"email\":\"[email protected]\",\"image\":\"some_image_url\",\"name\":\"Name 1\"},{\"_id\":\"5078c3a803ff4197dc81fbfc\",\"email\":\"[email protected]\",\"image\":\"some_image_url\",\"name\":\"Name 2\"}]';\n\nconst obj = JSON.parse(json, function(k, v) {\n if (k === \"_id\") {\n this.id = v;\n return; // if return undefined, orignal property will be removed\n }\n return v;\n});\n\nconst res = JSON.stringify(obj);\nconsole.log(res)\n\noutput:\n[{\"email\":\"[email protected]\",\"image\":\"some_image_url\",\"name\":\"Name 1\",\"id\":\"5078c3a803ff4197dc81fbfb\"},{\"email\":\"[email protected]\",\"image\":\"some_image_url\",\"name\":\"Name 2\",\"id\":\"5078c3a803ff4197dc81fbfc\"}]\n\n", "Try this:\nlet jsonArr = [\n {\n \"_id\":\"5078c3a803ff4197dc81fbfb\",\n \"email\":\"[email protected]\",\n \"image\":\"some_image_url\",\n \"name\":\"Name 1\"\n },\n {\n \"_id\":\"5078c3a803ff4197dc81fbfc\",\n \"email\":\"[email protected]\",\n \"image\":\"some_image_url\",\n \"name\":\"Name 2\"\n }\n]\n\nlet idModified = jsonArr.map(\n obj => {\n return {\n \"id\" : obj._id,\n \"email\":obj.email,\n \"image\":obj.image,\n \"name\":obj.name\n }\n }\n);\nconsole.log(idModified);\n\n", "If you want to rename all occurrences of some key you can use a regex with the g option. For example:\nvar json = [{\"_id\":\"1\",\"email\":\"[email protected]\",\"image\":\"some_image_url\",\"name\":\"Name 1\"},{\"_id\":\"2\",\"email\":\"[email protected]\",\"image\":\"some_image_url\",\"name\":\"Name 2\"}];\n\nstr = JSON.stringify(json);\n\nnow we have the json in string format in str.\nReplace all occurrences of \"_id\" to \"id\" using regex with the g option:\nstr = str.replace(/\\\"_id\\\":/g, \"\\\"id\\\":\");\n\nand return to json format:\njson = JSON.parse(str);\n\nnow we have our json with the wanted key name.\n", "Is possible, using typeScript\nfunction renameJson(json,oldkey,newkey) { \n return Object.keys(json).reduce((s,item) => \n item == oldkey ? ({...s,[newkey]:json[oldkey]}) : ({...s,[item]:json[item]}),{}) \n}\n\nExample: https://codepen.io/lelogualda/pen/BeNwWJ\n", "If your object looks like this:\nobj = {\n \"_id\":\"5078c3a803ff4197dc81fbfb\",\n \"email\":\"[email protected]\",\n \"image\":\"some_image_url\",\n \"name\":\"Name 1\"\n }\n\nProbably the simplest method in JavaScript is:\nobj.id = obj._id\ndel object['_id']\n\nAs a result, you will get:\nobj = {\n \"id\":\"5078c3a803ff4197dc81fbfb\",\n \"email\":\"[email protected]\",\n \"image\":\"some_image_url\",\n \"name\":\"Name 1\"\n }\n\n", "By using map function you can do that. \nPlease refer below code.\nvar userDetails = [{\n \"_id\":\"5078c3a803ff4197dc81fbfb\",\n \"email\":\"[email protected]\",\n \"image\":\"some_image_url\",\n \"name\":\"Name 1\"\n},{\n \"_id\":\"5078c3a803ff4197dc81fbfc\",\n \"email\":\"[email protected]\",\n \"image\":\"some_image_url\",\n \"name\":\"Name 2\"\n}];\n\nvar formattedUserDetails = userDetails.map(({ _id:id, email, image, name }) => ({\n id,\n email,\n image,\n name\n}));\nconsole.log(formattedUserDetails);\n\n", "If anyone needs to do this dynamically:\nconst keys = Object.keys(jsonObject);\n\nkeys.forEach((key) => {\n\n // CREATE A NEW KEY HERE\n var newKey = key.replace(' ', '_');\n\n jsonObject[newKey] = jsonObject[key];\n delete jsonObject[key];\n });\n\njsonObject will now have the new keys.\nIMPORTANT:\nIf your key is not changed by the replace function, it will just take it out of the array. You may want to put some if statements in there.\n", "If you want replace the key of JSON object, use below logic\n\n\nconst student= {\n \"key\": \"b9ed-9c1a04247482\",\n \"name\": \"Devaraju\",\n \"DOB\" : \"01/02/2000\",\n \"score\" : \"A+\"\n}\nlet {key, ...new_student} = {...student}\nnew_student.id= key\n\nconsole.log(new_student)\n\n\n\n", "To update oldKey with a newKey in a nested json at any deeper level.\nfunction transformKeys(object, newKey, oldKey) {\n if(Array.isArray(object)){\n object.map((item) => {\n transformKeys(item, newKey, oldKey)\n })\n }\n if(typeof object === 'object' && !Array.isArray(object)){\n Object.keys(object).forEach(key => {\n if (typeof object[key] === 'object') {\n transformKeys(object[key], newKey, oldKey)\n }\n if (key === oldKey) {\n object[newKey] = object[key]\n delete object[key]\n }\n })\n }\n}\n\n", "My answer works for nested json like this,\n\n[\n {\n \"id\": 1,\n \"name\": \"1111111111\",\n \"children\": [\n {\n \"id\": 2,\n \"name\": \"2222\",\n }\n ]\n },\n {\n \"id\": 3,\n \"name\": \"1\",\n },\n]\n\nI want replace key 'id' to 'value', and 'name' to 'label' for select componet.\nFunction:\nfunction renameKeyInJson(json, keys) {\n let dataStr = JSON.stringify(json);\n keys.forEach(e => {\n dataStr = dataStr.replace(new RegExp(`\"${e.oldKey}\":`, \"g\"), `\"${e.newKey}\":`);\n });\n return JSON.parse(dataStr);\n}\n\nUsage:\nconst response = await getAll(bookId);\nreturn renameKeyInJson(response.data, [\n {oldKey: 'name', newKey: 'label'},\n {oldKey: 'id', newKey: 'value'},\n]);\n\n" ]
[ 109, 30, 24, 17, 12, 8, 3, 2, 2, 1, 0, 0, 0 ]
[ "If you want to do it dynamically, for example, you have an array which you want to apply as a key to JSON object:\nyour Array will be like : \nvar keys = [\"id\", \"name\",\"Address\",\"Phone\"] // The array size should be same as JSON Object keys size\n\nNow you have a JSON Array like: \nvar jArray = [\n {\n \"_id\": 1,\n \"_name\": \"Asna\",\n \"Address\": \"NY\",\n \"Phone\": 123\n },\n {\n \"_id\": 2,\n \"_name\": \"Euphoria\",\n \"Address\": \"Monaco\",\n \"Phone\": 124\n },\n {\n \"_id\": 3,\n \"_name\": \"Ahmed\",\n \"Address\": \"Mumbai\",\n \"Phone\": 125\n }\n]\n\n$.each(jArray ,function(pos,obj){\n var counter = 0;\n $.each(obj,function(key,value){\n jArray [pos][keys[counter]] = value;\n delete jArray [pos][key];\n counter++;\n }) \n})\n\nYour resultant JSON Array will be like : \n[\n {\n \"id\": 1,\n \"name\": \"Asna\",\n \"Address\": \"NY\",\n \"Phone\": 123\n },\n {\n \"id\": 2,\n \"name\": \"Euphoria\",\n \"Address\": \"Monaco\",\n \"Phone\": 124\n },\n {\n \"id\": 3,\n \"name\": \"Ahmed\",\n \"Address\": \"Mumbai\",\n \"Phone\": 125\n }\n]\n\n", "For a more flexible solution for renaming a key in an object,\nUsage:\njsondata = renameKey(jsondata,\"_id\",\"id\");\n\nFunction:\nfunction renameKey(data,oldname,newname)\n{\n for (let i = 0; i < data.length; i++) {\n let element = data[i];\n element[newname] = element[oldname];\n delete element[oldname];\n }\n return data;\n}\n\nif you need the keys to stay in the same order (like i did) here is a messy solution that I'm sure is poorly optimized.\nfunction renameKey(data,oldname,newname)\n{\n for (let i = 0; i < data.length; i++)\n {\n let element = data[i];\n let info = Object.keys(data[i]);\n\n for (let ii = 0; ii < info.length; ii++)\n {\n\n let key = info[ii];\n if (key !== oldname)\n {\n let skey = key + \"~\"; //make temporary key\n element[skey] = element[key]; //copy values to temp key\n delete element[key]; //delete old key\n element[key] = element[skey]; //copy key back to orginal name, preserving its position.\n delete element[skey]; //delete temp key\n }\n else\n {\n element[newname] = element[key];\n delete element[key];\n }\n }\n }\n return data;\n}\n\n" ]
[ -1, -1 ]
[ "json" ]
stackoverflow_0013391579_json.txt
Q: How to add new service/bounded context to already running system? Lets say I have two bounded contexts Project and Budgets. When project adds new member it is publishing MemberAdded event. Budgets listen to this events and it creates local version of Member entity - it just holds what it needs. This will work fine if both services are deployed at the same time. Lets say I use kafka. These MemberAdded events will be stored for example for next 7 days and then kafka deletes them. What if later I need to add new service for example Orders that also need replicated version of Member entity - Customer. I would need to start listening for MemberAdded events but I would still not have old data. How you can handle this case? The only solution I can think of is to use persistent event store that I can query for all events and from this I could restore all data required for new service. A: You have two options: Use a persistent event store and store all events ever generated. This can be thought of a pull system, where new services (or even old services) can fetch data as and when they need it. Regenerate events from the source system on the fly (Project) and target them to specific services (using a particular pub-sub or message channel, for example). This can be considered a push system, where you must trigger republishing of old events whenever another part of the system needs to access data from another service. Needless to say, the former is much more efficient and is a one-time effort to gather all events at a central location than the latter, which needs you to do some work whenever a new service (or old service) needs to access/process data from another service. Extending the thought process, the central event store can also double up as a source of truth and help in audits, reporting, and debugging if made immutable (like in the event sourcing pattern).
How to add new service/bounded context to already running system?
Lets say I have two bounded contexts Project and Budgets. When project adds new member it is publishing MemberAdded event. Budgets listen to this events and it creates local version of Member entity - it just holds what it needs. This will work fine if both services are deployed at the same time. Lets say I use kafka. These MemberAdded events will be stored for example for next 7 days and then kafka deletes them. What if later I need to add new service for example Orders that also need replicated version of Member entity - Customer. I would need to start listening for MemberAdded events but I would still not have old data. How you can handle this case? The only solution I can think of is to use persistent event store that I can query for all events and from this I could restore all data required for new service.
[ "You have two options:\n\nUse a persistent event store and store all events ever generated. This can be thought of a pull system, where new services (or even old services) can fetch data as and when they need it.\nRegenerate events from the source system on the fly (Project) and target them to specific services (using a particular pub-sub or message channel, for example). This can be considered a push system, where you must trigger republishing of old events whenever another part of the system needs to access data from another service.\n\nNeedless to say, the former is much more efficient and is a one-time effort to gather all events at a central location than the latter, which needs you to do some work whenever a new service (or old service) needs to access/process data from another service.\nExtending the thought process, the central event store can also double up as a source of truth and help in audits, reporting, and debugging if made immutable (like in the event sourcing pattern).\n" ]
[ 1 ]
[]
[]
[ "cqrs", "domain_driven_design", "event_sourcing" ]
stackoverflow_0074668181_cqrs_domain_driven_design_event_sourcing.txt
Q: SPSS equivalent to Excel IFS statement I am wondering how can I have it so that if the value in one column is 1, the value in this column is 5, and if the value is 0 the value in this column is 10. With what I've seen I am only able to have it so that if the value in one column is 1 the value in this column is 5, and if the value is anything else the cell in this column is blank. A: This will do it (and yes, so much easier than ifs :) - recode thiscolumn (1=5)(0=10) into thatcolumn.
SPSS equivalent to Excel IFS statement
I am wondering how can I have it so that if the value in one column is 1, the value in this column is 5, and if the value is 0 the value in this column is 10. With what I've seen I am only able to have it so that if the value in one column is 1 the value in this column is 5, and if the value is anything else the cell in this column is blank.
[ "This will do it (and yes, so much easier than ifs :) -\nrecode thiscolumn (1=5)(0=10) into thatcolumn.\n\n" ]
[ 0 ]
[]
[]
[ "function", "spss" ]
stackoverflow_0074659334_function_spss.txt
Q: Rails 7 session_id cookie different from sessions table I'm using active_record_store for sessions: session_store.rb: Rails.application.config.session_store :active_record_store I have code for reading/parsing the session data for logging purposes. When the user logs into the ui, I get a new record in the sessions table, with a session_id like: 2::cbd180f1b721cc89d70e417661cf43c83f34d1c967a76daf14ca77db094a423a But in my controller, when I look at cookies['_session_id'], I get: eac9bd2420e0f5dbdfc22654df3b78dc What is causing the discrepancy? A: For anyone who runs into this, I found the answer in the rack gem, file lib/rack/session/abstract/id.rb. The code refers to a public session id, which is the one in the cookie. The private session id is: "2::#{Digest::SHA256.hexdigest(public_session_id)}"
Rails 7 session_id cookie different from sessions table
I'm using active_record_store for sessions: session_store.rb: Rails.application.config.session_store :active_record_store I have code for reading/parsing the session data for logging purposes. When the user logs into the ui, I get a new record in the sessions table, with a session_id like: 2::cbd180f1b721cc89d70e417661cf43c83f34d1c967a76daf14ca77db094a423a But in my controller, when I look at cookies['_session_id'], I get: eac9bd2420e0f5dbdfc22654df3b78dc What is causing the discrepancy?
[ "For anyone who runs into this, I found the answer in the rack gem, file lib/rack/session/abstract/id.rb.\nThe code refers to a public session id, which is the one in the cookie.\nThe private session id is:\n\"2::#{Digest::SHA256.hexdigest(public_session_id)}\"\n\n" ]
[ 0 ]
[]
[]
[ "ruby_on_rails" ]
stackoverflow_0074322892_ruby_on_rails.txt
Q: Client side compression with HTML5 and Javascript Am working on a web application and we allow users to upload files to our server. Am trying to do client side compression before uploading files to the server. What would be the better way to achieve this using HTML5 and JavaScript. Thanks. A: The common mechanism to do what you want is using FileReader and a JavaScript client-side compression library (i.e. compressjs). A: In 2022 it's almost too simple, if the browser supports CompressionStream, FormData and Response. In the example below I use FormData to collect all the fields from the form. Then I use the readable stream from the file, and pipe it though the compression stream. Then I use Response to read everything from the compressed stream and return it in a blob. async function compress(file, encoding = 'gzip') { try { return { data: await new Response(file.stream().pipeThrough(new CompressionStream(encoding)), { headers: { 'Content-Type': file.type }, }).blob(), encoding, }; } catch (error) { // If error, return the file uncompressed console.error(error.message); return { data: file, encoding: null }; } } theForm.addEventListener( 'submit', (event) => event.preventDefault() ) theForm.addEventListener( 'input', async function(event) { // collect all fields const fd = new FormData(theForm); // Get 'file handle' from imput elemen const file = fd.get('theFile'); if (!file) return const encoding = fd.get('theEncoding'); const compressed = await compress(file, encoding); theMessage.value = [ 'Compressed with', compressed.encoding, 'Source file was', file.size, 'bytes', 'and the compressed file', compressed.data.size, 'saving', ((1 - compressed.data.size / file.size) * 100) .toFixed(0), '%.' ].join(' ') } ) form>* { display: block; width: 100%; } <form id="theForm"> <select name="theEncoding"> <option>gzip</option> <option>deflate</option> <option>deflate-raw</option> </select> <input type="file" name="theFile" id="theFile"> </form> <output id="theMessage"></output>
Client side compression with HTML5 and Javascript
Am working on a web application and we allow users to upload files to our server. Am trying to do client side compression before uploading files to the server. What would be the better way to achieve this using HTML5 and JavaScript. Thanks.
[ "The common mechanism to do what you want is using FileReader and a JavaScript client-side compression library (i.e. compressjs).\n", "In 2022 it's almost too simple, if the browser supports CompressionStream, FormData and Response.\nIn the example below I use FormData to collect all the fields from the form.\nThen I use the readable stream from the file, and pipe it though the compression stream. Then I use Response to read everything from the compressed stream and return it in a blob.\n\n\nasync function compress(file, encoding = 'gzip') {\n try {\n return {\n data: await new Response(file.stream().pipeThrough(new CompressionStream(encoding)), {\n headers: {\n 'Content-Type': file.type\n },\n }).blob(),\n encoding,\n };\n } catch (error) {\n // If error, return the file uncompressed\n console.error(error.message);\n return {\n data: file,\n encoding: null\n };\n }\n}\n\ntheForm.addEventListener(\n 'submit',\n (event) => event.preventDefault()\n)\n\ntheForm.addEventListener(\n 'input',\n async function(event) {\n // collect all fields\n const fd = new FormData(theForm);\n\n // Get 'file handle' from imput elemen\n const file = fd.get('theFile');\n if (!file) return\n\n const encoding = fd.get('theEncoding');\n const compressed = await compress(file, encoding);\n\n theMessage.value = [\n 'Compressed with', compressed.encoding,\n 'Source file was', file.size, 'bytes',\n 'and the compressed file', compressed.data.size,\n 'saving', ((1 - compressed.data.size / file.size) * 100)\n .toFixed(0),\n '%.'\n ].join(' ')\n }\n)\nform>* {\n display: block;\n width: 100%;\n}\n<form id=\"theForm\">\n <select name=\"theEncoding\">\n <option>gzip</option>\n <option>deflate</option>\n <option>deflate-raw</option>\n </select>\n <input type=\"file\" name=\"theFile\" id=\"theFile\">\n\n</form>\n<output id=\"theMessage\"></output>\n\n\n\n" ]
[ 2, 0 ]
[]
[]
[ "asp.net", "html", "javascript" ]
stackoverflow_0007151467_asp.net_html_javascript.txt
Q: Useragent string doesn't contain browser name I've been seeing a lot of this useragent in my logs from a webapp: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/605.1.15 (KHTML, like Gecko) . As the user agent doesn't contain any browser name, is there a way to tell what browser and version user was using? Also, does anyone know what this user agent is? The operating system seems to be macOS X 10.13.6, but beyond that, there is no information on what the browser is. A: The user agent string Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/605.1.15 (KHTML, like Gecko)indicates that the user was using a browser that is based on the WebKit engine and the KHTML layout engine. This user agent string does not contain any information about the specific browser or version, so it is not possible to determine the exact browser and version that the user was using.
Useragent string doesn't contain browser name
I've been seeing a lot of this useragent in my logs from a webapp: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/605.1.15 (KHTML, like Gecko) . As the user agent doesn't contain any browser name, is there a way to tell what browser and version user was using? Also, does anyone know what this user agent is? The operating system seems to be macOS X 10.13.6, but beyond that, there is no information on what the browser is.
[ "The user agent string Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/605.1.15 (KHTML, like Gecko)indicates that the user was using a browser that is based on the WebKit engine and the KHTML layout engine. This user agent string does not contain any information about the specific browser or version, so it is not possible to determine the exact browser and version that the user was using.\n" ]
[ 0 ]
[]
[]
[ "browser", "logging", "user_agent" ]
stackoverflow_0074641088_browser_logging_user_agent.txt
Q: error deploying image to kubernetes pod: "http: server gave HTTP response to HTTPS client" i've got a kubernetes node, control-plane, which is untainted for deploying pods to. i've got a docker image sdmay23-42.ece.iastate.edu:5000/canvas-lti-frontend:v2. i'm signed into docker cli. the daemon.json is set with insecure registry and i can verify with docker info : Docker Root Dir: /var/lib/docker Debug Mode: false Username: sdmay2342 Registry: https://index.docker.io/v1/ Labels: Experimental: false Insecure Registries: sdmay23-42.ece.iastate.edu:5000 127.0.0.0/8 Live Restore Enabled: false i can pull the image: Status: Image is up to date for sdmay23-42.ece.iastate.edu:5000/canvas-lti-frontend:v2 sdmay23-42.ece.iastate.edu:5000/canvas-lti-frontend:v2 i can build a container from the image: CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES ad582a4d514b sdmay23-42.ece.iastate.edu:5000/canvas-lti-frontend:v2 "docker-entrypoint.s…" 6 seconds ago Up 6 seconds 3000/tcp test-frontend when i deploy it to the node from yaml manifest, i get an error. basic manifest: apiVersion: v1 kind: Pod metadata: name: test-pod spec: containers: - name: test-container image: sdmay23-42.ece.iastate.edu:5000/canvas-lti-frontend:v2 ports: - containerPort: 6379 command: sudo kubectl create -f test-deploy.yaml response: pod/test-pod created the description of the pod: Name: test-pod Namespace: default Priority: 0 Service Account: default Node: sdmay23-42/10.29.160.55 Start Time: Sun, 27 Nov 2022 18:46:54 +0000 Labels: <none> Annotations: <none> Status: Pending IP: 10.244.0.116 IPs: IP: 10.244.0.116 Containers: test-container: Container ID: Image: sdmay23-42.ece.iastate.edu:5000/canvas-lti-frontend:v2 Image ID: Port: 6379/TCP Host Port: 0/TCP State: Waiting Reason: ImagePullBackOff Ready: False Restart Count: 0 Environment: <none> Mounts: /var/run/secrets/kubernetes.io/serviceaccount from kube-api-access-bvwzz (ro) Conditions: Type Status Initialized True Ready False ContainersReady False PodScheduled True Volumes: kube-api-access-bvwzz: Type: Projected (a volume that contains injected data from multiple sources) TokenExpirationSeconds: 3607 ConfigMapName: kube-root-ca.crt ConfigMapOptional: <nil> DownwardAPI: true QoS Class: BestEffort Node-Selectors: <none> Tolerations: node.kubernetes.io/not-ready:NoExecute op=Exists for 300s node.kubernetes.io/unreachable:NoExecute op=Exists for 300s Events: Type Reason Age From Message ---- ------ ---- ---- ------- Normal Scheduled 51s default-scheduler Successfully assigned default/test-pod to sdmay23-42 Normal BackOff 23s (x2 over 50s) kubelet Back-off pulling image "sdmay23-42.ece.iastate.edu:5000/canvas-lti-frontend:v2" Warning Failed 23s (x2 over 50s) kubelet Error: ImagePullBackOff Normal Pulling 12s (x3 over 50s) kubelet Pulling image "sdmay23-42.ece.iastate.edu:5000/canvas-lti-frontend:v2" Warning Failed 12s (x3 over 50s) kubelet Failed to pull image "sdmay23-42.ece.iastate.edu:5000/canvas-lti-frontend:v2": rpc error: code = Unknown desc = failed to pull and unpack image "sdmay23-42.ece.iastate.edu:5000/canvas-lti-frontend:v2": failed to resolve reference "sdmay23-42.ece.iastate.edu:5000/canvas-lti-frontend:v2": failed to do request: Head "https://sdmay23-42.ece.iastate.edu:5000/v2/canvas-lti-frontend/manifests/v2": http: server gave HTTP response to HTTPS client Warning Failed 12s (x3 over 50s) kubelet Error: ErrImagePull A: the solution was to configure containerd to accept insecure registries. i had thought kubernetes was using docker. you can do kubectl get nodes -o wide to see information about container runtime. steps for configuring containrd here: How to pull docker image from a insecure private registry with latest Kubernetes.
error deploying image to kubernetes pod: "http: server gave HTTP response to HTTPS client"
i've got a kubernetes node, control-plane, which is untainted for deploying pods to. i've got a docker image sdmay23-42.ece.iastate.edu:5000/canvas-lti-frontend:v2. i'm signed into docker cli. the daemon.json is set with insecure registry and i can verify with docker info : Docker Root Dir: /var/lib/docker Debug Mode: false Username: sdmay2342 Registry: https://index.docker.io/v1/ Labels: Experimental: false Insecure Registries: sdmay23-42.ece.iastate.edu:5000 127.0.0.0/8 Live Restore Enabled: false i can pull the image: Status: Image is up to date for sdmay23-42.ece.iastate.edu:5000/canvas-lti-frontend:v2 sdmay23-42.ece.iastate.edu:5000/canvas-lti-frontend:v2 i can build a container from the image: CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES ad582a4d514b sdmay23-42.ece.iastate.edu:5000/canvas-lti-frontend:v2 "docker-entrypoint.s…" 6 seconds ago Up 6 seconds 3000/tcp test-frontend when i deploy it to the node from yaml manifest, i get an error. basic manifest: apiVersion: v1 kind: Pod metadata: name: test-pod spec: containers: - name: test-container image: sdmay23-42.ece.iastate.edu:5000/canvas-lti-frontend:v2 ports: - containerPort: 6379 command: sudo kubectl create -f test-deploy.yaml response: pod/test-pod created the description of the pod: Name: test-pod Namespace: default Priority: 0 Service Account: default Node: sdmay23-42/10.29.160.55 Start Time: Sun, 27 Nov 2022 18:46:54 +0000 Labels: <none> Annotations: <none> Status: Pending IP: 10.244.0.116 IPs: IP: 10.244.0.116 Containers: test-container: Container ID: Image: sdmay23-42.ece.iastate.edu:5000/canvas-lti-frontend:v2 Image ID: Port: 6379/TCP Host Port: 0/TCP State: Waiting Reason: ImagePullBackOff Ready: False Restart Count: 0 Environment: <none> Mounts: /var/run/secrets/kubernetes.io/serviceaccount from kube-api-access-bvwzz (ro) Conditions: Type Status Initialized True Ready False ContainersReady False PodScheduled True Volumes: kube-api-access-bvwzz: Type: Projected (a volume that contains injected data from multiple sources) TokenExpirationSeconds: 3607 ConfigMapName: kube-root-ca.crt ConfigMapOptional: <nil> DownwardAPI: true QoS Class: BestEffort Node-Selectors: <none> Tolerations: node.kubernetes.io/not-ready:NoExecute op=Exists for 300s node.kubernetes.io/unreachable:NoExecute op=Exists for 300s Events: Type Reason Age From Message ---- ------ ---- ---- ------- Normal Scheduled 51s default-scheduler Successfully assigned default/test-pod to sdmay23-42 Normal BackOff 23s (x2 over 50s) kubelet Back-off pulling image "sdmay23-42.ece.iastate.edu:5000/canvas-lti-frontend:v2" Warning Failed 23s (x2 over 50s) kubelet Error: ImagePullBackOff Normal Pulling 12s (x3 over 50s) kubelet Pulling image "sdmay23-42.ece.iastate.edu:5000/canvas-lti-frontend:v2" Warning Failed 12s (x3 over 50s) kubelet Failed to pull image "sdmay23-42.ece.iastate.edu:5000/canvas-lti-frontend:v2": rpc error: code = Unknown desc = failed to pull and unpack image "sdmay23-42.ece.iastate.edu:5000/canvas-lti-frontend:v2": failed to resolve reference "sdmay23-42.ece.iastate.edu:5000/canvas-lti-frontend:v2": failed to do request: Head "https://sdmay23-42.ece.iastate.edu:5000/v2/canvas-lti-frontend/manifests/v2": http: server gave HTTP response to HTTPS client Warning Failed 12s (x3 over 50s) kubelet Error: ErrImagePull
[ "the solution was to configure containerd to accept insecure registries. i had thought kubernetes was using docker. you can do kubectl get nodes -o wide to see information about container runtime.\nsteps for configuring containrd here: How to pull docker image from a insecure private registry with latest Kubernetes.\n" ]
[ 1 ]
[]
[]
[ "deployment", "docker", "image", "kubernetes", "kubernetes_pod" ]
stackoverflow_0074592879_deployment_docker_image_kubernetes_kubernetes_pod.txt
Q: Getting a null when returning a Generic.List in a unit test, from in-memory data I've added some unit tests to an ASP.NET MVC app I've written using .NET 6. I'm using an in-memory database for the unit tests. One of the unit tests fails with the following error: Xunit.Sdk.IsAssignableFromException HResult=0x80131500 Message=Assert.IsAssignableFrom() Failure Expected: typeof(System.Collections.Generic.List<PharmacyWarehouseV2.Models.SiteToSite>) Actual: (null) Source=xunit.assert StackTrace: at Xunit.Assert.IsAssignableFrom(Type expectedType, Object object) at Xunit.Assert.IsAssignableFrom[T](Object object) at PharmacyWarehouseV2.Test.SiteToSiteControllerTest.IndexTest() in D:\Repos\PW\PharmacyWarehouseV2\PharmacyWarehouseV2.Test\SiteToSiteControllerTest.cs:line 29 The strange thing is I've got another unit test I wrote in the same way, which works fine. Here is the code for the in-memory data I'm using with Moq (note: the SiteToSite class is large, so I'll be removing most of the properties for brevity's sake. The only properties which are required are the first two): public static IEnumerable<SiteToSite?> GetSiteToSites() { // Construct some SiteToSites first var siteToSites = new List<SiteToSite>() { new SiteToSite() { SiteToSiteID = 1, DateReceived = new DateTime(2020, 7, 1), OrderedByName = "John Doe", OrderedByID = 1, // other properties removed for brevity }, new SiteToSite() { SiteToSiteID = 2, DateReceived = new DateTime(2021, 3, 1), OrderedByName = "Teresa", OrderedByID = 2, // other properties removed for brevity } }; // Now construct SiteToSiteItems var ss1 = new SiteToSiteItem() { SiteToSiteItemID = 1, SiteToSiteID = 1, ProgramName = "Program One", Notes = "First note" }; var ss2 = new SiteToSiteItem() { SiteToSiteItemID = 2, SiteToSiteID = 2, ProgramName = "Program Two", Notes = "Second note" }; var ss3 = new SiteToSiteItem() { SiteToSiteItemID = 3, SiteToSiteID = 2, ProgramName = "Program Two", Notes = "Third note" }; // Now assing SiteToSiteItems to their parent SiteToSites siteToSites[0].SiteToSiteItems = new List<SiteToSiteItem>() { ss1 }; siteToSites[1].SiteToSiteItems = new List<SiteToSiteItem>() { ss2, ss3 }; return siteToSites; } I use a service/repository class. This is the method that is used in the unit test: public IEnumerable<SiteToSite?> GetAll() { var tmp = _context.SiteToSite.OrderBy(s => s.SiteToSiteID); return tmp; } And here's the unit test that's failing: [Fact] public void IndexTest() { // arrange var mockRepo = new Mock<ISiteToSiteService>(); mockRepo.Setup(m => m.GetAll()).Returns(SiteToSiteMockData.GetSiteToSites()); var emptyDbContext = new PharmacyDBContext(); //won't test the AJAX calls var controller = new SiteToSiteController(emptyDbContext, mockRepo.Object); // act var result = controller.Index(); // assert Assert.NotNull(result); var viewResult = Assert.IsType<ViewResult>(result); Assert.True(viewResult.ViewData.Count > 0, "viewResult does not have any records, as it should"); var viewResultSites = Assert.IsAssignableFrom<List<SiteToSite>>(viewResult.ViewData.Model); if (viewResultSites.Count > 0) { // NOTE: I do not like this; it violates unit testing. Assert.Equal(2, viewResultSites.Count); Assert.Equal("John Doe", viewResultSites[0]?.OrderedByName); } } When I debug the test, after the result variable is assigned in the "act" step, it does have the data from in-memory. However, the viewResult.ViewData.Model is null. I don't understand how result has data, but viewResult.ViewData.Model doesn't. I've gone to the xUnit repo on GitHub to look at the documentation, but it wasn't clear to me what the problem is. What might be causing the discrepancy? Addendum 1 Here's the GetAll() method from the SiteToSiteService: public IEnumerable<SiteToSite?> GetAll() { var tmp = _context.SiteToSite.OrderBy(s => s.SiteToSiteID); return tmp; } And here's the Index() method from the controller: public IActionResult Index() { return View(); } A: (Posting answer on behalf of the question author, to move it to the answer space). After Peter's question I realized I made a mistake. The Index action method didn't pass any data into the view. This is what was giving me a null. (For business reasons we don't show a list of site-to-sites.) So, I've put an xUnit [Fact(Skip = "<message>")] into the unit test for the IndexTest. However, I do have a DetailTest unit test. Here's the code for the DetailTest: [Fact] public void DetailsTest() { // arrange var mockRepo = new Mock<ISiteToSiteService>(); mockRepo.Setup(m => m.Get(1)).Returns(SiteToSiteMockData.Get(1)); var controller = new SiteToSiteController(new PharmacyDBContext(), mockRepo.Object); // act var result = controller.GetSiteToSiteById(1); // assert var viewResult = Assert.IsType<ViewResult>(result); var viewResultSiteToSite = Assert.IsAssignableFrom<SiteToSite>(viewResult.ViewData.Model); Assert.Equal("John Doe", viewResultSiteToSite.OrderedByName); } Here's the action method from the controller: public ActionResult GetSiteToSiteById(int id) { var site2Site = siteToSiteService.Get(id); if (site2Site == null) { return NotFound(); } return View("SiteToSiteDetail", site2Site); } and here's the Get(int id) method from the service/repository method: public SiteToSite? Get(int id) { var result = _context.SiteToSite.Include(i => i.SiteToSiteItems).Where(s => s.SiteToSiteID == id); return result.FirstOrDefault(); }
Getting a null when returning a Generic.List in a unit test, from in-memory data
I've added some unit tests to an ASP.NET MVC app I've written using .NET 6. I'm using an in-memory database for the unit tests. One of the unit tests fails with the following error: Xunit.Sdk.IsAssignableFromException HResult=0x80131500 Message=Assert.IsAssignableFrom() Failure Expected: typeof(System.Collections.Generic.List<PharmacyWarehouseV2.Models.SiteToSite>) Actual: (null) Source=xunit.assert StackTrace: at Xunit.Assert.IsAssignableFrom(Type expectedType, Object object) at Xunit.Assert.IsAssignableFrom[T](Object object) at PharmacyWarehouseV2.Test.SiteToSiteControllerTest.IndexTest() in D:\Repos\PW\PharmacyWarehouseV2\PharmacyWarehouseV2.Test\SiteToSiteControllerTest.cs:line 29 The strange thing is I've got another unit test I wrote in the same way, which works fine. Here is the code for the in-memory data I'm using with Moq (note: the SiteToSite class is large, so I'll be removing most of the properties for brevity's sake. The only properties which are required are the first two): public static IEnumerable<SiteToSite?> GetSiteToSites() { // Construct some SiteToSites first var siteToSites = new List<SiteToSite>() { new SiteToSite() { SiteToSiteID = 1, DateReceived = new DateTime(2020, 7, 1), OrderedByName = "John Doe", OrderedByID = 1, // other properties removed for brevity }, new SiteToSite() { SiteToSiteID = 2, DateReceived = new DateTime(2021, 3, 1), OrderedByName = "Teresa", OrderedByID = 2, // other properties removed for brevity } }; // Now construct SiteToSiteItems var ss1 = new SiteToSiteItem() { SiteToSiteItemID = 1, SiteToSiteID = 1, ProgramName = "Program One", Notes = "First note" }; var ss2 = new SiteToSiteItem() { SiteToSiteItemID = 2, SiteToSiteID = 2, ProgramName = "Program Two", Notes = "Second note" }; var ss3 = new SiteToSiteItem() { SiteToSiteItemID = 3, SiteToSiteID = 2, ProgramName = "Program Two", Notes = "Third note" }; // Now assing SiteToSiteItems to their parent SiteToSites siteToSites[0].SiteToSiteItems = new List<SiteToSiteItem>() { ss1 }; siteToSites[1].SiteToSiteItems = new List<SiteToSiteItem>() { ss2, ss3 }; return siteToSites; } I use a service/repository class. This is the method that is used in the unit test: public IEnumerable<SiteToSite?> GetAll() { var tmp = _context.SiteToSite.OrderBy(s => s.SiteToSiteID); return tmp; } And here's the unit test that's failing: [Fact] public void IndexTest() { // arrange var mockRepo = new Mock<ISiteToSiteService>(); mockRepo.Setup(m => m.GetAll()).Returns(SiteToSiteMockData.GetSiteToSites()); var emptyDbContext = new PharmacyDBContext(); //won't test the AJAX calls var controller = new SiteToSiteController(emptyDbContext, mockRepo.Object); // act var result = controller.Index(); // assert Assert.NotNull(result); var viewResult = Assert.IsType<ViewResult>(result); Assert.True(viewResult.ViewData.Count > 0, "viewResult does not have any records, as it should"); var viewResultSites = Assert.IsAssignableFrom<List<SiteToSite>>(viewResult.ViewData.Model); if (viewResultSites.Count > 0) { // NOTE: I do not like this; it violates unit testing. Assert.Equal(2, viewResultSites.Count); Assert.Equal("John Doe", viewResultSites[0]?.OrderedByName); } } When I debug the test, after the result variable is assigned in the "act" step, it does have the data from in-memory. However, the viewResult.ViewData.Model is null. I don't understand how result has data, but viewResult.ViewData.Model doesn't. I've gone to the xUnit repo on GitHub to look at the documentation, but it wasn't clear to me what the problem is. What might be causing the discrepancy? Addendum 1 Here's the GetAll() method from the SiteToSiteService: public IEnumerable<SiteToSite?> GetAll() { var tmp = _context.SiteToSite.OrderBy(s => s.SiteToSiteID); return tmp; } And here's the Index() method from the controller: public IActionResult Index() { return View(); }
[ "(Posting answer on behalf of the question author, to move it to the answer space).\nAfter Peter's question I realized I made a mistake. The Index action method didn't pass any data into the view. This is what was giving me a null. (For business reasons we don't show a list of site-to-sites.) So, I've put an xUnit [Fact(Skip = \"<message>\")] into the unit test for the IndexTest.\nHowever, I do have a DetailTest unit test. Here's the code for the DetailTest:\n[Fact]\npublic void DetailsTest()\n{\n // arrange\n var mockRepo = new Mock<ISiteToSiteService>();\n mockRepo.Setup(m => m.Get(1)).Returns(SiteToSiteMockData.Get(1));\n var controller = new SiteToSiteController(new PharmacyDBContext(), mockRepo.Object);\n\n // act\n var result = controller.GetSiteToSiteById(1);\n\n // assert\n var viewResult = Assert.IsType<ViewResult>(result);\n var viewResultSiteToSite = Assert.IsAssignableFrom<SiteToSite>(viewResult.ViewData.Model);\n Assert.Equal(\"John Doe\", viewResultSiteToSite.OrderedByName);\n}\n\nHere's the action method from the controller:\npublic ActionResult GetSiteToSiteById(int id)\n{\n var site2Site = siteToSiteService.Get(id);\n if (site2Site == null)\n {\n return NotFound();\n }\n return View(\"SiteToSiteDetail\", site2Site);\n}\n\nand here's the Get(int id) method from the service/repository method:\npublic SiteToSite? Get(int id)\n{\n var result = _context.SiteToSite.Include(i => i.SiteToSiteItems).Where(s => s.SiteToSiteID == id);\n return result.FirstOrDefault();\n}\n\n" ]
[ 0 ]
[]
[]
[ "asp.net_mvc", "c#", "moq", "xunit" ]
stackoverflow_0074482381_asp.net_mvc_c#_moq_xunit.txt
Q: How to specify return type of variable when function returns multiple types In Python a function can return multiple types, for example, in the below example a is str, b is int and c is List[int] def test(): return 'abc', 100, [0, 1, 2] a, b, c = test() print(a) # abc print(b) # 100 print(c) # [0, 1, 2] So the function signature then becomes, def test() -> Tuple[str, int, List[int]]: In this case, how do I specify the types of variables that receive the value? Hypothetically I should be able to specify it like as shown below, but is not possible. a: str, b: int, c: List[int] = test() The only viable alternative is as shown below, ret: Tuple(str, int, List[int]) = test() But then I need to unpack the tuple into multiple variable, then we are back to square one, since we can not specify the type for those variables. What am I missing? A: What about using type hints? ( a, # type: str b, # type: int c, # type: List[int] ) = test() Anyway, the typing should be smart enough to infer the right types even without explicitly specifying them in the final variables.
How to specify return type of variable when function returns multiple types
In Python a function can return multiple types, for example, in the below example a is str, b is int and c is List[int] def test(): return 'abc', 100, [0, 1, 2] a, b, c = test() print(a) # abc print(b) # 100 print(c) # [0, 1, 2] So the function signature then becomes, def test() -> Tuple[str, int, List[int]]: In this case, how do I specify the types of variables that receive the value? Hypothetically I should be able to specify it like as shown below, but is not possible. a: str, b: int, c: List[int] = test() The only viable alternative is as shown below, ret: Tuple(str, int, List[int]) = test() But then I need to unpack the tuple into multiple variable, then we are back to square one, since we can not specify the type for those variables. What am I missing?
[ "What about using type hints?\n(\n a, # type: str\n b, # type: int\n c, # type: List[int]\n) = test()\n\nAnyway, the typing should be smart enough to infer the right types even without explicitly specifying them in the final variables.\n" ]
[ 0 ]
[]
[]
[ "python_3.x", "python_typing" ]
stackoverflow_0074667417_python_3.x_python_typing.txt
Q: Cannot resolve external dependency org.jetbrains.kotlin:kotlin-sam-with-receiver:1.5.31 because no repositories are defined Trying to add buildSrc to manage dependencies getting the following error: Error while evaluating property 'filteredArgumentsMap' of task ':buildSrc:compileKotlin' A: Add this repositories{ mavenCentral() } in the build.gradle.kts file after the plugins block to solve.
Cannot resolve external dependency org.jetbrains.kotlin:kotlin-sam-with-receiver:1.5.31 because no repositories are defined
Trying to add buildSrc to manage dependencies getting the following error: Error while evaluating property 'filteredArgumentsMap' of task ':buildSrc:compileKotlin'
[ "Add this\n repositories{\n mavenCentral()\n }\n\nin the build.gradle.kts file after the plugins block to solve.\n" ]
[ 0 ]
[]
[]
[ "android", "build", "buildsrc", "gradle", "kotlin" ]
stackoverflow_0074668902_android_build_buildsrc_gradle_kotlin.txt
Q: Background Service in Singleton Scope in my rested-web-service project, i need to check database in one hour intervals, this method should continue to work all the time, even if there is not user, and this method is single per hosted server.(some thing like cron in linux but i will host is iis) i have created a hostedService using microsft docs, with merely modifying the execute intervals (from 5 sec to 1 hours), **but problem occure after i deploy webservice solution in iis,this hosted servicerun if swagger page is open when i close browser or not calling rest-service, there is no logs in database another problem is if a open if i open swagger ui and call webservices from mobile-client there is multiple logs instead of only one per hour.** i bellive there is two problem here, first TimedHostedService scope is not singleton and it is created per request(scoped) and second problem is application is not kept alive where there is not any session in swagger-ui (or there is no user for werb services). i hava tried creating Async Method for this purpose that method call-it self with task.delay(onHour) but this didnt work either. public class TimedHostedService : IHostedService, IDisposable { private int executionCount = 0; private readonly ILogger<TimedHostedService> _logger; private Timer? _timer = null; public TimedHostedService(ILogger<TimedHostedService> logger) { _logger = logger; } public Task StartAsync(CancellationToken stoppingToken) { _timer = new Timer(DoWork, null, TimeSpan.Zero, TimeSpan.FromHours(1)); return Task.CompletedTask; } private void DoWork(object? state) { var count = Interlocked.Increment(ref executionCount); _logger.LogInformation( "Timed Hosted Service is working. Count: {Count}", count); } public Task StopAsync(CancellationToken stoppingToken) { _timer?.Change(Timeout.Infinite, 0); return Task.CompletedTask; } public void Dispose() { _timer?.Dispose(); } } A: Use Worker Service/Background Service instead of hosted service Replace code with below code public class TimedHostedService : BackgroundService { private readonly ILogger<Worker> _logger; private readonly TimeSpan _hourly = TimeSpan.FromHours(1); public Worker(ILogger<Worker> logger) { _logger = logger; } protected override async Task ExecuteAsync(CancellationToken stoppingToken) { using PeriodicTimer periodicTimer = new PeriodicTimer(_hourly); while (!stoppingToken.IsCancellationRequested && await periodicTimer.WaitForNextTickAsync(stoppingToken)) { _logger.LogInformation("Every 1 hour seconds"); await CheckDatabaseAsync(); } } private async Task CheckDatabaseAsync() { //check something in database as per you requirement _logger.LogInformation("Checking database"); } } Add Into scope services.AddHostedService<TimedHostedService>(); No need to use more confirmation.
Background Service in Singleton Scope
in my rested-web-service project, i need to check database in one hour intervals, this method should continue to work all the time, even if there is not user, and this method is single per hosted server.(some thing like cron in linux but i will host is iis) i have created a hostedService using microsft docs, with merely modifying the execute intervals (from 5 sec to 1 hours), **but problem occure after i deploy webservice solution in iis,this hosted servicerun if swagger page is open when i close browser or not calling rest-service, there is no logs in database another problem is if a open if i open swagger ui and call webservices from mobile-client there is multiple logs instead of only one per hour.** i bellive there is two problem here, first TimedHostedService scope is not singleton and it is created per request(scoped) and second problem is application is not kept alive where there is not any session in swagger-ui (or there is no user for werb services). i hava tried creating Async Method for this purpose that method call-it self with task.delay(onHour) but this didnt work either. public class TimedHostedService : IHostedService, IDisposable { private int executionCount = 0; private readonly ILogger<TimedHostedService> _logger; private Timer? _timer = null; public TimedHostedService(ILogger<TimedHostedService> logger) { _logger = logger; } public Task StartAsync(CancellationToken stoppingToken) { _timer = new Timer(DoWork, null, TimeSpan.Zero, TimeSpan.FromHours(1)); return Task.CompletedTask; } private void DoWork(object? state) { var count = Interlocked.Increment(ref executionCount); _logger.LogInformation( "Timed Hosted Service is working. Count: {Count}", count); } public Task StopAsync(CancellationToken stoppingToken) { _timer?.Change(Timeout.Infinite, 0); return Task.CompletedTask; } public void Dispose() { _timer?.Dispose(); } }
[ "\nUse Worker Service/Background Service instead of hosted service\nReplace code with below code\n\n public class TimedHostedService : BackgroundService\n {\n private readonly ILogger<Worker> _logger;\n private readonly TimeSpan _hourly = TimeSpan.FromHours(1);\n public Worker(ILogger<Worker> logger)\n {\n _logger = logger;\n }\n\n protected override async Task ExecuteAsync(CancellationToken stoppingToken)\n {\n using PeriodicTimer periodicTimer = new PeriodicTimer(_hourly);\n\n while (!stoppingToken.IsCancellationRequested &&\n await periodicTimer.WaitForNextTickAsync(stoppingToken))\n {\n _logger.LogInformation(\"Every 1 hour seconds\");\n await CheckDatabaseAsync();\n }\n }\n\n private async Task CheckDatabaseAsync()\n {\n //check something in database as per you requirement\n _logger.LogInformation(\"Checking database\");\n }\n }\n\n\nAdd Into scope services.AddHostedService<TimedHostedService>();\nNo need to use more confirmation.\n\n" ]
[ 0 ]
[]
[]
[ "asp.net_core_6.0", "asp.net_core_webapi", "c#", "cron" ]
stackoverflow_0074667527_asp.net_core_6.0_asp.net_core_webapi_c#_cron.txt
Q: General Code, Class, Method cleanup tool in Android studio I am using Android Studio for a fairly large project and have been using it for a while. However, inevitably many unused pieces of Code (along with other classes and methods) have built up. I have tried numerous things, for example unused declaration and code inspection; but they do not seem to be very direct nor particularly effective (unless of course I have used them wrong). I am just asking to see if there are any suggestions of built-in or plugin based ways of accomplishing this cleanup. Also, if it is any help, classes are predominantly in kotlin, rather than Java. I'd really appreciate any advice/guidance on this topic A: One of the best ways to clean up unused code in Android Studio is to use a plugin like CodeGlance or Code Inspector. These plugins allow you to quickly scan through your codebase and identify any sections of code that are not being used. From there, you can easily delete the unused code, saving yourself time and reducing the size of your project. Additionally, you can use the Android Lint tool to scan your code for errors and potential issues. This can help you identify any pieces of code that have been deprecated or are no longer needed. Finally, you can also use automated refactoring tools (such as IntelliJ's Code Cleanup) to help you clean up and restructure your codebase.
General Code, Class, Method cleanup tool in Android studio
I am using Android Studio for a fairly large project and have been using it for a while. However, inevitably many unused pieces of Code (along with other classes and methods) have built up. I have tried numerous things, for example unused declaration and code inspection; but they do not seem to be very direct nor particularly effective (unless of course I have used them wrong). I am just asking to see if there are any suggestions of built-in or plugin based ways of accomplishing this cleanup. Also, if it is any help, classes are predominantly in kotlin, rather than Java. I'd really appreciate any advice/guidance on this topic
[ "One of the best ways to clean up unused code in Android Studio is to use a plugin like CodeGlance or Code Inspector. These plugins allow you to quickly scan through your codebase and identify any sections of code that are not being used. From there, you can easily delete the unused code, saving yourself time and reducing the size of your project. Additionally, you can use the Android Lint tool to scan your code for errors and potential issues. This can help you identify any pieces of code that have been deprecated or are no longer needed. Finally, you can also use automated refactoring tools (such as IntelliJ's Code Cleanup) to help you clean up and restructure your codebase.\n" ]
[ 1 ]
[]
[]
[ "android", "android_studio", "kotlin" ]
stackoverflow_0074668577_android_android_studio_kotlin.txt
Q: Pandas : Calculate the Mean of the value_counts() from row 0 to row n I am struggling to create a function that could first calculate the number of occurrences for each string in a specific column (from row 0 to row n) and then reduce this to one single value by calculating the mean of the value_counts from the first row to the row n. More precisely, what I would like to do is to create a new column ['Mean'] where the value of each row n equals to the mean of the value_counts() from the first row to the nth row of the column ['Name']. import pandas as pd import datetime as dt data = [["2022-11-1", 'Tom'], ["2022-11-2", 'Mike'], ["2022-11-3", 'Paul'], ["2022-11-4", 'Pauline'], ["2022-11-5", 'Pauline'], ["2022-11-6", 'Mike'], ["2022-11-7", 'Tom'], ["2022-11-8", 'Louise'], ["2022-11-9", 'Tom'], ["2022-11-10", 'Mike'], ["2022-11-11", 'Paul'], ["2022-11-12", 'Pauline'], ["2022-11-13", 'Pauline'], ["2022-11-14", 'Mike'], ["2022-11-15", 'Tom'], ["2022-11-16", 'Louise']] df = pd.DataFrame(data, columns=['Date', 'Name']) So for example, the 6th row of ['Mean'] should have a value of 1.25 as Pauline appeared twice, so the calcul should be (1 + 1 + 1 + 2 + 1)/5 = 1.25 . Thank you, A: The logic is unclear, but assuming you want the expanding average count of values, use: df['mean'] = pd.Series(pd.factorize(df['Name'])[0], index=df.index) .expanding() .apply(lambda s: s.value_counts().mean()) ) Output: Date Name mean 0 2022-11-1 Tom 1.00 1 2022-11-2 Mike 1.00 2 2022-11-3 Paul 1.00 3 2022-11-4 Pauline 1.00 4 2022-11-5 Pauline 1.25 5 2022-11-6 Mike 1.50 6 2022-11-7 Tom 1.75 7 2022-11-8 Louise 1.60 8 2022-11-9 Tom 1.80 9 2022-11-10 Mike 2.00 10 2022-11-11 Paul 2.20 11 2022-11-12 Pauline 2.40 12 2022-11-13 Pauline 2.60 13 2022-11-14 Mike 2.80 14 2022-11-15 Tom 3.00 15 2022-11-16 Louise 3.20
Pandas : Calculate the Mean of the value_counts() from row 0 to row n
I am struggling to create a function that could first calculate the number of occurrences for each string in a specific column (from row 0 to row n) and then reduce this to one single value by calculating the mean of the value_counts from the first row to the row n. More precisely, what I would like to do is to create a new column ['Mean'] where the value of each row n equals to the mean of the value_counts() from the first row to the nth row of the column ['Name']. import pandas as pd import datetime as dt data = [["2022-11-1", 'Tom'], ["2022-11-2", 'Mike'], ["2022-11-3", 'Paul'], ["2022-11-4", 'Pauline'], ["2022-11-5", 'Pauline'], ["2022-11-6", 'Mike'], ["2022-11-7", 'Tom'], ["2022-11-8", 'Louise'], ["2022-11-9", 'Tom'], ["2022-11-10", 'Mike'], ["2022-11-11", 'Paul'], ["2022-11-12", 'Pauline'], ["2022-11-13", 'Pauline'], ["2022-11-14", 'Mike'], ["2022-11-15", 'Tom'], ["2022-11-16", 'Louise']] df = pd.DataFrame(data, columns=['Date', 'Name']) So for example, the 6th row of ['Mean'] should have a value of 1.25 as Pauline appeared twice, so the calcul should be (1 + 1 + 1 + 2 + 1)/5 = 1.25 . Thank you,
[ "The logic is unclear, but assuming you want the expanding average count of values, use:\ndf['mean'] = pd.Series(pd.factorize(df['Name'])[0], index=df.index)\n .expanding()\n .apply(lambda s: s.value_counts().mean())\n )\n\nOutput:\n Date Name mean\n0 2022-11-1 Tom 1.00\n1 2022-11-2 Mike 1.00\n2 2022-11-3 Paul 1.00\n3 2022-11-4 Pauline 1.00\n4 2022-11-5 Pauline 1.25\n5 2022-11-6 Mike 1.50\n6 2022-11-7 Tom 1.75\n7 2022-11-8 Louise 1.60\n8 2022-11-9 Tom 1.80\n9 2022-11-10 Mike 2.00\n10 2022-11-11 Paul 2.20\n11 2022-11-12 Pauline 2.40\n12 2022-11-13 Pauline 2.60\n13 2022-11-14 Mike 2.80\n14 2022-11-15 Tom 3.00\n15 2022-11-16 Louise 3.20\n\n" ]
[ 2 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074668825_pandas_python.txt
Q: h2o-pysparkling-2.4 and Glue Jobs with: {"error":"TypeError: 'JavaPackage' object is not callable","errorType":"EXECUTION_FAILURE"} I am try to using pysparkling.ml.H2OMOJOModel for predict a spark dataframe using a MOJO model trained with h2o==3.32.0.2 in AWS Glue Jobs, how ever a got the error: TypeError: 'JavaPackage' object is not callable. I opened a ticket in AWS support and they confirmed that Glue environment is ok and the problem is probably with sparkling-water (pysparkling). It seems that some dependency library is missing, but I have no idea which one. The simple code bellow works perfectly if I run in my local computer (I only need to change the mojo path for GBM_grid__1_AutoML_20220323_233606_model_53.zip) Could anyone ever run sparkling-water in Glue jobs successfully? Job Details: -Glue version 2.0 --additional-python-modules, h2o-pysparkling-2.4==3.36.0.2-1 -Worker type: G1.X -Number of workers: 2 -Using script "createFromMojo.py" createFromMojo.py: import sys from awsglue.transforms import * from awsglue.utils import getResolvedOptions from pyspark.context import SparkContext from awsglue.context import GlueContext from awsglue.job import Job import pandas as pd from pysparkling.ml import H2OMOJOSettings from pysparkling.ml import H2OMOJOModel # from pysparkling.ml import * ## @params: [JOB_NAME] args = getResolvedOptions(sys.argv, ["JOB_NAME"]) #Job setup sc = SparkContext() glueContext = GlueContext(sc) spark = glueContext.spark_session job = Job(glueContext) job.init(args["JOB_NAME"], args) caminho_modelo_mojo='s3://prod-lakehouse-stream/modeling/approaches/GBM_grid__1_AutoML_20220323_233606_model_53.zip' print(caminho_modelo_mojo) print(dir()) settings = H2OMOJOSettings(convertUnknownCategoricalLevelsToNa = True, convertInvalidNumbersToNa = True) model = H2OMOJOModel.createFromMojo(caminho_modelo_mojo, settings) data = {'days_since_last_application': [3, 2, 1, 0], 'job_area': ['a', 'b', 'c', 'd']} base_escorada = model.transform(spark.createDataFrame(pd.DataFrame.from_dict(data))) print(base_escorada.printSchema()) print(base_escorada.show()) job.commit() A: I could run successfully following the steps: Downloaded sparkling water distribution zip: http://h2o-release.s3.amazonaws.com/sparkling-water/spark-3.1/3.36.1.1-1-3.1/index.html Dependent JARs path: s3://bucket_name/sparkling-water-assembly-scoring_2.12-3.36.1.1-1-3.1-all.jar --additional-python-modules, h2o-pysparkling-3.1==3.36.1.1-1-3.1
h2o-pysparkling-2.4 and Glue Jobs with: {"error":"TypeError: 'JavaPackage' object is not callable","errorType":"EXECUTION_FAILURE"}
I am try to using pysparkling.ml.H2OMOJOModel for predict a spark dataframe using a MOJO model trained with h2o==3.32.0.2 in AWS Glue Jobs, how ever a got the error: TypeError: 'JavaPackage' object is not callable. I opened a ticket in AWS support and they confirmed that Glue environment is ok and the problem is probably with sparkling-water (pysparkling). It seems that some dependency library is missing, but I have no idea which one. The simple code bellow works perfectly if I run in my local computer (I only need to change the mojo path for GBM_grid__1_AutoML_20220323_233606_model_53.zip) Could anyone ever run sparkling-water in Glue jobs successfully? Job Details: -Glue version 2.0 --additional-python-modules, h2o-pysparkling-2.4==3.36.0.2-1 -Worker type: G1.X -Number of workers: 2 -Using script "createFromMojo.py" createFromMojo.py: import sys from awsglue.transforms import * from awsglue.utils import getResolvedOptions from pyspark.context import SparkContext from awsglue.context import GlueContext from awsglue.job import Job import pandas as pd from pysparkling.ml import H2OMOJOSettings from pysparkling.ml import H2OMOJOModel # from pysparkling.ml import * ## @params: [JOB_NAME] args = getResolvedOptions(sys.argv, ["JOB_NAME"]) #Job setup sc = SparkContext() glueContext = GlueContext(sc) spark = glueContext.spark_session job = Job(glueContext) job.init(args["JOB_NAME"], args) caminho_modelo_mojo='s3://prod-lakehouse-stream/modeling/approaches/GBM_grid__1_AutoML_20220323_233606_model_53.zip' print(caminho_modelo_mojo) print(dir()) settings = H2OMOJOSettings(convertUnknownCategoricalLevelsToNa = True, convertInvalidNumbersToNa = True) model = H2OMOJOModel.createFromMojo(caminho_modelo_mojo, settings) data = {'days_since_last_application': [3, 2, 1, 0], 'job_area': ['a', 'b', 'c', 'd']} base_escorada = model.transform(spark.createDataFrame(pd.DataFrame.from_dict(data))) print(base_escorada.printSchema()) print(base_escorada.show()) job.commit()
[ "I could run successfully following the steps:\n\nDownloaded sparkling water distribution zip: http://h2o-release.s3.amazonaws.com/sparkling-water/spark-3.1/3.36.1.1-1-3.1/index.html\nDependent JARs path: s3://bucket_name/sparkling-water-assembly-scoring_2.12-3.36.1.1-1-3.1-all.jar\n--additional-python-modules, h2o-pysparkling-3.1==3.36.1.1-1-3.1\n\n" ]
[ 0 ]
[]
[]
[ "apache_spark", "h2o", "python", "sparkling_water" ]
stackoverflow_0071928885_apache_spark_h2o_python_sparkling_water.txt
Q: Isomorphic Strings Function Always Returns True I am attempting the Isomorphic Strings problem on LeetCode and am having issues with my current solution. I'm sure there are plenty of answers on exactly how to complete this problem, but I would really prefer to finish it through my own thought process before learning the best possible way to do it. For reference, here is the problem: https://leetcode.com/problems/isomorphic-strings/?envType=study-plan&id=level-1 This is my code as it is right now: var isIsomorphic = function(s, t) { const map = new Map(); const array1 = [...s]; const array2 = [...t]; for (i = 0; i < s.length; i++) { if ((map.has(array1[i]) === true) && (map.has(array2[i]) === true)) { if (map.get(array1[i]) !== array2[i]) { return false; } else { continue; } } else if (map.has(array1[i]) === false) { map.set(array1[i], array2[i]); } } return true; }; It's messy but I can't figure out why it isn't giving me the desired results. Right now, it seems to always return true for any given values, even though I have the initial if statement to return false if it ever comes across previously-mapped values that don't match. Am I missing something obvious? This is my first question on SA, so I apologize if the format is wrong. A: The map is set like: map.set(array1[i], array2[i]); The key is the character in the first string, and the value is the corresponding character in the second string. So, when iterating over a new character, checking map.has will only make sense if the character being passed is from the first string; doing map.has(array2[i]) === true)) does not test anything useful, because the second string's characters are not keys of the Map. You need to perform two tests: that the 1st string's character corresponds to the 2nd string's character (which you're doing right), and that the 2nd string's character is not already set to a different 1st string's character (which needs to be fixed). For this second condition, consider having another Map that's the reverse of the first one - the keys are the characters from the 2nd string, and the values are the characters from the 1st string. (You don't have to have another Map - you could also iterate through the .entries of the first, check that, for every entry's value that matches the 2nd character, the entry's key matches the 1st - but that could feel a bit messy.) Cleaning up your code some, there's also no need to turn the strings into arrays, and === true can be omitted entirely, and the i variable should be declared with let. You also might want to check if the length of the first string is equal to the length of the second. var isIsomorphic = function(s1, s2) { if (s1.length !== s2.length) return false; const map1to2 = new Map(); const map2to1 = new Map(); for (let i = 0; i < s1.length; i++) { // Check that s1 here corresponds to s2 if (map1to2.has(s1[i]) && map1to2.get(s1[i]) !== s2[i]) { return false; } // And that s2 here doesn't correspond to any other s1 if (map2to1.has(s2[i]) && map2to1.get(s2[i]) !== s1[i]) { return false; } map1to2.set(s1[i], s2[i]); map2to1.set(s2[i], s1[i]); } return true; }; console.log(isIsomorphic('aa', 'bb')); console.log(isIsomorphic('aa', 'ba')); console.log(isIsomorphic('badc', 'baba'));
Isomorphic Strings Function Always Returns True
I am attempting the Isomorphic Strings problem on LeetCode and am having issues with my current solution. I'm sure there are plenty of answers on exactly how to complete this problem, but I would really prefer to finish it through my own thought process before learning the best possible way to do it. For reference, here is the problem: https://leetcode.com/problems/isomorphic-strings/?envType=study-plan&id=level-1 This is my code as it is right now: var isIsomorphic = function(s, t) { const map = new Map(); const array1 = [...s]; const array2 = [...t]; for (i = 0; i < s.length; i++) { if ((map.has(array1[i]) === true) && (map.has(array2[i]) === true)) { if (map.get(array1[i]) !== array2[i]) { return false; } else { continue; } } else if (map.has(array1[i]) === false) { map.set(array1[i], array2[i]); } } return true; }; It's messy but I can't figure out why it isn't giving me the desired results. Right now, it seems to always return true for any given values, even though I have the initial if statement to return false if it ever comes across previously-mapped values that don't match. Am I missing something obvious? This is my first question on SA, so I apologize if the format is wrong.
[ "The map is set like:\nmap.set(array1[i], array2[i]);\n\nThe key is the character in the first string, and the value is the corresponding character in the second string. So, when iterating over a new character, checking map.has will only make sense if the character being passed is from the first string; doing map.has(array2[i]) === true)) does not test anything useful, because the second string's characters are not keys of the Map.\nYou need to perform two tests: that the 1st string's character corresponds to the 2nd string's character (which you're doing right), and that the 2nd string's character is not already set to a different 1st string's character (which needs to be fixed). For this second condition, consider having another Map that's the reverse of the first one - the keys are the characters from the 2nd string, and the values are the characters from the 1st string. (You don't have to have another Map - you could also iterate through the .entries of the first, check that, for every entry's value that matches the 2nd character, the entry's key matches the 1st - but that could feel a bit messy.)\nCleaning up your code some, there's also no need to turn the strings into arrays, and === true can be omitted entirely, and the i variable should be declared with let.\nYou also might want to check if the length of the first string is equal to the length of the second.\n\n\nvar isIsomorphic = function(s1, s2) {\n if (s1.length !== s2.length) return false;\n const map1to2 = new Map();\n const map2to1 = new Map();\n for (let i = 0; i < s1.length; i++) {\n // Check that s1 here corresponds to s2\n if (map1to2.has(s1[i]) && map1to2.get(s1[i]) !== s2[i]) {\n return false;\n }\n // And that s2 here doesn't correspond to any other s1\n if (map2to1.has(s2[i]) && map2to1.get(s2[i]) !== s1[i]) {\n return false;\n }\n map1to2.set(s1[i], s2[i]);\n map2to1.set(s2[i], s1[i]);\n }\n return true;\n};\nconsole.log(isIsomorphic('aa', 'bb'));\nconsole.log(isIsomorphic('aa', 'ba'));\nconsole.log(isIsomorphic('badc', 'baba'));\n\n\n\n" ]
[ 0 ]
[]
[]
[ "isomorphism", "javascript" ]
stackoverflow_0074668828_isomorphism_javascript.txt
Q: How do I get the return value when using Python exec on the code object of a function? For testing purposes I want to directly execute a function defined inside of another function. I can get to the code object of the child function, through the code (func_code) of the parent function, but when I exec it, i get no return value. Is there a way to get the return value from the exec'ed code? A: Yes, you need to have the assignment within the exec statement: >>> def foo(): ... return 5 ... >>> exec("a = foo()") >>> a 5 This probably isn't relevant for your case since its being used in controlled testing, but be careful with using exec with user defined input. A: A few years later, but the following snippet helped me: the_code = ''' a = 1 b = 2 return_me = a + b ''' loc = {} exec(the_code, globals(), loc) return_workaround = loc['return_me'] print(return_workaround) # 3 exec() doesn't return anything itself, but you can pass a dict which has all the local variables stored in it after execution. By accessing it you have a something like a return. I hope it helps someone. A: While this is the ugliest beast ever seen by mankind, this is how you can do it by using a global variable inside your exec call: def my_exec(code): exec('global i; i = %s' % code) global i return i This is misusing global variables to get your data across the border. >>> my_exec('1 + 2') 3 Needless to say that you should never allow any user inputs for the input of this function in there, as it poses an extreme security risk. A: Something like this can work: def outer(): def inner(i): return i + 10 for f in outer.func_code.co_consts: if getattr(f, 'co_name', None) == 'inner': inner = type(outer)(f, globals()) # can also use `types` module for readability: # inner = types.FunctionType(f, globals()) print inner(42) # 52 The idea is to extract the code object from the inner function and create a new function based on it. Additional work is required when an inner function can contain free variables. You'll have to extract them as well and pass to the function constructor in the last argument (closure). A: Here's a way to return a value from exec'd code: def exec_and_return(expression): exec(f"""locals()['temp'] = {expression}""") return locals()['temp'] I'd advise you to give an example of the problem you're trying to solve. Because I would only ever use this as a last resort. A: use eval() instead of exec(), it returns result A: This doesn't get the return value per say, but you can provide an empty dictionary when calling exec to retrieve any variables defined in the code. # Python 3 ex_locals = {} exec("a = 'Hello world!'", None, ex_locals) print(ex_locals['a']) # Output: Hello world! From the Python 3 documentation on exec: The default locals act as described for function locals() below: modifications to the default locals dictionary should not be attempted. Pass an explicit locals dictionary if you need to see effects of the code on locals after function exec() returns. For more information, see How does exec work with locals? A: Here's a solution with a simple code: # -*- coding: utf-8 -*- import math x = [0] exec("x[0] = 3*2") print(x[0]) # 6 A: Since Python 3.7, dictionary are ordered. So you no longer need to agree on a name, you can just say "last item that got created": >>> d = {} >>> exec("def addone(i): return i + 1", d, d) >>> list(d) ['__builtins__', 'addone'] >>> thefunction = d[list(d)[-1]] >>> thefunction <function addone at 0x7fd03123fe50>
How do I get the return value when using Python exec on the code object of a function?
For testing purposes I want to directly execute a function defined inside of another function. I can get to the code object of the child function, through the code (func_code) of the parent function, but when I exec it, i get no return value. Is there a way to get the return value from the exec'ed code?
[ "Yes, you need to have the assignment within the exec statement:\n>>> def foo():\n... return 5\n...\n>>> exec(\"a = foo()\")\n>>> a\n5\n\nThis probably isn't relevant for your case since its being used in controlled testing, but be careful with using exec with user defined input. \n", "A few years later, but the following snippet helped me:\nthe_code = '''\na = 1\nb = 2\nreturn_me = a + b\n'''\n\nloc = {}\nexec(the_code, globals(), loc)\nreturn_workaround = loc['return_me']\nprint(return_workaround) # 3\n\nexec() doesn't return anything itself, but you can pass a dict which has all the local variables stored in it after execution. By accessing it you have a something like a return.\nI hope it helps someone.\n", "While this is the ugliest beast ever seen by mankind, this is how you can do it by using a global variable inside your exec call:\ndef my_exec(code):\n exec('global i; i = %s' % code)\n global i\n return i\n\nThis is misusing global variables to get your data across the border.\n>>> my_exec('1 + 2')\n3\n\nNeedless to say that you should never allow any user inputs for the input of this function in there, as it poses an extreme security risk.\n", "Something like this can work:\ndef outer():\n def inner(i):\n return i + 10\n\n\nfor f in outer.func_code.co_consts:\n if getattr(f, 'co_name', None) == 'inner':\n\n inner = type(outer)(f, globals())\n\n # can also use `types` module for readability:\n # inner = types.FunctionType(f, globals())\n\n print inner(42) # 52\n\nThe idea is to extract the code object from the inner function and create a new function based on it.\nAdditional work is required when an inner function can contain free variables. You'll have to extract them as well and pass to the function constructor in the last argument (closure).\n", "Here's a way to return a value from exec'd code:\ndef exec_and_return(expression):\n exec(f\"\"\"locals()['temp'] = {expression}\"\"\")\n return locals()['temp']\n\nI'd advise you to give an example of the problem you're trying to solve. Because I would only ever use this as a last resort.\n", "use eval() instead of exec(), it returns result\n", "This doesn't get the return value per say, but you can provide an empty dictionary when calling exec to retrieve any variables defined in the code.\n# Python 3\nex_locals = {}\nexec(\"a = 'Hello world!'\", None, ex_locals)\nprint(ex_locals['a'])\n# Output: Hello world!\n\nFrom the Python 3 documentation on exec:\n\nThe default locals act as described for function locals() below: modifications to the default locals dictionary should not be attempted. Pass an explicit locals dictionary if you need to see effects of the code on locals after function exec() returns.\n\nFor more information, see How does exec work with locals?\n", "Here's a solution with a simple code:\n# -*- coding: utf-8 -*-\nimport math\n\nx = [0]\nexec(\"x[0] = 3*2\")\nprint(x[0]) # 6\n\n", "Since Python 3.7, dictionary are ordered. So you no longer need to agree on a name, you can just say \"last item that got created\":\n>>> d = {}\n>>> exec(\"def addone(i): return i + 1\", d, d)\n>>> list(d)\n['__builtins__', 'addone']\n>>> thefunction = d[list(d)[-1]]\n>>> thefunction\n<function addone at 0x7fd03123fe50>\n\n" ]
[ 37, 29, 10, 4, 3, 3, 2, 0, 0 ]
[ "if we need a function that is in a file in another directory, eg\nwe need the function1 in file my_py_file.py \nlocated in /home/.../another_directory\n\nwe can use the following code:\n\n\ndef cl_import_function(a_func,py_file,in_Dir): \n... import sys\n... sys.path.insert(0, in_Dir)\n... ax='from %s import %s'%(py_file,a_func)\n... loc={}\n... exec(ax, globals(), loc)\n... getFx = loc[afunc]\n... return getFx\n\ntest = cl_import_function('function1',r'my_py_file',r'/home/.../another_directory/')\ntest()\n\n(a simple way for newbies...)\n", "program = 'a = 5\\nb=10\\nprint(\"Sum =\", a+b)'\nprogram = exec(program)\nprint(program)\n" ]
[ -1, -1 ]
[ "exec", "function", "python", "return" ]
stackoverflow_0023917776_exec_function_python_return.txt
Q: What is the best way to update `HAS ONE` using gorm? I have two models type User { ID uint `gorm:"primarykey" json:"-"` FirstName string `json:"firstName"` LastName string `json:"lastName"` Email string `json:"email"` Profile Profile `gorm:"constraint:OnDelete:CASCADE;"` } and type Profile struct { ID uint `gorm:"primarykey" json:"-"` UserID uint `gorm:"uniqueIndex:idx_uniqueProfile" json:"-"` PhoneNumber string `json:"phoneNumber"` } Assuming i have json data to update it like this data := schema.UserUpdate{ FirstName: "ABC", LastName: "XYZ", Profile: schema.Profile{PhoneNumber: "123445666"}} and I update user like this var user authmodels.User // get user object to be updated if err := database.Db.Joins("Profile").First(&user, "uid = ?", uid).Error; err != nil { if errors.Is(err, gorm.ErrRecordNotFound) { return c.Status(fiber.StatusNotFound).JSON(er.NotFound("")) } return c.Status(fiber.StatusBadRequest).JSON(er.BadRequest(err.Error())) } // data used to update user object var updateData = authmodels.User{FirstName: data.FirstName, LastName: data.LastName, Profile: authmodels.Profile{PhoneNumber: data.Profile.PhoneNumber}} // update user object and it's profile as well if err := database.Db.Model(&user).Updates(updateData).Error; err != nil { return c.Status(fiber.StatusBadRequest).JSON(er.BadRequest(err.Error())) } Output results User Model it only update selected fields (OK) UPDATE "users" SET "updated_at"='2022-07-07 00:03:18.57',"first_name"='Fiber',"last_name"='Go lang' WHERE "id" = 11 Profile Model it insert instead of updating and it uses original data instead of new data(phoneNumber) INSERT INTO "profiles" ("created_at","updated_at","user_id","phone_number","id") VALUES ('2022-07-06 23:58:25.61','2022-07-06 23:58:25.61',11,'255765889960',15) ON CONFLICT ("id") DO UPDATE SET "user_id"="excluded"."user_id" RETURNING "id" A: You have to set FullSaveAssociations to true if you want to update associations data. Check it out: https://gorm.io/docs/session.html Therefore your update query shall look like: err := database.Db.Session(&gorm.Session{FullSaveAssociations: true}).Updates(&updateData).Error And make sure to specify the User and Profile IDs in updateData or through a WHERE clause.
What is the best way to update `HAS ONE` using gorm?
I have two models type User { ID uint `gorm:"primarykey" json:"-"` FirstName string `json:"firstName"` LastName string `json:"lastName"` Email string `json:"email"` Profile Profile `gorm:"constraint:OnDelete:CASCADE;"` } and type Profile struct { ID uint `gorm:"primarykey" json:"-"` UserID uint `gorm:"uniqueIndex:idx_uniqueProfile" json:"-"` PhoneNumber string `json:"phoneNumber"` } Assuming i have json data to update it like this data := schema.UserUpdate{ FirstName: "ABC", LastName: "XYZ", Profile: schema.Profile{PhoneNumber: "123445666"}} and I update user like this var user authmodels.User // get user object to be updated if err := database.Db.Joins("Profile").First(&user, "uid = ?", uid).Error; err != nil { if errors.Is(err, gorm.ErrRecordNotFound) { return c.Status(fiber.StatusNotFound).JSON(er.NotFound("")) } return c.Status(fiber.StatusBadRequest).JSON(er.BadRequest(err.Error())) } // data used to update user object var updateData = authmodels.User{FirstName: data.FirstName, LastName: data.LastName, Profile: authmodels.Profile{PhoneNumber: data.Profile.PhoneNumber}} // update user object and it's profile as well if err := database.Db.Model(&user).Updates(updateData).Error; err != nil { return c.Status(fiber.StatusBadRequest).JSON(er.BadRequest(err.Error())) } Output results User Model it only update selected fields (OK) UPDATE "users" SET "updated_at"='2022-07-07 00:03:18.57',"first_name"='Fiber',"last_name"='Go lang' WHERE "id" = 11 Profile Model it insert instead of updating and it uses original data instead of new data(phoneNumber) INSERT INTO "profiles" ("created_at","updated_at","user_id","phone_number","id") VALUES ('2022-07-06 23:58:25.61','2022-07-06 23:58:25.61',11,'255765889960',15) ON CONFLICT ("id") DO UPDATE SET "user_id"="excluded"."user_id" RETURNING "id"
[ "You have to set FullSaveAssociations to true if you want to update associations data. Check it out: https://gorm.io/docs/session.html\nTherefore your update query shall look like:\nerr := database.Db.Session(&gorm.Session{FullSaveAssociations: true}).Updates(&updateData).Error\n\nAnd make sure to specify the User and Profile IDs in updateData or through a WHERE clause.\n" ]
[ 0 ]
[]
[]
[ "fibers", "go_gorm", "postgresql" ]
stackoverflow_0072889924_fibers_go_gorm_postgresql.txt
Q: Create Sample Noisy signal in C I am trying to create a sample noisy signal that I will be filtering in C. I have written the code in python but will be deploying it to a microcotroller so I want to create it in C. Here is the python code I am trying to replicate # 1000 samples per second sample_rate = 1000 # frequency in Hz center_freq = 20 # filter frequency in Hz cutoff_freq = 10 test_signal = np.linspace( start=0., stop=2. * pi * center_freq, num=sample_rate, endpoint=False ) test_signal = np.cos(test_signal) second_test_signal = np.random.randn(sample_rate) I tried manually coding a linearlly spaced array but I cannot seem to get it to work. I have looked into libraries to make it easier but can't find any. Does anyone have any ideas on how to translate this python code into C a simple and easy to use way? Here is the C code I have so far. I am also wondering if I need to do this a completely different way? #include <stdlib.h> #include <stdio.h> #include <math.h> int sampleRate = 1000; int center_freq = 20; int cutoff_freq = 10; A: have written the code in python but will be deploying it to a microcotroller so I want to create it in C. There exist MicroPython MicroPython is a lean and efficient implementation of the Python 3 programming language that includes a small subset of the Python standard library and is optimised to run on microcontrollers and in constrained environments. and there exist numpy subset for above in form of micropython-numpy, if you manage to make it run at your microcotroller then conversion to C becomes no longer required. A: This is some code for the linearly spaced array: #include <stdlib.h> #include <stdio.h> #include <math.h> // ... int sampleRate = 1000; int center_freq = 20; int cutoff_freq = 10; float signal_1[1000]; float signal_2[1000]; float value = 0.0f; float inc = (2.0f * M_PI * (float)center_freq) / (float)sampleRate; for(int i = 0; i < sampleRate; ++i) { signal_1[i] = (float)cos(value); value += inc; } for(int i = 0; i < sampleRate; ++i) { signal_2[i] = (float)rand() / (float)RAND_MAX; }
Create Sample Noisy signal in C
I am trying to create a sample noisy signal that I will be filtering in C. I have written the code in python but will be deploying it to a microcotroller so I want to create it in C. Here is the python code I am trying to replicate # 1000 samples per second sample_rate = 1000 # frequency in Hz center_freq = 20 # filter frequency in Hz cutoff_freq = 10 test_signal = np.linspace( start=0., stop=2. * pi * center_freq, num=sample_rate, endpoint=False ) test_signal = np.cos(test_signal) second_test_signal = np.random.randn(sample_rate) I tried manually coding a linearlly spaced array but I cannot seem to get it to work. I have looked into libraries to make it easier but can't find any. Does anyone have any ideas on how to translate this python code into C a simple and easy to use way? Here is the C code I have so far. I am also wondering if I need to do this a completely different way? #include <stdlib.h> #include <stdio.h> #include <math.h> int sampleRate = 1000; int center_freq = 20; int cutoff_freq = 10;
[ "\nhave written the code in python but will be deploying it to a\nmicrocotroller so I want to create it in C.\n\nThere exist MicroPython\n\nMicroPython is a lean and efficient implementation of the Python 3\nprogramming language that includes a small subset of the Python\nstandard library and is optimised to run on microcontrollers and in\nconstrained environments.\n\nand there exist numpy subset for above in form of micropython-numpy, if you manage to make it run at your microcotroller then conversion to C becomes no longer required.\n", "This is some code for the linearly spaced array:\n#include <stdlib.h>\n#include <stdio.h>\n#include <math.h>\n\n// ...\n\nint sampleRate = 1000;\nint center_freq = 20;\nint cutoff_freq = 10;\n\nfloat signal_1[1000];\nfloat signal_2[1000];\n\nfloat value = 0.0f;\nfloat inc = (2.0f * M_PI * (float)center_freq) / (float)sampleRate;\n\nfor(int i = 0; i < sampleRate; ++i)\n{\n signal_1[i] = (float)cos(value);\n value += inc;\n}\n\nfor(int i = 0; i < sampleRate; ++i)\n{\n signal_2[i] = (float)rand() / (float)RAND_MAX;\n}\n\n" ]
[ 0, 0 ]
[]
[]
[ "arduino", "c", "python" ]
stackoverflow_0074632566_arduino_c_python.txt