qid int64 4 22.2M | question stringlengths 18 48.3k | answers list | date stringlengths 10 10 | metadata list |
|---|---|---|---|---|
74,195,306 | <pre><code>
values = ['random word1', 20, 'random word2', 54]
values = list(map(list,zip(values[::2], values[1::2])))
print(values)
[['random word1', 20], ['random word2', 54]]
</code></pre>
<p>Now I want to fetch values
like this:</p>
<p><code>if ‘random word2’ in values:</code></p>
<p>get the value associated with random word 2 which is in this case 54.</p>
<p>Note: string words and values are random.</p>
<p>How can I do that?</p>
<p>I need to fetch the correct value.</p>
| [
{
"answer_id": 74195367,
"author": "jsbueno",
"author_id": 108205,
"author_profile": "https://Stackoverflow.com/users/108205",
"pm_score": 2,
"selected": false,
"text": "try:\n value = values[values.index(\"random words2\") + 1]\nexcept ValueError:\n value = None \n"
},
{
"... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74195306",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19222846/"
] |
74,195,319 | <p>i have a page that shows my product, but this product comes with a very long description</p>
<p>I wanted that when it goes down x amount of characters it would cut in css and show ... at the end</p>
<pre><code><dd class="hiddendescricao deskonly" id="descricao"></dd>
<a (click)="rollDown(sectionRelated)" class="text-secondary">Ver mais</a>
.hiddendescricao {
display: -webkit-box;
text-overflow: ellipsis;
overflow: hidden;
-webkit-line-clamp: 2;
-webkit-box-orient: vertical;
position: relative;
height: 100%;
}
setDescricao() {
document.getElementById('descricao').innerHTML = this.item.item_linkWeb?.linkWeb.descricaoHtml; //<p>Belíssimo buquê de astromélias, feito a mão por nossos profissionais, garante a beleza e o cuidado especial que a pessoa amada merece. Seu fácil cuidado e manutenção permitem que desde de crianças até adultos possam receber esse carinho em forma de flores.</p>
document.getElementById('descricao2').innerHTML = this.item.item_linkWeb?.linkWeb.descricaoHtml; //<p>Belíssimo buquê de astromélias, feito a mão por nossos profissionais, garante a beleza e o cuidado especial que a pessoa amada merece. Seu fácil cuidado e manutenção permitem que desde de crianças até adultos possam receber esse carinho em forma de flores.</p>
}
</code></pre>
<p>the problem with my css is that to limit and put the ... at the end, is that the description has to go to the end of the line to work, I think limiting by character is better</p>
<p><a href="https://i.stack.imgur.com/yn8Wj.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/yn8Wj.png" alt="enter image description here" /></a></p>
| [
{
"answer_id": 74195401,
"author": "Vayne Valerius",
"author_id": 11888674,
"author_profile": "https://Stackoverflow.com/users/11888674",
"pm_score": 1,
"selected": false,
"text": "const truncateString = (string) => {\n if (string.length > 20) {\n const truncatedString = `${string.sl... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74195319",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19574035/"
] |
74,195,322 | <p>i have a quick question i'm trying to make an application but i've faced a problem, i want to assign data to a button then pass that data to datagridview when the button is clicked ex.</p>
<p><a href="https://i.stack.imgur.com/5T3di.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/5T3di.png" alt="enter image description here" /></a></p>
<pre><code>private void TeaButton_Click(object sender, EventArgs e)
{
sales.OrderDataGridView.Rows.Add(1, "Tea", 5.0);
}
</code></pre>
<p>i expected it to pass the values inside the parentheses to the data grid view, but it returned a null reference error, the reason was "sales." it was returning null value, but i don't know any other way beside this .</p>
| [
{
"answer_id": 74195401,
"author": "Vayne Valerius",
"author_id": 11888674,
"author_profile": "https://Stackoverflow.com/users/11888674",
"pm_score": 1,
"selected": false,
"text": "const truncateString = (string) => {\n if (string.length > 20) {\n const truncatedString = `${string.sl... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74195322",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20330704/"
] |
74,195,334 | <p>I'm not pro in JavaScript, I'm still learning. On my site, there is a hero section that has a title, paragraph, and is filled with a picture.</p>
<pre class="lang-html prettyprint-override"><code><div class="slider" style="background-image:url('https://source.unsplash.com/random/400x400');">
<div class="slider-title">Main Text 1</div>
<div class="slider-title display-none">Main Text 2</div>
<div class="slider-title display-none">Main Text 3</div>
<div class="slider-lead">Paragraph text 1</div>
<div class="slider-lead display-none">Paragraph text 2</div>
<div class="slider-lead display-none">Paragraph text 3</div>
</div>
<div class="d-flex">
<div class="hero-switch">
<img src="https://www.svgrepo.com/show/331860/dot.svg">
</div>
<div class="hero-switch">
<img src="https://www.svgrepo.com/show/331860/dot.svg">
</div>
<div class="hero-switch">
<img src="https://www.svgrepo.com/show/331860/dot.svg">
</div>
</div>
</code></pre>
<p>I would like to switch divs with 3 "bullet" buttons - each is responsible for showing relevant content (1st bullet = 1st div with Main Text1, Paragraph Text1 and 1st url background, 2nd bullet = 2nd div with Main text 2 and so on).</p>
<p>I know that I can assign specific IDs to each "bullet" button and add event listener but I feel that way is not too good.</p>
<p>Thanks for help!</p>
<p>I'm looking for solution in pure JS.</p>
<p>I have tried the forEach function but i don't know exactly how it is supposed to work.</p>
| [
{
"answer_id": 74195401,
"author": "Vayne Valerius",
"author_id": 11888674,
"author_profile": "https://Stackoverflow.com/users/11888674",
"pm_score": 1,
"selected": false,
"text": "const truncateString = (string) => {\n if (string.length > 20) {\n const truncatedString = `${string.sl... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74195334",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7617461/"
] |
74,195,355 | <p><strong>!!!UPDATE!!!</strong> Using the vertex shader to generate quads via DrawInstanced() calls definitely reduced CPU overhead and increased quads drawn per second. But there was much more performance to be found by using a combination of instanced drawing via a vertex shader that generates a point list, and a geometry shader that generates quads based on those points.</p>
<p>Thanks to @Soonts for not only recommending a faster way, but also for reminding me of conditional moves and unrolling loops.</p>
<p>Here is the geometry shader I created for sprites with 2D rotation:</p>
<pre><code>cbuffer CB_PROJ {
matrix camera;
};
/* Reduced packet size -- 256x256 max atlas segments
-------------------
FLOAT3 Sprite location // 12 bytes
FLOAT Rotation // 16 bytes
FLOAT2 Scale // 24 bytes
UINT // 28 bytes
Fixed8p00 Texture X segment
Fixed8p00 Texture X total segments
Fixed8p00 Texture Y segment
Fixed8p00 Texture Y total segments
.Following vertex data is only processed by the vertex shader.
UINT // 32 bytes
Fixed3p00 Squadron generation method
Fixed7p00 Sprite stride
Fixed8p14 X/Y distance between sprites
*/
struct VOut {
float3 position : POSITION;
float3 r_s : NORMAL;
uint bits : BLENDINDICES;
};
struct GOut {
float4 pos : SV_Position;
float3 position : POSITION;
float3 n : NORMAL;
float2 tex : TEXCOORD;
uint pID : SV_PrimitiveID;
};
[maxvertexcount(4)]
void main(point VOut gin[1], uint pID : SV_PrimitiveID, inout TriangleStream<GOut> triStream) {
GOut output;
const uint bits = gin[0].bits;
const uint ySegs = (bits & 0x0FF000000) >> 24u;
const uint _yOS = (bits & 0x000FF0000) >> 16u;
const float yOS = 1.0f - float(_yOS) / float(ySegs);
const float yOSd = rcp(float(ySegs));
const uint xSegs = (bits & 0x00000FF00) >> 8u;
const uint _xOS = (bits & 0x0000000FF);
const float xOS = float(_xOS) / float(xSegs);
const float xOSd = rcp(float(xSegs));
float2 v;
output.pID = pID;
output.n = float3( 0.0f, 0.0f, -1.0f );
output.position = gin[0].position; // Translate
v.x = -gin[0].r_s.y; v.y = -gin[0].r_s.z; // Scale
output.tex = float2(xOS, yOS);
output.position.x += v.x * cos(gin[0].r_s.x) - v.y * sin(gin[0].r_s.x); // Rotate
output.position.y += v.x * sin(gin[0].r_s.x) + v.y * cos(gin[0].r_s.x);
output.pos = mul(float4(output.position, 1.0f), camera); // Transform
triStream.Append(output);
output.position = gin[0].position;
v.x = -gin[0].r_s.y; v.y = gin[0].r_s.z;
output.tex = float2(xOS, yOS - yOSd);
output.position.x += v.x * cos(gin[0].r_s.x) - v.y * sin(gin[0].r_s.x);
output.position.y += v.x * sin(gin[0].r_s.x) + v.y * cos(gin[0].r_s.x);
output.pos = mul(float4(output.position, 1.0f), camera);
triStream.Append(output);
output.position = gin[0].position;
v.x = gin[0].r_s.y; v.y = -gin[0].r_s.z;
output.tex = float2(xOS + xOSd, yOS);
output.position.x += v.x * cos(gin[0].r_s.x) - v.y * sin(gin[0].r_s.x);
output.position.y += v.y * sin(gin[0].r_s.x) + v.y * cos(gin[0].r_s.x);
output.pos = mul(float4(output.position, 1.0f), camera);
triStream.Append(output);
output.position = gin[0].position;
v.x = gin[0].r_s.y; v.y = gin[0].r_s.z;
output.tex = float2(xOS + xOSd, yOS - yOSd);
output.position.x += v.x * cos(gin[0].r_s.x) - v.y * sin(gin[0].r_s.x);
output.position.y += v.y * sin(gin[0].r_s.x) + v.y * cos(gin[0].r_s.x);
output.pos = mul(float4(output.position, 1.0f), camera);
triStream.Append(output);
}
</code></pre>
<p><strong>!!!ORIGINAL TEXT!!!</strong></p>
<p>Last time I was coding, I had barely started learning Direct3D9c. Currently I'm hitting about 30K single-texture quads lit with 15 lights at about 450fps. I haven't learned instancing or geometry shading at all yet, and I'm trying to prioritise the order I learn things in for my needs, so I've only taken glances at them.</p>
<p>My first thought was to reduce the amount of vertex data being shunted to the GPU, so I changed the vertex structure to a FLOAT2 (for texture coords) and an UINT (for indexing), relying on 4x float3 constants in the vertex shader to define the corners of the quads.</p>
<p>I figured I could reduce the size of the vertex data further, and reduced each vertex unit to a single UINT containing a 2bit index (to reference the real vertexes of the quad), and 2x 15bit fixed-point numbers (yes, I'm showing my age but fixed-point still has it's value) representing offsets into atlas textures.</p>
<p>So far, so good, but I know bugger all about Direct3D11 and HLSL so I've been wondering if there's a faster way.</p>
<p>Here's the current state of my vertex shader:</p>
<pre><code>cbuffer CB_PROJ
{
matrix model;
matrix modelViewProj;
};
struct VOut
{
float3 position : POSITION;
float3 n : NORMAL;
float2 texcoord : TEXCOORD;
float4 pos : SV_Position;
};
static const float3 position[4] = { -0.5f, 0.0f,-0.5f,-0.5f, 0.0f, 0.5f, 0.5f, 0.0f,-0.5f, 0.5f, 0.0f, 0.5f };
// Index bitpattern: YYYYYYYYYYYYYYYXXXXXXXXXXXXXXXVV
//
// 00-01 . uint2b == Vertex index (0-3)
// 02-17 . fixed1p14 == X offset into atlas texture(s)
// 18-31 . fixed1p14 == Y offset into atlas texture(s)
//
VOut main(uint bitField : BLENDINDICES) {
VOut output;
const uint i = bitField & 0x03u;
const uint xStep = (bitField >> 2) & 0x7FFFu;
const uint yStep = (bitField >> 17);
const float xDelta = float(xStep) * 0.00006103515625f;
const float yDelta = float(yStep) * 0.00006103515625f;
const float2 texCoord = float2(xDelta, yDelta);
output.position = (float3) mul(float4(position[i], 1.0f), model);
output.n = mul(float3(0.0f, 1.0f, 0.0f), (float3x3) model);
output.texcoord = texCoord;
output.pos = mul(float4(output.position, 1.0f), modelViewProj);
return output;
}
</code></pre>
<p>My pixel shader for completeness:</p>
<pre><code>Texture2D Texture : register(t0);
SamplerState Sampler : register(s0);
struct LIGHT {
float4 lightPos; // .w == range
float4 lightCol; // .a == flags
};
cbuffer cbLight {
LIGHT l[16] : register(b0); // 256 bytes
}
static const float3 ambient = { 0.15f, 0.15f, 0.15f };
float4 main(float3 position : POSITION, float3 n : NORMAL, float2 TexCoord : TEXCOORD) : SV_Target
{
const float4 Texel = Texture.Sample(Sampler, TexCoord);
if (Texel.a < 0.707106f) discard; // My source images have their alpha values inverted.
float3 result = { 0.0f, 0.0f, 0.0f };
for (uint xx = 0 ; xx < 16 && l[xx].lightCol.a != 0xFFFFFFFF; xx++)
{
const float3 lCol = l[xx].lightCol.rgb;
const float range = l[xx].lightPos.w;
const float3 vToL = l[xx].lightPos.xyz - position;
const float distToL = length(vToL);
if (distToL < range * 2.0f)
{
const float att = min(1.0f, (distToL / range + distToL / (range * range)) * 0.5f);
const float3 lum = Texel.rgb * saturate(dot(vToL / distToL, n)) * lCol;
result += lum * (1.0f - att);
}
}
return float4(ambient * Texel.rgb + result, Texel.a);
}
</code></pre>
<p>And the rather busy looking C function to generate the vertex data (all non-relevant functions removed):</p>
<pre class="lang-c prettyprint-override"><code>al16 struct CLASS_PRIMITIVES {
ID3D11Buffer* pVB = { NULL, NULL }, * pIB = { NULL, NULL };
const UINT strideV1 = sizeof(VERTEX1);
void CreateQuadSet1(ui32 xSegs, ui32 ySegs) {
al16 VERTEX1* vBuf;
al16 D3D11_BUFFER_DESC bd = {};
D3D11_SUBRESOURCE_DATA srd = {};
ui32 index = 0, totalVerts = xSegs * ySegs * 4;
if (pVB) return;
vBuf = (VERTEX1*)_aligned_malloc(strideV1 * totalVerts, 16);
for (ui32 yy = ySegs; yy; yy--)
for (ui32 xx = 0; xx < xSegs; xx++) {
double dyStep2 = 16384.0 / double(ySegs); double dyStep1 = dyStep2 * double(yy); dyStep2 *= double(yy - 1);
ui32 yStep1 = dyStep1;
yStep1 <<= 17;
ui32 yStep2 = dyStep2;
yStep2 <<= 17;
vBuf[index].b = 0 + (ui32(double(16384.0 / double(xSegs) * double(xx))) << 2) + yStep1;
index++;
vBuf[index].b = 1 + (ui32(double(16384.0 / double(xSegs) * double(xx))) << 2) + yStep2;
index++;
vBuf[index].b = 2 + (ui32(double(16384.0 / double(xSegs) * double(xx + 1))) << 2) + yStep1;
index++;
vBuf[index].b = 3 + (ui32(double(16384.0 / double(xSegs) * double(xx + 1))) << 2) + yStep2;
index++;
}
bd.Usage = D3D11_USAGE_IMMUTABLE;
bd.BindFlags = D3D11_BIND_VERTEX_BUFFER;
bd.CPUAccessFlags = 0;
bd.ByteWidth = strideV1 * totalVerts;
bd.StructureByteStride = strideV1;
srd.pSysMem = vBuf;
hr = dev->CreateBuffer(&bd, &srd, &pVB);
if (hr != S_OK) ThrowError();
_aligned_free(vBuf);
};
void DrawQuadFromSet1(ui32 offset) {
offset *= sizeof(VERTEX1) * 4;
devcon->IASetVertexBuffers(0, 1, &pVB, &strideV1, &offset);
devcon->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP);
devcon->Draw(4, 0);
};
void DestroyQuadSet() {
if (pVB) pVB->Release();
};
</code></pre>
<p>It's all functioning as it should, but it just seems like I'm resorting to hacks to achieve my goal. Surely there's a faster way? Using DrawIndexed() consistently dropped the frame-rate by 1% so I switched back to non-indexed Draw calls.</p>
| [
{
"answer_id": 74195959,
"author": "Blindy",
"author_id": 108796,
"author_profile": "https://Stackoverflow.com/users/108796",
"pm_score": 2,
"selected": false,
"text": "clamp"
},
{
"answer_id": 74208244,
"author": "Soonts",
"author_id": 126995,
"author_profile": "http... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74195355",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20330556/"
] |
74,195,360 | <p>I'm building a web app using Node, Express, Cors and Body Parser. The app uses the fetch api to fetch data from online apis. Now I have written all the code with a server.js file, an index.html and an app.js. My server.js file contains the express server functions and middleware. My app.js contains the main functionality. Here are my files:</p>
<p>Index.html:</p>
<pre><code><!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Weather Journal</title>
</head>
<body>
<div id="app">
<div class="holder headline">
Weather Journal App
</div>
<form id="userInfo">
<div class="holder zip">
<label for="zip">Enter City here</label>
<input type="text" id="city" placeholder="enter city here" required>
</div>
<div class="holder feel">
<label for="date">Enter departure date</label>
<input type="datetime-local" id="date" required>
<button id="submitBtn" type="submit"> Generate </button>
</div>
</form>
<div class="holder entry">
<div class="title">Most Recent Entry</div>
<div id="entryHolder">
<div id="lat"></div>
<div id="lng"></div>
<div id="countryName"></div>
<div id="temp"></div>
</div>
</div>
</div>
<script src="app.js" type="text/javascript"></script>
</body>
</html>
</code></pre>
<p>My app.js:</p>
<pre><code>const geoURL = "http://api.geonames.org/searchJSON?";
const geoUsername = `rohanasif1990`;
const weatherURL = "https://api.weatherbit.io/v2.0/forecast/daily?"
const weatherKey = "20028a8267a24bba9a807362767bc4a7"
let d = new Date();
let newDate = d.getMonth() + 1 + "." + d.getDate() + "." + d.getFullYear();
const submitBtn = document.getElementById("submitBtn");
submitBtn.addEventListener("click", (e) => {
e.preventDefault();
const city = document.getElementById("city").value;
if (city !== "") {
getCity(geoURL, city, geoUsername)
.then(function (data) {
getWeather(weatherURL, weatherKey, data["geonames"][0]['lat'], data["geonames"][0]['lng'])
}).then(weatherData => {
postWeatherData("/addWeather", { temp: weatherData })
}).then(function () {
receiveWeatherData()
}).catch(function (error) {
console.log(error);
alert("Invalid city");
})
}
})
const getCity = async (geoURL, city, geoUsername) => {
const res = await fetch(`${geoURL}q=${city}&username=${geoUsername}`);
try {
const cityData = await res.json();
return cityData;
}
catch (error) {
console.log("error", error);
}
}
const postWeatherData = async (url = "", data = {}) => {
const response = await fetch(url, {
method: "POST",
credentials: "same-origin",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
temp: data.temp
})
});
try {
const newData = await response.json();
return newData;
}
catch (error) {
console.log(error);
}
}
const receiveWeatherData = async () => {
const request = await fetch("/allWeather");
try {
const allData = await request.json()
document.getElementById("temp").innerHTML = allData.temp;
}
catch (error) {
console.log("error", error)
}
}
const getWeather = async (weatherURL, weatherKey, lat, lon) => {
const res = await fetch(`${weatherURL}&lat=${lat}&lon=${lon}&key=${weatherKey}`);
try {
const weatherData = await res.json();
return weatherData;
}
catch (error) {
console.log("error", error);
}
}
</code></pre>
<p>My server.js:</p>
<pre><code>// Setup empty JS object to act as endpoint for all routes
cityData = {};
weatherData = {};
picturesData = {};
// Require Express to run server and routes
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
// Start up an instance of app
const app = express();
/* Middleware*/
//Here we are configuring express to use body-parser as middle-ware.
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
// Cors for cross origin allowance
app.use(cors())
// Initialize the main project folder
app.use(express.static('website'));
app.get("/all", function sendData(req, res) {
res.send(cityData);
})
app.get("/allWeather", function sendWeather(req, res) {
res.send(weatherData);
})
app.get("allPictures", function sendPictures(req, res) {
res.send(picturesData);
})
app.post("/add", (req, res) => {
projectData['lat'] = req.body.lat;
projectData['lng'] = req.body.lng;
projectData['countryName'] = req.body.countryName
res.send(cityData);
})
app.post("/addWeather", (req, res) => {
weatherData['temp'] = req.body.temp;
res.send(weatherData);
})
app.post("/addPicture", (req, res) => {
picturesData['pic'] = req.body.pic;
res.send(picturesData);
})
// Setup Server
app.listen(3000, () => {
console.log("App listening on port 3000")
console.log("Go to http://localhost:3000")
})
</code></pre>
<p>I am trying to get the geonames api to fetch the latitude and longitude of a city . Then I want to use the latitude and longitude to fetch the weather for that location. The pictures api is not implemented yet. I just want to use the data fetched from one api (geonames.org) as input to the other api (weatherbit.io). Right the app returns undefined when I console.log the final data.</p>
| [
{
"answer_id": 74195959,
"author": "Blindy",
"author_id": 108796,
"author_profile": "https://Stackoverflow.com/users/108796",
"pm_score": 2,
"selected": false,
"text": "clamp"
},
{
"answer_id": 74208244,
"author": "Soonts",
"author_id": 126995,
"author_profile": "http... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74195360",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15218468/"
] |
74,195,366 | <p>In my app, I need to get some data and storage them and finally show them in graph. So, I have defined some class as follows:</p>
<pre><code>class DurationTime {
StatisticalParam p24H;
StatisticalParam p1W;
StatisticalParam p1M;
StatisticalParam p1GD;
DurationTime(this.p24H,this.p1W,this.p1M,this.p1GD);// to create getter : Alt+Insert
factory DurationTime.fromMap(Map data) => DurationTime(data['p24H'],data['p1W'],data['p1M'],data['p1G']);
}
class StatisticalParam {
TimeValuePair max;
TimeValuePair min;
TimeValuePair avg;
TimeValuePair latest;
List<TimeValuePair> timeSeriesData = List<TimeValuePair>.filled(5760,TimeValuePair(0,0));//<TimeValuePair>[];
StatisticalParam(this.min,this.max,this.avg,this.latest,this.timeSeriesData);
factory StatisticalParam.fromMap(Map data) => StatisticalParam(data['max'],data['min'],data['avg'],data['latest'],data['timeSeriesData']);
}
class TimeValuePair{
TimeValuePair(this.value,this.time);
double value;
double time;
factory TimeValuePair.fromMap(Map data) => TimeValuePair(data['value'],data['time']);
}
</code></pre>
<p><code>Then I defined a list with name of instDevice, and initialize it as follow:</code></p>
<pre><code>List<DurationTime> instDevice = List<DurationTime>.filled(11,
DurationTime(StatisticalParam(TimeValuePair(0,0), TimeValuePair(0,0), TimeValuePair(0,0), TimeValuePair(0,0),List<TimeValuePair>.filled(5760,TimeValuePair(0,0))),
StatisticalParam(TimeValuePair(0,0), TimeValuePair(0,0), TimeValuePair(0,0), TimeValuePair(0,0),List<TimeValuePair>.filled(5760,TimeValuePair(0,0))),
StatisticalParam(TimeValuePair(0,0), TimeValuePair(0,0), TimeValuePair(0,0),TimeValuePair(0,0),List<TimeValuePair>.filled(5760,TimeValuePair(0,0))),
StatisticalParam(TimeValuePair(0,0), TimeValuePair(0,0), TimeValuePair(0,0),TimeValuePair(0,0),List<TimeValuePair>.filled(5760,TimeValuePair(0,0)))));
</code></pre>
<p>When I want to assign value to
<code>instDevice.elementAt(Index).p24H.latest.value</code>
for <code>Index=1</code>, it is changing for all <code>Index=0</code> to <code>11</code> not only <code>Index=1</code>!!
Please let me know, how I can set <code>instDevice.elementAt(Index).p24H.latest.value</code> for special <code>Index</code>?</p>
<p>Please let me know, how I can set <code>instDevice.elementAt(Index).p24H.latest.value</code> for special <code>Index</code>?</p>
| [
{
"answer_id": 74195959,
"author": "Blindy",
"author_id": 108796,
"author_profile": "https://Stackoverflow.com/users/108796",
"pm_score": 2,
"selected": false,
"text": "clamp"
},
{
"answer_id": 74208244,
"author": "Soonts",
"author_id": 126995,
"author_profile": "http... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74195366",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19524487/"
] |
74,195,370 | <p>Hello so im new on python, i want to know how to do multiple string input on list. I already try to append the input to the list, but it doesn't give me expected output. Here is the source code:</p>
<pre><code>test=[]
input1=input("Enter multiple strings: ")
splitinput1=input1.split()
for x in range(len(splitinput1)):
test.append(splitinput1)
print(test)
print(len(test))
</code></pre>
<p>And the output is not what i expected:</p>
<pre><code>Enter multiple strings: A B C
[['A', 'B', 'C'], ['A', 'B', 'C'], ['A', 'B', 'C']]
3
</code></pre>
<p>However, when i change to <code>print(splitinput1)</code>, it give me expected output:</p>
<pre><code>Enter multiple strings: A B C
['A', 'B', 'C']
3
</code></pre>
<p>So how to make the output like <code>print(splitinput1)</code> while use <code>print(test)</code> and whats missing on my code? Thankyou.</p>
| [
{
"answer_id": 74195959,
"author": "Blindy",
"author_id": 108796,
"author_profile": "https://Stackoverflow.com/users/108796",
"pm_score": 2,
"selected": false,
"text": "clamp"
},
{
"answer_id": 74208244,
"author": "Soonts",
"author_id": 126995,
"author_profile": "http... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74195370",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19363291/"
] |
74,195,390 | <p>I am new to the JQ Library and I cannot figure out how to replace values in config_new.json with values from keys that exist in both config.json and config_new.json, recursively, without copying any other attributes from config.json.</p>
<p>Basically having:</p>
<pre><code>// config_new.json
{
"name": "testName",
"age": "tooOld",
"properties": {
"title": "Mr",
"fruits": ["apple", "banana"]
},
}
</code></pre>
<pre><code>// config.json
{
"newName": "changedName",
"age": "tooYoung",
"properties": {
"title": "Mr",
"height": "tooTall",
"fruits": ["banana"]
},
"certificate": "present"
}
</code></pre>
<pre><code>// expected result
{
"name": "testName",
"age": "tooYoung",
"properties": {
"title": "Mr",
"height": "tooTall",
"fruits": ["banana"]
},
}
</code></pre>
<p>So I am trying to override the values in config_new.json only with known values in config.json.</p>
<p>I have tried using</p>
<pre><code>jq -s '.[0] * .[1]' config_new.json config.json
</code></pre>
<p>but this works only partially, because it also copies the key-value pairs that do not exist in config_new.json:</p>
<pre><code>{
"name": "testName",
"newName": "changedName", // This should not be here
"age": "tooYoung", // This was replaced from config.json
"properties": {
"title": "Mr",
"height": "tooTall", // This should not be here
"fruits": ["banana"]
},
}
</code></pre>
<p>Could someone help me?</p>
| [
{
"answer_id": 74196460,
"author": "knittl",
"author_id": 112968,
"author_profile": "https://Stackoverflow.com/users/112968",
"pm_score": 1,
"selected": false,
"text": "config_new.jq"
},
{
"answer_id": 74197668,
"author": "glenn jackman",
"author_id": 7552,
"author_pr... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74195390",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20330911/"
] |
74,195,409 | <p>Suppose I have the following data frame:</p>
<pre><code>> survey
workshop gender q1 q2 q3 q4
1 R Female 4 3 4 5
2 SPSS Male 3 4 3 4
3 <NA> <NA> 3 2 NA 3
4 SPSS Female 5 4 5 3
5 STATA Female 4 4 3 4
6 SPSS Female 5 4 3 5
</code></pre>
<p>I would like to change "Female" to "F" and change "Male" to "M". Of course I can remake a column of c(F,M,,F,F,F), but is it possible to set a command function take "female" and "male" as inputs and outputs "F" and "M"?</p>
| [
{
"answer_id": 74196460,
"author": "knittl",
"author_id": 112968,
"author_profile": "https://Stackoverflow.com/users/112968",
"pm_score": 1,
"selected": false,
"text": "config_new.jq"
},
{
"answer_id": 74197668,
"author": "glenn jackman",
"author_id": 7552,
"author_pr... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74195409",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20154643/"
] |
74,195,436 | <p>I am trying to make my user model not care about case sensitivity in <code>email</code> and <code>username</code> fields. So if I try to create a user with email <code>Thisemail@email.com</code> and another one with <code>thisemail@email.com</code>, the second time it is not allowed, since the email is not unique, despite the upper case and lowercases.</p>
<p>My user schema is the following:</p>
<pre><code>const UserSchema = new mongoose.Schema({
email: {
type: String,
unique: true,
required: true,
validate: // validators here,
},
username: {
type: String,
unique: true,
required: true,
validate: // validators here,
},
// Some other fields not case insensitive
});
</code></pre>
<p>The users are created with mongoose create function:</p>
<pre><code>user = await User.create(userData)
</code></pre>
<p>I have tried creating a collation and it works with the <code>find</code> command directly on mongo shell.</p>
<pre><code>db.users.createIndex({'email': 1}, {'collation': { 'locale': 'en', 'strength': 2}, 'name': 'testcollation'})
db.users.find({'email':'thisemail@email.com'}).collation({'locale':'en', 'strength': 2})
</code></pre>
<p>But when I try to append the collation to the create call, I get an error message saying collation function does not exist.</p>
<pre><code>user = await User.create(userData).collation({ "locale": "en", "strength": 2 });
</code></pre>
<p>Following this link, <a href="https://mongoosejs.com/docs/api.html#query_Query-collation" rel="nofollow noreferrer">https://mongoosejs.com/docs/api.html#query_Query-collation</a>, I would expect this to work:</p>
<pre><code>User.create(...).collation is not a function
</code></pre>
<p>Any idea how to run the collation with the create function?</p>
| [
{
"answer_id": 74225304,
"author": "Someone Special",
"author_id": 2822041,
"author_profile": "https://Stackoverflow.com/users/2822041",
"pm_score": 1,
"selected": false,
"text": "find"
},
{
"answer_id": 74225850,
"author": "Tim",
"author_id": 20317091,
"author_profil... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74195436",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3770881/"
] |
74,195,493 | <p>I have locally deployed the <strong>nexus repository</strong> for <strong>maven-snapshots</strong>.
I has a spring boot application (java).</p>
<p>I need to publish some projects to this repository, and then connect these libraries to other projects using the nexus repository.</p>
<ul>
<li>gradle version</li>
</ul>
<pre class="lang-yaml prettyprint-override"><code>------------------------------------------------------------
Gradle 7.5.1
------------------------------------------------------------
Build time: 2022-08-05 21:17:56 UTC
Revision: d1daa0cbf1a0103000b71484e1dbfe096e095918
Kotlin: 1.6.21
Groovy: 3.0.10
Ant: Apache Ant(TM) version 1.10.11 compiled on July 10 2021
JVM: 17.0.2 (Oracle Corporation 17.0.2+8-86)
</code></pre>
<ul>
<li>published artifact</li>
</ul>
<p><strong>gradle.buid</strong></p>
<pre class="lang-yaml prettyprint-override"><code>plugins {
id 'org.springframework.boot' version '2.7.5'
id 'io.spring.dependency-management' version '1.0.14.RELEASE'
id 'java'
}
group = 'com.model'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '17'
configurations {
compileOnly {
extendsFrom annotationProcessor
}
}
repositories {
mavenCentral()
maven {
url "http://localhost:8081/repository/model-snapshot/"
setAllowInsecureProtocol(true);
}
}
ext {
springJacksonVersion = "2.13.4"
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
implementation 'com.fasterxml.jackson.core:jackson-annotations:' + springJacksonVersion
compileOnly 'org.projectlombok:lombok'
annotationProcessor 'org.springframework.boot:spring-boot-configuration-processor'
annotationProcessor 'org.projectlombok:lombok'
}
publishing {
repositories {
mavenDeployer {
repository(url: "http://localhost:8081/repository/model-snapshot/") {
authentication(userName: "user", password: "1")
setAllowInsecureProtocol(true);
}
pom.version = "1.0-SNAPSHOT"
pom.artifactId = "m-entities"
pom.groupId = "com.model"
}
}
}
</code></pre>
<blockquote>
<ul>
<li>Exception is:
org.gradle.api.GradleScriptException: A problem occurred evaluating project ':m-entities'.
....
Caused by: org.gradle.internal.metaobject.AbstractDynamicObject$CustomMessageMissingMethodException: Could not find method publishing() for arguments [build_7pz2gcbsao2wyri8rdvmjwrzm$_run_closure5@482a5d97] on project ':m-entities' of type org.gradle.api.Project.
at org.gradle.internal.metaobject.AbstractDynamicObject$CustomMissingMethodExecutionFailed.(AbstractDynamicObject.java:190)
at org.gradle.internal.metaobject.AbstractDynamicObject.methodMissingException(AbstractDynamicObject.java:184)
at org.gradle.groovy.scripts.BasicScript$ScriptDynamicObject.methodMissingException(BasicScript.java:162)
at org.gradle.internal.metaobject.AbstractDynamicObject.invokeMethod(AbstractDynamicObject.java:167)
at org.gradle.groovy.scripts.BasicScript.invokeMethod(BasicScript.java:84)
at build_7pz2gcbsao2wyri8rdvmjwrzm.run</li>
</ul>
</blockquote>
<ul>
<li>the project in which the <strong>library</strong> is connected, which should be published in the nexus repository</li>
</ul>
<p><strong>gradle.build</strong></p>
<pre class="lang-yaml prettyprint-override"><code>plugins {
id 'org.springframework.boot' version '2.7.5'
id 'io.spring.dependency-management' version '1.0.15.RELEASE'
id 'java'
}
group = 'com.model'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '17'
configurations {
compileOnly {
extendsFrom annotationProcessor
}
}
repositories {
mavenCentral()
maven {
name 'm-shapshot'
url "http://localhost:8081/repository/model-snapshot/"
setAllowInsecureProtocol(true)
credentials {
username project.repoUser
password project.repoPassword
}}
}
ext {
set('springCloudVersion', "2021.0.4")
set('testcontainersVersion', "1.17.4")
mapStructVersion = '1.5.3.Final'
mEntitiesVersion = '0.0.1-SNAPSHOT'
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
implementation 'com.model:m-entities:0.0.1-SNAPSHOT'
compileOnly 'org.projectlombok:lombok'
runtimeOnly 'org.postgresql:postgresql'
annotationProcessor 'org.springframework.boot:spring-boot-configuration-processor'
annotationProcessor 'org.projectlombok:lombok'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
testImplementation 'org.testcontainers:junit-jupiter'
testImplementation 'org.testcontainers:postgresql'
}
dependencyManagement {
imports {
mavenBom "org.testcontainers:testcontainers-bom:${testcontainersVersion}"
mavenBom "org.springframework.cloud:spring-cloud-dependencies:${springCloudVersion}"
}
}
tasks.named('test') {
useJUnitPlatform()
}
</code></pre>
<ul>
<li>gradle.properties</li>
</ul>
<pre class="lang-yaml prettyprint-override"><code>repoUser=user
repoPassword=1
</code></pre>
<blockquote>
<p>Could not GET 'http://localhost:8081/repository/model-snapshot/com/model/m-entities/0.0.1-SNAPSHOT/maven-metadata.xml'. Received status code 401 from server: Unauthorized
Disable Gradle 'offline mode' and sync project</p>
</blockquote>
<p>Does anyone have any ideas on how to configure uploading artifacts to the local nexus repository and using this repository to get the artifacts published there ?</p>
| [
{
"answer_id": 74225304,
"author": "Someone Special",
"author_id": 2822041,
"author_profile": "https://Stackoverflow.com/users/2822041",
"pm_score": 1,
"selected": false,
"text": "find"
},
{
"answer_id": 74225850,
"author": "Tim",
"author_id": 20317091,
"author_profil... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74195493",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12093975/"
] |
74,195,498 | <p>I have a an image directory I have loaded into a dataframe with annotations coordinates, I am trying to crop the images according to the coordinates (xmin, xmax, ymin, ymax) and save them into a new dataframe but keep getting an error.</p>
<p>This is the code I have so far:</p>
<p>Here is the df I have</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>File_Path</th>
<th>xmin</th>
<th>xmax</th>
<th>ymin</th>
<th>ymax</th>
<th>filename</th>
</tr>
</thead>
<tbody>
<tr>
<td>/MyDrive/Brand_Logos/img1.jpg</td>
<td>100</td>
<td>200</td>
<td>100</td>
<td>200</td>
<td>img1.jpg</td>
</tr>
<tr>
<td>/MyDrive/Brand_Logos/img2.jpg</td>
<td>200</td>
<td>300</td>
<td>200</td>
<td>300</td>
<td>img2.jpg</td>
</tr>
<tr>
<td>/MyDrive/Brand_Logos/img3.jpg</td>
<td>200</td>
<td>300</td>
<td>200</td>
<td>300</td>
<td>img3.jpg</td>
</tr>
</tbody>
</table>
</div>
<p>here is the code I am trying to use to parse all the files and save them to a new directory</p>
<pre><code>import pandas as pd
import os
import cv2
df = pd.read_csv('annotations.csv')
src_path = '/MyDrive/Brand_Logos/'
if not os.path.exists(os.path.join(src_path,'imageProcessDir')):
os.mkdir(os.path.join(src_path,'imageProcessDir'))
dest_path = src_path+'imageProcessDir'
for index, row in df.iterrows():
filename = row['filename']
xmin = row['xmin']
xmax = row['xmax']
ymin = row['ymin']
ymax = row['ymax']
xmin = int(xmin)
xmax = int(xmax)
ymin = int(ymin)
ymax = int(ymax)
image = cv2.imread(src_path+row['filename'])
crop = image((xmin, ymin), (xmax, ymax))
cv2.imwrite(dest_path+"/"+filename+ "_" +'cropped'+".jpg", crop)
</code></pre>
<p>I have a feeling that the cv2 or the crop variable are not working properly, what am I missing?</p>
| [
{
"answer_id": 74225304,
"author": "Someone Special",
"author_id": 2822041,
"author_profile": "https://Stackoverflow.com/users/2822041",
"pm_score": 1,
"selected": false,
"text": "find"
},
{
"answer_id": 74225850,
"author": "Tim",
"author_id": 20317091,
"author_profil... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74195498",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18964980/"
] |
74,195,519 | <p>This is the html of what I want to hide</p>
<pre><code><div class="count">
<div class="number">1</div>
<div class="text">donation</div>
</div>
</code></pre>
<p>I've tried to use the CSS code:</p>
<pre><code>.count {
display: none;
}
</code></pre>
<p>As well as:</p>
<pre><code>body.page-id-750 div.count {
display: none;
}
</code></pre>
<p>For ref the body is:</p>
<pre><code><body itemtype="https://schema.org/WebPage" itemscope="itemscope" class="page-template-default page page-id-750 logged-in admin-bar wp-custom-logo ast-single-post ast-mobile-inherit-site-logo ast-inherit-site-logo-transparent ast-theme-transparent-header ast-hfb-header ast-page-builder-template ast-no-sidebar astra-3.9.2 elementor-default elementor-kit-442 elementor-page elementor-page-750 customize-support e--ua-blink e--ua-chrome e--ua-webkit ast-mouse-clicked ast-header-break-point"
</code></pre>
| [
{
"answer_id": 74195609,
"author": "Valentina Furnò",
"author_id": 18009438,
"author_profile": "https://Stackoverflow.com/users/18009438",
"pm_score": 1,
"selected": false,
"text": ".count {\n display: none!important;\n}\n\nbody.page-id-750 div.count {\n display: none!important;\n}\n"
... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74195519",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20330206/"
] |
74,195,534 | <p>I have the following HTML form:</p>
<p>I am wanting to have fields 1-3 shown as normal when a user visits the page. Fields 4 and 5 are additional non-mandatory for the form to submit, so I would like to hide these and show them when the user clicks a '+' image/button and have them drop down at the bottom of the form but above the submit button (sort of like a show advanced type thing).</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><form action="#" class="u-clearfix u-form-spacing-25 u-form-vertical u-inner-form" source="email" name="Netflow" style="padding: 10px;">
<div class="u-form-group u-form-name u-form-partition-factor-2">
<label for="field1" class="u-custom-font u-heading-font u-label u-text-body-alt-color u-label-1">field1</label>
<input type="text" placeholder="field1" id="name-26a2" name="text-1" class="u-border-1 u-border-custom-color-1 u-custom-font u-heading-font u-input u-input-rectangle u-radius-50 u-white u-input-1" required="">
</div>
<div class="u-form-email u-form-group u-form-partition-factor-2">
<label for="field2" class="u-custom-font u-heading-font u-label u-text-body-alt-color u-label-2">field2</label>
<input type="number" placeholder="field2" id="email-26a2" name="number" class="u-border-1 u-border-custom-color-1 u-custom-font u-heading-font u-input u-input-rectangle u-radius-50 u-white u-input-2" required="">
</div>
<div class="u-form-group u-form-partition-factor-2 u-form-group-5">
<label for="field3" class="u-custom-font u-heading-font u-label u-text-body-alt-color u-label-5">field3</label>
<input type="text" placeholder="field3" id="text-c578" name="number-1" class="u-border-1 u-border-custom-color-1 u-custom-font u-heading-font u-input u-input-rectangle u-radius-50 u-white u-input-5">
</div>
<div class="u-form-group u-form-partition-factor-2 u-form-group-6">
<label for="field4" class="u-custom-font u-heading-font u-label u-text-body-alt-color u-label-6">field4</label>
<input type="text" placeholder="field4" id="text-a09b" name="text" class="u-border-1 u-border-custom-color-1 u-custom-font u-heading-font u-input u-input-rectangle u-radius-50 u-white u-input-6">
</div>
<div class="u-form-group u-form-partition-factor-2 u-form-group-7">
<label for="field5" class="u-custom-font u-heading-font u-label u-text-body-alt-color u-label-7">field5</label>
<input type="text" placeholder="field5" id="text-414f" name="text-2" class="u-border-1 u-border-custom-color-1 u-custom-font u-heading-font u-input u-input-rectangle u-radius-50 u-white u-input-7">
</div>
<div class="u-align-left u-form-group u-form-submit">
<a href="#" class="u-btn u-btn-round u-btn-submit u-button-style u-custom-color-2 u-custom-font u-heading-font u-radius-50 u-btn-1">Submit</a>
<input type="submit" value="submit" class="u-form-control-hidden">
</div>
</form></code></pre>
</div>
</div>
</p>
<p>I have researched how to do this but couldn't find a clear answer. As far as I can tell I would need to use JavaScript to create the drop-down animation showing the additional fields.</p>
<p>If someone could provide me an example of how to achieve this or point me in the right direction with this simple HTML form I would really appreciate it, thanks!</p>
| [
{
"answer_id": 74195881,
"author": "Damodar Hegde",
"author_id": 14873577,
"author_profile": "https://Stackoverflow.com/users/14873577",
"pm_score": 1,
"selected": false,
"text": "<html>\n\n<head>\n <script>\n window.onload = function () {\n\n const btn = document.ge... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74195534",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
74,195,577 | <p>Versions:</p>
<ul>
<li>Python: 3.10.4</li>
<li>Pylint: 2.15.3</li>
<li>Visual Studio Code: 1.72.2</li>
</ul>
<p>The <code>.pylintrc</code> file was generated using</p>
<pre><code>pylint --generate-rcfile
</code></pre>
<p>command.</p>
<p>It has the following option configured:</p>
<pre><code>[METHOD_ARGS]
# List of qualified names (i.e., library.method) which require a timeout
# parameter e.g. 'requests.api.get,requests.api.post'
timeout-methods=requests.api.delete,requests.api.get,requests.api.head,requests.api.options,requests.api.patch,requests.api.post,requests.api.put,requests.api.request
</code></pre>
<p>However I see an error which sounds:</p>
<pre><code>Unrecognized option found: timeout-methods Pylint(E0015:unrecognized-option)
</code></pre>
<p>The documentation states that option <code>timeout-methods</code> is supported: <a href="https://pylint.pycqa.org/en/latest/user_guide/configuration/all-options.html#timeout-methods" rel="nofollow noreferrer">https://pylint.pycqa.org/en/latest/user_guide/configuration/all-options.html#timeout-methods</a>.</p>
<p>So I am lost why do I have that error displayed by pylint in visual studio code.</p>
| [
{
"answer_id": 74263028,
"author": "dudenr33",
"author_id": 4030694,
"author_profile": "https://Stackoverflow.com/users/4030694",
"pm_score": 3,
"selected": true,
"text": "pylint"
}
] | 2022/10/25 | [
"https://Stackoverflow.com/questions/74195577",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2645644/"
] |
74,195,617 | <p>I recieve a JSON file from database in the c# client. Then I deserialize this JSON to an object of a class. Now when updated JSON arrives from database afterwards, what I want is to somehow replace every data of the old object with a new one. I need this because rest of code has many references to the old object and its properties, so simply assigning new object to old one would not work as all references would be lost. Is the only solution here performing a deep copy of the object? If so what is a best way to do this? Honestly I never needed anything like that for many years, I am quite surprised that this issue arise now but the reason is probably that I recieve dataj from database in JSON and have to someho deserialize it into new object.</p>
<p>The only solution I tried is manual copying of the fields betwee new and old object but its a pain to keep it updated whenever I change the class structure which I do a lot</p>
| [
{
"answer_id": 74196131,
"author": "paulsm4",
"author_id": 421195,
"author_profile": "https://Stackoverflow.com/users/421195",
"pm_score": 1,
"selected": false,
"text": "public class MyWrapper\n{\n public MyDataClass MyData { get; set; }\n}\n\npublic class SomeClass\n{\n public voi... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74195617",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20046716/"
] |
74,195,659 | <blockquote>
<p>i am trying to write code using useState to toggle between on and off when clicking on button.</p>
</blockquote>
<pre><code>
const [isON, setIsON] = React.useState(true)
<button onClick={() => setIsON(!isON)}>{ isON ? console.log('ON') : console.log('off') } />
</code></pre>
<p>i used this <a href="https://www.folkstalk.com/2022/07/react-button-toggle-on-off-example.html" rel="nofollow noreferrer">website's</a> code, but when i use this in react i get syntax error</p>
| [
{
"answer_id": 74196131,
"author": "paulsm4",
"author_id": 421195,
"author_profile": "https://Stackoverflow.com/users/421195",
"pm_score": 1,
"selected": false,
"text": "public class MyWrapper\n{\n public MyDataClass MyData { get; set; }\n}\n\npublic class SomeClass\n{\n public voi... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74195659",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
74,195,666 | <p>I need to convert a string to decimal with specific format in C#. This string can be in different formats. For example it can be: <code>20</code> or <code>20.5</code>.</p>
<p>I need it to convert to <code>xx.xxx</code>. Is there is a method to do this?</p>
| [
{
"answer_id": 74195912,
"author": "n-azad",
"author_id": 5997281,
"author_profile": "https://Stackoverflow.com/users/5997281",
"pm_score": 1,
"selected": false,
"text": "string t = \"2020.5\";\n\nvar d = decimal.Parse(t).ToString(\"00.000\");\n"
},
{
"answer_id": 74195921,
"... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74195666",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11450029/"
] |
74,195,677 | <p>I've got a website that I want to test with cypress. This website is working with coordinates, which are stored in a global var.</p>
<p>I want to write a test that accesses these coordinates and checks if they are right.
Is there any way to do this with cypress?</p>
<p>I mean, there is a way to access the vars in the DevTools (Chrome) via the Console, so it should also be possible with cypress, right...?</p>
<p>Thanks for helping! <3</p>
<p>I searched on the web but did not find anything about this.
I tried (like in the chrome DevTools) to access the vars directly but it did not work...</p>
<p>Edit:
<strong>WAIT! im dumb...</strong></p>
<p>I did not realised that my "global" var is the same as the "window" var....
So, i now accessing it with the solution from @Nichola Walker</p>
| [
{
"answer_id": 74195912,
"author": "n-azad",
"author_id": 5997281,
"author_profile": "https://Stackoverflow.com/users/5997281",
"pm_score": 1,
"selected": false,
"text": "string t = \"2020.5\";\n\nvar d = decimal.Parse(t).ToString(\"00.000\");\n"
},
{
"answer_id": 74195921,
"... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74195677",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15243356/"
] |
74,195,752 | <p>Please can someone help me on how to make my react native app detect when a user swipes left or right? I already researched randomly but seem not to have a positive answer.</p>
<p>So any function or package that can help?</p>
<p>I am mapping through a list of objects and I want the user to view next object in array whenever he swipes ( just like on click ).</p>
<p>It works with onClick but I need it with swipes.</p>
| [
{
"answer_id": 74195912,
"author": "n-azad",
"author_id": 5997281,
"author_profile": "https://Stackoverflow.com/users/5997281",
"pm_score": 1,
"selected": false,
"text": "string t = \"2020.5\";\n\nvar d = decimal.Parse(t).ToString(\"00.000\");\n"
},
{
"answer_id": 74195921,
"... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74195752",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16786944/"
] |
74,195,812 | <p>When the user inputs the word that they want to see, and what line its in.
So the code is going to tell you what line its in.</p>
<pre class="lang-py prettyprint-override"><code>
userAns = input("Enter english word: ")
print("I will try to find that word now!\n\n")
found = False
count = 0
with open("english3.txt", "r+") as f:
for line in f:
count += 1
if userAns == line:
print(f"I found it! in line {count}\n")
found = True
break
else:
continue
if not found:
print("I did not find it!\n")
print("I looked in a 1.8 MB file also")
print("I will have a larger file soon too!")
print("The code may get some thngs wrong")
</code></pre>
<p>The first line of the file is "a" so when you enter "a".
It should say "found in line 1" or any other word that is within the file</p>
<p>any help would be nice</p>
<p><strong>NOTE</strong>
If you type "one" into it, it would say line 33, when its not line 33. The line CONTAINS the word and is not the actual word.</p>
<p>My code has that protection, and the <code>if userAns == line</code> is to help</p>
| [
{
"answer_id": 74195919,
"author": "Mark",
"author_id": 2203038,
"author_profile": "https://Stackoverflow.com/users/2203038",
"pm_score": 0,
"selected": false,
"text": "else continue"
},
{
"answer_id": 74195975,
"author": "Omer Dagry",
"author_id": 15010874,
"author_p... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74195812",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19157472/"
] |
74,195,818 | <p>When I run a job with the new Spring Batch 5 RC1, it comes always to the following error:</p>
<p>org.springframework.core.convert.ConverterNotFoundException: No converter found capable of converting from type [my.package.FileProvider] to type [java.lang.String]</p>
<p>So, it seems that I need to provide a <code>GenericConverter</code>. But the standard ways aren't working.</p>
<p>If I register them via:</p>
<pre><code> @Configuration
public class ConverterRegistration implements WebMvcConfigurer {
public void addFormatters(FormatterRegistry registry) {
registry.addConverter(new FileConverter<>());
registry.addConverterFactory(new FileConverterFactory());
}
}
</code></pre>
<p>it doesn't work. And even if I extend <code>DefaultBatchConfiguration</code> and set the converter in a <code>@PostConstruct</code> method with calls like <code>getConversionService().addConverter(new FileConverter())</code>,
my debugger shows that the list of converters stays always the same, at the point where the exception comes from: <code>GenericConversionService</code>. It seems that the Jobs have their own local list of converters. A first stop at a breakpoint shows that <code>GenericConversionService</code> has 129 converters, including my custom ones, and at a later stop, when the exceptions gets thrown, it has always 52 converters.</p>
<p>How do I add a converter there?</p>
<p>At the JobBuilder?</p>
<pre><code> return new JobBuilder(JOB_IMPORT, jobRepository)
.incrementer(new RunIdIncrementer())
.start(infoImport)
.end()
.build();
</code></pre>
<p>At the step builder?</p>
<pre><code> new StepBuilder(getStepName(), jobRepository)
.<I, O>chunk(chunkSize, platformTransactionManager)
.listener(readListener)
.reader(reader)
.processor(processor)
.writer(writer)
</code></pre>
<p>Most likely the job parameters, but how?</p>
<pre><code> JobParameters jobParameters = new JobParametersBuilder()
.addJobParameter(FILE_PROVIDER,
new JobParameter<>(fileProvider, FileProvider.class))
.addString(INFO_FILE_NAME, fileInfo)
.toJobParameters();
jobLauncher.run(fileImportJob, jobParameters);
</code></pre>
<p>Can somebody show me where and how I can set my custom <code>GenericConverter</code>?
Or is it somehow a <code>JobParametersConverter</code> which is needed, but then: How to set <em>that</em>
(the documentation at <a href="https://docs.spring.io/spring-batch/docs/5.0.0-RC1/reference/html/job.html#javaConfig/html/job.html#javaConfig" rel="nofollow noreferrer">Spring Batch 5 RC1, Java Config</a> seems incomplete)?</p>
| [
{
"answer_id": 74196062,
"author": "Mahmoud Ben Hassine",
"author_id": 5019386,
"author_profile": "https://Stackoverflow.com/users/5019386",
"pm_score": 2,
"selected": true,
"text": "WebMvcConfigurer"
},
{
"answer_id": 74196215,
"author": "Jan",
"author_id": 1534698,
... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74195818",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1534698/"
] |
74,195,873 | <p>I am doing e2e testing with Cypress <code>version 10.9.0</code> and using <a href="https://www.npmjs.com/package/cypress-cucumber-preprocessor" rel="nofollow noreferrer">this cypress-cucumber-preprocessor</a></p>
<pre class="lang-js prettyprint-override"><code>Given('I am at the portal login page', () => {
cy.visit(Cypress.env("newPortalWeb_login"), { timeout: 100000 });
})
When('I enter an invalid username on the login page', () => {
cy.get('#username').type('portal').invoke('removeAttr', 'value').click({ force: true }, { timeout: 30000 })
cy.get('#password').type('SwY66bc3VZLUFR9')
cy.get('[type="submit"]').click()
})
Then('an error message is displayed with the text Invalid username/password', () => {
cy.get(".invalid").should('contain.text', 'Invalid username/password')
})
When('I enter an invalid password on the login page', () => {
cy.get('#username').type('portaluser')
cy.get('#password').type('Srntrhn$')
cy.get('[type="submit"]').click()
})
</code></pre>
<pre><code>Feature: Login
Scenario: #1 Test Invalid Username / Invalid Password / Empty Username / Valid Username and Empty Password
Given I am at the portal login page
When I enter an invalid username on the login page
Then an error message is displayed with the text Invalid username/password
When I enter an invalid password on the login page
Then an error message is displayed with the text Invalid username/password
When I enter a valid username with an empty password on the login page
Then an error message is displayed with the text Please enter your password
When I enter an empty username with a valid password on the login page
Then an error message is displayed with the text Please enter your username
When I enter an empty username with an empty password on the login page
Then an error message is displayed with the text Please enter your username
And an error message is displayed with the text Please enter your password
</code></pre>
<p>There is step implementation but still getting the error that says step impl is missing. Can someone assist me please? Thank you
<a href="https://i.stack.imgur.com/5PYUJ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/5PYUJ.png" alt="SS of Cypress Error" /></a></p>
| [
{
"answer_id": 74201320,
"author": "Amit Kahlon",
"author_id": 13508689,
"author_profile": "https://Stackoverflow.com/users/13508689",
"pm_score": 0,
"selected": false,
"text": "cy.get('#username').type('portal').invoke('removeAttr', 'value')\n.click({ force: true }, { timeout: 30000 })\... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74195873",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20303047/"
] |
74,195,878 | <p>I am trying to pull a list of products from an REST api to show up in a dropdown. Here is my code:</p>
<pre><code>import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:gateway_device/backend/api/api_services.dart';
import 'package:gateway_device/flutter_flow/flutter_flow_theme.dart';
import 'package:gateway_device/models/products_list_model.dart';
import 'package:gateway_device/routes/route_helper.dart';
import 'package:get/get.dart';
class EditDevicePortWidget extends StatefulWidget {
final String deviceId;
final String portId;
final String publicId;
final String label;
const EditDevicePortWidget(
{Key? key,
required this.deviceId,
required this.portId,
required this.publicId,
required this.label})
: super(key: key);
@override
State<EditDevicePortWidget> createState() =>
_EditDevicePortWidgetState(deviceId, portId, publicId, label);
}
class _EditDevicePortWidgetState extends State<EditDevicePortWidget> {
final String deviceId;
final String portId;
final String publicId;
final String label;
late String dropDownValueSelected = '';
Future<List<TankProduct>> dropDownProduct = ApiService().getAllProducts();
late TextEditingController textController1 = TextEditingController();
late TextEditingController textController2 = TextEditingController();
late TextEditingController textController3 = TextEditingController();
late TextEditingController textController4 = TextEditingController();
@override
void initState() {
super.initState();
String dropDownValueSelected = '';
textController1.text = '';
textController2.text = '';
textController3.text = '';
textController4.text = '';
}
_EditDevicePortWidgetState(
this.deviceId, this.portId, this.publicId, this.label);
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.white,
appBar: AppBar(
title: Text(
publicId + ' - ' + label,
style: FlutterFlowTheme.of(context).bodyText1.override(
fontFamily: 'Heebo',
fontSize: 18,
fontWeight: FontWeight.w500,
),
),
centerTitle: true,
elevation: 0,
backgroundColor: Colors.white,
automaticallyImplyLeading: false,
actions: [
IconButton(
hoverColor: Colors.transparent,
// borderRadius: 30,
// borderWidth: 1,
iconSize: 40,
icon: Icon(
Icons.close,
color: Colors.black,
size: 30,
),
onPressed: () {
Get.offNamed(RouteHelper.getPortProfile(
deviceId, portId, publicId, label));
},
),
],
iconTheme: IconThemeData(color: Colors.black),
),
body: SafeArea(
child: Container(
width: MediaQuery.of(context).size.width,
height: MediaQuery.of(context).size.height.h * 1,
decoration: BoxDecoration(color: Colors.white),
child: Column(
children: [
Row(
mainAxisSize: MainAxisSize.max,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Padding(
padding:
EdgeInsetsDirectional.fromSTEB(0, 10, 0, 0),
child: Text(
'Product:',
style: FlutterFlowTheme.of(context)
.bodyText1
.override(
fontFamily: 'Heebo',
fontSize: 18,
fontWeight: FontWeight.w500,
),
),
),
],
),
Row(
mainAxisSize: MainAxisSize.max,
children: [
DropdownButton<String>(
value: dropDownValueSelected,
items: dropDownProduct.map((item) => DropdownMenuItem<String>(
value: item,
child: Text(item,
style: TextStyle(fontSize: 14)),
))
.toList(),
onChanged: (item) => setState(() {
dropDownValueSelected = item!;
}))
],
),
],
),
),
),
);
}
}
</code></pre>
<p>The error I am getting is:</p>
<p>The method 'map' isn't defined for the type 'Future'.
Try correcting the name to the name of an existing method, or defining a method named 'map'.</p>
<p>The error is from line 121.</p>
<p>Thanks in advance!</p>
| [
{
"answer_id": 74196039,
"author": "Zeeshan Ahmad",
"author_id": 10961649,
"author_profile": "https://Stackoverflow.com/users/10961649",
"pm_score": 0,
"selected": false,
"text": "ApiService().getAllProducts()"
},
{
"answer_id": 74196064,
"author": "Fabián Bardecio",
"aut... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74195878",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8227931/"
] |
74,195,910 | <p>Let's say I have some code like this:</p>
<pre><code>_TEXT16 SEGMENT USE16 'CODE'
_start:
; some code...
; add padding
byte 512-($-_start) dup (0) ; works fine
_TEXT16 ENDS
_TEXT32 SEGMENT USE32 'CODE'
; some code
byte 1024-($-_start) dup (0) ; error A2192: Operands must be in same segment
_TEXT32 ENDS
</code></pre>
<p>In NASM you would just do something like this <code>times 1024-($-$$) db 0</code>, but unfortunately the <code>$$</code> is not supported in MASM or in JWASM, which is what I'm using at the moment. I need this to align the blocks of my bootloader to the size of readable disk sectors.</p>
<p>So, my question is, how do I add padding of 512 bytes to my code blocks in MASM?</p>
<p>Edit:</p>
<p>The scenario has changed a bit.</p>
<pre><code>_TEXT16 SEGMENT USE16 'CODE'
_start:
; some code...
_TEXT16 ENDS
_TEXT32 SEGMENT USE32 'CODE'
; some code
_TEXT32 ENDS
_TEXT64 SEGMENT USE64 'CODE'
; some code
; add padding
byte 510-($-_start) dup (0) ; error A2192: Operands must be in same segment
dw 0AA55h
_TEXT64 ENDS
</code></pre>
<p>Now how would I go about adding the correct padding here?</p>
| [
{
"answer_id": 74200705,
"author": "Peter Cordes",
"author_id": 224132,
"author_profile": "https://Stackoverflow.com/users/224132",
"pm_score": 0,
"selected": false,
"text": "org 510"
},
{
"answer_id": 74209018,
"author": "Albert Wesker",
"author_id": 17216806,
"autho... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74195910",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17216806/"
] |
74,195,939 | <p>I created a Person Model:</p>
<pre><code>Model Person = new Model();
Person.LastName = values[0];
</code></pre>
<p><em>[LastName is a string]</em><br />
I would like to replace the <strong>values [0]</strong> which is "<strong>Anna</strong>" with another string value like "<strong>Frank</strong>" if it contains a double character, in this case "if <strong>Anna</strong> contains a <strong>double character</strong>, change the value
with another string".</p>
<p><em>how to do?</em></p>
| [
{
"answer_id": 74196000,
"author": "Michał Turczyn",
"author_id": 7132550,
"author_profile": "https://Stackoverflow.com/users/7132550",
"pm_score": 0,
"selected": false,
"text": "public static class StringExtensions\n{\n public static bool HasDoubleChar(this string @this)\n {\n ... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74195939",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
74,195,940 | <p>I'm looking to nicely group some data from a list of maps, effectively attempting to "join" on given keys, and consolidating values associated with others. I have a (non-generic) example.</p>
<p>I work at a digital marketing company, and my particular example is regarding trying to consolidate a list of maps representing click-counts on our sites from different device types.</p>
<p>Example data is as follows</p>
<pre class="lang-clj prettyprint-override"><code>(def example-data
[{:site-id "439", :pid "184", :device-type "PC", :clicks 1}
{:site-id "439", :pid "184", :device-type "Tablet", :clicks 2}
{:site-id "439", :pid "184", :device-type "Mobile", :clicks 4}
{:site-id "439", :pid "3", :device-type "Mobile", :clicks 6}
{:site-id "100", :pid "200", :device-type "PC", :clicks 3}
{:site-id "100", :pid "200", :device-type "Mobile", :clicks 7}])
</code></pre>
<p>I want to "join" on the <code>:site-id</code> and <code>:pid</code> keys, while consolidating the <code>:device-type</code>s and their corresponding <code>:clicks</code> into a map themselves: a working solution would result in the following list</p>
<pre class="lang-clj prettyprint-override"><code>[{:site-id "439", :pid "184", :device-types {"PC" 1, "Tablet" 2, "Mobile" 4}}
{:site-id "439", :pid "3", :device-types {"Mobile" 6}}
{:site-id "100", :pid "200", :device-types {"PC" 3, "Mobile" 7}}]
</code></pre>
<p>So, I do have a working solution for this specific transformation, which is as follows:</p>
<pre class="lang-clj prettyprint-override"><code>(defn consolidate-click-counts [click-counts]
(let [[ks vs] (->> click-counts
(group-by (juxt :site-id :pid))
((juxt keys vals)))
consolidate #(reduce (fn [acc x]
(assoc acc (:device-type x) (:clicks x)))
{}
%)]
(map (fn [[site-id pid] devs]
{:site-id site-id :pid pid :device-types (consolidate devs)})
ks
vs)))
</code></pre>
<p>While this works for my immediate use, this solution feels a little clumsy to me, and is also strongly tied to this exact transformation, I've been trying to think of what a more generic version of this function would look like, where the keys to join/consolidate on were parameterized maybe? I think it would also be ideal to have some kind of resolving fn that could be provided for duplicate (not-joined-on) keys (e.g. if I had two maps with a matching <code>:site-id</code>, <code>:pid</code>, and <code>:device-type</code>, where I would then probably want to add the click-counts together), sort of like <code>merge-with</code> - but maybe that's too much)</p>
<p>I'm not sold on my grouping method either, perhaps it would be better to have another list of maps, a la</p>
<pre class="lang-clj prettyprint-override"><code>[{:site-id "439",
:pid "184",
:grouped-data [{:device-type "PC", :clicks 1}
{:device-type "Tablet", :clicks 2}
{:device-type "Mobile", :clicks 4}}]
{:site-id "439",
:pid "3",
:grouped-data [{:device-type "Mobile", :clicks 6}}]
{:site-id "100",
:pid "200",
:grouped-data [{:device-type "PC", :clicks 3}
{:device-type "Mobile", :clicks 7}}]
</code></pre>
| [
{
"answer_id": 74196966,
"author": "amalloy",
"author_id": 625403,
"author_profile": "https://Stackoverflow.com/users/625403",
"pm_score": 3,
"selected": true,
"text": "group-by"
},
{
"answer_id": 74197343,
"author": "xificurC",
"author_id": 1688998,
"author_profile":... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74195940",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9682103/"
] |
74,195,949 | <p>When I'm loading my components on my host app, the componnet loads with no css, I'm using Vite + Vue with tailwind, does anyone know how to load those styles?</p>
<p>This is my vite.conf.ts:</p>
<pre class="lang-js prettyprint-override"><code>import federation from "@originjs/vite-plugin-federation";
import { defineConfig } from "vite";
import vue from "@vitejs/plugin-vue";
export default defineConfig({
server: {
port: 8000,
},
build: {
target: ["chrome101", "edge89", "firefox89", "safari15"],
},
plugins: [
vue(),
federation({
name: "myLib",
filename: "remoteEntry.js",
// Modules to expose
exposes: {
"./Counter": "./src/components/Counter.vue",
"./Controller": "./src/controller.ts",
},
shared: ["vue", "css"],
}),
],
});
</code></pre>
| [
{
"answer_id": 74196966,
"author": "amalloy",
"author_id": 625403,
"author_profile": "https://Stackoverflow.com/users/625403",
"pm_score": 3,
"selected": true,
"text": "group-by"
},
{
"answer_id": 74197343,
"author": "xificurC",
"author_id": 1688998,
"author_profile":... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74195949",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16552992/"
] |
74,195,968 | <p>I'm wondering if in Python3 there is a one liner that can turn:</p>
<pre class="lang-py prettyprint-override"><code>in_dict = {
("ID1", "TEXT_A"): "TIMESTAMP_X",
("ID1", "TEXT_B"): "TIMESTAMP_Y",
("ID2", "TEXT_C"): "TIMESTAMP_X",
("ID3", "TEXT_E"): "TIMESTAMP_Y",
}
</code></pre>
<p>into</p>
<pre class="lang-py prettyprint-override"><code>out_dict = {
"ID1": [
{"TEXT_A": "TIMESTAMP_X"},
{"TEXT_B": "TIMESTAMP_Y"}
],
"ID2": [{"TEXT_C": "TIMESTAMP_X"}],
"ID3": [{"TEXT_E": "TIMESTAMP_Y"}],
}
</code></pre>
<p>I know I can easily do this in a for loop but I was wondering if there is a super fancy way.</p>
| [
{
"answer_id": 74196966,
"author": "amalloy",
"author_id": 625403,
"author_profile": "https://Stackoverflow.com/users/625403",
"pm_score": 3,
"selected": true,
"text": "group-by"
},
{
"answer_id": 74197343,
"author": "xificurC",
"author_id": 1688998,
"author_profile":... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74195968",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2069812/"
] |
74,195,982 | <p>I have a database. These database has two tables.</p>
<p>One table is <code>music</code>.</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>name</th>
<th>Date</th>
<th>Edition</th>
<th>Song_ID</th>
<th>Singer_ID</th>
</tr>
</thead>
<tbody>
<tr>
<td>LA</td>
<td>01.05.2009</td>
<td>1</td>
<td>1</td>
<td>1</td>
</tr>
<tr>
<td>Second</td>
<td>13.07.2009</td>
<td>1</td>
<td>2</td>
<td>2</td>
</tr>
<tr>
<td>Mexico</td>
<td>13.07.2009</td>
<td>1</td>
<td>3</td>
<td>1</td>
</tr>
<tr>
<td>Let's go</td>
<td>13.09.2009</td>
<td>1</td>
<td>4</td>
<td>3</td>
</tr>
<tr>
<td>Hello</td>
<td>18.09.2009</td>
<td>1</td>
<td>5</td>
<td>(4,5)</td>
</tr>
<tr>
<td>Don't give up</td>
<td>12.02.2010</td>
<td>2</td>
<td>6</td>
<td>(5,6)</td>
</tr>
<tr>
<td>ZIC ZAC</td>
<td>18.03.2010</td>
<td>2</td>
<td>7</td>
<td>7</td>
</tr>
<tr>
<td>Blablabla</td>
<td>14.04.2010</td>
<td>2</td>
<td>8</td>
<td>2</td>
</tr>
<tr>
<td>Oh la la</td>
<td>14.05.2011</td>
<td>3</td>
<td>9</td>
<td>4</td>
</tr>
<tr>
<td>Food First</td>
<td>14.05.2011</td>
<td>3</td>
<td>10</td>
<td>5</td>
</tr>
<tr>
<td>La Vie est..</td>
<td>17.06.2011</td>
<td>3</td>
<td>11</td>
<td>8</td>
</tr>
<tr>
<td>Jajajajajaja</td>
<td>13.07.2011</td>
<td>3</td>
<td>12</td>
<td>9</td>
</tr>
</tbody>
</table>
</div>
<p>And another table called <code>singer</code></p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Singer</th>
<th>nationality</th>
<th>Singer_ID</th>
</tr>
</thead>
<tbody>
<tr>
<td>JT Watson</td>
<td>USA</td>
<td>1</td>
</tr>
<tr>
<td>Rafinha</td>
<td>Brazil</td>
<td>2</td>
</tr>
<tr>
<td>Juan Casa</td>
<td>Spain</td>
<td>3</td>
</tr>
<tr>
<td>Kidi</td>
<td>USA</td>
<td>4</td>
</tr>
<tr>
<td>Dede</td>
<td>USA</td>
<td>5</td>
</tr>
<tr>
<td>Briana</td>
<td>USA</td>
<td>6</td>
</tr>
<tr>
<td>Jay Ado</td>
<td>UK</td>
<td>7</td>
</tr>
<tr>
<td>Dani</td>
<td>Australia</td>
<td>8</td>
</tr>
<tr>
<td>Mike Rich</td>
<td>USA</td>
<td>9</td>
</tr>
</tbody>
</table>
</div>
<p>Now I would like to find out how many Songs are there. I gave that code, but it says invalid sytax??</p>
<pre><code>SELECT DISTINCT Song_ID FROM music
</code></pre>
<p>The invalid syntax is near DISTINCT</p>
<p>I create the database like these, maybe that is why it has error:</p>
<pre><code>import sqlite3
conn = sqlite3.connect('musicten.db')
c = conn.cursor()
c.execute('''
CREATE TABLE IF NOT EXISTS singer
([Singer_ID] INTEGER PRIMARY KEY, [Singer] TEXT, [nationality] TEXT)
''')
c.execute('''
CREATE TABLE IF NOT EXISTS music
([SONG_ID] INTEGER PRIMARY KEY, [SINGER_ID] INTEGER SECONDARY KEY, [name] TEXT, [Date] DATE, [EDITION] INTEGER)
''')
conn.commit()
import sqlite3
conn = sqlite3.connect('musicten.db')
c = conn.cursor()
c.execute('''
INSERT INTO singer (Singer_ID, Singer,nationality)
VALUES
(1,'JT Watson',' USA'),
(2,'Rafinha','Brazil'),
(3,'Juan Casa','Spain'),
(4,'Kidi','USA'),
(5,'Dede','USA')
''')
c.execute('''
INSERT INTO music (Song_ID,Singer_ID, name, Date,Edition)
VALUES
(1,1,'LA',01/05/2009,1),
(2,2,'Second',13/07/2009,1),
(3,1,'Mexico',13/07/2009,1),
(4,3,'Let"s go',13/09/2009,1),
(5,(4,5),'Hello',18/09/2009,1)
''')
</code></pre>
<p>But I don't think, because this works fine. I can not do the sql code</p>
| [
{
"answer_id": 74196014,
"author": "Tim Biegeleisen",
"author_id": 1863229,
"author_profile": "https://Stackoverflow.com/users/1863229",
"pm_score": 2,
"selected": true,
"text": "SELECT COUNT(DISTINCT Song_ID) FROM music;\n"
}
] | 2022/10/25 | [
"https://Stackoverflow.com/questions/74195982",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
74,195,992 | <p>I am working with cost data for a retailer, where I am making some predictions using gam that look as follows (sample data, self-generated). The GAM fits values in the middle, but has some NAs at the extremes. The elasticity is calculated as a percentage change in cost over percentage change in items.</p>
<pre><code>df <- tibble(
factor = seq(0.7,1.3, 0.1),
items = c(7, 8, 9, 10, 11, 12, 13),
cost = c(NA, NA, 70, 80, 90, NA, NA),
elasticity = c(NA, NA, 0.5, 0.6, 0.7, NA, NA)
)
</code></pre>
<p>An easy estimate for the elasticises is to extend the last known value up and down.</p>
<pre><code>df %>%
fill(elasticity, .direction = 'updown') ->
df
</code></pre>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>factor</th>
<th>items</th>
<th>cost</th>
<th>elasticity</th>
</tr>
</thead>
<tbody>
<tr>
<td>0.7</td>
<td>7</td>
<td>NA</td>
<td>0.5</td>
</tr>
<tr>
<td>0.8</td>
<td>8</td>
<td>NA</td>
<td>0.5</td>
</tr>
<tr>
<td>0.9</td>
<td>9</td>
<td>70</td>
<td>0.5</td>
</tr>
<tr>
<td>1.0</td>
<td>10</td>
<td>80</td>
<td>0.6</td>
</tr>
<tr>
<td>1.1</td>
<td>11</td>
<td>90</td>
<td>0.7</td>
</tr>
<tr>
<td>1.2</td>
<td>12</td>
<td>NA</td>
<td>0.7</td>
</tr>
<tr>
<td>1.3</td>
<td>13</td>
<td>NA</td>
<td>0.7</td>
</tr>
</tbody>
</table>
</div>
<p>I would like to calculate the cost, having estimated the elasticity of cost. For example, for a factor of 1.2, the items are 12 and elasticity is 0.7. The percentage change in items is (12-11)/11 = 9.09%, so the percentage change in cost should be 0.7 * 9.09% = 6.36%. Since cost for factor of 1.1 is 90, the cost for factor of 1.2 is 95.72. And the same propagated both down and up.</p>
<p>I cannot figure a way of doing this. Can someone suggest how this can be done in R and preferably in dplyr?</p>
| [
{
"answer_id": 74196548,
"author": "Captain Hat",
"author_id": 4676560,
"author_profile": "https://Stackoverflow.com/users/4676560",
"pm_score": 2,
"selected": false,
"text": "dplyr"
},
{
"answer_id": 74196826,
"author": "Ric Villalba",
"author_id": 6912817,
"author_p... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74195992",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2102784/"
] |
74,195,998 | <p>I have date-wise data to plot but not all consecutive dates available. However, on x-axis I have to show years only. I have tried set_major_locator, YearLocator, MonthLocator etc but it didnt work. Also, I made sure to have dates in datetime format.</p>
<p>After trying these, still some years are missing in graph as marked in below screen shot.</p>
<p>Output:
<a href="https://i.stack.imgur.com/ukKVz.png" rel="nofollow noreferrer">Graph screenshot</a></p>
<p>Code:</p>
<pre><code>plt.figure(figsize=(15,5))
ax1 = plt.subplot(111)
ax1.set_xticks(np.arange(len(dates)))
ax1.set_xticklabels(dates)
ax1.tick_params(axis='x',rotation=90, zorder=120)
ax1.xaxis.set_major_locator(YearLocator(1,month=1,day=1))
plt.plot(dates,baseData.Sabic, linewidth=3)
plt.plot(dates,baseData.PriceDivReinv, linewidth=3)
plt.plot(dates,baseData.PricePlusAccDividend, linewidth=3)
ax1.margins(x=0)
plt.show()
</code></pre>
<p>Also, i am unable to get year only using datetime.DateFormatter('%Y')</p>
<p>So, i need help with showing all available years in x-axis.</p>
| [
{
"answer_id": 74196548,
"author": "Captain Hat",
"author_id": 4676560,
"author_profile": "https://Stackoverflow.com/users/4676560",
"pm_score": 2,
"selected": false,
"text": "dplyr"
},
{
"answer_id": 74196826,
"author": "Ric Villalba",
"author_id": 6912817,
"author_p... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74195998",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9950870/"
] |
74,196,055 | <p>I am trying to do "=COUNTIF(B1:B3,">"&B1)" in sql, it counts the number of elements in a column, from B1 row to B3, which are greater then B1. We are doing this for every 3 rows.</p>
<p>Suppose we have B column</p>
<p>532.02</p>
<p>667.96</p>
<p>588.1</p>
<p>579.35</p>
<p>623.98</p>
<p>621.29</p>
<p>Now we i need to calculate the number of elements which are greater then elements B(i) for every three rows.</p>
<p>532.02 -> 2 (=COUNTIF(B1:B3,">"&B1) (Number of elements from B1 to B3 which are greater then B1)</p>
<p>667.96 -> 0 (=COUNTIF(B2:B3,">"&B2) (Number of elements from B2 to B3 which are greater then B2)</p>
<p>588.1 -> 0 (=COUNTIF(B3:B3,">"&B3)(Number of elements from B3 to B3 which are greater then B3)</p>
<p>579.35 -> 2 (=COUNTIF(B4:B6,">"&B4) (Number of elements from B4 to B6 which are greater then B4)</p>
<p>623.98 -> 0 (=COUNTIF(B5:B6,">"&B5) (Number of elements from B5 to B6 which are greater then B5)</p>
<p>621.29 -> 0 (=COUNTIF(B6:B6,">"&B6) (Number of elements from B6 to B6 which are greater then B6)</p>
<p>So in sheets/excel, we use this (=COUNTIF(B5:B6,">"&B5), but how write query in sql on the basis of this?</p>
| [
{
"answer_id": 74196977,
"author": "Marco Aurelio Fernandez Reyes",
"author_id": 12511801,
"author_profile": "https://Stackoverflow.com/users/12511801",
"pm_score": 1,
"selected": false,
"text": "CELL"
},
{
"answer_id": 74197144,
"author": "Matthew Hart",
"author_id": 799... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74196055",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11363427/"
] |
74,196,068 | <p>I'm quite new with React and using API's. I'm trying to make a graph with <a href="https://recharts.org/en-US" rel="nofollow noreferrer">Recharts</a> and I'm kinda stuck with something. The time data that I get from the API shows as Unix time format as shown here: <a href="https://i.stack.imgur.com/EZH3T.png" rel="nofollow noreferrer">https://i.stack.imgur.com/EZH3T.png</a>
This is how I fetch the API data:</p>
<pre><code> const [devices, setDevices] = useState([] as IDeviceData[]);
useEffect(() => {
fetch("http://api...")
.then(response => {
if (response.ok) {
return response.json()
} else if (response.status === 404) {
return Promise.reject('Error 404')
} else {
return Promise.reject('There was an error: ' + response.status)
}
})
.then(data => setDevices(data))
.catch(error => navigate(
`/sensors/${imei}/404-not-found/`,
{
state: {
description: `No sensor found with: "${imei}"`
}
},
));
}, [imei, navigate, category]);
</code></pre>
<p>And this is how I show it in my graph:</p>
<pre><code> <ResponsiveContainer width="100%" height="100%">
<LineChart data={devices} margin={{ top: 5, right: 20, bottom: 5, left: 0 }}>
<Line type="monotone" dataKey={category} dot={{strokeWidth: '4'}} stroke="#0EA5E9" />
<CartesianGrid stroke="#ccc" strokeDasharray="5 5" />
<XAxis dataKey={"timestamp"}/>
<YAxis />
<Tooltip />
</LineChart>
</ResponsiveContainer>
</code></pre>
<p>I have tried to make a timestamp converter function like this:</p>
<pre><code>export function convertTimestampToDate(timestamp: string): string {
return new Intl.DateTimeFormat('nl', {
year: 'numeric',
day: '2-digit',
month: '2-digit',
hour: '2-digit',
minute: '2-digit',
second: '2-digit',
}).format(parseInt(timestamp));
}
</code></pre>
<p>I don't quite know how to use the API data that I've put inside <code>devices</code> within the <code>XAxis</code> component.</p>
| [
{
"answer_id": 74196977,
"author": "Marco Aurelio Fernandez Reyes",
"author_id": 12511801,
"author_profile": "https://Stackoverflow.com/users/12511801",
"pm_score": 1,
"selected": false,
"text": "CELL"
},
{
"answer_id": 74197144,
"author": "Matthew Hart",
"author_id": 799... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74196068",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20281610/"
] |
74,196,081 | <p>Can anyone tell me why it doesn't work and how to fix it ?</p>
<p>I'm trying to use a lambda function to choose the value of a column based on a condition on another column.</p>
<pre><code>df = pd.DataFrame({'A': [4, 8, 2, 7, 4],
'B': [8, 10, 3, 4, 1],
'C': [10, 8, 2, 6, 2]})
df
</code></pre>
<pre><code>`df.apply(lambda x: x['B'] if x['A'].isin([1,2,3,4,5]) else x['C'])`
</code></pre>
<pre><code>KeyError Traceback (most recent call last)
c:\xxxxxx\xxxxxx\xxx Cellule 19 in <cell line: 1>()
----> 1 df.apply(lambda x: x['B'] if x['A'].isin([1,2,3,4,5]) else x['C'])
File c:\Anaconda\envs\xxxxx\xxxx.py:8839, in DataFrame.apply(self, func, axis, raw, result_type, args, **kwargs)
8828 from pandas.core.apply import frame_apply
8830 op = frame_apply(
8831 self,
8832 func=func,
(...)
8837 kwargs=kwargs,
8838 )
-> 8839 return op.apply().__finalize__(self, method="apply")
File c:\Anaconda\xxxxxlib\site-packages\pandas\core\apply.py:727, in FrameApply.apply(self)
724 elif self.raw:
725 return self.apply_raw()
--> 727 return self.apply_standard()
File c:\Anaconda\envs\xxxx\pandas\core\apply.py:851, in FrameApply.apply_standard(self)
850 def apply_standard(self):
--> 851 results, res_index = self.apply_series_generator()
853 # wrap results
854 return self.wrap_results(results, res_index)
...
388 self._check_indexing_error(key)
--> 389 raise KeyError(key)
390 return super().get_loc(key, method=method, tolerance=tolerance)
KeyError: 'A'
</code></pre>
| [
{
"answer_id": 74196099,
"author": "Naveed",
"author_id": 3494754,
"author_profile": "https://Stackoverflow.com/users/3494754",
"pm_score": 0,
"selected": false,
"text": "axis=1"
},
{
"answer_id": 74196253,
"author": "mozway",
"author_id": 16343464,
"author_profile": ... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74196081",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20331491/"
] |
74,196,090 | <p>This is the code I've run to get the error. I tried to change the int to str, hoping it would work but it did not really do anything.</p>
<pre><code>Name = input("Your name is: ")
print("Hi!",Name)
x = int(input("Your age is: "))
print("You are",x)
Year=2022
Year_user_will_turn_100 = 2022 - x + 100
print(Name,"will turn 100 on the year",Year_user_will_turn_100)
</code></pre>
| [
{
"answer_id": 74196099,
"author": "Naveed",
"author_id": 3494754,
"author_profile": "https://Stackoverflow.com/users/3494754",
"pm_score": 0,
"selected": false,
"text": "axis=1"
},
{
"answer_id": 74196253,
"author": "mozway",
"author_id": 16343464,
"author_profile": ... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74196090",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20331514/"
] |
74,196,107 | <p>I am making a small weather app using React. I intend to use the <code>useState</code> hook for an array of objects. Through an array of objects - <code>latLongStore</code>, I make multiple axios <code>get</code> calls to fetch weather data for different cities. The fetch part works well but <code>weatherData</code> values do not show up in the DOM. It has the correct number of objects but appears to contain no values. Below is my code:</p>
<pre><code>...
const latLongStore = [
{ latitude: 23.8315, longitude: 91.2868, title: "Agartala", color: "#299617", code: 'VEAT' },
{ latitude: 23.0225, longitude: 72.5714, title: "Ahmedabad", color: "#299617", code: 'VCBI' },
...
]
const initialData = {
city: '',
latitude: 0,
longitude: 0,
max_temperature: 0,
min_temperature: 0
}
function TableView(props) {
const [weatherData, updateWeatherData] = useState([initialData]);
useEffect(() => {
latLongStore.forEach((latLong) => {
axios.get(`api-url`).then((response) => {
const fetchedData = {
city: latLong.title,
latitude: response.data.latitude,
longitude: response.data.longitude,
max_temperature: response.data.daily.temperature_2m_max[0],
min_temperature: response.data.daily.temperature_2m_min[0]
}
console.log(fetchedData);
updateWeatherData(weatherData => [...weatherData, fetchedData]);
})
})
}, []);
switch (weatherData.length) {
default:
return (
<div>
<br />
<br />
<br />
<br />
LOADING...
{weatherData.length}
</div>
)
// weatherData contains 62 objects after fetch but no values show up in DOM
case 62:
return (
<div>
<br />
<br />
<br />
<br />
{ weatherData.forEach((data) => {
<div>
{ data.city } : { data.latitude }, { data.longitude }
</div>
}) }
</div>
)
// default:
// return (
// <div>
// <br />
// <br />
// <br />
// <br />
// LOADING...
// </div>
// )
}
}
export default TableView;
</code></pre>
<p>Here's the output:</p>
<ul>
<li>At a particular instant of updation</li>
</ul>
<p><a href="https://i.stack.imgur.com/V1nzk.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/V1nzk.png" alt="enter image description here" /></a></p>
<ul>
<li>After the <code>weatherData.length</code> reaches 62<br />
<a href="https://i.stack.imgur.com/lxJT3.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/lxJT3.png" alt="enter image description here" /></a></li>
</ul>
<p>Can someone tell me how I can show up <code>weatherData</code> values in DOM.</p>
| [
{
"answer_id": 74196718,
"author": "Harrison",
"author_id": 15291770,
"author_profile": "https://Stackoverflow.com/users/15291770",
"pm_score": 0,
"selected": false,
"text": "useEffect"
},
{
"answer_id": 74196743,
"author": "DINO",
"author_id": 1836657,
"author_profil... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74196107",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17324341/"
] |
74,196,119 | <p>hello i need to find the mean of a sample of random numbers in an interval between -1 and 1 with a confidence interval of 95 % and then repeat the process 50 times i am using a for cycle that calculates the means for the 50 repetitions but when i apply it to the confidence interval it doesn't calculate the standard deviation i have this code</p>
<pre><code>for (i in 1:50) {
n<-100
z[i] <-runif(min=-1,max=1,n)
m[i] <-mean(z[i])
s[i] <-sd(z[i])
sigma[i] <-1.96*(s[i] /sqrt(n))
ls[i] <-m[i] +sigma[i]
li[i] <-m[i] -sigma[i]
}
</code></pre>
| [
{
"answer_id": 74196200,
"author": "Jilber Urbina",
"author_id": 1315767,
"author_profile": "https://Stackoverflow.com/users/1315767",
"pm_score": 3,
"selected": true,
"text": "for"
},
{
"answer_id": 74196356,
"author": "KacZdr",
"author_id": 12382064,
"author_profile... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74196119",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20326515/"
] |
74,196,125 | <p>I would like to subtract two dates, the birth date, and the study date, and store the difference in terms of months. The DICOM entries have a weird format for the birth date (e.g.,19760404) and study date (e.g., 19940211). These entries are in the YYYYMMDD sequence. How do I compute the difference between these two values in terms of months?</p>
| [
{
"answer_id": 74196245,
"author": "cybernetic.nomad",
"author_id": 8260484,
"author_profile": "https://Stackoverflow.com/users/8260484",
"pm_score": 1,
"selected": false,
"text": "=DATE(LEFT(A1,4),MID(A1,5,2),RIGHT(A1,2))-DATE(LEFT(B1,4),MID(B1,5,2),RIGHT(B1,2))\n"
},
{
"answer_... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74196125",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7575552/"
] |
74,196,150 | <p>Here is the query to find the address from a table where it matches to variable <code>$fromCity</code>,</p>
<pre><code>$fromCity= "324 West Gore Street, Orlando, FL 32806, USA";
$sql = "SELECT * FROM vendor_info WHERE mailing_address LIKE '$fromCity'";
$em = $this->getDoctrine()->getManager();
$stmt = $em->getConnection()->prepare($sql);
$stmt->execute();
$company = $stmt->fetchAll();
dd($company);
</code></pre>
<p>In the table <code>vendor_info</code> the column <code>mailing address</code> is like
<code>324 WEST GORE STREETORLANDO, FL 32806</code></p>
<p>I want to get result if any single word is match from <code>mailing_address</code> column</p>
<p>now the result of <code>dd(company);</code> is empty array,</p>
<p>kindly help me out to figure out this solution, it is in symfony,</p>
| [
{
"answer_id": 74208305,
"author": "Rufinus",
"author_id": 151097,
"author_profile": "https://Stackoverflow.com/users/151097",
"pm_score": 0,
"selected": false,
"text": "$fromCity = \"324 West Gore Street, Orlando, FL 32806\";\n$fromCity_arr = explode(', ', $fromCity);\n$stm = $this->get... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74196150",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17973097/"
] |
74,196,233 | <p>My problem is that when I try to delete records from a table in postgreSQL with python I can't do it, the method I created deletes 1 by 1, but when I want to delete 2 or more at once I get an error, which is this,
TypeError: PersonaDAO.delete() takes 2 positional arguments but 3 were given</p>
<p>The method I create to delete is this one, inside the PersonaDAO class.
In addition I have the classes of connection, that has the method to connect to the bd and of cursor.
Person class that has the initializer method with the attributes (id_person, name, last name, email).</p>
<pre><code>conexion
from logger_base import log
import psycopg2 as bd
import sys
class Conexion:
_DATABASE = 'test_db'
_USERNAME = 'postgres'
_DB_PORT = '5432'
_HOST = '127.0.0.1'
_conexion = None
_cursor = None
@classmethod
def obtenerConexion(cls):
if cls._conexion is None:
try:
cls._conexion = bd.connect(host=cls._HOST,
user=cls._USERNAME,
port=cls._DB_PORT,
database=cls._DATABASE)
log.debug(f'Conexión exitosa: {cls._conexion}')
return cls._conexion
except Exception as e:
log.error(f'Ocurrió una excepción al obtener la conexión: {e}')
sys.exit()
else:
return cls._conexion
@classmethod
def obtenerCursor(cls):
if cls._cursor is None:
try:
cls._cursor = cls.obtenerConexion().cursor()
log.debug(f'Se abrió correctamente el cursor: {cls._cursor}')
return cls._cursor
except Exception as e:
log.error(f'Ocurrió una excepción al obtener el cursor: {e}')
sys.exit()
else:
return cls._cursor
if __name__ == '__main__':
Conexion.obtenerConexion()
Conexion.obtenerCursor()
----------------
Persona and methods get and set
from logger_base import log
class Persona:
def __init__(self, id_persona=None, nombre=None, apellido=None, email=None):
self._id_persona = id_persona
self._nombre = nombre
self._apellido = apellido
self._email = email
def __str__(self):
return f'''
Id Persona: {self._id_persona}, Nombre: {self._nombre},
Apellido: {self._apellido}, Email: {self._email}
'''
--------------------
class PersonaDAO:
'''
DAO (Data Access Object)
CRUD (Create-Read-Update-Delete)
'''
_SELECCIONAR = 'SELECT * FROM persona ORDER BY id_persona'
_INSERTAR = 'INSERT INTO persona(nombre, apellido, email) VALUES(%s, %s, %s)'
_ACTUALIZAR = 'UPDATE persona SET nombre=%s, apellido=%s, email=%s WHERE id_persona=%s'
_ELIMINAR = 'DELETE FROM persona WHERE id_persona = %s'
@classmethod
def eliminar(cls, persona):
with Conexion.obtenerConexion():
with Conexion.obtenerCursor() as cursor:
valores = (persona.id_persona,)
cursor.execute(cls._ELIMINAR, valores)
log.debug(f'Objeto eliminado: {persona}')
return cursor.rowcount
</code></pre>
<p>with this method I can delete one at a time, but not multiple ids at once.
`</p>
| [
{
"answer_id": 74208305,
"author": "Rufinus",
"author_id": 151097,
"author_profile": "https://Stackoverflow.com/users/151097",
"pm_score": 0,
"selected": false,
"text": "$fromCity = \"324 West Gore Street, Orlando, FL 32806\";\n$fromCity_arr = explode(', ', $fromCity);\n$stm = $this->get... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74196233",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19941195/"
] |
74,196,240 | <p>I have two python files <code>main.py</code> and <code>conftest.py</code>. I want to access a variable inside the method of <code>main.py</code> from <code>contest.py</code>. I have tried a bit, but I know it's wrong as I get a syntax error in the first place. Is there any way to do this?
main.py</p>
<pre><code>class Test():
def test_setup(self):
#make new directory for downloads
new_dir = r"D:\Selenium\Insights\timestamp}".format(timestamp=datetime.now().strftime('%Y-%m-%d_%H-%M-%S'))
# print(new_dir)
if not os.path.exists(new_dir):
os.makedirs(new_dir)
saved_dir=new_dir
</code></pre>
<p>conftest.py</p>
<pre><code>from main import Test
def newfunc():
dir=Test.test_setup()
print(dir.saved_dir)
</code></pre>
| [
{
"answer_id": 74208305,
"author": "Rufinus",
"author_id": 151097,
"author_profile": "https://Stackoverflow.com/users/151097",
"pm_score": 0,
"selected": false,
"text": "$fromCity = \"324 West Gore Street, Orlando, FL 32806\";\n$fromCity_arr = explode(', ', $fromCity);\n$stm = $this->get... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74196240",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3304747/"
] |
74,196,252 | <p>I have a time-series in pandas with several products (id's: a, b, etc), but with monthly holes. I have to fill those holes. It may be with np.nan or any other constant. I tried groupby but I wasnt able.</p>
<pre><code>date id units
2022-01-01 a 10
2022-01-01 b 100
2022-02-01 a 15
2022-03-01 a 30
2022-03-01 b 70
2022-05-01 b 60
2022-06-01 a 8
2022-06-01 b 90
</code></pre>
<p>Should be:</p>
<pre><code>date id units
2022-01-01 a 10
2022-01-01 b 100
2022-02-01 a 15
2022-02-01 b np.nan
2022-03-01 a 30
2022-03-01 b 70
2022-04-01 a np.nan
2022-04-01 b np.nan
2022-05-01 a np.nan
2022-05-01 b 60
2022-06-01 a 8
2022-06-01 b 90
</code></pre>
| [
{
"answer_id": 74208305,
"author": "Rufinus",
"author_id": 151097,
"author_profile": "https://Stackoverflow.com/users/151097",
"pm_score": 0,
"selected": false,
"text": "$fromCity = \"324 West Gore Street, Orlando, FL 32806\";\n$fromCity_arr = explode(', ', $fromCity);\n$stm = $this->get... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74196252",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15846225/"
] |
74,196,268 | <pre><code>def new_list(lst):
for i in lst:
if i%10 == 0:
return i
else:
return False
print(new_list([10, 20.0, 25, 30, 40, 98]))
</code></pre>
<p>i want to see all numbers from the list that can be divided into 10</p>
| [
{
"answer_id": 74196319,
"author": "Nathan Roberts",
"author_id": 17135653,
"author_profile": "https://Stackoverflow.com/users/17135653",
"pm_score": 2,
"selected": false,
"text": "return"
},
{
"answer_id": 74196396,
"author": "Riccardo Bucco",
"author_id": 5296106,
"... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74196268",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20331691/"
] |
74,196,285 | <p>I have been following along with the <a href="https://forge.autodesk.com/en/docs/model-derivative/v2/tutorials/prep-roominfo4viewer/" rel="nofollow noreferrer">Translate a Revit File, Generating Room and Space Information</a> tutorial. Right now I'm stuck on task 3 trying to translate a Revit source file to SVF2.</p>
<p>Using the provided <a href="https://github.com/Autodesk-Forge/forge-tutorial-postman/tree/master/ModelDerivative_07/tutorial_data" rel="nofollow noreferrer">Revit file</a> and the following request POST <code>https://developer.api.autodesk.com/modelderivative/v2/regions/eu/designdata/job</code>:</p>
<pre class="lang-php prettyprint-override"><code>// Headers
[
'Authorization' => ...,
'Content-Type' => 'application/json',
'x-ads-force' => true,
]
// Body
[
"input" => [
"urn" => "<some urn>",
"compressedUrn" => false
],
"output" => [
"destination" => [
"region" => "EMEA"
],
"formats" => [
[
"type" => "svf2",
"views" => [
"2d",
"3d"
],
"advanced" => [
"generateMasterViews" => true
]
]
]
]
]
</code></pre>
<p>I always get the following messages:</p>
<blockquote>
<p>Revit-UnsupportedFileType
The file is not a Revit file or is not a supported version. TranslationWorker-RecoverableInternalFailure
Possibly recoverable warning exit code from extractor: -536870935</p>
</blockquote>
<p>I hope someone can tell what is wrong with the POST request. I found a <a href="https://stackoverflow.com/questions/73252655/possibly-recoverable-warning-exit-code-from-extractor">similar question</a> but the answer doesn't seem apply to this issue.</p>
| [
{
"answer_id": 74261598,
"author": "SuperDJ",
"author_id": 3390200,
"author_profile": "https://Stackoverflow.com/users/3390200",
"pm_score": 1,
"selected": true,
"text": "$response = Http::attach( 'file', $file->getContent(), $file->getClientOriginalName() )\n->put( $signed_url );\n"
}... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74196285",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3390200/"
] |
74,196,301 | <p>I have several custom module scrips in my python project that are all in a folder that is one directory down named "modules". After about a day of use on every machine I touch, importing these modules starts spitting out this error:</p>
<pre><code>ImportError: cannot import name 'letters' from 'modules' (C:\Program Files\Python39\lib\site-packages\modules.py)
</code></pre>
<p>The code for importing custom modules is here.</p>
<pre><code> from modules import letters
from modules import sfx
from modules import bgm
from modules.colors import colors, hex2dec
from modules import lessons
from modules import sessions
from key import key
</code></pre>
<p>The project folder looks like this (folders and files unrelated to the issue excluded):</p>
<pre><code>formapp
├───modules
│ ├───bgm.py
│ ├───bot_ir.py
│ ├───chat.py
│ ├───colors.py
│ ├───formbot.py
│ ├───ir.py
│ ├───lessons.py
│ ├───letters.py
│ ├───sessions.py
│ └───sfx.py
├───app.py
├───key.py
</code></pre>
<p>For the most part, <code>sys.path.append(r"modules")</code> had worked to solve this issue however hex2dec in colors.py still caused errors. Regardless, of the 15 people working on this project this error only appears for me so I should not have to append a new folder to search for modules. The only thing that separates me from the other 15 people is that I was using formbot.py</p>
<p>Here is the code for formbot.py.</p>
<pre><code>import requests
import time
class FormBot():
def __init__(self, username, password, timeout=0, host='127.0.0.1', port=420) :
self.host = '192.168.10.69'
self.port = 420
self.username = username
self.password = password
self.loggedin = False
time.sleep(timeout)
self.login()
print('logged in as', username)
#change "userType": "login", to "usertype": "new" on first time use
def login(self):
loginAttempt = requests.post(url="http://"+self.host+":"+str(self.port)+"/login", data={"username": self.username, "password": self.password, "userType": "new", "bot": "True", "forward":"/"})
#forbius login
Forbius = FormBot('Forbius', 'Password#1')
</code></pre>
<p>I have also tried reinstalling Python entirely and that has not worked.</p>
<p>To test, I tried running a fresh copy of the main branch on a computer affected by this issue and got the same error. The same code works fine on other machines.</p>
| [
{
"answer_id": 74261598,
"author": "SuperDJ",
"author_id": 3390200,
"author_profile": "https://Stackoverflow.com/users/3390200",
"pm_score": 1,
"selected": true,
"text": "$response = Http::attach( 'file', $file->getContent(), $file->getClientOriginalName() )\n->put( $signed_url );\n"
}... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74196301",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17207217/"
] |
74,196,335 | <p>I am having several python errors in this code and I need help with the code. I'm fairly new to python so I have trouble figuring this out.</p>
<pre><code>Traceback (most recent call last):
File "/root/sandbox/stats.py", line 74, in <module>
main()
File "/root/sandbox/stats.py", line 66, in main
"Mean of [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]: ", mean(range(1, 11))
File "/root/sandbox/stats.py", line 25, in mean
list.range()
AttributeError: 'range' object has no attribute 'range'
</code></pre>
<p>this is the error I keep getting.</p>
<p>This is my code</p>
<pre><code>def median(list):
if len(list) == 0:
return 0
list.sort()
midIndex = len(list) / 2
if len(list) % 2 == 1:
return list[midIndex]
else:
return (list[midIndex] + list[midIndex - 1]) / 2
def mean(list):
if len(list) == 0:
return 0
list.range()
total = 0
for number in list:
total += number
return total / len(list)
def mode(list):
numberDictionary = {}
for digit in list:
number = numberDictionary.get(digit, None)
if number is None:
numberDictionary[digit] = 1
else:
numberDictionary[digit] = number + 1
maxValue = max(numberDictionary.values())
modeList = []
for key in numberDictionary:
if numberDictionary[key] == maxValue:
modeList.append(key)
return modeList
def main():
print
"Mean of [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]: ", mean(range(1, 11))
print
"Mode of [1, 1, 1, 1, 4, 4]:", mode([1, 1, 1, 1, 4, 4])
print
"Median of [1, 2, 3, 4]:", median([1, 2, 3, 4])
main()
</code></pre>
<p>I don't know how to actually fix it.
I've tried to quick fix and replaced == with the is operator but nothing worked</p>
| [
{
"answer_id": 74196632,
"author": "BadMan",
"author_id": 20331682,
"author_profile": "https://Stackoverflow.com/users/20331682",
"pm_score": -1,
"selected": false,
"text": "list.range()\n"
},
{
"answer_id": 74196981,
"author": "DevQandA",
"author_id": 18297923,
"auth... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74196335",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20331645/"
] |
74,196,359 | <pre><code>def AddStudent():
#Variable to control the loop
again = 'y'
#While loop that gets user input to be added to dictionary
while again.lower() == 'y':
student_key = input("What's the name of the student? ")
#Ask user for number of grades
n = int(input('How many grades do you wish to input? '))
#Empty list where grades will be saved
grades = []
#for loop to add as many grades as user wishes
for i in range(0 ,n):
grade = int(input(f'Grade {i + 1}: '))
grades.append(grade)
#Call StudentGradeBook and send values as parameters
StudentGradeBook(student_key, grades)
again = input('Do you wish to add another student? (y) ')
def StudentGradeBook(name, grade_value):
#Dictionary of the grades
grade_book = {'Tom':[90,85,82], 'Bob':[92,79,85]}
#Add the key and value to the dict
grade_book[name] = grade_value
print(grade_book)
</code></pre>
<p>When I add more than one name and grade list to the dict, it just replaces the third one instead of adding a 4th, 5th, etc.</p>
<p>This is the output:</p>
<pre class="lang-none prettyprint-override"><code>What's the name of the student? Bill
How many grades do you wish to input? 3
Grade 1: 88
Grade 2: 88
Grade 3: 88
{'Tom': [90, 85, 82], 'Bob': [92, 79, 85], 'Bill': [88, 88, 88]}
Do you wish to add another student? (y) y
What's the name of the student? Thomas
How many grades do you wish to input? 3
Grade 1: 87
Grade 2: 88
Grade 3: 88
{'Tom': [90, 85, 82], 'Bob': [92, 79, 85], 'Thomas': [87, 88, 88]}
Do you wish to add another student? (y) n
</code></pre>
| [
{
"answer_id": 74196465,
"author": "chc",
"author_id": 12932447,
"author_profile": "https://Stackoverflow.com/users/12932447",
"pm_score": 0,
"selected": false,
"text": "StudentGradeBook"
},
{
"answer_id": 74196483,
"author": "ShadowRanger",
"author_id": 364696,
"auth... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74196359",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20124685/"
] |
74,196,423 | <p>I've got some date and time data as a string that is formatted like this, in UTC:</p>
<pre><code>,utc_date_and_time, api_calls
0,2022-10-20 00:00:00,12
1,2022-10-20 00:05:00,14
2,2022-10-20 00:10:00,17
</code></pre>
<p>Is there a way to create another column here that always represents that time, but so it is for London/Europe?</p>
<pre><code>,utc_date_and_time, api_calls, london_date_and_time
0,2022-10-20 00:00:00,12,2022-10-20 01:00:00
1,2022-10-20 00:05:00,14,2022-10-20 01:05:00
2,2022-10-20 00:10:00,17,2022-10-20 01:10:00
</code></pre>
<p>I want to write some code that, for any time of the year, will display the time in London - but I'm worried that when the timezone changes in London/UK that my code will break.</p>
| [
{
"answer_id": 74196465,
"author": "chc",
"author_id": 12932447,
"author_profile": "https://Stackoverflow.com/users/12932447",
"pm_score": 0,
"selected": false,
"text": "StudentGradeBook"
},
{
"answer_id": 74196483,
"author": "ShadowRanger",
"author_id": 364696,
"auth... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74196423",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1468810/"
] |
74,196,424 | <p>I have a Typescript class that is getting quite big. To organize it better and avoid cramming it up, I'd like to split it over 5-7 different files based on the page object structure.
Currently it looks like this in a single file:</p>
<p>mainAPI.ts</p>
<pre><code>
const axios = require('axios');
export class API {
makeAxiosRequest() {}
doLogin() {}
getJSESSIONID() {}
getLoginResponse() {}
deleteAnUser(userName) {}
addAnUser(userName) {}
.,etc
}
</code></pre>
<p>testFile.ts</p>
<pre><code>
import mainAPI from mainAPI.ts
await mainAPI.doLogin();
await mainAPI.addAnUser();
await mainAPI.logout();
</code></pre>
<p>EDIT:
I'm looking to achieve something like this:</p>
<p>mainAPI.ts</p>
<pre><code>
const axios = require('axios');
export class API {
//Want the methods from loginAPI.ts, userAPI.ts, purchaseAPI.ts to be a part of this class.
}
</code></pre>
<p>loginAPI.ts</p>
<pre><code>doLogin() {}
doAdminLogin() {}
doMemberLogin() {} etc
</code></pre>
<p>userAPI.ts</p>
<pre><code>deleteAnUser() {}
addAnUser() {}
updateUser() {} etc
</code></pre>
<p>purchaseAPI.ts</p>
<pre><code>addToCart() {}
buyProduct() {}
cancelOrder() {} etc
</code></pre>
<p>So far I have only tried to split the API methods component-wise by comments. I'm reaching out for help on how one can split a class into multiple files. Thank you</p>
| [
{
"answer_id": 74196619,
"author": "Foucauld Gaudin",
"author_id": 12939653,
"author_profile": "https://Stackoverflow.com/users/12939653",
"pm_score": -1,
"selected": false,
"text": "export class API extends YourNewClass {\n \n}\n"
},
{
"answer_id": 74196726,
"author": "Apol... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74196424",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17033870/"
] |
74,196,451 | <p>I have the below code that colors all the buttons (there are 10) grey to clear any previously colored button, and then colors the button selected blue. Basically acting as an indicator of what button is currently selected. I noticed that the code now takes a moment to run with this cosmetic addition and I was wondering if there is any way to re-write this to run faster?</p>
<p>Thank you for your help and please let me know if I can provide any more detail</p>
<pre><code>'
' all_days Macro
'change all buttons to grey first
ActiveSheet.Shapes.Range(Array("Rectangle: Rounded Corners 17", _
"Rectangle: Rounded Corners 12", "Rectangle: Rounded Corners 11")).Select
With Selection.ShapeRange.Fill
.Visible = msoTrue
.ForeColor.ObjectThemeColor = msoThemeColorBackground1
.ForeColor.TintAndShade = 0
.ForeColor.Brightness = -0.5
.Transparency = 0
.Solid
End With
'change selected button to blue
ActiveSheet.Shapes.Range(Array("Rectangle: Rounded Corners 12")).Select
With Selection.ShapeRange.Fill
.Visible = msoTrue
.ForeColor.ObjectThemeColor = msoThemeColorAccent1
.ForeColor.TintAndShade = 0
.ForeColor.Brightness = -0.25
.Transparency = 0
.Solid
End With
ActiveSheet.Range("$A$1:$X$740").AutoFilter Field:=12
ActiveSheet.Range("$A$1:$X$100000").AutoFilter Field:=17
End Sub```
</code></pre>
| [
{
"answer_id": 74197342,
"author": "FunThomas",
"author_id": 7599798,
"author_profile": "https://Stackoverflow.com/users/7599798",
"pm_score": 2,
"selected": false,
"text": "Select"
},
{
"answer_id": 74198027,
"author": "VBasic2008",
"author_id": 9814069,
"author_prof... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74196451",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16759275/"
] |
74,196,453 | <p>I have a query that must choose from one table if certain criteria is meet or from another if the criteria is different.</p>
<p>In my case i need to select from Table_A if we are on Database_A or from Table_B if we are on Database_B, but the criteria could be a different one.</p>
<p>I want to do something like this:</p>
<pre><code>SELECT
COLUMN_1, COLUMN_2, ..., COLUMN_N
FROM
(if database is Database_A then Table_A
but if database is Database_B then from Table B
else... it could be DUAL if any other situation, it will throw an error, but i can manage it)
WHERE
(my where criteria)
</code></pre>
<p>How can i do it with pure SQL not PL-SQL? I can use nested queries or WITH or similar stuff, but not "coding". I cannot create tables or views, i can only query the database for data.</p>
<p>I tried using CASE or other options, with no luck.</p>
| [
{
"answer_id": 74197342,
"author": "FunThomas",
"author_id": 7599798,
"author_profile": "https://Stackoverflow.com/users/7599798",
"pm_score": 2,
"selected": false,
"text": "Select"
},
{
"answer_id": 74198027,
"author": "VBasic2008",
"author_id": 9814069,
"author_prof... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74196453",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/365816/"
] |
74,196,457 | <p>I want to use where method in dynamic array. I am getting data from api and i want to find some data from the response with the help of where method.</p>
<p>Following are the repsonse of api.</p>
<pre><code>[
{
'status': true,
'result': 'found',
'data': [
{
'id': 10676487174744,
'name': 'Taki Rajani',
'email': 'mohamtaki.rai@gmail.com',
'isAdmin': false,
'description': 'ta rai'
},
{
'id': 1172269813061229,
'name': 'Aar Raj',
'email': 'rajnia@gmail.com',
'isAdmin': false,
'description': 'test'
},
{
'id': 12854121,
'name': 'testing',
'email': 'testing1222@gmail.com',
'isAdmin': false,
'description': 'details'
}
]
}
]
</code></pre>
<p>following are my code for finding same user id which i was stored in storeUserID variable.</p>
<p><strong>2 problems:-
1)when i print listof user, I am getting all datas in my case 3 data but <em>when I print length of this list the reponse shows count only 1</em>.
2)"where" method is showing nothing on print might be is not working.</strong></p>
<pre><code>Future<GetUserData> getUserDetail() async {
var url = "https://aeliya.mydomin.com/getUser.php";
var response = await http.get(Uri.parse(url));
var jsondata = jsonDecode(response.body.toString());
List listOfUser = [];
if (response.statusCode == 200) {
//print(jsondata);
listOfUser.add(jsondata);
print(listOfUser);
print(listOfUser.length);
var findid = listOfUser.where((element) => element == storeUserID);
print(findid);
return GetUserData.fromJson(jsondata);
} else {
return GetUserData.fromJson(jsondata);
}
</code></pre>
| [
{
"answer_id": 74197342,
"author": "FunThomas",
"author_id": 7599798,
"author_profile": "https://Stackoverflow.com/users/7599798",
"pm_score": 2,
"selected": false,
"text": "Select"
},
{
"answer_id": 74198027,
"author": "VBasic2008",
"author_id": 9814069,
"author_prof... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74196457",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19458028/"
] |
74,196,479 | <p>I have a column in my DF where data type is :</p>
<pre class="lang-none prettyprint-override"><code>testcolumn:array
--element: struct
-----id:integer
-----configName: string
-----desc:string
-----configparam:array
--------element:map
-------------key:string
-------------value:string
</code></pre>
<p>testcolumn<br />
<strong>Row1:</strong></p>
<pre><code>[{"id":1,"configName":"test1","desc":"Ram1","configparam":[{"removeit":"[]"}]},
{"id":2,"configName":"test2","desc":"Ram2","configparam":[{"removeit":"[]"}]},
{"id":3,"configName":"test3","desc":"Ram1","configparam":[{"paramId":"4","paramvalue":"200"}]}]
</code></pre>
<p><strong>Row2:</strong></p>
<pre><code>[{"id":11,"configName":"test11","desc":"Ram11","configparam":[{"removeit":"[]"}]},
{"id":33,"configName":"test33","desc":"Ram33","configparam":[{"paramId":"43","paramvalue":"300"}]},
{"id":6,"configName":"test26","desc":"Ram26","configparam":[{"removeit":"[]"}]},
{"id":93,"configName":"test93","desc":"Ram93","configparam":[{"paramId":"93","paramvalue":"3009"}]}
]
</code></pre>
<p>I want to remove where configparam is <strong>"configparam":[{"removeit":"[]"}]</strong> to <strong>"configparam":[]</strong></p>
<p><strong>expecting output:</strong><br />
outputcolumn</p>
<p><strong>Row1:</strong></p>
<pre><code>[{"id":1,"configName":"test1","desc":"Ram1","configparam":[]},
{"id":2,"configName":"test2","desc":"Ram2","configparam":[]},
{"id":3,"configName":"test3","desc":"Ram1","configparam":[{"paramId":"4","paramvalue":"200"}]}]
</code></pre>
<p><strong>Row2:</strong></p>
<pre><code>[{"id":11,"configName":"test11","desc":"Ram11","configparam":[]},
{"id":33,"configName":"test33","desc":"Ram33","configparam":[{"paramId":"43","paramvalue":"300"}]},
{"id":6,"configName":"test26","desc":"Ram26","configparam":[]},
{"id":93,"configName":"test93","desc":"Ram93","configparam":[{"paramId":"93","paramvalue":"3009"}]}
]
</code></pre>
<p>I have tried this code but it is not giving me output:</p>
<pre class="lang-py prettyprint-override"><code>test=df.withColumn('outputcolumn',F.expr("translate"(testcolumn,x-> replace(x,':[{"removeit":"[]"}]','[]')))
</code></pre>
<p>it will be really great if someone can help me.</p>
| [
{
"answer_id": 74197342,
"author": "FunThomas",
"author_id": 7599798,
"author_profile": "https://Stackoverflow.com/users/7599798",
"pm_score": 2,
"selected": false,
"text": "Select"
},
{
"answer_id": 74198027,
"author": "VBasic2008",
"author_id": 9814069,
"author_prof... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74196479",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9630160/"
] |
74,196,487 | <p>I have an duende identityserver that has multiple BFFs as a client.
One of these BFFs is for my admins.</p>
<p>My identityserver has multiple sign in schemes (Think facebook, google etc) however i want to force my Administrator bff to use the (Azure AD (for my organization only) login.</p>
<p>I was thinking maybe setting clientproperties in the database and having the identityserver respond to that. But i was wondering if there is a more standard way of doing it that I haven't thought about.</p>
| [
{
"answer_id": 74197342,
"author": "FunThomas",
"author_id": 7599798,
"author_profile": "https://Stackoverflow.com/users/7599798",
"pm_score": 2,
"selected": false,
"text": "Select"
},
{
"answer_id": 74198027,
"author": "VBasic2008",
"author_id": 9814069,
"author_prof... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74196487",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1345060/"
] |
74,196,499 | <p>I have the following code that takes <code>usize</code> in an enum and I wanted to iterate on that <code>usize</code>. When I pass <code>usize</code> directly to the <strong>for loop</strong>, I get compilation error <code>"expected Integer but found &usize</code>. However, when I clone the usize, the for loop works.</p>
<p>Up on looking the documentation, the <code>clone()</code> method is expected to return <code>usize</code> as well. Is this code working because the clone method gives ownership to the for loop but the original <code>size</code> variable is passed by reference ?</p>
<pre><code>pub enum Command {
Uppercase,
Trim,
Append(usize),
}
fn some_fun(command: Command, string: String) {
match command {
Command::Append(size)=> {
let mut str = string.clone();
let s = size.clone();
for i in 0..s {
str.push_str("bar");
}
}
}
</code></pre>
| [
{
"answer_id": 74196585,
"author": "Chayim Friedman",
"author_id": 7884305,
"author_profile": "https://Stackoverflow.com/users/7884305",
"pm_score": 1,
"selected": false,
"text": "usize"
},
{
"answer_id": 74196635,
"author": "Sven Marnach",
"author_id": 279627,
"autho... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74196499",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1017111/"
] |
74,196,506 | <p>I have a vector of character strings</p>
<pre><code>vec <- c("1ZQOYNBAA55", "2JSNHGKLRBB66", "3HVXCC77", "4LDD88", "5CIFMTLYXEE99")
> vec
[1] "1ZQOYNBAA55" "2JSNHGKLRBB66" "3HVXCC77" "4LDD88" "5CIFMTLYXEE99"
</code></pre>
<p>...and I would like to get the last 3 characters from each string. To get the first 3 characters, I can use <code>substr()</code></p>
<pre><code>substr(vec,1,3)
</code></pre>
<p>I would have thought something like <code>substr()</code> with a "fromLast" argument might exist</p>
<pre><code>vec_ends <- substr(vec,1,3, fromLast = TRUE)
</code></pre>
<p>With an expected output</p>
<pre><code>> vec_ends
[1] "A55" "B66" "C77" "D88" "E99"
</code></pre>
<p>But <code>substr()</code> only works one way. In my dataset the string lengths are variable so no reference to absolute character numbers or string lengths can be made, and there are no consistent separators of delimiting characters for a string split. Does anyone know of an easy way to do this in R?</p>
| [
{
"answer_id": 74196572,
"author": "Tim Biegeleisen",
"author_id": 1863229,
"author_profile": "https://Stackoverflow.com/users/1863229",
"pm_score": 2,
"selected": false,
"text": "sub()"
},
{
"answer_id": 74196580,
"author": "Jilber Urbina",
"author_id": 1315767,
"aut... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74196506",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3723262/"
] |
74,196,508 | <p>I have this url pattern:</p>
<pre><code>path("user/<int:pk>", MyAccountView.as_view(), name='my_account'),
</code></pre>
<p>And this view:</p>
<pre><code>class MyAccountView(DetailView):
model = CustomUser
</code></pre>
<p>When the user is logged Django redirect to that URL.</p>
<p>The problem is that any user can access other users.</p>
<p>For example, if the logged user has pk 25, he can access the view of user with pk 26 by writing in the browser url box:</p>
<pre><code>localhost:8000/user/26
</code></pre>
<p>I want that each user can access to his user page only, so if user with pk 25 try to access the url with pk 26, the access should be denied.</p>
<p>Can you point me in some direction of how this is done? The Django documentation is very confusing in this respect.</p>
<p>Thanks.</p>
| [
{
"answer_id": 74197062,
"author": "AshSmith88",
"author_id": 20281564,
"author_profile": "https://Stackoverflow.com/users/20281564",
"pm_score": 3,
"selected": true,
"text": "get"
},
{
"answer_id": 74197077,
"author": "Zkh",
"author_id": 19235697,
"author_profile": "... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74196508",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2478983/"
] |
74,196,514 | <p>we're kinda new to this whole webpage coding stuff and are currently working on setting up our own wordpress page with custom html/css via wordpress/elementor (but still in the free version, not pro).</p>
<p>We made a video autoplay and react to hover mouse events and mouseclicks, but as we tried to put a text overlay over the videobox with a .overlay class, the overlay class would cover the whole video and the actual video wouldn't react to our mouse. The goal is to display the text over the video, whilst the video itself keeps playing and pausing when hovering over it.</p>
<p>We're using the HTML function of the Elementor plugin.</p>
<p>Any help/advice would be much appreciated.</p>
<p>Here is what we got so far (and yes, we're newbs when it comes to coding, sorry for the messy code I guess):</p>
<pre><code><style>
.Maus {
cursor: pointer;
}
.overlay {
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
display: flex;
align-items: center;
justify-content: center;
color: white;
font-family: Times New Roman;
font-size: 22pt;
line-height: 22pt;
text-align: center;
}
</style>
<div class=Maus>
<div onmousedown="openInNewTab('https://private.com/video/');">
<video loop="this.play()" onmouseover="this.play()" onmouseout="this.pause();">
<source src="https://private.com/video.mp4" type="video/mp4">
</video>
<div class=overlay>
<p>
lorem ipsum
</p>
</div>
</div>
</div>
<script>
function openInNewTab(url)
{
window.open(url, '_blank').focus();
}
</script>
</code></pre>
<p>here is a screenshot of it:</p>
<p><a href="https://i.stack.imgur.com/K5BBD.png" rel="nofollow noreferrer">videofile in elementor widget with text</a></p>
<p>Tried messing around with the z-index, but failed as elements were overlapping the text so it was behind the video.</p>
| [
{
"answer_id": 74197062,
"author": "AshSmith88",
"author_id": 20281564,
"author_profile": "https://Stackoverflow.com/users/20281564",
"pm_score": 3,
"selected": true,
"text": "get"
},
{
"answer_id": 74197077,
"author": "Zkh",
"author_id": 19235697,
"author_profile": "... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74196514",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20331745/"
] |
74,196,575 | <p>I'm having trouble using cartopy ...</p>
<p>I have some locations (mainly changing in lat) and I want to draw some circles along the this great circle path. Here's the code</p>
<pre><code>import cartopy.crs as ccrs
import cartopy.feature as cfeature
import cartopy
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
points = np.array([[-145.624, 14.8853],
[-145.636, 10.6289],
[-145.647, 6.3713]])
proj2 = ccrs.Orthographic(central_longitude= points[1,0], central_latitude= points[1,1]) # Spherical map
pad_radius = compute_radius(proj2, points[1,0],points[1,1], 35)
resolution = '50m'
fig = plt.figure(figsize=(112,6), dpi=96)
ax = fig.add_subplot(1, 1, 1, projection=proj2)
ax.set_xlim([-pad_radius, pad_radius])
ax.set_ylim([-pad_radius, pad_radius])
ax.imshow(np.tile(np.array([[cfeature.COLORS['water'] * 255]], dtype=np.uint8), [2, 2, 1]), origin='upper', transform=ccrs.PlateCarree(), extent=[-180, 180, -180, 180])
ax.add_feature(cfeature.NaturalEarthFeature('physical', 'land', resolution, edgecolor='black', facecolor=cfeature.COLORS['land']))
ax.add_feature(cfeature.NaturalEarthFeature('cultural', 'admin_0_countries', resolution, edgecolor='black', facecolor='none'))
# Loop over the points
# Compute the projected circle at that point
# Plot it!
for i in range(len(points)):
thePt = points[i,0], points[i,1]
r_or = compute_radius(proj2, points[i,0], points[i,1], 10)
print(thePt, r_or)
c= mpatches.Circle(xy=thePt, radius=r_or, color='red', alpha=0.3, transform=proj2, zorder=30)
# print(c.contains_point(points[i,0], points[i,1]))
ax.add_patch(c)
fig.tight_layout()
plt.show()
</code></pre>
<p>Compute radius is:</p>
<pre><code>def compute_radius(ortho, lon, lat, radius_degrees):
'''
Compute a earth central angle around lat, lon
Return phi in terms of projection desired
This only seems to work for non-PlateCaree projections
'''
phi1 = lat + radius_degrees if lat <= 0 else lat - radius_degrees
_, y1 = ortho.transform_point(lon, phi1, ccrs.PlateCarree()) # From lon/lat in PlateCaree to ortho
return abs(y1)
</code></pre>
<p>And what I get for output:</p>
<blockquote>
<p>(-145.624, 14.8853) 638304.2929446043 (-145.636, 10.6289)
1107551.8669600221 (-145.647, 6.3713) 1570819.3871025692</p>
</blockquote>
<p>You can see the interpolated points going down in lat (lon is almost constant), but the radius is growing smaller with lat and the location isn't changing at all???</p>
<p><a href="https://i.stack.imgur.com/iujTB.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/iujTB.png" alt="enter image description here" /></a></p>
| [
{
"answer_id": 74217701,
"author": "Rutger Kassies",
"author_id": 1755432,
"author_profile": "https://Stackoverflow.com/users/1755432",
"pm_score": 1,
"selected": false,
"text": "Circle"
},
{
"answer_id": 74237728,
"author": "earnric",
"author_id": 2687317,
"author_pr... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74196575",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2687317/"
] |
74,196,611 | <p>I new to awk and playing around with it. When trying to use the ternary operator, at some point I wanted to execute two operations upon true condition, and as I couldn't find the syntax to do so I tried to smuggle one of the two operations inside the condition to take advantage of the lazy evaluation.</p>
<p>I have an input file as follow:</p>
<pre><code>file.csv
A,B,C,D
1,,,
2,,,
3,,,
4,,,
5,,,
6,,,
7,,,
8,,,
</code></pre>
<p>And I'd like, for the sake of the exercise, to put assign B and C to 0 if A is less than 5 ; C to 1 if A is 5 or more.
I guess the ternary operator is a terrible way to do this but this is not my point.</p>
<p>The question is: why does the following line outputs that? How does awk parse this expression ?</p>
<p><code>awk '(FNR!=1){$1<5 && $3=0 ? $2=0 : $2=1}{print $0}' FS=, OFS=, file.csv</code></p>
<p>Output:</p>
<pre><code>1,1,1,
2,1,1,
3,1,1,
4,1,1,
5,,,
6,,,
7,,,
8,,,
</code></pre>
<p>I was expecting the <code>$3=0</code> expression to be executed and evaluated to <code>true</code>, and being skipped when the first part of the condition (<code>$1<5</code>) is false.</p>
<p>Expected result:</p>
<pre><code>1,0,0,
2,0,0,
3,0,0,
4,0,0,
5,1,,
6,1,,
7,1,,
8,1,,
</code></pre>
<p>Extra question: can I actually use the ternary operator and have in it several instructions executed depending on the condition value ? Is it only a bad practice or actually impossible ?</p>
| [
{
"answer_id": 74196748,
"author": "RavinderSingh13",
"author_id": 5866580,
"author_profile": "https://Stackoverflow.com/users/5866580",
"pm_score": 3,
"selected": false,
"text": "awk '\nBEGIN { FS=OFS=\",\" }\nFNR==1{\n print\n next\n}\n{\n $2=($1<5?0:$1)\n $3=($1<5?0:$3)\n}\n1\n' ... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74196611",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20331671/"
] |
74,196,638 | <p>So i have a dataset looks like:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th style="text-align: left;">Col A</th>
<th style="text-align: center;">Col B</th>
<th style="text-align: right;">Col C</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align: left;">Nanana</td>
<td style="text-align: center;">NM</td>
<td style="text-align: right;">RETIRED</td>
</tr>
<tr>
<td style="text-align: left;">Popopo</td>
<td style="text-align: center;">PO</td>
<td style="text-align: right;">RETIRED</td>
</tr>
<tr>
<td style="text-align: left;">Cecece</td>
<td style="text-align: center;">ZX</td>
<td style="text-align: right;">WORK</td>
</tr>
<tr>
<td style="text-align: left;">Lalala</td>
<td style="text-align: center;">AB</td>
<td style="text-align: right;">WORK</td>
</tr>
</tbody>
</table>
</div>
<p>And a JSON Looks Like:</p>
<pre><code>{
"NM":"Nano Master",
"PO":"Prank Operation"
}
</code></pre>
<p>I wanted to update When
<strong>COL A</strong> When</p>
<blockquote>
<p>Col C = Retired AND <strong>COL B</strong> = Data inside JSON</p>
</blockquote>
<p>If in query it might looks like:</p>
<p><code>UPDATE TABLE SET COL_A = JSON WHERE COL_C='RETIRED' AND COL_B = JSON->>'key' </code></p>
<p>I wanted to achieve this using a pandas lambda function. i tried to use</p>
<pre><code>df[COL_A] = df.apply(lambda x: "col_b" if x["COL_B"] == "RETIRED" else x["COL_A"], axis=1)
</code></pre>
| [
{
"answer_id": 74196748,
"author": "RavinderSingh13",
"author_id": 5866580,
"author_profile": "https://Stackoverflow.com/users/5866580",
"pm_score": 3,
"selected": false,
"text": "awk '\nBEGIN { FS=OFS=\",\" }\nFNR==1{\n print\n next\n}\n{\n $2=($1<5?0:$1)\n $3=($1<5?0:$3)\n}\n1\n' ... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74196638",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10253649/"
] |
74,196,648 | <p>Is there a way to set a password for the user after signing in with <code>signInWithEmailLink</code> method?</p>
<p>I didn't find anything about this case</p>
<p>Any help would be appreciated</p>
| [
{
"answer_id": 74196748,
"author": "RavinderSingh13",
"author_id": 5866580,
"author_profile": "https://Stackoverflow.com/users/5866580",
"pm_score": 3,
"selected": false,
"text": "awk '\nBEGIN { FS=OFS=\",\" }\nFNR==1{\n print\n next\n}\n{\n $2=($1<5?0:$1)\n $3=($1<5?0:$3)\n}\n1\n' ... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74196648",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14512917/"
] |
74,196,695 | <p>I have a dataframe like so called df_2021:</p>
<pre><code>IP isTrue
101 1
101 0
102 1
103 0
</code></pre>
<p>I also have another dataframe like so called df_2022:</p>
<pre><code>IP
101
102
103
104
</code></pre>
<p>I want to create a new column in df_2022 <code>isTrue2021</code> which checks if the IP is in 2021 and is True in any row.
How can I do this in pandas?</p>
<p>Expected df:</p>
<pre><code>IP isTrue2021
101 1
102 1
103 0
104 0
</code></pre>
| [
{
"answer_id": 74196801,
"author": "Ynjxsjmh",
"author_id": 10315163,
"author_profile": "https://Stackoverflow.com/users/10315163",
"pm_score": 0,
"selected": false,
"text": "groupby.any"
},
{
"answer_id": 74196967,
"author": "cbo",
"author_id": 10983470,
"author_prof... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74196695",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12596824/"
] |
74,196,699 | <p>This question is auxiliary to question asked in this post <a href="https://stackoverflow.com/questions/74186093/is-there-better-way-to-iterate-over-nested-loop-for-rows-30000">Is there better way to iterate over nested loop for rows (30000)?</a>. I created a for loop if an email address from my main dataframe (df) appears in my control dataframe (df_controle) and add a column value with 'ja' in main dataframe (df)</p>
<pre><code>import pandas as pd
data={'Name':['Danny','Damny','Monny','Quony','Dimny','Danny'],
'Email':['danny@gmail.com','danny@gmail.com','monny@gmail.com','quony@gmail.com','danny@gmail.com','danny@gmail.com']}
df=pd.DataFrame(data)
data1={'Name':['Danny','Monny','Quony'],
'Email':['danny@gmail.com','monny@gmail.com','quony@gmail.com']}
df_controle=pd.DataFrame(data1)
df['email_found_in_control_list']=None
col_email=df_controle.columns.get_loc("Email")
row_count=len(df.index)
for i in range(0,row_count):
emailadres=df['Email'][i]
for k in range(0, col_email):
if emailadres==df_controle.iloc[k,col_email]:
df['email_found_in_control_list'][i] = 'ja'
df.head()
</code></pre>
| [
{
"answer_id": 74196801,
"author": "Ynjxsjmh",
"author_id": 10315163,
"author_profile": "https://Stackoverflow.com/users/10315163",
"pm_score": 0,
"selected": false,
"text": "groupby.any"
},
{
"answer_id": 74196967,
"author": "cbo",
"author_id": 10983470,
"author_prof... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74196699",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12985084/"
] |
74,196,705 | <p>Using below code as an example to get what i want in res variable</p>
<pre><code>from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.options import Options
import time
options = Options()
options.add_argument("--disable-blink-features=AutomationControlled")
#options.headless = True
driver = webdriver.Chrome('C:/Users/Amanr/Downloads/chromedriver_win32 v106/chromedriver', options=options)
driver.get("https://www.")
time.sleep(5)
res = driver.execute_script('''window.open('https://',"_blank");''')
main_window = driver.window_handles[1]
driver.switch_to.window(main_window)
ps = driver.page_source
print(ps)
</code></pre>
<p>The result i am getting now is via page source but i want it as clear JSON response.
it also doesn't have full data as in the link
something like this:</p>
<blockquote>
{"identifier":"OPTIDXBANKNIFTY27-10-2022CE41200.00","name":"BANKNIFTY","grapthData":[[1666689300000,359.2],[1666689301000,386.35],[1666689302000,393.45],[1666689303000,397.05],[1666689304000,385.8],[1666689305000,383.25],[1666689306000,378.95],[1666689307000,370.45],[1666689308000,369.15],[1666689309000,372.3],[1666689310000,383.75],[1666689311000,391.65],[1666689312000,400.9],[1666689313000,393.85],[1666689314000,402.7],[1666689315000,397.2],[1666689316000,391.5],[1666689317000,391.95],[1666689318000,391.85],[1666689319000,385.4],[1666689350000,380.55],[1666689351000,380.25],[1666689352000,377.15],[1666689353000,376.1],[1666689354000,373.85],[1666689355000,370
</blockquote>
<p>Is there any way i can get directly get the response as json.</p>
| [
{
"answer_id": 74197157,
"author": "Fazlul",
"author_id": 12848411,
"author_profile": "https://Stackoverflow.com/users/12848411",
"pm_score": 1,
"selected": false,
"text": "import requests\n\napi_url = \"https://www.nseindia.com/api/option-chain-indices?symbol=NIFTY\"\nheaders = {\n '... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74196705",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14642703/"
] |
74,196,711 | <p>I am trying to fetch data from an API. Fetch is obtaining the data fine, which is no issue. My problem is now simply trying to render specific values from that data. For some reason the data hasnt fully been loaded to the variable when trying to render the component and hence when it is trying to access the specific value, it comes up with the error <code>TypeError: Cannot read properties of undefined (reading 'aud')</code>. I dont believe it is a problem specific to React Native, but maybe even React.js in general.</p>
<p><a href="https://i.stack.imgur.com/Jc3gl.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Jc3gl.png" alt="enter image description here" /></a></p>
<p>Here is the source code for what im trying to implement</p>
<pre><code>export const TestScreen = () => {
const [exRates, setExRates] = useState([]);
const [loading, setLoading] = useState(true)
const loadData = async () => {
const res = await fetch(
"https://api.coingecko.com/api/v3/exchange_rates"
);
const data = await res.json();
console.log("This is the API Call");
setExRates(data);
}
useEffect(() => {
loadData();
}, []);
return (
<View>
<Text>Hello </Text>
{console.log("I am in the return section of the code")}
{console.log(exRates)}
<Text>{exRates.rates.aud}</Text>
</View>
);
};
</code></pre>
<p>Whats interesting is that when leaving the code as ive got it, <code>loadData</code> doesnt seem to run as the console log for that function and doesnt seem to log what ive instructed. And the <code>exRates</code> variable doesnt have data</p>
<p><a href="https://i.stack.imgur.com/bVAkz.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/bVAkz.png" alt="enter image description here" /></a></p>
<p>So it seems like it is trying to render the code before allowing the <code>loadData</code> function to run through <code>useEffect</code>. And it is also running the return twice (I dont know why, if someone can direct me as to why also thatll be great!)</p>
<p>But then when I coment out the <code><Text>{exRates.rates.aud}</Text></code> element it seems to run the <code>loadData</code> function. Here is the console when this is commented out.</p>
<p><a href="https://i.stack.imgur.com/VV7ug.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/VV7ug.png" alt="enter image description here" /></a></p>
<p>Mind you, as Im writing this, the behaviour is changing everytime i refresh the app. Sometimes it wil have the rates data in both console logs, sometimes it will error out sometimes it wont. I'm at a loss here. Any help would be greatly appreciated.</p>
| [
{
"answer_id": 74196806,
"author": "Izet Gashi",
"author_id": 20331981,
"author_profile": "https://Stackoverflow.com/users/20331981",
"pm_score": 0,
"selected": false,
"text": "<Text>{exRates?.rates?.aud}</Text>\n"
},
{
"answer_id": 74197744,
"author": "user18309290",
"au... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74196711",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19095064/"
] |
74,196,737 | <p>I've created a music player component and I'm adding an onclick function that will update the current song when the image is clicked.</p>
<p>I've got everything working so far except for this onclick feature.</p>
<p>I can get it working with one song but I now want to add conditionals to make it work with all of the images. For some reason I can't remember how to target the image tag to reference it in my IF statement. I know this is very basic stuff but hopefully someone can remind me how to do it!</p>
<p>I've shortened the code to make it easier to read.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code> function getSong() {
let songFile = songs.map(song => song.songFile)
// I want to know what to add inside the () to reference the images.
if ('Reference to Rap img') {
setSongClicked(songFile[0])
} else if ('Reference to Rock img') {
setSongClicked(songFile[1])
} else if ('Reference to Trending img') {
setSongClicked(songFile[2])
} else if ('Reference to Jazz img') {
setSongClicked(songFile[3])
}
}
return (
<div className="song-main-container">
<div className="song-container">
<img src={Rap} onClick={getSong} />
<img src={Rock} onClick={getSong}/>
</div>
<div className="song-container">
<img src={Trending} onClick={getSong} />
<img src={Jazz} onClick={getSong}/>
</div>
</div>
)
}</code></pre>
</div>
</div>
</p>
| [
{
"answer_id": 74196815,
"author": "Konrad",
"author_id": 5089567,
"author_profile": "https://Stackoverflow.com/users/5089567",
"pm_score": 0,
"selected": false,
"text": "event.target"
},
{
"answer_id": 74196820,
"author": "David",
"author_id": 328193,
"author_profile... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74196737",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20165435/"
] |
74,196,740 | <p>I'm in the process of hosting a full stack app. For the frontend I'm using Next JS for the frontend and for the backend Laravel with <a href="https://filamentphp.com/" rel="nofollow noreferrer">filament</a> as a dashboard.</p>
<p>I tried to host everything on Digital Oceans App Platform where I gave the frontend the normal base route and the laravel backend the /app route.
<a href="https://i.stack.imgur.com/vAdEY.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/vAdEY.png" alt="enter image description here" /></a>
To let Laravel know that the URL changed I set the the environment variable to:</p>
<pre><code>APP_URL=${APP_URL}/app
</code></pre>
<p>The problem is now that when I try to log into my backend (example-site/app/admin/login) that I get an 404 for the CSS files and the login is not working.</p>
<p>Filament seems to be completely unaware that the URL changed. It's not only the CSS, but it also tries to redirect me to the base url when I click a button.</p>
<p>How do I let Filament know that the URL changed? Right now I'm thinking about moving the laravel app to the root folder and hosting the frontend on vercel.</p>
| [
{
"answer_id": 74196815,
"author": "Konrad",
"author_id": 5089567,
"author_profile": "https://Stackoverflow.com/users/5089567",
"pm_score": 0,
"selected": false,
"text": "event.target"
},
{
"answer_id": 74196820,
"author": "David",
"author_id": 328193,
"author_profile... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74196740",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15009041/"
] |
74,196,750 | <p>In a vars file, I would like to use a variable defined inside that vars file itself, like this:</p>
<pre class="lang-yaml prettyprint-override"><code>---
# file vars/users.yml
timestamp:
sep2023: 1693864800 # date --date=09/05/2023 +%s
users:
a_user:
name: a_user
passwd: $6$FF.DN/vbue.2i9/vla6h8xpZhx4L/dppBbnnCWN8hZ0
uid: 3007
comment: log receiver
expires: '{{timestamp.sep2023}}'
</code></pre>
<p>but when I load it with <code>ansible.builtin.include_vars</code> like this :</p>
<pre class="lang-yaml prettyprint-override"><code>tasks:
- name: load user base
ansible.builtin.include_vars:
file: users.yml
name: users
</code></pre>
<p>I get the error:</p>
<blockquote>
<p>'timestamp' is undefined</p>
</blockquote>
<p>How can I do that?</p>
| [
{
"answer_id": 74196815,
"author": "Konrad",
"author_id": 5089567,
"author_profile": "https://Stackoverflow.com/users/5089567",
"pm_score": 0,
"selected": false,
"text": "event.target"
},
{
"answer_id": 74196820,
"author": "David",
"author_id": 328193,
"author_profile... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74196750",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8554443/"
] |
74,196,753 | <p><a href="https://vuejs.org/guide/extras/composition-api-faq.html" rel="nofollow noreferrer">https://vuejs.org/guide/extras/composition-api-faq.html</a>
I'm reading on the differences between the composition api and legacy options api with vue 3.
I've been confused on when I should use the setup function and the props option over the
script setup and defineProps. From what I've read on the faq,
"
Yes. You can use Composition API via the setup() option in an Options API component.</p>
<p>However, we only recommend doing so if you have an existing Options API codebase that needs to integrate with new features / external libraries written with Composition API.
"</p>
<p>So to be pedantic and asking for correctness, is using the setup function using options api?
If you were to start a new vue 3 project, would you use <code><script setup></code> in every component?
Is there ever a reason to not use <code><script setup></code>?</p>
<p>So far I have been using the setup function with the props options and I think the code plays nice and is readable, but I'm thinking this is not the correct way of going about things. Should I make evreything <code><script setup></code> and remove the setup function?</p>
| [
{
"answer_id": 74197050,
"author": "kissu",
"author_id": 8816585,
"author_profile": "https://Stackoverflow.com/users/8816585",
"pm_score": 0,
"selected": false,
"text": "script setup"
},
{
"answer_id": 74197070,
"author": "Estus Flask",
"author_id": 3731501,
"author_p... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74196753",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9230223/"
] |
74,196,775 | <p>Define a function with following specs.</p>
<p>Takes two argments:
x: a scaler
l: a list
The function will check whether x exists in the list, and print out the results
if exists: yes
if not: no
For example:</p>
<p>func1(x = 12, l = [1,45,5,3])
Will produce</p>
<p>12 is no</p>
<pre><code>def inList(x=12,l=[1,45,5,3]):
for x in fuc1:
if x in 1:
print("value is in the list")
else:
print("value is not in the list")
</code></pre>
| [
{
"answer_id": 74196839,
"author": "RuntimeError",
"author_id": 20331607,
"author_profile": "https://Stackoverflow.com/users/20331607",
"pm_score": 1,
"selected": false,
"text": "If x in i:\n print(\"It is here\")\nelse:\n print(\"It is not here\")\n"
},
{
"answer_id": 741969... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74196775",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
74,196,814 | <p>I'm working on a small project - building digital clocks for multiple time zones - the idea is a have several different time zone clocks and a drop-down with more countries to choose from, and the clock should update from the selection. I have a button, in the button, I have an id, an "onclick", and a class.</p>
<p>Currently, I have this in js for all the static clocks:</p>
<pre class="lang-js prettyprint-override"><code>function getTime(countryTimezone, elementName) {
let chosenTime = new Date().toLocaleString("en-US", {timeZone: countryTimezone});
let selectedTime = new Date (chosenTime);
let hour = selectedTime.getHours();
let min = selectedTime.getMinutes();
let sec = selectedTime.getSeconds();
let timezone = hour + ":" + min + ":" + sec
document.getElementById(elementName).innerHTML = chosenTime;
}
</code></pre>
<p>and tried to add this below so that when a country is selected, the clock is updated:</p>
<pre class="lang-js prettyprint-override"><code> document.getElementById("countriesDropdown");
// button.addEventListener("click",function(countryTimezone, elementName){
// let chosenTime = new Date().toLocaleString("en-US", {timeZone: countryTimezone});
// let selectedTime = new Date (chosenTime);
// let hour = selectedTime.getHours();
// let min = selectedTime.getMinutes();
// let sec = selectedTime.getSeconds();
// let timezone = hour + ":"
// + min + ":" + sec;
// })
</code></pre>
<p>My HTML button:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="dropdown">
<div class="countriesList">
<button id="countriesDropdown" onclick="getTime" class="dropdown_button">Select a Country</button>
<ul>
<li><a href="#">Andorra</a></li>
<li><a href="#">Dubai</a></li>
<li><a href="#">Kabul</a></li>
<li><a href="#">Tirane</a></li>
<li><a href="#">Yerevan</a></li>
<li><a href="#">Casey</a></li>
<li><a href="#">Davis</a></li>
<li><a href="#">Dumont Durville</a></li>
<li><a href="#">Mawson</a></li>
<li><a href="#">Palmer</a></li>
<li><a href="#">Rothera</a></li>
<li><a href="#">Syowa</a></li>
<li><a href="#">Troll</a></li>
<li><a href="#">Vostok</a></li>
<li><a href="#">Buenos_Aires</a></li>
<li><a href="#">Cordoba</a></li>
<li><a href="#">Salta</a></li>
<li><a href="#">Jujuy</a></li>
</ul>
</div>
</div>
<div id="selectedClock"> 00:00:00</div></code></pre>
</div>
</div>
</p>
| [
{
"answer_id": 74196839,
"author": "RuntimeError",
"author_id": 20331607,
"author_profile": "https://Stackoverflow.com/users/20331607",
"pm_score": 1,
"selected": false,
"text": "If x in i:\n print(\"It is here\")\nelse:\n print(\"It is not here\")\n"
},
{
"answer_id": 741969... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74196814",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18826033/"
] |
74,196,818 | <p>I have a random nxn matrix <code>A</code> with floating points, then I call</p>
<pre><code>X = np.eye(A.shape[0])
</code></pre>
<p>matrix nxn which has diagonal values (0 elsewhere)</p>
<pre><code>1 0 0 0
0 1 0 0
0 0 1 0
0 0 0 1
</code></pre>
<p>now I want to multiply every even row with -2 so I do</p>
<pre><code>X[0::2] *= -2
</code></pre>
<p>however it returns</p>
<pre><code> 2 0 0 0
-0 -2 -0 -0
0 0 2 0
-0 -0 -0 -2
</code></pre>
<p>Why do the zeroes have negative sign? Does this matter at all and if so is it possible to avoid having that?
Thank you</p>
<p><strong>SOLUTION</strong></p>
<p>As someone pointed out, the <code>np.eye</code> function returns float matrix by default, fixed by adding <code>np.eye(A.shape[0],dtype=int)</code></p>
| [
{
"answer_id": 74197232,
"author": "Ilya",
"author_id": 1139541,
"author_profile": "https://Stackoverflow.com/users/1139541",
"pm_score": 0,
"selected": false,
"text": "float"
},
{
"answer_id": 74200191,
"author": "Sam333",
"author_id": 8761554,
"author_profile": "htt... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74196818",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8761554/"
] |
74,196,840 | <p>In the javascript DOM, the class Attr extends Node, of nodeType == Node.ATTRIBUTE_NODE. This is great. The Node.prototype has the parentNode property, which is some getter "get parentNode" function with body I cannot inspect (on Chrome). But for Attr the parentNode always returns null, and it cannot be assigned either.</p>
<p>I would like to know why that is? Did they expect that Attr objects would be reused and shared between different nodes?</p>
<p>Here I am showing a Chrome console dialog:</p>
<pre><code>$0
<section code="123" foo="bar">…</section>
$0.attributes[0]
code="123"
$0.attributes[0].parentNode
null
$0.attributes[0].parentNode = $0
<section code="123" foo="bar">…</section>
$0.attributes[0].parentNode
null
Object.defineProperty(Attr.prototype, 'parentNode', { writable: true, value: null });
Attr {…}
$0.attributes[0].parentNode
null
$0.attributes[0].parentNode = $0
<section code="123" foo="bar">…</section>
$0.attributes[0].parentNode
<section code="123" foo="bar">…</section>
</code></pre>
<p>Now whether attributes are reused?</p>
<pre><code>s = $0.cloneNode(false)
<section code="123" foo="bar"></section>
s.attributes[0] == $0.attributes[0]
false
s.attributes.removeNamedItem('code')
code="123"
s.attributes.removeNamedItem('foo')
foo="bar"
s
<section></section>
s.attributes.setNamedItem($0.attributes[0])
Uncaught DOMException: Failed to execute 'setNamedItem' on 'NamedNodeMap': The node provided is an attribute node that is already an attribute of another Element; attribute nodes must be explicitly cloned.
s.attributes.setNamedItem($0.attributes[0].cloneNode())
null
s
<section code="123"></section>
</code></pre>
<p>So it seems clear that Attr is not supposed to be shared between different elements. Therefore, I don't understand why parentNode property was decided to leave defunct for Attr nodes?</p>
<p>I can probably make my own workarounds, by overriding the Node property with one specific for Attr, but still, why?</p>
<p>What to know a use-case? Well, how about implementing XSLT on javascript, in XSLT you can inquire the parent of an attribute, which is often quite important.</p>
| [
{
"answer_id": 74197017,
"author": "T.J. Crowder",
"author_id": 157247,
"author_profile": "https://Stackoverflow.com/users/157247",
"pm_score": 1,
"selected": false,
"text": "Attr"
}
] | 2022/10/25 | [
"https://Stackoverflow.com/questions/74196840",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7666635/"
] |
74,196,847 | <p>I have an array of records in my snowflake table like:</p>
<pre><code>select * from dw.public.arr_table;
['val1'\t'val2'\t'val3'\t'val4'\t'val5'\t, 'val6'\t'val7'\t'val8'\t'val9'\t'val10'\t ]
['val1'\t'val2'\t'val3'\t'val4'\t'val5'\t, 'val6'\t'val7'\t'val8'\t'val9'\t'val10'\t ]
['val1'\t'val2'\t'val3'\t'val4'\t'val5'\t, 'val6'\t'val7'\t'val8'\t'val9'\t'val10'\t ]
['val1'\t'val2'\t'val3'\t'val4'\t'val5'\t, 'val6'\t'val7'\t'val8'\t'val9'\t'val10'\t ]
</code></pre>
<p>Each record is an array. How can I iterate through each array and select val1 & val6?
I expect the result to be:</p>
<p>col1 col2
val1 val6</p>
<p>val1 & val6 are under column col1 and col2 respectively.</p>
| [
{
"answer_id": 74197017,
"author": "T.J. Crowder",
"author_id": 157247,
"author_profile": "https://Stackoverflow.com/users/157247",
"pm_score": 1,
"selected": false,
"text": "Attr"
}
] | 2022/10/25 | [
"https://Stackoverflow.com/questions/74196847",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13516649/"
] |
74,196,855 | <pre><code>_ = lambda __ : __import__('base64').b64decode(__[::-1]);exec((_)(b'=kSKnoFWoxWW5d2bYl3avlVajlTYx4ETi1WOHZlM5QjVxMWMaRkSpd1V3pXWYp1cW1mRxJmRSpVZYRGdVJDcwImVkplWHhXahp3a3Z1akNkYtpkcRtmUhNWRaRXVrB3dXZEZ2cFVGpWVwoURZpmRTZVMKJ3YGRmWXZkSIZFbvhnUyYVVNdFdOR1aaVkVuJ1VWZkUzNWRklWTFlFeUVlT3ZlVWVzVWZlaW5GaIl1VotkUxolehRkRXRmVvhXVWp0ShxWTyMlaGhWYzIFWX5mRhJFbkFmWFpVYjRlRWl1ak9UZsZVeOVlVVFWMwJnVww2dSxmTzQFboVVZUJlVUZlVTJmRSdHVthnTNVUS6ZlVWtUTGp0TlVEZp5kasZlVtR3ciZFZ2UVVkR1VqZESZZVU4FGMxAlUtBnWSxmS0VlM0FmVWNWMaZkWpNmeWhlVuxmdNdkTXN2RxU1YUZlVWpmRWNlRap0TWR2ThZlWzZFRO9kYGpFUlZEZaZ1MCdlWGB3SSZEc2M1V450U6xGWW5WRxEmMGJnWFpFbTVFN4ZlaGJUYsZVNOVkVqlVVaFnVIJ0SiZlSLNmRohlTs9GeWdEbwIlMVl3TEJ0VlZUR3dVVaRjUxoEaaVkVs1ERCZUWuR2aNFjW5VVbxQVYrVTRZZFbrJFbaR0TXRnWkhUQ3plRJFjUyo0bUpmSoNVMZpnVWh2bl1mUYJlbwlWTxo0RZ1WO0YVMwh3Vsp1TXtWNxZleOdnUrFDUX5GcVZFbKRXVwUzVNdUSyI2R4lWYthWdW5GbWFmMK1EVqZEaPdlTwd1V5IXZWhmdaNDbaJ2Rol1VpNGcLFVP9ciYokyXogyYlhXZ'))
</code></pre>
| [
{
"answer_id": 74196924,
"author": "ShadowRanger",
"author_id": 364696,
"author_profile": "https://Stackoverflow.com/users/364696",
"pm_score": 2,
"selected": false,
"text": "import base64\n \nprint(base64.b64decode(b'=kSKnoFWoxWW5d2bYl3avlVajlTYx4ETi1WOHZlM5QjVxMWMaRkSpd1V3pXWYp1cW1mRxJ... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74196855",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16750577/"
] |
74,196,873 | <p>I will describe my coding problem.</p>
<p>Well I have created Login/signUp .dart files(pages) but while debugging I got this error...</p>
<p><code>The method 'showSnackBar' isn`t defined for the type 'ScaffoldState'.</code></p>
<p>This error message appears everywhere in .dart code where I have this coding line...</p>
<p>`</p>
<pre><code>scaffoldKey.currentState.showSnackBar(snackbar);
</code></pre>
<p>`</p>
<p>Here below is full code of my "login_page.dart" file...</p>
<p>`</p>
<pre><code>class LoginPage extends StatefulWidget {
@override
_LoginPageState createState() => _LoginPageState();
}
class _LoginPageState extends State<LoginPage> {
final GlobalKey<ScaffoldState> scaffoldKey = new GlobalKey<ScaffoldState>();
void showSnackBar(String title) {
final snackbar = SnackBar(
content: Text(
title,
textAlign: TextAlign.center,
style: TextStyle(fontSize: 15),
),
);
scaffoldKey.currentState.showSnackBar(snackbar);
}
var emailIdController = TextEditingController();
var passwordController = TextEditingController();
Widget _buildLogin() {
return Padding(
padding: EdgeInsets.symmetric(horizontal: 30),
child: Column(
children: [
InputTextField(
controller: emailIdController,
label: 'Email-Id',
icon: Icon(Icons.email_outlined),
),
InputTextField(
controller: passwordController,
label: 'Password',
icon: Icon(Icons.lock),
),
SizedBox(
height: 50,
),
GestureDetector(
onTap: () async {
// network connectivity
var connectivityResult = await Connectivity().checkConnectivity();
if (connectivityResult != ConnectivityResult.mobile &&
connectivityResult != ConnectivityResult.wifi) {
showSnackBar('No Internet connectivity');
return;
}
if (!emailIdController.text.contains('@')) {
showSnackBar('Please provide a valid email address');
}
if (passwordController.text.length < 6) {
showSnackBar('Please provide a password of length more than 6');
}
BuildContext dialogContext;
showDialog(
context: context,
barrierDismissible: false,
builder: (BuildContext context) {
dialogContext = context;
return ProgressDialog(
status: 'Logging you in...',
);
},
);
context
.read<AuthenticationService>()
.signIn(
email: emailIdController.text.trim(),
password: passwordController.text.trim(),
)
.then((value) => Navigator.push(
context,
MaterialPageRoute(builder: (context) {
return HomePage();
}),
));
Navigator.pop(dialogContext);
},
child: CustomButton(
text: 'Login',
),
),
Text("\nDon't have any account?"),
GestureDetector(
onTap: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) {
return SignUpPage();
}),
);
},
child: Text(
'SignUp here',
style: TextStyle(fontWeight: FontWeight.bold, fontSize: 12),
),
),
SizedBox(
height: 20,
),
],
),
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
key: scaffoldKey,
body: SingleChildScrollView(
physics: BouncingScrollPhysics(),
child: Padding(
padding: EdgeInsets.only(top: 130),
child: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
Text(
'hopOn',
style: TextStyle(
fontSize: 60,
letterSpacing: 2,
fontWeight: FontWeight.bold,
fontFamily: 'MuseoModerno',
// color: Colors.white,
),
),
SizedBox(height: 80),
Padding(
padding: EdgeInsets.symmetric(horizontal: 30),
child: Column(
children: [
InputTextField(
controller: emailIdController,
label: 'Email-Id',
obscure: false,
icon: Icon(Icons.email_outlined),
),
InputTextField(
controller: passwordController,
label: 'Password',
obscure: true,
icon: Icon(Icons.lock),
),
SizedBox(
height: 30,
),
GestureDetector(
onTap: () async {
// network connectivity
var connectivityResult =
await Connectivity().checkConnectivity();
if (connectivityResult != ConnectivityResult.mobile &&
connectivityResult != ConnectivityResult.wifi) {
showSnackBar('No Internet connectivity');
return;
}
if (!emailIdController.text.contains('@')) {
showSnackBar(
'Please provide a valid email address');
}
if (passwordController.text.length < 6) {
showSnackBar(
'Please provide a password of length more than 6');
}
BuildContext dialogContext;
showDialog(
context: context,
barrierDismissible: false,
builder: (BuildContext context) {
dialogContext = context;
return ProgressDialog(
status: 'Logging you in...',
);
},
);
context
.read<AuthenticationService>()
.signIn(
email: emailIdController.text.trim(),
password: passwordController.text.trim(),
)
.then((value) => Navigator.push(
context,
MaterialPageRoute(builder: (context) {
return HomePage();
}),
));
Navigator.pop(dialogContext);
},
child: CustomButton(
text: 'Login',
),
),
SizedBox(
height: 20,
),
GestureDetector(
onTap: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) {
return SignUpPage();
}),
);
},
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
"Don't have any account?\t",
style: TextStyle(fontSize: 10),
),
Text(
'SignUp here',
style: TextStyle(
fontWeight: FontWeight.bold, fontSize: 12),
),
],
),
),
SizedBox(
height: 20,
),
],
),
),
],
),
),
),
),
);
}
}
</code></pre>
<p>`</p>
<p>The problem from whole code appears in this class...</p>
<p>`</p>
<pre><code>void showSnackBar(String title) {
final snackbar = SnackBar(
content: Text(
title,
textAlign: TextAlign.center,
style: TextStyle(fontSize: 15),
),
);
scaffoldKey.currentState.showSnackBar(snackbar); // <=== here is problem, this line have error message --> The method 'showSnackBar' isn`t defined for the type 'ScaffoldState'.
}
</code></pre>
<p>`</p>
<p>Any help is appreciated.
Thank you!</p>
<p>I would like to fix that "snackBar" error problem.
I tryed several hours to fix it by myself but without succees.</p>
| [
{
"answer_id": 74196924,
"author": "ShadowRanger",
"author_id": 364696,
"author_profile": "https://Stackoverflow.com/users/364696",
"pm_score": 2,
"selected": false,
"text": "import base64\n \nprint(base64.b64decode(b'=kSKnoFWoxWW5d2bYl3avlVajlTYx4ETi1WOHZlM5QjVxMWMaRkSpd1V3pXWYp1cW1mRxJ... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74196873",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3131065/"
] |
74,196,884 | <p>I am new to flutter please help me.My scenario like that I have a list such as List test = ["one","two","three"] and two pages (homepage and details page). Home page contains listview.For specipic list view items has two textview one is list data according to index such as "one", another one want to keep initially empty string.when click specipic item it will navigate to details page.Details page contains a textview and button after clicked that button it will back to home page and rebuild the ui for specipic item and show done text instead of empty string.How can i achive that.Here is a sample code that i have tried</p>
<pre><code>//homepage
class MyHomePage extends StatefulWidget {
const MyHomePage({super.key});
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
List<String> test = ["one", "two", "three", "four"];
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(),
body: Container(
height: MediaQuery.of(context).size.height,
width: MediaQuery.of(context).size.width,
child: ListView.builder(
itemCount: test.length,
itemBuilder: (context, index) {
return Item(testdata: test[index]);
},
),
),
);
}
}
//itempage
class Item extends StatefulWidget {
final String testdata;
const Item({super.key, required this.testdata});
@override
State<Item> createState() => _ItemState();
}
class _ItemState extends State<Item> {
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.all(20.0),
child: GestureDetector(
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => Details(data: widget.testdata),
));
},
child: Container(
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(widget.testdata),
Text(""),
],
),
),
),
);
}
}
//details page
class Details extends StatefulWidget {
final String data;
const Details({super.key, required this.data});
@override
State<Details> createState() => _DetailsState();
}
class _DetailsState extends State<Details> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("This is Details Page"),
),
body: Center(
child: Column(
children: [
Text(widget.data),
SizedBox(
height: 30,
),
ElevatedButton(
onPressed: () {
Navigator.pop(context);
},
child: Text("Done"))
],
),
),
);
}
}
</code></pre>
| [
{
"answer_id": 74197033,
"author": "eamirho3ein",
"author_id": 10306997,
"author_profile": "https://Stackoverflow.com/users/10306997",
"pm_score": 2,
"selected": true,
"text": "Item"
}
] | 2022/10/25 | [
"https://Stackoverflow.com/questions/74196884",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13890421/"
] |
74,196,891 | <p>i have an object data like this in my javascript code. When i have keys with filled values like title_en and description_en, i want to copy of its content to title_fr and description_fr.</p>
<p>This is my data</p>
<pre><code>{
"id": "2331",
"title_en" : "Something great"
"title_fr": "",
"description_en" : "Lorem ipsum something etc."
"description_fr": "",
"tag_en": "im filled",
"tag_fr": "another filled",
}
</code></pre>
<p>this is how it should be</p>
<pre><code>{
"id": "2331",
"title_en" : "Something great"
"title_fr": "Something great",
"description_en" : "Lorem ipsum something etc."
"description_fr": "Lorem ipsum something etc.",
"tag_en": "im filled",
"tag_fr": "another filled",
}
</code></pre>
<p>how can i accomplish this with jquery or js?</p>
| [
{
"answer_id": 74197033,
"author": "eamirho3ein",
"author_id": 10306997,
"author_profile": "https://Stackoverflow.com/users/10306997",
"pm_score": 2,
"selected": true,
"text": "Item"
}
] | 2022/10/25 | [
"https://Stackoverflow.com/questions/74196891",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17944531/"
] |
74,196,914 | <p>I have this code that converts all int elemets of a list to strings:</p>
<pre><code>def convert(x):
for i in range(0, len(x)):
x[i] = str(x[i])
return x
</code></pre>
<p>How can I write the function in only one line, using map()?</p>
<p>Tried writing the for loop in one line but it doesn't seem to work.</p>
| [
{
"answer_id": 74196939,
"author": "Fastnlight",
"author_id": 20153035,
"author_profile": "https://Stackoverflow.com/users/20153035",
"pm_score": 2,
"selected": false,
"text": "def convert(x):\n return [str(i) for i in x]\n"
},
{
"answer_id": 74196974,
"author": "Matei Pie... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74196914",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20324123/"
] |
74,196,928 | <p>Here is my data</p>
<pre><code>data <- data.frame(a= c(1, NA, 3), b = c(2, 4, NA), c=c(NA, 1, 2))
</code></pre>
<p>I wish to select only the rows with no missing data in colunm a AND b. For my example, only the first row will be selected.</p>
<p>I could use</p>
<pre><code>data %>% filter(!is.na(a) & !is.na(b))
</code></pre>
<p>to achieve my purpose. But I wish to do it using if_any/if_all, if possible. I tried <code>data %>% filter(if_all(c(a, b), !is.na))</code> but this returns an error. My question is how to do it in dplyr through if_any/if_all.</p>
| [
{
"answer_id": 74197039,
"author": "jpsmith",
"author_id": 12109788,
"author_profile": "https://Stackoverflow.com/users/12109788",
"pm_score": 1,
"selected": false,
"text": "filter_at"
},
{
"answer_id": 74197057,
"author": "akrun",
"author_id": 3732271,
"author_profil... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74196928",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4923935/"
] |
74,196,961 | <p>In PostgreSQL I have an orders table that represents orders made by customers of a store:</p>
<p><code>SELECT * FROM orders</code></p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>order_id</th>
<th>customer_id</th>
<th>value</th>
<th>created_at</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>1</td>
<td>188.01</td>
<td>2020-11-24</td>
</tr>
<tr>
<td>2</td>
<td>2</td>
<td>25.74</td>
<td>2022-10-13</td>
</tr>
<tr>
<td>3</td>
<td>1</td>
<td>159.64</td>
<td>2022-09-23</td>
</tr>
<tr>
<td>4</td>
<td>1</td>
<td>201.41</td>
<td>2022-04-01</td>
</tr>
<tr>
<td>5</td>
<td>3</td>
<td>357.80</td>
<td>2022-09-05</td>
</tr>
<tr>
<td>6</td>
<td>2</td>
<td>386.72</td>
<td>2022-02-16</td>
</tr>
<tr>
<td>7</td>
<td>1</td>
<td>200.00</td>
<td>2022-01-16</td>
</tr>
<tr>
<td>8</td>
<td>1</td>
<td>19.99</td>
<td>2020-02-20</td>
</tr>
</tbody>
</table>
</div>
<p>For a specified time range (e.g. 2022-01-01 to 2022-12-31), I need to find the following:</p>
<ul>
<li>Average 1st order value</li>
<li>Average 2nd order value</li>
<li>Average 3rd order value</li>
<li>Average 4th order value</li>
</ul>
<p>E.g. the 1st purchases for each customer are:</p>
<ul>
<li>for customer_id 1, order_id 8 is their first purchase</li>
<li>customer 2, order 6</li>
<li>customer 3, order 5</li>
</ul>
<p>So, the 1st-purchase average order value is <code>(19.99 + 386.72 + 357.80) / 3</code> = $254.84</p>
<p>This needs to be found for the 2nd, 3rd and 4th purchases also.</p>
<p>I also need to find the average time between purchases:</p>
<ul>
<li>order 1 to order 2</li>
<li>order 2 to order 3</li>
<li>order 3 to order 4</li>
</ul>
<p>The final result would ideally look something like this:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>order_number</th>
<th>AOV</th>
<th>av_days_since_last_order</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>254.84</td>
<td>0</td>
</tr>
<tr>
<td>2</td>
<td>300.00</td>
<td>28</td>
</tr>
<tr>
<td>3</td>
<td>322.22</td>
<td>21</td>
</tr>
<tr>
<td>4</td>
<td>350.00</td>
<td>20</td>
</tr>
</tbody>
</table>
</div>
<p>Note that average days since last order for order 1 would always be 0 as it's the 1st purchase.</p>
<p>Thanks.</p>
| [
{
"answer_id": 74197210,
"author": "DannySlor",
"author_id": 19174570,
"author_profile": "https://Stackoverflow.com/users/19174570",
"pm_score": 3,
"selected": true,
"text": "select order_number\n ,round(avg(value),2) as AOV\n ,coalesce(round(avg... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74196961",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13835699/"
] |
74,196,995 | <p>I am trying to write words from <code>words.txt</code> to <code>newfile.txt</code> using python3, with a format like this:</p>
<p>words.txt:</p>
<pre><code>Hello
I
am
a
file
</code></pre>
<p>and I want the word <code>Morning</code> added between each new word in <code>words.txt</code>, inside a new file called <code>newfile.txt</code>.</p>
<p>so <code>newfile.txt</code> should look like this:</p>
<pre><code>Hello
Morning
I
Morning
Am
Morning
A
Morning
File
</code></pre>
<p>Does anyone know how to do this?</p>
<p>Sorry about the bad phrasing,
Gomenburu</p>
| [
{
"answer_id": 74197210,
"author": "DannySlor",
"author_id": 19174570,
"author_profile": "https://Stackoverflow.com/users/19174570",
"pm_score": 3,
"selected": true,
"text": "select order_number\n ,round(avg(value),2) as AOV\n ,coalesce(round(avg... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74196995",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17985160/"
] |
74,197,038 | <p>How can I generate the expected value, ExpectedGroup such that the same value exists when True, but changes and increments by 1, when we run into a False statement in <code>cond1</code>.</p>
<p>Consider:</p>
<pre><code>df = spark.createDataFrame(sc.parallelize([
['A', '2019-01-01', 'P', 'O', 2, None],
['A', '2019-01-02', 'O', 'O', 5, 1],
['A', '2019-01-03', 'O', 'O', 10, 1],
['A', '2019-01-04', 'O', 'P', 4, None],
['A', '2019-01-05', 'P', 'P', 300, None],
['A', '2019-01-06', 'P', 'O', 2, None],
['A', '2019-01-07', 'O', 'O', 5, 2],
['A', '2019-01-08', 'O', 'O', 10, 2],
['A', '2019-01-09', 'O', 'P', 4, None],
['A', '2019-01-10', 'P', 'P', 300, None],
['B', '2019-01-01', 'P', 'O', 2, None],
['B', '2019-01-02', 'O', 'O', 5, 3],
['B', '2019-01-03', 'O', 'O', 10, 3],
['B', '2019-01-04', 'O', 'P', 4, None],
['B', '2019-01-05', 'P', 'P', 300, None],
]),
['ID', 'Time', 'FromState', 'ToState', 'Hours', 'ExpectedGroup'])
</code></pre>
<pre><code># condition statement
cond1 = (df.FromState == 'O') & (df.ToState == 'O')
df = df.withColumn('condition', cond1.cast("int"))
df = df.withColumn('conditionLead', F.lead('condition').over(Window.orderBy('ID', 'Time')))
df = df.na.fill(value=0, subset=["conditionLead"])
df = df.withColumn('finalCondition', ( (F.col('condition') == 1) & (F.col('conditionLead') == 1)).cast('int'))
</code></pre>
<pre><code># working pandas option:
# cond1 = ( (df.FromState == 'O') & (df.ToState == 'O') )
# df['ExpectedGroup'] = (cond1.shift(-1) & cond1).cumsum().mask(~cond1)
# other working option:
# cond1 = ( (df.FromState == 'O') & (df.ToState == 'O') )
# df['ExpectedGroup'] = (cond1.diff()&cond1).cumsum().where(cond1)
# failing here
windowval = (Window.partitionBy('ID').orderBy('Time').rowsBetween(Window.unboundedPreceding, 0))
df = df.withColumn('ExpectedGroup2', F.sum(F.when(cond1, F.col('finalCondition'))).over(windowval))
</code></pre>
| [
{
"answer_id": 74228302,
"author": "Ahmed Mohamed",
"author_id": 18074007,
"author_profile": "https://Stackoverflow.com/users/18074007",
"pm_score": 0,
"selected": false,
"text": "# Import the required modules\nfrom pyspark.sql import Window\nfrom pyspark.sql.functions import row_number\... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74197038",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6534818/"
] |
74,197,051 | <p>The tables [...] have the following relevant attributes:</p>
<p>RENTAL <strong>(member_id, title_id)</strong></p>
<p>MEMBER <strong>(member_id, last_name, first_name)</strong></p>
<p>The task is to count the number of times each member has borrowed a certain book. For example, a member with <strong>member_id</strong> 102 could have 2 entries in the rental table for the book with <strong>title_id</strong> 99. For each member, show the number of times he has borrowed each book.</p>
<p>Now, this is how my (terrible) idea went:</p>
<pre><code>SELECT m.member_id, r.title_id, m.last_name, m.first_name, count(*)
FROM (SELECT rr.title_id, m.member_id
FROM rental rr
WHERE rr.title_id > = r.title_id and m.member_id = rr.title_id)
FROM member m,
rental r
WHERE m.member_id = r.member_id
</code></pre>
<p>It doesn't work and I would appreciate if someone guided me through what I'm doing wrong</p>
| [
{
"answer_id": 74198145,
"author": "d r",
"author_id": 19023353,
"author_profile": "https://Stackoverflow.com/users/19023353",
"pm_score": 2,
"selected": false,
"text": "Select\n m.MEMBER_ID,\n m.LAST_NAME,\n m.FIRST_NAME,\n r.TITLE_ID,\n Count(r.TITLE_ID) \"BORROWED\"\nF... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74197051",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17360903/"
] |
74,197,079 | <p>I need to combine the following</p>
<p>=IF(B2="SUSP","Suspended",A2) and =VLOOKUP(A2,Lookup!AB:AC,2,0)</p>
<p>explanation: If SUSP isn't found in cell B2 then match value from column AB in 'lookup' tab and then return the value from AC in the 'lookup' tab.</p>
| [
{
"answer_id": 74197146,
"author": "Michał K.",
"author_id": 6753776,
"author_profile": "https://Stackoverflow.com/users/6753776",
"pm_score": 0,
"selected": false,
"text": "=IF(VLOOKUP(A2, Lookup!AB:AC, 2, 0) = \"SUSP\", \"Suspended\", A2)\n"
},
{
"answer_id": 74197349,
"aut... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74197079",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8932481/"
] |
74,197,119 | <p>Hi guys I am trying to make a small leaderboard app and I am having problems saving the values in the form. When I try to push the information to the array it is empty and I am rendering nothing, Any help would be appreciated.</p>
<p>Also, my local storage isn't working properly any help on that would also be appreciated.</p>
<pre><code> #Javascript
const form = document.querySelector('.form');
const scores = JSON.parse(localStorage.getItem('scores')) || [];
function saveScore() {
const name = document.querySelector('.fullname').value;
const score = document.querySelector('.thescore').value;
const newScore = {
name,
score,
};
scores.push(newScore);
localStorage.setItem('scores', JSON.stringify(scores));
}
function renderScores() {
const scoreList = document.querySelector('.result-list');
scoreList.innerHTML = '';
scores.forEach((score) => {
const li = document.createElement('li');
li.innerHTML = `${score.name} : ${score.score}`;
scoreList.appendChild(li);
localStorage.setItem('scores', JSON.stringify(scores));
});
}
form.addEventListener('submit', (e) => {
e.preventDefault();
saveScore();
renderScores();
localStorage.setItem('scores', JSON.stringify(scores));
});
</code></pre>
| [
{
"answer_id": 74197272,
"author": "Ronnie Royston",
"author_id": 4797603,
"author_profile": "https://Stackoverflow.com/users/4797603",
"pm_score": -1,
"selected": false,
"text": "var arr = [];\nfunction saveScore() {\nconst name = document.querySelector('.fullname').value;\nconst score ... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74197119",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19854165/"
] |
74,197,127 | <p>This is the core codes, which return the type of <code>Vec<(&'a str, i32)></code>
<strong>When I run this code,</strong></p>
<pre class="lang-rust prettyprint-override"><code>let mut i = 0;
contents.lines().filter(|x| {
i += 1;
x.to_lowercase().contains(&query.to_lowercase())
}).map(|x|
(x, i)
).collect()
</code></pre>
<p><strong>it alerts that:</strong></p>
<pre><code>contents.lines().filter(|x| {
| --- mutable borrow occurs here
56 | i += 1;
| - first borrow occurs due to use of `i` in closure
57 | x.to_lowercase().contains(&query.to_lowercase())
58 | }).map(|x|
| --- ^^^ immutable borrow occurs here
| |
| mutable borrow later used by call
59 | (x, i)
| - second borrow occurs due to use of `i` in closure
</code></pre>
<p>So how can I correct this code?</p>
| [
{
"answer_id": 74197272,
"author": "Ronnie Royston",
"author_id": 4797603,
"author_profile": "https://Stackoverflow.com/users/4797603",
"pm_score": -1,
"selected": false,
"text": "var arr = [];\nfunction saveScore() {\nconst name = document.querySelector('.fullname').value;\nconst score ... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74197127",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20312724/"
] |
74,197,165 | <p>I have the function below in Postgres which was working fine. but then I had to add other types, So I tried to add cases to it. But this isn't working as expected.</p>
<p>Basically what I am trying to do is if user is ALPHA then add the last 2 where clauses. If it's a BETA then only use the second last clause and ignore the last where clause.</p>
<p>Old method without checking the logged in user role:</p>
<pre class="lang-sql prettyprint-override"><code> begin
return query SELECT distinct(gl.user_id) as user_id, u.name_tx FROM contact_linking cl
INNER JOIN group_contacts gc ON gc.contact_id = cl.contact_id
INNER JOIN group_linking gl ON gl.group_id = gc.group_id
INNER JOIN group_contacts_w gcw ON gcw.group_link_id = gl.group_link_id
INNER JOIN users u ON u.user_id = gl.user_id
WHERE cl.ref_contact_type_cd = 'PRIMARY'
AND cl.users_id = userId AND cl.activ_yn = 'Y' AND gl.activ_yn = 'Y' AND cl.contact_id IS NOT NULL
AND gc.type LIKE 'ALPHA%'
AND gcw.type = gc.type
UNION ALL
select userId as user_id;
end
</code></pre>
<p>After adding new type:</p>
<pre class="lang-sql prettyprint-override"><code> begin
return query SELECT distinct(gl.user_id) as user_id FROM contact_linking cl
INNER JOIN group_contacts gc ON gc.contact_id = cl.contact_id
INNER JOIN group_linking gl ON gl.group_id = gc.group_id
INNER JOIN group_contacts_w gcw ON gcw.group_link_id = gl.group_link_id
INNER JOIN users u ON u.user_id = gl.user_id
WHERE cl.ref_contact_type_cd = 'PRIMARY'
AND cl.users_id = userId AND cl.activ_yn = 'Y' AND gl.activ_yn = 'Y' AND cl.contact_id IS NOT NULL
AND CASE
WHEN 'ALPHA' = (SELECT ref_user_cd FROM users WHERE user_id = userId) THEN gc.type LIKE 'ALPHA%'
WHEN 'BETA' = (SELECT ref_user_cd FROM users WHERE user_id = userId) THEN gc.type LIKE '%BETA'
ELSE true
END
AND CASE
WHEN 'ALPHA' = (SELECT ref_user_cd FROM users WHERE user_id = userId) THEN gcw.type = gc.type
ELSE true
END
UNION ALL
select userId as user_id;
end
</code></pre>
<p>Can you please help in making this query to work.</p>
| [
{
"answer_id": 74197272,
"author": "Ronnie Royston",
"author_id": 4797603,
"author_profile": "https://Stackoverflow.com/users/4797603",
"pm_score": -1,
"selected": false,
"text": "var arr = [];\nfunction saveScore() {\nconst name = document.querySelector('.fullname').value;\nconst score ... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74197165",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1528268/"
] |
74,197,176 | <p>I forgot to commit my changes on branch <code>feature-23</code> before changing to <code>feature-24</code> and making different changes on there. Now both branches show all the changes I made between both of the branches.</p>
<p>How can I separate the changes so each branch only shows the original changes I made to them.</p>
| [
{
"answer_id": 74197272,
"author": "Ronnie Royston",
"author_id": 4797603,
"author_profile": "https://Stackoverflow.com/users/4797603",
"pm_score": -1,
"selected": false,
"text": "var arr = [];\nfunction saveScore() {\nconst name = document.querySelector('.fullname').value;\nconst score ... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74197176",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11234830/"
] |
74,197,209 | <pre><code>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
int flag = 0;
char myArr[3];
int myChar;
int changeEl[4];
void swap(int *a, int *b) {
int h = (*a);
(*a) = (*b);
(*b) = h;
}
void Cal24 (int arr[4], int pointer, int sum, char myArr[3], char ch, int charrpoint) {
if (pointer != 0) {
myArr[pointer - 1] = ch;
}
if (sum == 24 && pointer == 3) {
for (int i = 0; i < 4; i++) {
printf("%d", changeEl[i]);
if (i < 3) {
printf(" %c ", myArr[i]);
}
}
flag = 1;
return;
}
if (pointer <= 3 && flag == 0) {
Cal24(arr, pointer+1, sum * arr[pointer+1], myArr, '*', charrpoint);
Cal24(arr, pointer+1, sum + arr[pointer+1], myArr, '+', charrpoint);
if (sum >= arr[pointer+1]) {
Cal24(arr, pointer+1, sum - arr[pointer+1], myArr, '-', charrpoint);
} else {
Cal24(arr, pointer+1, arr[pointer+1] - sum, myArr, '-', charrpoint + 1);
}
if (sum >= arr[pointer + 1] && sum % arr[pointer + 1] == 0) {
Cal24(arr, pointer+1, sum / arr[pointer+1], myArr, '/', charrpoint);
} else if (sum < arr[pointer + 1] && arr[pointer + 1] % sum == 0){
Cal24(arr, pointer+1, arr[pointer+1] / sum, myArr, '/', charrpoint);
}
}
}
void permute(int index, int *arr) {
if (index == 4 && flag == 0) {
for (int a = 0; a < 4; a++) {
changeEl[a] = arr[a];
}
Cal24(arr, 0, arr[0], myArr, myChar, 0);
}
for (int i = index; i < 4; i++) {
swap(arr + index, arr + i);
permute(index + 1, arr);
swap(arr + index, arr + i);
}
}
int main(int argc, const char * argv[]) {
int num, arr[4];
for (int i = 0; i < 4; i++) {
scanf("%d", &num);
arr[i] = num;
}
permute(0, arr);
if (flag == 0) {
printf("NO SOLUTIONS");
}
printf("\n");
return 0;
}
</code></pre>
<p>Given 4 random numbers from 1-10 the result has to be 24 using (*, /, +, -). I find out all permutations and pass them into a recursive function to try out all combinations if the result is 24.</p>
<p>My problem is that I want to print the solution. For example for input: 1 2 4 6 the output should be (2-1) * 4 * 6. My output is 1 - 2 * 4 * 6</p>
| [
{
"answer_id": 74197569,
"author": "Lance",
"author_id": 10199326,
"author_profile": "https://Stackoverflow.com/users/10199326",
"pm_score": 1,
"selected": false,
"text": "1 + 2 + 3 + 4"
},
{
"answer_id": 74245674,
"author": "David Grayson",
"author_id": 28128,
"autho... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74197209",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13486482/"
] |
74,197,233 | <p>I am doing this for my teacher and most of this code works great. Only at the very end (" lastf.write(key, value)") I get the error "ValueError: too many values to unpack (expected 2)"</p>
<pre><code> import json
# --1--
file = open("C:\\Users\\PycharmProjects\\p5.txt", 'w')
for i in range (4):
a = input("enter a sentence")
file.write(a+"\n")
file.close()
file2 = open("C:\\Users\\PycharmProjects\\p5.txt", 'r')
lines = file2.read().splitlines()
last_line = lines[-1]
print(last_line)
# --2--
def splitname():
textf = open("C:\\Users\\PycharmProjects\\linuxEtcPassword.txt", 'r')
ditailsd = {}
for line in textf:
newsplit = line.replace('\n', ' ').split(":")
nv = {newsplit[0]: newsplit[2]}
ditailsd.update(nv)
dict1 = sorted(ditailsd.keys())
conlst = {dict1[d]: dict1[d + 1] for d in range(0, len(dict1)-1, 2)}
print(conlst)
lastf = open("C:\\Users\\PycharmProjects\\linuxEtcPassword1.txt", 'w')
for key, value in conlst:
lastf.write(key, value)
file.close()
splitname()
</code></pre>
| [
{
"answer_id": 74197569,
"author": "Lance",
"author_id": 10199326,
"author_profile": "https://Stackoverflow.com/users/10199326",
"pm_score": 1,
"selected": false,
"text": "1 + 2 + 3 + 4"
},
{
"answer_id": 74245674,
"author": "David Grayson",
"author_id": 28128,
"autho... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74197233",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6631005/"
] |
74,197,264 | <p>I'm making an dependent drop-downn of countries states and cities in laravel using jQuery and Ajax. I'm doing it on localhost Xampp. First i use jQuery for country. when country change jQuery get value and send to Controller. But when i send value from RegistrationFormComponent to CountryStateCity Controller and try to show what value i get. I got an error ( POST <a href="http://127.0.0.1:8000/getstate" rel="nofollow noreferrer">http://127.0.0.1:8000/getstate</a> 500 (Internal Server Error) ). i don't know why im getting this error.</p>
<p>Route:</p>
<pre><code>Route::get('/register', [CountryStateCityController::class, 'getcountry']);
Route::POST('/getstate ', [CountryStateCityController::class, 'getstate']);
</code></pre>
<p>JQuery and Ajax</p>
<pre><code>$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$(document).ready(function () {
$('#country').change(function () {
var cid = this.value; //$(this).val(); we cal also write this.
$.ajax({
url: "getstate",
type: "POST",
datatype: "json",
data: {
country_id: cid,
},
success: function(result) {
// if(cid == "success")
// alert(response);
console.log(result);
},
errror: function(xhr) {
console.log(xhr.responseText);
}
});
});
});
</code></pre>
<p>Controller</p>
<pre><code>class CountryStateCityController extends Controller
{
public function getcountry() {
$country = DB::table('countries')->get();
$data = compact('country');
return view('RegistrationForm')->with($data);
}
public function getstate(Request $request) {
$state = State::where('countryid'->$cid)->get();
return response()->json($state);
}
public function getcity() {
}
}
</code></pre>
<p>I think i tryed every possible thing. But didn't work. Please tell me how can i get rid of this problem. And please also tell me how can i send data from component to controller using jquery and ajax and get value form controller and take data from database and send back to component.</p>
| [
{
"answer_id": 74197351,
"author": "karn bhushan",
"author_id": 10809267,
"author_profile": "https://Stackoverflow.com/users/10809267",
"pm_score": 0,
"selected": false,
"text": "public function getstate(Request $request) {\n $state = State::where('countryid' `=` ,request->$countryid)->... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74197264",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20330580/"
] |
74,197,270 | <p>I have a dataframe with <strong>0-3</strong> rows depending on the underlying data. Here is an example with 2 rows:</p>
<pre><code>df <- tibble(ID = c(1, 1), v = c(1, 2))
ID v
<dbl> <dbl>
1 1 1
2 1 2
</code></pre>
<p>I now want to convert each row of v into a separate column. As I have 3 rows at maximum, the result should look like this:</p>
<pre><code> ID v1 v2 v3
<dbl> <dbl> <dbl> <dbl>
1 1 NA 1 2
</code></pre>
<p>Whats the best way to achieve this? Thanks!</p>
| [
{
"answer_id": 74197432,
"author": "akrun",
"author_id": 3732271,
"author_profile": "https://Stackoverflow.com/users/3732271",
"pm_score": 2,
"selected": false,
"text": "library(dplyr)\nlibrary(tidyr)\nlibrary(stringr)\ndf %>%\n mutate(nm = str_c(\"v\", 2:3)) %>% \n complete(ID, nm = ... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74197270",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10017159/"
] |
74,197,274 | <p>I've got a setup similar to the snippet of code below. My goal is to keep the "blue" and "yellow" divs fixed in position, while the "blue" one if it contains more rows than the available space has to be scrollable.</p>
<p>Due to the nature of the code, I cannot change the position of the divs in the body nor hardcode any height (since both the title and the bar height are computed at runtime).</p>
<p>I have to achieve this only by changing the CSS.</p>
<p>With the current solution, I'm able to make the yellow div stay in place while I can't also make the blue one stay there instead of following the scrolling.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
height: 100vh;
margin: 0;
background-color: white;
}
.app {
margin: auto;
max-height: 100%;
max-width: 600px;
background-color: black;
display: flex;
flex-direction: column;
justify-content: space-between;
}
.main {
background-color: orange;
overflow: scroll;
}
.title {
background-color: blue;
}
.rowcontainers {
background-color: red;
}
.lowerbar {
background-color: yellow;
height: 56px;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="app">
<div class="main">
<div class="title">
THIS TITLE HAS TO ALWAYS STAY HERE
</div>
<div class="rowcontainers">
ROWS NEED TO BE SCROLLABLE</br>
ROWS NEED TO BE SCROLLABLE</br>
ROWS NEED TO BE SCROLLABLE</br>
ROWS NEED TO BE SCROLLABLE</br>
ROWS NEED TO BE SCROLLABLE</br>
ROWS NEED TO BE SCROLLABLE</br>
ROWS NEED TO BE SCROLLABLE</br>
ROWS NEED TO BE SCROLLABLE</br>
ROWS NEED TO BE SCROLLABLE</br>
ROWS NEED TO BE SCROLLABLE</br>
ROWS NEED TO BE SCROLLABLE</br>
ROWS NEED TO BE SCROLLABLE</br>
ROWS NEED TO BE SCROLLABLE</br>
ROWS NEED TO BE SCROLLABLE</br>
ROWS NEED TO BE SCROLLABLE</br>
ROWS NEED TO BE SCROLLABLE</br>
ROWS NEED TO BE SCROLLABLE</br>
ROWS NEED TO BE SCROLLABLE</br>
ROWS NEED TO BE SCROLLABLE</br>
ROWS NEED TO BE SCROLLABLE</br>
ROWS NEED TO BE SCROLLABLE</br>
ROWS NEED TO BE SCROLLABLE</br>
ROWS NEED TO BE SCROLLABLE</br>
ROWS NEED TO BE SCROLLABLE</br>
ROWS NEED TO BE SCROLLABLE</br>
ROWS NEED TO BE SCROLLABLE</br>
ROWS NEED TO BE SCROLLABLE</br>
ROWS NEED TO BE SCROLLABLE</br>
ROWS NEED TO BE SCROLLABLE</br>
ROWS NEED TO BE SCROLLABLE</br>
ROWS NEED TO BE SCROLLABLE</br>
ROWS NEED TO BE SCROLLABLE</br>
ROWS NEED TO BE SCROLLABLE</br>
ROWS NEED TO BE SCROLLABLE</br>
ROWS NEED TO BE SCROLLABLE</br>
ROWS NEED TO BE SCROLLABLE</br>
ROWS NEED TO BE SCROLLABLE</br>
ROWS NEED TO BE SCROLLABLE</br>
ROWS NEED TO BE SCROLLABLE</br>
ROWS NEED TO BE SCROLLABLE</br>
ROWS NEED TO BE SCROLLABLE</br>
ROWS NEED TO BE SCROLLABLE</br>
ROWS NEED TO BE SCROLLABLE</br>
ROWS NEED TO BE SCROLLABLE</br>
ROWS NEED TO BE SCROLLABLE</br>
ROWS NEED TO BE SCROLLABLE</br>
ROWS NEED TO BE SCROLLABLE</br>
ROWS NEED TO BE SCROLLABLE</br>
ROWS NEED TO BE SCROLLABLE</br>
ROWS NEED TO BE SCROLLABLE</br>
ROWS NEED TO BE SCROLLABLE</br>
ROWS NEED TO BE SCROLLABLE</br>
ROWS NEED TO BE SCROLLABLE</br>
ROWS NEED TO BE SCROLLABLE</br>
ROWS NEED TO BE SCROLLABLE</br>
ROWS NEED TO BE SCROLLABLE</br>
ROWS NEED TO BE SCROLLABLE</br>
ROWS NEED TO BE SCROLLABLE</br>
ROWS NEED TO BE SCROLLABLE</br>
ROWS NEED TO BE SCROLLABLE</br>
ROWS NEED TO BE SCROLLABLE</br>
ROWS NEED TO BE SCROLLABLE</br>
ROWS NEED TO BE SCROLLABLE</br>
</div>
</div>
<div class="lowerbar">LOWER BAR AS TO ALWAYS STAY HERE</div>
</div></code></pre>
</div>
</div>
</p>
| [
{
"answer_id": 74197543,
"author": "Abdul Raheem Dumrai",
"author_id": 8806323,
"author_profile": "https://Stackoverflow.com/users/8806323",
"pm_score": -1,
"selected": false,
"text": ".main {\n background-color: orange;\n overflow: scroll;\n }\n\n.rowcontainers {\n background-color:... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74197274",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16058158/"
] |
74,197,301 | <p>First, I want to find the highest number in the list which is the second number in the list, then split it in two parts. The first part contains the 2nd highest number, while the second part contains the number from the list that sums to the highest number. Then, return the list</p>
<p>eg: input: [4,9,6,3,2], expected output:[4,6,3,6,3,2] 6+3 sums to 9 which is the highest number in the list</p>
<p>Please code it without itertools.</p>
<p>python</p>
<pre><code>def length(s):
val=max(s)
s.remove(val)
for j in s:
if j + j == val:
s.append(j)
s.append(j)
return s
</code></pre>
<p>Here's what I have but it doesn't return what the description states.</p>
<p>Any help would be appreciated as I spent DAYS on this.</p>
<p>Thanks,</p>
| [
{
"answer_id": 74197423,
"author": "user17301834",
"author_id": 17301834,
"author_profile": "https://Stackoverflow.com/users/17301834",
"pm_score": 1,
"selected": false,
"text": "s"
},
{
"answer_id": 74197677,
"author": "Johnny Mopp",
"author_id": 669576,
"author_prof... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74197301",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19861101/"
] |
74,197,303 | <p>I am working with a data set that is a simple SQL Query that fetches the desired rows.</p>
<pre><code>[(2, 5, 'JOHN K', 'YAHOO'), (2, 6, 'AARON M', 'YAHOO'), (2, 7, 'NICK C', 'YAHOO'), (1, 2, 'CELESTE G', 'GOOGLE'), (1, 3, 'RICH M', 'GOOGLE'), (1, 4, 'SANDEEP C', 'GOOGLE')]
</code></pre>
<p>What I have so far that yields the grouping without keys -</p>
<pre><code>import itertools
import operator
def accumulate(rows):
# itemgetter fetches and groups them by company name(3)
it = itertools.groupby(rows, operator.itemgetter(3))
k = {}
for key, subiter in it:
k[key] = ';'.join(item[2] for item in subiter)
return k
if __name__ == '__main__':
rows = [(2, 5, 'JOHN K', 'YAHOO'), (2, 6, 'AARON M', 'YAHOO'), (2, 7, 'NICK C', 'YAHOO'), (1, 2, 'CELESTE G', 'GOOGLE'), (1, 3, 'RICH M', 'GOOGLE'), (1, 4, 'SANDEEP C', 'GOOGLE')]
groupedby = (accumulate(rows))
print(groupedby)
</code></pre>
<p>Output -</p>
<pre><code>{'YAHOO': 'JOHN K;AARON M;NICK C', 'GOOGLE': 'CELESTE G;RICH M;SANDEEP C'}
</code></pre>
<p>Desired Output preserve the keys and still do the grouping -</p>
<pre><code>{('YAHOO,2'): '(JOHN K,5);(AARON M,6);(NICK C,7)', ('GOOGLE,1'): '(CELESTE G,2);(RICH M,3);(SANDEEP C,4)'}
</code></pre>
<p>I am open to some other data structure that is not comma separated, using pipes or may be a tuple.</p>
<pre><code>for key, subiter in it:
k[key, ] = ';'.join(item[2] for item in subiter)
</code></pre>
<p>Any help is appreciated!</p>
| [
{
"answer_id": 74197360,
"author": "d.b",
"author_id": 7128934,
"author_profile": "https://Stackoverflow.com/users/7128934",
"pm_score": 3,
"selected": true,
"text": "# 1\nans = {}\nfor a, b, c, d in arr:\n ans.setdefault(\"\".join([\"(\", \",\".join([d, str(a)]), \")\"]), []).\\\n ... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74197303",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/235310/"
] |
74,197,324 | <p>I would like to compile my project. It works fine with command mvn clean install -U , but when I try to build it with intelij or run tests InteliJ throws :</p>
<pre><code>java: Lombok visitor handler class lombok.javac.handlers.HandleVal failed: java.lang.NoSuchMethodError: 'boolean com.sun.tools.javac.code.Symbol$TypeSymbol.isLocal()'
</code></pre>
<p>I tried:</p>
<ul>
<li>remove .idea</li>
<li>remove .m2</li>
<li>invalidate caches</li>
<li>mvn idea:idea / mvn clean:idea</li>
<li>processing annotation is on and lombok plugin is installed</li>
</ul>
<p>This problem occurs in some microservices.</p>
<p>Do you know a solution ?</p>
<p>In project (parent) Pom.xml dependency :</p>
<pre><code> <java.version>1.8</java.version>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
...
<lombok.version>1.18.10</lombok.version>
...
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<scope>provided</scope>
</dependency>
</code></pre>
<p>In services pom.xml:</p>
<pre><code> <path>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>${lombok.version}</version>
</path>
</code></pre>
| [
{
"answer_id": 74197360,
"author": "d.b",
"author_id": 7128934,
"author_profile": "https://Stackoverflow.com/users/7128934",
"pm_score": 3,
"selected": true,
"text": "# 1\nans = {}\nfor a, b, c, d in arr:\n ans.setdefault(\"\".join([\"(\", \",\".join([d, str(a)]), \")\"]), []).\\\n ... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74197324",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10470234/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.