qid
int64 4
19.1M
| question
stringlengths 18
48.3k
| answers
list | date
stringlengths 10
10
| metadata
list |
|---|---|---|---|---|
74,613,334
|
<p>possible null reference argument for parameter 's' parse in 'double double.Parse(string s)'</p>
<pre><code>dr = cm.ExecuteReader();
while (dr.Read())
{
i += 1;
_total += double.Parse(s: dr["total"].ToString()); // warning message
dataGridView1.Rows.Add(i, dr["id"].ToString(), dr["transno"].ToString(), dr["pcode"].ToString(), dr["pdesc"].ToString(), dr["price"].ToString(), dr["qty"].ToString(), dr["disc"].ToString(), dr["total"].ToString());
}
</code></pre>
|
[
{
"answer_id": 74613410,
"author": "alec_djinn",
"author_id": 3190076,
"author_profile": "https://Stackoverflow.com/users/3190076",
"pm_score": 0,
"selected": false,
"text": "def parse_entry(entry):\n\n #remove currency and spaces\n entry = entry.replace(\"Kč\", \"\")\n entry = entry.replace(\" \", \"\")\n\n #check if a comma is used for decimals or thousands\n comma_i = entry.find(\",\")\n if len(entry[comma_i:]) > 3: #it's a thousands separator, it can be removed\n entry = entry.replace(\",\", \"\")\n else: #it's a decimal separator\n entry = entry.replace(\",\", \".\") #convert it to dot\n\n #remove extra dots\n while entry.count(\".\") > 1:\n entry = entry.replace(\".\", \"\", 1) #replace once\n return round(float(entry), 1) #round to 1 decimal\n\nmy_list = ['100,30 Kč','10 000,00 Kč', '10,000.00 Kč', '10000 Kč', '32.100,30 Kč', '12.345,678.91 Kč']\nparsed = list(map(parse_entry, my_list))\nprint(parsed) #[100.3, 10000.0, 10000.0, 10000.0, 32100.3, 12345678.9]\n"
},
{
"answer_id": 74613434,
"author": "Bob",
"author_id": 12750353,
"author_profile": "https://Stackoverflow.com/users/12750353",
"pm_score": 2,
"selected": true,
"text": "import re\n\nmy_list = ['100,30 Kč','10 000,00 Kč', '10,000.00 Kč', '10000 Kč', '32.100,30 Kč', '12.345,678.91 Kč']\n\nfor s in my_list:\n parts = list(re.findall('\\d+', s))\n if len(parts) == 1 or len(parts[-1]) != 2:\n parts.append('0')\n print(float(''.join(parts[:-1]) + '.' + parts[-1]))\n"
},
{
"answer_id": 74613457,
"author": "alphaBetaGamma",
"author_id": 12959241,
"author_profile": "https://Stackoverflow.com/users/12959241",
"pm_score": 0,
"selected": false,
"text": "import re\n\nmy_list = ['100,30 Kč','10 000,00 Kč', '10,000.00 Kč', '10000 Kč', '32.100,30 Kč', '12.345,678.91 Kč']\n\nfor i in my_list:\n ws = i.replace(\"Kč\", '')\n x = re.sub(',','.', ws).replace(\" \",\"\")\n \n if len( x.split(\".\"))>1:\n end= x.split(\".\")[-1]\n x = \"\".join([i for i in x.split(\".\")[:-1]])+\".\"+end\n print(x)\n"
},
{
"answer_id": 74613680,
"author": "gvee",
"author_id": 2610022,
"author_profile": "https://Stackoverflow.com/users/2610022",
"pm_score": 0,
"selected": false,
"text": "import re\n\nvalues = [\n \"100,30 Kč\",\n \"10 000,00 Kč\",\n \"10,000.00 Kč\",\n \"10000 Kč\",\n \"32.100,30 Kč\",\n \"12.345,678.91 Kč\", # This value is a bit odd... is it _right_?\n]\n\nfor value in values:\n # Remove any character that's not a number or a comma\n value = re.sub(\"[^0-9,]\", \"\", value)\n\n # Replace remaining commas with periods\n value = value.replace(\",\", \".\")\n\n # Convert from string to number\n value = float(value)\n\n print(value)\n 100.3\n10000.0\n10.0\n10000.0\n32100.3\n12345.67891\n"
},
{
"answer_id": 74613983,
"author": "Cobra",
"author_id": 17580381,
"author_profile": "https://Stackoverflow.com/users/17580381",
"pm_score": 0,
"selected": false,
"text": "my_list = ['100,30 Kč','10 000,00 Kč', '10,000.00 Kč', '10000 Kč', '32.100,30 Kč', '12.345,678.91 Kč']\n\ndef fix(s):\n r = []\n for c in s:\n if c in '0123456789':\n r.append(c)\n elif c == ',':\n r.append('.')\n elif not c in '. ':\n break\n return float(''.join(r))\n\nfor n in my_list:\n print(fix(n))\n 100.3\n10000.0\n10.0\n10000.0\n32100.3\n12345.67891\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74613334",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20132700/"
] |
74,613,349
|
<p>I'm new with Redux, and I'd like to improve performances of my web app as much as possible.</p>
<p>I have a state in redux, that I store in a variable to display it later.</p>
<p>Here is the code :</p>
<pre><code>const metricsState = useSelector((state: MetricsStateObject) => state.MetricsState);
const myMetrics = metricsState.myMetrics;
</code></pre>
<p>I saw that <a href="https://www.w3schools.com/react/react_usememo.asp" rel="nofollow noreferrer">useMemo</a> improve performance by not re-render if the data did not mutate.</p>
<p>So I'm wondering if <code>const myMetrics = useMemo(() => metricsState.myMetrics, [metricsState.myMetrics]);</code> is a good practice, or totaly useless ?</p>
<p>Thank you for your time.</p>
|
[
{
"answer_id": 74614008,
"author": "Alvin",
"author_id": 4134662,
"author_profile": "https://Stackoverflow.com/users/4134662",
"pm_score": 1,
"selected": true,
"text": "metricsState.myMetrics value-taking useMemo"
},
{
"answer_id": 74614018,
"author": "Wraithy",
"author_id": 16116506,
"author_profile": "https://Stackoverflow.com/users/16116506",
"pm_score": 1,
"selected": false,
"text": "useMemo const something = useMemo(()=> megaBigArray.reduce((acc,i)=>acc*i,0), [megaBigArray])\n megaBigArray useSelector"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74613349",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17978333/"
] |
74,613,359
|
<pre><code>::tm tm{0, 0, 0, 29, 10, 2022 - 1900, 0, 0}; // 10 for November
auto time_t = ::mktime(&tm);
cout << "milliseconds = " << time_t * 1000 << endl;
</code></pre>
<p>Above code outputs <code>1669660200000</code>, which is equivalent to <strong>2022 November 29, 00:00:00</strong>. But it is in local timezone. How to get the UTC time for the aforementioned date?<br />
A modern <a href="/questions/tagged/c%2b%2b17" class="post-tag" title="show questions tagged 'c++17'" aria-label="show questions tagged 'c++17'" rel="tag" aria-labelledby="c++17-container">c++17</a> way with thread-safety will be appreciated.</p>
|
[
{
"answer_id": 74615623,
"author": "Howard Hinnant",
"author_id": 576911,
"author_profile": "https://Stackoverflow.com/users/576911",
"pm_score": 2,
"selected": true,
"text": "tm #include \"date/date.h\"\n#include <chrono>\n#include <iostream>\n\nint\nmain()\n{\n using namespace std;\n using namespace chrono;\n using namespace date;\n\n sys_time<milliseconds> tp = sys_days{2022_y/11/29};\n cout << \"milliseconds = \" << tp.time_since_epoch().count() << '\\n';\n}\n milliseconds = 1669680000000\n #include <chrono>\n#include <iostream>\n\nint\nmain()\n{\n using namespace std;\n using namespace chrono;\n\n sys_time<milliseconds> tp = sys_days{2022y/11/29};\n cout << \"milliseconds = \" << tp.time_since_epoch() << '\\n';\n}\n milliseconds = 1669680000000ms\n"
},
{
"answer_id": 74626643,
"author": "iammilind",
"author_id": 514235,
"author_profile": "https://Stackoverflow.com/users/514235",
"pm_score": 0,
"selected": false,
"text": "static const auto TIMEZONE_OFFSET = [] (const ::time_t seconds)\n{ // This method is to be called only once per execution\n ::tm tmGMT = {}, tmLocal = {}; \n ::gmtime_r(&seconds, &tmGMT); // ::gmtime_s() for WINDOWS\n ::localtime_r(&seconds, &tmLocal); // ::localtime_s() for WINDOWS\n return ::mktime(&tmGMT) - ::mktime(&tmLocal);\n}(10000);\n\n::tm tm{0, 0, 0, 29, 10, 2022 - 1900}; // set fields 1 by 1 as the order is not guaranteed\ncout << \" start of day = \" << (::mktime(&tm) - TIMEZONE_OFFSET) << endl;\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74613359",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/514235/"
] |
74,613,413
|
<p>```const timeoutError = new error_1.MongoServerSelectionError(<code>Server selection timed out after ${serverSelectionTimeoutMS} ms</code>, this.description);
.MongoServerSelectionError: connect ECONNREFUSED ::1:27017</p>
<pre><code>const {MongoClient}=require('mongodb');
const url='mongodb://localhost:27017/';
const client= new MongoClient(url);
const dataBase= 'nodejs';
async function getdata(){
let result= await client.connect();
console.log('connect to server')
let db= result.db(dataBase)
console.log('2')
let collection = db.collection('node');
let response= await collection.find({}).toArray();
console.log(response)
}
getdata();
</code></pre>
|
[
{
"answer_id": 74613928,
"author": "Iangyl",
"author_id": 12228149,
"author_profile": "https://Stackoverflow.com/users/12228149",
"pm_score": 0,
"selected": false,
"text": "Control Panel\\System and Security\\Administrative Tools npm start"
},
{
"answer_id": 74614470,
"author": "Muqtadir Billah",
"author_id": 16016637,
"author_profile": "https://Stackoverflow.com/users/16016637",
"pm_score": 2,
"selected": true,
"text": "const url='mongodb://0.0.0.0:27017/';\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74613413",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19856261/"
] |
74,613,420
|
<p>How can I return the <strong>second</strong> most frequent text in a column?</p>
<p>I know that I can find the most frequent text in A2:A60 by using =INDEX(A2:A60;MODE(MATCH(A2:A60;A2:A60;0)))</p>
|
[
{
"answer_id": 74613634,
"author": "JvdV",
"author_id": 9758194,
"author_profile": "https://Stackoverflow.com/users/9758194",
"pm_score": 2,
"selected": false,
"text": "B1 =INDEX(SORTBY(UNIQUE(A1:A9),COUNTIF(A1:A9,UNIQUE(A1:A9)),-1),2)\n =LET(a,UNIQUE(A1:A9),b,COUNTIF(A1:A9,a),TAKE(SORT(FILTER(HSTACK(a,b),b<MAX(b)),2,-1),1,1))\n"
},
{
"answer_id": 74620277,
"author": "Tom Sharpe",
"author_id": 3894917,
"author_profile": "https://Stackoverflow.com/users/3894917",
"pm_score": 3,
"selected": true,
"text": "=LET(range,A1:A9,\nuniques,UNIQUE(range),\ncounts,COUNTIF(range,uniques),\nsCounts,UNIQUE(SORT(counts,1,-1)),\nFILTER(uniques,counts=INDEX(sCounts,2)))\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74613420",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17298382/"
] |
74,613,484
|
<p>I am trying to get data from the db into node js but getting error . I have got the data from the frontend and stored it in the backend but when I try to get the stored data I get error.</p>
<p>React js:(frontend)</p>
<pre><code>import React, { useEffect } from "react";
import axios from "axios";
export default function marketPlace(){
useEffect(()=>{
fetchingData();
})
const fetchingData = ()=>{
axios.get("http://localhost:4040/api/nftdata")
.then(res=>{
console.log(res)
})
.catch(err=>{
console.log(err)
})
}
return(
<div>
MArket Place
</div>
)
}
</code></pre>
<p>Backend:</p>
<pre><code>index.js:
var express = require("express");
var app =express()
var cors = require("cors");
var bodyparser = require("body-parser");
var router = require('./router/router');
const connectDB = require('./db/db');
require('./sevice/transactionChecker')(app);
connectDB();
var PORT = 4040
app.use(cors());
app.use(bodyparser.json());
app.use(bodyparser.urlencoded({extended:false}));
app.use('/api', router);
app.listen(PORT,()=>{
console.log(`Listening in ${PORT}`)
})
module.exports = app;
router.js:
var express = require("express")
var router = express.Router();
//var app = express();
const aadiTransaction = require('../controller/aadiTransaction');
const nftIds = require('../controller/nftIds');
const nftData = require('../controller/nftIds');
const ids = require('../controller/nftdata');
router.get("/", (req, res) => {
res.statusCode = 200;
res.setHeader("Content-Type", "text/plain");
res.json({
code: 200,
dismsg: "Api is Running...",
});
});
router.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
router.post('/ids', nftIds)
router.get('/inserttrans/:coinpair/:tx/:tokencount', aadiTransaction)
router.get('/nftdata', nftData)
module.exports = router;
</code></pre>
<p>schema:</p>
<pre><code>const mongoose = require("mongoose");
const ids = new mongoose.Schema(
{
id: {
type: String,
required: true
},
name:{
type:String,
required: true
},
description:{
type:String,
required: true
},
imageUrl:{
type: String,
required: true
},
price:{
type: Number,
required: true
},
videoUrl:{
type: String
}
}
)
module.exports = mongoose.model("contacts", ids);
</code></pre>
<p>nftData.js :</p>
<pre><code>const mongoose = require('mongoose')
require('dotenv').config()
const ids = require('../modals/nftId')
const nftData = async(req,res)=>{
await ids.find({})
.then((data)=>{
console.log(data)
res.json(data)
})
.catch((err)=>{
console.log(err)
})
}
module.exports = nftData;
</code></pre>
<p>I have data in my database when I try to get the data I get these errors.</p>
<pre><code>Error: contacts validation failed: id: Path `id` is required., name: Path `name` is required., description: Path `description` is required., imageUrl: Path `imageUrl` is required., price: Path `price` is required.
at ValidationError.inspect (C:\Users\gauth\OneDrive\Desktop\mint\server\node_modules\mongoose\lib\error\validation.js:50:26)
at formatValue (node:internal/util/inspect:806:19)
at inspect (node:internal/util/inspect:365:10)
at formatWithOptionsInternal (node:internal/util/inspect:2292:40)
at formatWithOptions (node:internal/util/inspect:2154:10)
at console.value (node:internal/console/constructor:339:14)
at console.log (node:internal/console/constructor:376:61)
at C:\Users\gauth\OneDrive\Desktop\mint\server\controller\nftIds.js:32:13
at processTicksAndRejections (node:internal/process/task_queues:96:5) {
errors: {
id: ValidatorError: Path `id` is required.
at validate (C:\Users\gauth\OneDrive\Desktop\mint\server\node_modules\mongoose\lib\schematype.js:1346:13)
at SchemaString.SchemaType.doValidate (C:\Users\gauth\OneDrive\Desktop\mint\server\node_modules\mongoose\lib\schematype.js:1330:7)
at C:\Users\gauth\OneDrive\Desktop\mint\server\node_modules\mongoose\lib\document.js:2903:18
at processTicksAndRejections (node:internal/process/task_queues:78:11) {
properties: [Object],
kind: 'required',
path: 'id',
value: undefined,
reason: undefined,
[Symbol(mongoose:validatorError)]: true
},
name: ValidatorError: Path `name` is required.
at validate (C:\Users\gauth\OneDrive\Desktop\mint\server\node_modules\mongoose\lib\schematype.js:1346:13)
at SchemaString.SchemaType.doValidate (C:\Users\gauth\OneDrive\Desktop\mint\server\node_modules\mongoose\lib\schematype.js:1330:7)
at C:\Users\gauth\OneDrive\Desktop\mint\server\node_modules\mongoose\lib\document.js:2903:18
at processTicksAndRejections (node:internal/process/task_queues:78:11) {
properties: [Object],
kind: 'required',
path: 'name',
value: undefined,
reason: undefined,
[Symbol(mongoose:validatorError)]: true
},
description: ValidatorError: Path `description` is required.
at validate (C:\Users\gauth\OneDrive\Desktop\mint\server\node_modules\mongoose\lib\schematype.js:1346:13)
at SchemaString.SchemaType.doValidate (C:\Users\gauth\OneDrive\Desktop\mint\server\node_modules\mongoose\lib\schematype.js:1330:7)
at C:\Users\gauth\OneDrive\Desktop\mint\server\node_modules\mongoose\lib\document.js:2903:18
at processTicksAndRejections (node:internal/process/task_queues:78:11) {
properties: [Object],
kind: 'required',
path: 'description',
value: undefined,
reason: undefined,
[Symbol(mongoose:validatorError)]: true
},
imageUrl: ValidatorError: Path `imageUrl` is required.
at validate (C:\Users\gauth\OneDrive\Desktop\mint\server\node_modules\mongoose\lib\schematype.js:1346:13)
at SchemaString.SchemaType.doValidate (C:\Users\gauth\OneDrive\Desktop\mint\server\node_modules\mongoose\lib\schematype.js:1330:7)
at C:\Users\gauth\OneDrive\Desktop\mint\server\node_modules\mongoose\lib\document.js:2903:18
at processTicksAndRejections (node:internal/process/task_queues:78:11) {
properties: [Object],
kind: 'required',
path: 'imageUrl',
value: undefined,
reason: undefined,
[Symbol(mongoose:validatorError)]: true
},
price: ValidatorError: Path `price` is required.
at validate (C:\Users\gauth\OneDrive\Desktop\mint\server\node_modules\mongoose\lib\schematype.js:1346:13)
at SchemaNumber.SchemaType.doValidate (C:\Users\gauth\OneDrive\Desktop\mint\server\node_modules\mongoose\lib\schematype.js:1330:7)
at C:\Users\gauth\OneDrive\Desktop\mint\server\node_modules\mongoose\lib\document.js:2903:18
at processTicksAndRejections (node:internal/process/task_queues:78:11) {
properties: [Object],
kind: 'required',
path: 'price',
value: undefined,
reason: undefined,
[Symbol(mongoose:validatorError)]: true
}
},
_message: 'contacts validation failed'
}
Error: contacts validation failed: id: Path `id` is required., name: Path `name` is required., description: Path `description` is required., imageUrl: Path `imageUrl` is required., price: Path `price` is required.
at ValidationError.inspect (C:\Users\gauth\OneDrive\Desktop\mint\server\node_modules\mongoose\lib\error\validation.js:50:26)
at formatValue (node:internal/util/inspect:806:19)
at inspect (node:internal/util/inspect:365:10)
at formatWithOptionsInternal (node:internal/util/inspect:2292:40)
at formatWithOptions (node:internal/util/inspect:2154:10)
at console.value (node:internal/console/constructor:339:14)
at console.log (node:internal/console/constructor:376:61)
at C:\Users\gauth\OneDrive\Desktop\mint\server\controller\nftIds.js:32:13
at processTicksAndRejections (node:internal/process/task_queues:96:5) {
errors: {
id: ValidatorError: Path `id` is required.
at validate (C:\Users\gauth\OneDrive\Desktop\mint\server\node_modules\mongoose\lib\schematype.js:1346:13)
at SchemaString.SchemaType.doValidate (C:\Users\gauth\OneDrive\Desktop\mint\server\node_modules\mongoose\lib\schematype.js:1330:7)
at C:\Users\gauth\OneDrive\Desktop\mint\server\node_modules\mongoose\lib\document.js:2903:18
at processTicksAndRejections (node:internal/process/task_queues:78:11) {
properties: [Object],
kind: 'required',
path: 'id',
value: undefined,
reason: undefined,
[Symbol(mongoose:validatorError)]: true
},
name: ValidatorError: Path `name` is required.
at validate (C:\Users\gauth\OneDrive\Desktop\mint\server\node_modules\mongoose\lib\schematype.js:1346:13)
at SchemaString.SchemaType.doValidate (C:\Users\gauth\OneDrive\Desktop\mint\server\node_modules\mongoose\lib\schematype.js:1330:7)
at C:\Users\gauth\OneDrive\Desktop\mint\server\node_modules\mongoose\lib\document.js:2903:18
at processTicksAndRejections (node:internal/process/task_queues:78:11) {
properties: [Object],
kind: 'required',
path: 'name',
value: undefined,
reason: undefined,
[Symbol(mongoose:validatorError)]: true
},
description: ValidatorError: Path `description` is required.
at validate (C:\Users\gauth\OneDrive\Desktop\mint\server\node_modules\mongoose\lib\schematype.js:1346:13)
at SchemaString.SchemaType.doValidate (C:\Users\gauth\OneDrive\Desktop\mint\server\node_modules\mongoose\lib\schematype.js:1330:7)
at C:\Users\gauth\OneDrive\Desktop\mint\server\node_modules\mongoose\lib\document.js:2903:18
at processTicksAndRejections (node:internal/process/task_queues:78:11) {
properties: [Object],
kind: 'required',
path: 'description',
value: undefined,
reason: undefined,
[Symbol(mongoose:validatorError)]: true
},
imageUrl: ValidatorError: Path `imageUrl` is required.
at validate (C:\Users\gauth\OneDrive\Desktop\mint\server\node_modules\mongoose\lib\schematype.js:1346:13)
at SchemaString.SchemaType.doValidate (C:\Users\gauth\OneDrive\Desktop\mint\server\node_modules\mongoose\lib\schematype.js:1330:7)
at C:\Users\gauth\OneDrive\Desktop\mint\server\node_modules\mongoose\lib\document.js:2903:18
at processTicksAndRejections (node:internal/process/task_queues:78:11) {
properties: [Object],
kind: 'required',
path: 'imageUrl',
value: undefined,
reason: undefined,
[Symbol(mongoose:validatorError)]: true
},
price: ValidatorError: Path `price` is required.
at validate (C:\Users\gauth\OneDrive\Desktop\mint\server\node_modules\mongoose\lib\schematype.js:1346:13)
at SchemaNumber.SchemaType.doValidate (C:\Users\gauth\OneDrive\Desktop\mint\server\node_modules\mongoose\lib\schematype.js:1330:7)
at C:\Users\gauth\OneDrive\Desktop\mint\server\node_modules\mongoose\lib\document.js:2903:18
at processTicksAndRejections (node:internal/process/task_queues:78:11) {
properties: [Object],
kind: 'required',
path: 'price',
value: undefined,
reason: undefined,
[Symbol(mongoose:validatorError)]: true
}
},
_message: 'contacts validation failed'
}
</code></pre>
|
[
{
"answer_id": 74613633,
"author": "rehan.ankalgi",
"author_id": 16041272,
"author_profile": "https://Stackoverflow.com/users/16041272",
"pm_score": 0,
"selected": false,
"text": "// package.json\nproxy: \"http://localhost:4040\"\n"
},
{
"answer_id": 74613697,
"author": "rehan.ankalgi",
"author_id": 16041272,
"author_profile": "https://Stackoverflow.com/users/16041272",
"pm_score": 1,
"selected": false,
"text": "const nftIds = require('../controller/nftIds');\nconst nftData = require('../controller/nftIds');\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74613484",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18036750/"
] |
74,613,491
|
<p>I'm using DOMMatrix to set transform on a canvas context, but I am not sure how to "fix" the translation after the rotate. Currently the code I've written rotates an image around a given point on the canvas, which works fine. The issue is after the rotation, the translate moves relative to the rotation, which is not what I want. I want the translation to be relative to the canvas.</p>
<p><a href="https://codesandbox.io/s/beautiful-frog-zxqcdh?file=/src/index.js" rel="nofollow noreferrer">CodeSandbox demo</a></p>
<p>I implemented this function which I read "fixes" the translation after rotation, but it doesn't seem to do what I need:</p>
<pre class="lang-js prettyprint-override"><code>function rotate(x, y, rotation) {
const panXX = x * Math.cos((rotation * Math.PI) / 180);
const panXY = y * Math.sin((rotation * Math.PI) / 180);
const panYY = y * Math.cos((rotation * Math.PI) / 180);
const panYX = x * Math.sin((rotation * Math.PI) / 180);
const panX = panXX + panXY;
const panY = panYY - panYX;
return { x: panX, y: panY };
}
</code></pre>
<p>Is there a way of doing this, either by modifying the <code>rotate</code> function above, or the <code>DOMMatrix</code>, or a different way entirely?</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>let rotation = 0;
let scale = 1;
let x = 0;
let y = 0;
let startX = 0;
let startY = 0;
let lastX = 0;
let lastY = 0;
let pointerDown = false;
const canvas = document.querySelector("#canvas");
const ctx = canvas.getContext("2d");
const imgWidth = 480;
const imgHeight = 300;
function resizeCanvas() {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
}
resizeCanvas();
window.addEventListener("resize", resizeCanvas);
const img = new Image();
img.crossOrigin = "anonymous";
img.src = "https://i.imgur.com/3q3kNGh.png";
function onPointerDown(event) {
pointerDown = true;
startX = (event.clientX - canvas.offsetLeft) / imgWidth;
startY = (event.clientY - canvas.offsetTop) / imgHeight;
}
function onPointerMove(event) {
if (!pointerDown) return;
x = lastX + ((event.clientX - canvas.offsetLeft) / imgWidth - startX);
y = lastY + ((event.clientY - canvas.offsetTop) / imgHeight - startY);
}
function onPointerUp() {
pointerDown = false;
lastX = x;
lastY = y;
}
window.addEventListener("pointerdown", onPointerDown);
window.addEventListener("pointermove", onPointerMove);
window.addEventListener("pointerup", onPointerUp);
window.addEventListener("keydown", (event) => {
const key = event.key.toLowerCase();
switch (key) {
case "r":
rotation = (rotation + 5) % 360;
break;
case "-":
scale = Math.max(0, scale - 0.1);
break;
case "=":
scale = Math.min(2, scale + 0.1);
break;
default:
break;
}
});
function rotate(x, y, rotation) {
const panXX = x * Math.cos((rotation * Math.PI) / 180);
const panXY = y * Math.sin((rotation * Math.PI) / 180);
const panYY = y * Math.cos((rotation * Math.PI) / 180);
const panYX = x * Math.sin((rotation * Math.PI) / 180);
const panX = panXX + panXY;
const panY = panYY - panYX;
return { x: panX, y: panY };
}
(function draw() {
requestAnimationFrame(draw);
const imgX = imgWidth * x;
const imgY = imgHeight * y;
const { x: tX, y: tY } = rotate(imgX, imgY, rotation);
const ox = canvas.width / 2 - imgX;
const oy = canvas.height / 2 - imgY;
const matrix = new DOMMatrix()
.translate(ox, oy)
.rotate(rotation)
.translate(-ox, -oy)
.translate(tX, tY)
.scale(scale);
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.setTransform(matrix);
ctx.drawImage(img, 0, 0, imgWidth, imgHeight);
ctx.resetTransform();
ctx.fillStyle = "rgba(255, 0, 0, 0.5)";
ctx.fillRect(canvas.width / 2 - 5, canvas.height / 2 - 5, 10, 10);
})();</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>html,
body {
margin: 0;
padding: 0;
}
canvas {
display: block;
}
pre {
position: absolute;
bottom: 0;
left: 0;
padding: 0.5em;
pointer-events: none;
user-select: none;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><canvas id="canvas"></canvas>
<pre>
Hotkeys
---
Rotate: r
Zoom out: -
Zoom in: =
</pre></code></pre>
</div>
</div>
</p>
|
[
{
"answer_id": 74614327,
"author": "ibrahim tanyalcin",
"author_id": 9410412,
"author_profile": "https://Stackoverflow.com/users/9410412",
"pm_score": 0,
"selected": false,
"text": "const matrix = new DOMMatrix()\n.translate(imgWidth/2, imgHeight/2)\n.rotate(rotation)\n.scale(scale)\n.translate(-imgWidth/2 + tX / scale, -imgHeight/2 + tY / scale);\n imgWidth / 2 canvas.width / 2 -imgWidth / 2 -canvas.width / 2"
},
{
"answer_id": 74616744,
"author": "ardget",
"author_id": 12793185,
"author_profile": "https://Stackoverflow.com/users/12793185",
"pm_score": 3,
"selected": true,
"text": "rotate() function onPointerMove(event) {\n if (!pointerDown) return;\n \n //x = lastX + ((event.clientX - canvas.offsetLeft) / imgWidth - startX);\n //y = lastY + ((event.clientY - canvas.offsetTop) / imgHeight - startY);\n\n let deltaX = (event.clientX - canvas.offsetLeft) / imgWidth - startX;\n let deltaY = (event.clientY - canvas.offsetTop) / imgHeight - startY;\n const { x: dX, y: dY } = rotate(deltaX * imgWidth, deltaY * imgHeight, rotation);\n x = lastX + dX / imgWidth;\n y = lastY + dY / imgHeight;\n}\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74613491",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2413722/"
] |
74,613,493
|
<p>I have this relationship</p>
<pre><code>Class Item(models.Model):
pass
Class Category(models.Model):
items = models.ManyToManyField(Item)
</code></pre>
<p>I can define the field name as <code>items</code> for category and access it via <code>category.items</code> but I want to define a field name for Item too as <code>item.categories</code> rather than the default <code>item.category</code></p>
<p>How can I achieve it?</p>
<h3>Update</h3>
<p>Tried</p>
<p><code>items = models.ManyToManyField(Item, related_name = "categories")</code></p>
<p>But I get</p>
<p><code>TypeError: Direct assignment to the reverse side of a many-to-many set is prohibited. Use categories.set() instead.</code></p>
<p>on <code>Item.object.create(**data)</code></p>
|
[
{
"answer_id": 74615469,
"author": "techbipin",
"author_id": 20615126,
"author_profile": "https://Stackoverflow.com/users/20615126",
"pm_score": -1,
"selected": false,
"text": "# models.py\n\nclass Item(models.Model):\n item_name = models.CharField(max_length=255, default=\"\")\n\n def __str__(self):\n return self.item_name\n\n\nclass Category(models.Model):\n category_name = models.CharField(max_length=255, default=\"\")\n items = models.ManyToManyField(Item)\n\n def __str__(self):\n return self.category_name\n # views.py\n\ndef get_items_by_categories(request):\n \n # Here, you will receive a set of items ...\n \n get_categories = Category.objects.all()\n\n # Filter out items with respect to categories ...\n\n get_items_list = [{\"category\": each.category_name, \"items\": each.items} for each in get_categories]\n\n return render(request, \"categories.html\", {\"data\": get_items_list})\n {% for each in data %}\n {% for content in each %}\n {{content.category}}\n {% for item in content.items.all %}\n {{item.item_name}}\n {% endfor %}\n {% endfor %}\n{% endfor %}\n"
},
{
"answer_id": 74642397,
"author": "kalkidan Teklu",
"author_id": 14680923,
"author_profile": "https://Stackoverflow.com/users/14680923",
"pm_score": 1,
"selected": false,
"text": "ItemCatagory class ItemCatagory(models.Model):\n item = modes.ForegnKeyField(Item, related_name=\"catagories\", on_delete... )\n catagory = models.ForegnKeyField(Item, related_name=\"items\", on_delete... )\n catagory.items ItemCatagory RelatedObject catagoty.items.all() QuerySet[ItemCatagory] model.save() save"
},
{
"answer_id": 74659501,
"author": "kimbo",
"author_id": 9638991,
"author_profile": "https://Stackoverflow.com/users/9638991",
"pm_score": 0,
"selected": false,
"text": "Item.objects.create() categories set() item = Item.objects.create()\nitem.categories.set(categories)\n add() item = Item.objects.create()\nitem.categories.add(category)\n add() set() item.save()"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74613493",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8340761/"
] |
74,613,506
|
<p>I have two tables of users and articles and I want to count how many new users and how many new articles I have in the past 7 days.</p>
<p>tbl_users:</p>
<pre><code>[Code, Username, Createdate]
1,David,01/01/2022
2,Henry,02/01/2022
</code></pre>
<p>tbl_articles:</p>
<pre><code>[Code, Header, Createdate]
1,Hello,01/01/2022
2,Goodbye,02/01/2022
</code></pre>
<p>This query works now but it's slow and long. Please help me fix this query (I know it's bad) and if it's possible to add diff columns for both counters:</p>
<p>(Please go easy on me with the comments)</p>
<pre><code>select articles.days_back,articles.count, users.count as users from (
select 0 as days_back,count(*) as count from tbl_articles where date(createdate)< date_add(curdate(), interval -0 day)
union all
select 1,count(*) from tbl_articles where date(createdate)< date_add(curdate(), interval -1 day)
union all
select 2,count(*) from tbl_articles where date(createdate)< date_add(curdate(), interval -2 day)
union all
select 3,count(*) from tbl_articles where date(createdate)< date_add(curdate(), interval -3 day)
union all
select 4,count(*) from tbl_articles where date(createdate)< date_add(curdate(), interval -4 day)
union all
select 5,count(*) from tbl_articles where date(createdate)< date_add(curdate(), interval -5 day)
union all
select 6,count(*) from tbl_articles where date(createdate)< date_add(curdate(), interval -6 day)
union all
select 7,count(*) from tbl_articles where date(createdate)< date_add(curdate(), interval -7 day)
) as articles
left join
(
select 0 as days_back,count(*) as count from tbl_users where date(createdate)< date_add(curdate(), interval -0 day)
union all
select 1,count(*) from tbl_users where date(createdate)< date_add(curdate(), interval -1 day)
union all
select 2,count(*) from tbl_users where date(createdate)< date_add(curdate(), interval -2 day)
union all
select 3,count(*) from tbl_users where date(createdate)< date_add(curdate(), interval -3 day)
union all
select 4,count(*) from tbl_users where date(createdate)< date_add(curdate(), interval -4 day)
union all
select 5,count(*) from tbl_users where date(createdate)< date_add(curdate(), interval -5 day)
union all
select 6,count(*) from tbl_users where date(createdate)< date_add(curdate(), interval -6 day)
union all
select 7,count(*) from tbl_users where date(createdate)< date_add(curdate(), interval -7 day)
) as users
on articles.days_back=users.days_back
</code></pre>
|
[
{
"answer_id": 74615469,
"author": "techbipin",
"author_id": 20615126,
"author_profile": "https://Stackoverflow.com/users/20615126",
"pm_score": -1,
"selected": false,
"text": "# models.py\n\nclass Item(models.Model):\n item_name = models.CharField(max_length=255, default=\"\")\n\n def __str__(self):\n return self.item_name\n\n\nclass Category(models.Model):\n category_name = models.CharField(max_length=255, default=\"\")\n items = models.ManyToManyField(Item)\n\n def __str__(self):\n return self.category_name\n # views.py\n\ndef get_items_by_categories(request):\n \n # Here, you will receive a set of items ...\n \n get_categories = Category.objects.all()\n\n # Filter out items with respect to categories ...\n\n get_items_list = [{\"category\": each.category_name, \"items\": each.items} for each in get_categories]\n\n return render(request, \"categories.html\", {\"data\": get_items_list})\n {% for each in data %}\n {% for content in each %}\n {{content.category}}\n {% for item in content.items.all %}\n {{item.item_name}}\n {% endfor %}\n {% endfor %}\n{% endfor %}\n"
},
{
"answer_id": 74642397,
"author": "kalkidan Teklu",
"author_id": 14680923,
"author_profile": "https://Stackoverflow.com/users/14680923",
"pm_score": 1,
"selected": false,
"text": "ItemCatagory class ItemCatagory(models.Model):\n item = modes.ForegnKeyField(Item, related_name=\"catagories\", on_delete... )\n catagory = models.ForegnKeyField(Item, related_name=\"items\", on_delete... )\n catagory.items ItemCatagory RelatedObject catagoty.items.all() QuerySet[ItemCatagory] model.save() save"
},
{
"answer_id": 74659501,
"author": "kimbo",
"author_id": 9638991,
"author_profile": "https://Stackoverflow.com/users/9638991",
"pm_score": 0,
"selected": false,
"text": "Item.objects.create() categories set() item = Item.objects.create()\nitem.categories.set(categories)\n add() item = Item.objects.create()\nitem.categories.add(category)\n add() set() item.save()"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74613506",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2396640/"
] |
74,613,542
|
<p>Trying to get data from products.json file and store it in Products[] mention in file JsonFileProductServices.cs but getting this error
'The JSON value could not be converted to System.Int32. Path: $[0].id | LineNumber: 2 | BytePositionInLine: 33.'</p>
<p>JsonFileProductServices.cs is basically service to fetch data from product.json</p>
<p>Below mention are the files</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Text.Json.Serialization;
using System.Text.Json;
namespace DevTest.Website.Models
{
public class Product
{
public int Id { get; set; }
public string Maker { get; set; }
[JsonPropertyName("img")]
public string Image { get; set; }
public string Url { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public int[] Ratings { get; set; }
public override string ToString() => JsonSerializer.Serialize<Product>(this);
}
}
---product.cs---
</code></pre>
<pre><code>[
{
"id" : "jenlooper-cactus",
"maker" : "@jenlooper",
"img" : "https://user-images.githubusercontent.com/41929050/61567048-13938600-aa33-11e9-9cfd-712191013192.jpeg",
"url" : "https://www.hackster.io/agent-hawking-1/the-quantified-cactus-an-easy-plant-soil-moisture-sensor-e65393",
"title" : "The Quantified Cactus: An Easy Plant Soil Moisture Sensor",
"description" : "This project is a good learning project to get comfortable with soldering and programming an Arduino."
},
{
"id" : "jenlooper-light",
"maker" : "jenlooper",
"img" : "https://user-images.githubusercontent.com/41929050/61567049-13938600-aa33-11e9-9c69-a4184bf8e524.jpeg",
"url" : "https://www.hackster.io/agent-hawking-1/book-light-dee7e4",
"title" : "A beautiful switch-on book light",
"description" : "Use craft items you have around the house, plus two LEDs and a LilyPad battery holder, to create a useful book light for reading in the dark."
},
{
"id" : "jenlooper-lightshow",
"maker" : "@jenlooper",
"img" : "https://user-images.githubusercontent.com/41929050/61567053-13938600-aa33-11e9-9780-104fe4019659.png",
"url" : "https://www.hackster.io/agent-hawking-1/bling-your-laptop-with-an-internet-connected-light-show-30e4db",
"title" : "Bling your Laptop with an Internet-Connected Light Show",
"description" : "Create a web-connected light-strip API controllable from your website, using the Particle.io."
},
{
"id" : "jenlooper-survival",
"maker" : "jenlooper",
"img" : "https://user-images.githubusercontent.com/41929050/61567051-13938600-aa33-11e9-8ae7-0b5c19aafab4.jpeg",
"url" : "https://www.hackster.io/agent-hawking-1/create-a-compact-survival-kit-38bfdb",
"title" : "Create a Compact Survival Kit with LED Track Lighting",
"description" : "Use an Altoids tin with Chibitronics sticker LEDs to create a light-up compact that doubles as a survival kit for the young hipster"
},
{
"id" : "sailorhg-bubblesortpic",
"maker" : "sailorhg",
"img" : "https://user-images.githubusercontent.com/41929050/61567054-13938600-aa33-11e9-9163-eec98e239b7a.png",
"url" : "https://twitter.com/sailorhg/status/1090107740049952770",
"title" : "Bubblesort Visualization",
"description" : "Visualization of sailor scouts sorted by bubblesort algorithm by their planet's distance from the sun"
},
{
"id" : "sailorhg-corsage",
"maker" : "sailorhg",
"img" : "https://user-images.githubusercontent.com/41929050/61567055-142c1c80-aa33-11e9-96ff-9fbac6413625.png",
"url" : "https://twitter.com/sailorhg/status/1090113666911891456",
"title" : "Light-up Corsage",
"description" : "Light-up corsage I made with my summer intern."
},
{
"id" : "sailorhg-kit",
"maker" : "sailorhg",
"img" : "https://user-images.githubusercontent.com/41929050/61567056-142c1c80-aa33-11e9-8682-10065d338145.png",
"url" : "https://twitter.com/sailorhg/status/1090122822007963648",
"title" : "Pastel hardware kit",
"description" : "Pastel hardware kits complete with custom manufactured pastel alligator clips."
},
{
"id" : "sailorhg-led",
"maker" : "sailorhg",
"img" : "https://user-images.githubusercontent.com/41929050/61567052-13938600-aa33-11e9-9a88-cd842073ba44.jpg",
"url" : "https://twitter.com/sailorhg/status/1090117277540745216",
"title" : "Heart-shaped LED",
"description" : "custom molded heart shaped LED with sprinkles."
},
{
"id" : "selinazawacki-soi-shirt",
"maker" : "selinazawacki",
"img" : "https://user-images.githubusercontent.com/41929050/61567060-142c1c80-aa33-11e9-8188-5a4803844a9e.png",
"url" : "https://www.instagram.com/p/BNvESj-j8PI/",
"title" : "Black Sweatshirt",
"description" : "Black sweatshirt hoody with the Sick of the Internet logo."
},
{
"id" : "selinazawacki-soi-pins",
"maker" : "selinazawacki",
"img" : "https://user-images.githubusercontent.com/41929050/61567059-142c1c80-aa33-11e9-939b-2ecf4492786d.png",
"url" : "https://www.instagram.com/p/BNm6hZzDoEF/",
"title" : "Sick of the Internet Pins",
"description" : "Still some time to enter the pin/sticker giveaway! "
},
{
"id" : "vogueandcode-hipster-dev-bro",
"maker" : "vogueandcode",
"img" : "https://user-images.githubusercontent.com/41929050/61567061-14c4b300-aa33-11e9-9fee-63ff2c0c9823.png",
"url" : "https://www.vogueandcode.com/shop/hipster-dev-bro",
"title" : "Hipster Dev",
"description" : "Hipster Dev is busy coding away while styled in a camo jacket and orange beanie."
},
{
"id" : "vogueandcode-pretty-girls-code-tee",
"maker" : "vogueandcode",
"img" : "https://user-images.githubusercontent.com/41929050/61567062-14c4b300-aa33-11e9-9dcd-8bfed4ece810.png",
"url" : "https://www.vogueandcode.com/shop/pretty-girls-code-tee",
"title" : "Pretty Girls Code Tee",
"description" : "Everyone’s favorite design is finally here on a tee! The Pretty Girls Code crew-neck tee is available in a soft pink with red writing."
},
{
"id" : "vogueandcode-ruby-sis-2",
"maker" : "vogueandcode",
"img" : "https://user-images.githubusercontent.com/41929050/61567063-14c4b300-aa33-11e9-8515-bcb866da9ea3.png",
"url" : "https://www.vogueandcode.com/shop/ruby-sis-2",
"title" : "Ruby Sis",
"description" : "Styled in a dashiki, Ruby Sis is listening to music while coding in her favorite language, Ruby!"
},
{
"id" : "selinazawacki-moon",
"maker" : "selinazawacki",
"img" : "https://user-images.githubusercontent.com/41929050/61567057-142c1c80-aa33-11e9-9781-9e442418eaab.png",
"url" : "https://www.instagram.com/p/BFktVYPinKQ/",
"title" : "Holographic Dark Moon Necklace",
"description" : "Not sure if I'll be making more, get it while I have it in the store."
},
{
"id" : "selinazawacki-shirt",
"maker" : "selinazawacki",
"img" : "https://user-images.githubusercontent.com/41929050/61567058-142c1c80-aa33-11e9-89fb-b4f30d84d69d.png",
"url" : "https://www.instagram.com/p/BEXlpiZCnJ3/",
"title" : "Floppy Crop",
"description" : "Used up the Diskette fabric today to make 2 of these crops."
}
]
----products.json
</code></pre>
<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Text.Json.Serialization;
using System.Text.Json;
using Microsoft.AspNetCore.Hosting;
using DevTest.Website.Models;
namespace DevTest.Website.Services
{
public class JsonFileProductService
{
public JsonFileProductService(IWebHostEnvironment webHostEnvironment)
{
WebHostEnvironment = webHostEnvironment;
}
public IWebHostEnvironment WebHostEnvironment { get; }
private string JsonFileName => Path.Combine(WebHostEnvironment.WebRootPath, "data", "products.json");
public IEnumerable<Product> GetProducts()
{
using (var jsonFileReader = File.OpenText(JsonFileName))
{
return JsonSerializer.Deserialize<Product[]>(jsonFileReader.ReadToEnd(),
new JsonSerializerOptions
{
PropertyNameCaseInsensitive = true
});
}
}
}
}
--JsonFileProductService.cs---
</code></pre>
|
[
{
"answer_id": 74614041,
"author": "Serge",
"author_id": 11392290,
"author_profile": "https://Stackoverflow.com/users/11392290",
"pm_score": 2,
"selected": true,
"text": " \"id\" : \"jenlooper-survival\",\n public class Product\n{\n public int Id { get; set; }\n .....\n}\n public class Product\n{\n public string Id { get; set; }\n .....\n}\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74613542",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20572601/"
] |
74,613,553
|
<p>I would like to change the values of this list by alternating the 0 and 1 values in a checkerboard pattern.</p>
<pre><code>table =
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1
</code></pre>
<p>i tried:</p>
<pre><code>for i in range(len(table)):
for j in range(0, len(table[i]), 2): # ho definito uno step nella funzione range
table[i][j] = 0
</code></pre>
<p>but for each list the count starts again and the result is:</p>
<pre><code>
0 1 0 1 0
0 1 0 1 0
0 1 0 1 0
0 1 0 1 0
0 1 0 1 0
</code></pre>
<p>my question is how can I change the loop to form a checkerboard pattern.</p>
<p>I expect the result to be like:</p>
<pre><code> 0 1 0 1 0
1 0 1 0 1
0 1 0 1 0
1 0 1 0 1
0 1 0 1 0
</code></pre>
|
[
{
"answer_id": 74613591,
"author": "JayPeerachai",
"author_id": 12135518,
"author_profile": "https://Stackoverflow.com/users/12135518",
"pm_score": 3,
"selected": true,
"text": "for i in range(len(table)):\n for j in range(len(table[i])):\n if (i+j)%2 == 0:\n table[i][j] = 0\n [[0, 1, 0, 1, 0],\n [1, 0, 1, 0, 1],\n [0, 1, 0, 1, 0],\n [1, 0, 1, 0, 1],\n [0, 1, 0, 1, 0]]\n"
},
{
"answer_id": 74614238,
"author": "Cobra",
"author_id": 17580381,
"author_profile": "https://Stackoverflow.com/users/17580381",
"pm_score": -1,
"selected": false,
"text": "def checkboard(rows, columns):\n e = 0\n result = []\n for _ in range(rows):\n c = []\n for _ in range(columns):\n c.append(e)\n e ^= 1\n result.append(c)\n return result\n \nprint(checkboard(5, 5))\nprint(checkboard(2, 3))\nprint(checkboard(4, 4))\n [[0, 1, 0, 1, 0], [1, 0, 1, 0, 1], [0, 1, 0, 1, 0], [1, 0, 1, 0, 1], [0, 1, 0, 1, 0]]\n[[0, 1, 0], [1, 0, 1]]\n[[0, 1, 0, 1], [0, 1, 0, 1], [0, 1, 0, 1], [0, 1, 0, 1]]\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74613553",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20592093/"
] |
74,613,639
|
<p>I am putting together some summary stats of a dataframe about biomass at different sights. Here's some dummy data:</p>
<pre><code>df1 <- data.frame(ID = c(1, 2, 3, 4, 5,6,7,8,9,10,11),
Reach = c('a', 'b', 'c', 'a', 'a', 'b', 'c', 'c','b','c','a'),
Bio = c(12, 11, 10.4, 10, 12.5, 14, 12, 17, 17.5, 17.3, 16.2))
</code></pre>
<p>I have created a table in which to capture summary stats:</p>
<pre><code>sumstats<- data.frame(matrix(data=NA, nrow=1, ncol=4))
colnames(sumstats) <- c("Total.Fish", "Mean.Fish", "St.Dev", "95%.Conf")
</code></pre>
<p>Completing the first three columns is easy enough</p>
<pre><code>sumstats$Total.Fish<- sum(df1$Bio)
sumstats$Mean.Fish<- mean(df1$Bio)
sumstats$St.Dev <- sd(df1$Bio)
</code></pre>
<p>But the last one is giving me some bother. To my understanding there isn't a function in base R which computes the 95% confidence level. I have found that I can compute it using a Z Test in BSDA:</p>
<pre><code>library(BSDA)
test1<- z.test(df1$Bio, sigma.x=(mean(df1$Bio)), conf.level = 0.95)
</code></pre>
<p>But I cannot figure out how to get the outputs of that into my dataframe. The output of the Z test is a list, one of the list items is the confidence level.</p>
<p>If I print the confidence level line of that list it shows several number, my summary stats dataframe needs the first one (5.74217 in this case).
So my question is either:</p>
<ol>
<li>how do I get just part of the outputs from the z test into my dataframe</li>
<li>is there an easier way to calculate the 95% condeince level?</li>
</ol>
|
[
{
"answer_id": 74614069,
"author": "Robert Hacken",
"author_id": 2094893,
"author_profile": "https://Stackoverflow.com/users/2094893",
"pm_score": 3,
"selected": true,
"text": "sigma.x test1$conf.int[1] z.test test <- t.test(df1$Bio)\nsumstats$Conf.Int.Lower <- test$conf.int[1]\n sumstats$Conf.Int.Upper <- test$conf.int[2]\n"
},
{
"answer_id": 74614475,
"author": "Shawn Hemelstrand",
"author_id": 16631565,
"author_profile": "https://Stackoverflow.com/users/16631565",
"pm_score": 1,
"selected": false,
"text": "#### Set Random Seed ####\nset.seed(1)\n\n#### Mean CI Function ####\nmean_ci <- function(x, conf = 0.95) { \n se <- sd(x) / sqrt(length(x)) \n alpha <- 1 - conf \n mean(x) + se * qnorm(c(alpha / 2, 1 - alpha / 2)) \n} \n\n#### Create Uniform Distribution of 100 Values ####\nx <- runif(100) \n\n#### Calculate Mean CI ####\nmean_ci(x)\n [1] 0.4654014 0.5702927\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74613639",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12989135/"
] |
74,613,647
|
<p>I have a dataframe (df_obs) indexed by date containing one column with a length in number of days of something being observed:</p>
<pre><code>Date duration
2012-01-01 3
2013-04-01 26
2014-05-01 14
2016-01-01 297
</code></pre>
<p>I am trying to repurpose this dataframe to provide a binary indication of whether an observation happens on each day, so the result would look like this:</p>
<pre><code>Date Obs
2012-01-01 1
2012-01-02 1
2012-01-03 1
2012-01-04 0
2012-01-05 0
</code></pre>
<p>I had a script to do this, but since performing updates it won't wor - this is what I had used before:</p>
<pre><code>Time = pd.DataFrame(pd.date_range(start='01/01/2012', end='31/12/2019'))
obs = np.zeros()
for d in df_obs.itertuples():
ilong = np.argwhere(Time.date == d.Index)[0][0]
obs[ilong:ilong+d.duration] = 1
</code></pre>
<p>This now returns the following error:</p>
<pre><code>ValueError: Length of values (1) does not match length of index (2921)
</code></pre>
<p>Any pointers of what edits I need to make this work?</p>
|
[
{
"answer_id": 74614069,
"author": "Robert Hacken",
"author_id": 2094893,
"author_profile": "https://Stackoverflow.com/users/2094893",
"pm_score": 3,
"selected": true,
"text": "sigma.x test1$conf.int[1] z.test test <- t.test(df1$Bio)\nsumstats$Conf.Int.Lower <- test$conf.int[1]\n sumstats$Conf.Int.Upper <- test$conf.int[2]\n"
},
{
"answer_id": 74614475,
"author": "Shawn Hemelstrand",
"author_id": 16631565,
"author_profile": "https://Stackoverflow.com/users/16631565",
"pm_score": 1,
"selected": false,
"text": "#### Set Random Seed ####\nset.seed(1)\n\n#### Mean CI Function ####\nmean_ci <- function(x, conf = 0.95) { \n se <- sd(x) / sqrt(length(x)) \n alpha <- 1 - conf \n mean(x) + se * qnorm(c(alpha / 2, 1 - alpha / 2)) \n} \n\n#### Create Uniform Distribution of 100 Values ####\nx <- runif(100) \n\n#### Calculate Mean CI ####\nmean_ci(x)\n [1] 0.4654014 0.5702927\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74613647",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10071715/"
] |
74,613,675
|
<pre class="lang-py prettyprint-override"><code>lv_seconds_back = mv_time_horizon.select(col("max(time_horizon)") * 60).show()
mv_now =spark.sql("select from_unixtime(unix_timestamp()) as mv_now")
local_date_time =mv_now.select(date_format('mv_now', 'HH:mm:ss').alias("local_date_time"))
lv_start =local_date_time.select(col("local_date_time") - expr("INTERVAL $lv_seconds_back seconds"))
</code></pre>
<p>How do i substract no of seconds which is in <code>lv_seconds_back</code> variable in the <code>lv start</code></p>
<p>I tried using <code>expr(interval seconds)</code> but it wont take the variable but takes number.</p>
<p>Also if I need too add that <code>lv_start</code> in the query how do i do that</p>
<pre class="lang-py prettyprint-override"><code>mt_cache_fauf_r_2= spark.sql("select mt_cache_fauf_r_temp from mt_cache_fauf_r_temp where RM_ZEITPUNKT>= ${lv_start} & RM_ZEITPUNKT <= ${lv_end}")
</code></pre>
<p>This doesn't work</p>
|
[
{
"answer_id": 74614069,
"author": "Robert Hacken",
"author_id": 2094893,
"author_profile": "https://Stackoverflow.com/users/2094893",
"pm_score": 3,
"selected": true,
"text": "sigma.x test1$conf.int[1] z.test test <- t.test(df1$Bio)\nsumstats$Conf.Int.Lower <- test$conf.int[1]\n sumstats$Conf.Int.Upper <- test$conf.int[2]\n"
},
{
"answer_id": 74614475,
"author": "Shawn Hemelstrand",
"author_id": 16631565,
"author_profile": "https://Stackoverflow.com/users/16631565",
"pm_score": 1,
"selected": false,
"text": "#### Set Random Seed ####\nset.seed(1)\n\n#### Mean CI Function ####\nmean_ci <- function(x, conf = 0.95) { \n se <- sd(x) / sqrt(length(x)) \n alpha <- 1 - conf \n mean(x) + se * qnorm(c(alpha / 2, 1 - alpha / 2)) \n} \n\n#### Create Uniform Distribution of 100 Values ####\nx <- runif(100) \n\n#### Calculate Mean CI ####\nmean_ci(x)\n [1] 0.4654014 0.5702927\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74613675",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11148994/"
] |
74,613,676
|
<pre><code>const express = require("express")
const app = express()
app.post("/create1",(req,resp)=>{
console.log("server started")
resp.send("done")
})
app.listen(3000)
</code></pre>
<p>I should get a</p>
<pre><code>send
</code></pre>
<p>on the</p>
<pre><code> https:// localhost:3000/create,
</code></pre>
<p>i tried changing port number, but am getting same error</p>
|
[
{
"answer_id": 74614069,
"author": "Robert Hacken",
"author_id": 2094893,
"author_profile": "https://Stackoverflow.com/users/2094893",
"pm_score": 3,
"selected": true,
"text": "sigma.x test1$conf.int[1] z.test test <- t.test(df1$Bio)\nsumstats$Conf.Int.Lower <- test$conf.int[1]\n sumstats$Conf.Int.Upper <- test$conf.int[2]\n"
},
{
"answer_id": 74614475,
"author": "Shawn Hemelstrand",
"author_id": 16631565,
"author_profile": "https://Stackoverflow.com/users/16631565",
"pm_score": 1,
"selected": false,
"text": "#### Set Random Seed ####\nset.seed(1)\n\n#### Mean CI Function ####\nmean_ci <- function(x, conf = 0.95) { \n se <- sd(x) / sqrt(length(x)) \n alpha <- 1 - conf \n mean(x) + se * qnorm(c(alpha / 2, 1 - alpha / 2)) \n} \n\n#### Create Uniform Distribution of 100 Values ####\nx <- runif(100) \n\n#### Calculate Mean CI ####\nmean_ci(x)\n [1] 0.4654014 0.5702927\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74613676",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13153007/"
] |
74,613,690
|
<p>I am trying to read a tif file using <code>terra</code> r package using the following code</p>
<pre><code>hh <- rast("imagery_HH.tif")
#> Warning message:
#> [rast] unknown extent
hh
#> class : SpatRaster
#> dimensions : 8371, 8946, 1 (nrow, ncol, nlyr)
#> resolution : 1, 1 (x, y)
#> extent : 0, 8946, 0, 8371 (xmin, xmax, ymin, ymax)
#> coord. ref. :
#> source : imagery_HH.tif
#> name : imagery_HH
</code></pre>
<p>Using the function <code>terra::describe("imagery_HH.tif")</code>, I got the following information:</p>
<pre><code> [4] "Size is 8946, 8371"
[5] "GCP Projection = "
[6] "GEOGCRS[\"WGS 84\","
[7] " DATUM[\"World Geodetic System 1984\","
[8] " ELLIPSOID[\"WGS 84\",6378137,298.257223563,"
[9] " LENGTHUNIT[\"metre\",1]]],"
[10] " PRIMEM[\"Greenwich\",0,"
[11] " ANGLEUNIT[\"degree\",0.0174532925199433]],"
[12] " CS[ellipsoidal,2],"
[13] " AXIS[\"geodetic latitude (Lat)\",north,"
[14] " ORDER[1],"
[15] " ANGLEUNIT[\"degree\",0.0174532925199433]],"
[16] " AXIS[\"geodetic longitude (Lon)\",east,"
[17] " ORDER[2],"
[18] " ANGLEUNIT[\"degree\",0.0174532925199433]],"
[19] " USAGE["
[20] " SCOPE[\"Horizontal component of 3D system.\"],"
[21] " AREA[\"World.\"],"
[22] " BBOX[-90,-180,90,180]],"
[23] " ID[\"EPSG\",4326]]"
[24] "Data axis to CRS axis mapping: 2,1"
</code></pre>
<p>If we look closely, we can see that the coordinate reference is missing and the resolution is showing 1 x 1 with the incorrect extent. But if we open the tif file in QGIS, it shows the following properties having a crs of EPSG:4326</p>
<p><a href="https://i.stack.imgur.com/h6HeM.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/h6HeM.png" alt="enter image description here" /></a></p>
<p>Now how to read the tif file with proper coordiante system, resolution and extent using <code>terra</code> R package?</p>
<p>Here is the link to download the <a href="https://www.transfernow.net/dl/20221129CCCW1b2a" rel="nofollow noreferrer">raster file</a></p>
|
[
{
"answer_id": 74645989,
"author": "Anthony Martinez",
"author_id": 7470643,
"author_profile": "https://Stackoverflow.com/users/7470643",
"pm_score": 0,
"selected": false,
"text": "terra::rast raster::raster terra hh <- terra::rast(\"imagery_HH.tif\")\nterra::set.ext(\n x = hh, \n value = c(76.6811227745188262,\n 78.59105666365414556,\n 27.9827663027027924,\n 29.6529629093873979)\n)\n"
},
{
"answer_id": 74663746,
"author": "Robert Hijmans",
"author_id": 635245,
"author_profile": "https://Stackoverflow.com/users/635245",
"pm_score": 1,
"selected": false,
"text": "terra::describe(\"imagery_HH.tif\")[31:40]\n [1] \"Data axis to CRS axis mapping: 2,1\" \n [2] \"GCP[ 0]: Id=1, Info=\" \n [3] \" (0,0) -> (78.591314,29.400624,0)\" \n [4] \"GCP[ 1]: Id=2, Info=\" \n [5] \" (357.84,0) -> (78.52592634,29.41112936,0)\" \n [6] \"GCP[ 2]: Id=3, Info=\" \n [7] \" (715.68,0) -> (78.4607346,29.4215638,0)\" \n [8] \"GCP[ 3]: Id=4, Info=\" \n [9] \" (1073.52,0) -> (78.39539736,29.43198708,0)\"\n[10] \"GCP[ 4]: Id=5, Info=\" \n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74613690",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6123824/"
] |
74,613,699
|
<p>I have been dealing with a issue that I cant solve in specifically c language in output terminal I want my cursor in previous line
for example</p>
<pre><code>prints("hello\n");
prints("Hi");
</code></pre>
<p>If want to print hi in near horizontal to hello but not my removing <code>\n</code> or by re writing anything I just want that after <code>\n</code> cursor go to previous line and print hi can anyone help me please</p>
<pre><code>prints("\n hi\r\b");
prints("hello");
</code></pre>
<p>I wanted it to be like <code>hello hi</code></p>
|
[
{
"answer_id": 74613907,
"author": "Elia Karrer",
"author_id": 17653989,
"author_profile": "https://Stackoverflow.com/users/17653989",
"pm_score": 0,
"selected": false,
"text": "printf(\"\\b\"); // 1 character back\n\nprintf(\"\\r\"); // Beginning of line\n #include <windows.h>\n\nvoid goto_xy(unsigned x, unsigned y)\n{\n SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), (COORD){x, y});\n}\n void goto_xy(unsigned x, unsigned y)\n{\n printf(\"\\033[%u;%uH\", y, x);\n}\n"
},
{
"answer_id": 74617183,
"author": "user3121023",
"author_id": 3121023,
"author_profile": "https://Stackoverflow.com/users/3121023",
"pm_score": 1,
"selected": false,
"text": "ncurses -lncurses #include <stdio.h>\n#include <ncurses.h>\n\nint main ( void) {\n int ch = 0;\n int row = 0;\n int col = 0;\n\n initscr ( );\n halfdelay ( 2); // tenths of a second that getch waits for input\n noecho ( );\n getmaxyx ( stdscr, row, col); // max rows and cols\n move ( row / 2, col / 2);\n printw ( \"hi\");\n refresh ( );\n move ( row / 2, 2);\n printw ( \"hello\");\n refresh ( );\n\n move ( row - 3, col / 4);\n printw ( \"press enter\");\n refresh ( );\n while ( ( ch = getch ( ))) {\n if ( '\\n' == ch) {\n break;\n }\n }\n endwin ( );\n return 0;\n}\n #include <stdio.h>\n\nint main ( void) {\n int row = 11;\n int col = 20;\n\n printf ( \"\\033[2J\"); // clear screen\n printf ( \"\\033[%d;%dH\", row, col);\n printf ( \"hi\");\n fflush ( stdout);\n printf ( \"\\033[%d;%dH\", row, 2);\n printf ( \"hello\");\n fflush ( stdout);\n\n printf ( \"\\033[%d;%dH\", 18, 2);\n fflush ( stdout);\n return 0;\n}\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74613699",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20632953/"
] |
74,613,704
|
<p>The dataset (named Politics) that I am working on looks as follows:</p>
<p><a href="https://i.stack.imgur.com/tkBkB.png" rel="nofollow noreferrer">Current Dataset of every country in the world</a></p>
<p>However, my original data set contains the years 1997, 1999 and 2001 as well.
As one can see in the picture, every country has no data for 1997, 1999 and 2001.</p>
<p>I would like to insert rows of the year 1997, 1999 and 2001 for every country in the current dataset such that we would have something like:</p>
<pre><code>Country Year Politics
Afghanistan 1996 Value 1
Afghanistan 1997 empty value
Afghanistan 1998 Value 2
....
....
....
Albania 1996 Value 3
Albania 1997 empty value
etc
etc
</code></pre>
<p>Is there maybe another way because my original dataset looks as follows:
<a href="https://i.stack.imgur.com/t5kfF.png" rel="nofollow noreferrer">Original dataset</a></p>
<p>The conclusion is that I want to make the current dataset fitted to the original dataset and currrently this is not possible as the original dataset has the years 1997, 1999 and 2001 whereas the current dataset did not include these years.</p>
<p>I hope that I have given a clear explanation of what I would like to see.</p>
|
[
{
"answer_id": 74615015,
"author": "islem",
"author_id": 11952767,
"author_profile": "https://Stackoverflow.com/users/11952767",
"pm_score": 0,
"selected": false,
"text": "dplyr::full_join(current_dataset,Original dataset, by=c(\"Country Name\"=\"Country\", \"Time\"=\"Time\")\n"
},
{
"answer_id": 74619466,
"author": "Ben",
"author_id": 3460670,
"author_profile": "https://Stackoverflow.com/users/3460670",
"pm_score": 2,
"selected": true,
"text": "complete tidyr dput set.seed(123)\n\ndf <- data.frame(\n Country = c(rep(\"Afghanistan\", 4), rep(\"Albania\", 4)),\n Time = c(1996, 1998, 2000, 2002, 1996, 1998, 2000, 2002),\n Politics = rnorm(n = 8)\n)\n\nlibrary(tidyverse)\n\ndf %>%\n complete(Time = 1996:2002, nesting(Country)) %>%\n arrange(Country, Time)\n Time Country Politics\n <dbl> <chr> <dbl>\n 1 1996 Afghanistan -0.230 \n 2 1997 Afghanistan NA \n 3 1998 Afghanistan 1.56 \n 4 1999 Afghanistan NA \n 5 2000 Afghanistan 0.0705\n 6 2001 Afghanistan NA \n 7 2002 Afghanistan 0.129 \n 8 1996 Albania 1.72 \n 9 1997 Albania NA \n10 1998 Albania 0.461 \n11 1999 Albania NA \n12 2000 Albania -1.27 \n13 2001 Albania NA \n14 2002 Albania -0.687\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74613704",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20131260/"
] |
74,613,705
|
<p>hi i want to access the mainwindow attributes and change some of its labels and button's states in my toplevel class however it can not find them. so im not sure how to use opp approach in tkinter and i tried using super__init__ and textvariable but i failed. the main problem is inheritance in tkinter frame work and i highlighted it in def login 2. i appreciate the help. peace.</p>
<pre><code>import tkinter as tk
import sqlite3
cnt = sqlite3.connect("simple_store.db")
class MainWindow():
def __init__(self,master):
self.master=master
self.master.geometry('350x200')
self.master.resizable(False, False)
self.lbl_msg = tk.Label(self.master, text='')
self.lbl_msg.pack()
self.login_btn = tk.Button(self.master, text="Login ", command=login)
self.login_btn.pack()
self.submit_btn = tk.Button(self.master, text="Submit", command=submit)
self.submit_btn.pack()
class submit:
pass
class login(MainWindow):
def __init__(self):
self.login_win = tk.Toplevel()
self.login_win.title("Login")
self.login_win.geometry("350x200")
self.lbl_temp = tk.Label(self.login_win, text='')
self.lbl_temp.pack()
self.lbl_user = tk.Label(self.login_win, text='Username:')
self.lbl_user.pack()
self.userw = tk.Entry(self.login_win, width=15)
self.userw.pack()
self.lbl_pass = tk.Label(self.login_win, text='Password')
self.lbl_pass.pack()
self.passwordw = tk.Entry(self.login_win, width=15)
self.passwordw.pack()
self.login_btn2 = tk.Button(self.login_win, text="Login", command= self.login2)
self.login_btn2.pack(pady=20)
self.login_win.mainloop()
def login2(self):
global userid
self.user = self.userw.get()
self.password = self.passwordw.get()
query = '''SELECT * FROM costumers WHERE username=? AND PASSWORD=?'''
result = cnt.execute(query, (self.user, self.password))
row = result.fetchall()
if (row):
self.lbl_temp.configure(text="welcome")
userid = row[0][0]
####the problem is here####
self.lbl_msg.configure(text="welcome " + self.user)
# self.login_btn.configure(state="disabled")
self.userw.delete(0, 'end')
self.passwordw.delete(0, 'end')
else:
self.lbl_temp.configure(text="error")
root= tk.Tk()
window= MainWindow(root)
root.mainloop()
</code></pre>
|
[
{
"answer_id": 74615015,
"author": "islem",
"author_id": 11952767,
"author_profile": "https://Stackoverflow.com/users/11952767",
"pm_score": 0,
"selected": false,
"text": "dplyr::full_join(current_dataset,Original dataset, by=c(\"Country Name\"=\"Country\", \"Time\"=\"Time\")\n"
},
{
"answer_id": 74619466,
"author": "Ben",
"author_id": 3460670,
"author_profile": "https://Stackoverflow.com/users/3460670",
"pm_score": 2,
"selected": true,
"text": "complete tidyr dput set.seed(123)\n\ndf <- data.frame(\n Country = c(rep(\"Afghanistan\", 4), rep(\"Albania\", 4)),\n Time = c(1996, 1998, 2000, 2002, 1996, 1998, 2000, 2002),\n Politics = rnorm(n = 8)\n)\n\nlibrary(tidyverse)\n\ndf %>%\n complete(Time = 1996:2002, nesting(Country)) %>%\n arrange(Country, Time)\n Time Country Politics\n <dbl> <chr> <dbl>\n 1 1996 Afghanistan -0.230 \n 2 1997 Afghanistan NA \n 3 1998 Afghanistan 1.56 \n 4 1999 Afghanistan NA \n 5 2000 Afghanistan 0.0705\n 6 2001 Afghanistan NA \n 7 2002 Afghanistan 0.129 \n 8 1996 Albania 1.72 \n 9 1997 Albania NA \n10 1998 Albania 0.461 \n11 1999 Albania NA \n12 2000 Albania -1.27 \n13 2001 Albania NA \n14 2002 Albania -0.687\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74613705",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20630480/"
] |
74,613,726
|
<p>Im able to get the sum in dataGridView but having trouble on properly getting the average.</p>
<pre><code>foreach (DataGridViewRow row in dataGridView.Rows) {
row.Cells["Average"].Value = Convert.ToDouble(row.Cells[4].Value) +
Convert.ToDouble(row.Cells[5].Value) +
Convert.ToDouble(row.Cells[6].Value);
}
</code></pre>
|
[
{
"answer_id": 74613827,
"author": "YungDeiza",
"author_id": 19214431,
"author_profile": "https://Stackoverflow.com/users/19214431",
"pm_score": 2,
"selected": true,
"text": "foreach (DataGridViewRow row in dataGridView.Rows)\n row.Cells[\"Average\"].Value = (Convert.ToDouble(row.Cells[4].Value) + Convert.ToDouble(row.Cells[5].Value) + Convert.ToDouble(row.Cells[6].Value)) / 3;\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74613726",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20632993/"
] |
74,613,737
|
<p>I created a script in JavaScript to take value from one input and place it in several inputs, but I have a problem that value is only put in the first input.</p>
<p>The JavaScript code is:</p>
<pre><code>jQuery(document).ready(function ($) {
var $apartament = $('#value-apartament'),
$permetru = $('#put-value');
$apartament.on('input', function () {
$permetru.val($apartament.val());
});
});
</code></pre>
<p>The first input have the id: <code>#value-apartament</code> and the others have <code>#put-value</code> for copy the value from the first input and put for the rest of three.</p>
<p>image: <a href="https://prnt.sc/nyj_S9AjhaMW" rel="nofollow noreferrer">https://prnt.sc/nyj_S9AjhaMW</a></p>
|
[
{
"answer_id": 74613827,
"author": "YungDeiza",
"author_id": 19214431,
"author_profile": "https://Stackoverflow.com/users/19214431",
"pm_score": 2,
"selected": true,
"text": "foreach (DataGridViewRow row in dataGridView.Rows)\n row.Cells[\"Average\"].Value = (Convert.ToDouble(row.Cells[4].Value) + Convert.ToDouble(row.Cells[5].Value) + Convert.ToDouble(row.Cells[6].Value)) / 3;\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74613737",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19249464/"
] |
74,613,777
|
<p>I want to create a dropdown menu using javaScript, however I have created a dropdown list using an array, but I am struggling to add the mouseOver event such that, when a user over a specific list item, the list item color changes to lightpink, bg color to black and shows a cursor pointer.</p>
<p>Finally , When I tried to click the button it always renders list item every time I click, I want to show a toggle effect, such that when a user click's button , show list items, then hide the same with the selected item.</p>
<p>I tried to add certain functionality but I do not know what went wrong. Can anyone please correct me?</p>
<p>Any help or suggestions are helpful.</p>
<p>Thanks</p>
<p>Please see the code below which I have tried:</p>
<p><strong>HTML</strong></p>
<pre><code><div class="dropdownMain">
<button id="dropdownBtn" class="dropdwonBtn"> Select Counrtry</button>
<div id="dropdownList" class="dropdownList">
</div>
</div>
</code></pre>
<p><strong>JavaScript</strong></p>
<pre><code>const countries = ["India", "Ireland", "USA", "UK"];
const dropdownBtn = document.getElementById("dropdownBtn");
const dropdownList = document.getElementById("dropdownList");
dropdownBtn.addEventListener("click", () => {
for (let i = 0; i < countries.length; i++) {
const list = document.createElement("li");
list.style.color = "#ff0000";
list.style.listStyleType = "none";
list.style.padding = "0.5rem";
list.style.paddingLeft = "1.1rem";
list.style.borderRadius = "5px";
list.style.marginBottom = "0.2rem";
list.style.marginTop = "0.2rem";
// only should trigger when hover over list item
list.addEventListener(
"mouseover",
(e) => {
e.target.style.color = "black";
e.target.style.backgroundColor = "lightpink";
e.style.cursor = "pointer";
// reset the color after a short delay
setTimeout(() => {
e.target.style.color = "";
}, 500);
},
false
);
list.appendChild(document.createTextNode(countries[i]));
dropdownList.appendChild(list);
}
});
</code></pre>
<p>Please see codepen demo here <a href="https://codepen.io/tapesh02/pen/ExRpgZb" rel="nofollow noreferrer">https://codepen.io/tapesh02/pen/ExRpgZb</a></p>
|
[
{
"answer_id": 74614549,
"author": "Satsangpriyadas Swami",
"author_id": 9677279,
"author_profile": "https://Stackoverflow.com/users/9677279",
"pm_score": 1,
"selected": false,
"text": "...\n dropdownList.innerHTML = \"\";\n for (let i = 0; i < countries.length; i++) {\n...\n"
},
{
"answer_id": 74614723,
"author": "EssXTee",
"author_id": 2339619,
"author_profile": "https://Stackoverflow.com/users/2339619",
"pm_score": 2,
"selected": true,
"text": "mouseover mouseout mouseover mouseout :hover <li> <li> const countries = [\"India\", \"Ireland\", \"USA\", \"UK\"],\ndropdownBtn = document.getElementById(\"dropdownBtn\"),\ndropdownList = document.getElementById(\"dropdownList\")\n\nconst showList = () => {\n if(dropdownList.innerText.length) {\n dropdownList.innerHTML = \"\"\n return\n }\n countries.forEach(c => {\n const list = document.createElement(\"li\")\n list.className = \"dropdownItem\"\n\n list.addEventListener(\"mouseover\", e => {\n e.target.classList.add(\"active\")\n })\n list.addEventListener(\"mouseout\", e => {\n e.target.classList.remove(\"active\")\n })\n list.addEventListener(\"click\", e => {\n dropdownBtn.innerText = e.target.innerText\n dropdownList.innerHTML = \"\"\n })\n\n list.append(c)\n dropdownList.append(list)\n })\n}\n\ndropdownBtn.addEventListener(\"click\", showList) .dropdownMain {\n width: 10rem;\n display: flex;\n justify-content: center;\n align-items: center;\n flex-direction: column;\n}\n\nbutton {\n color: white;\n border: none;\n width: 100%;\n height: 30px;\n margin-bottom: 0.5rem;\n background-image: linear-gradient(\n to bottom,\n #ff0000,\n #ff0031,\n #ff0050,\n #f8006b,\n #eb1283\n );\n font: 0.9rem bold;\n border-radius: 5px;\n cursor: pointer;\n transition: 0.5s all;\n}\n\nbutton:hover {\n color: black;\n background: inherit;\n border: 1px solid #ff0000;\n}\n\nbutton:focus {\n color: #ff0000;\n background: inherit;\n}\n\n.dropdownList {\n width: inherit;\n}\n\n.dropdownItem {\n color: #F00;\n list-style-type: none;\n padding: .5rem .5rem .5rem 1.1rem;\n margin: .2rem 0;\n border-radius: 5px;\n cursor: pointer;\n}\n.active {\n color: #000;\n background: lightpink;\n} <div class=\"dropdownMain\">\n <button id=\"dropdownBtn\" class=\"dropdwonBtn\">Select Country</button>\n <div id=\"dropdownList\" class=\"dropdownList\"></div>\n</div> .forEach() for .append()"
},
{
"answer_id": 74616270,
"author": "Tapesh Patel",
"author_id": 13843563,
"author_profile": "https://Stackoverflow.com/users/13843563",
"pm_score": 0,
"selected": false,
"text": "const countries = [\"India\", \"Ireland\", \"USA\", \"UK\"];\n\nconst dropdownBtn = document.getElementById(\"dropdownBtn\");\nconst dropdownList = document.getElementById(\"dropdownList\");\n\nconst showList = () => {\n if (dropdownList.style.display === \"none\") {\n dropdownList.style.display = \"block\";\n countries.map((c) => {\n const list = document.createElement(\"li\");\n list.className = \"dropdownItem\";\n\n list.addEventListener(\"click\", (e) => {\n dropdownBtn.innerText = e.target.innerText;\n dropdownList.innerHTML = \"\";\n });\n\n list.append(c);\n dropdownList.append(list);\n });\n } else {\n dropdownList.style.display = \"none\";\n dropdownList.innerHTML = \"\";\n }\n};\n\ndropdownBtn.addEventListener(\"click\", showList, false);\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74613777",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13843563/"
] |
74,613,781
|
<p>For Examle I have Request Validation</p>
<pre><code>'images.*' => 'mimes:jpg,jpeg|max:10240',
'images' => 'max:5',
</code></pre>
<p>It work In Create But , in update how I can check It , for example I already uploaded 4 image And In update I must add Only One Image , How I can validate it , is there any idea</p>
|
[
{
"answer_id": 74614549,
"author": "Satsangpriyadas Swami",
"author_id": 9677279,
"author_profile": "https://Stackoverflow.com/users/9677279",
"pm_score": 1,
"selected": false,
"text": "...\n dropdownList.innerHTML = \"\";\n for (let i = 0; i < countries.length; i++) {\n...\n"
},
{
"answer_id": 74614723,
"author": "EssXTee",
"author_id": 2339619,
"author_profile": "https://Stackoverflow.com/users/2339619",
"pm_score": 2,
"selected": true,
"text": "mouseover mouseout mouseover mouseout :hover <li> <li> const countries = [\"India\", \"Ireland\", \"USA\", \"UK\"],\ndropdownBtn = document.getElementById(\"dropdownBtn\"),\ndropdownList = document.getElementById(\"dropdownList\")\n\nconst showList = () => {\n if(dropdownList.innerText.length) {\n dropdownList.innerHTML = \"\"\n return\n }\n countries.forEach(c => {\n const list = document.createElement(\"li\")\n list.className = \"dropdownItem\"\n\n list.addEventListener(\"mouseover\", e => {\n e.target.classList.add(\"active\")\n })\n list.addEventListener(\"mouseout\", e => {\n e.target.classList.remove(\"active\")\n })\n list.addEventListener(\"click\", e => {\n dropdownBtn.innerText = e.target.innerText\n dropdownList.innerHTML = \"\"\n })\n\n list.append(c)\n dropdownList.append(list)\n })\n}\n\ndropdownBtn.addEventListener(\"click\", showList) .dropdownMain {\n width: 10rem;\n display: flex;\n justify-content: center;\n align-items: center;\n flex-direction: column;\n}\n\nbutton {\n color: white;\n border: none;\n width: 100%;\n height: 30px;\n margin-bottom: 0.5rem;\n background-image: linear-gradient(\n to bottom,\n #ff0000,\n #ff0031,\n #ff0050,\n #f8006b,\n #eb1283\n );\n font: 0.9rem bold;\n border-radius: 5px;\n cursor: pointer;\n transition: 0.5s all;\n}\n\nbutton:hover {\n color: black;\n background: inherit;\n border: 1px solid #ff0000;\n}\n\nbutton:focus {\n color: #ff0000;\n background: inherit;\n}\n\n.dropdownList {\n width: inherit;\n}\n\n.dropdownItem {\n color: #F00;\n list-style-type: none;\n padding: .5rem .5rem .5rem 1.1rem;\n margin: .2rem 0;\n border-radius: 5px;\n cursor: pointer;\n}\n.active {\n color: #000;\n background: lightpink;\n} <div class=\"dropdownMain\">\n <button id=\"dropdownBtn\" class=\"dropdwonBtn\">Select Country</button>\n <div id=\"dropdownList\" class=\"dropdownList\"></div>\n</div> .forEach() for .append()"
},
{
"answer_id": 74616270,
"author": "Tapesh Patel",
"author_id": 13843563,
"author_profile": "https://Stackoverflow.com/users/13843563",
"pm_score": 0,
"selected": false,
"text": "const countries = [\"India\", \"Ireland\", \"USA\", \"UK\"];\n\nconst dropdownBtn = document.getElementById(\"dropdownBtn\");\nconst dropdownList = document.getElementById(\"dropdownList\");\n\nconst showList = () => {\n if (dropdownList.style.display === \"none\") {\n dropdownList.style.display = \"block\";\n countries.map((c) => {\n const list = document.createElement(\"li\");\n list.className = \"dropdownItem\";\n\n list.addEventListener(\"click\", (e) => {\n dropdownBtn.innerText = e.target.innerText;\n dropdownList.innerHTML = \"\";\n });\n\n list.append(c);\n dropdownList.append(list);\n });\n } else {\n dropdownList.style.display = \"none\";\n dropdownList.innerHTML = \"\";\n }\n};\n\ndropdownBtn.addEventListener(\"click\", showList, false);\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74613781",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15826225/"
] |
74,613,812
|
<p>I have a use case, where i need to match the name <strong>key-value</strong> and according to match, it'll post a result.</p>
<p><strong>Input</strong></p>
<pre class="lang-json prettyprint-override"><code>{
"Dv type": null,
"Environment": null,
"ipa": null,
"category": null,
"name": "ALPHA009",
"Dv type0": "NYC",
"Environment0": "sev",
"ipa0": "X.Y.1",
"category0": "test",
"name0": "APLHA009"
}
</code></pre>
<ul>
<li><p>if <strong><code>name == name0</code></strong> then</p>
<p><strong>expected output</strong> will be</p>
</li>
</ul>
<pre class="lang-json prettyprint-override"><code> {
"Dv type0": "NYC",
"Environment0": "sev",
"ipa0": "X.Y.1",
"category0": "test",
"name0": "APLHA009"
}
</code></pre>
<ul>
<li><p>else when <strong><code>name != name0</code></strong> then</p>
<p><strong>expected output</strong> will look like</p>
</li>
</ul>
<pre class="lang-json prettyprint-override"><code> {
"Dv type": null,
"Environment": null,
"ipa": null,
"category": null,
"name": "ALPHA009"
}
</code></pre>
|
[
{
"answer_id": 74614549,
"author": "Satsangpriyadas Swami",
"author_id": 9677279,
"author_profile": "https://Stackoverflow.com/users/9677279",
"pm_score": 1,
"selected": false,
"text": "...\n dropdownList.innerHTML = \"\";\n for (let i = 0; i < countries.length; i++) {\n...\n"
},
{
"answer_id": 74614723,
"author": "EssXTee",
"author_id": 2339619,
"author_profile": "https://Stackoverflow.com/users/2339619",
"pm_score": 2,
"selected": true,
"text": "mouseover mouseout mouseover mouseout :hover <li> <li> const countries = [\"India\", \"Ireland\", \"USA\", \"UK\"],\ndropdownBtn = document.getElementById(\"dropdownBtn\"),\ndropdownList = document.getElementById(\"dropdownList\")\n\nconst showList = () => {\n if(dropdownList.innerText.length) {\n dropdownList.innerHTML = \"\"\n return\n }\n countries.forEach(c => {\n const list = document.createElement(\"li\")\n list.className = \"dropdownItem\"\n\n list.addEventListener(\"mouseover\", e => {\n e.target.classList.add(\"active\")\n })\n list.addEventListener(\"mouseout\", e => {\n e.target.classList.remove(\"active\")\n })\n list.addEventListener(\"click\", e => {\n dropdownBtn.innerText = e.target.innerText\n dropdownList.innerHTML = \"\"\n })\n\n list.append(c)\n dropdownList.append(list)\n })\n}\n\ndropdownBtn.addEventListener(\"click\", showList) .dropdownMain {\n width: 10rem;\n display: flex;\n justify-content: center;\n align-items: center;\n flex-direction: column;\n}\n\nbutton {\n color: white;\n border: none;\n width: 100%;\n height: 30px;\n margin-bottom: 0.5rem;\n background-image: linear-gradient(\n to bottom,\n #ff0000,\n #ff0031,\n #ff0050,\n #f8006b,\n #eb1283\n );\n font: 0.9rem bold;\n border-radius: 5px;\n cursor: pointer;\n transition: 0.5s all;\n}\n\nbutton:hover {\n color: black;\n background: inherit;\n border: 1px solid #ff0000;\n}\n\nbutton:focus {\n color: #ff0000;\n background: inherit;\n}\n\n.dropdownList {\n width: inherit;\n}\n\n.dropdownItem {\n color: #F00;\n list-style-type: none;\n padding: .5rem .5rem .5rem 1.1rem;\n margin: .2rem 0;\n border-radius: 5px;\n cursor: pointer;\n}\n.active {\n color: #000;\n background: lightpink;\n} <div class=\"dropdownMain\">\n <button id=\"dropdownBtn\" class=\"dropdwonBtn\">Select Country</button>\n <div id=\"dropdownList\" class=\"dropdownList\"></div>\n</div> .forEach() for .append()"
},
{
"answer_id": 74616270,
"author": "Tapesh Patel",
"author_id": 13843563,
"author_profile": "https://Stackoverflow.com/users/13843563",
"pm_score": 0,
"selected": false,
"text": "const countries = [\"India\", \"Ireland\", \"USA\", \"UK\"];\n\nconst dropdownBtn = document.getElementById(\"dropdownBtn\");\nconst dropdownList = document.getElementById(\"dropdownList\");\n\nconst showList = () => {\n if (dropdownList.style.display === \"none\") {\n dropdownList.style.display = \"block\";\n countries.map((c) => {\n const list = document.createElement(\"li\");\n list.className = \"dropdownItem\";\n\n list.addEventListener(\"click\", (e) => {\n dropdownBtn.innerText = e.target.innerText;\n dropdownList.innerHTML = \"\";\n });\n\n list.append(c);\n dropdownList.append(list);\n });\n } else {\n dropdownList.style.display = \"none\";\n dropdownList.innerHTML = \"\";\n }\n};\n\ndropdownBtn.addEventListener(\"click\", showList, false);\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74613812",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10932132/"
] |
74,613,826
|
<p>Using sklearn, I have just finished training, tuning hyperparameters and testing a Random Forest Multiclass Classifier using RandomizedSearchCV. I have obtained the best parameters, best score and so on. This was all done with a labelled dataset. Now I want to apply this classifier onto an unlabelled dataset (meaning there are only the features and no classes) to make class/label predictions.</p>
<p>How do I go about doing this?</p>
<p>I haven't tried anything yet because I am stuck.</p>
|
[
{
"answer_id": 74614222,
"author": "akilat90",
"author_id": 5864582,
"author_profile": "https://Stackoverflow.com/users/5864582",
"pm_score": 1,
"selected": false,
"text": "forest_search.predict(X_test)"
},
{
"answer_id": 74614938,
"author": "Keithx",
"author_id": 3079439,
"author_profile": "https://Stackoverflow.com/users/3079439",
"pm_score": 0,
"selected": false,
"text": "KMeans from sklearn.cluster import KMeans\nimport numpy as np\nX = np.array([[1, 2], [1, 4], [1, 0],\n [10, 2], [10, 4], [10, 0]])\nkmeans = KMeans(n_clusters=2, random_state=0).fit_predict(X)\nprint(kmeans)\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74613826",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
74,613,853
|
<p>I am trying to analyze an earnings call using python regular expression.
I want to delete unnecessary lines which only contain the name and position of the person, who is speaking next.</p>
<p>This is an excerpt of the text I want to analyze:</p>
<p>"Questions and Answers\nOperator [1]\n\n Shannon Siemsen Cross, Cross Research LLC - Co-Founder, Principal & Analyst [2]\n I hope everyone is well. Tim, you talked about seeing some improvement in the second half of April. So I was wondering if you could just talk maybe a bit more on the segment and geographic basis what you're seeing in the various regions that you're selling in and what you're hearing from your customers. And then I have a follow-up.\n Timothy D. Cook, Apple Inc. - CEO & Director [3]\n ..."</p>
<p>At the end of each line that I want to delete, you have [some number].</p>
<p>So I used the following line of code to get these lines:</p>
<p><code>name_lines = re.findall('.*[\d]]', text)</code></p>
<p>This works and gives me the following list:
['Operator [1]',
' Shannon Siemsen Cross, Cross Research LLC - Co-Founder, Principal & Analyst [2]',
' Timothy D. Cook, Apple Inc. - CEO & Director [3]']</p>
<p>So, now in the next step I want to replace this strings in the text using the following line of code:</p>
<pre><code>for i in range(0,len(name_lines)):
text = re.sub(name_lines[i], '', text)
</code></pre>
<p>But this does not work. Also if I just try to replace 1 instead of using the loop it does not work, but I have no clue why.</p>
<p>Also if I try now to use re.findall and search for the lines I obtained from the first line of code I don`t get a match.</p>
|
[
{
"answer_id": 74613921,
"author": "Thomas",
"author_id": 14637,
"author_profile": "https://Stackoverflow.com/users/14637",
"pm_score": 1,
"selected": true,
"text": "re.sub i for name_line in name_lines:\n text = text.replace(name_line, '')\n"
},
{
"answer_id": 74614215,
"author": "Andrej Kesely",
"author_id": 10035985,
"author_profile": "https://Stackoverflow.com/users/10035985",
"pm_score": 1,
"selected": false,
"text": "re.sub import re\n\ntext = \"\"\"\\\nQuestions and Answers\nOperator [1]\n\nShannon Siemsen Cross, Cross Research LLC - Co-Founder, Principal & Analyst [2]\nI hope everyone is well. Tim, you talked about seeing some improvement in the second half of April. So I was wondering if you could just talk maybe a bit more on the segment and geographic basis what you're seeing in the various regions that you're selling in and what you're hearing from your customers. And then I have a follow-up.\nTimothy D. Cook, Apple Inc. - CEO & Director [3]\"\"\"\n\ntext = re.sub(r\".*\\d]\", \"\", text)\nprint(text)\n Questions and Answers\n\n\n\nI hope everyone is well. Tim, you talked about seeing some improvement in the second half of April. So I was wondering if you could just talk maybe a bit more on the segment and geographic basis what you're seeing in the various regions that you're selling in and what you're hearing from your customers. And then I have a follow-up.\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74613853",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15788507/"
] |
74,613,861
|
<p>I have the following dataframe called df (<code>dput</code> below):</p>
<pre><code> group indicator value
1 A FALSE 2
2 A FALSE 1
3 A FALSE 2
4 A TRUE 4
5 B FALSE 5
6 B FALSE 1
7 B TRUE 3
</code></pre>
<p>I would like to remove the non-last rows with <code>indicator == FALSE</code> per group. This means that in df the rows: 1,2 and 5 should be removed because they are not the last rows with FALSE per group. Here is the desired output:</p>
<pre><code> group indicator value
1 A FALSE 2
2 A TRUE 4
3 B FALSE 1
4 B TRUE 3
</code></pre>
<p>So I was wondering if anyone knows how to remove non-last rows with certain condition per group in R?</p>
<hr />
<p><code>dput</code> of df:</p>
<pre><code>df <- structure(list(group = c("A", "A", "A", "A", "B", "B", "B"),
indicator = c(FALSE, FALSE, FALSE, TRUE, FALSE, FALSE, TRUE
), value = c(2, 1, 2, 4, 5, 1, 3)), class = "data.frame", row.names = c(NA,
-7L))
</code></pre>
|
[
{
"answer_id": 74613937,
"author": "MarBlo",
"author_id": 4282026,
"author_profile": "https://Stackoverflow.com/users/4282026",
"pm_score": 1,
"selected": false,
"text": "lead TRUE library(tidyverse)\ndf <- structure(list(group = c(\"A\", \"A\", \"A\", \"A\", \"B\", \"B\", \"B\"), \n indicator = c(FALSE, FALSE, FALSE, TRUE, FALSE, FALSE, TRUE\n ), value = c(2, 1, 2, 4, 5, 1, 3)), class = \"data.frame\", row.names = c(NA, \n -7L))\ndf |> \n group_by(group) |> \n mutate(slicer = if_else(lead(indicator) ==F, 1, 0)) |> \n mutate(slicer = if_else(is.na(slicer), 0 , slicer)) |> \n filter(slicer == 0) |> \n select(-slicer)\n#> # A tibble: 4 × 3\n#> # Groups: group [2]\n#> group indicator value\n#> <chr> <lgl> <dbl>\n#> 1 A FALSE 2\n#> 2 A TRUE 4\n#> 3 B FALSE 1\n#> 4 B TRUE 3\n"
},
{
"answer_id": 74614231,
"author": "zephryl",
"author_id": 17303805,
"author_profile": "https://Stackoverflow.com/users/17303805",
"pm_score": 3,
"selected": true,
"text": "last(which()) FALSE library(dplyr)\n\ndf %>%\n group_by(group) %>%\n filter(indicator | row_number() == last(which(!indicator))) %>%\n ungroup()\n # A tibble: 4 × 3\n group indicator value\n <chr> <lgl> <dbl>\n1 A FALSE 2\n2 A TRUE 4\n3 B FALSE 1\n4 B TRUE 3\n"
},
{
"answer_id": 74614262,
"author": "arg0naut91",
"author_id": 8389003,
"author_profile": "https://Stackoverflow.com/users/8389003",
"pm_score": 1,
"selected": false,
"text": "library(dplyr)\n\ndf %>%\n group_by(group) %>%\n slice_max(cumsum(!indicator))\n T T, F, F, T T F # A tibble: 4 x 3\n# Groups: group [2]\n group indicator value\n <chr> <lgl> <dbl>\n1 A FALSE 2\n2 A TRUE 4\n3 B FALSE 1\n4 B TRUE 3\n"
},
{
"answer_id": 74615711,
"author": "David",
"author_id": 11012216,
"author_profile": "https://Stackoverflow.com/users/11012216",
"pm_score": 1,
"selected": false,
"text": "should_be_kept <- logical(nrow(df))\nfor(row in 1:nrow(df)) {\n if(df[row,\"Indicator\"]) {\n should_be_kept[row] <- TRUE\n } else if(row == max(which(!df[, \"Indicator\"] & df$Group == df[row, \"Group\"]))) {\n should_be_kept[row] <- TRUE\n } else {\n should_be_kept[row] = FALSE\n }\n}\ndf[should_be_kept, ]\n rows_to_keep <- logical(nrow(df)) #We create a TRUE/FALSE vector with one entry for each row of df\nrows_to_keep[df$Indicator] <- TRUE #If Indicator is TRUE, we mark that row as \"selectable\"\n\nget_last_false_in_group <- function(df, group) {\n return(max(which(df$Group == group & !df$Indicator))) #Gets the last time the condition inside of which() is met\n}\n\n#The following chunk does a group-by-group search of the last false indicator. There's probably some apply magic that simplifies this but I'm too dumb to come up with it.\ngroups <- levels(factor(df$Group))\nfor(current_group in groups) {\n rows_to_keep[get_last_false_in_group(df, current_group)] <- TRUE\n}\n\n#Now that our rows_to_keep vector is ready, we can filter the corresponding rows and get the intended result:\ndf[rows_to_keep,]\n\n data.table last"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74613861",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14282714/"
] |
74,613,863
|
<p>I want to make a javascript code that if the user is using a chromium browser triggers an alert telling to change to Firefox/Other browser that are not using chromium derivates.</p>
<p>I tried modifying the folowing code:</p>
<pre><code> let notChrome = !/Chrome/.test(navigator.userAgent)
let alertMessage = "Please use Google Chrome to access this site.\nSome key features do not work in browsers other than Chrome."
if(notChrome) alert(alertMessage)
</code></pre>
<p>But I don't know how to modify-it</p>
|
[
{
"answer_id": 74613937,
"author": "MarBlo",
"author_id": 4282026,
"author_profile": "https://Stackoverflow.com/users/4282026",
"pm_score": 1,
"selected": false,
"text": "lead TRUE library(tidyverse)\ndf <- structure(list(group = c(\"A\", \"A\", \"A\", \"A\", \"B\", \"B\", \"B\"), \n indicator = c(FALSE, FALSE, FALSE, TRUE, FALSE, FALSE, TRUE\n ), value = c(2, 1, 2, 4, 5, 1, 3)), class = \"data.frame\", row.names = c(NA, \n -7L))\ndf |> \n group_by(group) |> \n mutate(slicer = if_else(lead(indicator) ==F, 1, 0)) |> \n mutate(slicer = if_else(is.na(slicer), 0 , slicer)) |> \n filter(slicer == 0) |> \n select(-slicer)\n#> # A tibble: 4 × 3\n#> # Groups: group [2]\n#> group indicator value\n#> <chr> <lgl> <dbl>\n#> 1 A FALSE 2\n#> 2 A TRUE 4\n#> 3 B FALSE 1\n#> 4 B TRUE 3\n"
},
{
"answer_id": 74614231,
"author": "zephryl",
"author_id": 17303805,
"author_profile": "https://Stackoverflow.com/users/17303805",
"pm_score": 3,
"selected": true,
"text": "last(which()) FALSE library(dplyr)\n\ndf %>%\n group_by(group) %>%\n filter(indicator | row_number() == last(which(!indicator))) %>%\n ungroup()\n # A tibble: 4 × 3\n group indicator value\n <chr> <lgl> <dbl>\n1 A FALSE 2\n2 A TRUE 4\n3 B FALSE 1\n4 B TRUE 3\n"
},
{
"answer_id": 74614262,
"author": "arg0naut91",
"author_id": 8389003,
"author_profile": "https://Stackoverflow.com/users/8389003",
"pm_score": 1,
"selected": false,
"text": "library(dplyr)\n\ndf %>%\n group_by(group) %>%\n slice_max(cumsum(!indicator))\n T T, F, F, T T F # A tibble: 4 x 3\n# Groups: group [2]\n group indicator value\n <chr> <lgl> <dbl>\n1 A FALSE 2\n2 A TRUE 4\n3 B FALSE 1\n4 B TRUE 3\n"
},
{
"answer_id": 74615711,
"author": "David",
"author_id": 11012216,
"author_profile": "https://Stackoverflow.com/users/11012216",
"pm_score": 1,
"selected": false,
"text": "should_be_kept <- logical(nrow(df))\nfor(row in 1:nrow(df)) {\n if(df[row,\"Indicator\"]) {\n should_be_kept[row] <- TRUE\n } else if(row == max(which(!df[, \"Indicator\"] & df$Group == df[row, \"Group\"]))) {\n should_be_kept[row] <- TRUE\n } else {\n should_be_kept[row] = FALSE\n }\n}\ndf[should_be_kept, ]\n rows_to_keep <- logical(nrow(df)) #We create a TRUE/FALSE vector with one entry for each row of df\nrows_to_keep[df$Indicator] <- TRUE #If Indicator is TRUE, we mark that row as \"selectable\"\n\nget_last_false_in_group <- function(df, group) {\n return(max(which(df$Group == group & !df$Indicator))) #Gets the last time the condition inside of which() is met\n}\n\n#The following chunk does a group-by-group search of the last false indicator. There's probably some apply magic that simplifies this but I'm too dumb to come up with it.\ngroups <- levels(factor(df$Group))\nfor(current_group in groups) {\n rows_to_keep[get_last_false_in_group(df, current_group)] <- TRUE\n}\n\n#Now that our rows_to_keep vector is ready, we can filter the corresponding rows and get the intended result:\ndf[rows_to_keep,]\n\n data.table last"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74613863",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20633107/"
] |
74,613,887
|
<p>What is the simplest way to write this in PowerShell:</p>
<pre><code>SELECT col1, SUM(col3) AS SumOfValues
FROM dbo.Table
GROUP BY col1
</code></pre>
<p>How can I combine <code>Group-Object</code> and <code>Measure-Object</code>?</p>
<p>I have found this answer <a href="https://stackoverflow.com/questions/68680733/powershell-group-array-objects-by-properties-and-sum">link</a>, but there must be a simpler way.</p>
|
[
{
"answer_id": 74613937,
"author": "MarBlo",
"author_id": 4282026,
"author_profile": "https://Stackoverflow.com/users/4282026",
"pm_score": 1,
"selected": false,
"text": "lead TRUE library(tidyverse)\ndf <- structure(list(group = c(\"A\", \"A\", \"A\", \"A\", \"B\", \"B\", \"B\"), \n indicator = c(FALSE, FALSE, FALSE, TRUE, FALSE, FALSE, TRUE\n ), value = c(2, 1, 2, 4, 5, 1, 3)), class = \"data.frame\", row.names = c(NA, \n -7L))\ndf |> \n group_by(group) |> \n mutate(slicer = if_else(lead(indicator) ==F, 1, 0)) |> \n mutate(slicer = if_else(is.na(slicer), 0 , slicer)) |> \n filter(slicer == 0) |> \n select(-slicer)\n#> # A tibble: 4 × 3\n#> # Groups: group [2]\n#> group indicator value\n#> <chr> <lgl> <dbl>\n#> 1 A FALSE 2\n#> 2 A TRUE 4\n#> 3 B FALSE 1\n#> 4 B TRUE 3\n"
},
{
"answer_id": 74614231,
"author": "zephryl",
"author_id": 17303805,
"author_profile": "https://Stackoverflow.com/users/17303805",
"pm_score": 3,
"selected": true,
"text": "last(which()) FALSE library(dplyr)\n\ndf %>%\n group_by(group) %>%\n filter(indicator | row_number() == last(which(!indicator))) %>%\n ungroup()\n # A tibble: 4 × 3\n group indicator value\n <chr> <lgl> <dbl>\n1 A FALSE 2\n2 A TRUE 4\n3 B FALSE 1\n4 B TRUE 3\n"
},
{
"answer_id": 74614262,
"author": "arg0naut91",
"author_id": 8389003,
"author_profile": "https://Stackoverflow.com/users/8389003",
"pm_score": 1,
"selected": false,
"text": "library(dplyr)\n\ndf %>%\n group_by(group) %>%\n slice_max(cumsum(!indicator))\n T T, F, F, T T F # A tibble: 4 x 3\n# Groups: group [2]\n group indicator value\n <chr> <lgl> <dbl>\n1 A FALSE 2\n2 A TRUE 4\n3 B FALSE 1\n4 B TRUE 3\n"
},
{
"answer_id": 74615711,
"author": "David",
"author_id": 11012216,
"author_profile": "https://Stackoverflow.com/users/11012216",
"pm_score": 1,
"selected": false,
"text": "should_be_kept <- logical(nrow(df))\nfor(row in 1:nrow(df)) {\n if(df[row,\"Indicator\"]) {\n should_be_kept[row] <- TRUE\n } else if(row == max(which(!df[, \"Indicator\"] & df$Group == df[row, \"Group\"]))) {\n should_be_kept[row] <- TRUE\n } else {\n should_be_kept[row] = FALSE\n }\n}\ndf[should_be_kept, ]\n rows_to_keep <- logical(nrow(df)) #We create a TRUE/FALSE vector with one entry for each row of df\nrows_to_keep[df$Indicator] <- TRUE #If Indicator is TRUE, we mark that row as \"selectable\"\n\nget_last_false_in_group <- function(df, group) {\n return(max(which(df$Group == group & !df$Indicator))) #Gets the last time the condition inside of which() is met\n}\n\n#The following chunk does a group-by-group search of the last false indicator. There's probably some apply magic that simplifies this but I'm too dumb to come up with it.\ngroups <- levels(factor(df$Group))\nfor(current_group in groups) {\n rows_to_keep[get_last_false_in_group(df, current_group)] <- TRUE\n}\n\n#Now that our rows_to_keep vector is ready, we can filter the corresponding rows and get the intended result:\ndf[rows_to_keep,]\n\n data.table last"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74613887",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10623301/"
] |
74,613,898
|
<p>I want to access and print a config parameter in a report.</p>
<p>I have tried this</p>
<pre><code><div t-if="ir.config_paramter">
<span t-field="ir.config_paramter.mymodule.myhtmlfield"/>
</div>
</code></pre>
<p>But I get an error saying it does not know 'ir'</p>
<p>The report I am trying to edit is <code>account.report_invoice_document</code></p>
<p>What do I need to do to correctly print the field on the report?</p>
|
[
{
"answer_id": 74613937,
"author": "MarBlo",
"author_id": 4282026,
"author_profile": "https://Stackoverflow.com/users/4282026",
"pm_score": 1,
"selected": false,
"text": "lead TRUE library(tidyverse)\ndf <- structure(list(group = c(\"A\", \"A\", \"A\", \"A\", \"B\", \"B\", \"B\"), \n indicator = c(FALSE, FALSE, FALSE, TRUE, FALSE, FALSE, TRUE\n ), value = c(2, 1, 2, 4, 5, 1, 3)), class = \"data.frame\", row.names = c(NA, \n -7L))\ndf |> \n group_by(group) |> \n mutate(slicer = if_else(lead(indicator) ==F, 1, 0)) |> \n mutate(slicer = if_else(is.na(slicer), 0 , slicer)) |> \n filter(slicer == 0) |> \n select(-slicer)\n#> # A tibble: 4 × 3\n#> # Groups: group [2]\n#> group indicator value\n#> <chr> <lgl> <dbl>\n#> 1 A FALSE 2\n#> 2 A TRUE 4\n#> 3 B FALSE 1\n#> 4 B TRUE 3\n"
},
{
"answer_id": 74614231,
"author": "zephryl",
"author_id": 17303805,
"author_profile": "https://Stackoverflow.com/users/17303805",
"pm_score": 3,
"selected": true,
"text": "last(which()) FALSE library(dplyr)\n\ndf %>%\n group_by(group) %>%\n filter(indicator | row_number() == last(which(!indicator))) %>%\n ungroup()\n # A tibble: 4 × 3\n group indicator value\n <chr> <lgl> <dbl>\n1 A FALSE 2\n2 A TRUE 4\n3 B FALSE 1\n4 B TRUE 3\n"
},
{
"answer_id": 74614262,
"author": "arg0naut91",
"author_id": 8389003,
"author_profile": "https://Stackoverflow.com/users/8389003",
"pm_score": 1,
"selected": false,
"text": "library(dplyr)\n\ndf %>%\n group_by(group) %>%\n slice_max(cumsum(!indicator))\n T T, F, F, T T F # A tibble: 4 x 3\n# Groups: group [2]\n group indicator value\n <chr> <lgl> <dbl>\n1 A FALSE 2\n2 A TRUE 4\n3 B FALSE 1\n4 B TRUE 3\n"
},
{
"answer_id": 74615711,
"author": "David",
"author_id": 11012216,
"author_profile": "https://Stackoverflow.com/users/11012216",
"pm_score": 1,
"selected": false,
"text": "should_be_kept <- logical(nrow(df))\nfor(row in 1:nrow(df)) {\n if(df[row,\"Indicator\"]) {\n should_be_kept[row] <- TRUE\n } else if(row == max(which(!df[, \"Indicator\"] & df$Group == df[row, \"Group\"]))) {\n should_be_kept[row] <- TRUE\n } else {\n should_be_kept[row] = FALSE\n }\n}\ndf[should_be_kept, ]\n rows_to_keep <- logical(nrow(df)) #We create a TRUE/FALSE vector with one entry for each row of df\nrows_to_keep[df$Indicator] <- TRUE #If Indicator is TRUE, we mark that row as \"selectable\"\n\nget_last_false_in_group <- function(df, group) {\n return(max(which(df$Group == group & !df$Indicator))) #Gets the last time the condition inside of which() is met\n}\n\n#The following chunk does a group-by-group search of the last false indicator. There's probably some apply magic that simplifies this but I'm too dumb to come up with it.\ngroups <- levels(factor(df$Group))\nfor(current_group in groups) {\n rows_to_keep[get_last_false_in_group(df, current_group)] <- TRUE\n}\n\n#Now that our rows_to_keep vector is ready, we can filter the corresponding rows and get the intended result:\ndf[rows_to_keep,]\n\n data.table last"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74613898",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14234203/"
] |
74,613,902
|
<p>I want to do change the name of a key in an <code>Object</code>. But when I want to do this with an if condition, I get this <code>(Assignment to function parameter 'key')</code> error. How can i manipulate a key name ?</p>
<p><strong>My Code:</strong></p>
<pre><code>const personData = [];
Object.keys(testItem).forEach((key) => {
item = testItem[key];
if (key === 'Name'){
key = 'Person Name';
}
personData.push({ name: key, data: Object.values(item) })
});
</code></pre>
<p><strong>testItem data:</strong></p>
<pre><code>testItem = {Name: {...}, Surname: {...}}
</code></pre>
<p>I want the <code>Name</code> key to change to <code>Person Name</code> without error.</p>
|
[
{
"answer_id": 74613937,
"author": "MarBlo",
"author_id": 4282026,
"author_profile": "https://Stackoverflow.com/users/4282026",
"pm_score": 1,
"selected": false,
"text": "lead TRUE library(tidyverse)\ndf <- structure(list(group = c(\"A\", \"A\", \"A\", \"A\", \"B\", \"B\", \"B\"), \n indicator = c(FALSE, FALSE, FALSE, TRUE, FALSE, FALSE, TRUE\n ), value = c(2, 1, 2, 4, 5, 1, 3)), class = \"data.frame\", row.names = c(NA, \n -7L))\ndf |> \n group_by(group) |> \n mutate(slicer = if_else(lead(indicator) ==F, 1, 0)) |> \n mutate(slicer = if_else(is.na(slicer), 0 , slicer)) |> \n filter(slicer == 0) |> \n select(-slicer)\n#> # A tibble: 4 × 3\n#> # Groups: group [2]\n#> group indicator value\n#> <chr> <lgl> <dbl>\n#> 1 A FALSE 2\n#> 2 A TRUE 4\n#> 3 B FALSE 1\n#> 4 B TRUE 3\n"
},
{
"answer_id": 74614231,
"author": "zephryl",
"author_id": 17303805,
"author_profile": "https://Stackoverflow.com/users/17303805",
"pm_score": 3,
"selected": true,
"text": "last(which()) FALSE library(dplyr)\n\ndf %>%\n group_by(group) %>%\n filter(indicator | row_number() == last(which(!indicator))) %>%\n ungroup()\n # A tibble: 4 × 3\n group indicator value\n <chr> <lgl> <dbl>\n1 A FALSE 2\n2 A TRUE 4\n3 B FALSE 1\n4 B TRUE 3\n"
},
{
"answer_id": 74614262,
"author": "arg0naut91",
"author_id": 8389003,
"author_profile": "https://Stackoverflow.com/users/8389003",
"pm_score": 1,
"selected": false,
"text": "library(dplyr)\n\ndf %>%\n group_by(group) %>%\n slice_max(cumsum(!indicator))\n T T, F, F, T T F # A tibble: 4 x 3\n# Groups: group [2]\n group indicator value\n <chr> <lgl> <dbl>\n1 A FALSE 2\n2 A TRUE 4\n3 B FALSE 1\n4 B TRUE 3\n"
},
{
"answer_id": 74615711,
"author": "David",
"author_id": 11012216,
"author_profile": "https://Stackoverflow.com/users/11012216",
"pm_score": 1,
"selected": false,
"text": "should_be_kept <- logical(nrow(df))\nfor(row in 1:nrow(df)) {\n if(df[row,\"Indicator\"]) {\n should_be_kept[row] <- TRUE\n } else if(row == max(which(!df[, \"Indicator\"] & df$Group == df[row, \"Group\"]))) {\n should_be_kept[row] <- TRUE\n } else {\n should_be_kept[row] = FALSE\n }\n}\ndf[should_be_kept, ]\n rows_to_keep <- logical(nrow(df)) #We create a TRUE/FALSE vector with one entry for each row of df\nrows_to_keep[df$Indicator] <- TRUE #If Indicator is TRUE, we mark that row as \"selectable\"\n\nget_last_false_in_group <- function(df, group) {\n return(max(which(df$Group == group & !df$Indicator))) #Gets the last time the condition inside of which() is met\n}\n\n#The following chunk does a group-by-group search of the last false indicator. There's probably some apply magic that simplifies this but I'm too dumb to come up with it.\ngroups <- levels(factor(df$Group))\nfor(current_group in groups) {\n rows_to_keep[get_last_false_in_group(df, current_group)] <- TRUE\n}\n\n#Now that our rows_to_keep vector is ready, we can filter the corresponding rows and get the intended result:\ndf[rows_to_keep,]\n\n data.table last"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74613902",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19443659/"
] |
74,613,903
|
<p>Firstly ,I was doing <code>cy.contains(option)</code> with it was clicking the exact value eg -I want to click <code>One</code> but <code>One One</code> is also there so <code>cy.contains</code> not working.</p>
<p>I tried Regex but it is not working</p>
<p>I am trying to click the exact match from drop down writing test step as ;</p>
<pre class="lang-js prettyprint-override"><code>cy.contains(new RegExp(option, "g"))
</code></pre>
<p>but not giving me correct output. I am getting error : <code>Timed out retrying after 4000ms: Expected to find content: 'option' but never did.</code></p>
|
[
{
"answer_id": 74617484,
"author": "Daniel",
"author_id": 197546,
"author_profile": "https://Stackoverflow.com/users/197546",
"pm_score": 0,
"selected": false,
"text": "^ $ // works on <span>One</span> but not on <span> One </span> or <span>One One</span>\ncy.get(`span`).contains(/^One$/)\n\n// so you might want to also include white space\ncy.get(`span`).contains(/^\\s?One\\s?$/)\n"
},
{
"answer_id": 74622078,
"author": "Graciella",
"author_id": 20639409,
"author_profile": "https://Stackoverflow.com/users/20639409",
"pm_score": 1,
"selected": false,
"text": ".select() cy.get('select')\n .select('One')\n .should('have.value', 'One')\n <select>\n <option>One One</option>\n <option>One</option>\n</select>\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74613903",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20625643/"
] |
74,613,924
|
<p>Hy! I have a dataframe with two columns latitude and longitude with a wrong format that i want to correct. The structure of de strings in columns is the next</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Lat</th>
<th>Long</th>
</tr>
</thead>
<tbody>
<tr>
<td>-314193332</td>
<td>-6419125129999990</td>
</tr>
<tr>
<td>-313147283</td>
<td>-641708031</td>
</tr>
</tbody>
</table>
</div>
<p>I need to append a point in the third position to have this structure:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Lat</th>
<th>Long</th>
</tr>
</thead>
<tbody>
<tr>
<td>-31.4193332</td>
<td>-64.19125129999990</td>
</tr>
<tr>
<td>-31.3147283</td>
<td>-64.1708031</td>
</tr>
</tbody>
</table>
</div>
<p>how can i do this?</p>
<p>the value being an integer type too, i can configure that if there is a function to edit integers</p>
|
[
{
"answer_id": 74614029,
"author": "mozway",
"author_id": 16343464,
"author_profile": "https://Stackoverflow.com/users/16343464",
"pm_score": 2,
"selected": false,
"text": "N = 2 # number of digits to keep before decimal part\nout = df.div(10**np.floor(np.log10(df.abs())+1).sub(N))\n Lat Long\n0 -31.419333 -64.191251\n1 -31.314728 -64.170803\n np.floor(np.log10(df.abs())+1)\n\n Lat Long\n0 9.0 16.0\n1 9.0 9.0\n"
},
{
"answer_id": 74614430,
"author": "PaulS",
"author_id": 11564487,
"author_profile": "https://Stackoverflow.com/users/11564487",
"pm_score": 1,
"selected": false,
"text": "regex . df.astype(str).replace(r'(^-?\\d{2})',r'\\1.', regex=True).astype(float)\n Lat Long\n0 -31.419333 -64.191251\n1 -31.314728 -64.170803\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74613924",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15386335/"
] |
74,613,951
|
<p>im going to create a new react app with npm , but it dos'nt work and i have too many errors each time i try
can someone help me please?:(</p>
<p>i entered this line in cmd</p>
<pre><code>npx create-react-app my-app
</code></pre>
<p>and the errors :</p>
<pre><code>npm ERR! code ECONNRESET
npm ERR! syscall read
npm ERR! errno -4077
npm ERR! network read ECONNRESET
npm ERR! network This is a problem related to network connectivity.
npm ERR! network In most cases you are behind a proxy or have bad network settings.
npm ERR! network
npm ERR! network If you are behind a proxy, please make sure that the
npm ERR! network 'proxy' config is set properly. See: 'npm help config'
npm ERR! A complete log of this run can be found in:
npm ERR! C:\Users\sobha\AppData\Local\npm-cache\_logs\2022-11-29T11_57_33_191Z-debug-0.log
Aborting installation.
npm install --no-audit --save --save-exact --loglevel error react react-dom react-scripts cra-template has failed.
Deleting generated file... node_modules
Deleting generated file... package.json
Deleting my-app/ from C:\Users\sobha\Desktop\react
Done.
</code></pre>
|
[
{
"answer_id": 74614029,
"author": "mozway",
"author_id": 16343464,
"author_profile": "https://Stackoverflow.com/users/16343464",
"pm_score": 2,
"selected": false,
"text": "N = 2 # number of digits to keep before decimal part\nout = df.div(10**np.floor(np.log10(df.abs())+1).sub(N))\n Lat Long\n0 -31.419333 -64.191251\n1 -31.314728 -64.170803\n np.floor(np.log10(df.abs())+1)\n\n Lat Long\n0 9.0 16.0\n1 9.0 9.0\n"
},
{
"answer_id": 74614430,
"author": "PaulS",
"author_id": 11564487,
"author_profile": "https://Stackoverflow.com/users/11564487",
"pm_score": 1,
"selected": false,
"text": "regex . df.astype(str).replace(r'(^-?\\d{2})',r'\\1.', regex=True).astype(float)\n Lat Long\n0 -31.419333 -64.191251\n1 -31.314728 -64.170803\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74613951",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20435133/"
] |
74,613,965
|
<p>When deploying a custom script extension for a VM in Azure, it times out after 15 minutes. The timeout block is set to 2hrs. I cannot figure out why it keeps timing out. Could anyone point me in the right direction please? Thanks.</p>
<p>Resource to deploy (<a href="https://i.stack.imgur.com/lIfKj.png" rel="nofollow noreferrer">https://i.stack.imgur.com/lIfKj.png</a>)</p>
<p>Error (<a href="https://i.stack.imgur.com/GFYRL.png" rel="nofollow noreferrer">https://i.stack.imgur.com/GFYRL.png</a>)</p>
|
[
{
"answer_id": 74614029,
"author": "mozway",
"author_id": 16343464,
"author_profile": "https://Stackoverflow.com/users/16343464",
"pm_score": 2,
"selected": false,
"text": "N = 2 # number of digits to keep before decimal part\nout = df.div(10**np.floor(np.log10(df.abs())+1).sub(N))\n Lat Long\n0 -31.419333 -64.191251\n1 -31.314728 -64.170803\n np.floor(np.log10(df.abs())+1)\n\n Lat Long\n0 9.0 16.0\n1 9.0 9.0\n"
},
{
"answer_id": 74614430,
"author": "PaulS",
"author_id": 11564487,
"author_profile": "https://Stackoverflow.com/users/11564487",
"pm_score": 1,
"selected": false,
"text": "regex . df.astype(str).replace(r'(^-?\\d{2})',r'\\1.', regex=True).astype(float)\n Lat Long\n0 -31.419333 -64.191251\n1 -31.314728 -64.170803\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74613965",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20633147/"
] |
74,613,972
|
<p><code>Azure Data Explorer</code> uses <code>Kusto Query Language (KQL)</code>. Why <code>Microsoft</code> didn't use <code>SQL</code> ?</p>
<pre><code>LogEvents
| where StartTime > datetime(2021-12-31)
| where EventType == 'Error'
| project StartTime, EventType , Message
</code></pre>
<p>The same could be written in <code>sql</code> saving developers effort to learn a new language</p>
<p><code>select StartTime, EventType, Message from LogEvents where startime > ....</code></p>
|
[
{
"answer_id": 74614029,
"author": "mozway",
"author_id": 16343464,
"author_profile": "https://Stackoverflow.com/users/16343464",
"pm_score": 2,
"selected": false,
"text": "N = 2 # number of digits to keep before decimal part\nout = df.div(10**np.floor(np.log10(df.abs())+1).sub(N))\n Lat Long\n0 -31.419333 -64.191251\n1 -31.314728 -64.170803\n np.floor(np.log10(df.abs())+1)\n\n Lat Long\n0 9.0 16.0\n1 9.0 9.0\n"
},
{
"answer_id": 74614430,
"author": "PaulS",
"author_id": 11564487,
"author_profile": "https://Stackoverflow.com/users/11564487",
"pm_score": 1,
"selected": false,
"text": "regex . df.astype(str).replace(r'(^-?\\d{2})',r'\\1.', regex=True).astype(float)\n Lat Long\n0 -31.419333 -64.191251\n1 -31.314728 -64.170803\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74613972",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6703783/"
] |
74,613,987
|
<p>I have the following function-based view:</p>
<pre><code>def get_emails(request, HOST, USERNAME, PASSWORD):
context = {
'FU_HOST': settings.FU_HOST,
'FU_USERNAME': settings.FU_USERNAME,
'FU_PASSWORD': settings.FU_PASSWORD,
'FV_HOST': settings.FV_HOST,
'FV_USERNAME': settings.FV_USERNAME,
'FV_PASSWORD': settings.FV_PASSWORD,
'USV_HOST': settings.USV_HOST,
'USV_USERNAME': settings.USV_USERNAME,
'USV_PASSWORD': settings.USV_PASSWORD,
}
m = imaplib.IMAP4_SSL(HOST, 993)
m.login(USERNAME, PASSWORD)
m.select('INBOX')
result, data = m.uid('search', None, "ALL")
if result == 'OK':
for num in data[0].split():
result, data = m.uid('fetch', num, '(RFC822)')
if result == 'OK':
email_message_raw = email.message_from_bytes(data[0][1])
email_from = str(make_header(decode_header(email_message_raw['From'])))
email_addr = email_from.replace('<', '>').split('>')
if len(email_addr) > 1:
new_entry = EmailMarketing(email_address=email_addr[1], mail_server='X')
new_entry.save()
else:
new_entry = EmailMarketing(email_address=email_addr[0], mail_server='X')
new_entry.save()
m.close()
m.logout()
messages.success(request, f'Subscribers list sychronized successfully.')
return redirect('subscribers')
</code></pre>
<p>I'd like to place 3 buttons on my front-end that call this same function with different arguments each time, for example one button get_emails(FU_HOST, FU_USERNAME, FU_PASSWORD), the other button get_emails(USV_HOST, USV_USERNAME, USV_PASSWORD).</p>
<p>How can one achieve this in Django? My credentials are stored in .env file.</p>
|
[
{
"answer_id": 74614309,
"author": "Constantinos Petrakis",
"author_id": 11718554,
"author_profile": "https://Stackoverflow.com/users/11718554",
"pm_score": 0,
"selected": false,
"text": "def get_emails(request):\n context = {\n 'FU_HOST': settings.FU_HOST,\n 'FU_USERNAME': settings.FU_USERNAME,\n 'FU_PASSWORD': settings.FU_PASSWORD,\n 'FV_HOST': settings.FV_HOST,\n 'FV_USERNAME': settings.FV_USERNAME,\n 'FV_PASSWORD': settings.FV_PASSWORD,\n 'USV_HOST': settings.USV_HOST,\n 'USV_USERNAME': settings.USV_USERNAME,\n 'USV_PASSWORD': settings.USV_PASSWORD,\n }\n\n if request.method == \"POST\":\n HOST = request.POST[\"HOST\"]\n USERNAME = request.POST[\"USERNAME\"]\n PASSWORD = request.POST[\"PASSWORD\"]\n\n m = imaplib.IMAP4_SSL(HOST, 993)\n m.login(USERNAME, PASSWORD)\n m.select('INBOX')\n result, data = m.uid('search', None, \"ALL\")\n if result == 'OK':\n for num in data[0].split():\n result, data = m.uid('fetch', num, '(RFC822)')\n if result == 'OK':\n email_message_raw = email.message_from_bytes(data[0][1])\n email_from = str(make_header(decode_header(email_message_raw['From'])))\n email_addr = email_from.replace('<', '>').split('>')\n if len(email_addr) > 1:\n new_entry = EmailMarketing(email_address=email_addr[1], mail_server='X')\n new_entry.save()\n else:\n new_entry = EmailMarketing(email_address=email_addr[0], mail_server='X')\n new_entry.save()\n m.close()\n m.logout()\n\n messages.success(request, f'Subscribers list sychronized successfully.')\n return redirect('subscribers')\n <form action=\"{% url 'name-of-your-view' %}\" method=\"POST\">\n<input type=\"text\" name=\"HOST\">\n<input type=\"text\" name=\"USERNAME\">\n<input type=\"text\" name=\"PASSWORD\">\n<input type=\"submit\">\n</form>\n"
},
{
"answer_id": 74614713,
"author": "Enis",
"author_id": 16027068,
"author_profile": "https://Stackoverflow.com/users/16027068",
"pm_score": 0,
"selected": false,
"text": "<script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js\"></script>\n<script>\n function post(_host,_username,_password){\n $.ajax({\n url: '{% url \"url-name\"%}',\n type: 'POST',\n data: { \n csrfmiddlewaretoken: \"{{ csrf_token }}\",\n host: _host,\n username = _username,\n password = _password\n },\n success: function (res) {\n console.log(res);\n }\n });\n }\n</script>\n def get_emails(request):\n HOST = request.POST.get('host')\n USERNAME = request.POST.get('username')\n PASSWORD = request.POST.get('password')\n context = {\n 'FU_HOST': settings.FU_HOST,\n 'FU_USERNAME': settings.FU_USERNAME,\n 'FU_PASSWORD': settings.FU_PASSWORD,\n 'FV_HOST': settings.FV_HOST,\n 'FV_USERNAME': settings.FV_USERNAME,\n 'FV_PASSWORD': settings.FV_PASSWORD,\n 'USV_HOST': settings.USV_HOST,\n 'USV_USERNAME': settings.USV_USERNAME,\n 'USV_PASSWORD': settings.USV_PASSWORD,\n }\n m = imaplib.IMAP4_SSL(HOST, 993)\n m.login(USERNAME, PASSWORD)\n m.select('INBOX')\n result, data = m.uid('search', None, \"ALL\")\n if result == 'OK':\n for num in data[0].split():\n result, data = m.uid('fetch', num, '(RFC822)')\n if result == 'OK':\n email_message_raw = email.message_from_bytes(data[0][1])\n email_from = str(make_header(decode_header(email_message_raw['From'])))\n email_addr = email_from.replace('<', '>').split('>')\n if len(email_addr) > 1:\n new_entry = EmailMarketing(email_address=email_addr[1], mail_server='X')\n new_entry.save()\n else:\n new_entry = EmailMarketing(email_address=email_addr[0], mail_server='X')\n new_entry.save()\n m.close()\n m.logout()\n\n messages.success(request, f'Subscribers list sychronized successfully.')\n return redirect('subscribers')\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74613987",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13887772/"
] |
74,613,993
|
<p>How can I convert a mutable u8 pointer to a mutable reference of another type?</p>
<pre class="lang-rs prettyprint-override"><code>let ptr: *mut u8;
let reference: &mut SomeType = ?; // What should i do here?
</code></pre>
<p>I have found a sort-of viable solution, but I wonder if there is a better way:</p>
<pre class="lang-rs prettyprint-override"><code>let reference = unsafe { &mut *(ptr as *mut SomeType) };
</code></pre>
|
[
{
"answer_id": 74614200,
"author": "cafce25",
"author_id": 442760,
"author_profile": "https://Stackoverflow.com/users/442760",
"pm_score": 0,
"selected": false,
"text": "std::mem::transmute use std::mem::transmute;\n#[repr(transparent)]\nstruct SomeStruct(u8);\n\nfn main() {\n let a = &mut 10u8;\n let ptr = a as *mut u8;\n let reference: &mut SomeStruct = unsafe { transmute(ptr) };\n}\n"
},
{
"answer_id": 74616791,
"author": "Kevin Reid",
"author_id": 99692,
"author_profile": "https://Stackoverflow.com/users/99692",
"pm_score": 2,
"selected": true,
"text": "pointer::cast as as let ptr = ptr.cast::<SomeType>();\nlet reference = unsafe { &mut *ptr };\n std::mem::transmute cast &*"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74613993",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12348390/"
] |
74,614,014
|
<p>when i change the background color from a div with js its doenst change it on my site.
when i inspect i see that the css gets added inline but it doenst change
this is the code i use in my js file to change the backgroundcolor
i also make the div in this file
i also have to ue js and setattribute because its for school task
here is the whole js file</p>
<pre><code>const div=document.createElement("div")
const h3=document.createElement("h3")
document.querySelector("main").appendChild(div)
div.appendChild(h3)
h3.innerHTML="Status"
div.id="status"
</code></pre>
<p>here i initiate the div</p>
<pre><code>document.getElementById("status").addEventListener("mouseover", () => document.getElementById("status").setAttribute("style", "background-color:black;"));
document.getElementById("status").addEventListener("mouseout", () => document.getElementById("status").removeAttribute("style"));
</code></pre>
<p>here i try to change the background color</p>
<pre><code><!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>My Games</title>
<link type="text/css" href="styles/style.css" rel="stylesheet" />
<script tpye="text/javascript" src="js/dom.js" defer></script>
<script type="text/javascript" src="js/table-overview.js" defer></script>
</head>
<body>
<header>
<img src="images/logo.jpg" alt="Logo image of games" class="logo" />
<nav>
<ul>
<li class="actual">
<a href="index.html">Home</a>
</li>
<li>
<a href="overview.html">Overview</a>
</li>
<li><a href="table-overview.html">Table overview</a></li>
</ul>
</nav>
</header>
<main>
<h2>My Games</h2>
</main>
<footer>Wietse Gijbels: Front-end - 2022</footer>
</body>
</html>
</code></pre>
<pre><code>*{
background-color: #00004f;
color: #fff;
text-align: center;
max-width: 800px;
margin: auto;
}
h2{
margin: 2em 0 ;
}
h3{
margin: 3em 0 1.5em 0
}
p{
margin: auto;
margin-bottom: 10px;
}
footer{
margin-top: 2em;
background-color: #000083;
padding: 10px 0;
border-radius: 10px;
}
</code></pre>
|
[
{
"answer_id": 74614078,
"author": "flyingfox",
"author_id": 3176419,
"author_profile": "https://Stackoverflow.com/users/3176419",
"pm_score": 2,
"selected": false,
"text": "div div let div = document.getElementById(\"status\")\ndiv.addEventListener(\"mouseover\", () => div.setAttribute(\"style\", \"background-color:black;color:white\"));\ndiv.addEventListener(\"mouseout\", () => div.removeAttribute(\"style\")); <div id=\"status\">Change Background Color</div> const div=document.createElement(\"div\")\nconst h3=document.createElement(\"h3\")\ndocument.querySelector(\"main\").appendChild(div)\ndiv.appendChild(h3)\nh3.innerHTML=\"Status\"\ndiv.id=\"status\"\n\nlet divEle = document.getElementById(\"status\")\ndivEle.addEventListener(\"mouseover\", () => divEle.setAttribute(\"style\", \"background-color:black;color:white\"));\ndivEle.addEventListener(\"mouseout\", () => divEle.removeAttribute(\"style\")); <main>\n</main>"
},
{
"answer_id": 74614103,
"author": "FUZIION",
"author_id": 13050564,
"author_profile": "https://Stackoverflow.com/users/13050564",
"pm_score": -1,
"selected": false,
"text": "const div = document.createElement(\"div\")\n\nvar body = document.getElementById(\"main\")\nbody.appendChild(div)\ndiv.setAttribute(\"id\", \"status\");\n\nlet divSelect = document.getElementById(\"main\")\ndivSelect.addEventListener(\"mouseover\", () => div.setAttribute(\"style\", \"background-color:black;color:white\"));\ndivSelect.addEventListener(\"mouseout\", () => div.removeAttribute(\"style\")); #status {\n width: 200px;\n height: 25px;\n border: 1px solid black;\n} <div id=\"main\"></div>"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74614014",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20633221/"
] |
74,614,107
|
<p>I am using Amazon's sample code to connect to my S3 bucket. I have changed the key and bucket name for that of my bucket in S3. I have tried using the standard bucket name and using access points however I am still getting the following error.</p>
<pre><code>Error CredentialsProviderError: Could not load credentials from any providers
</code></pre>
<p>I am unsure what exactly this error is saying I have missed, and also what credentials I need and how to recieve them.</p>
<p>I am relatively new to AWS so any help would be much appreciated.</p>
<p>I am running my code to access the bucket on an EC2 instance within the same VPC as the bucket so I was assuming I would not need additional permissions or credentials.</p>
<p>I am relatively new to AWS so any help would be much appreciated.</p>
|
[
{
"answer_id": 74614334,
"author": "Caldazar",
"author_id": 1992773,
"author_profile": "https://Stackoverflow.com/users/1992773",
"pm_score": 1,
"selected": false,
"text": "instance profiles IAM Roles IAM AmazonS3FullAccess AmazonS3ReadOnlyAccess Actions -> Security - Modify IAM Role"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74614107",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20633010/"
] |
74,614,112
|
<p>hi i have json like this:</p>
<pre><code>"data": {
"list_item": [
{
"item": "1",
"item_date": "1669189813143566825",
"item_id": "0",
"item_info": {},"
"item_status":"on",
}]}
</code></pre>
<p>this class with sample table worked for me!but my table in app used paginated table and not worked in.</p>
<pre><code>class TableSamleNew extends StatefulWidget {
const TableSamleNew({Key? key}) : super(key: key);
@override
State<TableSamleNew> createState() => _TableSamleNewState();
}
class _TableSamleNewState extends State<TableSamleNew> {
final getListController = Get.put(GetListController());
late List<ListItem>? listItem=getListController.getListClient!.data!.listItem;
</code></pre>
<p>@override
Widget build(BuildContext context) {</p>
<pre><code>return Scaffold(
body: GetBuilder<GetListController>(
builder: (_) => getListController.isLoading
? const Padding(
padding: EdgeInsets.only(top:50),
child: Center(child: CircularProgressIndicator()),
): DataTable(columns: [
DataColumn(label: Text("1")),
DataColumn(label: Text("1")),
DataColumn(label: Text("1")),
DataColumn(label: Text("1")),
DataColumn(label: Text("1"))
],rows: listItem!.map<DataRow>((e) => DataRow(cells: [
DataCell(Text(e.itemInfo!.clientMobile.toString())),
DataCell(Text(e.itemId.toString())),
DataCell(Text(e.itemId.toString())),
DataCell(Text("")),
DataCell(Text("")),
])).toList()),
),
);
</code></pre>
<p>}
}</p>
<p>this is my main table and not showing data..
table with paginated and sort data and search with one field in table but output showing me null</p>
<pre><code> class DataTableWithSortTest extends StatefulWidget {
const DataTableWithSortTest({Key? key, required this.title}) : super(key: key);
final String title;
@override
State<DataTableWithSortTest> createState() => _DataTableWithSortTestState();
}
class _DataTableWithSortTestState extends State<DataTableWithSortTest> {
final getListController = Get.put(GetListController());
late List<ListItem>? listItem=getListController.getListClient!.data!.listItem;
bool sort = true;
onsortColum(int columnIndex, bool ascending) {
if (columnIndex == 0) {
if (ascending) {
listItem!.sort((a, b) => a.itemStatus!.compareTo(b.itemStatus!));
} else {
listItem!.sort((a, b) => b.itemStatus!.compareTo(a.itemStatus!));
}
}
}
@override
void initState() {
listItem = listItem!.cast<ListItem>();
super.initState();
}
TextEditingController controller = TextEditingController();
@override
Widget build(BuildContext context) {
print(listItem);
return Directionality(
textDirection: TextDirection.rtl,
child: Scaffold(
body: SingleChildScrollView(
child: Container(
padding: const EdgeInsets.all(8.0),
decoration: BoxDecoration(
color: Theme.of(context).canvasColor,
borderRadius: const BorderRadius.all(Radius.circular(10)),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
SizedBox(
width: double.infinity,
child: Theme(
data: ThemeData.light()
.copyWith(cardColor: Theme.of(context).canvasColor),
child: PaginatedDataTable(
sortColumnIndex: 0,
sortAscending: sort,
header: Container(
padding: const EdgeInsets.all(5),
decoration: BoxDecoration(
border: Border.all(
color: Colors.grey,
),
borderRadius: BorderRadius.circular(12)),
child: TextField(
controller: controller,
decoration: const InputDecoration(
hintText: "search with name"),
onChanged: (value) {
setState(() {
listItem = listItem!
.where((element) =>
element.itemStatus!.contains(value))
.toList();
});
},
),
),
source: RowSource(
listItem: listItem,
count: listItem?.length,
),
rowsPerPage: 5,
columnSpacing: 5,
columns: [
DataColumn(
label: const Text(
"1",
style: TextStyle(
fontWeight: FontWeight.w600, fontSize: 14),
),
onSort: (columnIndex, ascending) {
setState(() {
sort = !sort;
});
// onsortColum(columnIndex, ascending);
}),
const DataColumn(//
label: Text(
"2",
style: TextStyle(
fontWeight: FontWeight.w600, fontSize: 14),
),
),
const DataColumn(
label: Text(
"3",
style: TextStyle(
fontWeight: FontWeight.w600, fontSize: 14),
),
),
const DataColumn(
label: Text(
"4",
style: TextStyle(
fontWeight: FontWeight.w600, fontSize: 14),
),
),
const DataColumn(
label: Text(
"5",
style: TextStyle(
fontWeight: FontWeight.w600, fontSize: 14),
),
),
],
),
)),
const SizedBox(height: 20),
],
),
),
)),
);
}
}
class RowSource extends DataTableSource {
var listItem;
final count;
RowSource({
required this.listItem,
required this.count,
});
@override
DataRow? getRow(int index) {
if (index < rowCount) {
return recentFileDataRow(listItem![index]);
} else
return null;
}
@override
bool get isRowCountApproximate => false;
@override
int get rowCount => count;
@override
int get selectedRowCount => 0;
}
DataRow recentFileDataRow(var listItem) {
return const DataRow(
cells: [
DataCell(Text("")),
DataCell(Text("")),
DataCell(Text("")),
DataCell(Text("")),
DataCell(Text("")),
],
);
}
</code></pre>
|
[
{
"answer_id": 74614210,
"author": "eamirho3ein",
"author_id": 10306997,
"author_profile": "https://Stackoverflow.com/users/10306997",
"pm_score": 2,
"selected": true,
"text": "build late List<ListItem>? listItem =getListController.getListClient!.data!.listItem;\n"
},
{
"answer_id": 74614961,
"author": "Ashot Khachatryan",
"author_id": 12397183,
"author_profile": "https://Stackoverflow.com/users/12397183",
"pm_score": 0,
"selected": false,
"text": "class TableSamleNew extends StatefulWidget {\n const TableSamleNew({Key? key}) : super(key: key);\n\n @override\n State<TableSamleNew> createState() => _TableSamleNewState();\n}\n\nclass _TableSamleNewState extends State<TableSamleNew> {\n final getListController = Get.put(GetListController());\nValueNotifier<List<ListItem>> listItemNotifier = ValueNotifier([]);\n\n @override\n Widget build(BuildContext context) {\n listItemNotifier.value=getListController.getListClient!.data!.listItem;\n\n return Scaffold(\n body: ValueListenableBuilder(\n valueListenable: listItemNotifier, \n builder:(context,List<ListItem> items, child) =>\n DataTable(columns: [\n DataColumn(label: Text(\"1\")),\n DataColumn(label: Text(\"1\")),\n DataColumn(label: Text(\"1\")),\n DataColumn(label: Text(\"1\")),\n DataColumn(label: Text(\"1\"))\n ],rows: items.map<DataRow>((e) => DataRow(cells: [\n DataCell(Text(e.itemId.toString())),\n DataCell(Text(e.itemId.toString())),\n DataCell(Text(e.itemId.toString())),\n DataCell(Text(e.itemId.toString())),\n DataCell(Text(e.itemId.toString())),\n ])).toList()),\n );\n );\n }\n}\n ValueNotifier"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74614112",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10766492/"
] |
74,614,115
|
<p>I have a list of scripts doing their own thing (they are actually Rscripts reading modifying and writing files) like this:</p>
<pre><code>## Script 1
echo "1" > file1.out
## Script 2
echo "2" > file2.out
## Script 3
echo "3" > file3.out
</code></pre>
<p>These are saved in different scripts as follow:</p>
<pre><code>## Writing script 1
echo "echo \"1\" > file1.out" > script1.task
## Writing script 2
echo "echo \"2\" > file2.out" > script2.task
## Writing script 3
echo "echo \"3\" > file3.out" > script3.task
</code></pre>
<p><strong>Is there a way to run all these scripts in parallel using the file names?</strong>
In a loop it'd look like this:</p>
<pre><code>for task_file in *.task
do
sh ${task_file}
done
</code></pre>
|
[
{
"answer_id": 74615131,
"author": "Thomas Guillerme",
"author_id": 9281298,
"author_profile": "https://Stackoverflow.com/users/9281298",
"pm_score": 1,
"selected": true,
"text": "& for task_file in *.task\ndo\n sh ${task_file} &\ndone\nwait\n"
},
{
"answer_id": 74649425,
"author": "Ole Tange",
"author_id": 363028,
"author_profile": "https://Stackoverflow.com/users/363028",
"pm_score": 1,
"selected": false,
"text": "seq 10000 | parallel 'echo {} > file{}.out'\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74614115",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9281298/"
] |
74,614,162
|
<p>I am trying to extract the colour (Farve) from this text string.
I can't seem to make the extraction either stop, or start the right place.
Also, the length of the target extraction will vary, as colours of course are varying length name.
The picture is of the target texted, wanted in the cell.</p>
<p>Hope some might be able to help, thank you.
<img src="https://i.stack.imgur.com/B8wRR.png" alt="enter image description here" /></p>
<p>I have tried multiple solutions of Len, left, right combination as well as trim, index combination and regexetraxt.</p>
|
[
{
"answer_id": 74615131,
"author": "Thomas Guillerme",
"author_id": 9281298,
"author_profile": "https://Stackoverflow.com/users/9281298",
"pm_score": 1,
"selected": true,
"text": "& for task_file in *.task\ndo\n sh ${task_file} &\ndone\nwait\n"
},
{
"answer_id": 74649425,
"author": "Ole Tange",
"author_id": 363028,
"author_profile": "https://Stackoverflow.com/users/363028",
"pm_score": 1,
"selected": false,
"text": "seq 10000 | parallel 'echo {} > file{}.out'\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74614162",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20633242/"
] |
74,614,170
|
<p>My professor wants us to submit our project for our node.js app but we are not allowed to include node_modules in the submission.</p>
<p>When I try to run the app without the folder in there, it crashes due to missing dependencies.</p>
<p>Am i missing a step?</p>
|
[
{
"answer_id": 74614194,
"author": "AKX",
"author_id": 51685,
"author_profile": "https://Stackoverflow.com/users/51685",
"pm_score": 1,
"selected": false,
"text": "node_modules package.json npm i yarn"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74614170",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20316876/"
] |
74,614,225
|
<p>Given the following data:</p>
<pre><code>┌─id────────────┬──────────created_at─┬─state─┐
│ 1234567890123 │ 2022-11-26 22:58:28 │ 0 │
│ 1234567890123 │ 2022-11-26 22:57:00 │ 0 │
│ 1234567890123 │ 2022-11-26 22:50:38 │ 0 │
│ 1234567890123 │ 2022-11-26 22:41:46 │ 0 │
│ 1234567890123 │ 2022-11-26 22:37:08 │ 0 │
│ 1234567890123 │ 2022-11-26 22:28:09 │ 0 │
│ 1234567890123 │ 2022-11-26 22:28:09 │ 0 │
│ 1234567890123 │ 2022-11-26 22:25:13 │ 0 │
│ 1234567890123 │ 2022-11-26 22:21:25 │ 0 │
│ 1234567890123 │ 2022-11-26 22:15:43 │ 0 │
│ 1234567890123 │ 2022-11-26 22:03:41 │ 0 │
│ 1234567890123 │ 2022-11-26 21:28:39 │ 1 │
│ 1234567890123 │ 2022-11-26 21:28:39 │ 1 │
│ 1234567890123 │ 2022-11-26 21:08:03 │ 1 │
│ 1234567890123 │ 2022-11-26 21:08:03 │ 1 │
│ 1234567890123 │ 2022-11-26 20:03:45 │ 1 │
│ 1234567890123 │ 2022-11-26 20:03:45 │ 1 │
│ 1234567890123 │ 2022-11-26 20:02:34 │ 0 │
│ 1234567890123 │ 2022-11-26 20:00:58 │ 0 │
│ 1234567890123 │ 2022-11-26 19:58:26 │ 0 │
│ 1234567890123 │ 2022-11-26 19:56:53 │ 0 │
│ 1234567890123 │ 2022-11-26 19:55:29 │ 0 │
│ 1234567890123 │ 2022-11-26 19:51:41 │ 0 │
│ 1234567890123 │ 2022-11-26 19:51:41 │ 0 │
│ 1234567890123 │ 2022-11-26 19:26:19 │ 1 │
│ 1234567890123 │ 2022-11-26 19:26:19 │ 1 │
│ 1234567890123 │ 2022-11-26 16:06:16 │ 1 │
│ 1234567890123 │ 2022-11-26 16:06:16 │ 1 │
│ 1234567890123 │ 2022-11-26 15:34:28 │ 0 │
│ 1234567890123 │ 2022-11-26 15:27:46 │ 0 │
└───────────────┴─────────────────────┴───────┘
</code></pre>
<p>I need to group the data in a way that the created_at of the first <code>true</code> state is grouped to the first <code>false</code> state. The end result should be:</p>
<pre><code>┌─id────────────┬───────────────start─┬─────────────────end─┐
│ 1234567890123 │ 2022-11-26 16:06:16 │ 2022-11-26 19:51:41 │
│ 1234567890123 │ 2022-11-26 20:03:45 │ 2022-11-26 22:03:41 │
└───────────────┴─────────────────────┴─────────────────────┘
</code></pre>
<p>Given that, I need a way to have the data filtered in this way:</p>
<pre><code>┌─id────────────┬──────────created_at─┬─state─┐
│ 1234567890123 │ 2022-11-26 22:03:41 │ 0 │
│ 1234567890123 │ 2022-11-26 20:03:45 │ 1 │
│ 1234567890123 │ 2022-11-26 19:51:41 │ 0 │
│ 1234567890123 │ 2022-11-26 16:06:16 │ 1 │
└───────────────┴─────────────────────┴───────┘
</code></pre>
<p>So I can then apply a LEAD/LAG window function and group the values.</p>
<p>But I cannot find a way to group the data in that way.</p>
<p>I've tried several combinations of LEAD/LAG, RANK, but I could not find a way that would match the first of every event instead of the last. (First time it goes TRUE, then the following first FALSE...)</p>
<p>This is the closest I could get, but the results are wrong:</p>
<pre><code>WITH states AS (
SELECT '1234567890123' AS id, toDateTime('2022-11-26 22:58:28') AS created_at, 0 AS state UNION ALL
SELECT '1234567890123' AS id, toDateTime('2022-11-26 22:57:00') AS created_at, 0 AS state UNION ALL
SELECT '1234567890123' AS id, toDateTime('2022-11-26 22:50:38') AS created_at, 0 AS state UNION ALL
SELECT '1234567890123' AS id, toDateTime('2022-11-26 22:41:46') AS created_at, 0 AS state UNION ALL
SELECT '1234567890123' AS id, toDateTime('2022-11-26 22:37:08') AS created_at, 0 AS state UNION ALL
SELECT '1234567890123' AS id, toDateTime('2022-11-26 22:28:09') AS created_at, 0 AS state UNION ALL
SELECT '1234567890123' AS id, toDateTime('2022-11-26 22:28:09') AS created_at, 0 AS state UNION ALL
SELECT '1234567890123' AS id, toDateTime('2022-11-26 22:25:13') AS created_at, 0 AS state UNION ALL
SELECT '1234567890123' AS id, toDateTime('2022-11-26 22:21:25') AS created_at, 0 AS state UNION ALL
SELECT '1234567890123' AS id, toDateTime('2022-11-26 22:15:43') AS created_at, 0 AS state UNION ALL
SELECT '1234567890123' AS id, toDateTime('2022-11-26 22:03:41') AS created_at, 0 AS state UNION ALL
SELECT '1234567890123' AS id, toDateTime('2022-11-26 21:28:39') AS created_at, 1 AS state UNION ALL
SELECT '1234567890123' AS id, toDateTime('2022-11-26 21:28:39') AS created_at, 1 AS state UNION ALL
SELECT '1234567890123' AS id, toDateTime('2022-11-26 21:08:03') AS created_at, 1 AS state UNION ALL
SELECT '1234567890123' AS id, toDateTime('2022-11-26 21:08:03') AS created_at, 1 AS state UNION ALL
SELECT '1234567890123' AS id, toDateTime('2022-11-26 20:03:45') AS created_at, 1 AS state UNION ALL
SELECT '1234567890123' AS id, toDateTime('2022-11-26 20:03:45') AS created_at, 1 AS state UNION ALL
SELECT '1234567890123' AS id, toDateTime('2022-11-26 20:02:34') AS created_at, 0 AS state UNION ALL
SELECT '1234567890123' AS id, toDateTime('2022-11-26 20:00:58') AS created_at, 0 AS state UNION ALL
SELECT '1234567890123' AS id, toDateTime('2022-11-26 19:58:26') AS created_at, 0 AS state UNION ALL
SELECT '1234567890123' AS id, toDateTime('2022-11-26 19:56:53') AS created_at, 0 AS state UNION ALL
SELECT '1234567890123' AS id, toDateTime('2022-11-26 19:55:29') AS created_at, 0 AS state UNION ALL
SELECT '1234567890123' AS id, toDateTime('2022-11-26 19:51:41') AS created_at, 0 AS state UNION ALL
SELECT '1234567890123' AS id, toDateTime('2022-11-26 19:51:41') AS created_at, 0 AS state UNION ALL
SELECT '1234567890123' AS id, toDateTime('2022-11-26 19:26:19') AS created_at, 1 AS state UNION ALL
SELECT '1234567890123' AS id, toDateTime('2022-11-26 19:26:19') AS created_at, 1 AS state UNION ALL
SELECT '1234567890123' AS id, toDateTime('2022-11-26 16:06:16') AS created_at, 1 AS state UNION ALL
SELECT '1234567890123' AS id, toDateTime('2022-11-26 16:06:16') AS created_at, 1 AS state UNION ALL
SELECT '1234567890123' AS id, toDateTime('2022-11-26 15:34:28') AS created_at, 0 AS state UNION ALL
SELECT '1234567890123' AS id, toDateTime('2022-11-26 15:27:46') AS created_at, 0 AS state
)
SELECT
id,
created_at,
state,
next.1 AS next_created_at,
next.2 AS next_state
FROM (
SELECT
id,
created_at,
state,
any((created_at, state)) OVER (PARTITION BY id ORDER BY created_at ASC ROWS BETWEEN 1 FOLLOWING AND 1 FOLLOWING) AS next
FROM states
ORDER BY created_at DESC
)
WHERE
state = 1
AND next_state = 0
</code></pre>
<p>And the result of that query:</p>
<pre><code>┌─id────────────┬──────────created_at─┬─state─┬─────next_created_at─┬─next_state─┐
│ 1234567890123 │ 2022-11-26 21:28:39 │ 1 │ 2022-11-26 22:03:41 │ 0 │
│ 1234567890123 │ 2022-11-26 19:26:19 │ 1 │ 2022-11-26 19:51:41 │ 0 │
└───────────────┴─────────────────────┴───────┴─────────────────────┴────────────┘
</code></pre>
|
[
{
"answer_id": 74614194,
"author": "AKX",
"author_id": 51685,
"author_profile": "https://Stackoverflow.com/users/51685",
"pm_score": 1,
"selected": false,
"text": "node_modules package.json npm i yarn"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74614225",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1151683/"
] |
74,614,246
|
<p>From a Google Codelab (can't remember which one), they adviced doing the following for fragments:</p>
<pre><code>class MyFragment : Fragment() {
private var _binding: MyFragmentBinding? = null
private val binding get() = _binding!!
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?
): View {
_binding = MyFragmentBinding.inflate(inflater, container, false)
return binding.root
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
}
</code></pre>
<p>And then accessing the views with e.g. <code>binding.button1</code>.</p>
<p>Is there a specific reason for doing it like this, with <em>_binding</em> and <em>binding</em>? Are there better methods? Perhaps an extension for Fragments - like a BaseFragment - to avoid code duplication.</p>
|
[
{
"answer_id": 74614405,
"author": "MoCoding",
"author_id": 11617754,
"author_profile": "https://Stackoverflow.com/users/11617754",
"pm_score": 2,
"selected": false,
"text": "private var binding: MyFragmentBinding? = null\n binding = MyFragmentBinding.inflate(inflater, container, false)\nbinding?.root\n binding?.button...\nbinding?.text...\nbinding?.cardView...\n binding = null\n onCreateView onDestroyView _binding binding private var _binding: MyFragmentBinding? = null\nprivate val binding get() = _binding!!\n _binding binding binding _binding !! _binding binding ?"
},
{
"answer_id": 74615232,
"author": "Tenfour04",
"author_id": 506796,
"author_profile": "https://Stackoverflow.com/users/506796",
"pm_score": 2,
"selected": true,
"text": "class FirstFragment: Fragment(R.layout.first_fragment) {\n private val binding by viewBinding(FirstFragmentBinding::bind)\n\n override fun onViewCreated(view: View, bundle: Bundle?) {\n super.onViewCreated(view, bundle)\n\n binding.buttonPressMe.onClick {\n showToast(\"Hello binding!\")\n }\n }\n"
},
{
"answer_id": 74619674,
"author": "shko",
"author_id": 14969444,
"author_profile": "https://Stackoverflow.com/users/14969444",
"pm_score": 0,
"selected": false,
"text": "abstract class ViewBindingFragment<Binding : ViewBinding>(\n private val bindingInflater: (LayoutInflater, ViewGroup?, Boolean) -> Binding\n) : Fragment() {\n private var binding: Binding? = null\n\n override fun onCreateView(\n inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?\n ): View {\n return bindingInflater(inflater, container, false).apply { binding = this }.root\n }\n\n override fun onDestroyView() {\n binding = null\n\n super.onDestroyView()\n }\n\n protected fun requireBinding(): Binding = binding\n ?: throw IllegalStateException(\"You used the binding before onCreateView() or after onDestroyView()\")\n\n protected fun useBinding(bindingUse: (Binding) -> Unit) {\n bindingUse(requireBinding())\n }\n}\n class ListFragment :\n ViewBindingFragment<TodoRosterBinding>(TodoRosterBinding::inflate) {\n\n override fun onViewCreated(view: View, savedInstanceState: Bundle?) {\n super.onViewCreated(view, savedInstanceState)\n\n useBinding { binding ->\n binding.items.layoutManager = LinearLayoutManager(context)\n }\n }\n}\n useBinding { binding -> }"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74614246",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14969444/"
] |
74,614,253
|
<p>I have a list with 72 bounding boxes. This is the dput (just 5 of them).</p>
<pre><code>list(`1` = c(V1 = 7.426758, V2 = 47.398349, V3 = 7.8508356, V4 = 47.686178
), `10` = c(V1 = 7.8508356, V2 = 47.686178, V3 = 8.2749132, V4 = 47.974007
), `11` = c(V1 = 8.2749132, V2 = 47.686178, V3 = 8.6989908, V4 = 47.974007
), `12` = c(V1 = 8.6989908, V2 = 47.686178, V3 = 9.1230684, V4 = 47.974007
), `13` = c(V1 = 9.1230684, V2 = 47.686178, V3 = 9.547146, V4 = 47.974007
))
</code></pre>
<p>and this is the desired output:</p>
<pre><code>c(7.4267580,47.3983490,7.8508356,47.6861780)
</code></pre>
<p>How can I print each bounding box in the desired output using a for loop?</p>
|
[
{
"answer_id": 74614519,
"author": "shaun_m",
"author_id": 18289387,
"author_profile": "https://Stackoverflow.com/users/18289387",
"pm_score": 0,
"selected": false,
"text": "have <- list(`1` = c(V1 = 7.426758, V2 = 47.398349, V3 = 7.8508356, V4 = 47.686178\n), `10` = c(V1 = 7.8508356, V2 = 47.686178, V3 = 8.2749132, V4 = 47.974007\n), `11` = c(V1 = 8.2749132, V2 = 47.686178, V3 = 8.6989908, V4 = 47.974007\n), `12` = c(V1 = 8.6989908, V2 = 47.686178, V3 = 9.1230684, V4 = 47.974007\n), `13` = c(V1 = 9.1230684, V2 = 47.686178, V3 = 9.547146, V4 = 47.974007\n))\n\nfor (item in have) {dput(unname(item))}\n"
},
{
"answer_id": 74615570,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 2,
"selected": true,
"text": "dput(lapply(your_list, unname))\n toString toString toString(1 : 5)\n# [1] \"1, 2, 3, 4, 5\"\n c(…) paste0('c(', toString(1 : 5), ')')\n# [1] \"c(1, 2, 3, 4, 5)\"\n vapply result = vapply(your_list, \\(x) paste0('c(', toString(x), ')'), character(1L))\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74614253",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17431143/"
] |
74,614,285
|
<p>What I want to implement is like this style. Pls see the picture below.
<a href="https://i.stack.imgur.com/dXy9B.png" rel="nofollow noreferrer">Need show</a></p>
<p>The border is gradient, start color is</p>
<pre><code>#08FFFB
</code></pre>
<p>and the end color is</p>
<pre><code>#FF4EEC
</code></pre>
<p>.And the background which like black is also gradient which start color is</p>
<pre><code>#3A3A3A
</code></pre>
<p>and the end color is</p>
<pre><code>#0B0B0B
</code></pre>
<p>The corner radius is 16.</p>
<p>I want to use it as a custom indicator in TabBar component. So, I custom the</p>
<pre><code>indicator
</code></pre>
<p>like this.</p>
<pre><code>
@override
Widget build(BuildContext context) {
List\<String\> list = \["全部","读书","电影", "小说"\];
return Padding(
padding: EdgeInsets.fromLTRB(15, 0, 15, 0),
child: Container(
width: double.infinity,
height: 62,
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.all(Radius.circular(20))),
child: Padding(
padding: EdgeInsets.fromLTRB(25, 13, 25, 13),
child: TabBar(
labelColor: Colors.white,
unselectedLabelColor: YYSColors.yysTextColor(),
isScrollable: true,
indicator: new BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
colors: \<Color\>\[
Color(int.parse("FF3A3A3A", radix: 16)),
Color(int.parse("FF2B2B2B", radix: 16))
\],
),
borderRadius: BorderRadius.circular(16),
border: new Border.all(
color: Color(int.parse("FF08FFFB", radix: 16)), width: 2),
),
tabs: list
.map((String arenaType) {
return Tab(text: arenaType);
}).toList(),
),
),
),
),
);
}
</code></pre>
<p>I have tried to use image in BoxDecoration but it is not work. And I also get some informations from internet that maybe I can use a custom Widget extends Decoration, but I need to override paint() method. It is too difficulty to me. So I came here to ask for help. Thanks a lot.</p>
<p>It is my frist question at here. So the format is not that good. Pls forgive me.</p>
|
[
{
"answer_id": 74614519,
"author": "shaun_m",
"author_id": 18289387,
"author_profile": "https://Stackoverflow.com/users/18289387",
"pm_score": 0,
"selected": false,
"text": "have <- list(`1` = c(V1 = 7.426758, V2 = 47.398349, V3 = 7.8508356, V4 = 47.686178\n), `10` = c(V1 = 7.8508356, V2 = 47.686178, V3 = 8.2749132, V4 = 47.974007\n), `11` = c(V1 = 8.2749132, V2 = 47.686178, V3 = 8.6989908, V4 = 47.974007\n), `12` = c(V1 = 8.6989908, V2 = 47.686178, V3 = 9.1230684, V4 = 47.974007\n), `13` = c(V1 = 9.1230684, V2 = 47.686178, V3 = 9.547146, V4 = 47.974007\n))\n\nfor (item in have) {dput(unname(item))}\n"
},
{
"answer_id": 74615570,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 2,
"selected": true,
"text": "dput(lapply(your_list, unname))\n toString toString toString(1 : 5)\n# [1] \"1, 2, 3, 4, 5\"\n c(…) paste0('c(', toString(1 : 5), ')')\n# [1] \"c(1, 2, 3, 4, 5)\"\n vapply result = vapply(your_list, \\(x) paste0('c(', toString(x), ')'), character(1L))\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74614285",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20631548/"
] |
74,614,354
|
<p>I have a simple map as below</p>
<pre><code>val myMap = Map("A" -> "AB300","B" -> "XI134","C" -> null)
</code></pre>
<p>I would like to validate the length of a particular key and would like to return the value as string (and not as <code>Option</code> . I tried the following</p>
<pre><code>myMap.getOrElse("A",null).toString.length
val res50: Int = 5
</code></pre>
<p>This works fine. But obviously, doesn't handle for null data</p>
<pre><code>myMap.getOrElse("C",null).toString.length
//Null pointer Exception
</code></pre>
<p>Is there a way to handle null too? The expectation is length for a null value should return zero (may be replacing null with space or something)</p>
|
[
{
"answer_id": 74614493,
"author": "AminMal",
"author_id": 14672383,
"author_profile": "https://Stackoverflow.com/users/14672383",
"pm_score": 1,
"selected": false,
"text": "null Option myMap.get(\"C\")\n .flatMap(Option.apply) // since some values are null in your map\n .fold(ifEmpty = 0)(s => s.length)\n"
},
{
"answer_id": 74617382,
"author": "Eastsun",
"author_id": 172677,
"author_profile": "https://Stackoverflow.com/users/172677",
"pm_score": 0,
"selected": false,
"text": "util.Try(myMap(\"D\").length).getOrElse(0)\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74614354",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6698715/"
] |
74,614,369
|
<p>Using a fresh Spring Initialzr with Java17 and Spring Boot 3.0.0, and an extra addition to the pom.xml for Springfox Swagger 3, I can't for the life of me get Swagger pages to work. Instead, I get the whitelabel error page with 404.</p>
<p>Pom.xml</p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.0.0</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>demo</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>17</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-boot-starter</artifactId>
<version>3.0.0</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
</code></pre>
<p>The standard Swagger URLs as defined in this <a href="https://github.com/springfox/springfox/issues/3441" rel="nofollow noreferrer">Github Issues page</a> aren't working for the above pom.xml project.</p>
|
[
{
"answer_id": 74614493,
"author": "AminMal",
"author_id": 14672383,
"author_profile": "https://Stackoverflow.com/users/14672383",
"pm_score": 1,
"selected": false,
"text": "null Option myMap.get(\"C\")\n .flatMap(Option.apply) // since some values are null in your map\n .fold(ifEmpty = 0)(s => s.length)\n"
},
{
"answer_id": 74617382,
"author": "Eastsun",
"author_id": 172677,
"author_profile": "https://Stackoverflow.com/users/172677",
"pm_score": 0,
"selected": false,
"text": "util.Try(myMap(\"D\").length).getOrElse(0)\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74614369",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5248498/"
] |
74,614,372
|
<p>I have a hard drive with thousands of images from a camera-trap proyect. I've used a software that detects in which photos there is an animal. From that I've got a .csv with one column per photo "tagged" with the full directory of each photo</p>
<pre><code>| Column A |
| -------- |
| E:\Imagenes\2-1\VK1050_01\VK1050_01_1\**MFDC0421.JPG** |
| E:\Imagenes\2-1\VK1050_01\VK1050_01_1\MFDC0422.JPG |
.....
| E:\Imagenes\2-1\UJ8090_01\UJ8090_01_1\**MFDC0421.JPG** |
</code></pre>
<p>The source hard drive have several folders and subfolders (season, site, etc), that I would like to keep (but with only the tagged fotos from the list inside)
Note that as the photos come from diferent cameras the photos names are the same sometimes, but in different folders.</p>
<p>For that I'm using the following code in R:</p>
<pre><code>tagged_img <- read.csv(file.path(dir, "images_filtered.csv"), header = TRUE, sep = ";")
from <- tagged_img$file_path
to <- "E:/"
</code></pre>
<p>file.copy(from, to, recursive=TRUE, copy.date=TRUE)</p>
<p>The code runs and the list "from" contains every image i want to copy) but the copy I get has no folders or subfolders, and only 20000 photos out of 150000 are copied. I've noticed that the copied photos have unique names: e.g. there's only one IMG0001.jpg whereas in the .csv file with the list I have several photos named IMG0001.jpg</p>
<p>Any way to fix these and keep the folders and copy all the files?
Thanks!</p>
|
[
{
"answer_id": 74614493,
"author": "AminMal",
"author_id": 14672383,
"author_profile": "https://Stackoverflow.com/users/14672383",
"pm_score": 1,
"selected": false,
"text": "null Option myMap.get(\"C\")\n .flatMap(Option.apply) // since some values are null in your map\n .fold(ifEmpty = 0)(s => s.length)\n"
},
{
"answer_id": 74617382,
"author": "Eastsun",
"author_id": 172677,
"author_profile": "https://Stackoverflow.com/users/172677",
"pm_score": 0,
"selected": false,
"text": "util.Try(myMap(\"D\").length).getOrElse(0)\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74614372",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20633320/"
] |
74,614,381
|
<p>So I'm running an app with nodejs + express, and trying to connect to the prismic API. keep getting " '[Link resolver error] Unknown type\n' ", I understand from the message it's something about my routes but I'm unsure how to fix it</p>
<p><strong>prismic config</strong></p>
<pre><code>require('dotenv').config()
const fetch = require('node-fetch')
const prismic = require('@prismicio/client')
const repoName = process.env.PRISMIC_REPO_NAME
const accessToken = process.env.PRISMIC_ACCESS_TOKEN
const endpoint = prismic.getEndpoint(repoName)
const routes = [
{
type: 'page',
path: '/'
}
]
module.exports.client = prismic.createClient(endpoint, {
fetch,
accessToken,
routes
})
</code></pre>
<p>app.js</p>
<pre><code>require('dotenv').config()
const path = require('path')
const express = require('express')
const prismicH = require('@prismicio/helpers')
const { client } = require('./config/prismicConfig.js')
const app = express()
const port = process.env.PORT || 3000
// template engine
app.set('views', path.join(__dirname, 'views'))
app.set('view engine', 'pug')
// middleware
app.use((req, res, next) => {
res.locals.ctx = {
prismicH
}
next()
})
app.get('/', async (req, res) => {
const document = await client.getFirst()
res.render('page', { document })
})
app.get('/about', (req, res) => {
res.render('pages/about')
})
app.get('/collections', (req, res) => {
res.render('pages/collections')
})
app.listen(port, () => {
console.log(`Example app listening on port ${port}`)
})
</code></pre>
<p><strong>prismic documents</strong>
<a href="https://i.stack.imgur.com/sNQaE.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/sNQaE.png" alt="prismic documents" /></a></p>
<p><strong>folder structure</strong></p>
<p><a href="https://i.stack.imgur.com/EriNi.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/EriNi.png" alt="folder structure" /></a></p>
<p>Edit: i fixed the issue
the issue was I was trying to render page, instead of pages/home</p>
<pre><code>app.get('/', async (req, res) => {
const document = await client.getFirst()
res.render('page', { document })
})
</code></pre>
<p>so i just edited the res.render to :</p>
<pre><code>res.render('pages/home', { document })
</code></pre>
|
[
{
"answer_id": 74614493,
"author": "AminMal",
"author_id": 14672383,
"author_profile": "https://Stackoverflow.com/users/14672383",
"pm_score": 1,
"selected": false,
"text": "null Option myMap.get(\"C\")\n .flatMap(Option.apply) // since some values are null in your map\n .fold(ifEmpty = 0)(s => s.length)\n"
},
{
"answer_id": 74617382,
"author": "Eastsun",
"author_id": 172677,
"author_profile": "https://Stackoverflow.com/users/172677",
"pm_score": 0,
"selected": false,
"text": "util.Try(myMap(\"D\").length).getOrElse(0)\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74614381",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10474914/"
] |
74,614,393
|
<p>I am using a code for a query, sometimes the input goes and there is no return (basically it does not find anything so the return is an empty row) so it is empty. However, when I use <code>pd.concat</code>, those empty rows disappear. Is there a way to keep these no return rows in the loop as well so that when I use that I can have empty rows on the final <code>output.csv</code>?</p>
<pre class="lang-py prettyprint-override"><code>import numpy as np
import pandas as pd
from dl import authClient as ac, queryClient as qc
from dl.helpers.utils import convert
import openpyxl as xl
wb = xl.load_workbook('/Users/somethingfile.xlsx')
sheet = wb['Sheet 1']
df = pd.DataFrame([],columns = ['col1','col2',...,'coln'])
for row in range(3, sheet.max_row + 1):
a0, b0, r = sheet.cell(row,1).value, sheet.cell(row,2).value, 0.001
query = """
SELECT a,b,c,d,e FROM smthng
WHERE q3c_radial_query(a,b,{:f},{:f},{:f}) LIMIT 1
""".format(a0,b0,r)
response = qc.query(sql=query,format='csv')
temp_df = convert(response,'pandas')
df = pd.concat([df,temp_df])
df.to_csv('output.csv')
</code></pre>
|
[
{
"answer_id": 74614493,
"author": "AminMal",
"author_id": 14672383,
"author_profile": "https://Stackoverflow.com/users/14672383",
"pm_score": 1,
"selected": false,
"text": "null Option myMap.get(\"C\")\n .flatMap(Option.apply) // since some values are null in your map\n .fold(ifEmpty = 0)(s => s.length)\n"
},
{
"answer_id": 74617382,
"author": "Eastsun",
"author_id": 172677,
"author_profile": "https://Stackoverflow.com/users/172677",
"pm_score": 0,
"selected": false,
"text": "util.Try(myMap(\"D\").length).getOrElse(0)\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74614393",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6023415/"
] |
74,614,394
|
<p>When I check the official Tailwind CSS documentation, it says that</p>
<blockquote>
<p>Use w-screen to make an element span the entire width of the viewport.</p>
</blockquote>
<p>I mean, w-screen is ok when I try to implement</p>
<pre><code>width: 100vw;
</code></pre>
<p>But what should I do when I try to implement</p>
<pre><code>width: 90vw;
height: 90vh;
</code></pre>
|
[
{
"answer_id": 74614659,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "w-90\nh-90\n"
},
{
"answer_id": 74615709,
"author": "Nathan Dawson",
"author_id": 1310929,
"author_profile": "https://Stackoverflow.com/users/1310929",
"pm_score": 3,
"selected": true,
"text": "90vw <div class=\"w-[90vw] h-[90vh]\"></div>\n // tailwind.config.js\nmodule.exports = {\n theme: {\n extend: {\n height: {\n 'screen/90': '90vh',\n },\n width: {\n 'screen/90': '90vw',\n }\n }\n }\n}\n <div class=\"w-screen/90 h-screen/90\"></div>\n"
},
{
"answer_id": 74620016,
"author": "Ihar Aliakseyenka",
"author_id": 14305076,
"author_profile": "https://Stackoverflow.com/users/14305076",
"pm_score": 1,
"selected": false,
"text": "const plugin = require('tailwindcss/plugin')\n\n// create default values\nconst screenKeys = Array.from({length: 20}, (_, i) => i*5)\nconst screenSizes = screenKeys.reduce((v, key) => Object.assign(v, {[key]: key}), {});\n\nmodule.exports = {\n\n // ...\n\n plugins: [\n plugin(function ({matchUtilities, theme}) {\n matchUtilities(\n {\n 'w-screen': width => ({\n width: `${width}vw`\n })\n },\n { values: Object.assign(screenSizes, theme('screenSize', {})) }\n ),\n matchUtilities(\n {\n 'h-screen': height => ({\n height: `${height}vh`\n })\n },\n { values: Object.assign(screenSizes, theme('screenSize', {})) }\n )\n })\n ],\n}\n w-screen h-screen vw vh w-screen 100vw <div class=\"w-screen h-screen-35\">\n Default width screen is still working\n</div>\n\n<div class=\"w-screen-50 h-screen-[15]\">\n 50vw width, 15vh from JIT\n No need to set h-screen-[15vh] as we already know we're working with vh units\n</div>\n w-screen-90 h-screen-90 screenSize module.exports = {\n theme: {\n extend: {\n screenSize: {\n 33: 33 // just an example\n }\n },\n },\n}\n <div class=\"w-screen-[22] h-screen-33\">\n 33vh from user config, 22vw from JIT\n</div>\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74614394",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13932449/"
] |
74,614,419
|
<p>Suppose you have a table with an user id and date+time (for simplicity in steps of 1 hour)</p>
<p>The table here is ordered by agent and time stamp.</p>
<pre><code>Usr Date Comment
1 2022-11-29 12:00 <- Start of a sequence
1 2022-11-29 13:00
1 2022-11-29 14:00
1 2022-11-30 12:00 <- Start of a sequence
1 2022-11-30 16:00 <- Start of a sequence
2 2022-11-29 22:00 <- Start of a sequence
2 2022-11-29 23:00
2 2022-11-30 00:00 <- Start of a sequence
2 2022-11-30 01:00
3 2022-11-29 13:00 <- Start of a sequence
3 2022-11-29 14:00
3 2022-11-30 12:00 <- Start of a sequence
3 2022-11-30 13:00
3 2022-11-30 14:00
4 2022-11-30 12:00 <- Start of a sequence
4 2022-11-30 13:00
4 2022-11-30 14:00
5 2022-11-30 16:00 <- Start of a sequence
</code></pre>
<ol>
<li>Expected result is the start of a sequence and its length.</li>
<li>For simplicity each gap is 1 hour.</li>
<li>The start of a new day (00:00) always starts a new sequence</li>
</ol>
<pre><code>Usr Date Length
1 2022-11-29 12:00 3
1 2022-11-30 12:00 1
1 2022-11-30 16:00 1
2 2022-11-29 22:00 2
2 2022-11-30 00:00 2
3 2022-11-29 13:00 2
3 2022-11-30 12:00 3
4 2022-11-30 12:00 3
5 2022-11-30 16:00 1
</code></pre>
<p>I found some code samples with <code>dense_rank</code> and <code>row_number</code> but didn't got a result that was expected.</p>
<p>I have a solution running over each record in the source table and and creating the result table, but it is slow.</p>
<p>The query has to run on a SQL 2012 or later.</p>
|
[
{
"answer_id": 74614659,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "w-90\nh-90\n"
},
{
"answer_id": 74615709,
"author": "Nathan Dawson",
"author_id": 1310929,
"author_profile": "https://Stackoverflow.com/users/1310929",
"pm_score": 3,
"selected": true,
"text": "90vw <div class=\"w-[90vw] h-[90vh]\"></div>\n // tailwind.config.js\nmodule.exports = {\n theme: {\n extend: {\n height: {\n 'screen/90': '90vh',\n },\n width: {\n 'screen/90': '90vw',\n }\n }\n }\n}\n <div class=\"w-screen/90 h-screen/90\"></div>\n"
},
{
"answer_id": 74620016,
"author": "Ihar Aliakseyenka",
"author_id": 14305076,
"author_profile": "https://Stackoverflow.com/users/14305076",
"pm_score": 1,
"selected": false,
"text": "const plugin = require('tailwindcss/plugin')\n\n// create default values\nconst screenKeys = Array.from({length: 20}, (_, i) => i*5)\nconst screenSizes = screenKeys.reduce((v, key) => Object.assign(v, {[key]: key}), {});\n\nmodule.exports = {\n\n // ...\n\n plugins: [\n plugin(function ({matchUtilities, theme}) {\n matchUtilities(\n {\n 'w-screen': width => ({\n width: `${width}vw`\n })\n },\n { values: Object.assign(screenSizes, theme('screenSize', {})) }\n ),\n matchUtilities(\n {\n 'h-screen': height => ({\n height: `${height}vh`\n })\n },\n { values: Object.assign(screenSizes, theme('screenSize', {})) }\n )\n })\n ],\n}\n w-screen h-screen vw vh w-screen 100vw <div class=\"w-screen h-screen-35\">\n Default width screen is still working\n</div>\n\n<div class=\"w-screen-50 h-screen-[15]\">\n 50vw width, 15vh from JIT\n No need to set h-screen-[15vh] as we already know we're working with vh units\n</div>\n w-screen-90 h-screen-90 screenSize module.exports = {\n theme: {\n extend: {\n screenSize: {\n 33: 33 // just an example\n }\n },\n },\n}\n <div class=\"w-screen-[22] h-screen-33\">\n 33vh from user config, 22vw from JIT\n</div>\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74614419",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2790621/"
] |
74,614,429
|
<p>I am trying to use tag icon in the html but it's not showing the icon.</p>
<p>This is how I am trying to display the icon but it's not displaying the icon</p>
<pre><code><i class="fas fa-plus"></i>
</code></pre>
<p>But whereas if I use icon like below it's displaying the icon</p>
<pre><code><fa-icon [icon]="['fas','plus']"></fa-icon>
</code></pre>
<p>But I need to display Icon as in the below type in order to do my logics.</p>
<pre><code><i class="fas fa-plus"></i>
</code></pre>
<p>Any Help, Thanks!</p>
|
[
{
"answer_id": 74614522,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<link rel=\"stylesheet\" href=\"https://use.fontawesome.com/releases/v5.7.2/css/all.css\" integrity=\"sha384-fnmOCqbTlWIlj8LyTjo7mOUStjsKC4pOpQbqyi7RrhN7udi9RwhKkMHpvLbHG9Sr\" crossorigin=\"anonymous\"> \n"
},
{
"answer_id": 74616319,
"author": "StackoverBlows",
"author_id": 19979278,
"author_profile": "https://Stackoverflow.com/users/19979278",
"pm_score": 0,
"selected": false,
"text": "<i class=\"fa fa-plus\"></i>\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74614429",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20466032/"
] |
74,614,441
|
<p>I'm trying to install the MySQLdb package for python3, because I need to use mysql for a project I'm currently doing.
But I can't get that package and work with it</p>
<p>I have tried the following things:</p>
<p>When I try to import it, I get this error:</p>
<pre><code>python3 Get_Acess_and_Refresh_Tokens.py
Traceback (most recent call last):
File "/home/*****/Desktop/*****/Get_Acess_and_Refresh_Tokens.py", line 6, in <module>
from MySQLdb import _mysql
ModuleNotFoundError: No module named 'MySQLdb'
</code></pre>
<p>When I try to install python-mysqldb I get this message:</p>
<pre><code>~$ sudo apt-get install python-mysqldb
Reading package lists... Done
Building dependency tree... Done
Reading state information... Done
Package python-mysqldb is not available, but is referred to by another package.
This may mean that the package is missing, has been obsoleted, or
is only available from another source
E: Package 'python-mysqldb' has no installation candidate`
</code></pre>
<p>When I try to apt-get update I get this: I have just copied some errors because it detects them as spam</p>
<pre><code>$ sudo apt-get update
Err:2 http://es.archive.ubuntu.com/ubuntu jammy InRelease
Temporary failure resolving 'es.archive.ubuntu.com'
Reading package lists... Done
W: Failed to fetch http://es.archive.ubuntu.com/ubuntu/dists/jammy/InRelease Temporary failure resolving 'es.archive.ubuntu.com'
W: Some index files failed to download. They have been ignored, or old ones used instead.
</code></pre>
<p>Edit: This last part I have solved with this post: <a href="https://askubuntu.com/questions/91543/apt-get-update-fails-to-fetch-files-temporary-failure-resolving-error">https://askubuntu.com/questions/91543/apt-get-update-fails-to-fetch-files-temporary-failure-resolving-error</a>
But the problem continues with the same result</p>
<p>Anyone know what I am doing wrong and any solution/alternative to deal with it?</p>
<p>Thanks in advance</p>
|
[
{
"answer_id": 74614522,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<link rel=\"stylesheet\" href=\"https://use.fontawesome.com/releases/v5.7.2/css/all.css\" integrity=\"sha384-fnmOCqbTlWIlj8LyTjo7mOUStjsKC4pOpQbqyi7RrhN7udi9RwhKkMHpvLbHG9Sr\" crossorigin=\"anonymous\"> \n"
},
{
"answer_id": 74616319,
"author": "StackoverBlows",
"author_id": 19979278,
"author_profile": "https://Stackoverflow.com/users/19979278",
"pm_score": 0,
"selected": false,
"text": "<i class=\"fa fa-plus\"></i>\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74614441",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20346787/"
] |
74,614,481
|
<p>I have a material design table and I wrote custom functions to load the data and extract the objects from the JSON array object.</p>
<p>I have the following code:</p>
<pre><code> public getDocumentList() {
return this.http.get(this.getDocumentUrl, this.httpOptions)
.subscribe(
documentResponse => {
for (let i = 0; i > Object.keys(documentResponse).length; i++){
console.log(Object.keys(documentResponse));
console.log("documentResponse:");
console.log(documentResponse);
console.log(of(documentResponse[i]).pipe(pluck('soap:Envelope', 'soap:Body', 'ns2:getDocumentsResponse', 'return')));
this.documentList$ = of(documentResponse[i]).pipe(pluck('soap:Envelope', 'soap:Body', 'ns2:getDocumentsResponse', 'return'));
this.documentList$.subscribe(x => this.documentListArray.push(x));
console.log("Doklist", this.documentListArray)
}
this.setDokumentStatus();
},
error => {
alert('Following error happened:' + ' ' + error['statusText']);
console.log('There was an error: ', error);
});
}
</code></pre>
<p>The following public function above fills <code>documentListArray</code> with the required objects...</p>
<p>But this semi-random error gets thrown:</p>
<pre><code>ERROR Error: Uncaught (in promise): TypeError: Cannot read properties of undefined (reading 'length')
TypeError: Cannot read properties of undefined (reading 'length')
at WorkDocumentComponent.<anonymous> (work-document.component.ts:139:6
</code></pre>
<p>The last line of this code is where the error happens (before the bracket obviously):</p>
<pre><code>async FillElementDataArray() {
ELEMENT_DATA.length = 0;
this.dataSource.connect().next(ELEMENT_DATA);
let add_WorkDocument = {} as WorkDocument;
console.log(this.DataService.documentListArray);
let docsForMetadata;
// this below is undefined yo
for (let i = 0; i < this.DataService.documentListArray[0].length; i++)
{
</code></pre>
<p>...which is VERY strange.</p>
<p>Is this an async and sync function issue?</p>
<ul>
<li>How do I fix this?</li>
<li>Why is it still undefined and I cannot console.log it? EDIT: I can console.log it IF I put the console.log before the log loop.</li>
</ul>
<p>P.S. my documentResponse looks like this:</p>
<pre><code>[
{
"soap:Envelope": {
"soap:Body": {
"ns2:getDocumentMetaDataResponse": {
"return": {
"items": [
{
"key": "blah",
"values": "blablabla"
and so on...
}
]
</code></pre>
|
[
{
"answer_id": 74644797,
"author": "Erhan Yaşar",
"author_id": 6371094,
"author_profile": "https://Stackoverflow.com/users/6371094",
"pm_score": 2,
"selected": false,
"text": "this.DataService.documentListArray[0] for (let i = 0; i < this.DataService.documentListArray[0]?.length; i++)\n{\n\n}\n"
},
{
"answer_id": 74654688,
"author": "olivarra1",
"author_id": 1026619,
"author_profile": "https://Stackoverflow.com/users/1026619",
"pm_score": 1,
"selected": false,
"text": "FillElementDataArray getDocumentList public getDocumentList() {\n this.documentList$ = this.http.get(this.getDocumentUrl, this.httpOptions).pipe(\n map(documentResponse => {\n // Assuming documentResponse is an array\n return documentResponse.map(\n // RxJS deprecates pluck in favour of just optional chaining\n x => x?.['soap:Envelope']?.['soap:Body']?.['ns2:getDocumentsResponse']?.['return']\n )\n }),\n // Not sure why this call is needed\n tap(() => this.setDokumentStatus())\n )\n}\n lastValueFrom async FillElementDataArray() {\n ELEMENT_DATA.length = 0;\n this.dataSource.connect().next(ELEMENT_DATA);\n\n let add_WorkDocument = {} as WorkDocument;\n const documentListArray = await lastValueFrom(this.DataService.documentList$);\n let docsForMetadata;\n\n // this below is undefined yo\n for (let i = 0; i < documentListArray.length; i++)\n {\n getDocumentList() getDocumentList shareReplay"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74614481",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12360035/"
] |
74,614,494
|
<p>I am trying to create Tabs and have JSX Components dynamically placed into each Tab as content. I am using React and Polaris as I am creating a new Shopify App.</p>
<p>I cannot seem to work out how to do this - I am very new to Javascript/Typescript and even React.</p>
<p>I have all the Tabs working showing the correct details in each, but I cannot pull the child JSX 'DesignForm' and make it show as within the First Tab.</p>
<pre><code>import React, { Children } from "react";
import { Card, Page, Layout, TextContainer, Image, Stack, Link, Heading, Tabs} from "@shopify/polaris";
import {ReactNode, useState, useCallback} from 'react';
import { DesignForm } from "../designform/DesignForm";
export function NavTabs() {
const [selected, setSelected] = useState(0);
interface childrenProps {
children: JSX.Element;
}
const index = ({ children }: childrenProps) => {
return (
<>
<DesignForm />
{children}
</>
);
};
const handleTabChange = useCallback(
(selectedTabIndex) => setSelected(selectedTabIndex),
[],
);
const tabs = [
{
id: 'all-customers-4',
content: 'All',
accessibilityLabel: 'All customers',
panelID: 'all-customers-content-4',
children: DesignForm,
},
{
id: 'accepts-marketing-4',
content: 'Accepts marketing',
panelID: 'accepts-marketing-content-4',
},
{
id: 'repeat-customers-4',
content: 'Repeat customers',
panelID: 'repeat-customers-content-4',
},
{
id: 'prospects-4',
content: 'Prospects',
panelID: 'prospects-content-4',
},
];
return (
<Card>
<Tabs
tabs={tabs}
selected={selected}
onSelect={handleTabChange}
disclosureText="More views"
>
<Card.Section title={tabs[selected].content}>
<p>Tab {selected} selected</p>
</Card.Section>
<Card.Section children={tabs[selected].children}></Card.Section>
</Tabs>
</Card>
);
}
</code></pre>
|
[
{
"answer_id": 74644797,
"author": "Erhan Yaşar",
"author_id": 6371094,
"author_profile": "https://Stackoverflow.com/users/6371094",
"pm_score": 2,
"selected": false,
"text": "this.DataService.documentListArray[0] for (let i = 0; i < this.DataService.documentListArray[0]?.length; i++)\n{\n\n}\n"
},
{
"answer_id": 74654688,
"author": "olivarra1",
"author_id": 1026619,
"author_profile": "https://Stackoverflow.com/users/1026619",
"pm_score": 1,
"selected": false,
"text": "FillElementDataArray getDocumentList public getDocumentList() {\n this.documentList$ = this.http.get(this.getDocumentUrl, this.httpOptions).pipe(\n map(documentResponse => {\n // Assuming documentResponse is an array\n return documentResponse.map(\n // RxJS deprecates pluck in favour of just optional chaining\n x => x?.['soap:Envelope']?.['soap:Body']?.['ns2:getDocumentsResponse']?.['return']\n )\n }),\n // Not sure why this call is needed\n tap(() => this.setDokumentStatus())\n )\n}\n lastValueFrom async FillElementDataArray() {\n ELEMENT_DATA.length = 0;\n this.dataSource.connect().next(ELEMENT_DATA);\n\n let add_WorkDocument = {} as WorkDocument;\n const documentListArray = await lastValueFrom(this.DataService.documentList$);\n let docsForMetadata;\n\n // this below is undefined yo\n for (let i = 0; i < documentListArray.length; i++)\n {\n getDocumentList() getDocumentList shareReplay"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74614494",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20633452/"
] |
74,614,497
|
<h2>Question</h2>
<p>I have a CSR matrix, and I want to be able to retrieve the column indices and the values stored.</p>
<h2>Data</h2>
<p>For different reasons I'm not allowed to share my data, but here's a look (the <code>numpy</code> library is imported as <code>np</code>):</p>
<pre class="lang-py prettyprint-override"><code>print(type(data) == type(ind) == list) # data and ind are lists
# OUT: True
print(len(data) == len(ind) == 134464) # data and ind have a size of 134,464
# OUT: True
print(np.alltrue([type(subarray) == np.ndarray for subarray in data])) # data (and ind) contains ndarray
# OUT: True
print(np.alltrue([len(data[i]) == len(ind[i]) for i in range(len(data))])) # each ndarray of data have the same length than the corresponding ndarray of ind
# OUT: True
print(min([len(data[i]) for i in range(len(data))]) >= 1) # each subarray of data (and of ind) has at least a length of 1
# OUT: True
print(np.alltrue([subarray.dtype == np.float64 for subarray in data])) # each subarray of data (and of ind) contains floats
# OUT: True
</code></pre>
<h2>Code</h2>
<p>Here is how I create the matrix (using <code>csr_matrix</code> from <code>scipy.sparse</code>):</p>
<pre class="lang-py prettyprint-override"><code>indptr = np.empty(nbr_of_rows + 1) # nbr_of_rows = 134,464 = len(data)
indptr[0] = 0
for i in range(1, len(indptr)):
indptr[i] = indptr[i-1] + len(data[i-1])
data = np.concatenate(data) # now I have type(data) = np.darray, data.dtype = np.float64 and len(data) = 2,821,574
ind = np.concatenante(ind) # same than above
X = csr_matrix((data, ind, indptr), shape=(nbr_of_rows, nbr_of_columns)) # nbr_of_columns = 3,991 = max(ind) + 1 (since min(ind) = 0)
print(f"The matrix has a shape of {X.shape} and a sparsity of {(1 - (X.nnz / (X.shape[0] * X.shape[1]))): .2%}.")
# OUT: The matrix has a shape of (134464, 3991) and a sparsity of 99.47%.
</code></pre>
<p>So far so good (at least I think so). But now, even though I manage to retrieve the column indices, I can’t successfully retrieve the values:</p>
<pre class="lang-py prettyprint-override"><code>print(np.alltrue(ind == X.nonzero()[1])) # Retrieving the columns indices
# OUT: True
print(np.alltrue(data == X[X.nonzero()])) # Trying to retrieve the values
# OUT: False
print(np.alltrue(np.sort(data) == np.sort(X[X.nonzero()]))) # Seeing if the values are at least the same
# OUT: False
print(np.sum(data) == np.sum(X[X.nonzero()])) # Seeing if the values add up to the same total
# OUT: False
</code></pre>
<p>When I look deeper, I find that I get <em>almost</em> all the values (only a small amount of mistakes):</p>
<pre class="lang-py prettyprint-override"><code>print(len(data) == len(X[X.nonzero()].tolist()[0]))
# OUT: True
print(len(np.argwhere((data != X[X.nonzero()]))))
# OUT: 2184
</code></pre>
<p>So I get "only" 2,184 wrong values out of 2,821,574 total values.</p>
<p>Can someone please help me in getting all the correct values from my CSR matrix?</p>
<h2>EDIT</h2>
<p>I know now thanks to @hpaulj that I can use the class attributes <code>X.indices</code> and <code>X.data</code> to retrieve the CSR format index array and the CSR format data array of the matrix. However, I still would like to know why, in my case, I don't have <code>np.altrue(X[X.nonzero()] == X.data)</code>.</p>
|
[
{
"answer_id": 74615745,
"author": "radof",
"author_id": 20349343,
"author_profile": "https://Stackoverflow.com/users/20349343",
"pm_score": 0,
"selected": false,
"text": "numpy.float64 numpy.int64 data numpy.array list"
},
{
"answer_id": 74645889,
"author": "hpaulj",
"author_id": 901925,
"author_profile": "https://Stackoverflow.com/users/901925",
"pm_score": 1,
"selected": false,
"text": "data In [60]: Mx\nOut[60]: \n<1x3 sparse matrix of type '<class 'numpy.intc'>'\n with 2 stored elements in Compressed Sparse Row format>\nIn [61]: Mx.A\nOut[61]: array([[0, 1, 2]], dtype=int32)\n nonzero coo In [62]: Mx.nonzero()\nOut[62]: (array([0, 0], dtype=int32), array([1, 2], dtype=int32))\n In [63]: Mx.data,Mx.indices,Mx.indptr\nOut[63]: \n(array([1, 2], dtype=int32),\n array([1, 2], dtype=int32),\n array([0, 2], dtype=int32))\n Mx indptr indices data In [64]: newM = sparse.csr_matrix((Mx.data, Mx.indices, Mx.indptr)) \nIn [65]: newM.A\nOut[65]: array([[0, 1, 2]], dtype=int32)\n data In [68]: Mx.data==newM.data\nOut[68]: array([ True, True])\n id data In [75]: id(Mx.data.base), id(newM.data.base)\nOut[75]: (2255407394864, 2255407394864)\n newA Mx In [77]: newM[0,1] = 100\nIn [78]: newM.A\nOut[78]: array([[ 0, 100, 2]], dtype=int32)\nIn [79]: Mx.A\nOut[79]: array([[ 0, 100, 2]], dtype=int32)\n In [92]: data = np.array([[1.23,2],[3],[]],object); ind = np.array([[1,2],[3],[]],object)\n ...: indptr = np.empty(4) \n ...: indptr[0] = 0\n ...: for i in range(1, 4):\n ...: indptr[i] = indptr[i-1] + len(data[i-1])\n ...: data = np.concatenate(data).ravel() \n ...: ind = np.concatenate(ind).ravel() # same than above\n\nIn [93]: data,ind,indptr\nOut[93]: (array([1.23, 2. , 3. ]), array([1., 2., 3.]), array([0., 2., 3., 3.]))\n In [94]: X = sparse.csr_matrix((data, ind, indptr), shape=(3,3)) \nIn [95]: X\nOut[95]: \n<3x3 sparse matrix of type '<class 'numpy.float64'>'\n with 3 stored elements in Compressed Sparse Row format>\n data In [96]: X.data\nOut[96]: array([1.23, 2. , 3. ])\n\nIn [97]: data == X.data\nOut[97]: array([ True, True, True])\n view In [98]: data[1]+=.23; data\nOut[98]: array([1.23, 2.23, 3. ]) \nIn [99]: X.A\nOut[99]: \narray([[0. , 1.23, 2.23],\n [0. , 0. , 0. ],\n [3. , 0. , 0. ]])\n X In [110]: X = sparse.csr_matrix((data, ind, indptr), shape=(3,4))\n\nIn [111]: X.A\nOut[111]: \narray([[0. , 1.23, 2.23, 0. ],\n [0. , 0. , 0. , 3. ],\n [0. , 0. , 0. , 0. ]])\n\nIn [112]: X.data\nOut[112]: array([1.23, 2.23, 3. ])\n\nIn [113]: X.nonzero()\nOut[113]: (array([0, 0, 1], dtype=int32), array([1, 2, 3], dtype=int32))\n\nIn [114]: X[X.nonzero()]\nOut[114]: matrix([[1.23, 2.23, 3. ]])\n\nIn [115]: data\nOut[115]: array([1.23, 2.23, 3. ])\n\nIn [116]: data == X[X.nonzero()]\nOut[116]: matrix([[ True, True, True]])\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74614497",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19288896/"
] |
74,614,517
|
<p>This is my first time posting a coding question on any website, so apologies if i dont do a great job. Constructive feedback is very welcome. I am working on the tideman problem in cs50, if that is meaningful to anyone.</p>
<p>I cant figure out a way to break out of the inner nested loop but continue the outer loop. As in, if is_cycle is true, the lines:</p>
<pre><code>locked[pairs[i].winner][pairs[i].loser] = true;
num_locked++;
</code></pre>
<p>need to be skipped for that current iteration of the outer loop.</p>
<p>Thank you so much.</p>
<pre><code>// Lock pairs into the candidate graph in order, without creating cycles
void lock_pairs(void)
{
int num_locked = 0;
//loop through pairs
//has loser won before?
//if no, lock the pair
//if yes, call is_cycle on pair. if its not a cycle lock the pair
for (int i = 0; i < pair_count; i++)
{
//has the loser won before?
for (int j = 0; j < i; j++)
{
if (pairs[i].loser == pairs[j].winner)
{
//if the loser has won before and it creates a cycle, break the inner loop, continue outer
if (is_cycle(pairs[i], pairs[j], num_locked))
{
break;
}
}
}
//this is incorrect this will lock the pair each time
locked[pairs[i].winner][pairs[i].loser] = true;
num_locked++;
}
return;
}
</code></pre>
<p>I have tried searching through stack overflow. Some mentioned a <code>goto</code> function but most people said that is bad programming. someone else mentioned creating a separate function and using <code>return</code> statements but i need that outer loop to continue, not stop. And one other answer suggested using <code>flags</code>, which after more searching i still dont get how that could help.</p>
|
[
{
"answer_id": 74614598,
"author": "unwind",
"author_id": 28169,
"author_profile": "https://Stackoverflow.com/users/28169",
"pm_score": 1,
"selected": false,
"text": "// Lock pairs into the candidate graph in order, without creating cycles\nvoid lock_pairs(void)\n{\n int num_locked = 0;\n //loop through pairs\n //has loser won before?\n //if no, lock the pair\n //if yes, call is_cycle on pair. if its not a cycle lock the pair\n for (int i = 0; i < pair_count; i++)\n {\n //has the loser won before?\n bool found = false;\n for (int j = 0; j < i; j++)\n {\n if (pairs[i].loser == pairs[j].winner)\n {\n //if the loser has won before and it creates a cycle, break the inner loop, continue outer\n if (is_cycle(pairs[i], pairs[j], num_locked))\n {\n found = true;\n break;\n }\n }\n }\n if (!found)\n {\n locked[pairs[i].winner][pairs[i].loser] = true;\n num_locked++;\n }\n }\n}\n return void"
},
{
"answer_id": 74614835,
"author": "Andreas Wenzel",
"author_id": 12149471,
"author_profile": "https://Stackoverflow.com/users/12149471",
"pm_score": 3,
"selected": true,
"text": "goto goto // Lock pairs into the candidate graph in order, without creating cycles\nvoid lock_pairs(void)\n{\n int num_locked = 0;\n //loop through pairs\n //has loser won before?\n //if no, lock the pair\n //if yes, call is_cycle on pair. if its not a cycle lock the pair\n for (int i = 0; i < pair_count; i++)\n {\n //has the loser won before?\n for (int j = 0; j < i; j++)\n {\n if (pairs[i].loser == pairs[j].winner)\n {\n //if the loser has won before and it creates a cycle, break the inner loop, continue outer\n if (is_cycle(pairs[i], pairs[j], num_locked))\n {\n goto continue_outer_loop;\n }\n }\n }\n //this is incorrect this will lock the pair each time\n locked[pairs[i].winner][pairs[i].loser] = true;\n num_locked++;\n\n continue_outer_loop:\n continue;\n }\n\n return;\n}\n"
},
{
"answer_id": 74615125,
"author": "Ian Abbott",
"author_id": 5264491,
"author_profile": "https://Stackoverflow.com/users/5264491",
"pm_score": 1,
"selected": false,
"text": "// Lock pairs into the candidate graph in order, without creating cycles\nvoid lock_pairs(void)\n{\n int num_locked = 0;\n //loop through pairs\n //has loser won before?\n //if no, lock the pair\n //if yes, call is_cycle on pair. if its not a cycle lock the pair\n for (int i = 0; i < pair_count; i++)\n {\n int j;\n //has the loser won before?\n for (j = 0; j < i; j++)\n {\n if (pairs[i].loser == pairs[j].winner)\n {\n //if the loser has won before and it creates a cycle, break the inner loop, continue outer\n if (is_cycle(pairs[i], pairs[j], num_locked))\n {\n break;\n }\n }\n }\n if (j < i)\n {\n continue;\n }\n locked[pairs[i].winner][pairs[i].loser] = true;\n num_locked++;\n }\n\n return;\n}\n j"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74614517",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20633421/"
] |
74,614,563
|
<p>I was hoping you could help me with a task in SAS. I have a data set (2 by 2 of numbers) and I would like to extract each entry and store them individually as a macro variable for later use. I am not very familiar with macros so I am not sure if this is possible.</p>
<p>Many thanks for any advice!</p>
|
[
{
"answer_id": 74614598,
"author": "unwind",
"author_id": 28169,
"author_profile": "https://Stackoverflow.com/users/28169",
"pm_score": 1,
"selected": false,
"text": "// Lock pairs into the candidate graph in order, without creating cycles\nvoid lock_pairs(void)\n{\n int num_locked = 0;\n //loop through pairs\n //has loser won before?\n //if no, lock the pair\n //if yes, call is_cycle on pair. if its not a cycle lock the pair\n for (int i = 0; i < pair_count; i++)\n {\n //has the loser won before?\n bool found = false;\n for (int j = 0; j < i; j++)\n {\n if (pairs[i].loser == pairs[j].winner)\n {\n //if the loser has won before and it creates a cycle, break the inner loop, continue outer\n if (is_cycle(pairs[i], pairs[j], num_locked))\n {\n found = true;\n break;\n }\n }\n }\n if (!found)\n {\n locked[pairs[i].winner][pairs[i].loser] = true;\n num_locked++;\n }\n }\n}\n return void"
},
{
"answer_id": 74614835,
"author": "Andreas Wenzel",
"author_id": 12149471,
"author_profile": "https://Stackoverflow.com/users/12149471",
"pm_score": 3,
"selected": true,
"text": "goto goto // Lock pairs into the candidate graph in order, without creating cycles\nvoid lock_pairs(void)\n{\n int num_locked = 0;\n //loop through pairs\n //has loser won before?\n //if no, lock the pair\n //if yes, call is_cycle on pair. if its not a cycle lock the pair\n for (int i = 0; i < pair_count; i++)\n {\n //has the loser won before?\n for (int j = 0; j < i; j++)\n {\n if (pairs[i].loser == pairs[j].winner)\n {\n //if the loser has won before and it creates a cycle, break the inner loop, continue outer\n if (is_cycle(pairs[i], pairs[j], num_locked))\n {\n goto continue_outer_loop;\n }\n }\n }\n //this is incorrect this will lock the pair each time\n locked[pairs[i].winner][pairs[i].loser] = true;\n num_locked++;\n\n continue_outer_loop:\n continue;\n }\n\n return;\n}\n"
},
{
"answer_id": 74615125,
"author": "Ian Abbott",
"author_id": 5264491,
"author_profile": "https://Stackoverflow.com/users/5264491",
"pm_score": 1,
"selected": false,
"text": "// Lock pairs into the candidate graph in order, without creating cycles\nvoid lock_pairs(void)\n{\n int num_locked = 0;\n //loop through pairs\n //has loser won before?\n //if no, lock the pair\n //if yes, call is_cycle on pair. if its not a cycle lock the pair\n for (int i = 0; i < pair_count; i++)\n {\n int j;\n //has the loser won before?\n for (j = 0; j < i; j++)\n {\n if (pairs[i].loser == pairs[j].winner)\n {\n //if the loser has won before and it creates a cycle, break the inner loop, continue outer\n if (is_cycle(pairs[i], pairs[j], num_locked))\n {\n break;\n }\n }\n }\n if (j < i)\n {\n continue;\n }\n locked[pairs[i].winner][pairs[i].loser] = true;\n num_locked++;\n }\n\n return;\n}\n j"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74614563",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20560185/"
] |
74,614,615
|
<p>I'm trying to make a single object larger than 2GB using new operator.
But if the size of the object is larger than 0x7fffffff, The size of memory to be allocated become strange.
I think it is done by compiler because the assembly code itself use strange size of memory allocation.</p>
<p>I'm using Visual Stuio 2015 and configuration is Release, x64.</p>
<p>Is it bug of VS2015? otherwise, I want to know why the limitation exists.</p>
<p>The example code is as below with assembly code.</p>
<pre><code>struct chunk1MB
{
char data[1024 * 1024];
};
class chunk1
{
chunk1MB data1[1024];
chunk1MB data2[1023];
char data[1024 * 1024 - 1];
};
class chunk2
{
chunk1MB data1[1024];
chunk1MB data2[1024];
};
auto* ptr1 = new chunk1;
00007FF668AF1044 mov ecx,7FFFFFFFh
00007FF668AF1049 call operator new (07FF668AF13E4h)
auto* ptr2 = new chunk2;
00007FF668AF104E mov rcx,0FFFFFFFF80000000h // must be 080000000h
00007FF668AF1055 mov rsi,rax
00007FF668AF1058 call operator new (07FF668AF13E4h)
</code></pre>
|
[
{
"answer_id": 74614598,
"author": "unwind",
"author_id": 28169,
"author_profile": "https://Stackoverflow.com/users/28169",
"pm_score": 1,
"selected": false,
"text": "// Lock pairs into the candidate graph in order, without creating cycles\nvoid lock_pairs(void)\n{\n int num_locked = 0;\n //loop through pairs\n //has loser won before?\n //if no, lock the pair\n //if yes, call is_cycle on pair. if its not a cycle lock the pair\n for (int i = 0; i < pair_count; i++)\n {\n //has the loser won before?\n bool found = false;\n for (int j = 0; j < i; j++)\n {\n if (pairs[i].loser == pairs[j].winner)\n {\n //if the loser has won before and it creates a cycle, break the inner loop, continue outer\n if (is_cycle(pairs[i], pairs[j], num_locked))\n {\n found = true;\n break;\n }\n }\n }\n if (!found)\n {\n locked[pairs[i].winner][pairs[i].loser] = true;\n num_locked++;\n }\n }\n}\n return void"
},
{
"answer_id": 74614835,
"author": "Andreas Wenzel",
"author_id": 12149471,
"author_profile": "https://Stackoverflow.com/users/12149471",
"pm_score": 3,
"selected": true,
"text": "goto goto // Lock pairs into the candidate graph in order, without creating cycles\nvoid lock_pairs(void)\n{\n int num_locked = 0;\n //loop through pairs\n //has loser won before?\n //if no, lock the pair\n //if yes, call is_cycle on pair. if its not a cycle lock the pair\n for (int i = 0; i < pair_count; i++)\n {\n //has the loser won before?\n for (int j = 0; j < i; j++)\n {\n if (pairs[i].loser == pairs[j].winner)\n {\n //if the loser has won before and it creates a cycle, break the inner loop, continue outer\n if (is_cycle(pairs[i], pairs[j], num_locked))\n {\n goto continue_outer_loop;\n }\n }\n }\n //this is incorrect this will lock the pair each time\n locked[pairs[i].winner][pairs[i].loser] = true;\n num_locked++;\n\n continue_outer_loop:\n continue;\n }\n\n return;\n}\n"
},
{
"answer_id": 74615125,
"author": "Ian Abbott",
"author_id": 5264491,
"author_profile": "https://Stackoverflow.com/users/5264491",
"pm_score": 1,
"selected": false,
"text": "// Lock pairs into the candidate graph in order, without creating cycles\nvoid lock_pairs(void)\n{\n int num_locked = 0;\n //loop through pairs\n //has loser won before?\n //if no, lock the pair\n //if yes, call is_cycle on pair. if its not a cycle lock the pair\n for (int i = 0; i < pair_count; i++)\n {\n int j;\n //has the loser won before?\n for (j = 0; j < i; j++)\n {\n if (pairs[i].loser == pairs[j].winner)\n {\n //if the loser has won before and it creates a cycle, break the inner loop, continue outer\n if (is_cycle(pairs[i], pairs[j], num_locked))\n {\n break;\n }\n }\n }\n if (j < i)\n {\n continue;\n }\n locked[pairs[i].winner][pairs[i].loser] = true;\n num_locked++;\n }\n\n return;\n}\n j"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74614615",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5452435/"
] |
74,614,634
|
<p>I have some Fact Revenue, I am trying to group by Conca, and display the values only if negative…</p>
<p>For doing it I have this calculated column:</p>
<pre><code>=
VAR name1 = Revenue[Conca]
VAR name2=
CALCULATE (
SUM ( Revenue[CostOfQuality] ),
FILTER ( Revenue, Revenue[Conca] = name1 )
)
RETURN
if (name2>0, 0, Revenue[CostOfQuality])
</code></pre>
<p>It works:</p>
<p><a href="https://i.stack.imgur.com/pEuUl.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/pEuUl.png" alt="enter image description here" /></a></p>
<p>(highest value is 0 as expected):</p>
<p>Now...</p>
<p>If I drag <strong>fiscal year</strong> it stops working:
<a href="https://i.stack.imgur.com/l8sIz.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/l8sIz.png" alt="enter image description here" /></a></p>
<p>Why is it that I see numbers higher than 0?? (I want it to still work even if I bring other filters...)</p>
|
[
{
"answer_id": 74614598,
"author": "unwind",
"author_id": 28169,
"author_profile": "https://Stackoverflow.com/users/28169",
"pm_score": 1,
"selected": false,
"text": "// Lock pairs into the candidate graph in order, without creating cycles\nvoid lock_pairs(void)\n{\n int num_locked = 0;\n //loop through pairs\n //has loser won before?\n //if no, lock the pair\n //if yes, call is_cycle on pair. if its not a cycle lock the pair\n for (int i = 0; i < pair_count; i++)\n {\n //has the loser won before?\n bool found = false;\n for (int j = 0; j < i; j++)\n {\n if (pairs[i].loser == pairs[j].winner)\n {\n //if the loser has won before and it creates a cycle, break the inner loop, continue outer\n if (is_cycle(pairs[i], pairs[j], num_locked))\n {\n found = true;\n break;\n }\n }\n }\n if (!found)\n {\n locked[pairs[i].winner][pairs[i].loser] = true;\n num_locked++;\n }\n }\n}\n return void"
},
{
"answer_id": 74614835,
"author": "Andreas Wenzel",
"author_id": 12149471,
"author_profile": "https://Stackoverflow.com/users/12149471",
"pm_score": 3,
"selected": true,
"text": "goto goto // Lock pairs into the candidate graph in order, without creating cycles\nvoid lock_pairs(void)\n{\n int num_locked = 0;\n //loop through pairs\n //has loser won before?\n //if no, lock the pair\n //if yes, call is_cycle on pair. if its not a cycle lock the pair\n for (int i = 0; i < pair_count; i++)\n {\n //has the loser won before?\n for (int j = 0; j < i; j++)\n {\n if (pairs[i].loser == pairs[j].winner)\n {\n //if the loser has won before and it creates a cycle, break the inner loop, continue outer\n if (is_cycle(pairs[i], pairs[j], num_locked))\n {\n goto continue_outer_loop;\n }\n }\n }\n //this is incorrect this will lock the pair each time\n locked[pairs[i].winner][pairs[i].loser] = true;\n num_locked++;\n\n continue_outer_loop:\n continue;\n }\n\n return;\n}\n"
},
{
"answer_id": 74615125,
"author": "Ian Abbott",
"author_id": 5264491,
"author_profile": "https://Stackoverflow.com/users/5264491",
"pm_score": 1,
"selected": false,
"text": "// Lock pairs into the candidate graph in order, without creating cycles\nvoid lock_pairs(void)\n{\n int num_locked = 0;\n //loop through pairs\n //has loser won before?\n //if no, lock the pair\n //if yes, call is_cycle on pair. if its not a cycle lock the pair\n for (int i = 0; i < pair_count; i++)\n {\n int j;\n //has the loser won before?\n for (j = 0; j < i; j++)\n {\n if (pairs[i].loser == pairs[j].winner)\n {\n //if the loser has won before and it creates a cycle, break the inner loop, continue outer\n if (is_cycle(pairs[i], pairs[j], num_locked))\n {\n break;\n }\n }\n }\n if (j < i)\n {\n continue;\n }\n locked[pairs[i].winner][pairs[i].loser] = true;\n num_locked++;\n }\n\n return;\n}\n j"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74614634",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4979809/"
] |
74,614,677
|
<p>I want to create a new view in SQL Server 2008 R2.
Given is a col called "ADRESS", based on which I want to create a col called "CompanyID".
I want to add a suffix, which counts +1 for each row in a group of adresses, ideally starting from ".002".
The output should look like this:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>ADRESS</th>
<th>CompanyID</th>
</tr>
</thead>
<tbody>
<tr>
<td>100000</td>
<td>100000.002</td>
</tr>
<tr>
<td>100000</td>
<td>100000.003</td>
</tr>
<tr>
<td>100000</td>
<td>100000.004</td>
</tr>
<tr>
<td>200000</td>
<td>100000.002</td>
</tr>
<tr>
<td>200000</td>
<td>100000.003</td>
</tr>
<tr>
<td>300000</td>
<td>100000.002</td>
</tr>
</tbody>
</table>
</div>
<p>My idea was to declare a count variable:</p>
<pre><code>DECLARE @count AS
SET @count = '002'
</code></pre>
<p>And then use a while loop:</p>
<pre><code>WHILE ()
BEGIN
SELECT ADRESS + '.' + @count AS CompanyID
SET @count = @count +1
END
</code></pre>
<p>Problem is, I don't have a idea what to loop through and also, which data type allows 3 digits without removing the first two zeros. I'm new to SQL so i would appreciate a short explanation.</p>
|
[
{
"answer_id": 74614598,
"author": "unwind",
"author_id": 28169,
"author_profile": "https://Stackoverflow.com/users/28169",
"pm_score": 1,
"selected": false,
"text": "// Lock pairs into the candidate graph in order, without creating cycles\nvoid lock_pairs(void)\n{\n int num_locked = 0;\n //loop through pairs\n //has loser won before?\n //if no, lock the pair\n //if yes, call is_cycle on pair. if its not a cycle lock the pair\n for (int i = 0; i < pair_count; i++)\n {\n //has the loser won before?\n bool found = false;\n for (int j = 0; j < i; j++)\n {\n if (pairs[i].loser == pairs[j].winner)\n {\n //if the loser has won before and it creates a cycle, break the inner loop, continue outer\n if (is_cycle(pairs[i], pairs[j], num_locked))\n {\n found = true;\n break;\n }\n }\n }\n if (!found)\n {\n locked[pairs[i].winner][pairs[i].loser] = true;\n num_locked++;\n }\n }\n}\n return void"
},
{
"answer_id": 74614835,
"author": "Andreas Wenzel",
"author_id": 12149471,
"author_profile": "https://Stackoverflow.com/users/12149471",
"pm_score": 3,
"selected": true,
"text": "goto goto // Lock pairs into the candidate graph in order, without creating cycles\nvoid lock_pairs(void)\n{\n int num_locked = 0;\n //loop through pairs\n //has loser won before?\n //if no, lock the pair\n //if yes, call is_cycle on pair. if its not a cycle lock the pair\n for (int i = 0; i < pair_count; i++)\n {\n //has the loser won before?\n for (int j = 0; j < i; j++)\n {\n if (pairs[i].loser == pairs[j].winner)\n {\n //if the loser has won before and it creates a cycle, break the inner loop, continue outer\n if (is_cycle(pairs[i], pairs[j], num_locked))\n {\n goto continue_outer_loop;\n }\n }\n }\n //this is incorrect this will lock the pair each time\n locked[pairs[i].winner][pairs[i].loser] = true;\n num_locked++;\n\n continue_outer_loop:\n continue;\n }\n\n return;\n}\n"
},
{
"answer_id": 74615125,
"author": "Ian Abbott",
"author_id": 5264491,
"author_profile": "https://Stackoverflow.com/users/5264491",
"pm_score": 1,
"selected": false,
"text": "// Lock pairs into the candidate graph in order, without creating cycles\nvoid lock_pairs(void)\n{\n int num_locked = 0;\n //loop through pairs\n //has loser won before?\n //if no, lock the pair\n //if yes, call is_cycle on pair. if its not a cycle lock the pair\n for (int i = 0; i < pair_count; i++)\n {\n int j;\n //has the loser won before?\n for (j = 0; j < i; j++)\n {\n if (pairs[i].loser == pairs[j].winner)\n {\n //if the loser has won before and it creates a cycle, break the inner loop, continue outer\n if (is_cycle(pairs[i], pairs[j], num_locked))\n {\n break;\n }\n }\n }\n if (j < i)\n {\n continue;\n }\n locked[pairs[i].winner][pairs[i].loser] = true;\n num_locked++;\n }\n\n return;\n}\n j"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74614677",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16365837/"
] |
74,614,688
|
<p>I am trying something like this:
<a href="https://stackoverflow.com/questions/47340518/list-append-in-pandas-cell">List append in pandas cell</a></p>
<p>But the problem is the post is old and everything is deprecated and should not be used anymore.</p>
<pre><code>d = {'col1': ['TEST', 'TEST'], 'col2': [[1, 2], [1, 2]], 'col3': [35, 89]}
df = pd.DataFrame(data=d)
</code></pre>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>col1</th>
<th>col2</th>
<th>col3</th>
</tr>
</thead>
<tbody>
<tr>
<td>TEST</td>
<td>[1, 2, 3]</td>
<td>35</td>
</tr>
<tr>
<td>TEST</td>
<td>[1, 2, 3]</td>
<td>89</td>
</tr>
</tbody>
</table>
</div>
<p>My Dataframe looks like this, were there is the col2 is the one I am interested in. I need to add [0,0] to the lists in col2 for every row in the DataFrame. My real DataFrame is of dynamic shape so I cant just set every cell on its own.</p>
<p>End result should look like this:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>col1</th>
<th>col2</th>
<th>col3</th>
</tr>
</thead>
<tbody>
<tr>
<td>TEST</td>
<td>[1, 2, 3, 0, 0]</td>
<td>35</td>
</tr>
<tr>
<td>TEST</td>
<td>[1, 2, 3, 0, 0]</td>
<td>89</td>
</tr>
</tbody>
</table>
</div>
<p>I fooled around with <code>df.apply</code> and <code>df.assign</code> but I can't seem to get it to work.
I tried:</p>
<pre><code>df['col2'] += [0, 0]
df = df.col2.apply(lambda x: x.append([0,0]))
Which returns a Series that looks nothing like i need it
df = df.assign(new_column = lambda x: x + list([0, 0))
</code></pre>
|
[
{
"answer_id": 74614800,
"author": "Tzane",
"author_id": 14536215,
"author_profile": "https://Stackoverflow.com/users/14536215",
"pm_score": 3,
"selected": true,
"text": "import pandas as pd\n\nd = {'col1': ['TEST', 'TEST'], 'col2': [[1, 2], [1, 2]], 'col3': [35, 89]}\ndf = pd.DataFrame(data=d)\ndf[\"col2\"] = df[\"col2\"].apply(lambda x: x + [0,0])\nprint(df)\n .extend .append None"
},
{
"answer_id": 74614865,
"author": "jezrael",
"author_id": 2901002,
"author_profile": "https://Stackoverflow.com/users/2901002",
"pm_score": 0,
"selected": false,
"text": "df[\"col2\"] = [x + [0,0] for x in df[\"col2\"]]\n \nprint (df)\n col1 col2 col3\n0 TEST [1, 2, 0, 0] 35\n1 TEST [1, 2, 0, 0] 89\n"
},
{
"answer_id": 74615014,
"author": "Stan U.",
"author_id": 20432831,
"author_profile": "https://Stackoverflow.com/users/20432831",
"pm_score": -1,
"selected": false,
"text": "for val in df['col2']:\n val.append(0)\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74614688",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7451746/"
] |
74,614,697
|
<p>i'm learning flutter recently, and i have a problem. How display nested json file in listview in flutter ?</p>
<p>On internet i see a lots of example but it's with an url of an api and i don't want use api. I'm in local.</p>
<p>I think the problem is not my parse, but i don't know so, below you can see my code.</p>
<p>array.json</p>
<pre><code>
[
{
"jp": {
"name": "jp",
"password": "pawwordTest",
"maxtun": 0,
"email": "jp@france.fr",
"date": {
"build": "test1",
"first_cnx": "test2"
}
}
}
]
</code></pre>
<p>array.dart</p>
<pre><code>class JP {
final String name;
final String password;
final int maxtun;
final String email;
final Date date;
JP({
required this.name,
required this.password,
required this.maxtun,
required this.email,
required this.date,
});
factory JP.fromJson(Map<String, dynamic> json){
return JP(
name: json['name'],
password: json['password'],
maxtun: json['maxtun'],
email: json['email'],
date: Date.fromJson(json['date']),
);
}
}
class Date{
final String build;
final String firstCNX;
Date({required this.build, required this.firstCNX});
factory Date.fromJson(Map<String, dynamic> json){
return Date(
build: json['build'],
firstCNX: json['first_cnx']
);
}
}
</code></pre>
<p>And event_page.dart</p>
<pre><code>import 'dart:convert';
import 'package:flutter/material.dart';
import 'dart:async' show Future;
//import 'package:flutter/material.dart' show rootBundle;
import 'package:array_json/array.dart';
import 'package:flutter/services.dart';
class EventPage extends StatefulWidget {
const EventPage({Key? key}) : super(key: key);
@override
State<EventPage> createState() => _EventPageState();
}
class _EventPageState extends State<EventPage> {
List<JP> testJson = [];
Future<void> readJson() async{
final String response = await rootBundle.loadString("assets/array.json");
final informationData = await json.decode(response);
var list = informationData['jp'] as List<dynamic>;
setState(() {
testJson = [];
testJson = list.map((e) => JP.fromJson(e)).toList();
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
leadingWidth: 100,
leading: ElevatedButton.icon(
onPressed: () => Navigator.of(context).pop(),
icon: const Icon(Icons.arrow_back_ios,
color: Colors.blue,
),
label: const Text("Back",
style: TextStyle(color: Colors.blue),
),
style: ElevatedButton.styleFrom(
elevation: 0,
backgroundColor: Colors.transparent,
),
),
centerTitle: true,
title: const Text("Load and Read JSON File",
style: TextStyle(color: Colors.black54),
),
backgroundColor: Colors.white,
),
body: Column(
children: [
Padding(padding: EdgeInsets.all(15.0),
child: ElevatedButton(onPressed: readJson,
child: const Text("Load Informations")),
),
Expanded(
child: ListView.builder(
itemCount: testJson.length,
itemBuilder: (BuildContext context, index){
final x = testJson[index];
return Container(
padding: EdgeInsets.all(10.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text("test : ${x.name}"),
Text(x.password),
Text(x.maxtun.toString()),
Text(x.email),
const SizedBox(
height: 5.0,
),
const Text("Date : ",
style: TextStyle(fontSize: 16.0, fontWeight: FontWeight.bold),
),
Text(x.date.build),
Text(x.date.firstCNX),
const SizedBox(
height: 5.0,
),
],
),
);
}
),
),
],
),
);
}
}
</code></pre>
<p>Help me please, i'm sure, i'm not missing much but it's the question</p>
|
[
{
"answer_id": 74614800,
"author": "Tzane",
"author_id": 14536215,
"author_profile": "https://Stackoverflow.com/users/14536215",
"pm_score": 3,
"selected": true,
"text": "import pandas as pd\n\nd = {'col1': ['TEST', 'TEST'], 'col2': [[1, 2], [1, 2]], 'col3': [35, 89]}\ndf = pd.DataFrame(data=d)\ndf[\"col2\"] = df[\"col2\"].apply(lambda x: x + [0,0])\nprint(df)\n .extend .append None"
},
{
"answer_id": 74614865,
"author": "jezrael",
"author_id": 2901002,
"author_profile": "https://Stackoverflow.com/users/2901002",
"pm_score": 0,
"selected": false,
"text": "df[\"col2\"] = [x + [0,0] for x in df[\"col2\"]]\n \nprint (df)\n col1 col2 col3\n0 TEST [1, 2, 0, 0] 35\n1 TEST [1, 2, 0, 0] 89\n"
},
{
"answer_id": 74615014,
"author": "Stan U.",
"author_id": 20432831,
"author_profile": "https://Stackoverflow.com/users/20432831",
"pm_score": -1,
"selected": false,
"text": "for val in df['col2']:\n val.append(0)\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74614697",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20632395/"
] |
74,614,707
|
<p>Hello all i want a latest record from table in laravel for each customer but i am not getting result as i expected below is my object and code.i want a latest entry for each customer from table</p>
<pre><code>[
{
"id": 1,
"customer_id": 10,
"bill_no": 1,
"bill_period": "",
"from_date": "2022-11-21",
"to_date": "2022-11-27",
"month": "Nov 2022",
"total_litres": "5600",
"amount": "420000",
"previous_balance": "0",
"total_amount": "420000",
"amount_paid": "350000",
"adjusted": "0",
"pending_amount": "70000",
"created_at": "2022-11-26 05:57:54",
"updated_at": "2022-11-27 03:11:57",
"customer_name": "qwe"
},
{
"id": 2,
"customer_id": 11,
"bill_no": 2,
"bill_period": "",
"from_date": "2022-11-21",
"to_date": "2022-11-27",
"month": "Nov 2022",
"total_litres": "1680",
"amount": "129360",
"previous_balance": "0",
"total_amount": "129360",
"amount_paid": "120000",
"adjusted": "9360",
"pending_amount": "0",
"created_at": "2022-11-26 05:57:54",
"updated_at": "2022-11-27 03:13:05",
"customer_name": "rty"
},
{
"id": 4,
"customer_id": 13,
"bill_no": 4,
"bill_period": "",
"from_date": "2022-11-21",
"to_date": "2022-11-27",
"month": "Nov 2022",
"total_litres": "560",
"amount": "42000",
"previous_balance": "0",
"total_amount": "42000",
"amount_paid": "42000",
"adjusted": "0",
"pending_amount": "0",
"created_at": "2022-11-26 05:57:54",
"updated_at": "2022-11-27 03:13:27",
"customer_name": "uio"
},
{
"id": 5,
"customer_id": 14,
"bill_no": 5,
"bill_period": "",
"from_date": "2022-11-21",
"to_date": "2022-11-27",
"month": "Nov 2022",
"total_litres": "500",
"amount": "39000",
"previous_balance": "0",
"total_amount": "39000",
"amount_paid": "39000",
"adjusted": "0",
"pending_amount": "0",
"created_at": "2022-11-26 05:57:54",
"updated_at": "2022-11-27 03:13:34",
"customer_name": "asd"
},
{
"id": 6,
"customer_id": 15,
"bill_no": 6,
"bill_period": "",
"from_date": "2022-11-21",
"to_date": "2022-11-27",
"month": "Nov 2022",
"total_litres": "560",
"amount": "42560",
"previous_balance": "0",
"total_amount": "42560",
"amount_paid": "42560",
"adjusted": "0",
"pending_amount": "0",
"created_at": "2022-11-26 05:57:54",
"updated_at": "2022-11-27 03:13:42",
"customer_name": "fgh"
},
{
"id": 7,
"customer_id": 17,
"bill_no": 7,
"bill_period": "",
"from_date": "2022-11-21",
"to_date": "2022-11-27",
"month": "Nov 2022",
"total_litres": "490",
"amount": "38220",
"previous_balance": "0",
"total_amount": "38220",
"amount_paid": "0",
"adjusted": "0",
"pending_amount": "38220",
"created_at": "2022-11-26 05:57:54",
"updated_at": null,
"customer_name": "jkl"
},
{
"id": 8,
"customer_id": 18,
"bill_no": 8,
"bill_period": "",
"from_date": "2022-11-21",
"to_date": "2022-11-27",
"month": "Nov 2022",
"total_litres": "315",
"amount": "24570",
"previous_balance": "0",
"total_amount": "24570",
"amount_paid": "24570",
"adjusted": "0",
"pending_amount": "0",
"created_at": "2022-11-26 05:57:54",
"updated_at": "2022-11-26 10:28:45",
"customer_name": "zxc"
},
{
"id": 9,
"customer_id": 10,
"bill_no": 9,
"bill_period": "",
"from_date": "2022-11-28",
"to_date": "2022-12-04",
"month": "Nov 2022",
"total_litres": "5600",
"amount": "420000",
"previous_balance": "70000",
"total_amount": "490000",
"amount_paid": "450000",
"adjusted": "0",
"pending_amount": "40000",
"created_at": "2022-11-27 03:16:17",
"updated_at": "2022-11-27 11:52:52",
"customer_name": "qwe"
},
{
"id": 10,
"customer_id": 11,
"bill_no": 10,
"bill_period": "",
"from_date": "2022-11-28",
"to_date": "2022-12-04",
"month": "Nov 2022",
"total_litres": "1680",
"amount": "129360",
"previous_balance": "0",
"total_amount": "129360",
"amount_paid": "115000",
"adjusted": "0",
"pending_amount": "14360",
"created_at": "2022-11-27 03:16:17",
"updated_at": "2022-11-27 11:52:52",
"customer_name": "rty"
},
{
"id": 12,
"customer_id": 13,
"bill_no": 12,
"bill_period": "",
"from_date": "2022-11-28",
"to_date": "2022-12-04",
"month": "Nov 2022",
"total_litres": "560",
"amount": "42000",
"previous_balance": "0",
"total_amount": "42000",
"amount_paid": "40000",
"adjusted": "0",
"pending_amount": "2000",
"created_at": "2022-11-27 03:16:17",
"updated_at": "2022-11-27 11:52:52",
"customer_name": "uio"
},
{
"id": 13,
"customer_id": 14,
"bill_no": 13,
"bill_period": "",
"from_date": "2022-11-28",
"to_date": "2022-12-04",
"month": "Nov 2022",
"total_litres": "490",
"amount": "38220",
"previous_balance": "0",
"total_amount": "38220",
"amount_paid": "38220",
"adjusted": "0",
"pending_amount": "0",
"created_at": "2022-11-27 03:16:17",
"updated_at": "2022-11-27 11:52:52",
"customer_name": "asd"
},
{
"id": 14,
"customer_id": 15,
"bill_no": 14,
"bill_period": "",
"from_date": "2022-11-28",
"to_date": "2022-12-04",
"month": "Nov 2022",
"total_litres": "560",
"amount": "42560",
"previous_balance": "0",
"total_amount": "42560",
"amount_paid": "42560",
"adjusted": "0",
"pending_amount": "0",
"created_at": "2022-11-27 03:16:17",
"updated_at": "2022-11-27 11:52:52",
"customer_name": "fgh"
},
{
"id": 15,
"customer_id": 17,
"bill_no": 15,
"bill_period": "",
"from_date": "2022-11-28",
"to_date": "2022-12-04",
"month": "Nov 2022",
"total_litres": "490",
"amount": "38220",
"previous_balance": "38220",
"total_amount": "76440",
"amount_paid": "76440",
"adjusted": "0",
"pending_amount": "0",
"created_at": "2022-11-27 03:16:17",
"updated_at": "2022-11-27 11:52:52",
"customer_name": "jkl"
},
{
"id": 16,
"customer_id": 18,
"bill_no": 16,
"bill_period": "",
"from_date": "2022-11-28",
"to_date": "2022-12-04",
"month": "Nov 2022",
"total_litres": "315",
"amount": "24570",
"previous_balance": "0",
"total_amount": "24570",
"amount_paid": "24570",
"adjusted": "0",
"pending_amount": "0",
"created_at": "2022-11-27 03:16:17",
"updated_at": "2022-11-27 11:52:52",
"customer_name": "zxc"
},
{
"id": 17,
"customer_id": 10,
"bill_no": 17,
"bill_period": "",
"from_date": "2022-12-05",
"to_date": "2022-12-11",
"month": "Dec 2022",
"total_litres": "5600",
"amount": "420000",
"previous_balance": "40000",
"total_amount": "460000",
"amount_paid": "0",
"adjusted": "0",
"pending_amount": "460000",
"created_at": "2022-11-27 11:53:45",
"updated_at": "2022-11-29 12:35:01",
"customer_name": "qwe"
},
{
"id": 18,
"customer_id": 11,
"bill_no": 18,
"bill_period": "",
"from_date": "2022-12-05",
"to_date": "2022-12-11",
"month": "Dec 2022",
"total_litres": "1680",
"amount": "129360",
"previous_balance": "14360",
"total_amount": "143720",
"amount_paid": "0",
"adjusted": "0",
"pending_amount": "143720",
"created_at": "2022-11-27 11:53:45",
"updated_at": "2022-11-29 12:35:01",
"customer_name": "rty"
},
{
"id": 20,
"customer_id": 13,
"bill_no": 20,
"bill_period": "",
"from_date": "2022-12-05",
"to_date": "2022-12-11",
"month": "Dec 2022",
"total_litres": "600",
"amount": "45000",
"previous_balance": "2000",
"total_amount": "47000",
"amount_paid": "0",
"adjusted": "0",
"pending_amount": "47000",
"created_at": "2022-11-27 11:53:45",
"updated_at": "2022-11-29 12:35:01",
"customer_name": "uio"
},
{
"id": 21,
"customer_id": 14,
"bill_no": 21,
"bill_period": "",
"from_date": "2022-12-05",
"to_date": "2022-12-11",
"month": "Dec 2022",
"total_litres": "495",
"amount": "38610",
"previous_balance": "0",
"total_amount": "38610",
"amount_paid": "0",
"adjusted": "0",
"pending_amount": "38610",
"created_at": "2022-11-27 11:53:45",
"updated_at": "2022-11-29 12:35:01",
"customer_name": "asd"
},
{
"id": 22,
"customer_id": 15,
"bill_no": 22,
"bill_period": "",
"from_date": "2022-12-05",
"to_date": "2022-12-11",
"month": "Dec 2022",
"total_litres": "560",
"amount": "42560",
"previous_balance": "0",
"total_amount": "42560",
"amount_paid": "0",
"adjusted": "0",
"pending_amount": "42560",
"created_at": "2022-11-27 11:53:45",
"updated_at": "2022-11-29 12:35:01",
"customer_name": "fgh"
},
{
"id": 23,
"customer_id": 17,
"bill_no": 23,
"bill_period": "",
"from_date": "2022-12-05",
"to_date": "2022-12-11",
"month": "Dec 2022",
"total_litres": "490",
"amount": "38220",
"previous_balance": "0",
"total_amount": "38220",
"amount_paid": "0",
"adjusted": "0",
"pending_amount": "38220",
"created_at": "2022-11-27 11:53:45",
"updated_at": "2022-11-29 12:35:01",
"customer_name": "jkl"
},
{
"id": 24,
"customer_id": 18,
"bill_no": 24,
"bill_period": "",
"from_date": "2022-12-05",
"to_date": "2022-12-11",
"month": "Dec 2022",
"total_litres": "315",
"amount": "24570",
"previous_balance": "0",
"total_amount": "24570",
"amount_paid": "24570",
"adjusted": "0",
"pending_amount": "0",
"created_at": "2022-11-27 11:53:45",
"updated_at": "2022-11-29 12:35:01",
"customer_name": "zxc"
},
{
"id": 25,
"customer_id": 12,
"bill_no": 25,
"bill_period": "",
"from_date": "2022-11-18",
"to_date": "2022-11-27",
"month": "Nov 2022",
"total_litres": "4001",
"amount": "296074",
"previous_balance": "0",
"total_amount": "296074",
"amount_paid": "250000",
"adjusted": "0",
"pending_amount": "46074",
"created_at": "2022-11-29 12:26:51",
"updated_at": "2022-11-29 12:35:01",
"customer_name": "mno"
},
{
"id": 26,
"customer_id": 12,
"bill_no": 26,
"bill_period": "",
"from_date": "2022-11-28",
"to_date": "2022-12-07",
"month": "Nov 2022",
"total_litres": "4000",
"amount": "296000",
"previous_balance": "46074",
"total_amount": "342074",
"amount_paid": "0",
"adjusted": "0",
"pending_amount": "342074",
"created_at": "2022-11-29 12:36:02",
"updated_at": null,
"customer_name": "mno"
}
]
</code></pre>
<p>bewlo result i want</p>
<pre><code>[
{
"id": 17,
"customer_id": 10,
"bill_no": 17,
"bill_period": "",
"from_date": "2022-12-05",
"to_date": "2022-12-11",
"month": "Dec 2022",
"total_litres": "5600",
"amount": "420000",
"previous_balance": "40000",
"total_amount": "460000",
"amount_paid": "0",
"adjusted": "0",
"pending_amount": "460000",
"created_at": "2022-11-27 11:53:45",
"updated_at": "2022-11-29 12:35:01",
"customer_name": "qwe"
},
{
"id": 18,
"customer_id": 11,
"bill_no": 18,
"bill_period": "",
"from_date": "2022-12-05",
"to_date": "2022-12-11",
"month": "Dec 2022",
"total_litres": "1680",
"amount": "129360",
"previous_balance": "14360",
"total_amount": "143720",
"amount_paid": "0",
"adjusted": "0",
"pending_amount": "143720",
"created_at": "2022-11-27 11:53:45",
"updated_at": "2022-11-29 12:35:01",
"customer_name": "rty"
},
{
"id": 20,
"customer_id": 13,
"bill_no": 20,
"bill_period": "",
"from_date": "2022-12-05",
"to_date": "2022-12-11",
"month": "Dec 2022",
"total_litres": "600",
"amount": "45000",
"previous_balance": "2000",
"total_amount": "47000",
"amount_paid": "0",
"adjusted": "0",
"pending_amount": "47000",
"created_at": "2022-11-27 11:53:45",
"updated_at": "2022-11-29 12:35:01",
"customer_name": "uio"
},
{
"id": 21,
"customer_id": 14,
"bill_no": 21,
"bill_period": "",
"from_date": "2022-12-05",
"to_date": "2022-12-11",
"month": "Dec 2022",
"total_litres": "495",
"amount": "38610",
"previous_balance": "0",
"total_amount": "38610",
"amount_paid": "0",
"adjusted": "0",
"pending_amount": "38610",
"created_at": "2022-11-27 11:53:45",
"updated_at": "2022-11-29 12:35:01",
"customer_name": "asd"
},
{
"id": 22,
"customer_id": 15,
"bill_no": 22,
"bill_period": "",
"from_date": "2022-12-05",
"to_date": "2022-12-11",
"month": "Dec 2022",
"total_litres": "560",
"amount": "42560",
"previous_balance": "0",
"total_amount": "42560",
"amount_paid": "0",
"adjusted": "0",
"pending_amount": "42560",
"created_at": "2022-11-27 11:53:45",
"updated_at": "2022-11-29 12:35:01",
"customer_name": "fgh"
},
{
"id": 23,
"customer_id": 17,
"bill_no": 23,
"bill_period": "",
"from_date": "2022-12-05",
"to_date": "2022-12-11",
"month": "Dec 2022",
"total_litres": "490",
"amount": "38220",
"previous_balance": "0",
"total_amount": "38220",
"amount_paid": "0",
"adjusted": "0",
"pending_amount": "38220",
"created_at": "2022-11-27 11:53:45",
"updated_at": "2022-11-29 12:35:01",
"customer_name": "jkl"
},
{
"id": 24,
"customer_id": 18,
"bill_no": 24,
"bill_period": "",
"from_date": "2022-12-05",
"to_date": "2022-12-11",
"month": "Dec 2022",
"total_litres": "315",
"amount": "24570",
"previous_balance": "0",
"total_amount": "24570",
"amount_paid": "24570",
"adjusted": "0",
"pending_amount": "0",
"created_at": "2022-11-27 11:53:45",
"updated_at": "2022-11-29 12:35:01",
"customer_name": "zxc"
},
{
"id": 26,
"customer_id": 12,
"bill_no": 26,
"bill_period": "",
"from_date": "2022-11-28",
"to_date": "2022-12-07",
"month": "Nov 2022",
"total_litres": "4000",
"amount": "296000",
"previous_balance": "46074",
"total_amount": "342074",
"amount_paid": "0",
"adjusted": "0",
"pending_amount": "342074",
"created_at": "2022-11-29 12:36:02",
"updated_at": null,
"customer_name": "mno"
}
]
</code></pre>
<p>i want a unique data of each customer with their latest entry below is my code.
any help would be appreciated.</p>
<pre><code>$data = DB::table('weekly_billing')
->leftJoin('customers', 'weekly_billing.customer_id', '=', 'customers.id')
->select('weekly_billing.*','customers.customer_name',DB::raw('max(weekly_billing.created_at)'))
->groupBy('weekly_billing.customer_id')
->get();
</code></pre>
|
[
{
"answer_id": 74615039,
"author": "Deathstorm",
"author_id": 7647266,
"author_profile": "https://Stackoverflow.com/users/7647266",
"pm_score": 0,
"selected": false,
"text": "where() ->orderBy('columnname', 'desc') created_at updated_at"
},
{
"answer_id": 74618831,
"author": "AdekunleCodez",
"author_id": 9107842,
"author_profile": "https://Stackoverflow.com/users/9107842",
"pm_score": 1,
"selected": false,
"text": "->latest() $data = DB::table('weekly_billing')\n ->leftJoin('customers', 'weekly_billing.customer_id', '=', 'customers.id')\n ->select('weekly_billing.*','customers.customer_name',DB::raw('max(weekly_billing.created_at)')) \n ->groupBy('weekly_billing.customer_id')\n ->latest() \n ->get();\n\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74614707",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17243161/"
] |
74,614,712
|
<p>Let it be the following python pandas dataframe.</p>
<pre><code>| date | other_columns |...
| ------------- | -------------- |...
| 2022-02-06 | row |...
| 2022-02-07 | row |...
| 2022-02-08 | row |...
| 2022-02-15 | row |...
| 2022-02-24 | row |...
| 2022-02-28 | row |...
</code></pre>
<p>I want to add the week corresponding to each date as an additional <code>week</code> column. It is simply grouping the days in 7-day intervals to assign each number. I don't want the functionality of datetime.week, I want the value to be relative to the month.</p>
<pre><code>| date | other_columns |...| week |
| ------------- | -------------- |...| -------- |
| 2022-02-06 | row |...| 1 week |
| 2022-02-07 | row |...| 1 week |
| 2022-02-08 | row |...| 2 week |
| 2022-02-15 | row |...| 3 week |
| 2022-02-24 | row |...| 4 week |
| 2022-02-28 | row |...| 5 week |
</code></pre>
<p>(1-7) correspond to the first week, (8-14) to the second, (15-21) to the third one, (21-28) fourth, (29-31) fifth. Only the day number really matters, not the month.</p>
|
[
{
"answer_id": 74614765,
"author": "jezrael",
"author_id": 2901002,
"author_profile": "https://Stackoverflow.com/users/2901002",
"pm_score": 1,
"selected": false,
"text": "df['date'] = pd.to_datetime(df['date'])\n\ndf['new2'] = ((df[\"date\"].dt.day - 1) // 7 + 1).astype(str) + ' week'\nprint (df)\n date other_columns new2\n0 2022-02-06 row 1 week\n1 2022-02-07 row 1 week\n2 2022-02-08 row 2 week\n3 2022-02-15 row 3 week\n4 2022-02-24 row 4 week\n5 2022-02-28 row 4 week\n"
},
{
"answer_id": 74615173,
"author": "tvanvalkenburg",
"author_id": 9626163,
"author_profile": "https://Stackoverflow.com/users/9626163",
"pm_score": 3,
"selected": true,
"text": "import pandas as pd\nimport math\n\n# create a date range\ndr = pd.date_range(\n start=\"2022-02-01\",\n end=\"2022-02-28\",\n freq=\"D\"\n)\n\n# create a dataframe\ndf = pd.DataFrame(\n {\n \"date\": dr\n }\n)\n\n# define a function to get the week number\ndef get_week_in_month(df, date_column):\n df[\"day\"] = df[date_column].dt.day\n\n df[\"week\"] = df[\"day\"].apply(lambda x: math.ceil(x / 7))\n\n del df[\"day\"]\n\n return df\n\n# transform the dataframe\ndf = get_week_in_month(df, \"date\")\n date week\n0 2022-02-01 1\n1 2022-02-02 1\n2 2022-02-03 1\n3 2022-02-04 1\n4 2022-02-05 1\n5 2022-02-06 1\n6 2022-02-07 1\n7 2022-02-08 2\n8 2022-02-09 2\n9 2022-02-10 2\n10 2022-02-11 2\n11 2022-02-12 2\n12 2022-02-13 2\n13 2022-02-14 2\n14 2022-02-15 3\n15 2022-02-16 3\n16 2022-02-17 3\n17 2022-02-18 3\n18 2022-02-19 3\n19 2022-02-20 3\n20 2022-02-21 3\n21 2022-02-22 4\n22 2022-02-23 4\n23 2022-02-24 4\n24 2022-02-25 4\n25 2022-02-26 4\n26 2022-02-27 4\n27 2022-02-28 4\n df[\"week\"] = df[\"date\"].dt.day.apply(lambda x: math.ceil(x / 7))\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74614712",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18396935/"
] |
74,614,779
|
<p>This is in reference to my previous <a href="https://stackoverflow.com/q/74589537/6744609">question </a>related to extracting data from .asc file and separating them while having multiple delimiters.</p>
<p>I want to perform mathematical operations on the float elements of the list of lists generated from the above question. The separation of individual data from the string has been achieved however, since the list of lists has also generated individual elements in form of strings i am unable to perform mathematical operations on them.</p>
<p>I would like to be able to access each element in the list of lists, convert them to float type and then perform mathematical operations on them.</p>
<p><a href="https://i.stack.imgur.com/m3jCi.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/m3jCi.png" alt="enter image description here" /></a></p>
<p>Here is my code where in the .asc file strings have been separated into individual elements and stored as list of lists.</p>
<p>This is the image of a specific set of datas i got from the bigger list of lists.</p>
<p><a href="https://i.stack.imgur.com/mlxwP.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/mlxwP.png" alt="enter image description here" /></a></p>
<p>I access the specific set of data from the lists and then when i try to convert them to float, i get this error
<strong>ValueError: could not convert string to float: '.'</strong></p>
<p>This is the code i have been working with</p>
<pre><code>import numpy as np
import pandas as pd
import re
Output_list = []
Final = []
count = 0
with open(r"myfile.asc","r") as file_in:
for line in map(str.strip, file_in):
if "LoggingString :=" in line:
first_quote = line.index('"') # returns the column number where '"' first appears in the
# whole string
last_quote = line.index('"', first_quote + 1) #returns the column value where " appears last
#in the # whole string ( end of line )
Output_list.append(
line[:first_quote].split(maxsplit=1)
+ line[first_quote + 1: last_quote].split(","),
)
Final.append(Output_list[count][8:25])
Data = list(map(float, Output_list[count][8])) #converting column 8th element of every lists
#in Output_list to float
count += 1
df = pd.DataFrame(Output_list)
df.to_csv("Triall_2.csv", sep=';')
df_1 = pd.DataFrame(Final)
df_1.to_csv("Test.csv", sep=";")
</code></pre>
<p>I alternatively tried using np.array(Final).astype(float).tolist() method as well but it didn't change the strings to float as i wanted.</p>
|
[
{
"answer_id": 74615118,
"author": "steven",
"author_id": 20631577,
"author_profile": "https://Stackoverflow.com/users/20631577",
"pm_score": 0,
"selected": false,
"text": "'1.06' . >>> my_array = ['0','1.06','23.345']\n>>> list(map(float, my_array[1]))\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nValueError: could not convert string to float: '.'\n >>> my_array = ['0', '1.06', '23.345']\n>>> list(map(float,my_array))\n[0.0, 1.06, 23.345]\n"
},
{
"answer_id": 74617839,
"author": "Andrej Kesely",
"author_id": 10035985,
"author_profile": "https://Stackoverflow.com/users/10035985",
"pm_score": 2,
"selected": true,
"text": "Data .append Data = []\nwith open(r\"myfile.asc\", \"r\") as file_in:\n for line in map(str.strip, file_in):\n if \"LoggingString :=\" in line:\n # ...\n Data.append(float(Output_list[count][8]))\n count += 1\n\nprint(Data)\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74614779",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6744609/"
] |
74,614,780
|
<p>I have a dynamic form, something like this.</p>
<pre><code> profileForm = new FormGroup({
firstName: new FormControl(''),
lastName: new FormControl(''),
age: new FormControl(''),
...
});
</code></pre>
<p>I want to do something when the value changes, so I did:</p>
<pre><code>this.profileForm.valueChanges.subscribe(() => {
console.log('changed' + this.profileForm.getRawValue());
});
</code></pre>
<p>But I don't want every change from the entire form, just from some of the controls, but I can't do this approach:</p>
<blockquote>
<p>this.profileForm.controls['firstName'].valueChanges...</p>
</blockquote>
<p>because my form is dynamic.
so I tried to create an array in my dynamic method, something like that will return this.</p>
<pre><code>controlsTrigger = ['firstname', 'age'];
</code></pre>
<p>note that the last name it's should not trigger the console.log.</p>
<p>so I saw the merge operator from rxjs</p>
<pre><code>merge(
this.form.get("firstname").valueChanges,
this.form.get("age").valueChanges,
).subscribe(() => console.log('changed'));
</code></pre>
<p>But I want to use it with dynamics controls.</p>
|
[
{
"answer_id": 74615106,
"author": "Gani Lastra",
"author_id": 9750302,
"author_profile": "https://Stackoverflow.com/users/9750302",
"pm_score": 0,
"selected": false,
"text": "combineLatest(this.form.get(\"fieldThatWillTrigger1\").valueChanges, this.form.get(\"fieldThatWillTrigger2\").valueChanges).pipe(withLatestFrom(this.form.get(\"fieldThatWONTTRIGGER1\").valueChanges),withLatestFrom(this.form.get(\"fieldThatWONTTRIGGER2\").valueChanges).subscribe(data => {\ndosomethinghere();\n});\n"
},
{
"answer_id": 74615204,
"author": "churill",
"author_id": 5105949,
"author_profile": "https://Stackoverflow.com/users/5105949",
"pm_score": 2,
"selected": false,
"text": "controlsTrigger Array.map merge(\n ...controlsTrigger.map(name => this.form.get(name).valueChanges))\n).subscribe(() => console.log('changed'));\n"
},
{
"answer_id": 74615704,
"author": "Jeff Nikelson",
"author_id": 11447705,
"author_profile": "https://Stackoverflow.com/users/11447705",
"pm_score": 1,
"selected": false,
"text": "const controls = [\"lastName\", \"firstName\"];\n\nmerge(\n ...controls.map(c =>\n this.profileForm.get(c).valueChanges.pipe(map(x => ({ control: c, value: x })))\n)).subscribe(console.log);\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74614780",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6533823/"
] |
74,614,801
|
<p>i want to ask how do i navigate tabs inside the DefaultTab, i have DefaultTabController Page that i name it OrderList inside OrderList i have 3 different tab which Progress,Complete and Cancel when i click button i want to navigate it to OrderList that show Cancel page. Below is my code. If i directly navigate to OrderList, it will show the first page which is progress, i wanted it to navigate to the 3rd page which is the cancel page.</p>
<pre><code>class _OrderListState extends State<OrderList> {
@override
Widget build(BuildContext context) {
return DefaultTabController(
length: 3,
child: Container(
decoration: BoxDecoration(
color: Colors.teal[300],
),
child: Scaffold(
bottomNavigationBar: BottomNavigationBarForAppClient(indexNum: 1),
backgroundColor: Colors.transparent,
appBar: AppBar(
title: const Text('Order List'),
centerTitle: true,
flexibleSpace: Container(
decoration: BoxDecoration(
color: Colors.teal[300],
),
),
),
body: Column(
children: [
TabBar(tabs: [
Tab(
text: 'In Progress',
),
Tab(
text: 'Completed',
),
Tab(
text: 'Cancelled',
),
]),
Expanded(
child: TabBarView(children: [
ProgressClient(),
CompletedClient(),
CancelledClient(),
]),
)
],
),
),
),
);
}
}
</code></pre>
<p>this is the other page code. As you can see here i navigate it to OrderList() and the default tab inside OrderList ProgressClient , i want it to go to the CancelledClient tab</p>
<pre><code>IconButton(
onPressed: () {
Navigator.pushReplacement(context,
MaterialPageRoute(builder: (context) => OrderList()));
},
icon: Icon(Icons.arrow_back, size: 40, color: Colors.white)),
</code></pre>
<p><a href="https://i.stack.imgur.com/s5798.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/s5798.png" alt="the button" /></a></p>
<p><a href="https://i.stack.imgur.com/K5pO7.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/K5pO7.png" alt="OrderList Page" /></a></p>
|
[
{
"answer_id": 74615261,
"author": "Ashot Khachatryan",
"author_id": 12397183,
"author_profile": "https://Stackoverflow.com/users/12397183",
"pm_score": 0,
"selected": false,
"text": "class _OrderListState extends State<OrderList> with TickerProviderStateMixin {\n\n\n TabBar(\n controller: TabController(initialIndex: 3, vsync: this,length: 3)\n ..\n"
},
{
"answer_id": 74617387,
"author": "Yeasin Sheikh",
"author_id": 10157127,
"author_profile": "https://Stackoverflow.com/users/10157127",
"pm_score": 1,
"selected": false,
"text": "Navigator.pushReplacement(\n context,\n MaterialPageRoute(\n builder: (context) => OrderList(),\n settings: RouteSettings(arguments: 2)));\n class OrderList extends StatefulWidget {\n const OrderList({super.key});\n\n @override\n State<OrderList> createState() => _OrderListState();\n}\n\nclass _OrderListState extends State<OrderList>\n with SingleTickerProviderStateMixin {\n late final TabController controller = TabController(length: 3, vsync: this);\n @override\n Widget build(BuildContext context) {\n final int? callBackTabIndex =\n ModalRoute.of(context)?.settings.arguments as int?;\n if (callBackTabIndex != null && callBackTabIndex == 2) {\n WidgetsBinding.instance.addPostFrameCallback((timeStamp) {\n controller.animateTo(2);\n });\n }\n return Container(\n decoration: BoxDecoration(\n color: Colors.teal[300],\n ),\n child: Scaffold(\n // bottomNavigationBar: BottomNavigationBarForAppClient(indexNum: 1),\n backgroundColor: Colors.transparent,\n appBar: AppBar(\n title: const Text('Order List'),\n centerTitle: true,\n flexibleSpace: Container(\n decoration: BoxDecoration(\n color: Colors.teal[300],\n ),\n ),\n ),\n body: Column(\n children: [\n TabBar(\n controller: controller,\n tabs: [\n Tab(\n text: 'In Progress',\n ),\n Tab(\n text: 'Completed',\n ),\n Tab(\n text: 'Cancelled',\n ),\n ],\n onTap: (value) {},\n ),\n Expanded(\n child: TabBarView(controller: controller, children: [\n ElevatedButton(\n onPressed: () {\n Navigator.of(context).push(MaterialPageRoute(\n builder: (context) => AnotherWidget(),\n ));\n },\n child: Text(\"NA\")),\n Text(\"CompletedClient\"),\n Text(\"CancelledClient\"),\n ]),\n )\n ],\n ),\n ),\n );\n }\n}\n class AnotherWidget extends StatelessWidget {\n const AnotherWidget({super.key});\n\n @override\n Widget build(BuildContext context) {\n return Column(\n mainAxisSize: MainAxisSize.min,\n children: [\n ElevatedButton(\n onPressed: () {\n Navigator.pushReplacement(\n context,\n MaterialPageRoute(\n builder: (context) => OrderList(),\n settings: RouteSettings(arguments: 2)));\n },\n child: Text(\"NV\"),\n ),\n ],\n );\n }\n}\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74614801",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10625379/"
] |
74,614,814
|
<p>I have the next question about webtable handling over Robot Framework with selenium:</p>
<p>the webpage has a table with 3 columns, but the rows are variable based on the months of a year, I already use the 'Table Column Should Contain' to confirm the existence of a row with the text of a month (i.e. 'monthA'), but now I need to work with the adjacent cells based on that row</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Column A</th>
<th>Column B</th>
<th>Column C</th>
</tr>
</thead>
<tbody>
<tr>
<td>monthA</td>
<td>orderA</td>
<td>link A</td>
</tr>
<tr>
<td>monthB</td>
<td>orderB</td>
<td>link B</td>
</tr>
</tbody>
</table>
</div>
<p>so far I'm trying to get a list of the available rows with</p>
<pre><code>${rows}= Get Element Count //*[@id="root"]/div[2]/div/div[2]/div[9]/div/table/tbody/tr
</code></pre>
<p>which gives me back the number of rows, but when I try to use it in a FOR cycle to get the names and the corresponding row, the index doesn't work, and looks like it doesn't recognize the value 0 of the index, the operation I try to do in the cycle is</p>
<pre><code>${value} Get Text (//*[@id="root"]/div[2]/div/div[2]/div[9]/div/table/tbody/tr)[${i}]
</code></pre>
<p><a href="https://i.stack.imgur.com/WjTlw.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/WjTlw.png" alt="enter image description here" /></a></p>
<p>for now I'm stuck in that part trying to figure how to make the index work</p>
|
[
{
"answer_id": 74615261,
"author": "Ashot Khachatryan",
"author_id": 12397183,
"author_profile": "https://Stackoverflow.com/users/12397183",
"pm_score": 0,
"selected": false,
"text": "class _OrderListState extends State<OrderList> with TickerProviderStateMixin {\n\n\n TabBar(\n controller: TabController(initialIndex: 3, vsync: this,length: 3)\n ..\n"
},
{
"answer_id": 74617387,
"author": "Yeasin Sheikh",
"author_id": 10157127,
"author_profile": "https://Stackoverflow.com/users/10157127",
"pm_score": 1,
"selected": false,
"text": "Navigator.pushReplacement(\n context,\n MaterialPageRoute(\n builder: (context) => OrderList(),\n settings: RouteSettings(arguments: 2)));\n class OrderList extends StatefulWidget {\n const OrderList({super.key});\n\n @override\n State<OrderList> createState() => _OrderListState();\n}\n\nclass _OrderListState extends State<OrderList>\n with SingleTickerProviderStateMixin {\n late final TabController controller = TabController(length: 3, vsync: this);\n @override\n Widget build(BuildContext context) {\n final int? callBackTabIndex =\n ModalRoute.of(context)?.settings.arguments as int?;\n if (callBackTabIndex != null && callBackTabIndex == 2) {\n WidgetsBinding.instance.addPostFrameCallback((timeStamp) {\n controller.animateTo(2);\n });\n }\n return Container(\n decoration: BoxDecoration(\n color: Colors.teal[300],\n ),\n child: Scaffold(\n // bottomNavigationBar: BottomNavigationBarForAppClient(indexNum: 1),\n backgroundColor: Colors.transparent,\n appBar: AppBar(\n title: const Text('Order List'),\n centerTitle: true,\n flexibleSpace: Container(\n decoration: BoxDecoration(\n color: Colors.teal[300],\n ),\n ),\n ),\n body: Column(\n children: [\n TabBar(\n controller: controller,\n tabs: [\n Tab(\n text: 'In Progress',\n ),\n Tab(\n text: 'Completed',\n ),\n Tab(\n text: 'Cancelled',\n ),\n ],\n onTap: (value) {},\n ),\n Expanded(\n child: TabBarView(controller: controller, children: [\n ElevatedButton(\n onPressed: () {\n Navigator.of(context).push(MaterialPageRoute(\n builder: (context) => AnotherWidget(),\n ));\n },\n child: Text(\"NA\")),\n Text(\"CompletedClient\"),\n Text(\"CancelledClient\"),\n ]),\n )\n ],\n ),\n ),\n );\n }\n}\n class AnotherWidget extends StatelessWidget {\n const AnotherWidget({super.key});\n\n @override\n Widget build(BuildContext context) {\n return Column(\n mainAxisSize: MainAxisSize.min,\n children: [\n ElevatedButton(\n onPressed: () {\n Navigator.pushReplacement(\n context,\n MaterialPageRoute(\n builder: (context) => OrderList(),\n settings: RouteSettings(arguments: 2)));\n },\n child: Text(\"NV\"),\n ),\n ],\n );\n }\n}\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74614814",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20599153/"
] |
74,614,836
|
<p>I am trying to type a function that does this</p>
<ul>
<li>Takes a string corresponding to a number type,</li>
<li>returns a typed array</li>
<li>Upon execution the user receives information about the exact typed array returned</li>
</ul>
<p>But after trying for a long while, I haven't been able to connect the input and output.</p>
<pre class="lang-js prettyprint-override"><code>const typedArrays = {
int8: Int8Array,
uint8: Uint8Array,
int16: Int16Array,
uint16: Uint16Array,
};
type TypedArrays = typeof typedArrays
function doSomething<T extends keyof TypedArrays>(input:T): TypedArrays[T]{
return new typedArrays[input]([1,2,3])
}
</code></pre>
<p><strong>Edit:</strong> incorporated a few of the suggestions in answers (still do not solve the main problem.)</p>
<p><a href="https://www.typescriptlang.org/play?target=7#code/MYewdgzgLgBFCeAHApgEwIICdMEN4RgF4YBvAKBhgEswoAOALhgEla6td4AaCmAVxr0mAVUHtseHpUEBGAGxNWUeR0m8BteSNlzV3XoIDMAJkW0TeqfyOmYo88cvrBcgCxMAQlQDm9qG6dpWjdPHyUAiX1KADMAGxAcKBMmADF4xItIqziE-3cYNNyIzh4AXwBuMjIEFBgAFSQ0PQJiGuQQaLhGjEiIKui+MGAoKnAYVBAAZRAAW2QoAAsabwAeOphkAA8oZDBUAgBrZHgO+u7mgD4AChpEPigGOoBKJgaUHs4IAG06gF1ySiUTDzPiYMAwMDIADuXXezS+t3uvyuXxkXGMXEMvyeZFKQA" rel="nofollow noreferrer">PLAYGROUND</a></p>
|
[
{
"answer_id": 74615261,
"author": "Ashot Khachatryan",
"author_id": 12397183,
"author_profile": "https://Stackoverflow.com/users/12397183",
"pm_score": 0,
"selected": false,
"text": "class _OrderListState extends State<OrderList> with TickerProviderStateMixin {\n\n\n TabBar(\n controller: TabController(initialIndex: 3, vsync: this,length: 3)\n ..\n"
},
{
"answer_id": 74617387,
"author": "Yeasin Sheikh",
"author_id": 10157127,
"author_profile": "https://Stackoverflow.com/users/10157127",
"pm_score": 1,
"selected": false,
"text": "Navigator.pushReplacement(\n context,\n MaterialPageRoute(\n builder: (context) => OrderList(),\n settings: RouteSettings(arguments: 2)));\n class OrderList extends StatefulWidget {\n const OrderList({super.key});\n\n @override\n State<OrderList> createState() => _OrderListState();\n}\n\nclass _OrderListState extends State<OrderList>\n with SingleTickerProviderStateMixin {\n late final TabController controller = TabController(length: 3, vsync: this);\n @override\n Widget build(BuildContext context) {\n final int? callBackTabIndex =\n ModalRoute.of(context)?.settings.arguments as int?;\n if (callBackTabIndex != null && callBackTabIndex == 2) {\n WidgetsBinding.instance.addPostFrameCallback((timeStamp) {\n controller.animateTo(2);\n });\n }\n return Container(\n decoration: BoxDecoration(\n color: Colors.teal[300],\n ),\n child: Scaffold(\n // bottomNavigationBar: BottomNavigationBarForAppClient(indexNum: 1),\n backgroundColor: Colors.transparent,\n appBar: AppBar(\n title: const Text('Order List'),\n centerTitle: true,\n flexibleSpace: Container(\n decoration: BoxDecoration(\n color: Colors.teal[300],\n ),\n ),\n ),\n body: Column(\n children: [\n TabBar(\n controller: controller,\n tabs: [\n Tab(\n text: 'In Progress',\n ),\n Tab(\n text: 'Completed',\n ),\n Tab(\n text: 'Cancelled',\n ),\n ],\n onTap: (value) {},\n ),\n Expanded(\n child: TabBarView(controller: controller, children: [\n ElevatedButton(\n onPressed: () {\n Navigator.of(context).push(MaterialPageRoute(\n builder: (context) => AnotherWidget(),\n ));\n },\n child: Text(\"NA\")),\n Text(\"CompletedClient\"),\n Text(\"CancelledClient\"),\n ]),\n )\n ],\n ),\n ),\n );\n }\n}\n class AnotherWidget extends StatelessWidget {\n const AnotherWidget({super.key});\n\n @override\n Widget build(BuildContext context) {\n return Column(\n mainAxisSize: MainAxisSize.min,\n children: [\n ElevatedButton(\n onPressed: () {\n Navigator.pushReplacement(\n context,\n MaterialPageRoute(\n builder: (context) => OrderList(),\n settings: RouteSettings(arguments: 2)));\n },\n child: Text(\"NV\"),\n ),\n ],\n );\n }\n}\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74614836",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12582392/"
] |
74,614,843
|
<p>If you have two Xpaths you can join them with the <code>|</code> operator to return both their results in one result set. This essentially gives back the union of the two sets of elements. The example below gives back all <code>div</code>s and all <code>span</code>s on a website:</p>
<pre><code>//div | //span
</code></pre>
<p>What I need is the difference (subsection). I need all elements in the first Xpath group that are not in the second Xpath group. So far I have seen that there is an <code>except</code> operator but that only works in Xpath2. I need an Xpath1 solution. I have seen that the <code>not</code> function might help but I was not able to make it work.</p>
<p>As an example imagine the following:</p>
<pre><code><tr>
<td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
<td>5</td>
</tr>
</code></pre>
<p>In this example I would have the Xpath group <code>//tr/td</code>. I would want to <strong>exclude</strong> <code><td>1</td></code> and <code><td>4</td></code>. Although there are many ways to solve the problem I am specifically looking for a solution where I can say in an Xpath: "Here is a group of elements and exclude this group of elements from it".</p>
|
[
{
"answer_id": 74614932,
"author": "Prophet",
"author_id": 3485434,
"author_profile": "https://Stackoverflow.com/users/3485434",
"pm_score": 0,
"selected": false,
"text": "\"//tr/td[not(text()=`1`)][not(text()=`4`)]\"\n"
},
{
"answer_id": 74615054,
"author": "zx485",
"author_id": 1305969,
"author_profile": "https://Stackoverflow.com/users/1305969",
"pm_score": 2,
"selected": true,
"text": "self:: not() <root>\n <tr>\n <td>1</td>\n <td>2</td>\n <td>3</td>\n <td>4</td>\n <td>5</td>\n </tr> \n <dr>\n <td>1</td>\n <td>4</td>\n </dr> \n</root>\n //tr/td[not(self::*=//dr/td)]\n //tr/td[not(.=//dr/td)]\n <td>2</td>\n<td>3</td>\n<td>5</td>\n self::* . not(...) . self::* self::* . self::node()"
},
{
"answer_id": 74616646,
"author": "Michael Kay",
"author_id": 415448,
"author_profile": "https://Stackoverflow.com/users/415448",
"pm_score": 0,
"selected": false,
"text": "except E except F E[count(.|F) != count(F)] //td[not(ancestor::tr)]"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74614843",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12366148/"
] |
74,614,914
|
<p>I have a <code>df</code> as below</p>
<pre><code>df <- data.frame(col1 = c("a", "a", "b",
"b", "c", "c"),
col2 = c("x1", "x1.1", "x2", "x2.1", "x3", "x3.1"),
col3 = c(1, NA, 2, NA, 3, NA),
col4 = c(NA, 1, NA, 2, NA, 3))
df
col1 col2 col3 col4
1 a x1 1 NA
2 a x1.1 NA 1
3 b x2 2 NA
4 b x2.1 NA 2
5 c x3 3 NA
6 c x3.1 NA 3
</code></pre>
<p>I want to merge rows that have the same letter in column <code>col1</code> and filter rows in column <code>col2</code> by telling them <code>col2 %in% c(x1,x1.1) & col2 %in% c(x2,x2.1) & col3 %in% (x3,x3.1)</code>, simulatenously.</p>
<p>My desired output would be:</p>
<pre><code> col1 col2 col3 col4
1 a x1 1 1
2 b x2 2 2
3 c x3 3 3
</code></pre>
<p>One solution from my side is to call if <code>x == "x1"</code>, then <code>col4</code> will be filled by values assosicated with <code>x == "x1.1"</code></p>
<p>Any suggestions for this to <code>group_by</code> <code>col1</code>? Thank you in advance!</p>
<p><strong>Additional note</strong></p>
<p>I did draw a pic for visualization, that I think would be easier for you to imagine.</p>
<p><a href="https://i.stack.imgur.com/YSXMK.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/YSXMK.jpg" alt="enter image description here" /></a></p>
<p>The values in the actual dataset are different from the example here.</p>
<p><strong>Updated solution</strong>
I found a solution with the help of akrun see here: <a href="https://stackoverflow.com/questions/69789751/use-separate-after-mutate-and-across/69789799#69789799">Use ~separate after mutate and across</a></p>
<pre><code>df |>
mutate(col2 = substring(col2, 1,2)) |>
mutate_if(is.numeric, ~replace(., is.na(.), "")) |>
group_by(col1, col2) |>
summarise(across(c(col3, col4), ~toString(.)), .groups = "drop") |>
mutate(col3 = str_remove(col3, ",")) |>
mutate(col4 = str_remove(col4, ", "))
</code></pre>
<p>I'm still open to further suggestions, if anyone has any.</p>
|
[
{
"answer_id": 74615398,
"author": "MarBlo",
"author_id": 4282026,
"author_profile": "https://Stackoverflow.com/users/4282026",
"pm_score": 0,
"selected": false,
"text": "col2 coalesce col3 col4 NA distinct library(tidyverse)\n\ndf <- data.frame(col1 = c(\"a\", \"a\", \"b\",\n \"b\", \"c\", \"c\"),\n col2 = c(\"x1\", \"x1.1\", \"x2\", \"x2.1\", \"x3\", \"x3.1\"),\n col3 = c(1, NA, 2, NA, 3, NA),\n col4 = c(NA, 1, NA, 2, NA, 3))\n\n\ndf |> \n mutate(col2 = substring(col2, 1,2)) |> \n mutate(mycol = coalesce(col3, col4)) |>\n mutate(col3 = if_else(is.na(col3), mycol, col3),\n col4 = ifelse(is.na(col4), mycol, col4)) |> \n select(-c(mycol)) |> \n distinct()\n#> col1 col2 col3 col4\n#> 1 a x1 1 1\n#> 2 b x2 2 2\n#> 3 c x3 3 3\n"
},
{
"answer_id": 74615486,
"author": "TimTeaFan",
"author_id": 9349302,
"author_profile": "https://Stackoverflow.com/users/9349302",
"pm_score": 1,
"selected": false,
"text": "library(dplyr)\n\ndf %>% \n mutate(col2 = sub(\"\\\\.[0-9]+$\", \"\", col2),\n col3 = coalesce(col3, col4),\n col4 = coalesce(col4, col3)) %>% \n distinct()\n#> col1 col2 col3 col4\n#> 1 a x1 1 1\n#> 2 b x2 2 2\n#> 3 c x3 3 3\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74614914",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14518614/"
] |
74,614,948
|
<p>I have the following code in wwwroot/index.html.</p>
<pre><code><script src="_framework/blazor.webassembly.js"></script>
<script>
window.downloadFileFromStream = async (fileName, contentStreamReference) => {
const arrayBuffer = await contentStreamReference.arrayBuffer();
const blob = new Blob([arrayBuffer]);
const url = URL.createObjectURL(blob);
const anchorElement = document.createElement('a');
anchorElement.href = url;
anchorElement.download = fileName ?? '';
anchorElement.click();
anchorElement.remove();
URL.revokeObjectURL(url);
}
</script>
</code></pre>
<p>In the .razor page I have</p>
<pre><code>await JS.InvokeVoidAsync("downloadFileFromStream", fileName, streamRef);
</code></pre>
<p>This was all added per the Microsoft doc <a href="https://learn.microsoft.com/en-us/aspnet/core/blazor/file-downloads?view=aspnetcore-7.0" rel="nofollow noreferrer">https://learn.microsoft.com/en-us/aspnet/core/blazor/file-downloads?view=aspnetcore-7.0</a>, but I have the error:</p>
<p>Error: Could not find 'downloadFileFromStream' ('downloadFileFromStream' was undefined).</p>
|
[
{
"answer_id": 74615398,
"author": "MarBlo",
"author_id": 4282026,
"author_profile": "https://Stackoverflow.com/users/4282026",
"pm_score": 0,
"selected": false,
"text": "col2 coalesce col3 col4 NA distinct library(tidyverse)\n\ndf <- data.frame(col1 = c(\"a\", \"a\", \"b\",\n \"b\", \"c\", \"c\"),\n col2 = c(\"x1\", \"x1.1\", \"x2\", \"x2.1\", \"x3\", \"x3.1\"),\n col3 = c(1, NA, 2, NA, 3, NA),\n col4 = c(NA, 1, NA, 2, NA, 3))\n\n\ndf |> \n mutate(col2 = substring(col2, 1,2)) |> \n mutate(mycol = coalesce(col3, col4)) |>\n mutate(col3 = if_else(is.na(col3), mycol, col3),\n col4 = ifelse(is.na(col4), mycol, col4)) |> \n select(-c(mycol)) |> \n distinct()\n#> col1 col2 col3 col4\n#> 1 a x1 1 1\n#> 2 b x2 2 2\n#> 3 c x3 3 3\n"
},
{
"answer_id": 74615486,
"author": "TimTeaFan",
"author_id": 9349302,
"author_profile": "https://Stackoverflow.com/users/9349302",
"pm_score": 1,
"selected": false,
"text": "library(dplyr)\n\ndf %>% \n mutate(col2 = sub(\"\\\\.[0-9]+$\", \"\", col2),\n col3 = coalesce(col3, col4),\n col4 = coalesce(col4, col3)) %>% \n distinct()\n#> col1 col2 col3 col4\n#> 1 a x1 1 1\n#> 2 b x2 2 2\n#> 3 c x3 3 3\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74614948",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10481016/"
] |
74,614,956
|
<p>Is there a way to have a function take in a list and then return true or false for each item in the list if they are palindromes? Below is what I have tried but I would like the console to look like this:</p>
<p>True
False
True</p>
<pre><code>x=[121,13,155551]
def palindrome_check(x):
for num_from__list in x:
if str(num_from__list) == str(num_from__list[::-1]):
return True
continue
else:
return False
print(palindrome_check(x))
</code></pre>
|
[
{
"answer_id": 74615016,
"author": "Guillaume BEDOYA",
"author_id": 20522241,
"author_profile": "https://Stackoverflow.com/users/20522241",
"pm_score": 1,
"selected": false,
"text": "x = [121,13,155551]\n\ndef palindrome_check(x):\n res = []\n for num_from__list in x:\n res.append(str(num_from__list) == str(num_from__list)[::-1])\n return res\n\nprint(palindrome_check(x))\n x = [121,13,155551]\n\ndef palindrome_check(x):\n return [str(num_from__list) == str(num_from__list[::-1]) for num_from__list in x]\n\nprint(palindrome_check(x))\n"
},
{
"answer_id": 74615057,
"author": "Jim Nilsson",
"author_id": 9576577,
"author_profile": "https://Stackoverflow.com/users/9576577",
"pm_score": 1,
"selected": false,
"text": "palindrome_check def palindrome_check(num):\n return str(num) == str(num)[::-1]\n\nnumbers = [121, 13, 155551]\n\nresults = [palindrome_check(num) for num in numbers]\nprint(results)\n True False"
},
{
"answer_id": 74615059,
"author": "0x0fba",
"author_id": 20339407,
"author_profile": "https://Stackoverflow.com/users/20339407",
"pm_score": 2,
"selected": true,
"text": "return yield def palindrome_check(x):\n for num_from__list in x:\n if str(num_from__list) == str(num_from__list[::-1]):\n yield True\n else:\n yield False\n\nprint(list(palindrome_check(x)))\n"
},
{
"answer_id": 74615836,
"author": "s3c",
"author_id": 9583480,
"author_profile": "https://Stackoverflow.com/users/9583480",
"pm_score": 0,
"selected": false,
"text": "def palindrome_check(x):\n return \" \".join([str(str(n) == str(n)[::-1]) for n in x])\n myList = [function(n) for n in x]\n# same as\nmyList = list()\nfor n in x:\n myList.append(function(n))\n# eg. [n for n in x] === [121, 13, 155551]\n # number\nn # eg. 123\n# string\nstr(n) # eg. '123'\n# mirrored string\nstr(n)[::-1] # eg. '321'\n# eg. [str(n) for n in x] === ['121', '13', '155551']\n# [str(n)[::-1] for n in x] === ['121', '31', '155551']\n str(n) == str(n)[::-1] # True/False\n# eg. [str(n) == str(n)[::-1] for n in x] === [True, False, True]\n str(str(n) == str(n)[::-1]) # 'True'/'False'\n# eg. [str(str(n) == str(n)[::-1]) for n in x] === ['True', 'False', 'True']\n # eg. \"xx\".join([\"A\", \"B\", \"C\"]) returns 'AxxBxxC'\n\" \".join([str(str(n) == str(n)[::-1]) for n in x]) # 'True False True'\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74614956",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16569701/"
] |
74,614,966
|
<p>I have the next matrix:</p>
<pre><code>structure(list(`1` = c(0, 0, NA, NA, NA, NA, 0, 0, NA, NA, NA,
1, NA, NA, NA), `2` = c(1, 0, NA, NA, NA, NA, NA, 0, NA, NA,
NA, 1, NA, NA, NA), `4` = c(NA, NA, 0, 1, 1, 0, NA, NA, 0, 1,
1, NA, 1, 0, 0), `5` = c(NA, NA, 0, 1, 1, 0, NA, NA, 1, 1, NA,
NA, 1, 0, 1), `6` = c(NA, NA, 0, 1, 1, 0, NA, NA, 1, 0, NA, NA,
1, 0, NA), `7` = c(NA, NA, NA, 1, 1, 0, NA, NA, 0, 1, NA, NA,
1, 0, NA), `8` = c(NA, NA, NA, 1, 0, 0, NA, NA, 1, 0, NA, NA,
1, 0, NA)), row.names = c(NA, 15L), class = "data.frame")
</code></pre>
<p>I want to create the following matrix based in the previous matrix, I have created the next code but it does not work.</p>
<pre><code>for(i in 1:nrow(mat)){
for(j in 1:7){
if(mat[i,j]==0){
next }else{
if(mat[i,j]==1){
mat[i,j:7]<-1
}else{
if(is.na(mat[i,j])){
mat[i,j]<-NA
}}}
}
}
</code></pre>
<p>The idea is for each row for example:</p>
<p>0,0,0,1,0,0,0</p>
<ul>
<li>if in the row there is a 1, then all the elements after this 1 should be equals 1.</li>
<li>if there is an NA then this value should be equals NA</li>
</ul>
<p>The idea is to create a matrix describing an intervention over time. I mean 1 is when the intervention is applied.</p>
<ul>
<li>If I have something like this:
0,NA,NA,1,0,NA,1
I want to get for example:
0,NA,NA,1,1,NA,1</li>
</ul>
<p>I hope you can help me with it.</p>
|
[
{
"answer_id": 74615099,
"author": "Maël",
"author_id": 13460602,
"author_profile": "https://Stackoverflow.com/users/13460602",
"pm_score": 1,
"selected": false,
"text": "cummax apply t(apply(mat, 1, \\(x) cummax(ifelse(is.na(x), 0, x)) + x*0))\n 1 2 4 5 6 7 8\n1 0 1 NA NA NA NA NA\n2 0 0 NA NA NA NA NA\n3 NA NA 0 0 0 NA NA\n4 NA NA 1 1 1 1 1\n5 NA NA 1 1 1 1 1\n6 NA NA 0 0 0 0 0\n7 0 NA NA NA NA NA NA\n8 0 0 NA NA NA NA NA\n9 NA NA 0 1 1 1 1\n10 NA NA 1 1 1 1 1\n11 NA NA 1 NA NA NA NA\n12 1 1 NA NA NA NA NA\n13 NA NA 1 1 1 1 1\n14 NA NA 0 0 0 0 0\n15 NA NA 0 1 NA NA NA\n"
},
{
"answer_id": 74615489,
"author": "jblood94",
"author_id": 9463489,
"author_profile": "https://Stackoverflow.com/users/9463489",
"pm_score": 0,
"selected": false,
"text": "cummax f <- function(m) {\n blnNA <- is.na(m)\n m[blnNA] <- 0\n m <- matrix(cummax(c(t(m + 1:nrow(m)))), nrow(m), ncol(m), 1) - 1:nrow(m)\n m[blnNA] <- NA\n m\n}\n\nf(m)\n#> [,1] [,2] [,3] [,4] [,5] [,6] [,7]\n#> [1,] 0 1 NA NA NA NA NA\n#> [2,] 0 0 NA NA NA NA NA\n#> [3,] NA NA 0 0 0 NA NA\n#> [4,] NA NA 1 1 1 1 1\n#> [5,] NA NA 1 1 1 1 1\n#> [6,] NA NA 0 0 0 0 0\n#> [7,] 0 NA NA NA NA NA NA\n#> [8,] 0 0 NA NA NA NA NA\n#> [9,] NA NA 0 1 1 1 1\n#> [10,] NA NA 1 1 1 1 1\n#> [11,] NA NA 1 NA NA NA NA\n#> [12,] 1 1 NA NA NA NA NA\n#> [13,] NA NA 1 1 1 1 1\n#> [14,] NA NA 0 0 0 0 0\n#> [15,] NA NA 0 1 NA NA NA\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74614966",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3483060/"
] |
74,615,011
|
<p>I'm stuck on an exercise where I should do a function which makes a tuple out of 3 given numbers and returns tuple following these rules:</p>
<ul>
<li>1st element must be the smallest parameter</li>
<li>2nd element must be the biggest parameter</li>
<li>3rd element is the sum of parameters</li>
</ul>
<p>For example:</p>
<pre><code>> print(do_tuple(5, 3, -1))
# (-1, 5, 7)
</code></pre>
<p>What I have so far:</p>
<pre><code>def do_tuple(x: int, y: int, z: int):
tuple_ = (x,y,z)
summ = x + y + z
mini = min(tuple_)
maxi = max(tuple_)
if __name__ == "__main__":
print(do_tuple(5, 3, -1))
</code></pre>
<p>I know I should be able to sort and return these values according to the criteria but I can't work my head around it..</p>
|
[
{
"answer_id": 74615099,
"author": "Maël",
"author_id": 13460602,
"author_profile": "https://Stackoverflow.com/users/13460602",
"pm_score": 1,
"selected": false,
"text": "cummax apply t(apply(mat, 1, \\(x) cummax(ifelse(is.na(x), 0, x)) + x*0))\n 1 2 4 5 6 7 8\n1 0 1 NA NA NA NA NA\n2 0 0 NA NA NA NA NA\n3 NA NA 0 0 0 NA NA\n4 NA NA 1 1 1 1 1\n5 NA NA 1 1 1 1 1\n6 NA NA 0 0 0 0 0\n7 0 NA NA NA NA NA NA\n8 0 0 NA NA NA NA NA\n9 NA NA 0 1 1 1 1\n10 NA NA 1 1 1 1 1\n11 NA NA 1 NA NA NA NA\n12 1 1 NA NA NA NA NA\n13 NA NA 1 1 1 1 1\n14 NA NA 0 0 0 0 0\n15 NA NA 0 1 NA NA NA\n"
},
{
"answer_id": 74615489,
"author": "jblood94",
"author_id": 9463489,
"author_profile": "https://Stackoverflow.com/users/9463489",
"pm_score": 0,
"selected": false,
"text": "cummax f <- function(m) {\n blnNA <- is.na(m)\n m[blnNA] <- 0\n m <- matrix(cummax(c(t(m + 1:nrow(m)))), nrow(m), ncol(m), 1) - 1:nrow(m)\n m[blnNA] <- NA\n m\n}\n\nf(m)\n#> [,1] [,2] [,3] [,4] [,5] [,6] [,7]\n#> [1,] 0 1 NA NA NA NA NA\n#> [2,] 0 0 NA NA NA NA NA\n#> [3,] NA NA 0 0 0 NA NA\n#> [4,] NA NA 1 1 1 1 1\n#> [5,] NA NA 1 1 1 1 1\n#> [6,] NA NA 0 0 0 0 0\n#> [7,] 0 NA NA NA NA NA NA\n#> [8,] 0 0 NA NA NA NA NA\n#> [9,] NA NA 0 1 1 1 1\n#> [10,] NA NA 1 1 1 1 1\n#> [11,] NA NA 1 NA NA NA NA\n#> [12,] 1 1 NA NA NA NA NA\n#> [13,] NA NA 1 1 1 1 1\n#> [14,] NA NA 0 0 0 0 0\n#> [15,] NA NA 0 1 NA NA NA\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74615011",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20633646/"
] |
74,615,041
|
<p>I have a PHP code</p>
<pre><code><?php $j = 0; foreach($v->valeur as $valeur) { ?>
<input type="checkbox"
class=" "
name="check<?php echo $v->id; ?>[]"
value="<?php echo $j; ?>"
<?php if(strpos($v->active,','.$j.',')!==false) echo ' checked'; ?>
data-labelauty="<?php echo $valeur; ?>" />
<?php echo $valeur.str_repeat('&nbsp;', 2); ?>
<?php ++$j; ?>[![enter image description here][1]][1]
<?php } ?>
</code></pre>
<p>where
<code>echo $valeur.str_repeat('&nbsp;', 2);</code> generates " Djembe ".
My problem is that I want the checkbox and the text to be on THE SAME LINE reagardless of screen width.
<a href="https://i.imgur.com/M0kMZyA.png" rel="nofollow noreferrer">See some code and desirde output</a></p>
|
[
{
"answer_id": 74615099,
"author": "Maël",
"author_id": 13460602,
"author_profile": "https://Stackoverflow.com/users/13460602",
"pm_score": 1,
"selected": false,
"text": "cummax apply t(apply(mat, 1, \\(x) cummax(ifelse(is.na(x), 0, x)) + x*0))\n 1 2 4 5 6 7 8\n1 0 1 NA NA NA NA NA\n2 0 0 NA NA NA NA NA\n3 NA NA 0 0 0 NA NA\n4 NA NA 1 1 1 1 1\n5 NA NA 1 1 1 1 1\n6 NA NA 0 0 0 0 0\n7 0 NA NA NA NA NA NA\n8 0 0 NA NA NA NA NA\n9 NA NA 0 1 1 1 1\n10 NA NA 1 1 1 1 1\n11 NA NA 1 NA NA NA NA\n12 1 1 NA NA NA NA NA\n13 NA NA 1 1 1 1 1\n14 NA NA 0 0 0 0 0\n15 NA NA 0 1 NA NA NA\n"
},
{
"answer_id": 74615489,
"author": "jblood94",
"author_id": 9463489,
"author_profile": "https://Stackoverflow.com/users/9463489",
"pm_score": 0,
"selected": false,
"text": "cummax f <- function(m) {\n blnNA <- is.na(m)\n m[blnNA] <- 0\n m <- matrix(cummax(c(t(m + 1:nrow(m)))), nrow(m), ncol(m), 1) - 1:nrow(m)\n m[blnNA] <- NA\n m\n}\n\nf(m)\n#> [,1] [,2] [,3] [,4] [,5] [,6] [,7]\n#> [1,] 0 1 NA NA NA NA NA\n#> [2,] 0 0 NA NA NA NA NA\n#> [3,] NA NA 0 0 0 NA NA\n#> [4,] NA NA 1 1 1 1 1\n#> [5,] NA NA 1 1 1 1 1\n#> [6,] NA NA 0 0 0 0 0\n#> [7,] 0 NA NA NA NA NA NA\n#> [8,] 0 0 NA NA NA NA NA\n#> [9,] NA NA 0 1 1 1 1\n#> [10,] NA NA 1 1 1 1 1\n#> [11,] NA NA 1 NA NA NA NA\n#> [12,] 1 1 NA NA NA NA NA\n#> [13,] NA NA 1 1 1 1 1\n#> [14,] NA NA 0 0 0 0 0\n#> [15,] NA NA 0 1 NA NA NA\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74615041",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13563009/"
] |
74,615,065
|
<p>now I'm making a user Authentication system, but I'm having trouble with javascript's process order. Here is my code.</p>
<pre><code>const isAuthenticated = async (username, password) => {
//this User.finOne is async function
User.findOne({ username: username }, function (err, foundUser) {
if (err) {
console.log(err);
}
else {
if (foundUser) {
if (foundUser.password === password) {
console.log("ID:", foundUser.id);
console.log("NAME:", foundUser.username);
return foundUser.id
}
}
else {
return 0;
}
}
});
}
app.post("/login", async function (req, res) {
const userName = req.body.username;
const password = md5(req.body.password);
let userID = await isAuthenticated(userName, password);
// userID becomes undefined
console.log("userID", userID);
if (userID === 0 || userID == undefined) {
const status = 401
const message = 'Incorrect username or password'
res.status(status).json({ status, message })
return
}
const accessToken = createToken({ id: isAuthenticated(userName, password) })
console.log("here is token", accessToken);
const responseJson = {
success: true,
username: userName,
userID: userID
}
res.cookie('JWTcookie', accessToken, { httpOnly: true })
res.status(200).json(responseJson)
</code></pre>
<p>When a user logged in with a correct password and username, this API is supposed to return cookie. This cookie itself works fine, but the problem is that " if (userID === 0 || userID == undefined)" is processed earlier than the function isAuthenticated().
When I checked the order, isAuthenticated is processed later. To prevent this, I tried using async await, so that the job stops at let userID = await isAuthenticated(userName, password);. But this didn't work.</p>
<p>If anyone point out why this programming is working in this order, I really appreciate it. Thank you.</p>
|
[
{
"answer_id": 74615099,
"author": "Maël",
"author_id": 13460602,
"author_profile": "https://Stackoverflow.com/users/13460602",
"pm_score": 1,
"selected": false,
"text": "cummax apply t(apply(mat, 1, \\(x) cummax(ifelse(is.na(x), 0, x)) + x*0))\n 1 2 4 5 6 7 8\n1 0 1 NA NA NA NA NA\n2 0 0 NA NA NA NA NA\n3 NA NA 0 0 0 NA NA\n4 NA NA 1 1 1 1 1\n5 NA NA 1 1 1 1 1\n6 NA NA 0 0 0 0 0\n7 0 NA NA NA NA NA NA\n8 0 0 NA NA NA NA NA\n9 NA NA 0 1 1 1 1\n10 NA NA 1 1 1 1 1\n11 NA NA 1 NA NA NA NA\n12 1 1 NA NA NA NA NA\n13 NA NA 1 1 1 1 1\n14 NA NA 0 0 0 0 0\n15 NA NA 0 1 NA NA NA\n"
},
{
"answer_id": 74615489,
"author": "jblood94",
"author_id": 9463489,
"author_profile": "https://Stackoverflow.com/users/9463489",
"pm_score": 0,
"selected": false,
"text": "cummax f <- function(m) {\n blnNA <- is.na(m)\n m[blnNA] <- 0\n m <- matrix(cummax(c(t(m + 1:nrow(m)))), nrow(m), ncol(m), 1) - 1:nrow(m)\n m[blnNA] <- NA\n m\n}\n\nf(m)\n#> [,1] [,2] [,3] [,4] [,5] [,6] [,7]\n#> [1,] 0 1 NA NA NA NA NA\n#> [2,] 0 0 NA NA NA NA NA\n#> [3,] NA NA 0 0 0 NA NA\n#> [4,] NA NA 1 1 1 1 1\n#> [5,] NA NA 1 1 1 1 1\n#> [6,] NA NA 0 0 0 0 0\n#> [7,] 0 NA NA NA NA NA NA\n#> [8,] 0 0 NA NA NA NA NA\n#> [9,] NA NA 0 1 1 1 1\n#> [10,] NA NA 1 1 1 1 1\n#> [11,] NA NA 1 NA NA NA NA\n#> [12,] 1 1 NA NA NA NA NA\n#> [13,] NA NA 1 1 1 1 1\n#> [14,] NA NA 0 0 0 0 0\n#> [15,] NA NA 0 1 NA NA NA\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74615065",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17232360/"
] |
74,615,085
|
<p>This is part of a homework assignment. As part of an administration script, one of the tasks is to open an interactive Powershell prompt on a remote computer using preset credentials from the script. Opening one from the regular interactive shell works fine, however opening one from a script has proven to be difficult.</p>
<p>I have tried the following:</p>
<pre><code>$password = ConvertTo-SecureString -String "password" -AsPlainText -Force`
$credentials = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList "username", $password
$session = New-PSSession -Credential $credentials -ComputerName "remote-computer"
Enter-PSSession -Session $session
</code></pre>
<p>Doing this from an interactive shell works as expected and spawns an interactive prompt on the remote machine, however doing this from a script results in a non-responsive shell as it expects further input from the script.</p>
<p>If I attempt <code>Start-Process -Wait -NoNewWindow -FilePath "powershell"</code> or tell <code>Start-Process</code> to execute Powershell via cmd.exe after entering a remote Powershell session it opens a local instance instead.</p>
|
[
{
"answer_id": 74615099,
"author": "Maël",
"author_id": 13460602,
"author_profile": "https://Stackoverflow.com/users/13460602",
"pm_score": 1,
"selected": false,
"text": "cummax apply t(apply(mat, 1, \\(x) cummax(ifelse(is.na(x), 0, x)) + x*0))\n 1 2 4 5 6 7 8\n1 0 1 NA NA NA NA NA\n2 0 0 NA NA NA NA NA\n3 NA NA 0 0 0 NA NA\n4 NA NA 1 1 1 1 1\n5 NA NA 1 1 1 1 1\n6 NA NA 0 0 0 0 0\n7 0 NA NA NA NA NA NA\n8 0 0 NA NA NA NA NA\n9 NA NA 0 1 1 1 1\n10 NA NA 1 1 1 1 1\n11 NA NA 1 NA NA NA NA\n12 1 1 NA NA NA NA NA\n13 NA NA 1 1 1 1 1\n14 NA NA 0 0 0 0 0\n15 NA NA 0 1 NA NA NA\n"
},
{
"answer_id": 74615489,
"author": "jblood94",
"author_id": 9463489,
"author_profile": "https://Stackoverflow.com/users/9463489",
"pm_score": 0,
"selected": false,
"text": "cummax f <- function(m) {\n blnNA <- is.na(m)\n m[blnNA] <- 0\n m <- matrix(cummax(c(t(m + 1:nrow(m)))), nrow(m), ncol(m), 1) - 1:nrow(m)\n m[blnNA] <- NA\n m\n}\n\nf(m)\n#> [,1] [,2] [,3] [,4] [,5] [,6] [,7]\n#> [1,] 0 1 NA NA NA NA NA\n#> [2,] 0 0 NA NA NA NA NA\n#> [3,] NA NA 0 0 0 NA NA\n#> [4,] NA NA 1 1 1 1 1\n#> [5,] NA NA 1 1 1 1 1\n#> [6,] NA NA 0 0 0 0 0\n#> [7,] 0 NA NA NA NA NA NA\n#> [8,] 0 0 NA NA NA NA NA\n#> [9,] NA NA 0 1 1 1 1\n#> [10,] NA NA 1 1 1 1 1\n#> [11,] NA NA 1 NA NA NA NA\n#> [12,] 1 1 NA NA NA NA NA\n#> [13,] NA NA 1 1 1 1 1\n#> [14,] NA NA 0 0 0 0 0\n#> [15,] NA NA 0 1 NA NA NA\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74615085",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20633643/"
] |
74,615,095
|
<p>The <code>Series.str.find()</code> function in pandas seems to take only a single integer for the start location. I have a Series containing strings and an array of start positions, and I want to find the position of a given substring starting from the corresponding position of each element as follows:</p>
<pre><code>a = pd.Series(data=['aaba', 'ababc', 'caaauuab'])
a.str.find('b', start=[0, 1, 2]) # returns a series of NaNs
</code></pre>
<p>I can do this using list comprehension:</p>
<pre><code>[s.find('b', pos) for s, pos in zip(a.values, [0, 1, 2])]
</code></pre>
<p>Is there a function in numpy or pandas that can do this directly and faster? Also, is there one that can take an array of substrings as well?</p>
|
[
{
"answer_id": 74615099,
"author": "Maël",
"author_id": 13460602,
"author_profile": "https://Stackoverflow.com/users/13460602",
"pm_score": 1,
"selected": false,
"text": "cummax apply t(apply(mat, 1, \\(x) cummax(ifelse(is.na(x), 0, x)) + x*0))\n 1 2 4 5 6 7 8\n1 0 1 NA NA NA NA NA\n2 0 0 NA NA NA NA NA\n3 NA NA 0 0 0 NA NA\n4 NA NA 1 1 1 1 1\n5 NA NA 1 1 1 1 1\n6 NA NA 0 0 0 0 0\n7 0 NA NA NA NA NA NA\n8 0 0 NA NA NA NA NA\n9 NA NA 0 1 1 1 1\n10 NA NA 1 1 1 1 1\n11 NA NA 1 NA NA NA NA\n12 1 1 NA NA NA NA NA\n13 NA NA 1 1 1 1 1\n14 NA NA 0 0 0 0 0\n15 NA NA 0 1 NA NA NA\n"
},
{
"answer_id": 74615489,
"author": "jblood94",
"author_id": 9463489,
"author_profile": "https://Stackoverflow.com/users/9463489",
"pm_score": 0,
"selected": false,
"text": "cummax f <- function(m) {\n blnNA <- is.na(m)\n m[blnNA] <- 0\n m <- matrix(cummax(c(t(m + 1:nrow(m)))), nrow(m), ncol(m), 1) - 1:nrow(m)\n m[blnNA] <- NA\n m\n}\n\nf(m)\n#> [,1] [,2] [,3] [,4] [,5] [,6] [,7]\n#> [1,] 0 1 NA NA NA NA NA\n#> [2,] 0 0 NA NA NA NA NA\n#> [3,] NA NA 0 0 0 NA NA\n#> [4,] NA NA 1 1 1 1 1\n#> [5,] NA NA 1 1 1 1 1\n#> [6,] NA NA 0 0 0 0 0\n#> [7,] 0 NA NA NA NA NA NA\n#> [8,] 0 0 NA NA NA NA NA\n#> [9,] NA NA 0 1 1 1 1\n#> [10,] NA NA 1 1 1 1 1\n#> [11,] NA NA 1 NA NA NA NA\n#> [12,] 1 1 NA NA NA NA NA\n#> [13,] NA NA 1 1 1 1 1\n#> [14,] NA NA 0 0 0 0 0\n#> [15,] NA NA 0 1 NA NA NA\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74615095",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/508222/"
] |
74,615,120
|
<p>I have the following df as example:</p>
<pre><code>df <- data.frame(status = c(rep("egr", 5), rep("ing", 5)),
ua = c(1, 1, 1, 1, 1, 1, 1, 1, 2, 2),
fam = c(rep("fam1", 2), rep("fam2", 7), "fam3"),
spp = c(rep("spp1", 3), rep("spp2", 3), "rep4", "rep5", rep("spp6", 2)))
</code></pre>
<p>What I'm trying to do is <code>summarise</code> the count of strings based on a <code>group_by</code> of the <code>ua</code> column and the differences between the names of <code>fam</code> and <code>spp</code> when comparing the two <code>status</code> (ing, egr).</p>
<p>In other words, for each <code>ua</code>, I want to count via <code>summarise</code> the differences between <code>ing</code> - <code>egr</code> for each other column (<code>spp</code> and <code>fam</code>). I'm having an issue specifically assigning the <code>status</code> column as the base for the differences, i.e., getting the names of <code>spp</code> and <code>fam</code> at each <code>status</code> before summarizing. A <code>setdiff</code> between <code>fam</code> or <code>spp</code> from each <code>status</code> seems enough, but I'm failing at, again, assigning the <code>status</code> before the summary.</p>
<p>EDIT:</p>
<p>Getting the different number of names in <code>ing</code> minus <code>egr</code>, an output might look like</p>
<pre><code>output <- data.frame(ua = c(1, 2),
fam = c(-1, 2),
spp = c(1, 1))
</code></pre>
<p>Example rationale:</p>
<p><code>ua</code> 1 has, considering both <code>egr</code> and <code>ing</code>, two names of <code>fam</code> (fam1 and fam2). Since fam2 is shared between <code>ing</code> and <code>egr</code>, the diff is 0. But <code>egr</code> has also <code>fam1</code>, then the difference became -1.</p>
<p>Another example: <code>ua</code> 2 has no <code>egr</code>, then the sum is simply 2 (fam2 and fam3).</p>
<p>Again: <code>ua</code> 1 has, considering both <code>ing</code> and <code>egr</code>, four <code>spp</code> (spp1, spp2, rep4, rep5). Doing the <code>ing</code> minus <code>egr</code>, it must result in 1 because <code>ing</code> has two unique names and (rep4 and rep5) and <code>egr</code> one (spp1). Thus, the diff of <code>ing</code> - <code>egr</code> is 1 since spp2 is shared</p>
<p>I hope this is understandable, it's kinda tricky to explain.</p>
|
[
{
"answer_id": 74615099,
"author": "Maël",
"author_id": 13460602,
"author_profile": "https://Stackoverflow.com/users/13460602",
"pm_score": 1,
"selected": false,
"text": "cummax apply t(apply(mat, 1, \\(x) cummax(ifelse(is.na(x), 0, x)) + x*0))\n 1 2 4 5 6 7 8\n1 0 1 NA NA NA NA NA\n2 0 0 NA NA NA NA NA\n3 NA NA 0 0 0 NA NA\n4 NA NA 1 1 1 1 1\n5 NA NA 1 1 1 1 1\n6 NA NA 0 0 0 0 0\n7 0 NA NA NA NA NA NA\n8 0 0 NA NA NA NA NA\n9 NA NA 0 1 1 1 1\n10 NA NA 1 1 1 1 1\n11 NA NA 1 NA NA NA NA\n12 1 1 NA NA NA NA NA\n13 NA NA 1 1 1 1 1\n14 NA NA 0 0 0 0 0\n15 NA NA 0 1 NA NA NA\n"
},
{
"answer_id": 74615489,
"author": "jblood94",
"author_id": 9463489,
"author_profile": "https://Stackoverflow.com/users/9463489",
"pm_score": 0,
"selected": false,
"text": "cummax f <- function(m) {\n blnNA <- is.na(m)\n m[blnNA] <- 0\n m <- matrix(cummax(c(t(m + 1:nrow(m)))), nrow(m), ncol(m), 1) - 1:nrow(m)\n m[blnNA] <- NA\n m\n}\n\nf(m)\n#> [,1] [,2] [,3] [,4] [,5] [,6] [,7]\n#> [1,] 0 1 NA NA NA NA NA\n#> [2,] 0 0 NA NA NA NA NA\n#> [3,] NA NA 0 0 0 NA NA\n#> [4,] NA NA 1 1 1 1 1\n#> [5,] NA NA 1 1 1 1 1\n#> [6,] NA NA 0 0 0 0 0\n#> [7,] 0 NA NA NA NA NA NA\n#> [8,] 0 0 NA NA NA NA NA\n#> [9,] NA NA 0 1 1 1 1\n#> [10,] NA NA 1 1 1 1 1\n#> [11,] NA NA 1 NA NA NA NA\n#> [12,] 1 1 NA NA NA NA NA\n#> [13,] NA NA 1 1 1 1 1\n#> [14,] NA NA 0 0 0 0 0\n#> [15,] NA NA 0 1 NA NA NA\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74615120",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15108186/"
] |
74,615,121
|
<p>i'm trying to add navigation between auth pages in flutter using TapGestureRecognizer on a TextSpan. Everything is set up but still the clicked text does not navigate to the preferred page.</p>
<p>part of the login ui where i'm using TapGestureRecognizer:</p>
<pre><code>RichText(
text: TextSpan(
text: 'No account',
style: TextStyle(color: Colors.black),
children: [
TextSpan(
recognizer: TapGestureRecognizer()
..onTap = () => widget.onClickedSignUp,
text: 'Click Here',
style: TextStyle(
decoration: TextDecoration.underline,
color: Colors.black))
]))
</code></pre>
<p>first part of the login.dart:</p>
<pre><code>class LoginScreen extends StatefulWidget {
final VoidCallback onClickedSignUp;
const LoginScreen({Key? key, required this.onClickedSignUp})
: super(key: key);
@override
State<LoginScreen> createState() => _LoginScreenState();
}
class _LoginScreenState extends State<LoginScreen> {
TextEditingController emailController = TextEditingController();
TextEditingController passwordController = TextEditingController();
final navigatorKey = GlobalKey<NavigatorState>();
final formKey = GlobalKey<FormState>();
@override
void dispose() {
emailController.dispose();
passwordController.dispose();
super.dispose();
}
</code></pre>
<p>auth.dart:</p>
<pre><code>class _AuthPageState extends State<AuthPage> {
bool isLogin = true;
@override
Widget build(BuildContext context) => isLogin
? LoginScreen(onClickedSignUp: toggle)
: SignUpScreen(onClickedSignIn: toggle);
void toggle() {
setState(() {
isLogin != isLogin;
});
}
}
</code></pre>
<p>main.dart:</p>
<pre><code>class MainPage extends StatelessWidget {
const MainPage({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
body: StreamBuilder<User?>(
stream: FirebaseAuth.instance.authStateChanges(),
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return Center(child: CircularProgressIndicator());
} else if (snapshot.hasError) {
return Center(child: Text('Something went wrong'));
} else if (snapshot.hasData) {
return HomeScreen();
} else {
return AuthPage();
}
},
));
}
}
</code></pre>
<p>I'd be grateful if anyone can help me!</p>
|
[
{
"answer_id": 74615175,
"author": "Ashot Khachatryan",
"author_id": 12397183,
"author_profile": "https://Stackoverflow.com/users/12397183",
"pm_score": 1,
"selected": false,
"text": "..onTap = () => widget.onClickedSignUp.call(),\n ..onTap = widget.onClickedSignUp,\n \n"
},
{
"answer_id": 74615510,
"author": "Yeasin Sheikh",
"author_id": 10157127,
"author_profile": "https://Stackoverflow.com/users/10157127",
"pm_score": 3,
"selected": true,
"text": "() TextSpan(\n recognizer: TapGestureRecognizer()\n ..onTap = () => widget.onClickedSignUp(),\n isLogin = !isLogin; \nclass MainPage extends StatelessWidget {\n const MainPage({super.key});\n\n @override\n Widget build(BuildContext context) {\n return Scaffold(body: AuthPage());\n }\n}\n\nclass AuthPage extends StatefulWidget {\n const AuthPage({super.key});\n\n @override\n State<AuthPage> createState() => _AuthPageState();\n}\n\nclass _AuthPageState extends State<AuthPage> {\n bool isLogin = true;\n void toggle() {\n debugPrint(\"yay\");\n setState(() {\n isLogin = !isLogin;\n });\n }\n\n @override\n Widget build(BuildContext context) => Column(\n children: [\n Text(\"$isLogin\"),\n SizedBox(\n height: 400,\n width: 400,\n child: isLogin ? LoginScreen(onClickedSignUp: toggle) : Text(\"F\"),\n )\n ],\n );\n}\n\nclass LoginScreen extends StatefulWidget {\n const LoginScreen({Key? key, required this.onClickedSignUp})\n : super(key: key);\n\n final VoidCallback onClickedSignUp;\n\n @override\n State<LoginScreen> createState() => _LogInScreenState();\n}\n\nclass _LogInScreenState extends State<LoginScreen> {\n @override\n Widget build(BuildContext context) {\n return Scaffold(\n body: RichText(\n text: TextSpan(\n text: 'No account',\n style: TextStyle(color: Colors.black),\n children: [\n TextSpan(\n recognizer: TapGestureRecognizer()\n ..onTap = () => widget.onClickedSignUp(),\n text: 'Click Here',\n style: TextStyle(\n decoration: TextDecoration.underline, color: Colors.black))\n ])),\n );\n }\n}\n```\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74615121",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12785864/"
] |
74,615,226
|
<p>I need to programmatically delete all caches of my Xamarin.Forms application called MyXFApp, the same way as the button 'Clear Cache' of the Setting/Apps/MyXFApp/Storage page.</p>
<p>I read the Android and Xamarin.Forms official documentations, and used the methods getGetCacheDir() and GetExternalCacheDir() to retrieve the cache directories, and I delete both of them.
After deleting both directories, I expect to see the cache size to 0 byte within the Setting/Apps/MyXFApp/Storage page. But the cache size displayed in the Setting/Apps/MyXFApp/Storage page has indeed diminished, but is not strictly equal to 0 byte, and I do not understand why?</p>
<p>Is there any other directory I must delete in order to fully clear my Xamarin.Forms cache? Or is it a bug of the Setting/Apps/MyXFApp/Storage displayed cache size?</p>
<p>And otherwise, what is the correct way or difference(s) between these two methods?</p>
<p>I tried to delete directories obtained from methods getGetCacheDir() and GetExternalCacheDir().
Expected to see cache size of 0B in the Setting/Apps/MyXFApp/Storage page, but I see 20KB and not 0B.</p>
|
[
{
"answer_id": 74615175,
"author": "Ashot Khachatryan",
"author_id": 12397183,
"author_profile": "https://Stackoverflow.com/users/12397183",
"pm_score": 1,
"selected": false,
"text": "..onTap = () => widget.onClickedSignUp.call(),\n ..onTap = widget.onClickedSignUp,\n \n"
},
{
"answer_id": 74615510,
"author": "Yeasin Sheikh",
"author_id": 10157127,
"author_profile": "https://Stackoverflow.com/users/10157127",
"pm_score": 3,
"selected": true,
"text": "() TextSpan(\n recognizer: TapGestureRecognizer()\n ..onTap = () => widget.onClickedSignUp(),\n isLogin = !isLogin; \nclass MainPage extends StatelessWidget {\n const MainPage({super.key});\n\n @override\n Widget build(BuildContext context) {\n return Scaffold(body: AuthPage());\n }\n}\n\nclass AuthPage extends StatefulWidget {\n const AuthPage({super.key});\n\n @override\n State<AuthPage> createState() => _AuthPageState();\n}\n\nclass _AuthPageState extends State<AuthPage> {\n bool isLogin = true;\n void toggle() {\n debugPrint(\"yay\");\n setState(() {\n isLogin = !isLogin;\n });\n }\n\n @override\n Widget build(BuildContext context) => Column(\n children: [\n Text(\"$isLogin\"),\n SizedBox(\n height: 400,\n width: 400,\n child: isLogin ? LoginScreen(onClickedSignUp: toggle) : Text(\"F\"),\n )\n ],\n );\n}\n\nclass LoginScreen extends StatefulWidget {\n const LoginScreen({Key? key, required this.onClickedSignUp})\n : super(key: key);\n\n final VoidCallback onClickedSignUp;\n\n @override\n State<LoginScreen> createState() => _LogInScreenState();\n}\n\nclass _LogInScreenState extends State<LoginScreen> {\n @override\n Widget build(BuildContext context) {\n return Scaffold(\n body: RichText(\n text: TextSpan(\n text: 'No account',\n style: TextStyle(color: Colors.black),\n children: [\n TextSpan(\n recognizer: TapGestureRecognizer()\n ..onTap = () => widget.onClickedSignUp(),\n text: 'Click Here',\n style: TextStyle(\n decoration: TextDecoration.underline, color: Colors.black))\n ])),\n );\n }\n}\n```\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74615226",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20265334/"
] |
74,615,293
|
<p>I'm trying to map one key to each value in array to a new array by using JOLT.
Could someone please help give me a solution for this:</p>
<p>My JSON:</p>
<pre class="lang-json prettyprint-override"><code>[
{
"person_id": "1",
"resources": ["asd", "zxc"]
},
{
"person_id": "2",
"resources": ["ghj", "asd"]
}
]
</code></pre>
<p>And my expected JSON:</p>
<pre class="lang-json prettyprint-override"><code>[
{
"person_id": "1",
"resource": "asd"
},
{
"person_id": "1",
"resource": "zxc"
},
{
"person_id": "2",
"resource": "ghj"
},
{
"person_id": "2",
"resource": "asd"
}
]
</code></pre>
<p>I had tried this Jolt Specification</p>
<pre class="lang-json prettyprint-override"><code>[
{
"operation": "shift",
"spec": {
"*": {
"resources": {
"*": {
"@(2,person_id)": "[&].person_id",
"@": "[&].resource"
}
}
}
}
}
]
</code></pre>
<p>But no luck it always maps all values at the same index to 1 array.</p>
|
[
{
"answer_id": 74615175,
"author": "Ashot Khachatryan",
"author_id": 12397183,
"author_profile": "https://Stackoverflow.com/users/12397183",
"pm_score": 1,
"selected": false,
"text": "..onTap = () => widget.onClickedSignUp.call(),\n ..onTap = widget.onClickedSignUp,\n \n"
},
{
"answer_id": 74615510,
"author": "Yeasin Sheikh",
"author_id": 10157127,
"author_profile": "https://Stackoverflow.com/users/10157127",
"pm_score": 3,
"selected": true,
"text": "() TextSpan(\n recognizer: TapGestureRecognizer()\n ..onTap = () => widget.onClickedSignUp(),\n isLogin = !isLogin; \nclass MainPage extends StatelessWidget {\n const MainPage({super.key});\n\n @override\n Widget build(BuildContext context) {\n return Scaffold(body: AuthPage());\n }\n}\n\nclass AuthPage extends StatefulWidget {\n const AuthPage({super.key});\n\n @override\n State<AuthPage> createState() => _AuthPageState();\n}\n\nclass _AuthPageState extends State<AuthPage> {\n bool isLogin = true;\n void toggle() {\n debugPrint(\"yay\");\n setState(() {\n isLogin = !isLogin;\n });\n }\n\n @override\n Widget build(BuildContext context) => Column(\n children: [\n Text(\"$isLogin\"),\n SizedBox(\n height: 400,\n width: 400,\n child: isLogin ? LoginScreen(onClickedSignUp: toggle) : Text(\"F\"),\n )\n ],\n );\n}\n\nclass LoginScreen extends StatefulWidget {\n const LoginScreen({Key? key, required this.onClickedSignUp})\n : super(key: key);\n\n final VoidCallback onClickedSignUp;\n\n @override\n State<LoginScreen> createState() => _LogInScreenState();\n}\n\nclass _LogInScreenState extends State<LoginScreen> {\n @override\n Widget build(BuildContext context) {\n return Scaffold(\n body: RichText(\n text: TextSpan(\n text: 'No account',\n style: TextStyle(color: Colors.black),\n children: [\n TextSpan(\n recognizer: TapGestureRecognizer()\n ..onTap = () => widget.onClickedSignUp(),\n text: 'Click Here',\n style: TextStyle(\n decoration: TextDecoration.underline, color: Colors.black))\n ])),\n );\n }\n}\n```\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74615293",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20634014/"
] |
74,615,310
|
<p>I have the next matrix:</p>
<pre><code>structure(c(0, 0, NA, NA, NA, NA, 0, 0, NA, NA, NA, 1, NA, NA,
NA, NA, 0, 1, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, 1, NA,
1, 0, NA, NA, NA, NA, NA, 0, NA, NA, NA, 1, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, 1, 1, NA, NA, 0,
1, 1, 0, NA, NA, 0, 1, 1, NA, 1, 0, 0, 0, NA, NA, 0, 1, 1, 0,
0, 1, 0, 0, 0, 0, 1, 1, NA, NA, 0, 1, 1, 0, NA, NA, 1, 1, NA,
NA, 1, 0, 1, 1, NA, NA, 0, 1, 1, 1, 0, 1, 0, NA, NA, NA, NA,
NA, NA, NA, 0, 1, 1, 0, NA, NA, 1, 1, NA, NA, 1, 0, NA, NA, NA,
NA, 0, 1, NA, NA, 0, 1, 0, NA, NA, NA, NA, NA, NA, NA, NA, 1,
1, 0, NA, NA, 1, 1, NA, NA, 1, 0, NA, NA, NA, NA, 0, 1, NA, NA,
1, 1, 0, NA, NA, NA, NA, NA, NA, NA, NA, 1, 1, 0, NA, NA, 1,
1, NA, NA, 1, 0, NA, 1, NA, NA, 1, 1, NA, NA, NA, NA, 0, NA,
NA, NA, NA, NA), dim = c(30L, 7L), dimnames = list(c("1", "2",
"3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14",
"15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25",
"26", "27", "28", "29", "30"), c("1", "2", "4", "5", "6", "7",
"8")))
</code></pre>
<p>I need to generate a matrix in the following way:</p>
<p>Let's suppose a row of this matrix:</p>
<p><code>0,1,1,1,1,1,1</code></p>
<p>I would like to define:</p>
<p><code>-1,0,1,2,3,4,5,6</code></p>
<p>Where zero means the time of the event of interest.</p>
<p>If I have elements with NA I would like to get something like this:</p>
<p><code>NA,NA,0,1,NA,NA,1</code></p>
<p>I would like to get:</p>
<p><code>NA,NA,-1,0,NA,NA,3</code></p>
<p>with a row like this:</p>
<p><code>NA,1,1,1,NA,NA,1</code></p>
<p><code>NA,0,1,2,NA,NA,5</code></p>
<p>I hope these specific could clarify my objective:</p>
|
[
{
"answer_id": 74615436,
"author": "Ric Villalba",
"author_id": 6912817,
"author_profile": "https://Stackoverflow.com/users/6912817",
"pm_score": 0,
"selected": false,
"text": "nomatch m <- structure(c(0, 0, NA, NA, NA, NA, 0, 0, NA, NA, NA, 1, NA, NA, \nNA, NA, 0, 1, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, 1, NA, \n1, 0, NA, NA, NA, NA, NA, 0, NA, NA, NA, 1, NA, NA, NA, NA, NA, \nNA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, 1, 1, NA, NA, 0, \n1, 1, 0, NA, NA, 0, 1, 1, NA, 1, 0, 0, 0, NA, NA, 0, 1, 1, 0, \n0, 1, 0, 0, 0, 0, 1, 1, NA, NA, 0, 1, 1, 0, NA, NA, 1, 1, NA, \nNA, 1, 0, 1, 1, NA, NA, 0, 1, 1, 1, 0, 1, 0, NA, NA, NA, NA, \nNA, NA, NA, 0, 1, 1, 0, NA, NA, 1, 1, NA, NA, 1, 0, NA, NA, NA, \nNA, 0, 1, NA, NA, 0, 1, 0, NA, NA, NA, NA, NA, NA, NA, NA, 1, \n1, 0, NA, NA, 1, 1, NA, NA, 1, 0, NA, NA, NA, NA, 0, 1, NA, NA, \n1, 1, 0, NA, NA, NA, NA, NA, NA, NA, NA, 1, 1, 0, NA, NA, 1, \n1, NA, NA, 1, 0, NA, 1, NA, NA, 1, 1, NA, NA, NA, NA, 0, NA, \nNA, NA, NA, NA), dim = c(30L, 7L), dimnames = list(c(\"1\", \"2\", \n\"3\", \"4\", \"5\", \"6\", \"7\", \"8\", \"9\", \"10\", \"11\", \"12\", \"13\", \"14\", \n\"15\", \"16\", \"17\", \"18\", \"19\", \"20\", \"21\", \"22\", \"23\", \"24\", \"25\", \n\"26\", \"27\", \"28\", \"29\", \"30\"), c(\"1\", \"2\", \"4\", \"5\", \"6\", \"7\", \n\"8\")))\nm\n\n#> 1 2 4 5 6 7 8\n#> 1 0 1 NA NA NA NA NA\n#> 2 0 0 NA NA NA NA NA\n#> 3 NA NA 0 0 0 NA NA\n#> 4 NA NA 1 1 1 1 1\n#> 5 NA NA 1 1 1 1 1\n#> 6 NA NA 0 0 0 0 0\n#> 7 0 NA NA NA NA NA NA\n#> 8 0 0 NA NA NA NA NA\n#> 9 NA NA 0 1 1 1 1\n#> 10 NA NA 1 1 1 1 1\n#> 11 NA NA 1 NA NA NA NA\n#> 12 1 1 NA NA NA NA NA\n#> 13 NA NA 1 1 1 1 1\n#> 14 NA NA 0 0 0 0 0\n#> 15 NA NA 0 1 NA NA NA\n#> 16 NA NA 0 1 NA NA 1\n#> 17 0 NA NA NA NA NA NA\n#> 18 1 NA NA NA NA NA NA\n#> 19 NA NA 0 0 0 0 1\n#> 20 NA NA 1 1 1 1 1\n#> 21 NA NA 1 1 NA NA NA\n#> 22 NA NA 0 1 NA NA NA\n#> 23 NA NA 0 0 0 1 NA\n#> 24 NA NA 1 1 1 1 NA\n#> 25 NA NA 0 0 0 0 0\n#> 26 NA NA 0 NA NA NA NA\n#> 27 NA NA 0 NA NA NA NA\n#> 28 NA NA 0 NA NA NA NA\n#> 29 1 1 1 NA NA NA NA\n#> 30 NA 1 1 NA NA NA NA\n\nt(apply(m, 1, function(x) ifelse(is.na(x), NA, seq_along(x) - match(1, x, nomatch = 0))))\n\n#> 1 2 4 5 6 7 8\n#> 1 -1 0 NA NA NA NA NA\n#> 2 1 2 NA NA NA NA NA\n#> 3 NA NA 3 4 5 NA NA\n#> 4 NA NA 0 1 2 3 4\n#> 5 NA NA 0 1 2 3 4\n#> 6 NA NA 3 4 5 6 7\n#> 7 1 NA NA NA NA NA NA\n#> 8 1 2 NA NA NA NA NA\n#> 9 NA NA -1 0 1 2 3\n#> 10 NA NA 0 1 2 3 4\n#> 11 NA NA 0 NA NA NA NA\n#> 12 0 1 NA NA NA NA NA\n#> 13 NA NA 0 1 2 3 4\n#> 14 NA NA 3 4 5 6 7\n#> 15 NA NA -1 0 NA NA NA\n#> 16 NA NA -1 0 NA NA 3\n#> 17 1 NA NA NA NA NA NA\n#> 18 0 NA NA NA NA NA NA\n#> 19 NA NA -4 -3 -2 -1 0\n#> 20 NA NA 0 1 2 3 4\n#> 21 NA NA 0 1 NA NA NA\n#> 22 NA NA -1 0 NA NA NA\n#> 23 NA NA -3 -2 -1 0 NA\n#> 24 NA NA 0 1 2 3 NA\n#> 25 NA NA 3 4 5 6 7\n#> 26 NA NA 3 NA NA NA NA\n#> 27 NA NA 3 NA NA NA NA\n#> 28 NA NA 3 NA NA NA NA\n#> 29 0 1 2 NA NA NA NA\n#> 30 NA 0 1 NA NA NA NA\n"
},
{
"answer_id": 74615541,
"author": "Maël",
"author_id": 13460602,
"author_profile": "https://Stackoverflow.com/users/13460602",
"pm_score": 1,
"selected": false,
"text": "mat[] <- t(apply(mat, 1, \\(x) (seq_along(x) - min(which(x == 1))) + x*0))\n#mat[is.infinite(mat)] <- 0\n > mat\n 1 2 4 5 6 7 8\n1 -1 0 NA NA NA NA NA\n2 -Inf -Inf NA NA NA NA NA\n3 NA NA -Inf -Inf -Inf NA NA\n4 NA NA 0 1 2 3 4\n5 NA NA 0 1 2 3 4\n6 NA NA -Inf -Inf -Inf -Inf -Inf\n7 -Inf NA NA NA NA NA NA\n8 -Inf -Inf NA NA NA NA NA\n9 NA NA -1 0 1 2 3\n10 NA NA 0 1 2 3 4\n11 NA NA 0 NA NA NA NA\n12 0 1 NA NA NA NA NA\n13 NA NA 0 1 2 3 4\n14 NA NA -Inf -Inf -Inf -Inf -Inf\n15 NA NA -1 0 NA NA NA\n16 NA NA -1 0 NA NA 3\n17 -Inf NA NA NA NA NA NA\n18 0 NA NA NA NA NA NA\n19 NA NA -4 -3 -2 -1 0\n20 NA NA 0 1 2 3 4\n21 NA NA 0 1 NA NA NA\n22 NA NA -1 0 NA NA NA\n23 NA NA -3 -2 -1 0 NA\n24 NA NA 0 1 2 3 NA\n25 NA NA -Inf -Inf -Inf -Inf -Inf\n26 NA NA -Inf NA NA NA NA\n27 NA NA -Inf NA NA NA NA\n28 NA NA -Inf NA NA NA NA\n29 0 1 2 NA NA NA NA\n30 NA 0 1 NA NA NA NA\n"
},
{
"answer_id": 74615918,
"author": "jblood94",
"author_id": 9463489,
"author_profile": "https://Stackoverflow.com/users/9463489",
"pm_score": 1,
"selected": false,
"text": "max.col sequence f <- function(m) {\n blnNA <- is.na(m)\n m[blnNA] <- 0\n i <- max.col(m, \"first\")\n x <- m[matrix(c(1:nrow(m), i), ncol = 2)]\n m <- matrix(sequence(rep(ncol(m), nrow(m)), x*(1 - i), x), nrow(m), ncol(m), 1)\n m[blnNA] <- NA\n m\n}\n\nf(m)\n#> [,1] [,2] [,3] [,4] [,5] [,6] [,7]\n#> [1,] -1 0 NA NA NA NA NA\n#> [2,] 0 0 NA NA NA NA NA\n#> [3,] NA NA 0 0 0 NA NA\n#> [4,] NA NA 0 1 2 3 4\n#> [5,] NA NA 0 1 2 3 4\n#> [6,] NA NA 0 0 0 0 0\n#> [7,] 0 NA NA NA NA NA NA\n#> [8,] 0 0 NA NA NA NA NA\n#> [9,] NA NA -1 0 1 2 3\n#> [10,] NA NA 0 1 2 3 4\n#> [11,] NA NA 0 NA NA NA NA\n#> [12,] 0 1 NA NA NA NA NA\n#> [13,] NA NA 0 1 2 3 4\n#> [14,] NA NA 0 0 0 0 0\n#> [15,] NA NA -1 0 NA NA NA\n#> [16,] NA NA -1 0 NA NA 3\n#> [17,] 0 NA NA NA NA NA NA\n#> [18,] 0 NA NA NA NA NA NA\n#> [19,] NA NA -4 -3 -2 -1 0\n#> [20,] NA NA 0 1 2 3 4\n#> [21,] NA NA 0 1 NA NA NA\n#> [22,] NA NA -1 0 NA NA NA\n#> [23,] NA NA -3 -2 -1 0 NA\n#> [24,] NA NA 0 1 2 3 NA\n#> [25,] NA NA 0 0 0 0 0\n#> [26,] NA NA 0 NA NA NA NA\n#> [27,] NA NA 0 NA NA NA NA\n#> [28,] NA NA 0 NA NA NA NA\n#> [29,] 0 1 2 NA NA NA NA\n#> [30,] NA 0 1 NA NA NA NA\n 1 f <- function(m) {\n idxNA <- which(is.na(m))\n m[idxNA] <- 0\n i <- max.col(m, \"first\")\n x <- m[matrix(c(1:nrow(m), i), ncol = 2)]\n m <- matrix(sequence(rep(ncol(m), nrow(m)), x*(1 - i) - 1, x), nrow(m), ncol(m), 1)/x + 1\n m[idxNA] <- NA\n m\n}\n\nf(m)\n#> [,1] [,2] [,3] [,4] [,5] [,6] [,7]\n#> [1,] -1 0 NA NA NA NA NA\n#> [2,] -Inf -Inf NA NA NA NA NA\n#> [3,] NA NA -Inf -Inf -Inf NA NA\n#> [4,] NA NA 0 1 2 3 4\n#> [5,] NA NA 0 1 2 3 4\n#> [6,] NA NA -Inf -Inf -Inf -Inf -Inf\n#> [7,] -Inf NA NA NA NA NA NA\n#> [8,] -Inf -Inf NA NA NA NA NA\n#> [9,] NA NA -1 0 1 2 3\n#> [10,] NA NA 0 1 2 3 4\n#> [11,] NA NA 0 NA NA NA NA\n#> [12,] 0 1 NA NA NA NA NA\n#> [13,] NA NA 0 1 2 3 4\n#> [14,] NA NA -Inf -Inf -Inf -Inf -Inf\n#> [15,] NA NA -1 0 NA NA NA\n#> [16,] NA NA -1 0 NA NA 3\n#> [17,] -Inf NA NA NA NA NA NA\n#> [18,] 0 NA NA NA NA NA NA\n#> [19,] NA NA -4 -3 -2 -1 0\n#> [20,] NA NA 0 1 2 3 4\n#> [21,] NA NA 0 1 NA NA NA\n#> [22,] NA NA -1 0 NA NA NA\n#> [23,] NA NA -3 -2 -1 0 NA\n#> [24,] NA NA 0 1 2 3 NA\n#> [25,] NA NA -Inf -Inf -Inf -Inf -Inf\n#> [26,] NA NA -Inf NA NA NA NA\n#> [27,] NA NA -Inf NA NA NA NA\n#> [28,] NA NA -Inf NA NA NA NA\n#> [29,] 0 1 2 NA NA NA NA\n#> [30,] NA 0 1 NA NA NA NA\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74615310",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3483060/"
] |
74,615,352
|
<p>The example code is using DryWetMidi library. The program plays a MIDI file (MIDI.Path) on button click until the file ends. The problem is there seems to be no way of stopping the playback with another button.</p>
<p>Is there anyone who has experience with the MIDI library that knows how to make a button that stops the current file playback?</p>
<pre><code>@using Melanchall.DryWetMidi.Multimedia;
@using Melanchall.DryWetMidi.Core;
<span @onclick="@(() => PlayMidi())">
<button>Play</button>
</span>
@code{
private static Playback playback;
public void PlayMidi()
{
var midiFile = MidiFile.Read(MIDI.Path);
var outputDevice = OutputDevice.GetByName("Microsoft GS Wavetable Synth");
playback = midiFile.GetPlayback(outputDevice);
playback.Start();
SpinWait.SpinUntil(() => !playback.IsRunning);
Console.WriteLine("Playback stopped or finished.");
outputDevice.Dispose();
playback.Dispose();
}
}
</code></pre>
|
[
{
"answer_id": 74615705,
"author": "stark",
"author_id": 1216776,
"author_profile": "https://Stackoverflow.com/users/1216776",
"pm_score": 0,
"selected": false,
"text": "<span @onclick=\"@(() => StopMidi())\">\n <button>Stop</button>\n</span>\n\n\npublic void StopMidi()\n{\n playback.Stop();\n}\n"
},
{
"answer_id": 74625966,
"author": "Ibrahim Timimi",
"author_id": 8316900,
"author_profile": "https://Stackoverflow.com/users/8316900",
"pm_score": 2,
"selected": true,
"text": "playBack outputDevice PlayMidi playBack SpinWait PlayMidi playback.IsRunning false playBack SpinWait StopMidi @page \"/\"\n@using Melanchall.DryWetMidi.Multimedia;\n@using Melanchall.DryWetMidi.Core;\n@implements IDisposable\n\n<span @onclick=\"@(() => PlayMidi())\">\n <button>Play</button>\n</span>\n\n<span @onclick=\"@(() => StopMidi())\">\n <button>Stop</button>\n</span>\n\n\n@code {\n private Playback playback { get; set; }\n private OutputDevice outputDevice = \n OutputDevice.GetByName(\"Microsoft GS Wavetable Synth\");\n\n public void PlayMidi()\n {\n var midiFile = MidiFile.Read(\"Midi/Cymatics - Waves MIDI 10 - E Min.mid\");\n \n playback = midiFile.GetPlayback(outputDevice);\n playback.Start();\n\n //SpinWait.SpinUntil(() => !playback.IsRunning);\n\n Console.WriteLine(\"Playback stopped or finished.\");\n }\n\n private void StopMidi()\n {\n playback.Stop();\n }\n\n public void Dispose()\n {\n outputDevice.Dispose();\n if (playback != null)\n playback.Dispose();\n }\n}\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74615352",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20373344/"
] |
74,615,371
|
<p>I have a problem with saving data from a form in django. Only the last record is saved. I generate a list of dates (days of the month) in the view and display it in the form in templates along with the fields next to the type. Everything is displayed correctly in templates, but when I submit to, only the last record from the form appears in the save view. What am I doing wrong, can someone help?</p>
<p>forms.py</p>
<pre class="lang-py prettyprint-override"><code>
class DoctorsSchedule(forms.ModelForm):
# work_hours = models.CharField(max_length=50, blank=True, null=True, default='8:00-21:00')
# official_hours = models.CharField(max_length=50, blank=True, null=True, default='8:00-19:00')
class Meta:
model = DoctorSchedule
fields = ['date', 'day_type', 'work_hours', 'scheme', 'official_hours']
</code></pre>
<p>model.py</p>
<pre class="lang-py prettyprint-override"><code>
class DoctorSchedule(models.Model):
id = models.AutoField(primary_key=True, unique=True)
date = models.DateField(blank=True, null=True)
day_type = models.CharField(max_length=255, blank=True, null=True, default='Pracujący')
work_hours = models.CharField(max_length=50, blank=True, null=True, default='8:00-21:00')
scheme = models.CharField(max_length=255, blank=True, null=True, default='20')
official_hours = models.CharField(max_length=50, blank=True, null=True, default='8:00-19:00')
def __str__(self):
return self.date
</code></pre>
<p>view.py</p>
<pre class="lang-py prettyprint-override"><code>
def terminarz(request):
today = datetime.now()
now = date.today()
locale.setlocale(locale.LC_TIME, 'pl_PL')
def months():
months = {'1': 'Styczeń', '2': 'Luty', '3': 'Marzec', '4': 'Kwiecień', '5': 'Maj', '6': 'Czerwiec',
'7': 'Lipiec',
'8': 'Sierpień', '9': 'Wrzesień', '10': 'Październik', '11': 'Listopad', '12': 'Grudzień'}
return months
##################### days of month list ######################################
def days_of_month_list():
if request.GET.get('year') and request.GET.get('month'):
y = int(request.GET.get('year'))
m = int(request.GET.get('month'))
btn_y = int(request.GET.get('year'))
else:
y = today.year
m = today.month
btn_y = today.year
date_list = {}
for d in range(1, monthrange(y, m)[1] + 1):
x = '{:04d}-{:02d}-{:02d}'.format(y, m, d)
dayName = datetime.strptime(x, '%Y-%m-%d').weekday()
date_list[x] = calendar.day_name[dayName].capitalize()
################### end days of month list #################################
return date_list
months = months()
date_list = days_of_month_list()
btn_today = today.year
btn_today_1 = today.year + 1
btn_today_2 = today.year + 2
if request.GET.get('year') and request.GET.get('month'):
btn_y = int(request.GET.get('year'))
else:
btn_y = today.year
if request.method == 'POST':
form = DoctorsSchedule(request.POST)
if form.is_valid():
form.save()
else:
print(form.is_valid()) # form contains data and errors
print(form.errors)
form = DoctorsSchedule()
else:
form = DoctorsSchedule
context = {
'form': form,
'today': today,
'now': now,
'months': months,
'date_list': date_list,
'btn_today': btn_today,
'btn_today_1': btn_today_1,
'btn_today_2': btn_today_2
}
return render(request, "vita/panel/terminarz.html", context)
</code></pre>
<p>templates.html</p>
<pre><code><div class="card-body">
<form method="POST" enctype="multipart/form-data">
{% csrf_token %}
{{ form.as_p }}
<div class="row p-3 text-center">
{% include 'vita/messages.html' %}
<div class="text-center p-2">
<a role="button" class="btn btn-info" href='terminarz?month={{today.month}}&year={{btn_today}}'>{{ btn_today }}</a>
<a role="button" class="btn btn-info" href='terminarz?month={{today.month}}&year={{ btn_today_1 }}'>{{ btn_today_1 }}</a>
<a role="button" class="btn btn-info" href='terminarz?month={{today.month}}&year={{ btn_today_2 }}'>{{ btn_today_2 }}</a>
</div>
{% for nr, month in months.items %}
<div class="col text-center">
{% if btn_y == btn_today_1 %}
<a role="button" class="btn btn-primary p-2" href="terminarz?month={{nr}}&year={{btn_today_1}}">{{month|upper}}</a>
{% elif btn_y == btn_today_2 %}
<a role="button" class="btn btn-primary p-2" href="terminarz?month={{nr}}&year={{btn_today_2}}">{{month|upper}}</a>
{% else %}
<a role="button" class="btn btn-primary p-2" href="terminarz?month={{nr}}&year={{btn_today}}">{{month|upper}}</a>
{% endif %}
</div>
{% endfor %}
</div>
<table class="table table-striped table-sm table-responsive">
<thead class="text-light" style="background: #26396F;">
<tr>
<th>Data</th>
<th class="text-center">Dzień pracy</th>
<th class="text-center">Godziny oficjalne</th>
<th class="text-center">Godziny pracy</th>
<th class="text-center">Przedział</th>
<th class="text-center">Ilość wizyt</th>
</tr>
</thead>
<tbody>
{% for date, day in date_list.items %}
<tr>
<td class="p-1">
<a href="/panel/{{ date }}">
<b>{{ date }}</b> -
{% if day == 'Sobota' or day == 'Niedziela' %}
<span class="text-danger">{{ day }}</span>
{% else %}
<span class="text-success">{{ day }}</span>
{% endif %}
</a>
<input type="hidden" name="data" value="{{date}}" />
</td>
<td class="p-1">
<select name="day_type">
{% if day == 'Sobota' or day == 'Niedziela' %}
<option value="Wolny" selected>Wolny</option>
<option value="Pracujący">Pracujący</option>
{% else %}
<option value="Pracujący" selected>Pracujący</option>
<option value="Wolny" >Wolny</option>
{% endif %}
</select>
</td>
{% if day == 'Sobota' or day == 'Niedziela' %}
<td></td>
<td></td>
<td></td>
<td></td>
{% else %}
<td class="p-1 text-center"><input name="official_hours_start" type="time" value="08:00" />-<input name="official_hours_end" type="time" value="19:00" /></td>
<td class="p-1 text-center"><input name="work_hours_start" type="time" value="08:00" />-<input name="work_hours_end" type="time" value="21:00" /></td>
<td class="p-1 text-center">
<select name="scheme">
<option value="10">10 min</option>
<option value="15">15 min</option>
<option value="20">20 min</option>
<option value="25">25 min</option>
<option value="30" selected>30 min</option>
</select>
</td>
<td class="p-1 text-center">0</td>
{% endif %}
</tr>
{% endfor %}
</tbody>
</table>
<div class="text-center"><input class="btn btn-success" type="submit" name="update_schedule" value="Uaktualnij terminarz" /></div>
</form>
</div>
</code></pre>
|
[
{
"answer_id": 74615669,
"author": "franckfournier",
"author_id": 3398093,
"author_profile": "https://Stackoverflow.com/users/3398093",
"pm_score": 1,
"selected": false,
"text": "...\nelse:\n form = DoctorsSchedule()\n...\n# into\n\n...\nelse:\n form = DoctorsSchedule({\n 'date': <place here the current correct value for this field>, \n 'day_type': <place here the current correct value for this field>, \n etc...\n })\n\n form = DoctorsSchedule # this is a Form class not an instance\n# with \n form = DoctorsSchedule()\n# or better\n form = DoctorsSchedule(initial_data={<your data>})\n# or also better\n form = DoctorsSchedule(<some DoctorsSchedule (the Model one) instance>)\n DoctorsSchedule DoctorsSchedule"
},
{
"answer_id": 74645063,
"author": "Erni",
"author_id": 11847900,
"author_profile": "https://Stackoverflow.com/users/11847900",
"pm_score": 0,
"selected": false,
"text": "<QueryDict: {'csrfmiddlewaretoken': ['mzIuVQEY1a6s15UEInWD5xZOm6HapMyOAikLItkMTvIGOizxIU9NErfh4SUkfiR9'], 'data': ['2022-12-01', '2022-12-02', '2022-12-03', '2022-12-04', '2022-12-05', '2022-12-06', '2022-12-07', '2022-12-08', '2022\n-12-09', '2022-12-10', '2022-12-11', '2022-12-12', '2022-12-13', '2022-12-14', '2022-12-15', '2022-12-16', '2022-12-17', '2022-12-18', '2022-12-19', '2022-12-20', '2022-12-21', '2022-12-22', '2022-12-23', '2022-12-24', '2022-12-25',\n '2022-12-26', '2022-12-27', '2022-12-28', '2022-12-29', '2022-12-30', '2022-12-31'], 'day_type': ['Pracujący', 'Pracujący', 'Wolny', 'Wolny', 'Pracujący', 'Pracujący', 'Pracujący', 'Pracujący', 'Pracujący', 'Wolny', 'Wolny', 'Pracu\njący', 'Pracujący', 'Pracujący', 'Pracujący', 'Pracujący', 'Wolny', 'Wolny', 'Pracujący', 'Pracujący', 'Pracujący', 'Pracujący', 'Pracujący', 'Wolny', 'Wolny', 'Pracujący', 'Pracujący', 'Pracujący', 'Pracujący', 'Pracujący', 'Wolny'\n], 'official_hours_start': ['08:00-19:00', '08:00-19:00', '08:00-19:00', '08:00-19:00', '08:00-19:00', '08:00-19:00', '08:00-19:00', '08:00-19:00', '08:00-19:00', '08:00-19:00', '08:00-19:00', '08:00-19:00', '08:00-19:00', '08:00-19\n:00', '08:00-19:00', '08:00-19:00', '08:00-19:00', '08:00-19:00', '08:00-19:00', '08:00-19:00', '08:00-19:00', '08:00-19:00'], 'work_hours_start': ['08:00-21:00', '08:00-21:00', '08:00-21:00', '08:00-21:00', '08:00-21:00', '08:00-21\n:00', '08:00-21:00', '08:00-21:00', '08:00-21:00', '08:00-21:00', '08:00-21:00', '08:00-21:00', '08:00-21:00', '08:00-21:00', '08:00-21:00', '08:00-21:00', '08:00-21:00', '08:00-21:00', '08:00-21:00', '08:00-21:00', '08:00-21:00', '08:00-21:00'], 'scheme': ['30', '30', '30', '30', '30', '30', '30', '30', '30', '30', '30', '30', '30', '30', '30', '30', '30', '30', '30', '30', '30', '30'], 'update_schedule': ['Uaktualnij terminarz']}>\n"
},
{
"answer_id": 74669955,
"author": "Erni",
"author_id": 11847900,
"author_profile": "https://Stackoverflow.com/users/11847900",
"pm_score": 1,
"selected": true,
"text": "\n if request.method == \"POST\":\n if form.is_valid():\n x1 = request.POST #get data from request and getlist from QueryDict\n data_l = x1.getlist('data')\n day_type_l = x1.getlist('day_type')\n work_hours_l = x1.getlist('work_hours_start')\n scheme_l = x1.getlist('scheme')\n official_hours_l = x1.getlist('official_hours_start')\n\n for date, day_type, work_hours, official_hours, scheme in zip(data_l,day_type_l,work_hours_l,official_hours_l,scheme_l):\n\n post_dict = {'date': date, 'day_type': day_type, 'work_hours': work_hours, 'official_hours': official_hours, 'scheme': scheme}\n \n form = DoctorsScheduleForm(post_dict)\n form.save()\n\n else:\n form = DoctorsScheduleForm()\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74615371",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11847900/"
] |
74,615,380
|
<p>How to get data from REST API using a graphql query</p>
<p>How to get data from REST API using a graphql</p>
|
[
{
"answer_id": 74619262,
"author": "Tim",
"author_id": 20317091,
"author_profile": "https://Stackoverflow.com/users/20317091",
"pm_score": 1,
"selected": false,
"text": "@client express-graphql const {\n GraphQLObjectType,\n GraphQLInt,\n GraphQLString,\n GraphQLBoolean,\n GraphQLList,\n GraphQLSchema\n} = require('graphql');\n\n// Launch Type\nconst LaunchType = new GraphQLObjectType({\n name: 'Launch',\n fields: () => ({\n flight_number: { type: GraphQLInt },\n mission_name: { type: GraphQLString },\n launch_year: { type: GraphQLString },\n launch_date_local: { type: GraphQLString },\n launch_success: { type: GraphQLBoolean }\n })\n});\n\nconst LaunchQuery = new GraphQLObjectType({\n name: 'LaunchQueryType',\n fields: {\n launches: {\n type: new GraphQLList(LaunchType),\n resolve(parent, args) {\n return axios\n .get('https://api.spacexdata.com/v4/launches')\n .then(res => res.data);\n }\n }\n }\n});\n\nmodule.exports = new GraphQLSchema({query: LaunchQuery});\n"
},
{
"answer_id": 74622988,
"author": "TeamEasyManage",
"author_id": 20640709,
"author_profile": "https://Stackoverflow.com/users/20640709",
"pm_score": 0,
"selected": false,
"text": " @QueryMapping\npublic List<DgproductinventoryviewTblRec> DgproductinventoryviewTblRecViewAll() \n throws Exception \n { \n List<DgproductinventoryviewTblRec> DgproductinventoryviewTblRecList = new ArrayList<DgproductinventoryviewTblRec>(); \n try { \n \n DgproductinventoryviewTblRec1Repository.findAll().forEach(DgproductinventoryviewTblRecList::add); \n \n \n } catch (Exception e) { \n System.out.println(\"Error: Exception: \"+e.getMessage()); \n //e.printStackTrace(System.out); \n throw new Exception(e.getMessage()); \n } \n return DgproductinventoryviewTblRecList; \n} \n //Get from 1st Db\n InventoryTblRec1Repository.findAll().forEach(InventoryTblRecList::add); \n //InventoryTblRec1Repository.findByColumnName(columnVal).forEach(InventoryTblRecList::add); \n\n //----------------------------------------------------------------------------\n //Get from 2nd Db\n String get_state = \"http://127.0.0.1:9085/emdbrest/inventory/ViewAll\";\n WebClient webClient1 = WebClient.builder().baseUrl(get_state)\n .defaultHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE).build();\n\n\n Mono<List<InventoryTblRec>> response =\n webClient1.get()\n .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE).retrieve()\n .bodyToMono(new ParameterizedTypeReference<List<InventoryTblRec>>() {});\n \n List<InventoryTblRec> getListInventoryTblRec = response.block();\n\n getListInventoryTblRec.forEach(InventoryTblRecList::add);\n //----------------------------------------------------------------------------\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74615380",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13791025/"
] |
74,615,396
|
<p>I am making a web app with VueJS that makes axios calls to a NodeJS API that uses express. I'm currently trying to send files to my NodeJS so it can save them. However, even though my browser displays all the properties of my array of files, my NodeJS reads it as empty. I've read all the questions previously asked on this topic but I haven't made any progress whatsoever. Note that I can POST any other data just fine, all my SQL Insert requests do well, mind you they don't involve sending arrays.</p>
<p>Example of promising solution that did not work : <a href="https://stackoverflow.com/a/66541165/12498040">https://stackoverflow.com/a/66541165/12498040</a></p>
<p>Here is my client side JS, console.log() prints an array of N files object in the browser console :</p>
<pre><code> console.log(data)
await axios.post('/api/fichiers', {fichiers:data});
</code></pre>
<p>Here is my NodeJS, with console.log(element) it prints N number of "{}" in the browser console and console.log(element.name) prints N number of "undefined" in the server terminal :</p>
<pre><code>app.post('/api/fichiers', (req, res) => {
req.body.fichiers.forEach((element) => {
console.log(element.name);
});
});
</code></pre>
<p>Thank you for any help you could provide :)</p>
|
[
{
"answer_id": 74619262,
"author": "Tim",
"author_id": 20317091,
"author_profile": "https://Stackoverflow.com/users/20317091",
"pm_score": 1,
"selected": false,
"text": "@client express-graphql const {\n GraphQLObjectType,\n GraphQLInt,\n GraphQLString,\n GraphQLBoolean,\n GraphQLList,\n GraphQLSchema\n} = require('graphql');\n\n// Launch Type\nconst LaunchType = new GraphQLObjectType({\n name: 'Launch',\n fields: () => ({\n flight_number: { type: GraphQLInt },\n mission_name: { type: GraphQLString },\n launch_year: { type: GraphQLString },\n launch_date_local: { type: GraphQLString },\n launch_success: { type: GraphQLBoolean }\n })\n});\n\nconst LaunchQuery = new GraphQLObjectType({\n name: 'LaunchQueryType',\n fields: {\n launches: {\n type: new GraphQLList(LaunchType),\n resolve(parent, args) {\n return axios\n .get('https://api.spacexdata.com/v4/launches')\n .then(res => res.data);\n }\n }\n }\n});\n\nmodule.exports = new GraphQLSchema({query: LaunchQuery});\n"
},
{
"answer_id": 74622988,
"author": "TeamEasyManage",
"author_id": 20640709,
"author_profile": "https://Stackoverflow.com/users/20640709",
"pm_score": 0,
"selected": false,
"text": " @QueryMapping\npublic List<DgproductinventoryviewTblRec> DgproductinventoryviewTblRecViewAll() \n throws Exception \n { \n List<DgproductinventoryviewTblRec> DgproductinventoryviewTblRecList = new ArrayList<DgproductinventoryviewTblRec>(); \n try { \n \n DgproductinventoryviewTblRec1Repository.findAll().forEach(DgproductinventoryviewTblRecList::add); \n \n \n } catch (Exception e) { \n System.out.println(\"Error: Exception: \"+e.getMessage()); \n //e.printStackTrace(System.out); \n throw new Exception(e.getMessage()); \n } \n return DgproductinventoryviewTblRecList; \n} \n //Get from 1st Db\n InventoryTblRec1Repository.findAll().forEach(InventoryTblRecList::add); \n //InventoryTblRec1Repository.findByColumnName(columnVal).forEach(InventoryTblRecList::add); \n\n //----------------------------------------------------------------------------\n //Get from 2nd Db\n String get_state = \"http://127.0.0.1:9085/emdbrest/inventory/ViewAll\";\n WebClient webClient1 = WebClient.builder().baseUrl(get_state)\n .defaultHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE).build();\n\n\n Mono<List<InventoryTblRec>> response =\n webClient1.get()\n .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE).retrieve()\n .bodyToMono(new ParameterizedTypeReference<List<InventoryTblRec>>() {});\n \n List<InventoryTblRec> getListInventoryTblRec = response.block();\n\n getListInventoryTblRec.forEach(InventoryTblRecList::add);\n //----------------------------------------------------------------------------\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74615396",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12498040/"
] |
74,615,450
|
<p>I want to find the .txt file with the shortest name inside a folder.</p>
<pre><code>import glob
import os
inpDir = "C:/Users/ft/Desktop/Folder"
os.chdir(inpDir)
for file in glob.glob("*.txt"):
l = len(file)
</code></pre>
<p>For the moment I found the length of the str of the name, how can I return the shortest name?
Thanks</p>
|
[
{
"answer_id": 74615513,
"author": "scr",
"author_id": 18781246,
"author_profile": "https://Stackoverflow.com/users/18781246",
"pm_score": 3,
"selected": true,
"text": "chosen_file = \"\"\n\nfor file in glob.glob(\"*.txt\"):\n if chosen_file == \"\" or len(file) < len(chosen_file):\n chosen_file = file\n\nprint(f\"{chosen_file} is the shortest file\")\n\n chosen_file"
},
{
"answer_id": 74615514,
"author": "rtoth",
"author_id": 20589189,
"author_profile": "https://Stackoverflow.com/users/20589189",
"pm_score": -1,
"selected": false,
"text": "min = 1000\n\nfor file in glob.glob(\"*.txt\"):\n if len(file) < min:\n min = len(file)\n name = file\n"
},
{
"answer_id": 74615568,
"author": "Guillaume BEDOYA",
"author_id": 20522241,
"author_profile": "https://Stackoverflow.com/users/20522241",
"pm_score": 0,
"selected": false,
"text": "\nimport glob\nimport os\n\ndef shortest_file_name(inpDir: str, extension: str) -> str:\n os.chdir(inpDir)\n shortest, l = '', 0b100000000\n for file in glob.glob(extension):\n if len(file) < l:\n l = len(file)\n shortest = file\n return shortest\n\ninpDir = \"C:/Users/ft/Desktop/Folder\"\nmin_file_name = shortest_file_name(inpDir, \"*.txt\")\n"
},
{
"answer_id": 74615679,
"author": "Klas Š.",
"author_id": 9288580,
"author_profile": "https://Stackoverflow.com/users/9288580",
"pm_score": 0,
"selected": false,
"text": "min(glob.glob('*.txt'), key=len)\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74615450",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20582560/"
] |
74,615,453
|
<p>I have a file, foo.S, which contains ARM thumb instructions, on an Ubuntu 22.04 x86_64 machine. Is it possible to convert this into an ARM object file using <code>as</code> from <code>binutils</code> or do I need to create a cross-compiler toolchain? I tried</p>
<pre class="lang-bash prettyprint-override"><code>$ as -mthumb foo.S -o foo.o
</code></pre>
<p>However, I got</p>
<pre><code>as: unrecognized option '-mthumb'
</code></pre>
<p>even though that's one of the options listed in <code>man as</code>.</p>
|
[
{
"answer_id": 74620507,
"author": "Frant",
"author_id": 4017881,
"author_profile": "https://Stackoverflow.com/users/4017881",
"pm_score": 2,
"selected": false,
"text": "wget sudo apt-get install wget arm-gnu-toolchain-11.3.rel1-x86_64-arm-none-eabi.tar.xz cd ${HOME}\n# Skip the wget command hereafter if arm-gnu-toolchain-11.3.rel1-x86_64-arm-none-eabi.tar.xz was already downloaded into your home directory.\nwget \"https://developer.arm.com/-/media/Files/downloads/gnu/11.3.rel1/binrel/arm-gnu-toolchain-11.3.rel1-x86_64-arm-none-eabi.tar.xz?rev=95edb5e17b9d43f28c74ce824f9c6f10&hash=176C4D884DBABB657ADC2AC886C8C095409547C4\" -O arm-gnu-toolchain-11.3.rel1-x86_64-arm-none-eabi.tar.xz\ntar Jxf arm-gnu-toolchain-11.3.rel1-x86_64-arm-none-eabi.tar.xz\n ${HOME}/arm-gnu-toolchain-11.3.rel1-x86_64-arm-none-eabi/bin/arm-none-eabi-gcc -c -mthumb foo.S -o foo.o \n arm-none-eabi-gcc arm-none-eabi-as"
},
{
"answer_id": 74621749,
"author": "hanshenrik",
"author_id": 1067003,
"author_profile": "https://Stackoverflow.com/users/1067003",
"pm_score": 2,
"selected": true,
"text": "sudo sh -c 'apt update;apt install binutils-arm-none-eabi;'\n arm-none-eabi-as -mthumb foo.S -o foo.o\n $ echo nop > foo.S \n$ arm-none-eabi-as -mthumb foo.S -o foo.o\n$ echo $?\n0\n$ file foo.o\nfoo.o: ELF 32-bit LSB relocatable, ARM, EABI5 version 1 (SYSV), not stripped\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74615453",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8075540/"
] |
74,615,456
|
<p>I want to apply pagination on my data I tried to watch lots of videos and read lots of articles but still can't solve my problem. This is my Views.</p>
<pre><code>def car(request):
all_products = None
all_category = category.get_all_category()
categoryid = request.GET.get('category')
if categoryid:
all_products = Product.get_all_products_by_id(categoryid)
else:
all_products = Product.get_all_products()
data = {}
data['products'] = all_products # all products
data['category'] = all_category # all category
all_products = Product.get_all_products()
data['product'] = all_products
]
return render(request, 'car.html', data)
</code></pre>
<p>as you can see I made some changes in above code but its make no diffrence</p>
<pre><code>def car(request):
all_products = None
all_category = category.get_all_category()
categoryid = request.GET.get('category')
if categoryid:
all_products = Product.get_all_products_by_id(categoryid)
else:
all_products = Product.get_all_products()
#pagination
paginator = Paginator(all_products,2) **Changes**
page_number=request.GET.get('page') **Changes**
finaldata=paginator.get_page(page_number) **Changes**
data = {'all_products':finaldata,} **Changes**
data['products'] = all_products #all products
data['category'] = all_category #all category
all_products = Product.get_all_products()
data['product'] = all_products
return render(request, 'car.html', data)
</code></pre>
<p>I want to display 4 products per page I tried to apply data limit query that work but that not a genuine approach to display data.
I read many articles and watch YouTube video. but can't find any solution. which videos and articles I watched there pagination method is totally different they use pagination with objects.all method to get all data and I used .get method to get data I think that is my problem. and second thing is that they just working with simple data to paginate but in my case it's so complicated. I tried alot please guide. I got stuck in solving a problem for 5 days now. I am convinced that I'm not a good programmer. I tried a lot but I can't succussed.</p>
|
[
{
"answer_id": 74620507,
"author": "Frant",
"author_id": 4017881,
"author_profile": "https://Stackoverflow.com/users/4017881",
"pm_score": 2,
"selected": false,
"text": "wget sudo apt-get install wget arm-gnu-toolchain-11.3.rel1-x86_64-arm-none-eabi.tar.xz cd ${HOME}\n# Skip the wget command hereafter if arm-gnu-toolchain-11.3.rel1-x86_64-arm-none-eabi.tar.xz was already downloaded into your home directory.\nwget \"https://developer.arm.com/-/media/Files/downloads/gnu/11.3.rel1/binrel/arm-gnu-toolchain-11.3.rel1-x86_64-arm-none-eabi.tar.xz?rev=95edb5e17b9d43f28c74ce824f9c6f10&hash=176C4D884DBABB657ADC2AC886C8C095409547C4\" -O arm-gnu-toolchain-11.3.rel1-x86_64-arm-none-eabi.tar.xz\ntar Jxf arm-gnu-toolchain-11.3.rel1-x86_64-arm-none-eabi.tar.xz\n ${HOME}/arm-gnu-toolchain-11.3.rel1-x86_64-arm-none-eabi/bin/arm-none-eabi-gcc -c -mthumb foo.S -o foo.o \n arm-none-eabi-gcc arm-none-eabi-as"
},
{
"answer_id": 74621749,
"author": "hanshenrik",
"author_id": 1067003,
"author_profile": "https://Stackoverflow.com/users/1067003",
"pm_score": 2,
"selected": true,
"text": "sudo sh -c 'apt update;apt install binutils-arm-none-eabi;'\n arm-none-eabi-as -mthumb foo.S -o foo.o\n $ echo nop > foo.S \n$ arm-none-eabi-as -mthumb foo.S -o foo.o\n$ echo $?\n0\n$ file foo.o\nfoo.o: ELF 32-bit LSB relocatable, ARM, EABI5 version 1 (SYSV), not stripped\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74615456",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18141702/"
] |
74,615,463
|
<p>I am trying to handle a dictionary that has a list as a value for a key named 'notes' , so I am trying to find the maximum element from that list and reassign the value with that maximum element from the list and also change the key value to 'top_notes' as follows.</p>
<pre><code>Input = top_note({ "name": "John", "notes": [3, 5, 4] })
Output = { "name": "John", "top_note": 5 }.
</code></pre>
<p>The output that I am getting is 'None'
Below is my code.</p>
<pre><code>class Solution(object):
def top_notes(self, di):
for key, values in di.items():
if key in di == 'notes':
lt = list(values)
maximum = max(lt)
di['top_notes'] = di['notes']
del di['notes']
di[maximum] = di[values]
del di[values]
return di
if __name__ == '__main__':
p = Solution()
dt = {"name": "John", "notes": [3, 5, 4]}
print(p.top_notes(dt))
</code></pre>
|
[
{
"answer_id": 74615502,
"author": "Hamatti",
"author_id": 1079129,
"author_profile": "https://Stackoverflow.com/users/1079129",
"pm_score": 0,
"selected": false,
"text": "if key in di == 'notes':\n key in di True True == 'notes' False if in di if key == 'notes':\n"
},
{
"answer_id": 74615564,
"author": "Gameplay",
"author_id": 15923186,
"author_profile": "https://Stackoverflow.com/users/15923186",
"pm_score": 1,
"selected": false,
"text": ".items() class Solution:\n def top_notes(self, di: dict)->dict:\n di[\"top_note\"] = max(di[\"notes\"])\n di.pop(\"notes\", None)\n return di\n"
},
{
"answer_id": 74615658,
"author": "Gabio",
"author_id": 12400214,
"author_profile": "https://Stackoverflow.com/users/12400214",
"pm_score": 1,
"selected": false,
"text": "if key in di == 'notes' di di == 'notes' lt = list(values) top_notes() def top_notes(self, di):\n if 'notes' in di.keys():\n di['top_note'] = max(di[\"notes\"])\n di.pop(\"notes\")\n return di\n"
},
{
"answer_id": 74615761,
"author": "Aman Agrawal",
"author_id": 20606228,
"author_profile": "https://Stackoverflow.com/users/20606228",
"pm_score": 0,
"selected": false,
"text": "class Solution(object):\n\n def top_notes(self, di):\n lt=[]\n for key, values in di.items():\n if key == 'notes':\n lt += list(values)\n maximum = max(lt)\n di['top_notes'] = di['notes']\n del di['notes']\n di['top_notes'] = maximum\n return di\n\nif __name__ == '__main__' :\n p = Solution()\n dt = {\"name\":\"John\", \"notes\": [3,5,4]}\n print(p.top_notes(dt))\n"
},
{
"answer_id": 74616187,
"author": "Arifa Chan",
"author_id": 19574157,
"author_profile": "https://Stackoverflow.com/users/19574157",
"pm_score": 0,
"selected": false,
"text": "dict.pop() class Solution(object):\n def top_notes(self, di):\n di['top_notes'] = di.pop('notes')\n di['top_notes'] = max(di['top_notes'])\n return di\n class Solution(object):\n def top_notes(self, di):\n di['top_notes'] = max(di.get('notes'))\n del di['notes']\n return di\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74615463",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20502753/"
] |
74,615,484
|
<p>I am trying to replace the value of a variable in parameters file using Replace(). This file which I am trying to edit accepts json format. But I am unable to do so. I am using this below script to do so. This only print the name of that particular field for which I am trying to replace a numeric value.</p>
<p>I tried this but it just displays the name of the variable which contains the old value I am trying to edit/replace.</p>
<pre><code>if($Value -like "*xyz*")
{
$Value -replace '$OldValue', '$NewValue'
}
else
{
Write-Host "$OldValue"
}
</code></pre>
<p>Please provide a solution so that I can replace a numeric value of a particular variable for json file.</p>
|
[
{
"answer_id": 74615502,
"author": "Hamatti",
"author_id": 1079129,
"author_profile": "https://Stackoverflow.com/users/1079129",
"pm_score": 0,
"selected": false,
"text": "if key in di == 'notes':\n key in di True True == 'notes' False if in di if key == 'notes':\n"
},
{
"answer_id": 74615564,
"author": "Gameplay",
"author_id": 15923186,
"author_profile": "https://Stackoverflow.com/users/15923186",
"pm_score": 1,
"selected": false,
"text": ".items() class Solution:\n def top_notes(self, di: dict)->dict:\n di[\"top_note\"] = max(di[\"notes\"])\n di.pop(\"notes\", None)\n return di\n"
},
{
"answer_id": 74615658,
"author": "Gabio",
"author_id": 12400214,
"author_profile": "https://Stackoverflow.com/users/12400214",
"pm_score": 1,
"selected": false,
"text": "if key in di == 'notes' di di == 'notes' lt = list(values) top_notes() def top_notes(self, di):\n if 'notes' in di.keys():\n di['top_note'] = max(di[\"notes\"])\n di.pop(\"notes\")\n return di\n"
},
{
"answer_id": 74615761,
"author": "Aman Agrawal",
"author_id": 20606228,
"author_profile": "https://Stackoverflow.com/users/20606228",
"pm_score": 0,
"selected": false,
"text": "class Solution(object):\n\n def top_notes(self, di):\n lt=[]\n for key, values in di.items():\n if key == 'notes':\n lt += list(values)\n maximum = max(lt)\n di['top_notes'] = di['notes']\n del di['notes']\n di['top_notes'] = maximum\n return di\n\nif __name__ == '__main__' :\n p = Solution()\n dt = {\"name\":\"John\", \"notes\": [3,5,4]}\n print(p.top_notes(dt))\n"
},
{
"answer_id": 74616187,
"author": "Arifa Chan",
"author_id": 19574157,
"author_profile": "https://Stackoverflow.com/users/19574157",
"pm_score": 0,
"selected": false,
"text": "dict.pop() class Solution(object):\n def top_notes(self, di):\n di['top_notes'] = di.pop('notes')\n di['top_notes'] = max(di['top_notes'])\n return di\n class Solution(object):\n def top_notes(self, di):\n di['top_notes'] = max(di.get('notes'))\n del di['notes']\n return di\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74615484",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20633979/"
] |
74,615,495
|
<p>I have a 1D array which is in fact a 2D matrix sampled this way:</p>
<pre><code>↓-------<------S <- start
>------->------↓
↓-------<------<
>------->------E <- end
</code></pre>
<p>For example</p>
<pre><code>B = 1 2 3 4
5 6 7 8
9 10 11 12
</code></pre>
<p>is coded as <code>A = [4, 3, 2, 1, 5, 6, 7, 8, 12, 11, 10, 9]</code>.<br />
The number of rows can be odd or even.</p>
<p>The following code works but is inefficient due to the loop (and no vectorization). <strong>How to do a more efficient Numpy "unzigzaging"?</strong></p>
<pre><code>import numpy as np
def unzigzag(z, numcols):
numrows = len(z) // numcols
a = np.zeros((numrows, numcols))
col = numcols - 1
row = 0
sign = -1
for i in range(numrows*numcols):
if col == -1:
col = 0
sign = 1
row += 1
if col == numcols:
col = numcols - 1
sign = -1
row += 1
a[row, col] = z[i]
col += sign
return a
A = [4, 3, 2, 1, 5, 6, 7, 8, 12, 11, 10, 9]
B = unzigzag(A, 4)
#[[ 1. 2. 3. 4.]
# [ 5. 6. 7. 8.]
# [ 9. 10. 11. 12.]]
</code></pre>
<p>If possible, it would be useful to have it working even if more dimensions than 1D:</p>
<ul>
<li>if A has shape <code>(12, )</code>, <code>unzigzag(A, numcols=4)</code> has shape (3, 4)</li>
<li>if A has shape <code>(12, 100)</code>, <code>unzigzag(A, numcols=4)</code> has shape (3, 4, 100)</li>
<li>if A has shape <code>(n, i, j, k, ...)</code>, <code>unzigzag(A, numcols)</code> has shape <code>(n/numcols, numcols, i, j, k, ...)</code></li>
</ul>
<hr />
<p>Edit: example for the n-dimensional case:</p>
<pre><code>import numpy as np
def unzigzag3(z, numcols):
numrows = z.shape[0] // numcols
new_shape = (numrows, numcols) + z.shape[1:]
a = np.zeros(new_shape)
col = numcols - 1
row = 0
sign = -1
for i in range(numrows*numcols):
if col == -1:
col = 0
sign = 1
row += 1
if col == numcols:
col = numcols - 1
sign = -1
row += 1
a[row, col, :] = z[i, :]
col += sign
return a
A = np.array([[4,4], [3, 3], [2, 2], [1, 1], [5, 5], [6, 6], [7, 7], [8, 8], [12, 12], [11, 11], [10, 10], [9, 9]])
print(A.shape) # (12, 2)
B = unzigzag3(A, 4)
print(B)
print(B.shape) # (3, 4, 2)
</code></pre>
|
[
{
"answer_id": 74615613,
"author": "Chris",
"author_id": 4718350,
"author_profile": "https://Stackoverflow.com/users/4718350",
"pm_score": 3,
"selected": true,
"text": "import numpy as np\n\na = np.array([4, 3, 2, 1, 5, 6, 7, 8, 12, 11, 10, 9])\nnumcols = 4\n\na = a.reshape(-1,numcols)\na[::2] = np.flip(a, axis=1)[::2]\n\nprint(a)\n [[ 1 2 3 4]\n [ 5 6 7 8]\n [ 9 10 11 12]]\n"
},
{
"answer_id": 74617309,
"author": "Basj",
"author_id": 1422096,
"author_profile": "https://Stackoverflow.com/users/1422096",
"pm_score": 1,
"selected": false,
"text": "import numpy as np\n\ndef unzigzag(z, numcols):\n new_shape = (z.shape[0] // numcols, numcols) + z.shape[1:]\n a = z.copy().reshape(new_shape)\n a[::2] = np.flip(a, axis=1)[::2]\n return a\n\nunzigzag(np.array([4, 3, 2, 1, 5, 6, 7, 8, 12, 11, 10, 9]), numcols=4)\n\n# [[ 1 2 3 4]\n# [ 5 6 7 8]\n# [ 9 10 11 12]]\n# shape: (3, 4)\n\nunzigzag(np.array([[4,4], [3, 3], [2, 2], [1, 1], [5, 5], [6, 6], [7, 7], [8, 8], [12, 12], [11, 11], [10, 10], [9, 9]]), numcols=4)\n\n# [[[ 1 1]\n# [ 2 2]\n# [ 3 3]\n# [ 4 4]]\n\n# [[ 5 5]\n# [ 6 6]\n# [ 7 7]\n# [ 8 8]]\n\n# [[ 9 9]\n# [10 10]\n# [11 11]\n# [12 12]]]\n# shape: (3, 4, 2)\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74615495",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1422096/"
] |
74,615,523
|
<p>Please help me. I have a code in which I try to open another page, but when I click on the button nothing happens, the console is also empty, how can I solve this or maybe I have an error somewhere?
P.S. I use Jquery
HTML, JS</p>
<pre><code><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>My Biograpy</title>
<link rel="stylesheet" href="libs/bootstrap-reboot.min.css">
<link rel="stylesheet" href="libs/bootstrap-grid.min.css">
<link rel="preconnect" href="https://fonts.gstatic.com">
<link href="https://fonts.googleapis.com/css2?family=Noto+Sans:ital,wght@0,400;0,700;1,400&display=swap" rel="stylesheet">
<link rel="stylesheet" href="css/styles.css">
</head>
<body>
<nav class="navbar">
<div class="container">
<a href="#" class="navbar-brand">BIOGRAHPY</a>
<div class="navbar-wrap">
<ul class="navbar-menu">
<li><button class="button1">About me</button></li>
<li><button class="button2">Portfolio</button></li>
<li><button class="button3">Place of study</button></li>
</ul>
<a href="#" class="contacts">Contacts</a>
</div>
</div>
</nav>
<div class="text1" id="option">
<p>Test</p>
</div>
<!-- <div class="portfolio" id="option2">Тест2</div> -->
<script type="text/javascript" src ="C:\Users\adeni\OneDrive\Desktop\site\jquery-3.6.1.min.js">
$('button1').click(function(){
window.location = $(this).find('.About_me').html();
})
</script>
</body>
</html>
</code></pre>
<p>CSS</p>
<pre><code>body {
position: relative;
font-family: 'Noto Sans', sans-serif;
font-size: 16px;
line-height: 1.6;
color: #000;
min-width: 320px;
overflow-x: hidden;
height: auto;
}
.navbar {
width: 100%;
height: 70px;
box-shadow: 0px 4px 10px rgba(0, 0, 0, .1);
}
.navbar .container {
height: inherit;
display: flex;;
justify-content: space-between;
align-items: center;
}
.navbar-menu {
list-style-type: none;
padding-left: 0px;
margin-bottom: 0px;
}
.navbar-menu li {
display: inline-block;
}
.navbar-menu li button {
border-radius: 60px;
border: none;
outline: none;
display: inline-block;
color: #000;
opacity: .6;
text-decoration: none;
padding: 10px;
transition: all .7s ease-in-out;
}
.navbar-menu li button:hover {
opacity: 1;
}
.text1 {
display: none;
}
.visible_block {
display: flex;
}
.navbar-wrap {
display: flex;
flex-flow: row nowrap;
}
.contacts {
margin-left: 25px;
padding: 10px 30px;
background-color: lightcoral;
border-radius: 90px;
color: #fff;
text-decoration: none;
box-shadow: 0 4px 6px rgba(255, 127, 80, .2);
transition: all .7s ease-in;
}
.contacts:hover {
box-shadow: 0 9px 9px rgba(255, 127, 80, .5);
transform: scale(1.050);
color: #000;
}
.navbar-brand {
font-weight: : 700;
font-size: 26px;
text-decoration: none;
color: #000;
transition: all .7s ease-out;
}
.navbar-brand:hover {
color: lightcoral;
}
</code></pre>
<p>I tried to change the names that apply to classes, or to set types and ids at all, but it also did not lead to anything</p>
|
[
{
"answer_id": 74615613,
"author": "Chris",
"author_id": 4718350,
"author_profile": "https://Stackoverflow.com/users/4718350",
"pm_score": 3,
"selected": true,
"text": "import numpy as np\n\na = np.array([4, 3, 2, 1, 5, 6, 7, 8, 12, 11, 10, 9])\nnumcols = 4\n\na = a.reshape(-1,numcols)\na[::2] = np.flip(a, axis=1)[::2]\n\nprint(a)\n [[ 1 2 3 4]\n [ 5 6 7 8]\n [ 9 10 11 12]]\n"
},
{
"answer_id": 74617309,
"author": "Basj",
"author_id": 1422096,
"author_profile": "https://Stackoverflow.com/users/1422096",
"pm_score": 1,
"selected": false,
"text": "import numpy as np\n\ndef unzigzag(z, numcols):\n new_shape = (z.shape[0] // numcols, numcols) + z.shape[1:]\n a = z.copy().reshape(new_shape)\n a[::2] = np.flip(a, axis=1)[::2]\n return a\n\nunzigzag(np.array([4, 3, 2, 1, 5, 6, 7, 8, 12, 11, 10, 9]), numcols=4)\n\n# [[ 1 2 3 4]\n# [ 5 6 7 8]\n# [ 9 10 11 12]]\n# shape: (3, 4)\n\nunzigzag(np.array([[4,4], [3, 3], [2, 2], [1, 1], [5, 5], [6, 6], [7, 7], [8, 8], [12, 12], [11, 11], [10, 10], [9, 9]]), numcols=4)\n\n# [[[ 1 1]\n# [ 2 2]\n# [ 3 3]\n# [ 4 4]]\n\n# [[ 5 5]\n# [ 6 6]\n# [ 7 7]\n# [ 8 8]]\n\n# [[ 9 9]\n# [10 10]\n# [11 11]\n# [12 12]]]\n# shape: (3, 4, 2)\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74615523",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20634333/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.