qid
int64 4
19.1M
| question
stringlengths 18
48.3k
| answers
list | date
stringlengths 10
10
| metadata
list |
|---|---|---|---|---|
74,492,675
|
<p>Code can only find and change one image link in the text. If it's more than one, it doesn't work. How can I get it to detect multiple image links?</p>
<pre><code>$sad222 = "somthing text bla bla bla ...... https://www.indyturk.com/sites/default/files/styles/150x100/public/article/main_image/2022/08/02/984246-1125154792.jpg asdas https://www.indyturk.com/sites/default/files/styles/800x600/public/article/main_image/2022/11/18/1055251-759331593.jpg 121das";
function findAndChangeImgLinksInStrings($string)
{
$reg_exUrl = '/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/m';
if (preg_match_all($reg_exUrl, $string, $urls, PREG_SET_ORDER, 0)) {
foreach ($urls as $url) {
$newLinks = $url[0][0];
if (strstr($newLinks, ":") === false) {
$link = 'https://' . $newLinks;
} else {
$link = $newLinks;
}
$exploded = explode($link, $string);
$string_before = $exploded[0];
$string_after = $exploded[1];
if (strtolower(substr($link, 0, 7)) == "http://" || strtolower(substr($link, 0, 7)) == "ftps://" || strtolower(substr($link, 0, 8)) == "https://" || strtolower(substr($link, 0, 6)) == "ftp://") {
if (strtolower(substr($link, strlen($link) - 4, 4)) == ".jpg" || strtolower(substr($link, strlen($link) - 4, 4)) == ".jpe" || strtolower(substr($link, strlen($link) - 4, 4)) == ".jif" || strtolower(substr($link, strlen($link) - 4, 4)) == ".jfi" || strtolower(substr($link, strlen($link) - 4, 4)) == ".gif" || strtolower(substr($link, strlen($link) - 4, 4)) == ".png" || strtolower(substr($link, strlen($link) - 4, 4)) == ".bmp" || strtolower(substr($link, strlen($link) - 4, 4)) == ".dib" || strtolower(substr($link, strlen($link) - 4, 4)) == ".ico" || strtolower(substr($link, strlen($link) - 5, 5)) == ".jpeg" || strtolower(substr($link, strlen($link) - 5, 5)) == ".jfif" || strtolower(substr($link, strlen($link) - 5, 5)) == ".apng" || strtolower(substr($link, strlen($link) - 5, 5)) == ".tiff" || strtolower(substr($link, strlen($link) - 4, 4)) == ".tif") {
$imageCode = erisimKoduOlustur();
getFile($link, '/images/' . $imageCode . strtolower(substr($link, strlen($link) - 4, 4)));
}
}
return $string_before . '<a class="noteImageInQNote" href="https://example.com/images/' . $imageCode . strtolower(substr($link, strlen($link) - 4, 4)) . '" target="_blank"><img class="noteImageInQNote" src="https://example.com/images/' . $imageCode . strtolower(substr($link, strlen($link) - 4, 4)) . '"></a>' . $string_after;
}
}
return $string;
}
echo findAndChangeImgLinksInStrings($sad222);
</code></pre>
|
[
{
"answer_id": 74495876,
"author": "Cristian Antonio Rosas Ayala",
"author_id": 20543270,
"author_profile": "https://Stackoverflow.com/users/20543270",
"pm_score": 2,
"selected": false,
"text": "npm i @bahmutov/cypress-esbuild-preprocessor \n"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74492675",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18491093/"
] |
74,492,697
|
<p>This solution is for the 1-12 exercise from the C programming language book. The question is to write a program that prints its input one word per line.</p>
<p>I found the following solution:</p>
<pre><code>#include <stdio.h>
int main(void)
{
int c;
int inspace;
inspace = 0;
while((c = getchar()) != EOF)
{
if(c == ' ' || c == '\t' || c == '\n')
{
if(inspace == 0)
{
inspace = 1;
putchar('\n');
}
/* else, don't print anything */
}
else
{
inspace = 0;
putchar(c);
}
}
return 0;
}
</code></pre>
<p>Can someone please explain why is inspace == 0 used in the if argument and how the logic works later with inspace = 1 in the statements?</p>
<p>Does the 0 indicate space in the input?</p>
|
[
{
"answer_id": 74495876,
"author": "Cristian Antonio Rosas Ayala",
"author_id": 20543270,
"author_profile": "https://Stackoverflow.com/users/20543270",
"pm_score": 2,
"selected": false,
"text": "npm i @bahmutov/cypress-esbuild-preprocessor \n"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74492697",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20541333/"
] |
74,492,706
|
<p>I created a feature branch from master but I should have done it from develop branch how can I fix it?</p>
<p>For visualization I've done this:</p>
<pre><code> D---E---F develop
/
A---B---C master
\
G---H feature
</code></pre>
<p>but I should have done this:</p>
<pre><code> G---H feature
/
D---E---F develop
/
A---B---C master
</code></pre>
<p>I haven't tried anything, I am not sure how to approach this</p>
|
[
{
"answer_id": 74492727,
"author": "knittl",
"author_id": 112968,
"author_profile": "https://Stackoverflow.com/users/112968",
"pm_score": 1,
"selected": false,
"text": "feature develop git rebase git rebase --onto develop master feature\n master feature develop develop git merge git checkout feature\ngit merge develop\n"
},
{
"answer_id": 74492734,
"author": "chepner",
"author_id": 1126841,
"author_profile": "https://Stackoverflow.com/users/1126841",
"pm_score": 2,
"selected": false,
"text": "git rebase feature git checkout feature\ngit rebase develop\n"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74492706",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18666815/"
] |
74,492,769
|
<p>I have two files, <code>file.component.ts</code> containing:</p>
<pre><code> removeComma(e) {
const USER_VAL = parseFloat(e.target.value.replace(/,/g, ''));
}
</code></pre>
<p>and my test file <code>file.component.specs.ts</code> containing:</p>
<pre><code>describe('removeComma()', () => {
it('Should remove commas from value', () => {
const mockEvent = {target: {value: '1,234,567.85,'}};
/* missing mock event functionality here*/
expect(USER_VALUE).toEqual('1234567.85');
});
});
</code></pre>
<p>I want to be able to check that, after <code>removeComma(e)</code> is run, <code>USER_VAL</code> is equal to <code>'1234567.89'</code> (that is, the commas have been removed).</p>
<p>The functionality already works for the comma replace.</p>
|
[
{
"answer_id": 74492727,
"author": "knittl",
"author_id": 112968,
"author_profile": "https://Stackoverflow.com/users/112968",
"pm_score": 1,
"selected": false,
"text": "feature develop git rebase git rebase --onto develop master feature\n master feature develop develop git merge git checkout feature\ngit merge develop\n"
},
{
"answer_id": 74492734,
"author": "chepner",
"author_id": 1126841,
"author_profile": "https://Stackoverflow.com/users/1126841",
"pm_score": 2,
"selected": false,
"text": "git rebase feature git checkout feature\ngit rebase develop\n"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74492769",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14197885/"
] |
74,492,803
|
<p>Function named minmax_index has two parameters: one of type list and another type bool. If the Boolean parameter refers to True, the function returns a tuple containing the minimum and its index; and if it refers to False, it returns a tuple containing the maximum and its index.</p>
<p>eg: minmax_index([1,2,3,4],False)</p>
<p>(4,3)</p>
<p>Please modify it to make it work if possible,</p>
<p>Thanks,</p>
|
[
{
"answer_id": 74492727,
"author": "knittl",
"author_id": 112968,
"author_profile": "https://Stackoverflow.com/users/112968",
"pm_score": 1,
"selected": false,
"text": "feature develop git rebase git rebase --onto develop master feature\n master feature develop develop git merge git checkout feature\ngit merge develop\n"
},
{
"answer_id": 74492734,
"author": "chepner",
"author_id": 1126841,
"author_profile": "https://Stackoverflow.com/users/1126841",
"pm_score": 2,
"selected": false,
"text": "git rebase feature git checkout feature\ngit rebase develop\n"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74492803",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20214604/"
] |
74,492,804
|
<p>I'm new to programming and JavaScript, i tried creating an interface for a code challenge, but i keep getting this error message:</p>
<pre><code>Type '{ 1100: { albumTitle: string; artist: string; tracks: string[]; }; 2468: { albumTitle: string; artist: string; tracks: string[]; }; 1245: { artist: string; tracks: never[]; }; 5439: { albumTitle: string; }; }' is not assignable to type 'collectionInfo'.
Object literal may only specify known properties, and '1100' does not exist in type 'collectionInfo'.ts(2322)
</code></pre>
<p>Please i need your suggestions on how to resolve this or how to create a typescript interface that will eliminate this error message.</p>
<pre><code>
This my typescript interface attempt:
interface collectionInfo {
id : {
albumTitle: string | number |;
artist: string | number |;
tracks: string[] | number[] | null;
}
}
const recordCollection: collectionInfo = {
1100: {
albumTitle: "Prisoner",
artist: "Lucky Dube",
tracks: ["Prisoner", "Don\'t Cry"],
},
</code></pre>
|
[
{
"answer_id": 74492976,
"author": "Kyle Valderrama",
"author_id": 11609663,
"author_profile": "https://Stackoverflow.com/users/11609663",
"pm_score": 1,
"selected": false,
"text": "interface CollectionInfo {\n [id: number]: {\n albumTitle: string | number;\n artist: string | number;\n tracks: string[] | number[] | null; \n }\n}\n interface CollectionInfo {\n id: number;\n albumTitle: string; // I recommend sticking to one type only\n artist: string | number;\n tracks?: string[] | number[]; // if you are trying to add optional property, use ? to make it optional\n}\n\nconst recordCollection: CollectionInfo = {\n id: 1100,\n albumTitle: \"Prisoner\",\n artist: \"Lucky Dube\",\n tracks: [\"Prisoner\", \"Don't Cry\"]\n}\n\n// Usage\nconsole.log(recordCollection.id); // 1100\nconsole.log(recordCollection.albumTitle); // Prisoner\n"
},
{
"answer_id": 74492986,
"author": "Asad Gulzar",
"author_id": 12291046,
"author_profile": "https://Stackoverflow.com/users/12291046",
"pm_score": -1,
"selected": false,
"text": "interface collectionInfo {\n [id: number] : {\n albumTitle: string | number ;\n artist: string | number ;\n tracks: string[] | number[] | null; \n }\n }\n"
},
{
"answer_id": 74492997,
"author": "Amirhossein",
"author_id": 11342834,
"author_profile": "https://Stackoverflow.com/users/11342834",
"pm_score": 1,
"selected": true,
"text": "interface collectionInfo {\n [id: number] : {\n albumTitle: string | number | null;\n artist: string | number | null;\n tracks: string[] | number[] | null; \n }\n}\n\nconst recordCollection: collectionInfo = {\n 1100: {\n albumTitle: \"Prisoner\",\n artist: \"Lucky Dube\",\n tracks: [\"Prisoner\", \"Don\\'t Cry\"],\n }\n}\n interface collectionInfo {\n id: number;\n albumTitle: string | number | null;\n artist: string | number | null;\n tracks: string[] | number[] | null;\n}\n\nconst recordCollection: collectionInfo[] = [\n {\n id: 1100,\n albumTitle: \"Prisoner\",\n artist: \"Lucky Dube\",\n tracks: [\"Prisoner\", \"Don\\'t Cry\"],\n }\n]\n"
},
{
"answer_id": 74493018,
"author": "Kevin Pastor",
"author_id": 7817501,
"author_profile": "https://Stackoverflow.com/users/7817501",
"pm_score": 0,
"selected": false,
"text": "collectionInfo id interface CollectionsInfo {\n [id: number]: {\n albumTitle: string | number;\n artist: string | number;\n tracks: string[] | number[] | null; \n }\n}\n interface CollectionInfo {\n albumTitle: string | number;\n artist: string | number;\n tracks: string[] | number[] | null;\n}\n\ntype CollectionsInfo = Record<number, CollectionInfo>;\n"
},
{
"answer_id": 74493098,
"author": "Chinedu Orie",
"author_id": 13403926,
"author_profile": "https://Stackoverflow.com/users/13403926",
"pm_score": 0,
"selected": false,
"text": "| recordCollection 1100 id collectionInfo interface collectionInfo {\n id : {\n albumTitle: string | number;\n artist: string | number;\n tracks: string[] | number[] | null; \n }\n}\nconst recordCollection: collectionInfo = {\n id: {\n albumTitle: \"Prisoner\",\n artist: \"Lucky Dube\",\n tracks: [\"Prisoner\", \"Don\\'t Cry\"],\n },\n} interface collectionInfo {\n [key: number] : {\n albumTitle: string | number;\n artist: string | number;\n tracks: string[] | number[] | null; \n }\n}\nconst recordCollection: collectionInfo = {\n 1100: {\n albumTitle: \"Prisoner\",\n artist: \"Lucky Dube\",\n tracks: [\"Prisoner\", \"Don\\'t Cry\"],\n },\n}"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74492804",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20541292/"
] |
74,492,845
|
<p>previous issue</p>
<p><a href="https://stackoverflow.com/questions/74490898/building-a-rating-app-using-strapi-and-react-throws-errors">building a rating app using strapi and react throws errors</a> is solved.</p>
<p>But, the records are not getting added to the admin.</p>
<p>can anyone help on this?</p>
<p>This is the code to add and read reviews from strapi admin,</p>
<pre><code>
function App() {
const stars = Array(5).fill(0);
const [currentValue, setCurrentValue] = React.useState(0);
const [hoverValue, setHoverValue] = React.useState(undefined);
const handleClick = (value) => {
setCurrentValue(value);
};
const handleMouseOver = (value) => {
setHoverValue(value);
};
const [review, setReview] = useState({});
const [reviews, setReviews] = useState([]);
useEffect(() => {
const fetchData = async () => {
const result = await api.readReviews();
//console.log(result.data);
setReviews(result.data.data);
};
fetchData();
}, []);
const createReview = async () => {
try {
//console.log(review);
const data = await api.createReview(review);
setReview([...reviews, data]);
} catch (error) {
//console.log(error);
}
};
let [reviewCount, setreviewCount] = useState([]);
const setCountFxn = (no) => {
setReview(no);
};
return (
<>
<form>
<div style={styles.container}>
<h2>RATE OUR SERVICE</h2>
<div style={styles.stars}>
{stars.map((_, index) => {
return (
<FaStar
key={index}
size={24}
style={{
marginRight: 10,
cursor: 'pointer',
}}
color={(hoverValue || currentValue) > index ? colors.orange : colors.grey}
onClick={() => {
setReview({ ...review, Rating: index + 1 });
}}
onMouseOver={() => handleMouseOver(index + 1)}
/>
);
})}
</div>
<div>
<input
type='text'
placeholder='input your name'
required
style={styles.input}
value={review.Name}
onChange={(e) => setReview({ ...review, Name: e.target.value })}
/>
</div>
<textarea
placeholder="what's your feedback"
required
style={styles.textarea}
value={review.review}
onChange={(e) => setReview({ ...review, review: e.target.value })}
/>
<button type='submit' style={styles.button} className='btn btn-primary' onClick={createReview}>
submit
</button>
</div>
</form>
<section id='reviews'>
<div className='reviews-heading'>
<span>REVIEWS FROM CUSTOMERS</span>
</div>
<div className='container'>
<div className='row'>
{reviews.map((review, i) => (
<div key={review.id} className='col-md-6'>
<div className='reviews-box'>
<div className='box-top'>
<div className='profile'>
<div className='name-user'>
<strong>{review.attributes.Title}</strong>
</div>
</div>
<div style={styles.stars}>
{Array.from({ length: review.attributes.Rating }).map((i) => (
<FaStar key={i} size={18} color={colors.orange} />
))}
</div>
</div>
<div className='client-comment'>{review.attributes.Body}</div>
</div>
</div>
))}
</div>
</div>
</section>
</>
);
}
export default App;
</code></pre>
<p>The form gets submitted and reloads after submit, but the record does not get added to strapi admin. I've set the roles of the data to public.</p>
<p>thanks
Nabi</p>
|
[
{
"answer_id": 74492976,
"author": "Kyle Valderrama",
"author_id": 11609663,
"author_profile": "https://Stackoverflow.com/users/11609663",
"pm_score": 1,
"selected": false,
"text": "interface CollectionInfo {\n [id: number]: {\n albumTitle: string | number;\n artist: string | number;\n tracks: string[] | number[] | null; \n }\n}\n interface CollectionInfo {\n id: number;\n albumTitle: string; // I recommend sticking to one type only\n artist: string | number;\n tracks?: string[] | number[]; // if you are trying to add optional property, use ? to make it optional\n}\n\nconst recordCollection: CollectionInfo = {\n id: 1100,\n albumTitle: \"Prisoner\",\n artist: \"Lucky Dube\",\n tracks: [\"Prisoner\", \"Don't Cry\"]\n}\n\n// Usage\nconsole.log(recordCollection.id); // 1100\nconsole.log(recordCollection.albumTitle); // Prisoner\n"
},
{
"answer_id": 74492986,
"author": "Asad Gulzar",
"author_id": 12291046,
"author_profile": "https://Stackoverflow.com/users/12291046",
"pm_score": -1,
"selected": false,
"text": "interface collectionInfo {\n [id: number] : {\n albumTitle: string | number ;\n artist: string | number ;\n tracks: string[] | number[] | null; \n }\n }\n"
},
{
"answer_id": 74492997,
"author": "Amirhossein",
"author_id": 11342834,
"author_profile": "https://Stackoverflow.com/users/11342834",
"pm_score": 1,
"selected": true,
"text": "interface collectionInfo {\n [id: number] : {\n albumTitle: string | number | null;\n artist: string | number | null;\n tracks: string[] | number[] | null; \n }\n}\n\nconst recordCollection: collectionInfo = {\n 1100: {\n albumTitle: \"Prisoner\",\n artist: \"Lucky Dube\",\n tracks: [\"Prisoner\", \"Don\\'t Cry\"],\n }\n}\n interface collectionInfo {\n id: number;\n albumTitle: string | number | null;\n artist: string | number | null;\n tracks: string[] | number[] | null;\n}\n\nconst recordCollection: collectionInfo[] = [\n {\n id: 1100,\n albumTitle: \"Prisoner\",\n artist: \"Lucky Dube\",\n tracks: [\"Prisoner\", \"Don\\'t Cry\"],\n }\n]\n"
},
{
"answer_id": 74493018,
"author": "Kevin Pastor",
"author_id": 7817501,
"author_profile": "https://Stackoverflow.com/users/7817501",
"pm_score": 0,
"selected": false,
"text": "collectionInfo id interface CollectionsInfo {\n [id: number]: {\n albumTitle: string | number;\n artist: string | number;\n tracks: string[] | number[] | null; \n }\n}\n interface CollectionInfo {\n albumTitle: string | number;\n artist: string | number;\n tracks: string[] | number[] | null;\n}\n\ntype CollectionsInfo = Record<number, CollectionInfo>;\n"
},
{
"answer_id": 74493098,
"author": "Chinedu Orie",
"author_id": 13403926,
"author_profile": "https://Stackoverflow.com/users/13403926",
"pm_score": 0,
"selected": false,
"text": "| recordCollection 1100 id collectionInfo interface collectionInfo {\n id : {\n albumTitle: string | number;\n artist: string | number;\n tracks: string[] | number[] | null; \n }\n}\nconst recordCollection: collectionInfo = {\n id: {\n albumTitle: \"Prisoner\",\n artist: \"Lucky Dube\",\n tracks: [\"Prisoner\", \"Don\\'t Cry\"],\n },\n} interface collectionInfo {\n [key: number] : {\n albumTitle: string | number;\n artist: string | number;\n tracks: string[] | number[] | null; \n }\n}\nconst recordCollection: collectionInfo = {\n 1100: {\n albumTitle: \"Prisoner\",\n artist: \"Lucky Dube\",\n tracks: [\"Prisoner\", \"Don\\'t Cry\"],\n },\n}"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74492845",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3986620/"
] |
74,492,856
|
<p>I'm trying to update the <a href="https://www.npmjs.com/package/swiper" rel="nofollow noreferrer">swiper.js</a> library</p>
<p>I was using swiper version: <strong>6.8.2</strong>,</p>
<p>Now I would like to upgrade it to a newer version <strong>7.4.1</strong></p>
<p>My App is written in React and Node js with SSR( I'm not using Next.js) and Node version: v14.11.0</p>
<p>Here is how my component code, looks like</p>
<pre><code>import React from 'react'
import { Swiper, SwiperSlide } from 'swiper/react'
const CustomView = () => {
return (
<Swiper>
</Swiper>
)
}
export default CustomView
</code></pre>
<p>When I run it I'm getting the following error in terminal</p>
<pre><code>"message":"Must use import to load ES Module: /Users/Projects/ReactStarter/node_modules/swiper/react/swiper-react.js\nrequire() of ES modules is not supported.
</code></pre>
<p>Then I change Import to:</p>
<pre><code>import { Swiper, SwiperSlide } from 'swiper/react/swiper-react.js'
</code></pre>
<p>In Terminal error is printed:</p>
<pre><code>"message":"Package subpath './react/swiper-react.js' is not defined by \"exports\"
</code></pre>
<p>Is there any way I can bypass this, since I'm using <strong>webpack</strong> so maybe I can somehow ignore it or something else</p>
|
[
{
"answer_id": 74492976,
"author": "Kyle Valderrama",
"author_id": 11609663,
"author_profile": "https://Stackoverflow.com/users/11609663",
"pm_score": 1,
"selected": false,
"text": "interface CollectionInfo {\n [id: number]: {\n albumTitle: string | number;\n artist: string | number;\n tracks: string[] | number[] | null; \n }\n}\n interface CollectionInfo {\n id: number;\n albumTitle: string; // I recommend sticking to one type only\n artist: string | number;\n tracks?: string[] | number[]; // if you are trying to add optional property, use ? to make it optional\n}\n\nconst recordCollection: CollectionInfo = {\n id: 1100,\n albumTitle: \"Prisoner\",\n artist: \"Lucky Dube\",\n tracks: [\"Prisoner\", \"Don't Cry\"]\n}\n\n// Usage\nconsole.log(recordCollection.id); // 1100\nconsole.log(recordCollection.albumTitle); // Prisoner\n"
},
{
"answer_id": 74492986,
"author": "Asad Gulzar",
"author_id": 12291046,
"author_profile": "https://Stackoverflow.com/users/12291046",
"pm_score": -1,
"selected": false,
"text": "interface collectionInfo {\n [id: number] : {\n albumTitle: string | number ;\n artist: string | number ;\n tracks: string[] | number[] | null; \n }\n }\n"
},
{
"answer_id": 74492997,
"author": "Amirhossein",
"author_id": 11342834,
"author_profile": "https://Stackoverflow.com/users/11342834",
"pm_score": 1,
"selected": true,
"text": "interface collectionInfo {\n [id: number] : {\n albumTitle: string | number | null;\n artist: string | number | null;\n tracks: string[] | number[] | null; \n }\n}\n\nconst recordCollection: collectionInfo = {\n 1100: {\n albumTitle: \"Prisoner\",\n artist: \"Lucky Dube\",\n tracks: [\"Prisoner\", \"Don\\'t Cry\"],\n }\n}\n interface collectionInfo {\n id: number;\n albumTitle: string | number | null;\n artist: string | number | null;\n tracks: string[] | number[] | null;\n}\n\nconst recordCollection: collectionInfo[] = [\n {\n id: 1100,\n albumTitle: \"Prisoner\",\n artist: \"Lucky Dube\",\n tracks: [\"Prisoner\", \"Don\\'t Cry\"],\n }\n]\n"
},
{
"answer_id": 74493018,
"author": "Kevin Pastor",
"author_id": 7817501,
"author_profile": "https://Stackoverflow.com/users/7817501",
"pm_score": 0,
"selected": false,
"text": "collectionInfo id interface CollectionsInfo {\n [id: number]: {\n albumTitle: string | number;\n artist: string | number;\n tracks: string[] | number[] | null; \n }\n}\n interface CollectionInfo {\n albumTitle: string | number;\n artist: string | number;\n tracks: string[] | number[] | null;\n}\n\ntype CollectionsInfo = Record<number, CollectionInfo>;\n"
},
{
"answer_id": 74493098,
"author": "Chinedu Orie",
"author_id": 13403926,
"author_profile": "https://Stackoverflow.com/users/13403926",
"pm_score": 0,
"selected": false,
"text": "| recordCollection 1100 id collectionInfo interface collectionInfo {\n id : {\n albumTitle: string | number;\n artist: string | number;\n tracks: string[] | number[] | null; \n }\n}\nconst recordCollection: collectionInfo = {\n id: {\n albumTitle: \"Prisoner\",\n artist: \"Lucky Dube\",\n tracks: [\"Prisoner\", \"Don\\'t Cry\"],\n },\n} interface collectionInfo {\n [key: number] : {\n albumTitle: string | number;\n artist: string | number;\n tracks: string[] | number[] | null; \n }\n}\nconst recordCollection: collectionInfo = {\n 1100: {\n albumTitle: \"Prisoner\",\n artist: \"Lucky Dube\",\n tracks: [\"Prisoner\", \"Don\\'t Cry\"],\n },\n}"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74492856",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4397306/"
] |
74,492,859
|
<p>When I tap on a button I want to navigate to the second screen Focus on TextField(there is only one) and raise a keyboard.</p>
<p>I successfully focused when I taped on a widget on the same screen using FocusNode.</p>
|
[
{
"answer_id": 74492976,
"author": "Kyle Valderrama",
"author_id": 11609663,
"author_profile": "https://Stackoverflow.com/users/11609663",
"pm_score": 1,
"selected": false,
"text": "interface CollectionInfo {\n [id: number]: {\n albumTitle: string | number;\n artist: string | number;\n tracks: string[] | number[] | null; \n }\n}\n interface CollectionInfo {\n id: number;\n albumTitle: string; // I recommend sticking to one type only\n artist: string | number;\n tracks?: string[] | number[]; // if you are trying to add optional property, use ? to make it optional\n}\n\nconst recordCollection: CollectionInfo = {\n id: 1100,\n albumTitle: \"Prisoner\",\n artist: \"Lucky Dube\",\n tracks: [\"Prisoner\", \"Don't Cry\"]\n}\n\n// Usage\nconsole.log(recordCollection.id); // 1100\nconsole.log(recordCollection.albumTitle); // Prisoner\n"
},
{
"answer_id": 74492986,
"author": "Asad Gulzar",
"author_id": 12291046,
"author_profile": "https://Stackoverflow.com/users/12291046",
"pm_score": -1,
"selected": false,
"text": "interface collectionInfo {\n [id: number] : {\n albumTitle: string | number ;\n artist: string | number ;\n tracks: string[] | number[] | null; \n }\n }\n"
},
{
"answer_id": 74492997,
"author": "Amirhossein",
"author_id": 11342834,
"author_profile": "https://Stackoverflow.com/users/11342834",
"pm_score": 1,
"selected": true,
"text": "interface collectionInfo {\n [id: number] : {\n albumTitle: string | number | null;\n artist: string | number | null;\n tracks: string[] | number[] | null; \n }\n}\n\nconst recordCollection: collectionInfo = {\n 1100: {\n albumTitle: \"Prisoner\",\n artist: \"Lucky Dube\",\n tracks: [\"Prisoner\", \"Don\\'t Cry\"],\n }\n}\n interface collectionInfo {\n id: number;\n albumTitle: string | number | null;\n artist: string | number | null;\n tracks: string[] | number[] | null;\n}\n\nconst recordCollection: collectionInfo[] = [\n {\n id: 1100,\n albumTitle: \"Prisoner\",\n artist: \"Lucky Dube\",\n tracks: [\"Prisoner\", \"Don\\'t Cry\"],\n }\n]\n"
},
{
"answer_id": 74493018,
"author": "Kevin Pastor",
"author_id": 7817501,
"author_profile": "https://Stackoverflow.com/users/7817501",
"pm_score": 0,
"selected": false,
"text": "collectionInfo id interface CollectionsInfo {\n [id: number]: {\n albumTitle: string | number;\n artist: string | number;\n tracks: string[] | number[] | null; \n }\n}\n interface CollectionInfo {\n albumTitle: string | number;\n artist: string | number;\n tracks: string[] | number[] | null;\n}\n\ntype CollectionsInfo = Record<number, CollectionInfo>;\n"
},
{
"answer_id": 74493098,
"author": "Chinedu Orie",
"author_id": 13403926,
"author_profile": "https://Stackoverflow.com/users/13403926",
"pm_score": 0,
"selected": false,
"text": "| recordCollection 1100 id collectionInfo interface collectionInfo {\n id : {\n albumTitle: string | number;\n artist: string | number;\n tracks: string[] | number[] | null; \n }\n}\nconst recordCollection: collectionInfo = {\n id: {\n albumTitle: \"Prisoner\",\n artist: \"Lucky Dube\",\n tracks: [\"Prisoner\", \"Don\\'t Cry\"],\n },\n} interface collectionInfo {\n [key: number] : {\n albumTitle: string | number;\n artist: string | number;\n tracks: string[] | number[] | null; \n }\n}\nconst recordCollection: collectionInfo = {\n 1100: {\n albumTitle: \"Prisoner\",\n artist: \"Lucky Dube\",\n tracks: [\"Prisoner\", \"Don\\'t Cry\"],\n },\n}"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74492859",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20524109/"
] |
74,492,876
|
<p>I have 2 DAGs: dag_a and dag_b (dag_a -> dag_b)
After dag_a is executed, TriggerDagRunOperator is called, which starts dag_b. The problem is, when dag_b is off (paused), dag_a's TriggerDagRunOperator creates scheduled runs in dag_b that queue up for as long as dag_a is running. After turning dag_b back ON, the execution of tasks from the queue begins.
I'm trying to find a solution for TriggerDagRunOperator, namely a conditionally_trigger function that would skip the execution of the TriggerDagRunOperator task if dag_b is paused (OFF). How can i do this?</p>
|
[
{
"answer_id": 74494126,
"author": "Emma",
"author_id": 2956135,
"author_profile": "https://Stackoverflow.com/users/2956135",
"pm_score": 2,
"selected": true,
"text": "ShortCircuitOperator dag_b dag_b dag_a = TriggerDagRunOperator(\n trigger_dag_id='dag_a',\n ...\n)\n\npause_check = ShortCircuitOperator(\n task_id='pause_check',\n python_callable=is_dag_paused,\n op_kwargs={\n 'dag_id': 'dag_b'\n }\n)\n\ndag_b = TriggerDagRunOperator(\n trigger_dag_id='dag_b',\n ...\n)\n\ndag_a >> pause_check >> dag_b\n is_dag_paused def is_dag_paused(**kwargs):\n import requests\n from requests.auth import HTTPBasicAuth\n \n dag_id = kwargs['dag_id']\n res = requests.get(f'http://{airflow_host}/api/v1/dags/{dag_id}/details',\n auth=HTTPBasicAuth('username', 'pasword')) # The auth method could be different for you. \n\n if res.status_code == 200:\n rjson = res.json()\n # if you return True, the downstream tasks will be executed\n # if False, it will be skipped\n return not rjson['is_paused']\n else:\n print('Error: ', res)\n exit(1)\n"
},
{
"answer_id": 74530091,
"author": "Andrew Yar",
"author_id": 14884187,
"author_profile": "https://Stackoverflow.com/users/14884187",
"pm_score": 0,
"selected": false,
"text": "import airflow.settings\nfrom airflow.models import DagModel\ndef check_status_dag(*op_args):\n session = airflow.settings.Session()\n qry = session.query(DagModel).filter(DagModel.dag_id == op_args[0])\n if not qry.value(DagModel.is_paused):\n return op_args[1]\n else: return op_args[2]\n start = DummyOperator(\n task_id = 'start',\n dag=dag\n )\n\ncheck_dag_B = BranchPythonOperator(\n task_id = \"check_dag_B\",\n python_callable = check_status_dag,\n op_args = ['dag_B','trigger_dag_B','skip_trigger_dag_B'],\n trigger_rule = 'all_done',\n dag = dag\n)\n\ntrigger_dag_B = TriggerDagRunOperator(\n task_id = 'trigger_dag_B',\n trigger_dag_id = 'dag_B',\n dag = dag\n)\n\nskip_trigger_dag_B = DummyOperator(\n task_id = 'skip_trigger_dag_B',\n dag = dag\n)\n\nfinish = DummyOperator(\n task_id = 'finish',\n trigger_rule = 'all_done',\n dag=dag\n)\n\nstart >> check_dag_B >> [trigger_dag_B, skip_trigger_dag_B] >> finish#or continue working\n"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74492876",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14884187/"
] |
74,492,884
|
<p>I'm writing a hashing function to help speed up string comparisons.<br />
My codebase compares strings against a lot of <code>const char[]</code> constants, and it would be ideal if I could work with hashes instead. I went ahead and translated xxHash to modern C++, and I have a working prototype that does work at compile time, but I'm not sure what the function definition should be for the main hashing function.</p>
<p>At the moment, I have this:</p>
<pre><code>template <size_t arr_size>
constexpr uint64_t xxHash64(const char(data)[arr_size])
{...}
</code></pre>
<p>This does work, and I am able to do a compile time call like this</p>
<pre><code>constexpr char myString[] = "foobar";
constexpr uint64_t hashedString = xxHash64<sizeof myString>(myString);
</code></pre>
<p>[Find a minimal <a href="https://godbolt.org/z/foTdxMz77" rel="nofollow noreferrer">example here</a>]</p>
<p>All good so far, but I would like to add a user-defined literal wrapper function for some eye candy, and this is where the problem lies.<br />
UDLs come with a fixed prototype, as <a href="https://learn.microsoft.com/en-us/cpp/cpp/user-defined-literals-cpp?view=msvc-170#user-defined-literal-operator-signatures" rel="nofollow noreferrer">specified here</a><br />
The Microsoft doc stipulates "<em>Also, any of these operators can be defined as constexpr</em>".<br />
But when I try to call my hashing function from a constexpr UDL:</p>
<pre><code>constexpr uint64_t operator "" _hashed(const char *arr, size_t size) {
return xxHash64<size>(arr);
}
</code></pre>
<blockquote>
<p>function "xxHash64" cannot be called with the given argument list<br />
argument types are: (const char*)</p>
</blockquote>
<p>And the error does make sense. My function expects a character array, and instead it gets a pointer.<br />
But if I were to modify the definition of my xxHash64 function to take a <code>const char *</code>, I can no longer work in a constexpr context because the compiler needs to resolve the pointer first, which happens at runtime.</p>
<p>So am I doing anything wrong here, or is this a limitation of UDLs or constexpr functions as a whole?
Again, I'm not 100% sure the templated definition at the top is the way to go, but I'm not sure how else I could read characters from a string at compile time.</p>
<p>I'm not limited by any compiler version or library. If there is a better way to do this, feel free to suggest.</p>
|
[
{
"answer_id": 74493174,
"author": "apple apple",
"author_id": 5980430,
"author_profile": "https://Stackoverflow.com/users/5980430",
"pm_score": 2,
"selected": false,
"text": "constexpr constexpr constexpr uint64_t xxHash64(const char* s){return s[0];}\nconstexpr uint64_t operator \"\" _g(const char *arr,std::size_t){\n return xxHash64(arr);\n}\n\nint main()\n{\n xxHash64(\"foo\");\n constexpr auto c = \"foobar\"_g;\n return c;\n}\n"
},
{
"answer_id": 74494851,
"author": "apple apple",
"author_id": 5980430,
"author_profile": "https://Stackoverflow.com/users/5980430",
"pm_score": 2,
"selected": false,
"text": "#include <cstdint>\n\ntemplate <std::size_t arr_size>\nconstexpr std::uint64_t xxHash64(const char(&data)[arr_size]){\n return data[0];\n}\n\n// template <std::size_t N> // can also be full class template (with CTAD)\nstruct hash_value{\n std::uint64_t value;\n template <std::size_t N>\n constexpr hash_value(const char(&p)[N]):value(xxHash64(p)){}\n};\n\n\ntemplate < hash_value v > \nconstexpr std::uint64_t operator \"\"_hashed() { return v.value; }\n\nint main()\n{\n constexpr auto v = \"foobar\"_hashed;\n return v;\n}\n"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74492884",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4820749/"
] |
74,492,912
|
<p>I'm a beginner with Python and wanted to make a script to collect some basketball stats from basketball-reference.com and sort the list based on a certain stat. I understand this error is thrown when you try to reference an index in a list where that index does not exist. But I've tried creating both a completely empty list and one with a defined range and I'm still getting that error.</p>
<p>CODE:</p>
<pre><code>player_first_name = ["Luka", "Nikola", "Giannis", "Stephen", "Jayson"]
player_last_name = ["Doncic", "Jokic", "Antetokounmpo", "Curry", "Tatum"]
player = []
</code></pre>
<p>... some code not pertaining to this</p>
<pre><code>for x in range(5):
player[x] = player_first_name[x] + " " + player_last_name[x]
</code></pre>
<p>NOTE: I get this error if I declare player = [], player = list(), or player = [] * 5, according to what I've read online, all of these should have been fine. The only way I can get this error to go away is if I actually put values into each index (eg. player = ["a", "b", "c", "d", "e"]</p>
<p>As said before, I've tried declaring the player list as:</p>
<pre><code>player = []
player = [] * 5
player = list()
</code></pre>
<p>All of these cases resulted in the error.</p>
|
[
{
"answer_id": 74493024,
"author": "Talha Tayyab",
"author_id": 13086128,
"author_profile": "https://Stackoverflow.com/users/13086128",
"pm_score": 2,
"selected": true,
"text": "player = [] append for x in range(5):\n player[x] = player_first_name[x] + \" \" + player_last_name[x]\n\n#IndexError: list assignment index out of range\n for loop for x in range(5):\n player.append(player_first_name[x] + \" \" + player_last_name[x])\nprint(player)\n\n\n#['Luka Doncic', 'Nikola Jokic', 'Giannis Antetokounmpo', 'Stephen Curry', 'Jayson Tatum', 'Luka Doncic', 'Nikola Jokic', 'Giannis Antetokounmpo', 'Stephen Curry', 'Jayson Tatum']\n"
},
{
"answer_id": 74493157,
"author": "Edward Peters",
"author_id": 6016064,
"author_profile": "https://Stackoverflow.com/users/6016064",
"pm_score": 0,
"selected": false,
"text": "x = []\nx[1]= 2\nprint(x[1])\n Traceback (most recent call last):\n File \"main.py\", line 2, in <module>\n x[1]= 2\nIndexError: list assignment index out of range\n list() []*5 print([]*5) [] print([1]*5) [1, 1, 1, 1, 1] x = []\nx.append(1)\nprint(x)\n x= list(map(lambda x : x * 2, range(5)))\nprint(x)\n [0,2,4,6,8]\n map players = list(map(lambda x : layer_first_name[x] + \" \" + player_last_name[x], range(5))\n"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74492912",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20541412/"
] |
74,492,930
|
<p>Is it a bad practice to return a class inside the method of another class?</p>
<p>Example: createBlockClass method</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>class BlockBuilder {
constructor (methodForBlock) {
this.methodForBlock = methodForBlock;
};
createBlockClass () {
const method = this.methodForBlock.bind(this.methodForBlock);
return class Block {
constructor(title) {
this.title = title;
};
method = method;
}
}
};
const blockBuilder = new BlockBuilder(() => console.log('Hello, world!!!'));
const Block = blockBuilder.createBlockClass();
const block1 = new Block("block one");
const block2 = new Block("block two");
block1.method();
block2.method();</code></pre>
</div>
</div>
</p>
<p>I need to receive a method as a parameter and add it to the block class before creating any instance</p>
|
[
{
"answer_id": 74493024,
"author": "Talha Tayyab",
"author_id": 13086128,
"author_profile": "https://Stackoverflow.com/users/13086128",
"pm_score": 2,
"selected": true,
"text": "player = [] append for x in range(5):\n player[x] = player_first_name[x] + \" \" + player_last_name[x]\n\n#IndexError: list assignment index out of range\n for loop for x in range(5):\n player.append(player_first_name[x] + \" \" + player_last_name[x])\nprint(player)\n\n\n#['Luka Doncic', 'Nikola Jokic', 'Giannis Antetokounmpo', 'Stephen Curry', 'Jayson Tatum', 'Luka Doncic', 'Nikola Jokic', 'Giannis Antetokounmpo', 'Stephen Curry', 'Jayson Tatum']\n"
},
{
"answer_id": 74493157,
"author": "Edward Peters",
"author_id": 6016064,
"author_profile": "https://Stackoverflow.com/users/6016064",
"pm_score": 0,
"selected": false,
"text": "x = []\nx[1]= 2\nprint(x[1])\n Traceback (most recent call last):\n File \"main.py\", line 2, in <module>\n x[1]= 2\nIndexError: list assignment index out of range\n list() []*5 print([]*5) [] print([1]*5) [1, 1, 1, 1, 1] x = []\nx.append(1)\nprint(x)\n x= list(map(lambda x : x * 2, range(5)))\nprint(x)\n [0,2,4,6,8]\n map players = list(map(lambda x : layer_first_name[x] + \" \" + player_last_name[x], range(5))\n"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74492930",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16490155/"
] |
74,492,934
|
<p>I have several lists that are generated from a <code>get_topic()</code> function. That is,</p>
<pre><code>list1 = get_topic(1)
list2 = get_topic(2)
and another dozens of lists.
# The list contains something like
[('A', 0.1),('B', 0.2),('C',0.3)]
</code></pre>
<p>I am trying to write a loop so that all different lists can be saved to different columns in a dataframe. The code I tried was:</p>
<pre><code>for i in range(1,number) # number is the total number of lists + 1
df_02 = pd.DataFrame(get_topic(i)
</code></pre>
<p>This only returns with list1, but no other lists. The result that I would like to get is something like:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>List 1</th>
<th>Number 1</th>
<th>List 2</th>
<th>Number 2</th>
</tr>
</thead>
<tbody>
<tr>
<td>A</td>
<td>0.1</td>
<td>D</td>
<td>0.03</td>
</tr>
<tr>
<td>B</td>
<td>0.2</td>
<td>E</td>
<td>0.04</td>
</tr>
<tr>
<td>C</td>
<td>0.3</td>
<td>F</td>
<td>0.05</td>
</tr>
</tbody>
</table>
</div>
<p>Could anyone help me to correct the loop? Thank you.</p>
|
[
{
"answer_id": 74493153,
"author": "Giuseppe La Gualano",
"author_id": 20249888,
"author_profile": "https://Stackoverflow.com/users/20249888",
"pm_score": 0,
"selected": false,
"text": "import pandas as pd\n\ntopics = [\n [('A', 0.1), ('B', 0.2), ('C', 0.3)],\n [('D', 0.3), ('E', 0.4), ('F', 0.5)]\n]\nnumber = len(topics)\n\n\ndef get_topic(index) -> []:\n return topics[index]\n\n\nif __name__ == '__main__':\n df = pd.DataFrame()\n for i in range(0, number): # number is the total number of lists\n curr_topic = get_topic(i)\n curr_columns = ['List ' + str(i+1), 'Number ' + str(i+1)]\n df = pd.concat([df, pd.DataFrame(data=curr_topic, columns=curr_columns)], axis=1)\n\nprint(df)\n List 1 Number 1 List 2 Number 2\n0 A 0.1 D 0.3\n1 B 0.2 E 0.4\n2 C 0.3 F 0.5\n"
},
{
"answer_id": 74493155,
"author": "Steven Rumbalski",
"author_id": 1322401,
"author_profile": "https://Stackoverflow.com/users/1322401",
"pm_score": 2,
"selected": false,
"text": "df = pd.DataFrame()\nfor i in range(1, number):\n df[f'List {i}'], df[f'Number {i}'] = zip(*get_topic(i))\n"
},
{
"answer_id": 74493506,
"author": "payloc91",
"author_id": 8524301,
"author_profile": "https://Stackoverflow.com/users/8524301",
"pm_score": 1,
"selected": true,
"text": "df = pd.DataFrame([get_topic(i) for i in range(1, number)])\ndf = df.apply(pd.Series.explode).reset_index(drop=True)\ndf = df.transpose()\n 0 1 2 3 4 5\n0 A 0.1 D 0.1 G 0.1\n1 B 0.2 E 0.2 H 0.2\n2 C 0.3 F 0.3 I 0.3\n df = pd.DataFrame([get_topic(i) for i in range(1, number)]).apply(pd.Series.explode).reset_index(drop=True).transpose()\n"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74492934",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19192947/"
] |
74,492,945
|
<p>This is my HTML</p>
<pre><code>
<section class="carousel">
<div class="carousel__slider">
<ul class="carousel__list">
<li class="carousel__item">
<img src="images/KawaiiCoded Logo.jpg" alt="Kawaii Logo" width="400" height="400">
</li>
<li class="carousel__item">
<img src="images/KawaiiCoded Logo.jpg" alt="Kawaii Logo" width="400" height="400">
</li>
<li class="carousel__item">
<img src="images/KawaiiCoded Logo.jpg" alt="Kawaii Logo" width="400" height="400">
</li>
<li class="carousel__item">
<img src="images/KawaiiCoded Logo.jpg" alt="Kawaii Logo" width="400" height="400">
</li>
<li class="carousel__item">
<img src="images/KawaiiCoded Logo.jpg" alt="Kawaii Logo" width="400" height="400">
</li>
<li class="carousel__item">
<img src="images/KawaiiCoded Logo.jpg" alt="Kawaii Logo" width="400" height="400">
</li>
<li class="carousel__item">
<img src="images/KawaiiCoded Logo.jpg" alt="Kawaii Logo" width="400" height="400">
</li>
</ul>
</div>
</section>
<script src="js/infinite.js"></script>
</code></pre>
<p>THIS IS MY CSS</p>
<pre><code> .main{
width: 50vw;
}
ul {
margin: 0;
padding: 0;
list-style: none;
}
.carousel {
position: relative;
overflow: hidden;
}
.carousel__slider {
position: relative;
display: flex;
align-items: center;
width: 50vw;
height: 400px;
}
.carousel__list {
position: absolute;
width: 260%;
top: 50%;
left: 0;
transform: translateY(-50%);
display: flex;
align-items: center;
justify-content: space-around;
}
.carousel__item {
display: flex;
align-items: center;
justify-content: center;
cursor: pointer;
}
.carousel__item:hover {
transform: scale(1.1);
font-size: 30px;
background-color: rgba(255, 255, 255, 0.7);
}
</code></pre>
<p>THIS IS MY JAVASCRIPT</p>
<pre><code>"use strict";
function carousel() {
let carouselSlider = document.querySelector(".carousel__slider");
let list = document.querySelector(".carousel__list");
let item = document.querySelectorAll(".carousel__item");
let list2;
const speed = 1;
const width = list.offsetWidth;
let x = 0;
let x2 = width;
function clone() {
list2 = list.cloneNode(true);
carouselSlider.appendChild(list2);
list2.style.left = `${width}px`;
}
function moveFirst() {
x -= speed;
if (width >= Math.abs(x)) {
list.style.left = `${x}px`;
} else {
x = width;
}
}
function moveSecond() {
x2 -= speed;
if (list2.offsetWidth >= Math.abs(x2)) {
list2.style.left = `${x2}px`;
} else {
x2 = width;
}
}
function hover() {
clearInterval(a);
clearInterval(b);
}
function unhover() {
a = setInterval(moveFirst, 10);
b = setInterval(moveSecond, 10);
}
clone();
let a = setInterval(moveFirst, 10);
let b = setInterval(moveSecond, 10);
carouselSlider.addEventListener("mouseenter", hover);
carouselSlider.addEventListener("mouseleave", unhover);
}
carousel();
</code></pre>
<p>THE CODE AND JAVASCRIPT WORKS GREAT HOWEVER!</p>
<p>IF I COPY AND PASTE MY HTML CODE TWICE IN MY HTML FILE!</p>
<p>The 1st carousel works but, the second set which is an exact duplicate of the 1st set does not work.</p>
<p>for example below I JUST DID A DUPLICATE OF THE CODE AND THE 1ST ONE WORKS BUT,THE SECOND ONE DOES NOTHING! Is there an explanation for why this happens ?</p>
<pre><code> <section class="carousel">
<div class="carousel__slider">
<ul class="carousel__list">
<li class="carousel__item">
<img src="images/KawaiiCoded Logo.jpg" alt="Kawaii Logo" width="400" height="400">
</li>
<li class="carousel__item">
<img src="images/KawaiiCoded Logo.jpg" alt="Kawaii Logo" width="400" height="400">
</li>
<li class="carousel__item">
<img src="images/KawaiiCoded Logo.jpg" alt="Kawaii Logo" width="400" height="400">
</li>
<li class="carousel__item">
<img src="images/KawaiiCoded Logo.jpg" alt="Kawaii Logo" width="400" height="400">
</li>
<li class="carousel__item">
<img src="images/KawaiiCoded Logo.jpg" alt="Kawaii Logo" width="400" height="400">
</li>
<li class="carousel__item">
<img src="images/KawaiiCoded Logo.jpg" alt="Kawaii Logo" width="400" height="400">
</li>
<li class="carousel__item">
<img src="images/KawaiiCoded Logo.jpg" alt="Kawaii Logo" width="400" height="400">
</li>
</ul>
</div>
</section>
<section class="carousel">
<div class="carousel__slider">
<ul class="carousel__list">
<li class="carousel__item">
<img src="images/KawaiiCoded Logo.jpg" alt="Kawaii Logo" width="400" height="400">
</li>
<li class="carousel__item">
<img src="images/KawaiiCoded Logo.jpg" alt="Kawaii Logo" width="400" height="400">
</li>
<li class="carousel__item">
<img src="images/KawaiiCoded Logo.jpg" alt="Kawaii Logo" width="400" height="400">
</li>
<li class="carousel__item">
<img src="images/KawaiiCoded Logo.jpg" alt="Kawaii Logo" width="400" height="400">
</li>
<li class="carousel__item">
<img src="images/KawaiiCoded Logo.jpg" alt="Kawaii Logo" width="400" height="400">
</li>
<li class="carousel__item">
<img src="images/KawaiiCoded Logo.jpg" alt="Kawaii Logo" width="400" height="400">
</li>
<li class="carousel__item">
<img src="images/KawaiiCoded Logo.jpg" alt="Kawaii Logo" width="400" height="400">
</li>
</ul>
</div>
</section>
<script src="js/infinite.js"></script>
</code></pre>
<p>I am not too sure where to start with this one on how to resolve it.</p>
|
[
{
"answer_id": 74493153,
"author": "Giuseppe La Gualano",
"author_id": 20249888,
"author_profile": "https://Stackoverflow.com/users/20249888",
"pm_score": 0,
"selected": false,
"text": "import pandas as pd\n\ntopics = [\n [('A', 0.1), ('B', 0.2), ('C', 0.3)],\n [('D', 0.3), ('E', 0.4), ('F', 0.5)]\n]\nnumber = len(topics)\n\n\ndef get_topic(index) -> []:\n return topics[index]\n\n\nif __name__ == '__main__':\n df = pd.DataFrame()\n for i in range(0, number): # number is the total number of lists\n curr_topic = get_topic(i)\n curr_columns = ['List ' + str(i+1), 'Number ' + str(i+1)]\n df = pd.concat([df, pd.DataFrame(data=curr_topic, columns=curr_columns)], axis=1)\n\nprint(df)\n List 1 Number 1 List 2 Number 2\n0 A 0.1 D 0.3\n1 B 0.2 E 0.4\n2 C 0.3 F 0.5\n"
},
{
"answer_id": 74493155,
"author": "Steven Rumbalski",
"author_id": 1322401,
"author_profile": "https://Stackoverflow.com/users/1322401",
"pm_score": 2,
"selected": false,
"text": "df = pd.DataFrame()\nfor i in range(1, number):\n df[f'List {i}'], df[f'Number {i}'] = zip(*get_topic(i))\n"
},
{
"answer_id": 74493506,
"author": "payloc91",
"author_id": 8524301,
"author_profile": "https://Stackoverflow.com/users/8524301",
"pm_score": 1,
"selected": true,
"text": "df = pd.DataFrame([get_topic(i) for i in range(1, number)])\ndf = df.apply(pd.Series.explode).reset_index(drop=True)\ndf = df.transpose()\n 0 1 2 3 4 5\n0 A 0.1 D 0.1 G 0.1\n1 B 0.2 E 0.2 H 0.2\n2 C 0.3 F 0.3 I 0.3\n df = pd.DataFrame([get_topic(i) for i in range(1, number)]).apply(pd.Series.explode).reset_index(drop=True).transpose()\n"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74492945",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17977590/"
] |
74,492,958
|
<p>I have a UIViewRepresentable of a third-party library component <code>FSCalendar</code>. However, I need this to conform to type UIView... Is there a way to do this? Any help is appreciated :)</p>
<pre><code>struct CalendarViewRepresentable: UIViewRepresentable {
typealias UIViewType = FSCalendar
var calendar = FSCalendar()
@Binding var selectedDate: Date
var calendarHeight: NSLayoutConstraint?
func updateUIView(_ uiView: FSCalendar, context: Context) { }
func makeUIView(context: Context) -> FSCalendar {
calendar.delegate = context.coordinator
calendar.dataSource = context.coordinator
calendar.translatesAutoresizingMaskIntoConstraints = false
calendar.setContentHuggingPriority(.required, for: .vertical)
calendar.setContentHuggingPriority(.required, for: .horizontal)
NSLayoutConstraint.activate([
calendar.topAnchor.constraint(equalTo: context.coordinator.topAnchor)
])
return calendar
}
func makeCoordinator() -> Coordinator {
Coordinator(self)
}
class Coordinator: NSObject, FSCalendarDelegate, FSCalendarDataSource {
var parent: CalendarViewRepresentable
init(_ parent: CalendarViewRepresentable) {
self.parent = parent
}
func calendar(_ calendar: FSCalendar, didSelect date: Date, at monthPosition: FSCalendarMonthPosition) {
parent.selectedDate = date
}
func calendar(_ calendar: FSCalendar, boundingRectWillChange bounds: CGRect, animated: Bool) {
parent.calendarHeight?.constant = bounds.height
parent.calendar.layoutIfNeeded()
}
}
}
struct HomeView: View {
@State private var selectedDate: Date = Date()
var body: some View {
VStack {
CalendarViewRepresentable(selectedDate: self.$selectedDate)
}
}
}
</code></pre>
|
[
{
"answer_id": 74493153,
"author": "Giuseppe La Gualano",
"author_id": 20249888,
"author_profile": "https://Stackoverflow.com/users/20249888",
"pm_score": 0,
"selected": false,
"text": "import pandas as pd\n\ntopics = [\n [('A', 0.1), ('B', 0.2), ('C', 0.3)],\n [('D', 0.3), ('E', 0.4), ('F', 0.5)]\n]\nnumber = len(topics)\n\n\ndef get_topic(index) -> []:\n return topics[index]\n\n\nif __name__ == '__main__':\n df = pd.DataFrame()\n for i in range(0, number): # number is the total number of lists\n curr_topic = get_topic(i)\n curr_columns = ['List ' + str(i+1), 'Number ' + str(i+1)]\n df = pd.concat([df, pd.DataFrame(data=curr_topic, columns=curr_columns)], axis=1)\n\nprint(df)\n List 1 Number 1 List 2 Number 2\n0 A 0.1 D 0.3\n1 B 0.2 E 0.4\n2 C 0.3 F 0.5\n"
},
{
"answer_id": 74493155,
"author": "Steven Rumbalski",
"author_id": 1322401,
"author_profile": "https://Stackoverflow.com/users/1322401",
"pm_score": 2,
"selected": false,
"text": "df = pd.DataFrame()\nfor i in range(1, number):\n df[f'List {i}'], df[f'Number {i}'] = zip(*get_topic(i))\n"
},
{
"answer_id": 74493506,
"author": "payloc91",
"author_id": 8524301,
"author_profile": "https://Stackoverflow.com/users/8524301",
"pm_score": 1,
"selected": true,
"text": "df = pd.DataFrame([get_topic(i) for i in range(1, number)])\ndf = df.apply(pd.Series.explode).reset_index(drop=True)\ndf = df.transpose()\n 0 1 2 3 4 5\n0 A 0.1 D 0.1 G 0.1\n1 B 0.2 E 0.2 H 0.2\n2 C 0.3 F 0.3 I 0.3\n df = pd.DataFrame([get_topic(i) for i in range(1, number)]).apply(pd.Series.explode).reset_index(drop=True).transpose()\n"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74492958",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13702200/"
] |
74,492,996
|
<p>I have added text widget inside row widget.then 2nd text value</p>
<pre><code>Text(
widget.leavemodel.reason ?? '',
style: TextStyle(
fontSize: 16.0,
),
</code></pre>
<p>getting 4 pixcel overflowed.how can i sloved this?</p>
<p>code is bello</p>
<pre><code> Row(
children: [
Text(
'Reason :',
style:
TextStyle(fontSize: 16.0, fontWeight: FontWeight.w600),
),
Padding(
padding: const EdgeInsets.only(left: 15.0),
child: Text(
widget.leavemodel.reason ?? '',
style: TextStyle(
fontSize: 16.0,
),
),
),
],
),
</code></pre>
<p>solution for text overflowed in flutter</p>
|
[
{
"answer_id": 74493153,
"author": "Giuseppe La Gualano",
"author_id": 20249888,
"author_profile": "https://Stackoverflow.com/users/20249888",
"pm_score": 0,
"selected": false,
"text": "import pandas as pd\n\ntopics = [\n [('A', 0.1), ('B', 0.2), ('C', 0.3)],\n [('D', 0.3), ('E', 0.4), ('F', 0.5)]\n]\nnumber = len(topics)\n\n\ndef get_topic(index) -> []:\n return topics[index]\n\n\nif __name__ == '__main__':\n df = pd.DataFrame()\n for i in range(0, number): # number is the total number of lists\n curr_topic = get_topic(i)\n curr_columns = ['List ' + str(i+1), 'Number ' + str(i+1)]\n df = pd.concat([df, pd.DataFrame(data=curr_topic, columns=curr_columns)], axis=1)\n\nprint(df)\n List 1 Number 1 List 2 Number 2\n0 A 0.1 D 0.3\n1 B 0.2 E 0.4\n2 C 0.3 F 0.5\n"
},
{
"answer_id": 74493155,
"author": "Steven Rumbalski",
"author_id": 1322401,
"author_profile": "https://Stackoverflow.com/users/1322401",
"pm_score": 2,
"selected": false,
"text": "df = pd.DataFrame()\nfor i in range(1, number):\n df[f'List {i}'], df[f'Number {i}'] = zip(*get_topic(i))\n"
},
{
"answer_id": 74493506,
"author": "payloc91",
"author_id": 8524301,
"author_profile": "https://Stackoverflow.com/users/8524301",
"pm_score": 1,
"selected": true,
"text": "df = pd.DataFrame([get_topic(i) for i in range(1, number)])\ndf = df.apply(pd.Series.explode).reset_index(drop=True)\ndf = df.transpose()\n 0 1 2 3 4 5\n0 A 0.1 D 0.1 G 0.1\n1 B 0.2 E 0.2 H 0.2\n2 C 0.3 F 0.3 I 0.3\n df = pd.DataFrame([get_topic(i) for i in range(1, number)]).apply(pd.Series.explode).reset_index(drop=True).transpose()\n"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74492996",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16752454/"
] |
74,493,013
|
<p>I have initial data which works fine.</p>
<pre><code>var data = {field1: FieldValue.increment(1)};
</code></pre>
<p>And it is also fine when I add another field to the data.</p>
<pre><code>data.addAll({field2: FieldValue.increment(1)});
</code></pre>
<p>But if I set the value to 0, it won't allow me to.</p>
<pre><code>data.addAll({field3: 0});
</code></pre>
<p>It will give an error of:
The element type 'int' can't be assigned to the map value type 'FieldValue'.</p>
<p>I tried doing this but still, have the same issue.</p>
<pre><code>data[field3] = 0;
</code></pre>
<p>How will I set the <code>field3</code> to a specific value?</p>
<p>Note:
This is the full code.</p>
<pre><code>DocumentReference<Map<String, dynamic>> ref = db.collection('MyCollect').doc(uid);
var data = {field1: FieldValue.increment(1)};
data.addAll({field2: FieldValue.increment(1)});
data.addAll({field3: 0});
ref.set(data, SetOptions(merge: true));
</code></pre>
|
[
{
"answer_id": 74513286,
"author": "rodpold",
"author_id": 2566770,
"author_profile": "https://Stackoverflow.com/users/2566770",
"pm_score": 2,
"selected": false,
"text": "var data = {field1: FieldValue.increment(1)};\n"
},
{
"answer_id": 74513409,
"author": "Gwhyyy",
"author_id": 18670641,
"author_profile": "https://Stackoverflow.com/users/18670641",
"pm_score": 4,
"selected": true,
"text": "var dynamic var a = \"text\";\na = \"text2\"; // ok\na = 1; // throws the error\n\ndynamic b = \"text\";\nb = \"text2\"; // ok\nb = 1; // also ok\n var var data = {field1: FieldValue.increment(1)}; // takes the Map<String, FieldValue> type\ndata.addAll({field3: 0}); // 0 is int and FieldValue.increment(1) is FieldValue type, so it throws an error\n data dynamic dynamic data = {field1: FieldValue.increment(1)}; // will accept it.\n Map dynamic Map<String, dynamic> data = {field1: FieldValue.increment(1)}; // will accept it also.\n"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74493013",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11555124/"
] |
74,493,022
|
<p>With Go <a href="https://pkg.go.dev/text/template" rel="nofollow noreferrer">text/template</a> language, how can I convert a bool to an int (false=0, true=1)?</p>
<p>Here is an example using the <a href="https://github.com/dolmen-go/goproc" rel="nofollow noreferrer">goproc</a> tool that allows to execute template from the command line:</p>
<pre><code>$ echo false | goproc -e '{{.}} => <template here>'
false => 0
$ echo true | goproc -e '{{.}} => <template here>'
true => 1
</code></pre>
|
[
{
"answer_id": 74493023,
"author": "dolmen",
"author_id": 328115,
"author_profile": "https://Stackoverflow.com/users/328115",
"pm_score": 0,
"selected": false,
"text": "index \"true\" \"false\" $ echo false | goproc -e '{{.}} => {{index \"....\\001\\000\" (len (print .))}}{{\"\\n\"}}'\nfalse => 0\n$ echo true | goproc -e '{{.}} => {{index \"....\\001\\000\" (len (print .))}}{{\"\\n\"}}'\ntrue => 1\n"
},
{
"answer_id": 74494080,
"author": "Nicholas Carey",
"author_id": 467473,
"author_profile": "https://Stackoverflow.com/users/467473",
"pm_score": 1,
"selected": false,
"text": "digitizeBoolTemplate := \"{{if . }}1{{else}}0{{end}}\"\n"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74493022",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/328115/"
] |
74,493,057
|
<p>So basically, i need to get the user to input some type of string and then get the user to input a number and slice the string depending on the users number and print on a new line every time it sliced. I don't think that made since so here is an example</p>
<pre><code>Welcome to the jungle.
5
Welco
me to
the
jungl
e.
</code></pre>
<p>I understand how to slice it but i dont understand how to get it to continue slicing until the full string is printed</p>
<pre><code>y=input('enter a sentence ')
x=int(input('enter a number '))
z=0
while z==0:
z==0
print(y[0:x])
print(y[x:]
</code></pre>
|
[
{
"answer_id": 74493023,
"author": "dolmen",
"author_id": 328115,
"author_profile": "https://Stackoverflow.com/users/328115",
"pm_score": 0,
"selected": false,
"text": "index \"true\" \"false\" $ echo false | goproc -e '{{.}} => {{index \"....\\001\\000\" (len (print .))}}{{\"\\n\"}}'\nfalse => 0\n$ echo true | goproc -e '{{.}} => {{index \"....\\001\\000\" (len (print .))}}{{\"\\n\"}}'\ntrue => 1\n"
},
{
"answer_id": 74494080,
"author": "Nicholas Carey",
"author_id": 467473,
"author_profile": "https://Stackoverflow.com/users/467473",
"pm_score": 1,
"selected": false,
"text": "digitizeBoolTemplate := \"{{if . }}1{{else}}0{{end}}\"\n"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74493057",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20188275/"
] |
74,493,073
|
<p><strong>Question:</strong></p>
<p>Is there a way to combine the advantages of GitHub's fine-grained PATs with the simplicity of <code>git pull</code> over HTTPS? If so, then how?</p>
<p><strong>Background</strong></p>
<p>GitHub has "classic" and "fine-grained" personal access tokens (PATs):</p>
<p><a href="https://i.stack.imgur.com/KkklW.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/KkklW.png" alt="enter image description here" /></a></p>
<p>Go to Settings > Developer Settings to see these.</p>
<p>I have been using a classic PAT to run <code>git pull</code> commands over HTTPS, to pull the latest commits from GitHub:</p>
<pre class="lang-bash prettyprint-override"><code>git pull https://${token}@github.com/${owner}/${repo}.git
</code></pre>
<p>This works without prompting for a password (I keep the PAT's expiration period reasonably short).</p>
<p>I cannot just (naively) substitute a new fine-grained token for the classic token in my <code>git pull</code> command. It prompts me for a password. (It is treated as a user ID, I assume.)</p>
<p>Fine-grained PATs certainly work with the GitHub <a href="https://docs.github.com/en/rest" rel="nofollow noreferrer">REST API</a>. I can use the API to <a href="https://docs.github.com/en/rest/git/commits#get-a-commit" rel="nofollow noreferrer">get a commit</a> if I have the commit SHA. But that is quite low-level compared to <code>git pull</code> and I don't want to "reimplement a lot of Git functionality" (<a href="https://docs.github.com/en/rest/guides/getting-started-with-the-git-database-api" rel="nofollow noreferrer">ref</a>).</p>
<p>Fine-grained PATs are welcomed because of their ability to lock down access to specific repos and specific functions. But how (if at all) can they be used directly with <code>git pull</code> commands?</p>
<p>I am using Git v2.38.1 (the latest release, currently).</p>
|
[
{
"answer_id": 74495336,
"author": "bk2204",
"author_id": 8705432,
"author_profile": "https://Stackoverflow.com/users/8705432",
"pm_score": 2,
"selected": true,
"text": "credential.usehttppath credential.https://github.com.usehttppath"
},
{
"answer_id": 74495393,
"author": "Bench Vue",
"author_id": 8054998,
"author_profile": "https://Stackoverflow.com/users/8054998",
"pm_score": 0,
"selected": false,
"text": "git pull https://${token}@github.com/${owner}/${repo}.git\n"
},
{
"answer_id": 74496280,
"author": "andrewJames",
"author_id": 12567365,
"author_profile": "https://Stackoverflow.com/users/12567365",
"pm_score": 0,
"selected": false,
"text": "libsecret store .ssh pull git config --global credential.helper store\ngit config --global credential.useHttpPath true\n .gitconfig [credential]\n helper = store\n useHttpPath = true\n pull git pull https://github.com/${owner}/${repo}.git\n .git-credentials https://<user ID>:<fine-grained PAT>@github.com/<owner>/<repo>.git\n git pull"
},
{
"answer_id": 74511733,
"author": "k4rim",
"author_id": 19382866,
"author_profile": "https://Stackoverflow.com/users/19382866",
"pm_score": 0,
"selected": false,
"text": "git pull https://${username}:${token}@github.com/${owner}/${repo}.git\n"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74493073",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12567365/"
] |
74,493,096
|
<p>I have 40 provider and 10,000 product but i want to show 1 product of each provider</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Brand</th>
<th>Provider</th>
<th>Product</th>
<th>URL</th>
</tr>
</thead>
<tbody>
<tr>
<td>Lightning</td>
<td>Pragmatic Play</td>
<td>Madame Destiny</td>
<td>Link</td>
</tr>
<tr>
<td>Lightning</td>
<td>Isoftbet</td>
<td>Halloween Jack</td>
<td>Link</td>
</tr>
<tr>
<td>Lightning</td>
<td>Pragmatic Play</td>
<td>Sweet Bonanza</td>
<td>Link</td>
</tr>
<tr>
<td>Lightning</td>
<td>Isoftbet</td>
<td>Tropical Bonan</td>
<td>Link</td>
</tr>
<tr>
<td>Lightning</td>
<td>Netent</td>
<td>Royal Potato</td>
<td>Link</td>
</tr>
<tr>
<td>Lightning</td>
<td>Netent</td>
<td>Madame Destiny</td>
<td>Link</td>
</tr>
</tbody>
</table>
</div>
<p>SO this my SQL table now. But i want to show 1 item of each Provider like:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Brand</th>
<th>Provider</th>
<th>Product</th>
<th>URL</th>
</tr>
</thead>
<tbody>
<tr>
<td>Lightning</td>
<td>Pragmatic Play</td>
<td>Madame Destiny</td>
<td>Link</td>
</tr>
<tr>
<td>Lightning</td>
<td>Isoftbet</td>
<td>Halloween Jack</td>
<td>Link</td>
</tr>
<tr>
<td>Lightning</td>
<td>Netent</td>
<td>Royal Potato</td>
<td>Link</td>
</tr>
</tbody>
</table>
</div>
<p>this is my code
`</p>
<pre><code>
<?php
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$link = mysqli_connect("localhost", "newuser1", "p,+Dn@auTD3$*G5", "newdatabse");
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// Attempt select query execution
$sql = "SELECT * FROM tablename WHERE Brand='Coolcasino' and Provider IN ('Pragmatic Play','Isoftbet','Netent') ;";
if($result = mysqli_query($link, $sql)){
if(mysqli_num_rows($result) > 0){
echo "<table>";
echo "<tr>";
echo "<th>Brand</th>";
echo "<th>Provider</th>";
echo "<th>Product</th>";
echo "<th>URL</th>";
echo "</tr>";
while($row = mysqli_fetch_array($result)){
echo "<tr>";
echo "<td>" . $row['Brand'] . "</td>";
echo "<td>" . $row['Provider'] . "</td>";
echo "<td>" . $row['Product'] . "</td>";
echo "<td>" . $row['URL'] . "</td>";
echo "</tr>";
}
echo "</table>";
// Close result set
mysqli_free_result($result);
} else{
echo "No records matching your query were found.";
}
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
// Close connection
mysqli_close($link);
?>
</code></pre>
<p>Please help me if anyboday can`</p>
|
[
{
"answer_id": 74493489,
"author": "Chandan",
"author_id": 19493154,
"author_profile": "https://Stackoverflow.com/users/19493154",
"pm_score": 0,
"selected": false,
"text": "$sql = \"SELECT * FROM tablename WHERE Brand='Coolcasino' and Provider IN ('Pragmatic Play','Isoftbet','Netent') GROUP BY Provider;\"; \n"
},
{
"answer_id": 74493556,
"author": "reza hrkeng",
"author_id": 20517507,
"author_profile": "https://Stackoverflow.com/users/20517507",
"pm_score": -1,
"selected": false,
"text": "$sql = \"SELECT * FROM tablename WHERE Brand='Coolcasino' and Provider IN ('Pragmatic Play','Isoftbet','Netent') GROUP BY Provider, RAND()\";\n"
},
{
"answer_id": 74494341,
"author": "Ergest Basha",
"author_id": 16461952,
"author_profile": "https://Stackoverflow.com/users/16461952",
"pm_score": 2,
"selected": true,
"text": "select Brand,\n Provider,\n Product,\n URL\nfrom ( select Brand,\n Provider,\n Product,\n URL,\n row_number() over(partition by Provider order by rand()) as row_num\n from tablename\n where Brand='Lightning' \n and Provider IN ('Pragmatic Play','Isoftbet','Netent') \n ) as rand_prod\nwhere row_num=1;\n select *"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74493096",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20541535/"
] |
74,493,112
|
<p>There are three aligned elements with <code>display: flex</code>.</p>
<p>I'd like to hide a middle element if it's too long (if the text goes to another line) and the middle element is dynamic so sometimes it's short, sometimes it's long.</p>
<p>Also, this is specific for the mobile screen size.</p>
<p>How can I do that?</p>
<pre><code>import "./styles.css";
export default function App() {
return (
<div className="App">
<h1>LOGO</h1>
<h2>Start editing to see some magic happen! Long Title</h2>
<h1>test</h1>
</div>
);
}
</code></pre>
<pre><code>.App {
width: 100%;
height: 60px;
display: flex;
align-content: space-between;
gap: 20px;
}
</code></pre>
<p>it would be nice if we can hide the middle element if it goes to another line but if we can't, we also could do something like if the middle element's width is larger than 80px, we hide the element.</p>
|
[
{
"answer_id": 74493318,
"author": "Pratik Dev",
"author_id": 15908339,
"author_profile": "https://Stackoverflow.com/users/15908339",
"pm_score": 0,
"selected": false,
"text": "hide display: none hide bottom, top, height, width, left, right, x, y const middle = document.querySelector(\".middle\")\nif(middle.getBoundingClientRect().width < 80){\n middle.classList.add(\"hide\")\n} else {\n middle.classList.remove(\"hide\")\n} .App {\n width: 100%;\n height: 60px;\n display: flex;\n align-content: space-between;\n gap: 20px;\n}\n\n.middle{\n width: 80px;\n}\n\n.hide{\n display: none;\n} <div class=\"App\">\n <h1>LOGO</h1>\n <h2 class=\"middle\">Start editing to see some magic happen! Long Title</h2>\n <h1>test</h1>\n </div> useEffect window.onresize()"
},
{
"answer_id": 74493352,
"author": "Lakruwan Pathirage",
"author_id": 12383492,
"author_profile": "https://Stackoverflow.com/users/12383492",
"pm_score": 0,
"selected": false,
"text": "useRef <h2> import \"./styles.css\";\nimport {useRef} from \"react\";\nexport default function App() {\n const el=useRef();\n return (\n <div className=\"App\">\n <h1>LOGO</h1>\n <h2 style={{display:el.current.getBoundingClientRect().width>80?\"none\":\"block\"}}>Start editing to see some magic happen! Long Title</h2>\n <h1>test</h1>\n </div>\n );\n}\n getBoundingClientRect() el.current.getBoundingClientRect().width"
},
{
"answer_id": 74493756,
"author": "AtomicUs5000",
"author_id": 17934914,
"author_profile": "https://Stackoverflow.com/users/17934914",
"pm_score": 2,
"selected": true,
"text": ".App {\n width: 100%;\n height: 60px;\n display: flex;\n flex-wrap: nowrap;\n align-items: top;\n justify-content: center;\n gap: 10px;\n overflow: hidden;\n}\n.inner {\n align-self: top;\n display: flex;\n flex-direction: row;\n flex-wrap: wrap;\n flex-grow: 1;\n min-width: 0;\n}\n.inner .hider {\n height: 60px;\n width: 1px;\n flex-grow: 1;\n}\n.inner h2 {\n overflow: hidden;\n} <div class=\"App\">\n<h1>LOGO</h1>\n <div class=\"inner\">\n <div class=\"hider\"></div>\n <h2>Start editing to see some magic happen! Long Title</h2>\n <div class=\"hider\"></div>\n </div>\n<h1>test</h1>\n</div>"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74493112",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14489531/"
] |
74,493,131
|
<p>I have a situation here ..</p>
<p>If there is a , var ttext = " enzo had a pen, watch and key "</p>
<p>i want to check if ttext has either pen or watch or key ..</p>
<p>i tried using include</p>
<pre><code>var ttext = " enzo had a pen, watch and key "
let result = ttext.includes("pen");
</code></pre>
<p>how to check multiple items efficiently .. if includes pen or watch or key .</p>
<p>Please help out.</p>
<p>var ttext = " enzo had a pen, watch and key "</p>
<p>let result = ttext.includes("pen");</p>
<p>want to check multiple words present</p>
|
[
{
"answer_id": 74493318,
"author": "Pratik Dev",
"author_id": 15908339,
"author_profile": "https://Stackoverflow.com/users/15908339",
"pm_score": 0,
"selected": false,
"text": "hide display: none hide bottom, top, height, width, left, right, x, y const middle = document.querySelector(\".middle\")\nif(middle.getBoundingClientRect().width < 80){\n middle.classList.add(\"hide\")\n} else {\n middle.classList.remove(\"hide\")\n} .App {\n width: 100%;\n height: 60px;\n display: flex;\n align-content: space-between;\n gap: 20px;\n}\n\n.middle{\n width: 80px;\n}\n\n.hide{\n display: none;\n} <div class=\"App\">\n <h1>LOGO</h1>\n <h2 class=\"middle\">Start editing to see some magic happen! Long Title</h2>\n <h1>test</h1>\n </div> useEffect window.onresize()"
},
{
"answer_id": 74493352,
"author": "Lakruwan Pathirage",
"author_id": 12383492,
"author_profile": "https://Stackoverflow.com/users/12383492",
"pm_score": 0,
"selected": false,
"text": "useRef <h2> import \"./styles.css\";\nimport {useRef} from \"react\";\nexport default function App() {\n const el=useRef();\n return (\n <div className=\"App\">\n <h1>LOGO</h1>\n <h2 style={{display:el.current.getBoundingClientRect().width>80?\"none\":\"block\"}}>Start editing to see some magic happen! Long Title</h2>\n <h1>test</h1>\n </div>\n );\n}\n getBoundingClientRect() el.current.getBoundingClientRect().width"
},
{
"answer_id": 74493756,
"author": "AtomicUs5000",
"author_id": 17934914,
"author_profile": "https://Stackoverflow.com/users/17934914",
"pm_score": 2,
"selected": true,
"text": ".App {\n width: 100%;\n height: 60px;\n display: flex;\n flex-wrap: nowrap;\n align-items: top;\n justify-content: center;\n gap: 10px;\n overflow: hidden;\n}\n.inner {\n align-self: top;\n display: flex;\n flex-direction: row;\n flex-wrap: wrap;\n flex-grow: 1;\n min-width: 0;\n}\n.inner .hider {\n height: 60px;\n width: 1px;\n flex-grow: 1;\n}\n.inner h2 {\n overflow: hidden;\n} <div class=\"App\">\n<h1>LOGO</h1>\n <div class=\"inner\">\n <div class=\"hider\"></div>\n <h2>Start editing to see some magic happen! Long Title</h2>\n <div class=\"hider\"></div>\n </div>\n<h1>test</h1>\n</div>"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74493131",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20541555/"
] |
74,493,134
|
<p>I want to load some information about a server from a json file, each server is identified within this file by its guild.id.
However if I want to try and load some data at the start with on_ready(), I cant use ctx, which I need to get the current servers guild.id, so I can identify it within the file.</p>
<p>(sorry if that's a bad explanation but just look at line 6 of my code and you'll understand what I'm trying to do)</p>
<p>Here is my current code:</p>
<pre><code>@bot.event
async def on_ready():
with open("server_info.json", "r") as infoRaw:
infoJson = json.load(infoRaw)
for server in infoJson["Servers"]: #search each server data
if (server["id"] == ctx.message.guild.id): #compare id in file to current id (error line)
data = server[data]
break
</code></pre>
<p>I cant find any other ways online of getting the the servers id without a user sending a message first.</p>
|
[
{
"answer_id": 74495356,
"author": "Pythonwolf",
"author_id": 18666199,
"author_profile": "https://Stackoverflow.com/users/18666199",
"pm_score": 2,
"selected": false,
"text": "guild = discord.utils.get(bot.guilds, id=378473289473829)\n bot"
},
{
"answer_id": 74495359,
"author": "Ed Vraz",
"author_id": 17637967,
"author_profile": "https://Stackoverflow.com/users/17637967",
"pm_score": 1,
"selected": false,
"text": "bot.guilds"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74493134",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19753572/"
] |
74,493,149
|
<p>Is there a standard QML component using which several items created in Repeater can be animated one after the other with some delay (i.e. not simultaneously)?
So far I could only come up with a Timer based solution like below:</p>
<pre><code>import QtQuick 6.3
Item {
width: 600; height: 400
Row {
anchors.fill: parent
spacing: 5
Repeater {
id: _repeater
anchors.fill: parent
model: 10
delegate: Rectangle {
id: _rect
width: 50; height: 50
color: "green"
function animate() {_anim.start()}
SequentialAnimation {
id: _anim
NumberAnimation {target: _rect; property: "height"; from: 50; to: 150}
NumberAnimation {target: _rect; property: "height"; from: 150; to: 50}
}
}
}
}
Timer {
id: _timer
property var indexes
repeat: true
interval: 150
onTriggered: {
if (indexes.length !== 0) {
_repeater.itemAt(indexes.shift()).animate()
} else
stop()
}
}
MouseArea {
anchors.fill: parent
onClicked: {
_timer.indexes = [1, 2, 3, 4]
_timer.start()
}
}
}
</code></pre>
|
[
{
"answer_id": 74493788,
"author": "folibis",
"author_id": 2981610,
"author_profile": "https://Stackoverflow.com/users/2981610",
"pm_score": 1,
"selected": false,
"text": " import QtQuick\n import QtQuick.Timeline\n import QtQuick.Controls\n \n Window {\n width: 500\n height: 400\n visible: true\n \n Component {\n id: keyframeComponent\n KeyframeGroup {\n property int startFrame: 0\n property int endFrame: 0\n property int startValue: 0\n property: \"height\"\n Keyframe { frame: startFrame; value: startValue }\n Keyframe { frame: (startFrame + endFrame) / 2; value: 300 }\n Keyframe { frame: endFrame; value: startValue }\n }\n }\n \n Row {\n width: parent.width\n height: 300\n spacing: 1\n Repeater {\n model: 10\n Rectangle {\n id: rect\n width: 49\n height: Math.round(Math.random() * parent.height)\n color: \"orange\"\n Component.onCompleted: {\n var startFrame = Math.round(Math.random() * 100);\n var endFrame = Math.round(Math.random() * 100);\n if(startFrame > endFrame)\n {\n var temp = endFrame;\n endFrame = startFrame;\n startFrame = temp;\n }\n var group = keyframeComponent.createObject(timelineAnimation, {\n startFrame: startFrame,\n endFrame: endFrame,\n startValue: rect.height,\n target: rect });\n timeline.keyframeGroups.push(group);\n }\n }\n }\n }\n \n Button {\n anchors.bottom: parent.bottom\n anchors.horizontalCenter: parent.horizontalCenter\n anchors.bottomMargin: 10\n text: \"Start\"\n onClicked: {\n timelineAnimation.start();\n }\n }\n \n Timeline {\n id: timeline\n startFrame: 0\n endFrame: 100\n enabled: true\n \n animations: [\n TimelineAnimation {\n duration: 1000;\n from: 0;\n to: 100;\n running: false;\n id: timelineAnimation\n }\n ]\n keyframeGroups: []\n }\n }\n KeyframeGroup"
},
{
"answer_id": 74496078,
"author": "Stephen Quan",
"author_id": 881441,
"author_profile": "https://Stackoverflow.com/users/881441",
"pm_score": 0,
"selected": false,
"text": "PauseAnimation MouseArea import QtQuick\nimport QtQuick.Controls\nPage {\n id: page\n background: Rectangle { color: \"#848895\" }\n property var animateFuncs: ([ ])\n Repeater {\n model: 10\n delegate: Rectangle {\n id: _rect\n border.color: \"white\"\n color: \"green\"\n x: index * 60 + 50\n y: 50\n width: 50\n height: 50\n SequentialAnimation {\n id: anim\n property int delay\n PauseAnimation {duration: anim.delay}\n NumberAnimation {target: _rect; property: \"height\"; from: 50; to: 150}\n NumberAnimation {target: _rect; property: \"height\"; from: 150; to: 50}\n }\n function animateWithDelay(delay) {\n anim.delay = delay;\n anim.start();\n }\n Component.onCompleted: animateFuncs[index] = animateWithDelay\n }\n }\n MouseArea {\n anchors.fill: parent\n onClicked: {\n let pick = Math.floor(Math.random() * 6);\n animateFuncs[pick](0);\n animateFuncs[pick+1](300);\n animateFuncs[pick+2](600);\n animateFuncs[pick+3](900);\n animateFuncs[pick+4](1200);\n }\n }\n}\n"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74493149",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5405069/"
] |
74,493,189
|
<p>I have the following data in R:</p>
<pre><code>id = 1:5
col1 = c("john", "henry", "adam", "jenna", "Phone: 222 2222")
col2 = c("river B8C 9L4", "Field U9H 5E2 PP", "NA", "ocean A1B 5H1 dd", "dave")
col3 = c("Phone: 111 1111 111", "steve", "forest K0Y 1U9 hu2", "NA", "NA")
col4 = c("matt", "peter", "Phone: 333 333 1113", "Phone: 444 111 1153", "kevin")
my_data = data.frame(id, col1, col2, col3, col4)
id col1 col2 col3 col4
1 1 john river B8C 9L4 Phone: 111 1111 111 matt
2 2 henry Field U9H 5E2 PP steve peter
3 3 adam NA forest K0Y 1U9 hu2 Phone: 333 333 1113
4 4 jenna ocean A1B 5H1 dd NA Phone: 444 111 1153
5 5 Phone: 222 2222 dave NA kevin
</code></pre>
<p>I am trying to accomplish the following task - I would like to create a new dataset with the following columns. For each row:</p>
<ul>
<li>Step 1: id (trivial, this is always the first column)</li>
<li>Step 2: A column with the phone number</li>
<li>Step 3: A column that satisfies the following condition <code>'(([A-Z] ?[0-9]){3})|.', '\\1'</code></li>
<li>Step 4: Once Step 1 - Step 3 has been completed, I would like to combine all names into a single column</li>
</ul>
<p>Here is a sample of the desired output:</p>
<pre><code> id name address phone
1 1 john matt river B8C 9L4 Phone: 111 1111 111
2 2 henry steve peter Field U9H 5E2 PP NA
3 3 adam forest K0Y 1U9 hu2 Phone: 333 333 1113
4 4 jenna ocean A1B 5H1 dd Phone: 444 111 1153
5 5 dave kevin NA Phone: 222 2222
</code></pre>
<p>Here is the code I have written:</p>
<pre><code>my_data$col1[grep("Phone", my_data$col1)]
my_data$col2[grep("Phone", my_data$col2)]
my_data$col3[grep("Phone", my_data$col3)]
my_data$col4[grep("Phone", my_data$col4)]
my_data$col1[grep( '(([A-Z] ?[0-9]){3})|.', '\\1' , my_data$col1)]
my_data$col2[grep('(([A-Z] ?[0-9]){3})|.', '\\1', my_data$col2)]
my_data$col3[grep('(([A-Z] ?[0-9]){3})|.', '\\1', my_data$col3)]
my_data$col4[grep('(([A-Z] ?[0-9]){3})|.', '\\1', my_data$col4)]
</code></pre>
<p>Based on the above code, I was thinking on identifying which of the columns meet the condition in each step, and then using the COLASCE statement in dplyr to create the final dataset. But I think this might be a very long way of accomplishing this problem.</p>
<p>Can someone please suggest a faster way to solve this problem?</p>
<p>Thanks!</p>
|
[
{
"answer_id": 74493788,
"author": "folibis",
"author_id": 2981610,
"author_profile": "https://Stackoverflow.com/users/2981610",
"pm_score": 1,
"selected": false,
"text": " import QtQuick\n import QtQuick.Timeline\n import QtQuick.Controls\n \n Window {\n width: 500\n height: 400\n visible: true\n \n Component {\n id: keyframeComponent\n KeyframeGroup {\n property int startFrame: 0\n property int endFrame: 0\n property int startValue: 0\n property: \"height\"\n Keyframe { frame: startFrame; value: startValue }\n Keyframe { frame: (startFrame + endFrame) / 2; value: 300 }\n Keyframe { frame: endFrame; value: startValue }\n }\n }\n \n Row {\n width: parent.width\n height: 300\n spacing: 1\n Repeater {\n model: 10\n Rectangle {\n id: rect\n width: 49\n height: Math.round(Math.random() * parent.height)\n color: \"orange\"\n Component.onCompleted: {\n var startFrame = Math.round(Math.random() * 100);\n var endFrame = Math.round(Math.random() * 100);\n if(startFrame > endFrame)\n {\n var temp = endFrame;\n endFrame = startFrame;\n startFrame = temp;\n }\n var group = keyframeComponent.createObject(timelineAnimation, {\n startFrame: startFrame,\n endFrame: endFrame,\n startValue: rect.height,\n target: rect });\n timeline.keyframeGroups.push(group);\n }\n }\n }\n }\n \n Button {\n anchors.bottom: parent.bottom\n anchors.horizontalCenter: parent.horizontalCenter\n anchors.bottomMargin: 10\n text: \"Start\"\n onClicked: {\n timelineAnimation.start();\n }\n }\n \n Timeline {\n id: timeline\n startFrame: 0\n endFrame: 100\n enabled: true\n \n animations: [\n TimelineAnimation {\n duration: 1000;\n from: 0;\n to: 100;\n running: false;\n id: timelineAnimation\n }\n ]\n keyframeGroups: []\n }\n }\n KeyframeGroup"
},
{
"answer_id": 74496078,
"author": "Stephen Quan",
"author_id": 881441,
"author_profile": "https://Stackoverflow.com/users/881441",
"pm_score": 0,
"selected": false,
"text": "PauseAnimation MouseArea import QtQuick\nimport QtQuick.Controls\nPage {\n id: page\n background: Rectangle { color: \"#848895\" }\n property var animateFuncs: ([ ])\n Repeater {\n model: 10\n delegate: Rectangle {\n id: _rect\n border.color: \"white\"\n color: \"green\"\n x: index * 60 + 50\n y: 50\n width: 50\n height: 50\n SequentialAnimation {\n id: anim\n property int delay\n PauseAnimation {duration: anim.delay}\n NumberAnimation {target: _rect; property: \"height\"; from: 50; to: 150}\n NumberAnimation {target: _rect; property: \"height\"; from: 150; to: 50}\n }\n function animateWithDelay(delay) {\n anim.delay = delay;\n anim.start();\n }\n Component.onCompleted: animateFuncs[index] = animateWithDelay\n }\n }\n MouseArea {\n anchors.fill: parent\n onClicked: {\n let pick = Math.floor(Math.random() * 6);\n animateFuncs[pick](0);\n animateFuncs[pick+1](300);\n animateFuncs[pick+2](600);\n animateFuncs[pick+3](900);\n animateFuncs[pick+4](1200);\n }\n }\n}\n"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74493189",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13203841/"
] |
74,493,191
|
<p>I was prompted to modify one of our filters so that we can specify which portion of the image should be modified.
row1 and col1 : the top left coordinates the rectangle to modify
row2 and col2: the bottom right coordinates of the rectangle to modify</p>
<p>I have attmepted this but it has not worked.</p>
<p>This is what I have attempted thus far</p>
<p>`</p>
<pre><code>def invertspot(pic, row1, col1, row2, col2):
# Go through each row and column
for row in range(pic.height):
for col in range(pic.width):
# Gets a pixel at row/col
pixel = pic.pixels[row1][col1][row2][col2]
# Get the RGB values of this pixel
red = pixel.red
green = pixel.green
blue = pixel.blue
# Resave them and get the inverse by subtracting 255 from the value of the
#color
pixel.red = 255 - red
pixel.green = 255 - green
pixel.blue = 255 - blue
# Finally, reset the pixel stored at that spot
pic.pixels[row][col] = pixel
</code></pre>
<p>`</p>
|
[
{
"answer_id": 74493788,
"author": "folibis",
"author_id": 2981610,
"author_profile": "https://Stackoverflow.com/users/2981610",
"pm_score": 1,
"selected": false,
"text": " import QtQuick\n import QtQuick.Timeline\n import QtQuick.Controls\n \n Window {\n width: 500\n height: 400\n visible: true\n \n Component {\n id: keyframeComponent\n KeyframeGroup {\n property int startFrame: 0\n property int endFrame: 0\n property int startValue: 0\n property: \"height\"\n Keyframe { frame: startFrame; value: startValue }\n Keyframe { frame: (startFrame + endFrame) / 2; value: 300 }\n Keyframe { frame: endFrame; value: startValue }\n }\n }\n \n Row {\n width: parent.width\n height: 300\n spacing: 1\n Repeater {\n model: 10\n Rectangle {\n id: rect\n width: 49\n height: Math.round(Math.random() * parent.height)\n color: \"orange\"\n Component.onCompleted: {\n var startFrame = Math.round(Math.random() * 100);\n var endFrame = Math.round(Math.random() * 100);\n if(startFrame > endFrame)\n {\n var temp = endFrame;\n endFrame = startFrame;\n startFrame = temp;\n }\n var group = keyframeComponent.createObject(timelineAnimation, {\n startFrame: startFrame,\n endFrame: endFrame,\n startValue: rect.height,\n target: rect });\n timeline.keyframeGroups.push(group);\n }\n }\n }\n }\n \n Button {\n anchors.bottom: parent.bottom\n anchors.horizontalCenter: parent.horizontalCenter\n anchors.bottomMargin: 10\n text: \"Start\"\n onClicked: {\n timelineAnimation.start();\n }\n }\n \n Timeline {\n id: timeline\n startFrame: 0\n endFrame: 100\n enabled: true\n \n animations: [\n TimelineAnimation {\n duration: 1000;\n from: 0;\n to: 100;\n running: false;\n id: timelineAnimation\n }\n ]\n keyframeGroups: []\n }\n }\n KeyframeGroup"
},
{
"answer_id": 74496078,
"author": "Stephen Quan",
"author_id": 881441,
"author_profile": "https://Stackoverflow.com/users/881441",
"pm_score": 0,
"selected": false,
"text": "PauseAnimation MouseArea import QtQuick\nimport QtQuick.Controls\nPage {\n id: page\n background: Rectangle { color: \"#848895\" }\n property var animateFuncs: ([ ])\n Repeater {\n model: 10\n delegate: Rectangle {\n id: _rect\n border.color: \"white\"\n color: \"green\"\n x: index * 60 + 50\n y: 50\n width: 50\n height: 50\n SequentialAnimation {\n id: anim\n property int delay\n PauseAnimation {duration: anim.delay}\n NumberAnimation {target: _rect; property: \"height\"; from: 50; to: 150}\n NumberAnimation {target: _rect; property: \"height\"; from: 150; to: 50}\n }\n function animateWithDelay(delay) {\n anim.delay = delay;\n anim.start();\n }\n Component.onCompleted: animateFuncs[index] = animateWithDelay\n }\n }\n MouseArea {\n anchors.fill: parent\n onClicked: {\n let pick = Math.floor(Math.random() * 6);\n animateFuncs[pick](0);\n animateFuncs[pick+1](300);\n animateFuncs[pick+2](600);\n animateFuncs[pick+3](900);\n animateFuncs[pick+4](1200);\n }\n }\n}\n"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74493191",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18749302/"
] |
74,493,198
|
<p>OK, what I want is, if a person types the URL "test.MyClientsDomain.net" they actually go to "MyCompanyDomain.com" (but the URL bar shows "test.MyClientsDomain.net").</p>
<p>Here is what I have done so far:</p>
<ul>
<li>We purchased a SSL from goDaddy that allows us to add multiple domains and both domains are on it.</li>
<li>MyCompanyDomain.com is our main site, on a windows server at Rackspace that I have control over, and that works as expected</li>
<li>I have MyClientsDomain.net registered at NameCheap, the DNS is hosted at a 3rd party (plesk server that I have control of)</li>
<li>I have added a CNAME at the 3rd party DNS that points test.MyClientsDomain.net to MyCompanyDomain.com</li>
<li>I have added the "zone" MyClientsDomain.net to the DNS at Rackspace and it points to the webserver's IP</li>
<li>I have added a CNAME at the Rackspace DNS that points test.MyClientsDomain.net to MyCompanyDomain.com</li>
</ul>
<p>But it's not working as I want, can you tell me what I am doing wrong?</p>
|
[
{
"answer_id": 74493788,
"author": "folibis",
"author_id": 2981610,
"author_profile": "https://Stackoverflow.com/users/2981610",
"pm_score": 1,
"selected": false,
"text": " import QtQuick\n import QtQuick.Timeline\n import QtQuick.Controls\n \n Window {\n width: 500\n height: 400\n visible: true\n \n Component {\n id: keyframeComponent\n KeyframeGroup {\n property int startFrame: 0\n property int endFrame: 0\n property int startValue: 0\n property: \"height\"\n Keyframe { frame: startFrame; value: startValue }\n Keyframe { frame: (startFrame + endFrame) / 2; value: 300 }\n Keyframe { frame: endFrame; value: startValue }\n }\n }\n \n Row {\n width: parent.width\n height: 300\n spacing: 1\n Repeater {\n model: 10\n Rectangle {\n id: rect\n width: 49\n height: Math.round(Math.random() * parent.height)\n color: \"orange\"\n Component.onCompleted: {\n var startFrame = Math.round(Math.random() * 100);\n var endFrame = Math.round(Math.random() * 100);\n if(startFrame > endFrame)\n {\n var temp = endFrame;\n endFrame = startFrame;\n startFrame = temp;\n }\n var group = keyframeComponent.createObject(timelineAnimation, {\n startFrame: startFrame,\n endFrame: endFrame,\n startValue: rect.height,\n target: rect });\n timeline.keyframeGroups.push(group);\n }\n }\n }\n }\n \n Button {\n anchors.bottom: parent.bottom\n anchors.horizontalCenter: parent.horizontalCenter\n anchors.bottomMargin: 10\n text: \"Start\"\n onClicked: {\n timelineAnimation.start();\n }\n }\n \n Timeline {\n id: timeline\n startFrame: 0\n endFrame: 100\n enabled: true\n \n animations: [\n TimelineAnimation {\n duration: 1000;\n from: 0;\n to: 100;\n running: false;\n id: timelineAnimation\n }\n ]\n keyframeGroups: []\n }\n }\n KeyframeGroup"
},
{
"answer_id": 74496078,
"author": "Stephen Quan",
"author_id": 881441,
"author_profile": "https://Stackoverflow.com/users/881441",
"pm_score": 0,
"selected": false,
"text": "PauseAnimation MouseArea import QtQuick\nimport QtQuick.Controls\nPage {\n id: page\n background: Rectangle { color: \"#848895\" }\n property var animateFuncs: ([ ])\n Repeater {\n model: 10\n delegate: Rectangle {\n id: _rect\n border.color: \"white\"\n color: \"green\"\n x: index * 60 + 50\n y: 50\n width: 50\n height: 50\n SequentialAnimation {\n id: anim\n property int delay\n PauseAnimation {duration: anim.delay}\n NumberAnimation {target: _rect; property: \"height\"; from: 50; to: 150}\n NumberAnimation {target: _rect; property: \"height\"; from: 150; to: 50}\n }\n function animateWithDelay(delay) {\n anim.delay = delay;\n anim.start();\n }\n Component.onCompleted: animateFuncs[index] = animateWithDelay\n }\n }\n MouseArea {\n anchors.fill: parent\n onClicked: {\n let pick = Math.floor(Math.random() * 6);\n animateFuncs[pick](0);\n animateFuncs[pick+1](300);\n animateFuncs[pick+2](600);\n animateFuncs[pick+3](900);\n animateFuncs[pick+4](1200);\n }\n }\n}\n"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74493198",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2872007/"
] |
74,493,224
|
<p>I have a pandas Dataframe of tennis games with 70,000 games (rows) with two issues:</p>
<ol>
<li><p>Every game is duplicated, because for every game between player A and B, there's a row when A plays with B and a row when B plays with A. This happens because I extracted all games played for each player, so I have all games that Nadal played, and then all games that Federer played. For the games I extracted from Nadal's page, Nadal is player A and Federer is player B, and for the games I extracted from Federer's page, Federer is player A and Nadal is player B.</p>
</li>
<li><p>The second issue is that for every game, I only have info about player A, so using the example mentioned before, for the games I extracted where Nadal is player A, facing Federer, I have Nadal's height, age and ranking, but I don't have that info for Federer. And for the games I extracted where Federer is player A, facing Nadal, I have Federer's height, age and ranking, but I don't have that info for Nadal</p>
</li>
</ol>
<p>Bellow is the example of the data for a better understanding:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Player A</th>
<th>Rank</th>
<th>Height</th>
<th>Age</th>
<th>Tourn.</th>
<th>Year</th>
<th>Round</th>
<th>Player B</th>
<th>Result</th>
</tr>
</thead>
<tbody>
<tr>
<td>Nadal</td>
<td>3</td>
<td>185</td>
<td>37</td>
<td>US Open</td>
<td>2019</td>
<td>Finals</td>
<td>Federer</td>
<td>W</td>
</tr>
<tr>
<td>Federer</td>
<td>7</td>
<td>183</td>
<td>40</td>
<td>US Open</td>
<td>2019</td>
<td>Finals</td>
<td>Nadal</td>
<td>L</td>
</tr>
</tbody>
</table>
</div>
<p>My objective is to add in the same row the information of both players like this:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Player A</th>
<th>Rank</th>
<th>Height</th>
<th>Age</th>
<th>Tourn.</th>
<th>Year</th>
<th>Round</th>
<th>Player B</th>
<th>Rank_B</th>
<th>Height_B</th>
<th>Age_B</th>
<th>Result</th>
</tr>
</thead>
<tbody>
<tr>
<td>Nadal</td>
<td>3</td>
<td>185</td>
<td>37</td>
<td>US Open</td>
<td>2019</td>
<td>Finals</td>
<td>Federer</td>
<td>7</td>
<td>183</td>
<td>40</td>
<td>W</td>
</tr>
</tbody>
</table>
</div>
<p>And then remove all duplicate lines.</p>
<p>I have already solved the issue by doing a for loop inside a for loop and comparing every line. Once the criteria I set is met I proceed to change the lines. I consider that a game is duplicate if in the same year, tournament and round, the same players face each other.</p>
<pre class="lang-python prettyprint-override"><code>
import pandas as pd
import numpy as np
games = pd.read_csv("games.csv")
# create the new columns to add info of opponent:
games["Rank_B"] = np.nan
games["Height_B"] = np.nan
games["Age_B"] = np.nan
# loop through every line:
for i in range(0,len(games)):
# if the row was already mark to delete skip it
if games.loc[i, "p_name"] == "Delete":
next
# for each line compare it to every line:
for j in range(0,len(games)):
if games.loc[i, "Tourn."] == games.loc[j, "Tourn."] and games.loc[i, "Year"] == games.loc[j, "Year"] and games.loc[i, "Round"] == games.loc[j, "Round"] and games.loc[i, "Player A"] == games.loc[j, "Player B"]:
games.loc[i, "Height_B"] = games.loc[j, "Height"]
games.loc[i, "Rank_B"] = games.loc[j, "Rank"]
games.loc[i, "Age_B"] = games.loc[j, "Age"]
# marks row to delete because it is duplicate:
games.loc[j, "p_name"] = "Delete"
break
games = games[games["p_name"].str.contains("Delete") == False]
</code></pre>
<p>The problem is that my solution is very slow, taking a whopping 12 hours to run for 70,000 rows. If I want to run this code with a dataframe of 1,000,000 rows this solution is impractical.</p>
<p>Can you think of a better way to accomplish my objective?</p>
|
[
{
"answer_id": 74493788,
"author": "folibis",
"author_id": 2981610,
"author_profile": "https://Stackoverflow.com/users/2981610",
"pm_score": 1,
"selected": false,
"text": " import QtQuick\n import QtQuick.Timeline\n import QtQuick.Controls\n \n Window {\n width: 500\n height: 400\n visible: true\n \n Component {\n id: keyframeComponent\n KeyframeGroup {\n property int startFrame: 0\n property int endFrame: 0\n property int startValue: 0\n property: \"height\"\n Keyframe { frame: startFrame; value: startValue }\n Keyframe { frame: (startFrame + endFrame) / 2; value: 300 }\n Keyframe { frame: endFrame; value: startValue }\n }\n }\n \n Row {\n width: parent.width\n height: 300\n spacing: 1\n Repeater {\n model: 10\n Rectangle {\n id: rect\n width: 49\n height: Math.round(Math.random() * parent.height)\n color: \"orange\"\n Component.onCompleted: {\n var startFrame = Math.round(Math.random() * 100);\n var endFrame = Math.round(Math.random() * 100);\n if(startFrame > endFrame)\n {\n var temp = endFrame;\n endFrame = startFrame;\n startFrame = temp;\n }\n var group = keyframeComponent.createObject(timelineAnimation, {\n startFrame: startFrame,\n endFrame: endFrame,\n startValue: rect.height,\n target: rect });\n timeline.keyframeGroups.push(group);\n }\n }\n }\n }\n \n Button {\n anchors.bottom: parent.bottom\n anchors.horizontalCenter: parent.horizontalCenter\n anchors.bottomMargin: 10\n text: \"Start\"\n onClicked: {\n timelineAnimation.start();\n }\n }\n \n Timeline {\n id: timeline\n startFrame: 0\n endFrame: 100\n enabled: true\n \n animations: [\n TimelineAnimation {\n duration: 1000;\n from: 0;\n to: 100;\n running: false;\n id: timelineAnimation\n }\n ]\n keyframeGroups: []\n }\n }\n KeyframeGroup"
},
{
"answer_id": 74496078,
"author": "Stephen Quan",
"author_id": 881441,
"author_profile": "https://Stackoverflow.com/users/881441",
"pm_score": 0,
"selected": false,
"text": "PauseAnimation MouseArea import QtQuick\nimport QtQuick.Controls\nPage {\n id: page\n background: Rectangle { color: \"#848895\" }\n property var animateFuncs: ([ ])\n Repeater {\n model: 10\n delegate: Rectangle {\n id: _rect\n border.color: \"white\"\n color: \"green\"\n x: index * 60 + 50\n y: 50\n width: 50\n height: 50\n SequentialAnimation {\n id: anim\n property int delay\n PauseAnimation {duration: anim.delay}\n NumberAnimation {target: _rect; property: \"height\"; from: 50; to: 150}\n NumberAnimation {target: _rect; property: \"height\"; from: 150; to: 50}\n }\n function animateWithDelay(delay) {\n anim.delay = delay;\n anim.start();\n }\n Component.onCompleted: animateFuncs[index] = animateWithDelay\n }\n }\n MouseArea {\n anchors.fill: parent\n onClicked: {\n let pick = Math.floor(Math.random() * 6);\n animateFuncs[pick](0);\n animateFuncs[pick+1](300);\n animateFuncs[pick+2](600);\n animateFuncs[pick+3](900);\n animateFuncs[pick+4](1200);\n }\n }\n}\n"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74493224",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17777564/"
] |
74,493,302
|
<p>Checking if the Struct conformed to protocol, but if the nested struct is optional it always returns <code>false</code>,</p>
<p>example:</p>
<pre class="lang-swift prettyprint-override"><code>protocol XYZ {
}
extension XYZ {
func test() {
print("asdsfd")
}
}
struct Test1: XYZ {
var test2: Test2
var test3: Test3?
init(){
self.test2 = Test2()
self.test3 = Test3()
}
}
struct Test2: XYZ {
}
struct Test3: XYZ {
}
</code></pre>
<p>Now: if I want check if the struct is using protocol</p>
<pre class="lang-swift prettyprint-override"><code>let x = Test1()
</code></pre>
<p>below condition will be true because <code>Test2</code> conformed to <code>XYZ</code> protocol</p>
<pre class="lang-swift prettyprint-override"><code>print(type(of: x.test2) is XYZ.Type)
</code></pre>
<p>below condition will be false because <code>Optional<Test2></code> conformed to <code>XYZ</code> protocol should be <code>true</code> but it's return <code>false</code> because of optional</p>
<pre class="lang-swift prettyprint-override"><code>print(type(of: x.test3) is XYZ.Type)
</code></pre>
<p>how should I handle the optional in this case, I tried by unwrapping optional but it's not happening. any help is appreciated.</p>
<p>I tried to unwrap the optional but it's not happening. I am trying to find a way to compare the optional type conforms to protocol.</p>
|
[
{
"answer_id": 74493788,
"author": "folibis",
"author_id": 2981610,
"author_profile": "https://Stackoverflow.com/users/2981610",
"pm_score": 1,
"selected": false,
"text": " import QtQuick\n import QtQuick.Timeline\n import QtQuick.Controls\n \n Window {\n width: 500\n height: 400\n visible: true\n \n Component {\n id: keyframeComponent\n KeyframeGroup {\n property int startFrame: 0\n property int endFrame: 0\n property int startValue: 0\n property: \"height\"\n Keyframe { frame: startFrame; value: startValue }\n Keyframe { frame: (startFrame + endFrame) / 2; value: 300 }\n Keyframe { frame: endFrame; value: startValue }\n }\n }\n \n Row {\n width: parent.width\n height: 300\n spacing: 1\n Repeater {\n model: 10\n Rectangle {\n id: rect\n width: 49\n height: Math.round(Math.random() * parent.height)\n color: \"orange\"\n Component.onCompleted: {\n var startFrame = Math.round(Math.random() * 100);\n var endFrame = Math.round(Math.random() * 100);\n if(startFrame > endFrame)\n {\n var temp = endFrame;\n endFrame = startFrame;\n startFrame = temp;\n }\n var group = keyframeComponent.createObject(timelineAnimation, {\n startFrame: startFrame,\n endFrame: endFrame,\n startValue: rect.height,\n target: rect });\n timeline.keyframeGroups.push(group);\n }\n }\n }\n }\n \n Button {\n anchors.bottom: parent.bottom\n anchors.horizontalCenter: parent.horizontalCenter\n anchors.bottomMargin: 10\n text: \"Start\"\n onClicked: {\n timelineAnimation.start();\n }\n }\n \n Timeline {\n id: timeline\n startFrame: 0\n endFrame: 100\n enabled: true\n \n animations: [\n TimelineAnimation {\n duration: 1000;\n from: 0;\n to: 100;\n running: false;\n id: timelineAnimation\n }\n ]\n keyframeGroups: []\n }\n }\n KeyframeGroup"
},
{
"answer_id": 74496078,
"author": "Stephen Quan",
"author_id": 881441,
"author_profile": "https://Stackoverflow.com/users/881441",
"pm_score": 0,
"selected": false,
"text": "PauseAnimation MouseArea import QtQuick\nimport QtQuick.Controls\nPage {\n id: page\n background: Rectangle { color: \"#848895\" }\n property var animateFuncs: ([ ])\n Repeater {\n model: 10\n delegate: Rectangle {\n id: _rect\n border.color: \"white\"\n color: \"green\"\n x: index * 60 + 50\n y: 50\n width: 50\n height: 50\n SequentialAnimation {\n id: anim\n property int delay\n PauseAnimation {duration: anim.delay}\n NumberAnimation {target: _rect; property: \"height\"; from: 50; to: 150}\n NumberAnimation {target: _rect; property: \"height\"; from: 150; to: 50}\n }\n function animateWithDelay(delay) {\n anim.delay = delay;\n anim.start();\n }\n Component.onCompleted: animateFuncs[index] = animateWithDelay\n }\n }\n MouseArea {\n anchors.fill: parent\n onClicked: {\n let pick = Math.floor(Math.random() * 6);\n animateFuncs[pick](0);\n animateFuncs[pick+1](300);\n animateFuncs[pick+2](600);\n animateFuncs[pick+3](900);\n animateFuncs[pick+4](1200);\n }\n }\n}\n"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74493302",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20541684/"
] |
74,493,308
|
<p>I am trying to create an array of urls, the array is called "sentences". So far I have seen that you must use a useState if you want to put the API response in an array. This is what I have tried so far.</p>
<pre><code> const [sentences, setSentences] = useState([]);
const getOpenAIResponse = () => {
for (var i = 0; i < 6; i++) {
openai.createImage({
prompt: prompts[i],
n: 1,
size: "256x256",
}).then((response) => {
setSentences(response.data.data[0].url)
console.log(sentences)
})
}
};
</code></pre>
<p>The issue is sentences just refreshes with the next url response that is generated. Using setSentences.push(...) does not work. Is there anything you would you recommend?</p>
|
[
{
"answer_id": 74493336,
"author": "Blundering Philosopher",
"author_id": 2430414,
"author_profile": "https://Stackoverflow.com/users/2430414",
"pm_score": 3,
"selected": true,
"text": "getOpenAIResponse openai.createImage sentences const getOpenAIResponse = () => {\n imagePromises = [];\n\n // Collect all image promises in an array\n for (var i = 0; i < 6; i++) {\n imagePromises.push(\n openai.createImage({\n prompt: prompts[i],\n n: 1,\n size: \"256x256\",\n })\n );\n }\n\n // Do something once all promises resolve\n Promise.all(imagePromises)\n .then((responses) => {\n setSentences([\n // Keep current list of sentences\n ...sentences,\n\n // Add new sentences to old list of sentences\n ...responses.map(response => response.data.data[0].url),\n ]);\n });\n};\n setSentences(response.data.data[0].url) openai.createImage sentences setSentences setSentences(sentences.concat(response.data.data[0].url)) .push .push .concat // This returns 4 which is the size of the array!\n[1,2,3].push(4);\n\n// These return [1,2,3,4] which is the new array, with the added new element at the end\n[1,2,3].concat(4);\n[1,2,3].concat([4]);\n"
},
{
"answer_id": 74493375,
"author": "Beyondo",
"author_id": 8524922,
"author_profile": "https://Stackoverflow.com/users/8524922",
"pm_score": 2,
"selected": false,
"text": "setSentences([...sentences, response.data.data[0].url])\n setSentences(sentences.concat(response.data.data[0].url))\n"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74493308",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20518918/"
] |
74,493,310
|
<p>Suppose you have this simple class hierarchy:</p>
<pre><code>struct base {
virtual void f () const = 0;
};
struct derived : public base {
virtual void f () const final
{
...
}
};
</code></pre>
<p>There is only one implementation of f(), and because it is declared final, may we consider that there is no polymorphism ?</p>
<p>If so, will the compiler optimize code by avoiding use of a virtual table since 'You don't pay what you don't use ?'</p>
<p>Thank you.</p>
|
[
{
"answer_id": 74493580,
"author": "Hein Breukers",
"author_id": 16860716,
"author_profile": "https://Stackoverflow.com/users/16860716",
"pm_score": 2,
"selected": false,
"text": "struct base {\n\nvirtual int f () const = 0;\n\n};\n\nstruct derived : public base {\n\nvirtual int f () const final { return 2; }\n\n};\n\nint returnf(const base& b)\n{\n return b.f();\n}\n main:\n xor eax,eax\n ret \n cs nop WORD PTR [rax+rax*1+0x0]\n nop DWORD PTR [rax]\nreturnf(base const&):\n mov rax,QWORD PTR [rdi]\n mov rax,QWORD PTR [rax]\n cmp rax,0x401140\n jne 401138 <returnf(base const&)+0x18>\n mov eax,0x2\n ret \n nop DWORD PTR [rax+0x0]\n jmp rax\n nop WORD PTR [rax+rax*1+0x0]\nderived::f() const:\n mov eax,0x2\n ret \n cs nop WORD PTR [rax+rax*1+0x0]\n cmp rax,0x401140\n jne 401138 <returnf(base const&)+0x18>\n"
},
{
"answer_id": 74494190,
"author": "n. m.",
"author_id": 775806,
"author_profile": "https://Stackoverflow.com/users/775806",
"pm_score": 2,
"selected": false,
"text": "pDerived->f() final pBase->f() pBase derived base f final"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74493310",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1856951/"
] |
74,493,317
|
<p>In our compony we use ant design library. And when I added one of the components from the library to my project and I looked in Chrome DevTools I was amused that I found a property that called <strong>--antd-arrow-background-color: none;</strong></p>
<p>Before I thought that all browsers can understand and show only properties from W3C standard that is from this list <a href="https://www.w3schools.com/cssref/index.php" rel="nofollow noreferrer">https://www.w3schools.com/cssref/index.php</a>
But how is possible that my browser (Chrome) understans other properties? For example properties that have <strong>antd</strong> prefix?</p>
<p>Can anybody explain me this?</p>
<p><strong>PS</strong> I know that there are vendor prefixes but there is no such prefix as antd among of them.</p>
|
[
{
"answer_id": 74493580,
"author": "Hein Breukers",
"author_id": 16860716,
"author_profile": "https://Stackoverflow.com/users/16860716",
"pm_score": 2,
"selected": false,
"text": "struct base {\n\nvirtual int f () const = 0;\n\n};\n\nstruct derived : public base {\n\nvirtual int f () const final { return 2; }\n\n};\n\nint returnf(const base& b)\n{\n return b.f();\n}\n main:\n xor eax,eax\n ret \n cs nop WORD PTR [rax+rax*1+0x0]\n nop DWORD PTR [rax]\nreturnf(base const&):\n mov rax,QWORD PTR [rdi]\n mov rax,QWORD PTR [rax]\n cmp rax,0x401140\n jne 401138 <returnf(base const&)+0x18>\n mov eax,0x2\n ret \n nop DWORD PTR [rax+0x0]\n jmp rax\n nop WORD PTR [rax+rax*1+0x0]\nderived::f() const:\n mov eax,0x2\n ret \n cs nop WORD PTR [rax+rax*1+0x0]\n cmp rax,0x401140\n jne 401138 <returnf(base const&)+0x18>\n"
},
{
"answer_id": 74494190,
"author": "n. m.",
"author_id": 775806,
"author_profile": "https://Stackoverflow.com/users/775806",
"pm_score": 2,
"selected": false,
"text": "pDerived->f() final pBase->f() pBase derived base f final"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74493317",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9664379/"
] |
74,493,338
|
<p>I am trying to grab a record that meets multiple conditions. See below.</p>
<p><strong>DATA:</strong></p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>PERSON_ID</th>
<th>DOCTOR</th>
<th>DATE_OF_SERVICE</th>
</tr>
</thead>
<tbody>
<tr>
<td>1234</td>
<td>Dr. Smith</td>
<td>2022-01-01</td>
</tr>
<tr>
<td>1234</td>
<td></td>
<td>2022-01-01</td>
</tr>
<tr>
<td>1234</td>
<td>Dr. Jane</td>
<td>2022-03-01</td>
</tr>
<tr>
<td>1234</td>
<td></td>
<td>2022-06-01</td>
</tr>
</tbody>
</table>
</div>
<p><strong>DESIRED OUTPUT:</strong></p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>ID</th>
<th>DOCTOR</th>
<th>DATE_OF_SERVICE</th>
</tr>
</thead>
<tbody>
<tr>
<td>1234</td>
<td>Dr. Smith</td>
<td>2022-01-01</td>
</tr>
<tr>
<td>1234</td>
<td>Dr. Jane</td>
<td>2022-03-01</td>
</tr>
<tr>
<td>1234</td>
<td></td>
<td>2022-06-01</td>
</tr>
</tbody>
</table>
</div>
<p>Basically, if a person_id has the same date_of_service but one record has a doctor populated and the other doesn't, take the record where the doctor is not null.</p>
<p>BUT - if there is only one record where there is no doctor listed, then it is okay to keep.</p>
<p>Is this doable? Any help would be greatly helpful</p>
|
[
{
"answer_id": 74493402,
"author": "forpas",
"author_id": 10498828,
"author_profile": "https://Stackoverflow.com/users/10498828",
"pm_score": 2,
"selected": true,
"text": "NOT EXISTS SELECT t1.*\nFROM tablename t1\nWHERE t1.doctor IS NOT NULL\n OR NOT EXISTS (\n SELECT *\n FROM tablename t2\n WHERE t2.person_id = t1.person_id \n AND t2.date_of_service = t1.date_of_service \n AND t2.doctor IS NOT NULL\n );\n"
},
{
"answer_id": 74494040,
"author": "Greg Pavlik",
"author_id": 12756381,
"author_profile": "https://Stackoverflow.com/users/12756381",
"pm_score": 2,
"selected": false,
"text": "qualify create or replace table T1 as \nselect \nCOLUMN1::string as \"PERSON_ID\",\nCOLUMN2::string as \"DOCTOR\",\nCOLUMN3::string as \"DATE_OF_SERVICE\"\nfrom (values\n('1234','Dr. Smith','2022-01-01'),\n('1234',null,'2022-01-01'),\n('1234','Dr. Jane','2022-03-01'),\n('1234',null,'2022-06-01')\n);\n\nselect * from T1 \nqualify (count(*)) over (partition by person_id, date_of_service) = 1 \n or doctor is not null;\n count(*) over... doctor is not null"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74493338",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14945726/"
] |
74,493,359
|
<p><strong>View:</strong></p>
<pre><code> <form action="/checklogin" method="post" enctype="multipart/form-data" class="account-form" id="login_form_order_page">
{{ csrf_field() }}
<div class="error-wrap"></div>
<div class="form-group">
<input type="text" name="email" class="form-control" placeholder="Email*" required>
</div>
<div class="form-group">
<input type="password" name="password" class="form-control" placeholder="Password*" required>
</div>
<div class="form-group btn-wrapper">
<button type="submit" id="login_btn" class="submit-btn">Login</button>
</div>
<div class="row mb-4 rmber-area">
<div class="col-6">
<div class="custom-control custom-checkbox mr-sm-2">
<input type="checkbox" name="remember" class="custom-control-input" id="remember">
<label class="custom-control-label" for="remember">Remember Me</label>
</div>
</div>
<div class="col-6 text-right">
<a class="d-block" href="/register">Create New account?</a>
<a href="login/forget-password">Forgot Password?</a>
</div>
</div>
<div class="col-lg-12">
<div class="social-login-wrap">
</div>
</div>
</form>
</code></pre>
<p><strong>Route web.php:</strong></p>
<pre><code>Route::POST('/checklogin', 'HomeController@checklogin');
</code></pre>
<p>I am submitting the form with csrf still after submitting form 419|Page Expired Error.
After adding session_start() method on page it shows headers already sent.</p>
|
[
{
"answer_id": 74493402,
"author": "forpas",
"author_id": 10498828,
"author_profile": "https://Stackoverflow.com/users/10498828",
"pm_score": 2,
"selected": true,
"text": "NOT EXISTS SELECT t1.*\nFROM tablename t1\nWHERE t1.doctor IS NOT NULL\n OR NOT EXISTS (\n SELECT *\n FROM tablename t2\n WHERE t2.person_id = t1.person_id \n AND t2.date_of_service = t1.date_of_service \n AND t2.doctor IS NOT NULL\n );\n"
},
{
"answer_id": 74494040,
"author": "Greg Pavlik",
"author_id": 12756381,
"author_profile": "https://Stackoverflow.com/users/12756381",
"pm_score": 2,
"selected": false,
"text": "qualify create or replace table T1 as \nselect \nCOLUMN1::string as \"PERSON_ID\",\nCOLUMN2::string as \"DOCTOR\",\nCOLUMN3::string as \"DATE_OF_SERVICE\"\nfrom (values\n('1234','Dr. Smith','2022-01-01'),\n('1234',null,'2022-01-01'),\n('1234','Dr. Jane','2022-03-01'),\n('1234',null,'2022-06-01')\n);\n\nselect * from T1 \nqualify (count(*)) over (partition by person_id, date_of_service) = 1 \n or doctor is not null;\n count(*) over... doctor is not null"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74493359",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15703550/"
] |
74,493,362
|
<p>I have created an SQL query that returns me elements from a film table that satisfy one of two conditions. They are either the most profitable (gross - budget) or the least expensive movies to make.</p>
<p>However, i wanted to add a column to the return of the query that said 'most profitable' or 'least expensive' in function of whichever of the conditions the tuple satisfied. I tried looking online for a solution; and i decided to try using CASE WHEN in the SELECT part of the Query.</p>
<p>Original sql query:</p>
<pre><code>SELECT DISTINCT Films.title, Films.year
FROM Films,
(
SELECT DISTINCT (MAX(Films.gross-Films.budget))AS profit FROM Films
) AS Temp1
WHERE
(
(Films.gross-Films.budget)=Temp1.profit)
OR (Films.budget)=(SELECT DISTINCT Min(Films.budget) FROM Films)
)
</code></pre>
<p>CASE WHEN attempt:</p>
<pre><code>SELECT DISTINCT
CASE WHEN Temp1.profit=Max(Temp1.profit) THEN 'most profitable' ELSE 'least expensive' END AS feature,
Films.title,
Films.year
FROM Films,
(
SELECT DISTINCT (MAX(Films.gross-Films.budget))AS profit FROM Films
) AS Temp1
WHERE
(
(Films.gross-Films.budget)=Temp1.profit)
OR (Films.budget)=(SELECT DISTINCT Min(Films.budget) FROM Films)
)
</code></pre>
<p>However, that gave all sorts of errors like:
column "temp1.profit" must appear in the GROUP BY clause or be used in an aggregate function</p>
<p>I am not sure why it's asking this but i tried nonetheless to give it what it wanted by adding the line</p>
<pre><code>GROUP BY TEMP1.profit,Films.title,Films.year;
</code></pre>
<p>This made the error disappear but now all of the rows get the same 'most profitable' value to the feature column even if that's not why they are there!</p>
<p>I don't know if there's any way to make this work, but even a completely different way to get that column working would be a great help.</p>
|
[
{
"answer_id": 74493895,
"author": "histocrat",
"author_id": 1747583,
"author_profile": "https://Stackoverflow.com/users/1747583",
"pm_score": 1,
"selected": true,
"text": "WITH max_profit AS (SELECT MAX(gross-budget) FROM Films),\nmin_cost AS (SELECT MIN(budget) FROM Films)\nSELECT title, year, most_profitable, least_expensive FROM\n (SELECT \n Films.title, Films.year, \n (Films.gross-Films.budget = (SELECT * FROM max_profit)) AS most_profitable,\n (Films.budget = (SELECT * FROM min_cost)) AS least_expensive\n FROM Films\n )\n WHERE most_profitable OR least_expensive;\n WITH max_profit AS (SELECT MAX(gross-budget) FROM Films),\nmin_cost AS (SELECT MIN(budget) FROM Films)\nSELECT title, year, (CASE WHEN most_profitable THEN 'most profitable' ELSE 'least expensive' END) FROM\n (SELECT \n Films.title, Films.year, \n (Films.gross-Films.budget = (SELECT * FROM max_profit)) AS most_profitable,\n (Films.budget = (SELECT * FROM min_cost)) AS least_expensive\n FROM Films\n )\n WHERE most_profitable OR least_expensive;\n"
},
{
"answer_id": 74496340,
"author": "GMB",
"author_id": 10676716,
"author_profile": "https://Stackoverflow.com/users/10676716",
"pm_score": 0,
"selected": false,
"text": "select f.title, f.year,\n row_number() (order by gross - budget desc) rn_profit,\n row_number() (order by budget) rn_budget\nfrom films f\n select *\nfrom (\n select f.title, f.year,\n row_number() (order by gross - budget desc) rn_profit,\n row_number() (order by budget) rn_budget\n from films f\n) f\nwhere 1 in (rn_profit, rn_budget)\n rn_profit 1 1 rn_budget case"
},
{
"answer_id": 74498902,
"author": "a_horse_with_no_name",
"author_id": 330315,
"author_profile": "https://Stackoverflow.com/users/330315",
"pm_score": 1,
"selected": false,
"text": "(\n select *, 'most profitable'\n from films\n order by gross - budget desc\n fetch first 1 rows with ties\n)\nunion all\n(\n select *, 'least expensive'\n from films\n order by budget\n fetch first 1 rows with ties\n)\n"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74493362",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20541599/"
] |
74,493,377
|
<p>The below program is to check whether a number (say "n") prime factors are limited to 2,3,and 5 only or not. But program gives me signed integer overflow runtime error. Can anyone please help me in solving this problem? Here's the piece of code:</p>
<pre><code> bool check(int n)
{
if(n<0)
n=n*(-1); // If 'n' is negative, making it positive.
int count=1; //'count' variable to check whether the number is divisible by 2 or 3 or 5.
while(n!=1 && count)
{
count=0;
if(n%2==0)
{
n/=2; count++;
}
else if(n%3==0)
{
n/=3; count++;
}
else if(n%5==0)
{
n/=5; count++;
}
}
if(n==1)
return true;
else return false;
}
</code></pre>
<p>Program gave me this error:</p>
<p><strong>runtime error: signed integer overflow: -2147483648 * -1 cannot be represented in type 'int'</strong></p>
|
[
{
"answer_id": 74493577,
"author": "FLAK-ZOSO",
"author_id": 15888601,
"author_profile": "https://Stackoverflow.com/users/15888601",
"pm_score": 1,
"selected": false,
"text": "2^3 8 -8 7 -2147483648 2147483647"
},
{
"answer_id": 74493800,
"author": "Eljay",
"author_id": 4641116,
"author_profile": "https://Stackoverflow.com/users/4641116",
"pm_score": 0,
"selected": false,
"text": "if (n < 0) return false;\n bool check(int n) {\n for (;;) {\n if (n%2 == 0) {\n n /= 2;\n } else if (n%3 == 0) {\n n /= 3;\n } else if (n%5 == 0) {\n n /= 5;\n } else {\n break;\n } \n } \n\n return (n == 1) || (n == -1);\n}\n"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74493377",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16479369/"
] |
74,493,387
|
<p>Given query</p>
<pre><code>query user($id: Int!) {
getUser(id: $id) {
id
name
}
}
</code></pre>
<p>I'd like to grab multiple users and get them returned as an array ex: <code>const users = [1, 2, 3, 5]</code></p>
<p>I it possible to query this from client, or do I need to define new Query on the server?</p>
<p>I am using Apollo with React btw.</p>
|
[
{
"answer_id": 74493577,
"author": "FLAK-ZOSO",
"author_id": 15888601,
"author_profile": "https://Stackoverflow.com/users/15888601",
"pm_score": 1,
"selected": false,
"text": "2^3 8 -8 7 -2147483648 2147483647"
},
{
"answer_id": 74493800,
"author": "Eljay",
"author_id": 4641116,
"author_profile": "https://Stackoverflow.com/users/4641116",
"pm_score": 0,
"selected": false,
"text": "if (n < 0) return false;\n bool check(int n) {\n for (;;) {\n if (n%2 == 0) {\n n /= 2;\n } else if (n%3 == 0) {\n n /= 3;\n } else if (n%5 == 0) {\n n /= 5;\n } else {\n break;\n } \n } \n\n return (n == 1) || (n == -1);\n}\n"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74493387",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1333744/"
] |
74,493,398
|
<p>I want to put a temporary text in more than 1 entry with tkinter, but my func is not working.
I have this situation:</p>
<pre><code>def temp_text_entry_delete(e):
self.id_entry.delete(0, 'end')
self.id_entry = tk.Entry(borderwidth=2, width=10)
self.id_entry.insert(0, "ex:001")
self.id_entry.pack()
self.id_entry.bind("<FocusIn>", temp_text_entry_delete)
</code></pre>
<p>Its working, but...</p>
<p>I wan't to use the same func for other entrys, like this one:</p>
<pre><code>self.type_entry = tk.Entry(borderwidth=2, width=10)
self.type_entry.insert(0, "metal")
self.type_entry.pack()
self.type_entry.bind("<FocusIn>", temp_text_entry_delete)
</code></pre>
<p>Any ideas on how to make it universal?</p>
|
[
{
"answer_id": 74493543,
"author": "JRiggles",
"author_id": 8512262,
"author_profile": "https://Stackoverflow.com/users/8512262",
"pm_score": 1,
"selected": true,
"text": "PlaceholderEntry import tkinter as tk\nfrom tkinter import ttk\n\n\nclass PlaceholderEntry(ttk.Entry):\n \"\"\"Entry widget with placeholder text\"\"\"\n def __init__(\n self, parent, placeholder='', color='#888', *args, **kwargs\n ) -> None:\n super().__init__(parent, *args, **kwargs)\n self.placeholder = placeholder\n self._ph_color = color\n self._default_fg = self._get_fg_string()\n # focus bindings\n self.bind('<FocusIn>', self.clear_placeholder)\n self.bind('<FocusOut>', self.set_placeholder)\n # initialize the placeholder\n self.set_placeholder()\n\n def clear_placeholder(self, *args) -> None: # on focus in\n if self._get_fg_string() == self._ph_color:\n self.delete(0, tk.END) # clear the placeholder text\n self.configure(foreground=self._default_fg) # set 'normal' text color\n\n def set_placeholder(self, *args) -> None: # on focus out\n if not self.get(): # if Entry has no text...\n self.insert(0, self.placeholder) # insert placeholder text\n self.configure(foreground=self._ph_color) # set placeholder text color\n\n def _get_fg_string(self) -> str:\n return str(self.cget('foreground')\n root = tk.Tk()\nself.id_entry = PlaceholderEntry(\n parent=root,\n placeholder='Type Here',\n borderwidth=2, \n width=10\n)\nself.id_entry.pack()\n"
},
{
"answer_id": 74493808,
"author": "Bryan Oakley",
"author_id": 7432,
"author_profile": "https://Stackoverflow.com/users/7432",
"pm_score": 1,
"selected": false,
"text": "event def temp_text_entry_delete(e):\n e.widget.delete(0, 'end')\n"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74493398",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20541106/"
] |
74,493,407
|
<p>The Next.js image component is normally choosing the best possible format for an images (avif, webm etc.) by accepted format-types of the browser.
In my case i need to have the best possible format (avif) for most images except some gallery images that need to be jpeg.</p>
<p>I tried to set the format (jpg) for a specific image/url but nothing worked yet.</p>
<p>Is there a possibility to specify the format.
Like a query for the optimization "/_next/image?url=" + img-url + "?fm=jpg" or something like that?
Or a special way in the next/config?</p>
|
[
{
"answer_id": 74493543,
"author": "JRiggles",
"author_id": 8512262,
"author_profile": "https://Stackoverflow.com/users/8512262",
"pm_score": 1,
"selected": true,
"text": "PlaceholderEntry import tkinter as tk\nfrom tkinter import ttk\n\n\nclass PlaceholderEntry(ttk.Entry):\n \"\"\"Entry widget with placeholder text\"\"\"\n def __init__(\n self, parent, placeholder='', color='#888', *args, **kwargs\n ) -> None:\n super().__init__(parent, *args, **kwargs)\n self.placeholder = placeholder\n self._ph_color = color\n self._default_fg = self._get_fg_string()\n # focus bindings\n self.bind('<FocusIn>', self.clear_placeholder)\n self.bind('<FocusOut>', self.set_placeholder)\n # initialize the placeholder\n self.set_placeholder()\n\n def clear_placeholder(self, *args) -> None: # on focus in\n if self._get_fg_string() == self._ph_color:\n self.delete(0, tk.END) # clear the placeholder text\n self.configure(foreground=self._default_fg) # set 'normal' text color\n\n def set_placeholder(self, *args) -> None: # on focus out\n if not self.get(): # if Entry has no text...\n self.insert(0, self.placeholder) # insert placeholder text\n self.configure(foreground=self._ph_color) # set placeholder text color\n\n def _get_fg_string(self) -> str:\n return str(self.cget('foreground')\n root = tk.Tk()\nself.id_entry = PlaceholderEntry(\n parent=root,\n placeholder='Type Here',\n borderwidth=2, \n width=10\n)\nself.id_entry.pack()\n"
},
{
"answer_id": 74493808,
"author": "Bryan Oakley",
"author_id": 7432,
"author_profile": "https://Stackoverflow.com/users/7432",
"pm_score": 1,
"selected": false,
"text": "event def temp_text_entry_delete(e):\n e.widget.delete(0, 'end')\n"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74493407",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10653404/"
] |
74,493,441
|
<p>I want to sum a 2d list.
Example:
<code>x==[[1, 2],[3, 4],[5, 6]]</code></p>
<p>a solution should lool like:
<code>sum_2d = [3, 7, 11]</code></p>
<p>I tried this:
<code>y = sum(sum(x,[]))</code>
but that sums all the numbers.</p>
<p>Thanks for any advice.</p>
|
[
{
"answer_id": 74493469,
"author": "Talha Tayyab",
"author_id": 13086128,
"author_profile": "https://Stackoverflow.com/users/13086128",
"pm_score": 1,
"selected": false,
"text": "x=[[1, 2],[3, 4],[5, 6]]\n\n[sum(y) for y in x]\n\n#output\n[3, 7, 11]\n"
},
{
"answer_id": 74493548,
"author": "Fab",
"author_id": 18292832,
"author_profile": "https://Stackoverflow.com/users/18292832",
"pm_score": 0,
"selected": false,
"text": "x = [[1, 2], [3, 4], [5, 6]]\n\nsum_2d = []\n\nfor i in x:\n sum_2d += [sum(i)]\n \nprint(sum_2d)\n"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74493441",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11500064/"
] |
74,493,443
|
<p>The only users that should see the list of contacts are authenticated users.</p>
<p>Inside the <code>Contacts Controllers</code>, I've been testing different file paths to route the unauthenticated users to the login screen to no avail.</p>
<p>When routing to anything inside the Area folder, exactly how would you go about writing the file path?</p>
<p>I've tried:</p>
<p><code>Areas/Identity/Pages/Account/Manage/Login.cshtml</code></p>
<p><code>~/Areas/Identity/Pages/Account/Manage/Login.cshtml</code></p>
<p><code>~/Account/Login</code></p>
<pre><code>namespace ContactPro.Controllers
{
public class ContactsController : Controller
{
private readonly ApplicationDbContext _context;
public ContactsController(ApplicationDbContext context)
{
_context = context;
}
public async Task<IActionResult> Index()
{
if (User.Identity != null && User.Identity.IsAuthenticated)
{
return View(await _context.Contacts.ToListAsync());
}
else
{
return View("~/Account/Login");
}
}
}
}
</code></pre>
|
[
{
"answer_id": 74493469,
"author": "Talha Tayyab",
"author_id": 13086128,
"author_profile": "https://Stackoverflow.com/users/13086128",
"pm_score": 1,
"selected": false,
"text": "x=[[1, 2],[3, 4],[5, 6]]\n\n[sum(y) for y in x]\n\n#output\n[3, 7, 11]\n"
},
{
"answer_id": 74493548,
"author": "Fab",
"author_id": 18292832,
"author_profile": "https://Stackoverflow.com/users/18292832",
"pm_score": 0,
"selected": false,
"text": "x = [[1, 2], [3, 4], [5, 6]]\n\nsum_2d = []\n\nfor i in x:\n sum_2d += [sum(i)]\n \nprint(sum_2d)\n"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74493443",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11720959/"
] |
74,493,455
|
<p>I have a dataframe in python containing various dates.</p>
<pre><code>df = pd.DataFrame({"Date":["2020-01-27 welcome ! offer","Space ! offer 2020-02-27","new | 2020-03-27"],
"A_item":[2, 8, 0],
"B_item":[1, 7, 10],
"C_item":[9, 2, 9],
})
</code></pre>
<p>and i need to get this as a result</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Date</th>
<th>A_item</th>
<th>B_item</th>
<th>C_item</th>
<th>Extracted Date</th>
</tr>
</thead>
<tbody>
<tr>
<td>2020-01-27 welcome ! offer</td>
<td>2</td>
<td>1</td>
<td>9</td>
<td>27-01-2020</td>
</tr>
<tr>
<td>Space ! offer 2020-02-27</td>
<td>8</td>
<td>7</td>
<td>2</td>
<td>27-02-2020</td>
</tr>
<tr>
<td>Space ! offer new 2020-03-27</td>
<td>0</td>
<td>10</td>
<td>9</td>
<td>27-03-2020</td>
</tr>
</tbody>
</table>
</div>
<p>Does anybody know how to extract them</p>
|
[
{
"answer_id": 74493469,
"author": "Talha Tayyab",
"author_id": 13086128,
"author_profile": "https://Stackoverflow.com/users/13086128",
"pm_score": 1,
"selected": false,
"text": "x=[[1, 2],[3, 4],[5, 6]]\n\n[sum(y) for y in x]\n\n#output\n[3, 7, 11]\n"
},
{
"answer_id": 74493548,
"author": "Fab",
"author_id": 18292832,
"author_profile": "https://Stackoverflow.com/users/18292832",
"pm_score": 0,
"selected": false,
"text": "x = [[1, 2], [3, 4], [5, 6]]\n\nsum_2d = []\n\nfor i in x:\n sum_2d += [sum(i)]\n \nprint(sum_2d)\n"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74493455",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17149139/"
] |
74,493,459
|
<p>Let's say I have the following date as a string:</p>
<pre><code>2022-01-05
</code></pre>
<p>I'd like to convert this to the following format:</p>
<pre><code>Jan 5, 2022
</code></pre>
<p>I've tried using the following code:</p>
<pre><code>const shortDateFormat = new Intl.DateTimeFormat("en-US", {
dateStyle: "medium",
});
shortDateFormat.format(new Date("2022-01-05"));
</code></pre>
<p>But I'm getting the following result:</p>
<pre><code>Jan 4, 2022
</code></pre>
<p>Looks like the problem is a localization issue. I'm in NY so creating a new date creates the wrong datetime:</p>
<pre><code>new Date("2022-01-05")
# Tue Jan 04 2022 19:00:00 GMT-0500 (Eastern Standard Time)
</code></pre>
<p>How can I format the date without worrying about localization issues?
Note:</p>
<blockquote>
<p>These dates are in <code>UTC</code> and my frontend displays this fact.</p>
</blockquote>
|
[
{
"answer_id": 74493527,
"author": "Dream Bold",
"author_id": 12743692,
"author_profile": "https://Stackoverflow.com/users/12743692",
"pm_score": 1,
"selected": false,
"text": "const event = new Date(Date.UTC(2012, 11, 20, 3, 0, 0));\nconst options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' };\n\nconsole.log(event.toLocaleDateString('de-DE', options));\n// expected output (varies according to local timezone): Donnerstag, 20. Dezember 2012\n\nconsole.log(event.toLocaleDateString('ar-EG', options));\n// expected output (varies according to local timezone): الخميس، ٢٠ ديسمبر، ٢٠١٢\n\nconsole.log(event.toLocaleDateString(undefined, options));\n// expected output (varies according to local timezone and default locale): Thursday, December 20, 2012\n new Date().toLocaleDateString(\"en-US\", {timeZone: \"America/New_York\"})\n const options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric', timeZone: \"America/New_York\" };\n const timezone = Intl.DateTimeFormat().resolvedOptions().timeZone;\n//expected output: \"America/Los_Angeles\" (if you are in PST)\n var world_timezones =\n[\n 'Europe/Andorra',\n 'Asia/Dubai',\n 'Asia/Kabul',\n 'Europe/Tirane',\n 'Asia/Yerevan',\n 'Antarctica/Casey',\n 'Antarctica/Davis',\n 'Antarctica/DumontDUrville', \n 'Antarctica/Mawson',\n 'Antarctica/Palmer',\n 'Antarctica/Rothera',\n 'Antarctica/Syowa',\n 'Antarctica/Troll',\n 'Antarctica/Vostok',\n 'America/Argentina/Buenos_Aires',\n 'America/Argentina/Cordoba',\n 'America/Argentina/Salta',\n 'America/Argentina/Jujuy',\n 'America/Argentina/Tucuman',\n 'America/Argentina/Catamarca',\n 'America/Argentina/La_Rioja',\n 'America/Argentina/San_Juan',\n 'America/Argentina/Mendoza',\n 'America/Argentina/San_Luis',\n 'America/Argentina/Rio_Gallegos',\n 'America/Argentina/Ushuaia',\n 'Pacific/Pago_Pago',\n 'Europe/Vienna',\n 'Australia/Lord_Howe',\n 'Antarctica/Macquarie',\n 'Australia/Hobart',\n 'Australia/Currie',\n 'Australia/Melbourne',\n 'Australia/Sydney',\n 'Australia/Broken_Hill',\n 'Australia/Brisbane',\n 'Australia/Lindeman',\n 'Australia/Adelaide',\n 'Australia/Darwin',\n 'Australia/Perth',\n 'Australia/Eucla',\n 'Asia/Baku',\n 'America/Barbados',\n 'Asia/Dhaka',\n 'Europe/Brussels',\n 'Europe/Sofia',\n 'Atlantic/Bermuda',\n 'Asia/Brunei',\n 'America/La_Paz',\n 'America/Noronha',\n 'America/Belem',\n 'America/Fortaleza',\n 'America/Recife',\n 'America/Araguaina',\n 'America/Maceio',\n 'America/Bahia',\n 'America/Sao_Paulo',\n 'America/Campo_Grande',\n 'America/Cuiaba',\n 'America/Santarem',\n 'America/Porto_Velho',\n 'America/Boa_Vista',\n 'America/Manaus',\n 'America/Eirunepe',\n 'America/Rio_Branco',\n 'America/Nassau',\n 'Asia/Thimphu',\n 'Europe/Minsk',\n 'America/Belize',\n 'America/St_Johns',\n 'America/Halifax',\n 'America/Glace_Bay',\n 'America/Moncton',\n 'America/Goose_Bay',\n 'America/Blanc-Sablon',\n 'America/Toronto',\n 'America/Nipigon',\n 'America/Thunder_Bay',\n 'America/Iqaluit',\n 'America/Pangnirtung',\n 'America/Atikokan',\n 'America/Winnipeg',\n 'America/Rainy_River',\n 'America/Resolute',\n 'America/Rankin_Inlet',\n 'America/Regina',\n 'America/Swift_Current',\n 'America/Edmonton',\n 'America/Cambridge_Bay',\n 'America/Yellowknife',\n 'America/Inuvik',\n 'America/Creston',\n 'America/Dawson_Creek',\n 'America/Fort_Nelson',\n 'America/Vancouver',\n 'America/Whitehorse',\n 'America/Dawson',\n 'Indian/Cocos',\n 'Europe/Zurich',\n 'Africa/Abidjan',\n 'Pacific/Rarotonga',\n 'America/Santiago',\n 'America/Punta_Arenas',\n 'Pacific/Easter',\n 'Asia/Shanghai',\n 'Asia/Urumqi',\n 'America/Bogota',\n 'America/Costa_Rica',\n 'America/Havana',\n 'Atlantic/Cape_Verde',\n 'America/Curacao',\n 'Indian/Christmas',\n 'Asia/Nicosia',\n 'Asia/Famagusta',\n 'Europe/Prague',\n 'Europe/Berlin',\n 'Europe/Copenhagen',\n 'America/Santo_Domingo',\n 'Africa/Algiers',\n 'America/Guayaquil',\n 'Pacific/Galapagos',\n 'Europe/Tallinn',\n 'Africa/Cairo',\n 'Africa/El_Aaiun',\n 'Europe/Madrid',\n 'Africa/Ceuta',\n 'Atlantic/Canary',\n 'Europe/Helsinki',\n 'Pacific/Fiji',\n 'Atlantic/Stanley',\n 'Pacific/Chuuk',\n 'Pacific/Pohnpei',\n 'Pacific/Kosrae',\n 'Atlantic/Faroe',\n 'Europe/Paris',\n 'Europe/London',\n 'Asia/Tbilisi',\n 'America/Cayenne',\n 'Africa/Accra',\n 'Europe/Gibraltar',\n 'America/Godthab',\n 'America/Danmarkshavn',\n 'America/Scoresbysund',\n 'America/Thule',\n 'Europe/Athens',\n 'Atlantic/South_Georgia',\n 'America/Guatemala',\n 'Pacific/Guam',\n 'Africa/Bissau',\n 'America/Guyana',\n 'Asia/Hong_Kong',\n 'America/Tegucigalpa',\n 'America/Port-au-Prince',\n 'Europe/Budapest',\n 'Asia/Jakarta',\n 'Asia/Pontianak',\n 'Asia/Makassar',\n 'Asia/Jayapura',\n 'Europe/Dublin',\n 'Asia/Jerusalem',\n 'Asia/Kolkata',\n 'Indian/Chagos',\n 'Asia/Baghdad',\n 'Asia/Tehran',\n 'Atlantic/Reykjavik',\n 'Europe/Rome',\n 'America/Jamaica',\n 'Asia/Amman',\n 'Asia/Tokyo',\n 'Africa/Nairobi',\n 'Asia/Bishkek',\n 'Pacific/Tarawa',\n 'Pacific/Enderbury',\n 'Pacific/Kiritimati',\n 'Asia/Pyongyang',\n 'Asia/Seoul',\n 'Asia/Almaty',\n 'Asia/Qyzylorda',\n 'Asia/Qostanay', \n 'Asia/Aqtobe',\n 'Asia/Aqtau',\n 'Asia/Atyrau',\n 'Asia/Oral',\n 'Asia/Beirut',\n 'Asia/Colombo',\n 'Africa/Monrovia',\n 'Europe/Vilnius',\n 'Europe/Luxembourg',\n 'Europe/Riga',\n 'Africa/Tripoli',\n 'Africa/Casablanca',\n 'Europe/Monaco',\n 'Europe/Chisinau',\n 'Pacific/Majuro',\n 'Pacific/Kwajalein',\n 'Asia/Yangon',\n 'Asia/Ulaanbaatar',\n 'Asia/Hovd',\n 'Asia/Choibalsan',\n 'Asia/Macau',\n 'America/Martinique',\n 'Europe/Malta',\n 'Indian/Mauritius',\n 'Indian/Maldives',\n 'America/Mexico_City',\n 'America/Cancun',\n 'America/Merida',\n 'America/Monterrey',\n 'America/Matamoros',\n 'America/Mazatlan',\n 'America/Chihuahua',\n 'America/Ojinaga',\n 'America/Hermosillo',\n 'America/Tijuana',\n 'America/Bahia_Banderas',\n 'Asia/Kuala_Lumpur',\n 'Asia/Kuching',\n 'Africa/Maputo',\n 'Africa/Windhoek',\n 'Pacific/Noumea',\n 'Pacific/Norfolk',\n 'Africa/Lagos',\n 'America/Managua',\n 'Europe/Amsterdam',\n 'Europe/Oslo',\n 'Asia/Kathmandu',\n 'Pacific/Nauru',\n 'Pacific/Niue',\n 'Pacific/Auckland',\n 'Pacific/Chatham',\n 'America/Panama',\n 'America/Lima',\n 'Pacific/Tahiti',\n 'Pacific/Marquesas',\n 'Pacific/Gambier',\n 'Pacific/Port_Moresby',\n 'Pacific/Bougainville',\n 'Asia/Manila',\n 'Asia/Karachi',\n 'Europe/Warsaw',\n 'America/Miquelon',\n 'Pacific/Pitcairn',\n 'America/Puerto_Rico',\n 'Asia/Gaza',\n 'Asia/Hebron',\n 'Europe/Lisbon',\n 'Atlantic/Madeira',\n 'Atlantic/Azores',\n 'Pacific/Palau',\n 'America/Asuncion',\n 'Asia/Qatar',\n 'Indian/Reunion',\n 'Europe/Bucharest',\n 'Europe/Belgrade',\n 'Europe/Kaliningrad',\n 'Europe/Moscow',\n 'Europe/Simferopol',\n 'Europe/Kirov',\n 'Europe/Astrakhan',\n 'Europe/Volgograd',\n 'Europe/Saratov',\n 'Europe/Ulyanovsk',\n 'Europe/Samara',\n 'Asia/Yekaterinburg',\n 'Asia/Omsk',\n 'Asia/Novosibirsk',\n 'Asia/Barnaul',\n 'Asia/Tomsk',\n 'Asia/Novokuznetsk',\n 'Asia/Krasnoyarsk',\n 'Asia/Irkutsk',\n 'Asia/Chita',\n 'Asia/Yakutsk',\n 'Asia/Khandyga',\n 'Asia/Vladivostok',\n 'Asia/Ust-Nera',\n 'Asia/Magadan',\n 'Asia/Sakhalin',\n 'Asia/Srednekolymsk',\n 'Asia/Kamchatka',\n 'Asia/Anadyr',\n 'Asia/Riyadh',\n 'Pacific/Guadalcanal',\n 'Indian/Mahe',\n 'Africa/Khartoum',\n 'Europe/Stockholm',\n 'Asia/Singapore',\n 'America/Paramaribo',\n 'Africa/Juba',\n 'Africa/Sao_Tome',\n 'America/El_Salvador',\n 'Asia/Damascus',\n 'America/Grand_Turk',\n 'Africa/Ndjamena',\n 'Indian/Kerguelen',\n 'Asia/Bangkok',\n 'Asia/Dushanbe',\n 'Pacific/Fakaofo',\n 'Asia/Dili',\n 'Asia/Ashgabat',\n 'Africa/Tunis',\n 'Pacific/Tongatapu',\n 'Europe/Istanbul',\n 'America/Port_of_Spain',\n 'Pacific/Funafuti',\n 'Asia/Taipei',\n 'Europe/Kiev',\n 'Europe/Uzhgorod',\n 'Europe/Zaporozhye',\n 'Pacific/Wake',\n 'America/New_York',\n 'America/Detroit',\n 'America/Kentucky/Louisville',\n 'America/Kentucky/Monticello',\n 'America/Indiana/Indianapolis',\n 'America/Indiana/Vincennes',\n 'America/Indiana/Winamac',\n 'America/Indiana/Marengo',\n 'America/Indiana/Petersburg',\n 'America/Indiana/Vevay',\n 'America/Chicago',\n 'America/Indiana/Tell_City',\n 'America/Indiana/Knox',\n 'America/Menominee',\n 'America/North_Dakota/Center',\n 'America/North_Dakota/New_Salem',\n 'America/North_Dakota/Beulah',\n 'America/Denver',\n 'America/Boise',\n 'America/Phoenix',\n 'America/Los_Angeles',\n 'America/Anchorage',\n 'America/Juneau',\n 'America/Sitka',\n 'America/Metlakatla',\n 'America/Yakutat',\n 'America/Nome',\n 'America/Adak',\n 'Pacific/Honolulu',\n 'America/Montevideo',\n 'Asia/Samarkand',\n 'Asia/Tashkent',\n 'America/Caracas',\n 'Asia/Ho_Chi_Minh',\n 'Pacific/Efate',\n 'Pacific/Wallis',\n 'Pacific/Apia',\n 'Africa/Johannesburg'\n];\n"
},
{
"answer_id": 74493583,
"author": "KooiInc",
"author_id": 58186,
"author_profile": "https://Stackoverflow.com/users/58186",
"pm_score": 2,
"selected": true,
"text": "DateTimeFormat Etc/UTC UTC Etc/Universal Etc/GMT[+0] Etc/Zulu const shortDateFormat = new Intl.DateTimeFormat(\"en-US\", {\n dateStyle: \"medium\",\n timeZone: \"UCT\",\n});\nconst dateStr = `2022-01-05`;\nconsole.log(shortDateFormat\n .format(new Date(dateStr)));"
},
{
"answer_id": 74494212,
"author": "Kazi Tajnur Islam",
"author_id": 11690507,
"author_profile": "https://Stackoverflow.com/users/11690507",
"pm_score": 0,
"selected": false,
"text": "let dateString = \"2022-01-05\";\nlet dateNums = dateString.split('-').map(str => parseInt(str));\n\nconst shortDateFormat = new Intl.DateTimeFormat(\"en-US\", {\n dateStyle: \"medium\",\n});\nshortDateFormat.format(new Date(dateNums[0], dateNums[1] - 1, dateNums[2], 0, 0, 0));\n// 'Jan 5, 2022'\n dateNums[1] - 1"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74493459",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6611672/"
] |
74,493,493
|
<p>For a task I need use <code>if atoi(INPUT) == 0</code> to check that a users input is a valid integer and not 0. The problem is when I enter any string that starts with an integer, it is automatically accepted, even if there are non-integer characters after the integer, for example "1aaaabcc" is accepted.</p>
<p>I understand that atoi() is in the example I just stated, would take the 1 and ignore it, but theortically this should be wrong input from the user since it is not a valid integer. Would there be something to add to my code (without adding any libraries) or change something with atoi to fix this?</p>
<p>Please let me know if you need sample code in case its not clear.</p>
|
[
{
"answer_id": 74493536,
"author": "Vlad from Moscow",
"author_id": 2877241,
"author_profile": "https://Stackoverflow.com/users/2877241",
"pm_score": 2,
"selected": false,
"text": "atoi atoi: (int)strtol(nptr, (char **)NULL, 10)\n strtol NULL #include <stdio.h>\n#include <stdlib.h>\n\nint main( void )\n{\n char *endptr;\n\n int n = ( int )strtol( \"A\", &endptr, 10 );\n\n printf( \"n = %d, *endptr = %d\\n\", n, *endptr );\n\n n = ( int )strtol( \"10A\", &endptr, 10 );\n\n printf( \"n = %d, *endptr = %d\\n\", n, *endptr );\n\n n = ( int )strtol( \"10\", &endptr, 10 );\n\n printf( \"n = %d, *endptr = %d\\n\", n, *endptr );\n}\n n = 0, *endptr = 65\nn = 10, *endptr = 65\nn = 10, *endptr = 0\n strtol endptr '\\0' 'A' 65 \"10 \" strtol"
},
{
"answer_id": 74493962,
"author": "chux - Reinstate Monica",
"author_id": 2410359,
"author_profile": "https://Stackoverflow.com/users/2410359",
"pm_score": 0,
"selected": false,
"text": "aoti() \"1aaaabcc\" strtol() strtol() int \"12345678901234567890\" \"00000000000000000001\" strtol()/atoi() \"1234\\n\" \"asd\" \" \" \"\" // Return true on success \nbool convert_string_to_int(int *dest, const char *s) {\n errno = 0;\n char *endptr; // Gets updated to point to the end of the conversion.\n long lvlaue = strtol(s, &endptr, 0);\n if (s == endptr) {\n *dest = 0;\n return false; // No conversion\n }\n if (errno == ERANGE || lvalue < INT_MIN || lvalue > INT_MAX) {\n errno = ERANGE;\n *dest = lvalue < 0 ? INT_MIN : INT_MAX; \n return false; // Out of range.\n }\n *dest = (int) lvalue;\n if (errno) {\n return false; // Implementation specific errors like s == NULL\n }\n while (isspace(*((unsigned char *)endptr))) {\n endptr++;\n }\n if (*endptr) {\n return false; // Junk at the end.\n }\n return true;\n}\n"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74493493",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20541883/"
] |
74,493,503
|
<p>Let <code>a</code> be some (not necessarily one-dimensional) NumPy array with <code>n * m</code> elements along its last axis. I wish to "split" this array along its last axis so that I take every <code>n</code>'th element starting from <code>0</code> up until <code>n</code>.</p>
<p>To be explicit let <code>a</code> have shape <code>(k, n * m)</code> then I wish to construct the array of shape <code>(n, k, m)</code></p>
<pre><code>np.array([a[:, i::n] for i in range(n)])
</code></pre>
<p>my problem is that though this indeed return the array that I seek, I still feel that there might be a more efficient and neat NumPy routine for this.</p>
<p>Cheers!</p>
|
[
{
"answer_id": 74499763,
"author": "John Zwinck",
"author_id": 4323,
"author_profile": "https://Stackoverflow.com/users/4323",
"pm_score": 0,
"selected": false,
"text": "indexes = np.arange(0, a.size*n, n) + np.repeat(np.arange(n), a.size/n)\nnp.take(a, indexes, mode='wrap').reshape(n, a.shape[0], -1)\n"
},
{
"answer_id": 74505382,
"author": "Jérôme Richard",
"author_id": 12939557,
"author_profile": "https://Stackoverflow.com/users/12939557",
"pm_score": 1,
"selected": false,
"text": "import numba as nb\n\n# The first call is slower due to the build.\n# Please consider specifying the signature of the function (ie. input types)\n# to precompile the function ahead of time.\n@nb.njit # Use nb.njit(parallel=True) for the parallel version\ndef compute(arr, n):\n k, m = arr.shape[0], arr.shape[1] // n\n assert arr.shape[1] == n * m\n\n out = np.empty((n, k, m), dtype=arr.dtype)\n\n # Use nb.prange for the parallel version\n for i2 in range(k):\n for i1 in range(n):\n outView = out[i1, i2]\n inView = a[i2]\n cur = i1\n for i3 in range(m):\n outView[i3] = inView[cur]\n cur += n\n\n return out\n k=37 n=42 m=53 a.dtype=np.int32 John Zwinck's solution: 986.1 µs\nInitial implementation: 91.7 µs\nSequential Numba: 62.9 µs\nParallel Numba: 14.7 µs\nOptimal lower-bound: ~7.0 µs\n"
},
{
"answer_id": 74593637,
"author": "isCzech",
"author_id": 20188124,
"author_profile": "https://Stackoverflow.com/users/20188124",
"pm_score": 0,
"selected": false,
"text": "a.reshape(k, m, n).swapaxes(1, 2).swapaxes(0, 1)\n import numpy as np\nk=5; n=3; m=4\na = np.arange(k*n*m).reshape(k, n*m)\na.reshape(k, m, n).swapaxes(1, 2).swapaxes(0, 1)\n\"\"\"\narray([[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11],\n [12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23],\n [24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35],\n [36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47],\n [48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59]])\n\nis transformed into:\n\narray([[[ 0, 3, 6, 9],\n [12, 15, 18, 21],\n [24, 27, 30, 33],\n [36, 39, 42, 45],\n [48, 51, 54, 57]],\n\n [[ 1, 4, 7, 10],\n [13, 16, 19, 22],\n [25, 28, 31, 34],\n [37, 40, 43, 46],\n [49, 52, 55, 58]],\n\n [[ 2, 5, 8, 11],\n [14, 17, 20, 23],\n [26, 29, 32, 35],\n [38, 41, 44, 47],\n [50, 53, 56, 59]]])\n\"\"\"\n from time import time\nk=37; n=42; m=53\na = np.arange(k*n*m).reshape(k, n*m)\n\nstart = time()\nfor _ in range(1_000_000):\n res = a.reshape(k, m, n).swapaxes(1, 2).swapaxes(0,1)\ntime() - start\n\n# 0.95 s per 1 mil repetitions\n"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74493503",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15461766/"
] |
74,493,515
|
<p><code>Book.No_Pages() missing 2 required positional arguments: 'Words' and 'Font_size'</code>
the error comes in line 14
The code is:-</p>
<pre><code>class Book():
def __init__ (b1,Font_size=12,Words=300):
b1.Words = Words
pass
b1.Font_size = Font_size
pass
def No_Pages(b1,Words,Font_size):
return b1.Words/b1.Font_size
cyn_Book = Book(300,12)
print(cyn_Book.Font_size)
print(cyn_Book.Words)
print(cyn_Book.No_Pages())
</code></pre>
<p>I actually tried this by another approach like adding pass after the <code>Font_size</code> and <code>Words</code> and thought that it could return <code>words 300</code>,<code>Font_size 12</code> and <code>pages</code> being <code>15</code></p>
|
[
{
"answer_id": 74499763,
"author": "John Zwinck",
"author_id": 4323,
"author_profile": "https://Stackoverflow.com/users/4323",
"pm_score": 0,
"selected": false,
"text": "indexes = np.arange(0, a.size*n, n) + np.repeat(np.arange(n), a.size/n)\nnp.take(a, indexes, mode='wrap').reshape(n, a.shape[0], -1)\n"
},
{
"answer_id": 74505382,
"author": "Jérôme Richard",
"author_id": 12939557,
"author_profile": "https://Stackoverflow.com/users/12939557",
"pm_score": 1,
"selected": false,
"text": "import numba as nb\n\n# The first call is slower due to the build.\n# Please consider specifying the signature of the function (ie. input types)\n# to precompile the function ahead of time.\n@nb.njit # Use nb.njit(parallel=True) for the parallel version\ndef compute(arr, n):\n k, m = arr.shape[0], arr.shape[1] // n\n assert arr.shape[1] == n * m\n\n out = np.empty((n, k, m), dtype=arr.dtype)\n\n # Use nb.prange for the parallel version\n for i2 in range(k):\n for i1 in range(n):\n outView = out[i1, i2]\n inView = a[i2]\n cur = i1\n for i3 in range(m):\n outView[i3] = inView[cur]\n cur += n\n\n return out\n k=37 n=42 m=53 a.dtype=np.int32 John Zwinck's solution: 986.1 µs\nInitial implementation: 91.7 µs\nSequential Numba: 62.9 µs\nParallel Numba: 14.7 µs\nOptimal lower-bound: ~7.0 µs\n"
},
{
"answer_id": 74593637,
"author": "isCzech",
"author_id": 20188124,
"author_profile": "https://Stackoverflow.com/users/20188124",
"pm_score": 0,
"selected": false,
"text": "a.reshape(k, m, n).swapaxes(1, 2).swapaxes(0, 1)\n import numpy as np\nk=5; n=3; m=4\na = np.arange(k*n*m).reshape(k, n*m)\na.reshape(k, m, n).swapaxes(1, 2).swapaxes(0, 1)\n\"\"\"\narray([[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11],\n [12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23],\n [24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35],\n [36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47],\n [48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59]])\n\nis transformed into:\n\narray([[[ 0, 3, 6, 9],\n [12, 15, 18, 21],\n [24, 27, 30, 33],\n [36, 39, 42, 45],\n [48, 51, 54, 57]],\n\n [[ 1, 4, 7, 10],\n [13, 16, 19, 22],\n [25, 28, 31, 34],\n [37, 40, 43, 46],\n [49, 52, 55, 58]],\n\n [[ 2, 5, 8, 11],\n [14, 17, 20, 23],\n [26, 29, 32, 35],\n [38, 41, 44, 47],\n [50, 53, 56, 59]]])\n\"\"\"\n from time import time\nk=37; n=42; m=53\na = np.arange(k*n*m).reshape(k, n*m)\n\nstart = time()\nfor _ in range(1_000_000):\n res = a.reshape(k, m, n).swapaxes(1, 2).swapaxes(0,1)\ntime() - start\n\n# 0.95 s per 1 mil repetitions\n"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74493515",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20541864/"
] |
74,493,524
|
<p>I have a set of variables (A1, A2, B1, B2, C1, C3 ...) that I need to calculate the difference for to eventually create a set of Bland-Altman plots after extracting the mean difference and sd of the difference from a t-test using OMS.</p>
<p>As a first step I have it working for a single pair of variables (e.g. A1 and A2) and am now trying to create a macro that will loop through the first few pairs as a test:</p>
<pre><code>```
DEFINE BlandAlt (scan1vars=!CMDEND / scan2vars=!CMDEND)
COMPUTE diff = scan1vars - scan2vars.
EXECUTE.
T-TEST
/TESTVAL=0
/MISSING=ANALYSIS
/VARIABLES=diff
/CRITERIA=CI(.95).
!ENDDEFINE.
BlandAlt
scan1vars = JumpJumpHeightcm.1 JumpJumpHeightt_score.1 JumpMaxChangeinAccelerationms3.1 JumpMaxChangeinAccelerationt_score.1 JumpMaxAccelerationms2.1 JumpMaxAccelerationt_score.1
scan2vars= JumpJumpHeightcm.2 JumpJumpHeightt_score.2 JumpMaxChangeinAccelerationms3.2 JumpMaxChangeinAccelerationt_score.2 JumpMaxAccelerationms2.2 JumpMaxAccelerationt_score.2.
```
</code></pre>
<p>When I run the macro I get an error on the first variable:</p>
<blockquote>
<p>Error # 4381 in column 35. Text: JumpJumpHeightt_score.1 The
expression ends unexpectedly. Execution of this command stops.</p>
</blockquote>
<p>and a warning when it tries to run the t-test:</p>
<blockquote>
<p>Text: diff Command: T-TEST An undefined variable name, or a scratch or
system variable was specified in a variable list >which accepts only
standard variables. Check spelling and verify the existence of this
variable. Execution of this command stops.</p>
</blockquote>
<p>Is anyone able to help get this part working? I'm hoping it should then be easy to include the other commands within the macro.</p>
|
[
{
"answer_id": 74499763,
"author": "John Zwinck",
"author_id": 4323,
"author_profile": "https://Stackoverflow.com/users/4323",
"pm_score": 0,
"selected": false,
"text": "indexes = np.arange(0, a.size*n, n) + np.repeat(np.arange(n), a.size/n)\nnp.take(a, indexes, mode='wrap').reshape(n, a.shape[0], -1)\n"
},
{
"answer_id": 74505382,
"author": "Jérôme Richard",
"author_id": 12939557,
"author_profile": "https://Stackoverflow.com/users/12939557",
"pm_score": 1,
"selected": false,
"text": "import numba as nb\n\n# The first call is slower due to the build.\n# Please consider specifying the signature of the function (ie. input types)\n# to precompile the function ahead of time.\n@nb.njit # Use nb.njit(parallel=True) for the parallel version\ndef compute(arr, n):\n k, m = arr.shape[0], arr.shape[1] // n\n assert arr.shape[1] == n * m\n\n out = np.empty((n, k, m), dtype=arr.dtype)\n\n # Use nb.prange for the parallel version\n for i2 in range(k):\n for i1 in range(n):\n outView = out[i1, i2]\n inView = a[i2]\n cur = i1\n for i3 in range(m):\n outView[i3] = inView[cur]\n cur += n\n\n return out\n k=37 n=42 m=53 a.dtype=np.int32 John Zwinck's solution: 986.1 µs\nInitial implementation: 91.7 µs\nSequential Numba: 62.9 µs\nParallel Numba: 14.7 µs\nOptimal lower-bound: ~7.0 µs\n"
},
{
"answer_id": 74593637,
"author": "isCzech",
"author_id": 20188124,
"author_profile": "https://Stackoverflow.com/users/20188124",
"pm_score": 0,
"selected": false,
"text": "a.reshape(k, m, n).swapaxes(1, 2).swapaxes(0, 1)\n import numpy as np\nk=5; n=3; m=4\na = np.arange(k*n*m).reshape(k, n*m)\na.reshape(k, m, n).swapaxes(1, 2).swapaxes(0, 1)\n\"\"\"\narray([[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11],\n [12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23],\n [24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35],\n [36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47],\n [48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59]])\n\nis transformed into:\n\narray([[[ 0, 3, 6, 9],\n [12, 15, 18, 21],\n [24, 27, 30, 33],\n [36, 39, 42, 45],\n [48, 51, 54, 57]],\n\n [[ 1, 4, 7, 10],\n [13, 16, 19, 22],\n [25, 28, 31, 34],\n [37, 40, 43, 46],\n [49, 52, 55, 58]],\n\n [[ 2, 5, 8, 11],\n [14, 17, 20, 23],\n [26, 29, 32, 35],\n [38, 41, 44, 47],\n [50, 53, 56, 59]]])\n\"\"\"\n from time import time\nk=37; n=42; m=53\na = np.arange(k*n*m).reshape(k, n*m)\n\nstart = time()\nfor _ in range(1_000_000):\n res = a.reshape(k, m, n).swapaxes(1, 2).swapaxes(0,1)\ntime() - start\n\n# 0.95 s per 1 mil repetitions\n"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74493524",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11300704/"
] |
74,493,537
|
<p>I have a method that takes in a function parameter with a generic like this:</p>
<pre><code>public async Task<T> MeasureAsync<T>(Func<Task<T>> sendFunc) {
// implementation
}
</code></pre>
<p>I'm wondering how I can mock the MeasureAsync function. I tried doing something like this:</p>
<pre><code>Mock.Get(_outgoingHttpOperationMeasurer)
.Setup(x => x.MeasureAsync<T>(It.IsAny<Func<Task<T>>>()))
.ReturnsAsync(T);
</code></pre>
<p>I get a compile error that <code>T</code> is not defined and I'm not sure exactly how to define it</p>
|
[
{
"answer_id": 74494482,
"author": "Guru Stron",
"author_id": 2501279,
"author_profile": "https://Stackoverflow.com/users/2501279",
"pm_score": 2,
"selected": true,
"text": "T public interface IMyClass\n{\n Task<T> MeasureAsync<T>(Func<Task<T>> sendFunc);\n}\n\nvar mock = new Mock<IMyClass>();\nvar measureAsync = mock.Object.MeasureAsync(() => Task.FromResult(1));\nvar isFalse = measureAsync is null; // false\n It.IsAnyType mock.Setup(c => c.MeasureAsync(It.IsAny<Func<Task<It.IsAnyType>>>()))\n .Returns(new InvocationFunc(invocation =>\n {\n var arg = (Func<Task>)invocation.Arguments[0];\n return arg.Invoke();\n }));;\n\n\nvar measureAsync = mock.Object.MeasureAsync(() => Task.FromResult(42));\n\nvar result = await measureAsync; // 42\n"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74493537",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1110590/"
] |
74,493,546
|
<p>I have been researching this for close to 4 hours but still, I can't connect my Invision Community 4 forum to my mysql ran on localhost with xampp.</p>
<p>I can connect from the shell, but I can't connect to it from elsewhere.</p>
<p><code>Access denied for user 'root'@'localhost' </code></p>
|
[
{
"answer_id": 74494482,
"author": "Guru Stron",
"author_id": 2501279,
"author_profile": "https://Stackoverflow.com/users/2501279",
"pm_score": 2,
"selected": true,
"text": "T public interface IMyClass\n{\n Task<T> MeasureAsync<T>(Func<Task<T>> sendFunc);\n}\n\nvar mock = new Mock<IMyClass>();\nvar measureAsync = mock.Object.MeasureAsync(() => Task.FromResult(1));\nvar isFalse = measureAsync is null; // false\n It.IsAnyType mock.Setup(c => c.MeasureAsync(It.IsAny<Func<Task<It.IsAnyType>>>()))\n .Returns(new InvocationFunc(invocation =>\n {\n var arg = (Func<Task>)invocation.Arguments[0];\n return arg.Invoke();\n }));;\n\n\nvar measureAsync = mock.Object.MeasureAsync(() => Task.FromResult(42));\n\nvar result = await measureAsync; // 42\n"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74493546",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17864494/"
] |
74,493,571
|
<p>I have a simple async setup which includes two coroutines: light_job and heavy_job. light_job halts in the middle and heavy_job starts. I want heavy_job to yield the control in the middle and allow light_job to finish but asyncio.sleep(0) is not working as I expect.</p>
<p>this is the setup:</p>
<pre><code>import asyncio
import time
loop = asyncio.get_event_loop()
async def light_job():
print("hello ")
print(time.time())
await asyncio.sleep(1)
print(time.time())
print("world!")
async def heavy_job():
print("heavy start")
time.sleep(3)
print("heavy halt started")
await asyncio.sleep(0)
print("heavy halt ended")
time.sleep(3)
print("heavy done")
loop.run_until_complete(asyncio.gather(
light_job(),
heavy_job()
))
</code></pre>
<p>if I run this code, the light_job will not continue until after heavy_job is done. this is the outpu:</p>
<pre><code>hello
1668793123.159075
haevy start
heavy halt started
heavy halt ended
heavy done
1668793129.1706061
world!
</code></pre>
<p>but if I change asyncio.sleep(0) to asyncio.sleep(0.0001), the code will work as expected:</p>
<pre><code>hello
1668793379.599066
heavy start
heavy halt started
1668793382.605899
world!
heavy halt ended
heavy done
</code></pre>
<p>based on documentations and <a href="https://github.com/python/asyncio/issues/284" rel="nofollow noreferrer">related threads</a>, I expect asyncio.sleep(0) to work exactly as asyncio.sleep(0.0001). what is off here?</p>
|
[
{
"answer_id": 74498442,
"author": "Daniel T",
"author_id": 10477326,
"author_profile": "https://Stackoverflow.com/users/10477326",
"pm_score": 2,
"selected": false,
"text": "asyncio.sleep(0) import asyncio\nimport time\n\n\nasync def light_job():\n print(\"hello \")\n print(time.time())\n await asyncio.sleep(1)\n print(time.time())\n print(\"world!\")\n\n\nasync def heavy_job():\n print(\"heavy start\")\n time.sleep(3)\n print(\"heavy halt started\")\n for _ in range(3):\n await asyncio.sleep(0)\n print(\"heavy halt ended\")\n time.sleep(3)\n print(\"heavy done\")\n\n\nasync def test():\n await asyncio.gather(\n light_job(),\n heavy_job()\n )\n\nasyncio.run(test())\n hello \n1668844526.157173\nheavy start\nheavy halt started\n1668844529.1575627\nworld!\nheavy halt ended\nheavy done\n asyncio.sleep asyncio.sleep(1) light_job light_job asyncio import asyncio\nimport time\n\n\nasync def light_job():\n print(\"hello \")\n print(time.time())\n await asyncio.sleep(1)\n print(time.time())\n print(\"world!\")\n\n\nasync def heavy_job():\n print(\"heavy start\")\n time.sleep(3)\n print(\"heavy halt started\")\n # Sleep to yield to the event loop. light_job isn't detected as ready so this iteration of the loop will finish\n await asyncio.sleep(0)\n\n print(\"after 1 sleep\")\n # We are still in front of the event loop. Yield so that the 1 second timer in light_job runs.\n # The timer will realize it itself has expired, then put light_job back onto the queue.\n await asyncio.sleep(0)\n\n # Again the current Python implementation puts us in front. Yield so that the light_job runs\n print(\"after 2 sleeps\")\n await asyncio.sleep(0)\n\n print(\"heavy halt ended\")\n time.sleep(3)\n print(\"heavy done\")\n\n\nasync def test():\n await asyncio.gather(\n light_job(),\n heavy_job()\n )\n\nasyncio.run(test())\n loop start\n<Task pending name='Task-1' coro=<test() running at /home/home/PycharmProjects/sandbox/notsync.py:34> cb=[_run_until_complete_cb() at /usr/lib/python3.11/asyncio/base_events.py:180]>\nloop end\nloop start\n<Task pending name='Task-2' coro=<light_job() running at /home/home/PycharmProjects/sandbox/notsync.py:5> cb=[gather.<locals>._done_callback() at /usr/lib/python3.11/asyncio/tasks.py:759]>\nhello \n1668844827.5052986\n<Task pending name='Task-3' coro=<heavy_job() running at /home/home/PycharmProjects/sandbox/notsync.py:13> cb=[gather.<locals>._done_callback() at /usr/lib/python3.11/asyncio/tasks.py:759]>\nheavy start\nheavy halt started\nloop end\nloop start\n<Task pending name='Task-3' coro=<heavy_job() running at /home/home/PycharmProjects/sandbox/notsync.py:18> cb=[gather.<locals>._done_callback() at /usr/lib/python3.11/asyncio/tasks.py:759]>\nafter 1 sleep\n<TimerHandle when=37442.097934711 _set_result_unless_cancelled(<Future pendi...ask_wakeup()]>, None) at /usr/lib/python3.11/asyncio/futures.py:317>\nloop end\nloop start\n<Task pending name='Task-3' coro=<heavy_job() running at /home/home/PycharmProjects/sandbox/notsync.py:23> cb=[gather.<locals>._done_callback() at /usr/lib/python3.11/asyncio/tasks.py:759]>\nafter 2 sleeps\n<Task pending name='Task-2' coro=<light_job() running at /home/home/PycharmProjects/sandbox/notsync.py:8> wait_for=<Future finished result=None> cb=[gather.<locals>._done_callback() at /usr/lib/python3.11/asyncio/tasks.py:759]>\n1668844830.9250844\nworld!\nloop end\nloop start\n<Task pending name='Task-3' coro=<heavy_job() running at /home/home/PycharmProjects/sandbox/notsync.py:27> cb=[gather.<locals>._done_callback() at /usr/lib/python3.11/asyncio/tasks.py:759]>\nheavy halt ended\nheavy done\n<Handle gather.<locals>._done_callback(<Task finishe...> result=None>) at /usr/lib/python3.11/asyncio/tasks.py:759>\nloop end\nloop start\n<Handle gather.<locals>._done_callback(<Task finishe...> result=None>) at /usr/lib/python3.11/asyncio/tasks.py:759>\nloop end\nloop start\n<Task pending name='Task-1' coro=<test() running at /home/home/PycharmProjects/sandbox/notsync.py:35> wait_for=<_GatheringFuture finished result=[None, None]> cb=[_run_until_complete_cb() at /usr/lib/python3.11/asyncio/base_events.py:180]>\nloop end\nloop start\n<Handle _run_until_complete_cb(<Task finishe...> result=None>) at /usr/lib/python3.11/asyncio/base_events.py:180>\nloop end\nloop start\n<Task pending name='Task-4' coro=<BaseEventLoop.shutdown_asyncgens() running at /usr/lib/python3.11/asyncio/base_events.py:539> cb=[_run_until_complete_cb() at /usr/lib/python3.11/asyncio/base_events.py:180]>\nloop end\nloop start\n<Handle _run_until_complete_cb(<Task finishe...> result=None>) at /usr/lib/python3.11/asyncio/base_events.py:180>\nloop end\nloop start\n<Task pending name='Task-5' coro=<BaseEventLoop.shutdown_default_executor() running at /usr/lib/python3.11/asyncio/base_events.py:564> cb=[_run_until_complete_cb() at /usr/lib/python3.11/asyncio/base_events.py:180]>\nloop end\nloop start\n<Handle _run_until_complete_cb(<Task finishe...> result=None>) at /usr/lib/python3.11/asyncio/base_events.py:180>\nloop end\n"
},
{
"answer_id": 74505785,
"author": "Paul Cornelius",
"author_id": 2442613,
"author_profile": "https://Stackoverflow.com/users/2442613",
"pm_score": 3,
"selected": true,
"text": "asyncio.sleep() asyncio.Event import asyncio\nimport time\n\nevent = asyncio.Event()\n\nasync def light_job():\n print(\"hello \")\n print(time.time())\n await asyncio.sleep(1)\n print(time.time())\n print(\"world!\")\n event.set()\n\n\nasync def heavy_job():\n print(\"heavy start\")\n time.sleep(3)\n print(\"heavy halt started\")\n # await asyncio.sleep(0)\n await event.wait()\n print(\"heavy halt ended\")\n time.sleep(3)\n print(\"heavy done\")\n \nasync def main():\n await asyncio.gather(light_job(), heavy_job())\n\nasyncio.run(main())\n import asyncio\nimport time\n\nasync def light_job():\n print(\"hello \")\n print(time.time())\n await asyncio.sleep(1)\n print(time.time())\n print(\"world!\")\n\nasync def heavy_job():\n light = asyncio.create_task(light_job())\n print(\"heavy start\")\n time.sleep(3)\n print(\"heavy halt started\")\n # await asyncio.sleep(0)\n await light\n print(\"heavy halt ended\")\n time.sleep(3)\n print(\"heavy done\")\n \nasync def main():\n await heavy_job()\n\nasyncio.run(main())\n _ready run ntodo = len(self._ready)\n for i in range(ntodo):\n handle = self._ready.popleft()\n if handle._cancelled:\n continue\n else:\n handle._run()\n await asyncio.sleep(0) loop.call_later asyncio.sleep @types.coroutine\ndef __sleep0():\n \"\"\"Skip one event loop run cycle.\n\n This is a private helper for 'asyncio.sleep()', used\n when the 'delay' is set to 0. It uses a bare 'yield'\n expression (which Task.__step knows how to handle)\n instead of creating a Future object.\n \"\"\"\n yield\n\n\nasync def sleep(delay, result=None):\n \"\"\"Coroutine that completes after a given time (in seconds).\"\"\"\n if delay <= 0:\n await __sleep0()\n return result\n\n loop = events.get_running_loop()\n future = loop.create_future()\n h = loop.call_later(delay,\n futures._set_result_unless_cancelled,\n future, result)\n try:\n return await future\n finally:\n h.cancel()\n test await asyncio.sleep(0) await asyncio.sleep(0.0001)"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74493571",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5332953/"
] |
74,493,584
|
<p>For example I have this dataframe :</p>
<pre><code> count
A 20
B 20
C 15
D 10
E 10
F 8
G 7
H 5
I 5
</code></pre>
<p>And if I want to make a group based on biggest 75%, 15%, 10%. I expect this :</p>
<pre><code> count Class
A 20 Top75
B 20 Top75
C 15 Top75
D 10 Top75
E 10 Top75
F 8 Top15
G 7 Top15
H 5 Top10
I 5 Top10
</code></pre>
<p>it has been anwered using <code>np.cut</code> with target 75%,15%,10%. It categorizes correctly but it removes the 'count' column. Using <code>np.qcut</code> it divides differently.
So, I want to use np.cut but without removing count value .
*Note the count could be any numbers, and I want to cut based on the percentage, cut of first 75%, 15% and the last 10%.</p>
|
[
{
"answer_id": 74493650,
"author": "crashMOGWAI",
"author_id": 5373105,
"author_profile": "https://Stackoverflow.com/users/5373105",
"pm_score": 1,
"selected": false,
"text": "df = pd.DataFrame(dict(count=[20,20,15,10,8,5]))\ndf['class'] = pd.cut(df['count'], [0, 5, 15, 20], labels=['Top10', 'Top15', 'Top75'])\n\n| | count | class |\n|---:|--------:|:--------|\n| 0 | 20 | Top75 |\n| 1 | 20 | Top75 |\n| 2 | 15 | Top15 |\n| 3 | 10 | Top15 |\n| 4 | 8 | Top15 |\n| 5 | 5 | Top10 |\n"
},
{
"answer_id": 74493667,
"author": "mozway",
"author_id": 16343464,
"author_profile": "https://Stackoverflow.com/users/16343464",
"pm_score": 1,
"selected": true,
"text": "bins = [10, 15, 75]\ndf['Class'] = pd.cut(df.loc[::-1, 'count'].cumsum(),\n np.cumsum([0]+bins),\n labels=[f'Top{n}' for n in bins])\n count Class\nA 20 Top75\nB 20 Top75\nC 15 Top75\nD 10 Top75\nE 10 Top75\nF 8 Top15\nG 7 Top15\nH 5 Top10\nI 5 Top10\n count cumsum bin Class\nA 20 100 (25, 100] Top75\nB 20 80 (25, 100] Top75\nC 15 60 (25, 100] Top75\nD 10 45 (25, 100] Top75\nE 10 35 (25, 100] Top75\nF 8 25 (10, 25] Top15\nG 7 17 (10, 25] Top15\nH 5 10 (0, 10] Top10\nI 5 5 (0, 10] Top10\n"
},
{
"answer_id": 74493760,
"author": "Panda Kim",
"author_id": 20430449,
"author_profile": "https://Stackoverflow.com/users/20430449",
"pm_score": 1,
"selected": false,
"text": "min_c = df['count'].min()\nmax_c = df['count'].max()\nbins = [min_c-0.001, 0.9 * min_c + 0.1 * max_c, 0.75 * min_c + 0.25 * max_c, max_c]\nlabels = ['Top10', 'Top25', 'Top75']\ndf.assign(Class=pd.cut(df['count'], bins=bins, labels=labels))\n count Class\nA 20 Top75\nB 20 Top75\nC 15 Top75\nD 10 Top75\nE 10 Top75\nF 8 Top25\nG 7 Top25\nH 5 Top10\nI 5 Top10\n"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74493584",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20434497/"
] |
74,493,599
|
<p>I tried to filter data where they are on a list by using Data step in SAS</p>
<pre><code>proc sql;
create table id_list as
select distinct id from customer;
quit;
data test;
set fulldata;
where id in id_list;
run;
</code></pre>
<p>It doesnt work. However, if I use "where id in (1,2,3)" it works.
Could anyone please help me with where in a list of data ?
Thanks</p>
|
[
{
"answer_id": 74493650,
"author": "crashMOGWAI",
"author_id": 5373105,
"author_profile": "https://Stackoverflow.com/users/5373105",
"pm_score": 1,
"selected": false,
"text": "df = pd.DataFrame(dict(count=[20,20,15,10,8,5]))\ndf['class'] = pd.cut(df['count'], [0, 5, 15, 20], labels=['Top10', 'Top15', 'Top75'])\n\n| | count | class |\n|---:|--------:|:--------|\n| 0 | 20 | Top75 |\n| 1 | 20 | Top75 |\n| 2 | 15 | Top15 |\n| 3 | 10 | Top15 |\n| 4 | 8 | Top15 |\n| 5 | 5 | Top10 |\n"
},
{
"answer_id": 74493667,
"author": "mozway",
"author_id": 16343464,
"author_profile": "https://Stackoverflow.com/users/16343464",
"pm_score": 1,
"selected": true,
"text": "bins = [10, 15, 75]\ndf['Class'] = pd.cut(df.loc[::-1, 'count'].cumsum(),\n np.cumsum([0]+bins),\n labels=[f'Top{n}' for n in bins])\n count Class\nA 20 Top75\nB 20 Top75\nC 15 Top75\nD 10 Top75\nE 10 Top75\nF 8 Top15\nG 7 Top15\nH 5 Top10\nI 5 Top10\n count cumsum bin Class\nA 20 100 (25, 100] Top75\nB 20 80 (25, 100] Top75\nC 15 60 (25, 100] Top75\nD 10 45 (25, 100] Top75\nE 10 35 (25, 100] Top75\nF 8 25 (10, 25] Top15\nG 7 17 (10, 25] Top15\nH 5 10 (0, 10] Top10\nI 5 5 (0, 10] Top10\n"
},
{
"answer_id": 74493760,
"author": "Panda Kim",
"author_id": 20430449,
"author_profile": "https://Stackoverflow.com/users/20430449",
"pm_score": 1,
"selected": false,
"text": "min_c = df['count'].min()\nmax_c = df['count'].max()\nbins = [min_c-0.001, 0.9 * min_c + 0.1 * max_c, 0.75 * min_c + 0.25 * max_c, max_c]\nlabels = ['Top10', 'Top25', 'Top75']\ndf.assign(Class=pd.cut(df['count'], bins=bins, labels=labels))\n count Class\nA 20 Top75\nB 20 Top75\nC 15 Top75\nD 10 Top75\nE 10 Top75\nF 8 Top25\nG 7 Top25\nH 5 Top10\nI 5 Top10\n"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74493599",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20541932/"
] |
74,493,618
|
<p>I would like to fill column <code>b</code> of a dataframe with values from <code>a</code> in case <code>b</code> is <code>nan</code>, and I would like to do it in a method chain, but I cannot figure out how to do this.</p>
<p>The following works</p>
<pre class="lang-py prettyprint-override"><code>import numpy as np
import pandas as pd
df = pd.DataFrame(
{"a": [1, 2, 3, 4], "b": [10, np.nan, np.nan, 40], "c": ["a", "b", "c", "d"]}
)
df["b"] = df[["a", "b"]].ffill(axis=1)["b"]
print(df.to_markdown())
| | a | b | c |
|---:|----:|----:|:----|
| 0 | 1 | 10 | a |
| 1 | 2 | 2 | b |
| 2 | 3 | 3 | c |
| 3 | 4 | 40 | d |
</code></pre>
<p>but is not method-chained. Thanks a lot for the help!</p>
|
[
{
"answer_id": 74493650,
"author": "crashMOGWAI",
"author_id": 5373105,
"author_profile": "https://Stackoverflow.com/users/5373105",
"pm_score": 1,
"selected": false,
"text": "df = pd.DataFrame(dict(count=[20,20,15,10,8,5]))\ndf['class'] = pd.cut(df['count'], [0, 5, 15, 20], labels=['Top10', 'Top15', 'Top75'])\n\n| | count | class |\n|---:|--------:|:--------|\n| 0 | 20 | Top75 |\n| 1 | 20 | Top75 |\n| 2 | 15 | Top15 |\n| 3 | 10 | Top15 |\n| 4 | 8 | Top15 |\n| 5 | 5 | Top10 |\n"
},
{
"answer_id": 74493667,
"author": "mozway",
"author_id": 16343464,
"author_profile": "https://Stackoverflow.com/users/16343464",
"pm_score": 1,
"selected": true,
"text": "bins = [10, 15, 75]\ndf['Class'] = pd.cut(df.loc[::-1, 'count'].cumsum(),\n np.cumsum([0]+bins),\n labels=[f'Top{n}' for n in bins])\n count Class\nA 20 Top75\nB 20 Top75\nC 15 Top75\nD 10 Top75\nE 10 Top75\nF 8 Top15\nG 7 Top15\nH 5 Top10\nI 5 Top10\n count cumsum bin Class\nA 20 100 (25, 100] Top75\nB 20 80 (25, 100] Top75\nC 15 60 (25, 100] Top75\nD 10 45 (25, 100] Top75\nE 10 35 (25, 100] Top75\nF 8 25 (10, 25] Top15\nG 7 17 (10, 25] Top15\nH 5 10 (0, 10] Top10\nI 5 5 (0, 10] Top10\n"
},
{
"answer_id": 74493760,
"author": "Panda Kim",
"author_id": 20430449,
"author_profile": "https://Stackoverflow.com/users/20430449",
"pm_score": 1,
"selected": false,
"text": "min_c = df['count'].min()\nmax_c = df['count'].max()\nbins = [min_c-0.001, 0.9 * min_c + 0.1 * max_c, 0.75 * min_c + 0.25 * max_c, max_c]\nlabels = ['Top10', 'Top25', 'Top75']\ndf.assign(Class=pd.cut(df['count'], bins=bins, labels=labels))\n count Class\nA 20 Top75\nB 20 Top75\nC 15 Top75\nD 10 Top75\nE 10 Top75\nF 8 Top25\nG 7 Top25\nH 5 Top10\nI 5 Top10\n"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74493618",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6658422/"
] |
74,493,648
|
<p>Im trying to figure out how to use conditinal rendering in react - if else statements but Im struggling, I need the button, that has only increment, to stop adding number past certain number, lets say 5 and then highlight the number in red.</p>
<p>I have declared function and called it onClick, also declared consts, this is what I have as a base component:</p>
<pre><code> const [count, setCount] = useState(0);
function addCount() {
setCount(prevCount => prevCount + 1)
}
</code></pre>
<pre><code> </div>
<h1>Kaufland</h1>
<p>Customers {count}</p>
<Uu5Elements.Button class="btn2" onClick={addCount}>+1</Uu5Elements.Button>
</div>
</code></pre>
<p>Any help really helps, Im not sure how to add that requirement to the function.</p>
|
[
{
"answer_id": 74493650,
"author": "crashMOGWAI",
"author_id": 5373105,
"author_profile": "https://Stackoverflow.com/users/5373105",
"pm_score": 1,
"selected": false,
"text": "df = pd.DataFrame(dict(count=[20,20,15,10,8,5]))\ndf['class'] = pd.cut(df['count'], [0, 5, 15, 20], labels=['Top10', 'Top15', 'Top75'])\n\n| | count | class |\n|---:|--------:|:--------|\n| 0 | 20 | Top75 |\n| 1 | 20 | Top75 |\n| 2 | 15 | Top15 |\n| 3 | 10 | Top15 |\n| 4 | 8 | Top15 |\n| 5 | 5 | Top10 |\n"
},
{
"answer_id": 74493667,
"author": "mozway",
"author_id": 16343464,
"author_profile": "https://Stackoverflow.com/users/16343464",
"pm_score": 1,
"selected": true,
"text": "bins = [10, 15, 75]\ndf['Class'] = pd.cut(df.loc[::-1, 'count'].cumsum(),\n np.cumsum([0]+bins),\n labels=[f'Top{n}' for n in bins])\n count Class\nA 20 Top75\nB 20 Top75\nC 15 Top75\nD 10 Top75\nE 10 Top75\nF 8 Top15\nG 7 Top15\nH 5 Top10\nI 5 Top10\n count cumsum bin Class\nA 20 100 (25, 100] Top75\nB 20 80 (25, 100] Top75\nC 15 60 (25, 100] Top75\nD 10 45 (25, 100] Top75\nE 10 35 (25, 100] Top75\nF 8 25 (10, 25] Top15\nG 7 17 (10, 25] Top15\nH 5 10 (0, 10] Top10\nI 5 5 (0, 10] Top10\n"
},
{
"answer_id": 74493760,
"author": "Panda Kim",
"author_id": 20430449,
"author_profile": "https://Stackoverflow.com/users/20430449",
"pm_score": 1,
"selected": false,
"text": "min_c = df['count'].min()\nmax_c = df['count'].max()\nbins = [min_c-0.001, 0.9 * min_c + 0.1 * max_c, 0.75 * min_c + 0.25 * max_c, max_c]\nlabels = ['Top10', 'Top25', 'Top75']\ndf.assign(Class=pd.cut(df['count'], bins=bins, labels=labels))\n count Class\nA 20 Top75\nB 20 Top75\nC 15 Top75\nD 10 Top75\nE 10 Top75\nF 8 Top25\nG 7 Top25\nH 5 Top10\nI 5 Top10\n"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74493648",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20518418/"
] |
74,493,671
|
<p>I have the following code:</p>
<pre><code>let object = {};
Object.keys(this.graphQL.body).forEach((key) => {
console.log(key, this[key])
object[key] = this[key]
})
let json = JSON.stringify(object);
console.log('API json', json)
</code></pre>
<p>Which gives this out this console log:</p>
<pre><code>id undefined
title undefined
filename mitchel-lensink-Y2OCQVuz6XM-unsplash.jpg
description undefined
keywords undefined
assetID undefined
height undefined
width undefined
uploadOwnerType image
uploadOwnerID 100513
createdAt undefined
updatedAt undefined
API json {"filename":"mitchel-lensink-Y2OCQVuz6XM-unsplash.jpg","uploadOwnerType":"image","uploadOwnerID":100513}
</code></pre>
<p>Why do I not get the undefined keys added? And how can I add them anyway?</p>
|
[
{
"answer_id": 74493730,
"author": "Anmol kansal",
"author_id": 11652772,
"author_profile": "https://Stackoverflow.com/users/11652772",
"pm_score": 2,
"selected": false,
"text": "let json = JSON.stringify(object);\n\n let object = {};\nObject.keys(this.graphQL.body).forEach((key) => {\n console.log(key, this[key])\n object[key] = this[key]\n})\n\nconst replacer = (key, value) =>\n typeof value === 'undefined' ? null : value;\n\nlet json = JSON.stringify(object, replacer);\nconsole.log('API json', json)\n\n"
},
{
"answer_id": 74493757,
"author": "DShadrin",
"author_id": 6694219,
"author_profile": "https://Stackoverflow.com/users/6694219",
"pm_score": 1,
"selected": false,
"text": "const replacer = (key, value) =>\n typeof value === 'undefined' ? null : value;\n let json = JSON.stringify(object, replacer);\n"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74493671",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17699392/"
] |
74,493,697
|
<p>Note: I've tried a dozen examples. Some I did find here. None work for me.</p>
<p>I did get Links in React to work sort of, but they add a component to the page, rather than replacing it.<br />
I understand to fix that issue that I need to wrap app in BrowserRouter, but every way I try makes the whole site render blank.</p>
<p>So in <code><Provider store={store}><App /></Provider></code> below, if I try to put <code><BrowserRouter></code> tags either outside or inside the <code><Provider></code> tags, the site renders blank. What I am missing?</p>
<p>Here is my index.js:</p>
<pre><code>import React from "react";
import ReactDOM from "react-dom/client";
import "./index.scss";
import reportWebVitals from "./reportWebVitals";
import { store } from "./store";
import { Provider } from "react-redux";
//header, footer, theme
import App from "./App";
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
<Provider store={store}>
<App />
</Provider>
);
reportWebVitals();
</code></pre>
<p>My router.js:</p>
<pre><code> // Routes.js
import React from "react";
import { BrowserRouter, Route, Routes, Link } from 'react-router-dom';
import Home from "./pages/home";
import About from "./pages/about";
const Router = () => {
return (
<BrowserRouter>
<Routes>
<Route exact path='/' element={<Home />} />
<Route path='/About' element={<About />} />
</Routes>
</BrowserRouter>
);
};
export default Router;
</code></pre>
<p>And my app.js:</p>
<pre><code>import { useEffect } from "react";
// mui
import { Container } from "@mui/material";
import { ThemeProvider } from "@mui/system";
// theme
import theme from "./styles/theme";
// components
import Footer from "./components/footer";
import Appbar from "./components/appbar";
// styles
import "./App.css";
import About from "./pages/about";
/*import Events from './components/Events/Events';*/
import {Route, Routes } from 'react-router-dom';
import Router from "./router";
// components
import ListArticles from "./components/list-articles";
function App() {
useEffect(() => {
document.title = "Home";
}, []);
return (
<ThemeProvider theme={theme}>
<Container
disableGutters
maxWidth="xl"
sx={{
background: "#fff",
}}
>
<Appbar />
<Router />
<Footer />
</Container>
</ThemeProvider>
);
}
export default App;
</code></pre>
<p>Note: As soon as I comment out Browser router in my index.js, the site content loads. When I put the browser router tag back, site content is blank. Same affect if browser router tag is inside provider tags.</p>
<pre><code> /* <BrowserRouter>*/
<Provider store={store}>
<App />
</Provider>
/*</BrowserRouter>*/
</code></pre>
|
[
{
"answer_id": 74493972,
"author": "Luann Sapucaia",
"author_id": 10467556,
"author_profile": "https://Stackoverflow.com/users/10467556",
"pm_score": -1,
"selected": false,
"text": "<Route exact path='/' element={<Home />} />\n"
},
{
"answer_id": 74495378,
"author": "Susan Anspaugh",
"author_id": 4538707,
"author_profile": "https://Stackoverflow.com/users/4538707",
"pm_score": 0,
"selected": false,
"text": " <BrowserRouter>\n <ThemeProvider theme={theme}>\n <Container\n disableGutters\n maxWidth=\"xl\"\n sx={{\n background: \"#fff\",\n }}\n >\n \n <Appbar /> \n <Router /> \n <Footer />\n </Container> \n </ThemeProvider>\n </BrowserRouter >\n <Link to=\"/about\">About</Link>\n"
},
{
"answer_id": 74495387,
"author": "Drew Reese",
"author_id": 8690857,
"author_profile": "https://Stackoverflow.com/users/8690857",
"pm_score": 0,
"selected": false,
"text": "BrowserRouter import { BrowserRouter } from \"react-router-dom\";\nimport { Provider } from \"react-redux\";\nimport { store } from \"./store\";\nimport App from \"./App\";\n\nconst root = ReactDOM.createRoot(document.getElementById(\"root\"));\nroot.render(\n <Provider store={store}>\n <BrowserRouter>\n <App />\n </BrowserRouter>\n </Provider>\n);\n import Router from \"./router\";\n\nfunction App() {\n useEffect(() => {\n document.title = \"Home\";\n }, []);\n\n return (\n <ThemeProvider theme={theme}>\n <Container\n disableGutters\n maxWidth=\"xl\"\n sx={{ background: \"#fff\" }}\n >\n <Appbar />\n <Router />\n <Footer />\n </Container> \n </ThemeProvider>\n );\n}\n import { Link } from \"react-router-dom\";\n\nconst Appbar = () => {\n ...\n\n return (\n ...\n <div className=\"wrapper\">\n <Link to=\"/about\">About</Link>\n ....\n </div>\n );\n};\n import React from \"react\";\nimport { Route, Routes } from \"react-router-dom\";\nimport Home from \"./pages/home\";\nimport About from \"./pages/about\";\n\nconst Router = () => (\n <Routes>\n <Route path='/' element={<Home />} />\n <Route path='/About' element={<About />} />\n ... other routes\n </Routes>\n);\n\nexport default Router;\n"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74493697",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4538707/"
] |
74,493,702
|
<p>With the new app directory, all route directories must have a <code>page.js</code>, <code>page.jsx</code> or a <code>page.tsx</code> file to be visible publicly (eg: <code>mywebsite.com/about</code> requires a file <code>app/about/page.js</code>). But when I try with MDX file <code>app/about/page.mdx</code>, and use nextMDX <code>@next/mdx</code>, I got a 404 not found.</p>
<p>Here is my <code>next.config.mjs</code> configuration file:</p>
<pre><code>import nextMDX from "@next/mdx";
import remarkFrontmatter from "remark-frontmatter";
import rehypeHighlight from "rehype-highlight";
const withMDX = nextMDX({
extension: /\.(md|mdx)$/,
options: {
remarkPlugins: [remarkFrontmatter],
rehypePlugins: [rehypeHighlight],
},
});
const nextConfig = {
experimental: {
appDir: true,
}
};
export default withMDX({
...nextConfig,
pageExtensions: ["js", "jsx", "ts", "tsx", "md", "mdx"],
});
</code></pre>
<p>Thanks for any response</p>
|
[
{
"answer_id": 74656757,
"author": "cyberpunk_unicorn",
"author_id": 20666543,
"author_profile": "https://Stackoverflow.com/users/20666543",
"pm_score": -1,
"selected": false,
"text": " import nextMDX from \"@next/mdx\";\nimport remarkFrontmatter from \"remark-frontmatter\";\nimport rehypeHighlight from \"rehype-highlight\";\n \nconst withMDX = nextMDX({\n extension: /\\.(md|mdx)$/,\n options: {\n remarkPlugins: [remarkFrontmatter],\n rehypePlugins: [rehypeHighlight],\n },\n});\n\nconst nextConfig = {\n experimental: {\n appDir: true,\n }\n};\n\nexport default withMDX({\n ...nextConfig,\n pageExtensions: [\"js\", \"jsx\", \"ts\", \"tsx\", \"md\", \"mdx\"], // include .mdx in pageExtensions\n});\n"
},
{
"answer_id": 74672764,
"author": "Midas",
"author_id": 20678816,
"author_profile": "https://Stackoverflow.com/users/20678816",
"pm_score": -1,
"selected": false,
"text": "const nextConfig = {\n experimental: {\n appDir: true,\n }\n};\n\nexport default withMDX({\n ...nextConfig,\n pageExtensions: [\"js\", \"jsx\", \"ts\", \"tsx\", \"mdx\", \"mdx\"],\n});\n"
},
{
"answer_id": 74677227,
"author": "kppro",
"author_id": 10955397,
"author_profile": "https://Stackoverflow.com/users/10955397",
"pm_score": -1,
"selected": false,
"text": "- app\n - about\n - page.mdx\n - next.config.mjs\n import AboutPage from \"./page.mdx\";\n\nconst About = () => {\n return <AboutPage />;\n};\n\nexport default About;\n"
},
{
"answer_id": 74680898,
"author": "zeefxd",
"author_id": 20683957,
"author_profile": "https://Stackoverflow.com/users/20683957",
"pm_score": 0,
"selected": false,
"text": "// To fix this, you have a couple of options:\n\n// Use a page.js, page.jsx, or page.tsx file for your page, and import and render your .mdx file within that page file.\n// Don't use the appDir feature, and instead structure your pages in the traditional way (i.e., pages/about.mdx instead of app/about/page.mdx).\n// Option 1 would involve changing your page.mdx file to a page.js, page.jsx, or page.tsx file, and importing and rendering your .mdx file within that file. Here's an example of what that might look like:\n\n// app/about/page.jsx\nimport MyAboutMDX from './page.mdx';\n\nfunction AboutPage() {\n return <MyAboutMDX />;\n}\n\nexport default AboutPage;\n\n// Option 2 would involve changing your file structure to the traditional Next.js structure, where pages are placed in the pages directory at the root of your project. In this case, you would move your page.mdx file to pages/about.mdx, and update your import paths accordingly.\n\n// I hope this helps! Let me know if you have any other questions.\n"
},
{
"answer_id": 74680923,
"author": "Ataberk",
"author_id": 4857232,
"author_profile": "https://Stackoverflow.com/users/4857232",
"pm_score": 0,
"selected": false,
"text": "next.config.mjs include \"mdx\" import nextMDX from \"@next/mdx\";\nimport remarkFrontmatter from \"remark-frontmatter\";\nimport rehypeHighlight from \"rehype-highlight\";\n \nconst withMDX = nextMDX({\n extension: /\\.(md|mdx)$/,\n options: {\n remarkPlugins: [remarkFrontmatter],\n rehypePlugins: [rehypeHighlight],\n },\n});\n\nconst nextConfig = {\n experimental: {\n appDir: true,\n }\n};\n\n// Include \"mdx\" as a page extension\nexport default withMDX({\n ...nextConfig,\n pageExtensions: [\"js\", \"jsx\", \"ts\", \"tsx\", \"md\", \"mdx\"],\n});\n app/about/page.mdx /about"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74493702",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10143236/"
] |
74,493,753
|
<p>I want to create a box which has on left and right side a blue "div" and in the middle a larger purple "div". My Problem is that when i write "align-items : center" all "div" vanishes but i dont know why. Can you help me?</p>
<p>This is my HTML Code</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>Flexbox Playground</title>
<link href="https://fonts.googleapis.com/css2?family=Open+Sans:wght@300&display=swap" rel="stylesheet">
<link rel="stylesheet" href="app.css">
</head>
<body>
<h1>Let's Play With Flexbox</h1>
<section id="anotherExample">
<div class="sidebar"></div>
<div class="mainContent"></div>
<div class="sidebar"></div>
</section>
</body>
</html>
</code></pre>
<p>This is my CSS Code</p>
<pre><code>#anotherExample{
width: 90%;
height: 500px;
margin: 0 auto;
border: 5px solid #003049;
display: flex;
justify-content: center;
/*align-items: center;*/
}
section .sidebar{
background-color: blue;
flex-grow:1 ;
flex-basis: 200px;
}
section .mainContent{
background-color: blueviolet;
flex-grow:2 ;
flex-basis: 200px;
}
</code></pre>
|
[
{
"answer_id": 74656757,
"author": "cyberpunk_unicorn",
"author_id": 20666543,
"author_profile": "https://Stackoverflow.com/users/20666543",
"pm_score": -1,
"selected": false,
"text": " import nextMDX from \"@next/mdx\";\nimport remarkFrontmatter from \"remark-frontmatter\";\nimport rehypeHighlight from \"rehype-highlight\";\n \nconst withMDX = nextMDX({\n extension: /\\.(md|mdx)$/,\n options: {\n remarkPlugins: [remarkFrontmatter],\n rehypePlugins: [rehypeHighlight],\n },\n});\n\nconst nextConfig = {\n experimental: {\n appDir: true,\n }\n};\n\nexport default withMDX({\n ...nextConfig,\n pageExtensions: [\"js\", \"jsx\", \"ts\", \"tsx\", \"md\", \"mdx\"], // include .mdx in pageExtensions\n});\n"
},
{
"answer_id": 74672764,
"author": "Midas",
"author_id": 20678816,
"author_profile": "https://Stackoverflow.com/users/20678816",
"pm_score": -1,
"selected": false,
"text": "const nextConfig = {\n experimental: {\n appDir: true,\n }\n};\n\nexport default withMDX({\n ...nextConfig,\n pageExtensions: [\"js\", \"jsx\", \"ts\", \"tsx\", \"mdx\", \"mdx\"],\n});\n"
},
{
"answer_id": 74677227,
"author": "kppro",
"author_id": 10955397,
"author_profile": "https://Stackoverflow.com/users/10955397",
"pm_score": -1,
"selected": false,
"text": "- app\n - about\n - page.mdx\n - next.config.mjs\n import AboutPage from \"./page.mdx\";\n\nconst About = () => {\n return <AboutPage />;\n};\n\nexport default About;\n"
},
{
"answer_id": 74680898,
"author": "zeefxd",
"author_id": 20683957,
"author_profile": "https://Stackoverflow.com/users/20683957",
"pm_score": 0,
"selected": false,
"text": "// To fix this, you have a couple of options:\n\n// Use a page.js, page.jsx, or page.tsx file for your page, and import and render your .mdx file within that page file.\n// Don't use the appDir feature, and instead structure your pages in the traditional way (i.e., pages/about.mdx instead of app/about/page.mdx).\n// Option 1 would involve changing your page.mdx file to a page.js, page.jsx, or page.tsx file, and importing and rendering your .mdx file within that file. Here's an example of what that might look like:\n\n// app/about/page.jsx\nimport MyAboutMDX from './page.mdx';\n\nfunction AboutPage() {\n return <MyAboutMDX />;\n}\n\nexport default AboutPage;\n\n// Option 2 would involve changing your file structure to the traditional Next.js structure, where pages are placed in the pages directory at the root of your project. In this case, you would move your page.mdx file to pages/about.mdx, and update your import paths accordingly.\n\n// I hope this helps! Let me know if you have any other questions.\n"
},
{
"answer_id": 74680923,
"author": "Ataberk",
"author_id": 4857232,
"author_profile": "https://Stackoverflow.com/users/4857232",
"pm_score": 0,
"selected": false,
"text": "next.config.mjs include \"mdx\" import nextMDX from \"@next/mdx\";\nimport remarkFrontmatter from \"remark-frontmatter\";\nimport rehypeHighlight from \"rehype-highlight\";\n \nconst withMDX = nextMDX({\n extension: /\\.(md|mdx)$/,\n options: {\n remarkPlugins: [remarkFrontmatter],\n rehypePlugins: [rehypeHighlight],\n },\n});\n\nconst nextConfig = {\n experimental: {\n appDir: true,\n }\n};\n\n// Include \"mdx\" as a page extension\nexport default withMDX({\n ...nextConfig,\n pageExtensions: [\"js\", \"jsx\", \"ts\", \"tsx\", \"md\", \"mdx\"],\n});\n app/about/page.mdx /about"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74493753",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
74,493,759
|
<p><a href="https://i.stack.imgur.com/E1lkz.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/E1lkz.png" alt="enter image description here" /></a>I want to add a feature to my current search bar where if I click, I am able to see a drop down of all the previous inputs. And if I were to click on this previous input, it will run my code again. I am a current boot camp student and I just need guidance into how to make this work. If someone to just point me in the right direction, or explain some sample functions that would be really helpful. Thanks in advance.</p>
<pre><code> <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link
rel="stylesheet"
href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
/>
<link rel="stylesheet" href="./assets/style.css" />
<title>Weather Dashboard</title>
</head>
<body onload="load()">
<div class="container">
<div class="card">
<div class="row">
<div class="col-9 left">
<nav class="row top">
<div class="col" id="cityName">City Name</div>
<form class="form-outline">
<input
type="search"
id="userInput"
class="form-control"
placeholder="search for a city"
aria-label="Search"
/>
</form>
<div class="col" id="date">Date</div>
</nav>
<div class="row">
<div class="col-7 temp" id="temperature">15&deg;</div>
<div class="col-5 time">
<p id="time">11:00</p>
<h2 id="today"><b>Saturday</b></h2>
<p id="conditions">Cloudy</p>
</div>
</div>
<div class="row bottom">
<div class="col"><hr /></div>
<div class="col">
<div class="row" id="condition1">Condition</div>
<div class="row data"><img id="conditionIcon1" /></div>
</div>
<div class="col">
<div class="row" id="condition2">Condition</div>
<div class="row data"><img id="conditionIcon2" /></div>
</div>
<div class="col">
<div class="row" id="condition3">Condition</div>
<div class="row data"><img id="conditionIcon3" /></div>
</div>
<div class="col">
<div class="row" id="condition4">Condition</div>
<div class="row data"><img id="conditionIcon4" /></div>
</div>
<div class="col">
<div class="row" id="condition5">Condition</div>
<div class="row data"><img id="conditionIcon5" /></div>
</div>
<div class="col"><hr /></div>
</div>
<div class="row bottom">
<div class="col"><hr /></div>
<div class="col">
<div class="row" id="date1">Sun</div>
<div class="row data" id="date1Temp"><b>0&deg;</b></div>
</div>
<div class="col">
<div class="row" id="date2">Mon</div>
<div class="row data" id="date2Temp"><b>0&deg;</b></div>
</div>
<div class="col">
<div class="row" id="date3">Tue</div>
<div class="row data" id="date3Temp"><b>0&deg;</b></div>
</div>
<div class="col">
<div class="row" id="date4">Wed</div>
<div class="row data" id="date4Temp"><b>0&deg;</b></div>
</div>
<div class="col">
<div class="row" id="date5">Thu</div>
<div class="row data" id="date5Temp"><b>0&deg;</b></div>
</div>
<div class="col"><hr /></div>
</div>
<div class="row bottom">
<div class="col"><hr /></div>
<div class="col">
<div class="row">Humidity</div>
<div class="row data" id="humidity1"><b>0&deg;</b></div>
</div>
<div class="col">
<div class="row">Humidity</div>
<div class="row data" id="humidity2"><b>0&deg;</b></div>
</div>
<div class="col">
<div class="row">Humidity</div>
<div class="row data" id="humidity3"><b>0&deg;</b></div>
</div>
<div class="col">
<div class="row">Humidity</div>
<div class="row data" id="humidity4"><b>0&deg;</b></div>
</div>
<div class="col">
<div class="row">Humidity</div>
<div class="row data" id="humidity5"><b>0&deg;</b></div>
</div>
<div class="col"><hr /></div>
</div>
<div class="row bottom">
<div class="col"><hr /></div>
<div class="col">
<div class="row">Wind Speed</div>
<div class="row data" id="windSpeed1"><b>0&deg;</b></div>
</div>
<div class="col">
<div class="row">Wind Speed</div>
<div class="row data" id="windSpeed2"><b>0&deg;</b></div>
</div>
<div class="col">
<div class="row">Wind Speed</div>
<div class="row data" id="windSpeed3"><b>0&deg;</b></div>
</div>
<div class="col">
<div class="row">Wind Speed</div>
<div class="row data" id="windSpeed4"><b>0&deg;</b></div>
</div>
<div class="col">
<div class="row">Wind Speed</div>
<div class="row data" id="windSpeed5"><b>0&deg;</b></div>
</div>
<div class="col"><hr /></div>
</div>
</div>
<div class="col-3 right">
<div class="row top" id="right-header">Today's Statistics</div>
<div class="timely">
<div class="row">Temp High:<b id="tempHigh">0&deg;</b></div>
<div class="row">Temp Low:<b id="tempLow">0&deg;</b></div>
<div class="row">Feels Like:<b id="feelslike">0&deg;</b></div>
<div class="row">Wind Speed:<b id="windspeed">0&deg;</b></div>
<div class="row">Humidity:<b id="humidity">0&deg;</b></div>
<div class="row">Pressure:<b id="pressure">0&deg;</b></div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/dayjs@1/dayjs.min.js"></script>
<script>
dayjs().format();
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
<script src="./assets/script.js"></script>
</body>
</html>
</code></pre>
<pre><code>const date = document.querySelector("#date");
const time = document.querySelector("#time");
const dayOfWeek = document.querySelector("#today");
const input = document.querySelector("#userInput");
date.innerText = moment().format("MMMM Do YYYY");
time.innerText = moment().format("h:mm A");
dayOfWeek.innerText = moment().format("dddd");
// applies elements on page load with current position
function load() {
navigator.geolocation.getCurrentPosition((position) => {
let lat = position.coords.latitude;
let long = position.coords.longitude;
let fiveDayURL = `https://api.openweathermap.org/data/2.5/forecast?lat=${lat}&lon=${long}&appid=b169b31281ffa2a2b70b9e8ac22c3e88&units=imperial`;
fetch(fiveDayURL)
.then((res) => {
return res.json();
})
.then((data) => {
fiveDayWeather(data);
console.log(data);
localStorage.setItem("response", JSON.stringify(data.city.name));
loadUrl();
});
});
}
function loadUrl() {
let cityName = JSON.parse(localStorage.getItem("response"));
let requestURL = `https://api.openweathermap.org/data/2.5/weather?q=${cityName}&appid=b169b31281ffa2a2b70b9e8ac22c3e88&units=imperial`;
fetch(requestURL)
.then((res) => {
return res.json();
})
.then((data) => {
// console.log(data);
displayWeather(data);
})
.catch(() => {
alert("Unable to connect to OpenWeather");
});
}
// uses user input as parameter to getApi()
input.addEventListener("keypress", function (e) {
if (e.key === "Enter") {
e.preventDefault();
// let cityName = document.querySelectro("#userInput").value;
// let li = document.createElement("li")
// li.innerText = cityName;
// document.querySelector('ul');
// ul.appendChild(li);
getApi();
input.value = "";
}
});
// fetches api using the user input
function getApi() {
let cityName = document.querySelector("#userInput").value;
let requestURL = `https://api.openweathermap.org/data/2.5/weather?q=${cityName}&appid=b169b31281ffa2a2b70b9e8ac22c3e88&units=imperial`;
fetch(requestURL)
.then((res) => {
return res.json();
})
.then((data) => {
// console.log(data);
displayWeather(data);
})
.catch(() => {
alert("Unable to connect to OpenWeather");
});
}
// uses api data from getApi() and replaces text in html
let displayWeather = function (weatherData) {
document.querySelector("#cityName").innerText = weatherData.name;
document.querySelector("#temperature").innerText =
Math.floor(weatherData.main.temp) + "\u00B0";
document.querySelector("#conditions").innerText =
weatherData.weather[0].description;
document.querySelector("#tempHigh").innerText =
weatherData.main.temp_max + "\u00B0 F";
document.querySelector("#tempLow").innerText =
weatherData.main.temp_min + "\u00B0 F";
document.querySelector("#feelslike").innerText =
weatherData.main.feels_like + "\u00B0 F";
document.querySelector("#windspeed").innerText =
weatherData.wind.speed + " MPH";
document.querySelector("#humidity").innerText =
weatherData.main.humidity + "%";
document.querySelector("#pressure").innerText =
weatherData.main.pressure + " hPa";
let fiveDayURL = `https://api.openweathermap.org/data/2.5/forecast?lat=${weatherData.coord.lat}&lon=${weatherData.coord.lon}&appid=b169b31281ffa2a2b70b9e8ac22c3e88&units=imperial`;
fetch(fiveDayURL)
.then((res) => {
return res.json();
})
.then((data) => {
// console.log(data);
fiveDayWeather(data);
})
.catch(() => {
alert("Unable to connect to OpenWeather");
});
};
// obtains lon and lat from previous function then completes new fetch to display 5 day forecast
let fiveDayWeather = function (weatherValue) {
let todaysMonth = dayjs().$M;
for (let i = 1; i < 6; i++) {
document.querySelector("#date" + i).innerText = `${todaysMonth}/${
dayjs().$D + i
}`;
document.querySelector("#date" + i + "Temp").innerText =
weatherValue.list[i].main.temp + "\u00B0 F";
document.querySelector("#condition" + i).innerText =
weatherValue.list[i].weather[0].description;
document.querySelector("#conditionIcon" + i).src =
"http://openweathermap.org/img/wn/" +
weatherValue.list[i].weather[0].icon +
"@2x.png";
document.querySelector("#humidity" + i).innerText =
weatherValue.list[i].main.humidity + "%";
document.querySelector("#windSpeed" + i).innerText =
weatherValue.list[i].wind.speed + "MPH";
}
};
</code></pre>
|
[
{
"answer_id": 74656757,
"author": "cyberpunk_unicorn",
"author_id": 20666543,
"author_profile": "https://Stackoverflow.com/users/20666543",
"pm_score": -1,
"selected": false,
"text": " import nextMDX from \"@next/mdx\";\nimport remarkFrontmatter from \"remark-frontmatter\";\nimport rehypeHighlight from \"rehype-highlight\";\n \nconst withMDX = nextMDX({\n extension: /\\.(md|mdx)$/,\n options: {\n remarkPlugins: [remarkFrontmatter],\n rehypePlugins: [rehypeHighlight],\n },\n});\n\nconst nextConfig = {\n experimental: {\n appDir: true,\n }\n};\n\nexport default withMDX({\n ...nextConfig,\n pageExtensions: [\"js\", \"jsx\", \"ts\", \"tsx\", \"md\", \"mdx\"], // include .mdx in pageExtensions\n});\n"
},
{
"answer_id": 74672764,
"author": "Midas",
"author_id": 20678816,
"author_profile": "https://Stackoverflow.com/users/20678816",
"pm_score": -1,
"selected": false,
"text": "const nextConfig = {\n experimental: {\n appDir: true,\n }\n};\n\nexport default withMDX({\n ...nextConfig,\n pageExtensions: [\"js\", \"jsx\", \"ts\", \"tsx\", \"mdx\", \"mdx\"],\n});\n"
},
{
"answer_id": 74677227,
"author": "kppro",
"author_id": 10955397,
"author_profile": "https://Stackoverflow.com/users/10955397",
"pm_score": -1,
"selected": false,
"text": "- app\n - about\n - page.mdx\n - next.config.mjs\n import AboutPage from \"./page.mdx\";\n\nconst About = () => {\n return <AboutPage />;\n};\n\nexport default About;\n"
},
{
"answer_id": 74680898,
"author": "zeefxd",
"author_id": 20683957,
"author_profile": "https://Stackoverflow.com/users/20683957",
"pm_score": 0,
"selected": false,
"text": "// To fix this, you have a couple of options:\n\n// Use a page.js, page.jsx, or page.tsx file for your page, and import and render your .mdx file within that page file.\n// Don't use the appDir feature, and instead structure your pages in the traditional way (i.e., pages/about.mdx instead of app/about/page.mdx).\n// Option 1 would involve changing your page.mdx file to a page.js, page.jsx, or page.tsx file, and importing and rendering your .mdx file within that file. Here's an example of what that might look like:\n\n// app/about/page.jsx\nimport MyAboutMDX from './page.mdx';\n\nfunction AboutPage() {\n return <MyAboutMDX />;\n}\n\nexport default AboutPage;\n\n// Option 2 would involve changing your file structure to the traditional Next.js structure, where pages are placed in the pages directory at the root of your project. In this case, you would move your page.mdx file to pages/about.mdx, and update your import paths accordingly.\n\n// I hope this helps! Let me know if you have any other questions.\n"
},
{
"answer_id": 74680923,
"author": "Ataberk",
"author_id": 4857232,
"author_profile": "https://Stackoverflow.com/users/4857232",
"pm_score": 0,
"selected": false,
"text": "next.config.mjs include \"mdx\" import nextMDX from \"@next/mdx\";\nimport remarkFrontmatter from \"remark-frontmatter\";\nimport rehypeHighlight from \"rehype-highlight\";\n \nconst withMDX = nextMDX({\n extension: /\\.(md|mdx)$/,\n options: {\n remarkPlugins: [remarkFrontmatter],\n rehypePlugins: [rehypeHighlight],\n },\n});\n\nconst nextConfig = {\n experimental: {\n appDir: true,\n }\n};\n\n// Include \"mdx\" as a page extension\nexport default withMDX({\n ...nextConfig,\n pageExtensions: [\"js\", \"jsx\", \"ts\", \"tsx\", \"md\", \"mdx\"],\n});\n app/about/page.mdx /about"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74493759",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20116550/"
] |
74,493,780
|
<p>When I use boto3 I can paginate if I am making a query or scan</p>
<p>Is it possible to do the same with put_item?</p>
|
[
{
"answer_id": 74494421,
"author": "Lee Hannigan",
"author_id": 7909676,
"author_profile": "https://Stackoverflow.com/users/7909676",
"pm_score": 1,
"selected": false,
"text": "--limit import boto3\n\ndynamodb = boto3.resource(\"dynamodb\")\ntable = dynamodb.Table(\"name\")\n\nwith table.batch_writer() as batch_writer:\n for _ in range(1000):\n batch_writer.put_item(Item=myitem) \n"
},
{
"answer_id": 74494714,
"author": "Dunedan",
"author_id": 4779904,
"author_profile": "https://Stackoverflow.com/users/4779904",
"pm_score": 2,
"selected": false,
"text": "PutItem BatchWriter PutItem DeleteItem import boto3\n\ndynamodb = boto3.resource(\"dynamodb\")\ntable = dynamodb.Table(\"name\")\n\nwith table.batch_writer() as batch_writer:\n for _ in range(1000):\n batch_writer.put_item(Item={\"HashKey\": \"...\",\n \"Otherstuff\": \"...\"}) \n\n"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74493780",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14183621/"
] |
74,493,795
|
<p>I have multiple Python scripts from which I want to run a docker container. From a related question <a href="https://stackoverflow.com/questions/53920742/how-to-run-multiple-python-scripts-and-an-executable-files-using-docker">How to run multiple Python scripts and an executable files using Docker?</a> , I found that the best way to do that is to have <code>run.sh</code> a shell file as follows:</p>
<pre><code>#!/bin/bash
python3 producer.py &
python3 consumer.py &
python3 test_conn.py
</code></pre>
<p>and then call this file from a Dockerfile as:</p>
<pre><code>FROM python:3.9
RUN mkdir -p /usr/src/app
WORKDIR /usr/src/app
COPY requirements.txt /usr/src/app
RUN pip install --no-cache-dir -r requirements.txt
COPY . /usr/src/app
CMD ["./run.sh"]
</code></pre>
<p>However, in the container logs the following error is prompting <code>exec ./run.sh: no such file or directory</code>, which makes no sense to me since I copied everything on the current directory, run.sh included, to /usr/src/app on my container via <code>COPY . /usr/src/app</code></p>
<p>Please, clone my repo and on the root directory call docker-compose up -d and check myapp container logs to help me.</p>
<p><a href="https://github.com/Quilograma/IES_Project" rel="nofollow noreferrer">https://github.com/Quilograma/IES_Project</a></p>
<p>Thank you!</p>
<p>Can't run multiple python scripts in a single container.</p>
|
[
{
"answer_id": 74493890,
"author": "Jib",
"author_id": 20124358,
"author_profile": "https://Stackoverflow.com/users/20124358",
"pm_score": 0,
"selected": false,
"text": "CMD [\"bash\", \"-c\", \"./run.sh\"]"
},
{
"answer_id": 74494496,
"author": "David Maze",
"author_id": 10008173,
"author_profile": "https://Stackoverflow.com/users/10008173",
"pm_score": -1,
"selected": false,
"text": "command: version: '3.8'\nservices:\n producer:\n build: .\n command: ./producer.py\n consumer:\n build: .\n command: ./consumer.py\n test_conn:\n build: .\n command: ./test_conn.py\n chmod +x producer.py #!/usr/bin/env python3"
},
{
"answer_id": 74500531,
"author": "Martim Sousa",
"author_id": 20534381,
"author_profile": "https://Stackoverflow.com/users/20534381",
"pm_score": -1,
"selected": false,
"text": "RUN sed -i -e 's/\\r$//' run.sh CMD [\"bash\", \"-c\", \"./run.sh\"]"
},
{
"answer_id": 74502893,
"author": "zsolt",
"author_id": 4223799,
"author_profile": "https://Stackoverflow.com/users/4223799",
"pm_score": 0,
"selected": false,
"text": "FROM python:3.9\n\nRUN mkdir -p /usr/src/app\n\nWORKDIR /usr/src/app\n\nCOPY requirements.txt /usr/src/app\n\nRUN pip install --no-cache-dir -r requirements.txt\n\nCOPY . /usr/src/app\n\nRUN chmod +x run.sh\n\nCMD [\"./run.sh\"]\n"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74493795",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20534381/"
] |
74,493,831
|
<p>I have a list of dicts</p>
<p>I need to search through the "Receiver" keys, and only output dicts that share the last X characters, inside the receiver value, with any other dict.</p>
<p>In this case, we search the last 3 characters of each Receiver value against all other Receiver values.</p>
<p>This is what i have so far</p>
<pre><code>transactions = [
{"Receiver":"alice111","Amount":50},
{"Receiver":"alice222","Amount":60},
{"Receiver":"alice111","Amount":70},
{"Receiver":"bob111","Amount":50},
{"Receiver":"bob222","Amount":150},
{"Receiver":"bob333","Amount":100},
{"Receiver":"kyle444","Amount":260},
{"Receiver":"richard555","Amount":260}
]
new_list=[]
for value in transactions:
receiver = value["Receiver"]
last_3 = receiver[-3:]
#print(receiver)
#print(last_3)
for substring in transactions:
if re.search(last_3 + r"$",substring["Receiver"]):
#print("MATCH" + str(substring))
new_list.append(substring)
print(new_list)
#[{'Receiver': 'alice111', 'Amount': 50}, {'Receiver': 'alice111', 'Amount': 70}, {'Receiver': 'bob111', 'Amount': 50}, {'Receiver': 'alice222', 'Amount': 60}, {'Receiver': 'bob222', 'Amount': 150}, {'Receiver': 'alice111', 'Amount': 50}, {'Receiver': 'alice111', 'Amount': 70}, {'Receiver': 'bob111', 'Amount': 50}, {'Receiver': 'alice111', 'Amount': 50}, {'Receiver': 'alice111', 'Amount': 70}, {'Receiver': 'bob111', 'Amount': 50}, {'Receiver': 'alice222', 'Amount': 60}, {'Receiver': 'bob222', 'Amount': 150}, {'Receiver': 'bob333', 'Amount': 100}, {'Receiver': 'kyle444', 'Amount': 260}, {'Receiver': 'richard555', 'Amount': 260}]
</code></pre>
<p>Unfortunately it's all wrong because it goes over the same values multiple times. With a longer list this would be a total disaster.</p>
<p>desired output</p>
<p><code>[{"Receiver":"alice111","Amount":50},{"Receiver":"alice222","Amount":60},{"Receiver":"alice111","Amount":70},{"Receiver":"bob111","Amount":50},{"Receiver":"bob222","Amount":150}]</code></p>
<p>The following should be omitted</p>
<pre><code>[{"Receiver":"bob333","Amount":100},{"Receiver":"kyle444","Amount":260},{"Receiver":"richard555","Amount":260}
]
</code></pre>
<p>As you can see, there is no "333" or "444" or "555" as the last characters in any other receiver value, so they are omitted, as i'm not interested in outputting uniques</p>
<p><code>Update: </code></p>
<p>what if i wish to match entries that DONT have the same preceeding prefix of characters (before the last 3 character suffix),</p>
<pre><code>transactions1 = [
{"Receiver":"alice111","Amount":50},
{"Receiver":"alice111","Amount":70},
{"Receiver":"bob222","Amount":50},
{"Receiver":"bob222","Amount":150},
{"Receiver":"bob222","Amount":100},
{"Receiver":"richard111","Amount":260},
{"Receiver":"bob333","Amount":100},
{"Receiver":"alice333","Amount":300},
]
</code></pre>
<p>new desired output:</p>
<p><code>[{"Receiver":"alice111","Amount":50}, {"Receiver":"alice111","Amount":70},{"Receiver":"richard111","Amount":50},{"Receiver":"bob333","Amount":100},{"Receiver":"alice333","Amount":300}]</code></p>
<p>So what's happening is we're only matching if :</p>
<p>-the last 3characters suffix matches AND a differnet name prefix exists</p>
<p>Hope that's clear.</p>
|
[
{
"answer_id": 74493890,
"author": "Jib",
"author_id": 20124358,
"author_profile": "https://Stackoverflow.com/users/20124358",
"pm_score": 0,
"selected": false,
"text": "CMD [\"bash\", \"-c\", \"./run.sh\"]"
},
{
"answer_id": 74494496,
"author": "David Maze",
"author_id": 10008173,
"author_profile": "https://Stackoverflow.com/users/10008173",
"pm_score": -1,
"selected": false,
"text": "command: version: '3.8'\nservices:\n producer:\n build: .\n command: ./producer.py\n consumer:\n build: .\n command: ./consumer.py\n test_conn:\n build: .\n command: ./test_conn.py\n chmod +x producer.py #!/usr/bin/env python3"
},
{
"answer_id": 74500531,
"author": "Martim Sousa",
"author_id": 20534381,
"author_profile": "https://Stackoverflow.com/users/20534381",
"pm_score": -1,
"selected": false,
"text": "RUN sed -i -e 's/\\r$//' run.sh CMD [\"bash\", \"-c\", \"./run.sh\"]"
},
{
"answer_id": 74502893,
"author": "zsolt",
"author_id": 4223799,
"author_profile": "https://Stackoverflow.com/users/4223799",
"pm_score": 0,
"selected": false,
"text": "FROM python:3.9\n\nRUN mkdir -p /usr/src/app\n\nWORKDIR /usr/src/app\n\nCOPY requirements.txt /usr/src/app\n\nRUN pip install --no-cache-dir -r requirements.txt\n\nCOPY . /usr/src/app\n\nRUN chmod +x run.sh\n\nCMD [\"./run.sh\"]\n"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74493831",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20525628/"
] |
74,493,865
|
<p>I have a DB with 106 entries and I can't seem to access the first 6 entries. I tried adding start_cursor and page_size keys to my request but they don't seem to have any effect. If I add them as ints the request gets rejected so I'm adding them as strings - not sure if this is the issue (I also tried converting to bytes). Whatever I do, it seems to return the last 100 results.</p>
<pre><code>import requests
_url = 'https://api.notion.com/v1/databases/xxxxx/query'
_header = {
'Authorization': _auth,
'Content-Type': 'application/json',
'Notion-Version': '2021-08-16',
'page_size': '3',
'start_cursor': '0'}
_result = requests.post(_url, headers=_header)
</code></pre>
<p>Any idea how I can get all the results, or change my request to get the first six results?</p>
|
[
{
"answer_id": 74493890,
"author": "Jib",
"author_id": 20124358,
"author_profile": "https://Stackoverflow.com/users/20124358",
"pm_score": 0,
"selected": false,
"text": "CMD [\"bash\", \"-c\", \"./run.sh\"]"
},
{
"answer_id": 74494496,
"author": "David Maze",
"author_id": 10008173,
"author_profile": "https://Stackoverflow.com/users/10008173",
"pm_score": -1,
"selected": false,
"text": "command: version: '3.8'\nservices:\n producer:\n build: .\n command: ./producer.py\n consumer:\n build: .\n command: ./consumer.py\n test_conn:\n build: .\n command: ./test_conn.py\n chmod +x producer.py #!/usr/bin/env python3"
},
{
"answer_id": 74500531,
"author": "Martim Sousa",
"author_id": 20534381,
"author_profile": "https://Stackoverflow.com/users/20534381",
"pm_score": -1,
"selected": false,
"text": "RUN sed -i -e 's/\\r$//' run.sh CMD [\"bash\", \"-c\", \"./run.sh\"]"
},
{
"answer_id": 74502893,
"author": "zsolt",
"author_id": 4223799,
"author_profile": "https://Stackoverflow.com/users/4223799",
"pm_score": 0,
"selected": false,
"text": "FROM python:3.9\n\nRUN mkdir -p /usr/src/app\n\nWORKDIR /usr/src/app\n\nCOPY requirements.txt /usr/src/app\n\nRUN pip install --no-cache-dir -r requirements.txt\n\nCOPY . /usr/src/app\n\nRUN chmod +x run.sh\n\nCMD [\"./run.sh\"]\n"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74493865",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/954835/"
] |
74,493,879
|
<p>I'm getting different errors running the code below (it counts the number of .mp3 files in each user directory):</p>
<pre><code> for us in /home/*
do
if [ -d $us ]
then
LT=$(find $us -name "*.jpg" -o -name "*.mp4" -o -name "*.mp3")
N_MP3=$("$LT" | grep "\.mp3$" | wc -l)
N_MP3=$($LT | grep "\.mp3$" | wc -l)
N_MP3=$(find $us -name "*.jpg" -o -name "*.mp4" -o -name "*.mp3" | grep "\.mp3$" | wc -l)
fi
done
</code></pre>
<p>Considerer that we have, in some user directory, let's say user=ubuntu, the files:</p>
<ul>
<li><strong>sample.jpg</strong></li>
<li><strong>sample.mp3</strong></li>
</ul>
<p>So let's run the code:</p>
<hr />
<p>(1) <strong>Doing "$LT" | ...</strong>, I get the message:</p>
<p><strong>/home/ubuntu/Desktop/Songs/sample.mp3 /home/ubuntu/Desktop/Images/sample.jpg: No such file or directory</strong></p>
<p>which means "$LT" command was executed and found all .mp4, .mp3 or .jpg files in my user and then gives that error.</p>
<hr />
<p>(2) <strong>Doing $LT | ...</strong>, which is <strong>equivalent</strong> to <strong>$(find $us -name "<em>.jpg" -o -name "</em>.mp4" -o -name "*.mp3") | ...</strong> I get the message <strong>/home/ubuntu/Desktop/Songs/sample.mp3: Permission denied</strong>. It means $LT command was executed and found only .mp3 file and then gives that error.</p>
<p>If I delete sample.jpg from my user=ubuntu, then in both cases I got the same error message: /home/ubuntu/Desktop/Songs/sample.mp3: Permission denied.</p>
<p>I know (but don't know why) I should use an echo command before $LT, but I'd like to know what's happening in theses cases which I didn't use echo before. Please, can someone shed a light on these errors?</p>
|
[
{
"answer_id": 74493890,
"author": "Jib",
"author_id": 20124358,
"author_profile": "https://Stackoverflow.com/users/20124358",
"pm_score": 0,
"selected": false,
"text": "CMD [\"bash\", \"-c\", \"./run.sh\"]"
},
{
"answer_id": 74494496,
"author": "David Maze",
"author_id": 10008173,
"author_profile": "https://Stackoverflow.com/users/10008173",
"pm_score": -1,
"selected": false,
"text": "command: version: '3.8'\nservices:\n producer:\n build: .\n command: ./producer.py\n consumer:\n build: .\n command: ./consumer.py\n test_conn:\n build: .\n command: ./test_conn.py\n chmod +x producer.py #!/usr/bin/env python3"
},
{
"answer_id": 74500531,
"author": "Martim Sousa",
"author_id": 20534381,
"author_profile": "https://Stackoverflow.com/users/20534381",
"pm_score": -1,
"selected": false,
"text": "RUN sed -i -e 's/\\r$//' run.sh CMD [\"bash\", \"-c\", \"./run.sh\"]"
},
{
"answer_id": 74502893,
"author": "zsolt",
"author_id": 4223799,
"author_profile": "https://Stackoverflow.com/users/4223799",
"pm_score": 0,
"selected": false,
"text": "FROM python:3.9\n\nRUN mkdir -p /usr/src/app\n\nWORKDIR /usr/src/app\n\nCOPY requirements.txt /usr/src/app\n\nRUN pip install --no-cache-dir -r requirements.txt\n\nCOPY . /usr/src/app\n\nRUN chmod +x run.sh\n\nCMD [\"./run.sh\"]\n"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74493879",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20488389/"
] |
74,493,898
|
<p>I want to change column names of a data frame with a function.</p>
<p>To overwrite my data frame with the new column names, I used assign(), which first argument has to be the name of the same data frame as a string. To get the name as a string, I used deparse(substitute(x)), which worked outside the function. But inside the function, it returns the content of my data frame as a string instead of the name itself...</p>
<pre><code>
df <- data.frame(
emp_id = c (1:5),
emp_name = c("Rick","Dan","Michelle","Ryan","Gary"),
stringsAsFactors = FALSE
)
deparse(substitute(df))
rename_fun <- function(x) {
colnames(x)[1] <- "___0"
colnames(x)[2] <- "___1"
y <- deparse(substitute(x))
assign(y, x, envir = .GlobalEnv)
}
rename_fun(df)
</code></pre>
<p>I also tried</p>
<pre><code>as.character(substitute(x))
</code></pre>
<p>but the same problem...</p>
|
[
{
"answer_id": 74493954,
"author": "akrun",
"author_id": 3732271,
"author_profile": "https://Stackoverflow.com/users/3732271",
"pm_score": 1,
"selected": false,
"text": "deparse/substitute rename_fun <- function(x) {\n y <- deparse(substitute(x))\n colnames(x)[1] <- \"___0\"\n colnames(x)[2] <- \"___1\" \n \n assign(y, x, envir = .GlobalEnv) \n}\n > rename_fun(df)\n> df\n ___0 ___1\n1 1 Rick\n2 2 Dan\n3 3 Michelle\n4 4 Ryan\n5 5 Gary\n"
},
{
"answer_id": 74493987,
"author": "Allan Cameron",
"author_id": 12500315,
"author_profile": "https://Stackoverflow.com/users/12500315",
"pm_score": 3,
"selected": true,
"text": "as.character(match.call()$x) rename_fun <- function(x) {\n colnames(x)[1] <- \"___0\"\n colnames(x)[2] <- \"___1\"\n assign(as.character(match.call()$x), x, envir = .GlobalEnv) \n}\n rename_fun(df)\n\ndf\n#> ___0 ___1\n#> 1 1 Rick\n#> 2 2 Dan\n#> 3 3 Michelle\n#> 4 4 Ryan\n#> 5 5 Gary\n rename_fun <- function(x) {\n \n colnames(x)[1] <- \"___0\"\n colnames(x)[2] <- \"___1\"\n x\n}\n df <- rename_fun(df)\n"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74493898",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20438103/"
] |
74,493,901
|
<p>The console error - "Uncaught SyntaxError: redeclaration of let sectionSelector"</p>
<p>The code -</p>
<pre><code><script type="text/javascript">
const sectionSelector = '#shopify-section-{{ section.id }}';
let collectionSelectors = document.querySelectorAll(`${sectionSelector} .recommendations__collection-selector`);
for (let collectionSelector of collectionSelectors) {
let blockId = collectionSelector.dataset.blockId;
let collectionCarousel = document.querySelector(`${sectionSelector} .recommendations__collection[data-block-id="${blockId}"]`);
let otherCarousels = document.querySelectorAll(`${sectionSelector} .recommendations__collection:not([data-block-id="${blockId}"])`);
collectionSelector.addEventListener('click', () => {
for (let otherCarousel of otherCarousels) {
otherCarousel.classList.remove('active');
}
for (let collectionSelector of collectionSelectors) {
collectionSelector.classList.remove('active');
}
collectionSelector.classList.add('active');
collectionCarousel.classList.add('active');
window.dispatchEvent(new Event('resize'));
})
}
</script>
</code></pre>
<p>I first changed <code>let sectionSelector</code> to <code>const</code>, that changes the error to collectionSelectors. This is the only reference to sectionSelector I have on the site, the error persists even if I have a single line -</p>
<pre><code> let sectionSelector = '#shopify-section-{{ section.id }}';
</code></pre>
<p>So my question is how is the variable being reassigned if there aren't any new declarations. I'm starting to think it has something to do with the for loops using for...of?</p>
|
[
{
"answer_id": 74493954,
"author": "akrun",
"author_id": 3732271,
"author_profile": "https://Stackoverflow.com/users/3732271",
"pm_score": 1,
"selected": false,
"text": "deparse/substitute rename_fun <- function(x) {\n y <- deparse(substitute(x))\n colnames(x)[1] <- \"___0\"\n colnames(x)[2] <- \"___1\" \n \n assign(y, x, envir = .GlobalEnv) \n}\n > rename_fun(df)\n> df\n ___0 ___1\n1 1 Rick\n2 2 Dan\n3 3 Michelle\n4 4 Ryan\n5 5 Gary\n"
},
{
"answer_id": 74493987,
"author": "Allan Cameron",
"author_id": 12500315,
"author_profile": "https://Stackoverflow.com/users/12500315",
"pm_score": 3,
"selected": true,
"text": "as.character(match.call()$x) rename_fun <- function(x) {\n colnames(x)[1] <- \"___0\"\n colnames(x)[2] <- \"___1\"\n assign(as.character(match.call()$x), x, envir = .GlobalEnv) \n}\n rename_fun(df)\n\ndf\n#> ___0 ___1\n#> 1 1 Rick\n#> 2 2 Dan\n#> 3 3 Michelle\n#> 4 4 Ryan\n#> 5 5 Gary\n rename_fun <- function(x) {\n \n colnames(x)[1] <- \"___0\"\n colnames(x)[2] <- \"___1\"\n x\n}\n df <- rename_fun(df)\n"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74493901",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5086257/"
] |
74,493,912
|
<p>I have a table with the following structure :</p>
<pre><code>create table test_18Nov ( account_id nvarchar(12)
, account_name nvarchar(25)
, zip_legacy_file nvarchar(5)
, Region_legacy_file nvarchar(30)
, zip_new_source nvarchar(5)
, Region_new_source nvarchar(30)
)
INSERT INTO test_18Nov VALUES ('S1018', 'John Smith', '32221', 'R087-Jacksonville', '33803', 'R026-Lakeland')
INSERT INTO test_18Nov VALUES ('S1018', 'John Smith', '33606', 'R011-Tampa', '32220', 'R087-Jacksonville')
INSERT INTO test_18Nov VALUES ('S1018', 'John Smith', '33803', 'R026-Lakeland', '33606', 'R011-Tampa')
INSERT INTO test_18Nov VALUES ('AC054', 'David Thompson', '33606', 'R011-Tampa', '32205', 'R087-Jacksonville')
INSERT INTO test_18Nov VALUES ('AC054', 'David Thompson', '33870', 'R058-Sebring', '33606', 'R011-Tampa')
INSERT INTO test_18Nov VALUES ('AC054', 'David Thompson', '33610', 'R011-Tampa', '33870', 'R058-Sebring')
INSERT INTO test_18Nov VALUES ('AC077', 'Stacey Leigh', '34950', 'R043-Fort Pierce', '34982', 'R043-Fort Pierce')
INSERT INTO test_18Nov VALUES ('AC077', 'Stacey Leigh', '33610', 'R011-Tampa', '34950', 'R043-Fort Pierce')
</code></pre>
<p>I have to generate a pseudo column for all rows with either Yes or No.
For an account id if the legacy region(or regions) is present in new source region(or regions) then the pseudo column will display 'No'. If for an account a new source region (or regions) is not present in legacy region (or regions) then the account will be considered as a move and the pseudo column will display 'Yes'. In the above data set AC054 is the only account id that should have the pseudo column value as 'Yes' because R087-Jacksonville (a new source region) is not present in the legacy region list.</p>
<p>The expected output should be :</p>
<pre><code>account_id | account_name | Region_legacy_file | Region_new_source | Will the account move? |
-------------------------------------------------------------------------------------------------------------
S1018 | John Smith | R087-Jacksonville | R026-Lakeland | No |
-------------------------------------------------------------------------------------------------------------
S1018 | John Smith | R011-Tampa | R087-Jacksonville | No |
-------------------------------------------------------------------------------------------------------------
S1018 | John Smith | R026-Lakeland | R011-Tampa | No |
-------------------------------------------------------------------------------------------------------------
AC054 | David Thompson | R011-Tampa | R087-Jacksonville | Yes |
-------------------------------------------------------------------------------------------------------------
AC054 | David Thompson | R058-Sebring | R011-Tampa | Yes |
-------------------------------------------------------------------------------------------------------------
AC054 | David Thompson | R011-Tampa | R058-Sebring | Yes |
-------------------------------------------------------------------------------------------------------------
AC077 | Stacey Leigh | R043-Fort Pierce | R043-Fort Pierce | No |
-------------------------------------------------------------------------------------------------------------
AC077 | Stacey Leigh | R011-Tampa | R043-Fort Pierce | No |
-------------------------------------------------------------------------------------------------------------
</code></pre>
<p>I thought of using NOT EXISTS clause but that will return only the rows where new source region is not found in the list of legacy regions for an account id - which is not of any help to me in this situation. Only way I can think of is using CASE WHEN EXISTS but have not been able to get it to work. If there is any other way please do share.</p>
<p>EDIT :
Why AC054 has the pseudo column as 'Yes'? - There are 3 new source regions for account id AC054 and they are R087, R011 and R058. Out of these 3 regions 2 regions are found in legacy regions for account id AC054 and they are R011 and R058. So R087 is not a part of legacy region list for account id AC054 and hence the pseudo column has 'Yes'. For the other 2 account ids that is not the case because all the new source regions are found in the legacy region list.</p>
|
[
{
"answer_id": 74494162,
"author": "T. van Schagen",
"author_id": 15649242,
"author_profile": "https://Stackoverflow.com/users/15649242",
"pm_score": -1,
"selected": false,
"text": "SELECT name, id, location, (SELECT TOP 1 'exists' FROM location l WHERE l.location = c.location) \nFROM customer c\n"
},
{
"answer_id": 74495135,
"author": "Diego",
"author_id": 20478349,
"author_profile": "https://Stackoverflow.com/users/20478349",
"pm_score": 3,
"selected": true,
"text": "WITH test_18Nov AS (\n SELECT * FROM (\n VALUES\n ('S1018', 'John Smith', '32221', 'R087-Jacksonville', '33803', 'R026-Lakeland'), \n ('S1018', 'John Smith', '33606', 'R011-Tampa', '32220', 'R087-Jacksonville'), \n ('S1018', 'John Smith', '33803', 'R026-Lakeland', '33606', 'R011-Tampa'), \n ('AC054', 'David Thompson', '33606', 'R011-Tampa', '32205', 'R087-Jacksonville'), \n ('AC054', 'David Thompson', '33870', 'R058-Sebring', '33606', 'R011-Tampa'),\n ('AC054', 'David Thompson', '33610', 'R011-Tampa', '33870', 'R058-Sebring'),\n ('AC077', 'Stacey Leigh', '34950', 'R043-Fort Pierce', '34982', 'R043-Fort Pierce'),\n ('AC077', 'Stacey Leigh', '33610', 'R011-Tampa', '34950', 'R043-Fort Pierce')\n ) AS _ (account_id,account_name, zip_legacy_file,Region_legacy_file,zip_new_source,Region_new_source)\n),\n--formatting the query for the field I need\nIdAndNewLegacy as (\n SELECT account_id, Region_new_source FROM test_18Nov\n),\n--check if some new legacy region is not in Region_legacy_file\nCheckLegacy as (\n SELECT I.account_id, T.account_id as id FROM IdAndNewLegacy as I\n LEFT JOIN test_18Nov as T ON I.account_id = T.account_id and I.Region_new_source = T.Region_legacy_file\n WHERE T.account_id is null\n GROUP BY I.account_id, T.account_id\n)\n--Query to present the data\nSELECT \n t.*,\n CASE WHEN c.account_id is not null then 'Yes' ELSE 'No' END as [Will the account move?]\nFROM \n test_18Nov as t\n LEFT JOIN CheckLegacy as c ON T.account_id = C.account_id \n"
},
{
"answer_id": 74496035,
"author": "MatBailie",
"author_id": 53341,
"author_profile": "https://Stackoverflow.com/users/53341",
"pm_score": 1,
"selected": false,
"text": "IIF() MAX(expression) OVER (PARTITION BY account_id) SELECT\n t.*,\n MAX(\n IIF(\n NOT EXISTS (\n SELECT *\n FROM Test_18Nov\n WHERE account_id = t.account_id\n AND region_legacy_file = t.region_new_source\n ),\n 'YES',\n 'NO'\n ) \n ) OVER (PARTITION BY t.account_id)\nFROM\n test_18Nov AS t\nORDER BY\n t.account_id,\n t.region_new_source\n"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74493912",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9839560/"
] |
74,493,930
|
<p>Theres' this html code:</p>
<pre><code><div class="wcpa_form_outer" data-attrrelated="[&quot;wcpa-select-1658734650073&quot;]">
</code></pre>
<p>for which i'm trying to append html to it. I have tried various approaches but none have worked.</p>
<pre><code>jQuery('.wcpa_form_outer[data-attrrelated="[&quot;wcpa-select-1658734650073&quot;]"]').append('some html here');
</code></pre>
<p>or</p>
<pre><code>jQuery('.wcpa_form_outer[data-attrrelated="[wcpa-select-1658734650073]"]').append('some html here');
</code></pre>
<p>or</p>
<pre><code>jQuery('.wcpa_form_outer').data('attrrelated').append('some html here');
</code></pre>
<p>any clues?</p>
|
[
{
"answer_id": 74494221,
"author": "KooiInc",
"author_id": 58186,
"author_profile": "https://Stackoverflow.com/users/58186",
"pm_score": 2,
"selected": false,
"text": "" [] $('[data-attrrelated*=\"1658734650073\"]')\n .append('some html here!');\n$('[data-attrrelated*=\"wcpa-select-165873465007\"')\n .append('<br>some html here too!'); <script src=\"https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js\"></script>\n\n<div class=\"wcpa_form_outer\" data-attrrelated=\"["wcpa-select-1658734650073"]\"></div>"
},
{
"answer_id": 74494300,
"author": "Tibrogargan",
"author_id": 2487517,
"author_profile": "https://Stackoverflow.com/users/2487517",
"pm_score": 2,
"selected": true,
"text": "" ["wcpa-select-1658734650073"] [\"wcpa-select-1658734650073\"] attr*=value attr=value '[\"' + value + '\"]' decodeEntities jQuery(`.wcpa_form_outer[data-attrrelated='[\"wcpa-select-1658734650073\"]']`).append('foo') <script src=\"https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js\"></script>\n<div class=\"wcpa_form_outer\" data-attrrelated=\"["wcpa-select-1658734650073"]\">append here: \n</div>"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74493930",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5032911/"
] |
74,493,933
|
<p>I am trying to Grant Admin Consent of a API in an Azure AD application through Graph API. I created the App, created its Client Secret, then created a Service Principal to which I want to add AppRoleAssignment.
The API call to do so requires three attributes in the body (<a href="https://learn.microsoft.com/en-us/graph/api/serviceprincipal-post-approleassignments?view=graph-rest-1.0&tabs=http" rel="nofollow noreferrer">Documentation</a>)</p>
<pre><code>GraphServiceClient graphClient = new GraphServiceClient( authProvider );
var appRoleAssignment = new AppRoleAssignment
{
PrincipalId = {Input the Service Principal Id},
ResourceId = {? Where to get this value?},
AppRoleId = {Input the App role of the API I added to my Azure AD App}
};
await graphClient.ServicePrincipals["{servicePrincipal-id}"].AppRoleAssignments
.Request()
.AddAsync(appRoleAssignment);
</code></pre>
<p>My question is where to get the ResourceId from? Knowing that this is different from one tenant to the other.
Please note that if I grant the admin consent manually, then run this API call</p>
<pre><code>var appRoleAssignments = GraphAppClient.ServicePrincipals[servicePrincipalId].AppRoleAssignments.Request().GetAsync().Result;
</code></pre>
<p>Then revoke the consent, get the ResourceId from what the API returned, and then use it in the original call, the admin consent works fine.</p>
|
[
{
"answer_id": 74494221,
"author": "KooiInc",
"author_id": 58186,
"author_profile": "https://Stackoverflow.com/users/58186",
"pm_score": 2,
"selected": false,
"text": "" [] $('[data-attrrelated*=\"1658734650073\"]')\n .append('some html here!');\n$('[data-attrrelated*=\"wcpa-select-165873465007\"')\n .append('<br>some html here too!'); <script src=\"https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js\"></script>\n\n<div class=\"wcpa_form_outer\" data-attrrelated=\"["wcpa-select-1658734650073"]\"></div>"
},
{
"answer_id": 74494300,
"author": "Tibrogargan",
"author_id": 2487517,
"author_profile": "https://Stackoverflow.com/users/2487517",
"pm_score": 2,
"selected": true,
"text": "" ["wcpa-select-1658734650073"] [\"wcpa-select-1658734650073\"] attr*=value attr=value '[\"' + value + '\"]' decodeEntities jQuery(`.wcpa_form_outer[data-attrrelated='[\"wcpa-select-1658734650073\"]']`).append('foo') <script src=\"https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js\"></script>\n<div class=\"wcpa_form_outer\" data-attrrelated=\"["wcpa-select-1658734650073"]\">append here: \n</div>"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74493933",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4985926/"
] |
74,493,938
|
<p>I have this dataframe that I wish to replace all the comma by dot, for example it would be 50.5 and 81.5.</p>
<pre><code> Unnamed: 0 NB Ppt Resale 5 yrs 10 yrs 15 yrs 20 yrs
1 VLCC 120 114 87 64 50,5 37
3 SUEZMAX 81,5 80 62 45 36 24
5 LR 2 69 72 57 42 32 20
7 AFRAMAX 66 68 55 40,5 30,5 19
9 LR 1 58 58 40 28 21 13,5
11 MR2 44 44,5 38 29 21 13
</code></pre>
<p>As dtypes for all the columns are object, I tried</p>
<pre><code>df_useful[['NB', 'Ppt Resale ', '5 yrs', '10 yrs', '15 yrs',
'20 yrs']] = df_useful[['NB', 'Ppt Resale ', '5 yrs', '10 yrs', '15 yrs',
'20 yrs']].apply(pd.to_numeric, errors='coerce')
</code></pre>
<p>then the numbers with comma would become <code>NAN</code>.</p>
|
[
{
"answer_id": 74494221,
"author": "KooiInc",
"author_id": 58186,
"author_profile": "https://Stackoverflow.com/users/58186",
"pm_score": 2,
"selected": false,
"text": "" [] $('[data-attrrelated*=\"1658734650073\"]')\n .append('some html here!');\n$('[data-attrrelated*=\"wcpa-select-165873465007\"')\n .append('<br>some html here too!'); <script src=\"https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js\"></script>\n\n<div class=\"wcpa_form_outer\" data-attrrelated=\"["wcpa-select-1658734650073"]\"></div>"
},
{
"answer_id": 74494300,
"author": "Tibrogargan",
"author_id": 2487517,
"author_profile": "https://Stackoverflow.com/users/2487517",
"pm_score": 2,
"selected": true,
"text": "" ["wcpa-select-1658734650073"] [\"wcpa-select-1658734650073\"] attr*=value attr=value '[\"' + value + '\"]' decodeEntities jQuery(`.wcpa_form_outer[data-attrrelated='[\"wcpa-select-1658734650073\"]']`).append('foo') <script src=\"https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js\"></script>\n<div class=\"wcpa_form_outer\" data-attrrelated=\"["wcpa-select-1658734650073"]\">append here: \n</div>"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74493938",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12131472/"
] |
74,493,975
|
<p>I have created a component which generates a Modal Dialog. As you may know, modal must be placed inside root (body) element as a child to defuse any parent styles.</p>
<p>To accomplish the process above, I use vanilla js to clone my Modal component and append it to body like so:</p>
<pre><code> useEffect(() => {
const modalInstance = document.getElementById('modal-instance-' + id);
if (modalInstance) {
const modal = modalInstance.cloneNode(true);
modal.id = 'modal-' + id;
const backdrop = document.createElement('div');
backdrop.id = 'modal-backdrop';
backdrop.className = 'hidden fixed top-0 bottom-0 start-0 end-0 bg-black bg-opacity-75 z-[59]';
backdrop.addEventListener('click', toggleModal);
document.body.appendChild(backdrop);
document.body.appendChild(modal);
const closeBtn = document.querySelector(`#modal-${id} > [data-close='modal']`);
closeBtn.addEventListener('click', toggleModal);
}
</code></pre>
<p>So far so good and Modal works perfectly; but problems start showing up when I pass elements with events as children to my Modal component.</p>
<pre><code><Modal id='someId' size='lg' show={showModal} setShow={setShowModal} title='some title'>
<ModalBody>
Hellowwww...
<Button onClick={() => alert('working')} type='button'>test</Button>
</ModalBody>
</Modal>
</code></pre>
<p>The above button has an <code>onClick</code> event that must be cloned when I clone the entire modal and append it to body.</p>
<h3>TL;DR</h3>
<p>Is there any other way to accomplish the same mechanism without vanilla js? If not, how can I resolve the problem?</p>
|
[
{
"answer_id": 74494298,
"author": "m4china",
"author_id": 15814542,
"author_profile": "https://Stackoverflow.com/users/15814542",
"pm_score": 0,
"selected": false,
"text": "createPortal ReactDom function Modal (props) {\n const wrapperRef = useRef<HTMLDivElement>(null);\n\n useIsomorphicEffect(() => {\n wrapperRef.current = document.getElementById(/* id of element */)\n }, []) \n \n return createPortal(<div>/* Modal content */ </div>, wrapperRef )\n\n}\n export const useIsomorphicEffect = typeof document !== 'undefined' ? useLayoutEffect : useEffect;"
},
{
"answer_id": 74494683,
"author": "Hooman",
"author_id": 6679820,
"author_profile": "https://Stackoverflow.com/users/6679820",
"pm_score": -1,
"selected": true,
"text": "import {useEffect, useState} from 'react';\nimport Button from '@/components/Button';\nimport {X} from 'react-bootstrap-icons';\nimport {createPortal} from 'react-dom';\n\nexport const Modal = ({id, title, className = '', size = 'md', show = false, setShow, children}) => {\n const [domReady, setDomReady] = useState(false);\n\n const sizeClass = {\n sm: 'top-28 bottom-28 start-2 end-2 sm:start-28 sm:end-28 sm:start-60 sm:end-60 xl:top-[7rem] xl:bottom-[7rem] xl:right-[20rem] xl:left-[20rem]',\n md: 'top-16 bottom-16 start-2 end-2 xl:top-[5rem] xl:bottom-[5rem] xl:right-[10rem] xl:left-[10rem]',\n lg: 'top-2 bottom-2 start-2 end-2 sm:top-3 sm:bottom-3 sm:start-3 sm:end-3 md:top-4 md:bottom-4 md:start-4 md:end-4 lg:top-5 lg:bottom-5 lg:start-5 lg:end-5',\n };\n\n useEffect(() => {\n setDomReady(true);\n }, []);\n\n return (\n domReady ?\n createPortal(\n <>\n <div className={`${show ? '' : 'hidden '}fixed top-0 bottom-0 start-0 end-0 bg-black bg-opacity-75 z-[59]`} onClick={() => setShow(false)}/>\n <div id={id}\n className={`${show ? '' : 'hidden '}fixed ${sizeClass[size]} bg-white dark:bg-gray-800 text-gray-600 dark:text-gray-200 drop-shadow-lg rounded-lg z-[60] ${className}`}>\n <Button\n className='absolute top-3 end-3'\n type='button'\n size='sm'\n color='secondaryOutlined'\n onClick={() => setShow(false)}\n ><X className='text-xl'/></Button>\n\n {title && <div className='absolute top-4 start-3 end-16 font-bold'>{title}</div>}\n <div>{children}</div>\n </div>\n </>\n , document.getElementById('modal-container'))\n : null\n );\n};\n\nexport const ModalBody = ({className = '', children}) => {\n return (\n <div className={`mt-10 p-3 ${className}`}>\n <div className='border-t border-gray-200 dark:border-gray-600 pt-3'>\n {children}\n </div>\n </div>\n );\n};\n _app.js <Html>\n <Head/>\n <body className='antialiased' dir='rtl'>\n <Main/>\n <div id='modal-container'/> <!-- Pay attention to this --!>\n <NextScript/>\n </body>\n</Html>\n <Modal id='someId' size='lg' show={showModal} setShow={setShowModal} title='Some title'>\n <ModalBody>\n Hellowwww...\n <Button onClick={() => alert('working')} type='button'>Test</Button>\n </ModalBody>\n</Modal>\n tailwindcss react-bootstrap-icons"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74493975",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6679820/"
] |
74,493,986
|
<p>I am looking to merge all rows corresponding to the same year and location into one that represents the average.</p>
<p>Let's say this is my data frame</p>
<pre><code>data<-data.frame(year=c(2000,2000,2000,2000,2001,2001,2001,2001,2002,2002,2002,2002),
location=c(1,1,2,2,1,1,2,2,1,1,2,2),
x=c(1,2,3,4,5,6,7,8,9,10,11,12))
</code></pre>
<p>I want to merge all rows that are representative of the same year (f.e. 2000) and the same location (f.e. 1) into one. The x-value of this new row should be the average of the x-values of the merged rows.</p>
<p>Unfortunately I have no idea how to do this and haven't been able to find a way in documentation or online.</p>
|
[
{
"answer_id": 74494034,
"author": "Jilber Urbina",
"author_id": 1315767,
"author_profile": "https://Stackoverflow.com/users/1315767",
"pm_score": 2,
"selected": false,
"text": " library(dplyr)\n data %>% \n group_by(year, location) %>% \n summarise(x_mean = mean(x)) %>% \n ungroup()\n`summarise()` has grouped output by 'year'. You can override using the `.groups` argument.\n# A tibble: 6 × 3\n year location x_mean\n <dbl> <dbl> <dbl>\n1 2000 1 1.5\n2 2000 2 3.5\n3 2001 1 5.5\n4 2001 2 7.5\n5 2002 1 9.5\n6 2002 2 11.5\n"
},
{
"answer_id": 74494094,
"author": "Andre Wildberg",
"author_id": 9462095,
"author_profile": "https://Stackoverflow.com/users/9462095",
"pm_score": 0,
"selected": false,
"text": "aggregate(data, list(data$year, data$location), mean)[, -c(1:2)]\n year location x\n1 2000 1 1.5\n2 2001 1 5.5\n3 2002 1 9.5\n4 2000 2 3.5\n5 2001 2 7.5\n6 2002 2 11.5\n dplyr library(dplyr)\n\ndata %>% \n group_by(year, location) %>% \n summarize(x = mean(x), .groups = \"drop\")\n# A tibble: 6 × 3\n year location x\n <dbl> <dbl> <dbl>\n1 2000 1 1.5\n2 2000 2 3.5\n3 2001 1 5.5\n4 2001 2 7.5\n5 2002 1 9.5\n6 2002 2 11.5\n"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74493986",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20533425/"
] |
74,494,036
|
<p>I need to style the markup (without changing it) mentioned below according to the screenshot. Text is not supposed to go under the checkbox, it must be aligned to the red line shown on my screenshot. How to do that?</p>
<p><a href="https://i.stack.imgur.com/zpTIv.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/zpTIv.png" alt="enter image description here" /></a></p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>.custom-checkbox {
width: 24px;
height: 24px;
background: blue;
border: 2px solid gray;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
<label class="custom-label">
<div class="custom-checkbox"></div>
Didn’t plan to pass the course. Just wanted to see wDidn’t plan to pass the course. Just wanted to see what is insideDidn’t plan to pass the course. Just wanted to see what is insideDidn’t plan to pass the course. Just wanted to see what is insideDidn’t plan to pass the course. Just wanted to see what is insideDidn’t plan to pass the course. Just wanted to see what is insidehat is insideDidn’t plan to pass the course. Just wanted to see what is inside
</label>
</div></code></pre>
</div>
</div>
</p>
|
[
{
"answer_id": 74494138,
"author": "John",
"author_id": 11111119,
"author_profile": "https://Stackoverflow.com/users/11111119",
"pm_score": 2,
"selected": true,
"text": ".custom-checkbox {\n width: 24px;\n height: 24px;\n background: blue;\n border: 2px solid gray;\n}\n\n.custom-label {\n display: grid;\n grid-template-columns: auto auto;\n} <div>\n <label class=\"custom-label\">\n <div class=\"custom-checkbox\"></div> \n Didn’t plan to pass the course. Just wanted to see wDidn’t plan to pass the course. Just wanted to see what is insideDidn’t plan to pass the course. Just wanted to see what is insideDidn’t plan to pass the course. Just wanted to see what is insideDidn’t plan to pass the course. Just wanted to see what is insideDidn’t plan to pass the course. Just wanted to see what is insidehat is insideDidn’t plan to pass the course. Just wanted to see what is inside\n </label>\n</div>"
},
{
"answer_id": 74494144,
"author": "wjatek",
"author_id": 4636502,
"author_profile": "https://Stackoverflow.com/users/4636502",
"pm_score": 0,
"selected": false,
"text": " .custom-label {\n display: flex;\n }\n\n .custom-label p {\n margin-top: 0;\n }\n\n .custom-checkbox {\n width: 24px;\n height: 24px;\n background: blue;\n border: 2px solid gray;\n flex-shrink: 0;\n } <div>\n <label class=\"custom-label\">\n <div class=\"custom-checkbox\"></div>\n <p>Didn’t plan to pass the course. Just wanted to see wDidn’t plan to pass the course. Just wanted to see what is insideDidn’t plan to pass the course. Just wanted to see what is insideDidn’t plan to pass the course. Just wanted to see what is insideDidn’t plan to pass the course. Just wanted to see what is insideDidn’t plan to pass the course. Just wanted to see what is insidehat is insideDidn’t plan to pass the course. Just wanted to see what is inside</p>\n </label>\n </div>"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74494036",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6678962/"
] |
74,494,073
|
<p>I need to put the value of variable "A" in place of the NA of variable "B".<br />
Example of my dataframe:</p>
<pre><code>> df <- data.frame(A = seq(1, 10), B = c(1, NA, 3, 4, NA, NA, 7, 8, NA, NA))
> df
A B
1 1 1
2 2 NA
3 3 3
4 4 4
5 5 NA
6 6 NA
7 7 7
8 8 8
9 9 NA
10 10 NA
</code></pre>
<p>I want the above dataframe converted into this:</p>
<pre><code>> df
A B
1 1 1
2 2 2
3 3 3
4 4 4
5 5 5
6 6 6
7 7 7
8 8 8
9 9 9
10 10 10
</code></pre>
|
[
{
"answer_id": 74494138,
"author": "John",
"author_id": 11111119,
"author_profile": "https://Stackoverflow.com/users/11111119",
"pm_score": 2,
"selected": true,
"text": ".custom-checkbox {\n width: 24px;\n height: 24px;\n background: blue;\n border: 2px solid gray;\n}\n\n.custom-label {\n display: grid;\n grid-template-columns: auto auto;\n} <div>\n <label class=\"custom-label\">\n <div class=\"custom-checkbox\"></div> \n Didn’t plan to pass the course. Just wanted to see wDidn’t plan to pass the course. Just wanted to see what is insideDidn’t plan to pass the course. Just wanted to see what is insideDidn’t plan to pass the course. Just wanted to see what is insideDidn’t plan to pass the course. Just wanted to see what is insideDidn’t plan to pass the course. Just wanted to see what is insidehat is insideDidn’t plan to pass the course. Just wanted to see what is inside\n </label>\n</div>"
},
{
"answer_id": 74494144,
"author": "wjatek",
"author_id": 4636502,
"author_profile": "https://Stackoverflow.com/users/4636502",
"pm_score": 0,
"selected": false,
"text": " .custom-label {\n display: flex;\n }\n\n .custom-label p {\n margin-top: 0;\n }\n\n .custom-checkbox {\n width: 24px;\n height: 24px;\n background: blue;\n border: 2px solid gray;\n flex-shrink: 0;\n } <div>\n <label class=\"custom-label\">\n <div class=\"custom-checkbox\"></div>\n <p>Didn’t plan to pass the course. Just wanted to see wDidn’t plan to pass the course. Just wanted to see what is insideDidn’t plan to pass the course. Just wanted to see what is insideDidn’t plan to pass the course. Just wanted to see what is insideDidn’t plan to pass the course. Just wanted to see what is insideDidn’t plan to pass the course. Just wanted to see what is insidehat is insideDidn’t plan to pass the course. Just wanted to see what is inside</p>\n </label>\n </div>"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74494073",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16386488/"
] |
74,494,099
|
<p>I have a github repo that got an accidental force push on a branch.</p>
<p>The PR of this branch shows both the new and the old commit and i even can browse the files of this commit - so everything is still be there.</p>
<p>Can i somehow add a branchname to this commit, so that it can get checked out normally (and at the end correct the messed up initial branch)?</p>
|
[
{
"answer_id": 74494138,
"author": "John",
"author_id": 11111119,
"author_profile": "https://Stackoverflow.com/users/11111119",
"pm_score": 2,
"selected": true,
"text": ".custom-checkbox {\n width: 24px;\n height: 24px;\n background: blue;\n border: 2px solid gray;\n}\n\n.custom-label {\n display: grid;\n grid-template-columns: auto auto;\n} <div>\n <label class=\"custom-label\">\n <div class=\"custom-checkbox\"></div> \n Didn’t plan to pass the course. Just wanted to see wDidn’t plan to pass the course. Just wanted to see what is insideDidn’t plan to pass the course. Just wanted to see what is insideDidn’t plan to pass the course. Just wanted to see what is insideDidn’t plan to pass the course. Just wanted to see what is insideDidn’t plan to pass the course. Just wanted to see what is insidehat is insideDidn’t plan to pass the course. Just wanted to see what is inside\n </label>\n</div>"
},
{
"answer_id": 74494144,
"author": "wjatek",
"author_id": 4636502,
"author_profile": "https://Stackoverflow.com/users/4636502",
"pm_score": 0,
"selected": false,
"text": " .custom-label {\n display: flex;\n }\n\n .custom-label p {\n margin-top: 0;\n }\n\n .custom-checkbox {\n width: 24px;\n height: 24px;\n background: blue;\n border: 2px solid gray;\n flex-shrink: 0;\n } <div>\n <label class=\"custom-label\">\n <div class=\"custom-checkbox\"></div>\n <p>Didn’t plan to pass the course. Just wanted to see wDidn’t plan to pass the course. Just wanted to see what is insideDidn’t plan to pass the course. Just wanted to see what is insideDidn’t plan to pass the course. Just wanted to see what is insideDidn’t plan to pass the course. Just wanted to see what is insideDidn’t plan to pass the course. Just wanted to see what is insidehat is insideDidn’t plan to pass the course. Just wanted to see what is inside</p>\n </label>\n </div>"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74494099",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2331592/"
] |
74,494,168
|
<p>so I'm having my first experience with react native, and I'm creating an app that gathers user input and renders a collection of strings with the form parameters, but when I try to fill the input fields I keep having the same error:</p>
<pre><code>Cannot read property 'value' of undefined
</code></pre>
<p>on form handling, how should I work around this? thanks for the attention.
here's the code:</p>
<pre><code>import {React, useState} from 'react';
import {
TextInput,
View,
Text,
SafeAreaView,
StyleSheet,
Button,
ScrollView,
} from 'react-native';
const Home = () => {
const [lines, setlines] = useState([
{
text: 'This is a default string',
fontSize: 32,
color: '#000000',
},
]);
const [line, setline] = useState({
text: '',
fontSize: '',
color: '',
});
const handleSubmit = e => {
setlines({...lines, line});
};
return (
<View>
<SafeAreaView>
<Text style={styles.desc}>Insert your quote here:</Text>
<TextInput
style={styles.input}
value={line?.text}
onChangeText={e => setline({...line, [line?.text]: e.target.value})}
/>
<Text style={styles.desc}>Insert choose font size:</Text>
<TextInput
keyboardType="numeric"
style={styles.input}
value={line?.fontSize}
maxLength={3}
onChangeText={e =>
setline({...line, [line?.fontSize]: parseInt(e.target.value, 10)})
}
/>
<Text style={styles.desc}>Insert choose Hex color:</Text>
<TextInput
style={styles.input}
value={`#${line?.color}`}
maxLength={7}
onChangeText={e => setline({...line, [line?.color]: e.target.value})}
/>
<Button
onPress={handleSubmit}
title="Generate paragraph"
color="#841584"
/>
</SafeAreaView>
<ScrollView>
{lines.map((myLine, index) => (
<Text
key={index}
// eslint-disable-next-line react-native/no-inline-styles
style={{
fontSize: myLine.fontSize,
color: myLine.color,
margin: 15,
}}>
{myLine.text}
</Text>
))}
</ScrollView>
</View>
);
};
const styles = StyleSheet.create({
input: {
height: 40,
margin: 12,
borderWidth: 1,
padding: 10,
},
desc: {
height: 40,
margin: 'auto',
padding: 10,
},
});
export default Home;
</code></pre>
<p>Tried to handle the inputs inline, but didn't solve the problem</p>
|
[
{
"answer_id": 74494874,
"author": "Artem Golendukhin",
"author_id": 9731103,
"author_profile": "https://Stackoverflow.com/users/9731103",
"pm_score": 1,
"selected": true,
"text": "import {React, useState} from 'react';\nimport {\n TextInput,\n View,\n Text,\n SafeAreaView,\n StyleSheet,\n Button,\n ScrollView,\n} from 'react-native';\n\nconst Home = () => {\n const [lines, setlines] = useState([\n {\n text: 'This is a default string',\n fontSize: 32,\n color: '#000000',\n },\n ]);\n const [line, setline] = useState({\n text: '',\n fontSize: '',\n color: '',\n });\n\n const handleSubmit = e => {\n setlines([...lines, line]);\n };\n\n return (\n <View>\n <SafeAreaView>\n <Text style={styles.desc}>Insert your quote here:</Text>\n <TextInput\n style={styles.input}\n value={line.text}\n onChangeText={text => setline({...line, text })}\n />\n <Text style={styles.desc}>Insert choose font size:</Text>\n <TextInput\n keyboardType=\"numeric\"\n style={styles.input}\n value={line.fontSize}\n maxLength={3}\n onChangeText={fontSizeStr =>\n setline({...line, fontSize: parseInt(fontSizeStr, 10)})\n }\n />\n <Text style={styles.desc}>Insert choose Hex color:</Text>\n <TextInput\n style={styles.input}\n value={line.color}\n maxLength={7}\n onChangeText={color => setline({...line, color })}\n />\n <Button\n onPress={handleSubmit}\n title=\"Generate paragraph\"\n color=\"#841584\"\n />\n </SafeAreaView>\n <ScrollView>\n {lines.map((myLine, index) => (\n <Text\n key={index}\n // eslint-disable-next-line react-native/no-inline-styles\n style={{\n fontSize: myLine.fontSize,\n color: '#' + myLine.color,\n margin: 15,\n }}>\n {myLine.text}\n </Text>\n ))}\n </ScrollView>\n </View>\n );\n};\n\nconst styles = StyleSheet.create({\n input: {\n height: 40,\n margin: 12,\n borderWidth: 1,\n padding: 10,\n },\n desc: {\n height: 40,\n margin: 'auto',\n padding: 10,\n },\n});\n\nexport default Home;\n"
},
{
"answer_id": 74495811,
"author": "Muhammad Usman",
"author_id": 7769653,
"author_profile": "https://Stackoverflow.com/users/7769653",
"pm_score": 1,
"selected": false,
"text": "onChangeText callback functions text TextInput e.target ReactJs"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74494168",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20542363/"
] |
74,494,202
|
<p>While adding an absolute path to my script because it has a \f in it the code won't run properly.</p>
<pre><code>C:\Users\showoi\Desktop\website\repository\fileAdder\softwarelisting.xlsx
</code></pre>
<p>The file is in the same directory as the script but using a relative path won't work. No misspellings or anything.</p>
|
[
{
"answer_id": 74494874,
"author": "Artem Golendukhin",
"author_id": 9731103,
"author_profile": "https://Stackoverflow.com/users/9731103",
"pm_score": 1,
"selected": true,
"text": "import {React, useState} from 'react';\nimport {\n TextInput,\n View,\n Text,\n SafeAreaView,\n StyleSheet,\n Button,\n ScrollView,\n} from 'react-native';\n\nconst Home = () => {\n const [lines, setlines] = useState([\n {\n text: 'This is a default string',\n fontSize: 32,\n color: '#000000',\n },\n ]);\n const [line, setline] = useState({\n text: '',\n fontSize: '',\n color: '',\n });\n\n const handleSubmit = e => {\n setlines([...lines, line]);\n };\n\n return (\n <View>\n <SafeAreaView>\n <Text style={styles.desc}>Insert your quote here:</Text>\n <TextInput\n style={styles.input}\n value={line.text}\n onChangeText={text => setline({...line, text })}\n />\n <Text style={styles.desc}>Insert choose font size:</Text>\n <TextInput\n keyboardType=\"numeric\"\n style={styles.input}\n value={line.fontSize}\n maxLength={3}\n onChangeText={fontSizeStr =>\n setline({...line, fontSize: parseInt(fontSizeStr, 10)})\n }\n />\n <Text style={styles.desc}>Insert choose Hex color:</Text>\n <TextInput\n style={styles.input}\n value={line.color}\n maxLength={7}\n onChangeText={color => setline({...line, color })}\n />\n <Button\n onPress={handleSubmit}\n title=\"Generate paragraph\"\n color=\"#841584\"\n />\n </SafeAreaView>\n <ScrollView>\n {lines.map((myLine, index) => (\n <Text\n key={index}\n // eslint-disable-next-line react-native/no-inline-styles\n style={{\n fontSize: myLine.fontSize,\n color: '#' + myLine.color,\n margin: 15,\n }}>\n {myLine.text}\n </Text>\n ))}\n </ScrollView>\n </View>\n );\n};\n\nconst styles = StyleSheet.create({\n input: {\n height: 40,\n margin: 12,\n borderWidth: 1,\n padding: 10,\n },\n desc: {\n height: 40,\n margin: 'auto',\n padding: 10,\n },\n});\n\nexport default Home;\n"
},
{
"answer_id": 74495811,
"author": "Muhammad Usman",
"author_id": 7769653,
"author_profile": "https://Stackoverflow.com/users/7769653",
"pm_score": 1,
"selected": false,
"text": "onChangeText callback functions text TextInput e.target ReactJs"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74494202",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20530266/"
] |
74,494,228
|
<p>In XML, Html and Co you need to specify which tag you want to close.
For Example:</p>
<pre><code><A>
<B>
</B>
</A>
<C>
</C>
</code></pre>
<p>But logically you could leave them away like this:</p>
<pre><code><A>
<B>
</>
</>
<C>
</>
</code></pre>
<p>The transfered information would be same, which should be crucial in a data format like xml. It seems illogical to me to increase the data size by up to 10% or so just to make it a bit more readable. So why is it like that?</p>
|
[
{
"answer_id": 74494874,
"author": "Artem Golendukhin",
"author_id": 9731103,
"author_profile": "https://Stackoverflow.com/users/9731103",
"pm_score": 1,
"selected": true,
"text": "import {React, useState} from 'react';\nimport {\n TextInput,\n View,\n Text,\n SafeAreaView,\n StyleSheet,\n Button,\n ScrollView,\n} from 'react-native';\n\nconst Home = () => {\n const [lines, setlines] = useState([\n {\n text: 'This is a default string',\n fontSize: 32,\n color: '#000000',\n },\n ]);\n const [line, setline] = useState({\n text: '',\n fontSize: '',\n color: '',\n });\n\n const handleSubmit = e => {\n setlines([...lines, line]);\n };\n\n return (\n <View>\n <SafeAreaView>\n <Text style={styles.desc}>Insert your quote here:</Text>\n <TextInput\n style={styles.input}\n value={line.text}\n onChangeText={text => setline({...line, text })}\n />\n <Text style={styles.desc}>Insert choose font size:</Text>\n <TextInput\n keyboardType=\"numeric\"\n style={styles.input}\n value={line.fontSize}\n maxLength={3}\n onChangeText={fontSizeStr =>\n setline({...line, fontSize: parseInt(fontSizeStr, 10)})\n }\n />\n <Text style={styles.desc}>Insert choose Hex color:</Text>\n <TextInput\n style={styles.input}\n value={line.color}\n maxLength={7}\n onChangeText={color => setline({...line, color })}\n />\n <Button\n onPress={handleSubmit}\n title=\"Generate paragraph\"\n color=\"#841584\"\n />\n </SafeAreaView>\n <ScrollView>\n {lines.map((myLine, index) => (\n <Text\n key={index}\n // eslint-disable-next-line react-native/no-inline-styles\n style={{\n fontSize: myLine.fontSize,\n color: '#' + myLine.color,\n margin: 15,\n }}>\n {myLine.text}\n </Text>\n ))}\n </ScrollView>\n </View>\n );\n};\n\nconst styles = StyleSheet.create({\n input: {\n height: 40,\n margin: 12,\n borderWidth: 1,\n padding: 10,\n },\n desc: {\n height: 40,\n margin: 'auto',\n padding: 10,\n },\n});\n\nexport default Home;\n"
},
{
"answer_id": 74495811,
"author": "Muhammad Usman",
"author_id": 7769653,
"author_profile": "https://Stackoverflow.com/users/7769653",
"pm_score": 1,
"selected": false,
"text": "onChangeText callback functions text TextInput e.target ReactJs"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74494228",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15545451/"
] |
74,494,263
|
<p>I have a dataframe and I am pulling out a specific column with the index. I want to perform a split on that column and get the [1] value.</p>
<p>The column looks like;</p>
<pre><code>Name
t_alpaha_omega
t_bravo_omega
d_charlie_omega
t_delta_omega
</code></pre>
<p>I need to split on _ and get alpha, bravo, charlie, delta. Then add those values as a new column in my dataframe.</p>
<p>I am getting the name column like;</p>
<pre><code>
final_df.loc[:,"Name"]
</code></pre>
<p>I can do the splitting, I just don't know how to insert the data as a new column.</p>
<p>I am playing with this and seeing if I can use a variation of it.</p>
<pre><code>final_df.insert(1, "Test", final_df.loc[:,"Name"], True)
</code></pre>
|
[
{
"answer_id": 74494294,
"author": "Anoushiravan R",
"author_id": 14314520,
"author_profile": "https://Stackoverflow.com/users/14314520",
"pm_score": 1,
"selected": true,
"text": "(?P<New_Column_Name>...) df['Value'] = df.Name.str.extract('(?P<Value>(?<=_)\\w+(?=_))')\ndf\n\n Name Value\n0 t_alpaha_omega alpaha\n1 t_bravo_omega bravo\n2 t_charlie_omega charlie\n3 t_delta_omega delta\n new_column = df.pop('Value')\ndf.insert(0, 'Value', new_column)\n\n Value Name\n0 alpaha t_alpaha_omega\n1 bravo t_bravo_omega\n2 charlie t_charlie_omega\n3 delta t_delta_omega\n"
},
{
"answer_id": 74494346,
"author": "Harishma Ashok",
"author_id": 20403698,
"author_profile": "https://Stackoverflow.com/users/20403698",
"pm_score": 1,
"selected": false,
"text": "newCol= [] \nfor i in range(len(df)):\n a = df.iloc[i].to_list()\n requiredValue = a.split(\"_\")[1]\n newCol.append(requiredValue)\ndf[\"newValue\"] = requiredValue\n"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74494263",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20497632/"
] |
74,494,281
|
<p>If I have multiple variables and I want to pull certain properties from all of them in a single view (for instance their Count), how would one do this?</p>
<p>For example, if I want something like the following</p>
<pre><code># Table Format
Name Count
Variable1 $Variable1.Count
Variable2 $Variable2.Count
Variable3 $Variable3.Count
# List Format
Name : Variable1
Count : $Variable1.Count
Name : Variable2
Count : $Variable2.Count
Name : Variable3
Count : $Variable3.Count
# Variables are ArrayLists, hence the Count property
</code></pre>
<p>I thought this would be fairly trivial using the standard select-object, format-list or format-table cmdlets and use of calculated properties, but I just cannot get it to work as expected.</p>
<p>This was my first thought:</p>
<pre><code>Format-List @{N='Variable1';E={$Variable1.Count}}, @{N='Variable2';E={$Variable2.Count}}
</code></pre>
<p>I guess those cmdlets cannot be called without piping something to them first, so then I tried the following, and it did what I wanted, however it seems to keep looping endlessly, outputting the results over and over and over.</p>
<pre><code>@($Variable1, $Variable2) | Format-List @{N='Variable1';E={$Variable1.Count}}, @{N='Variable2';E={$Variable2.Count}}
</code></pre>
<p>Is there something stupid/simple I'm overlooking here?</p>
|
[
{
"answer_id": 74494431,
"author": "Abraham Zinala",
"author_id": 14903754,
"author_profile": "https://Stackoverflow.com/users/14903754",
"pm_score": 3,
"selected": true,
"text": "Get-Variable $variable1 = 1..10\n$variable2 = 5..15\n$variable3 = 10..20\nGet-Variable -Name variable1,variable2,variable3 | \n Format-List -Property Name, @{\n Name = 'Count'\n Expression = { $_.Value.Count }\n }\n Format-List Name : variable1\nCount : 10\n\nName : variable2\nCount : 11\n\nName : variable3\nCount : 11\n Format-Table Name Count\n---- -----\nvariable1 10\nvariable2 11\nvariable3 11\n"
},
{
"answer_id": 74494642,
"author": "jdweng",
"author_id": 5015238,
"author_profile": "https://Stackoverflow.com/users/5015238",
"pm_score": 0,
"selected": false,
"text": "$table = [System.Collections.ArrayList]::new()\nfor($i = 0; $i -le 10000; $i++)\n{\n $newRow = New-Object -TypeName psobject\n $number = Get-Random -Minimum 1 -Maximum 100\n $newRow | Add-Member -NotePropertyName Name -NotePropertyValue (\"Variable\" + $number)\n $table.Add($newRow) | Out-Null \n}\n$groups = $table | Sort-Object -Property Name | Group-Object {$_.Name}\n$tableCount = [System.Collections.ArrayList]::new()\nforeach($group in $groups)\n{\n $newRow = New-Object -TypeName psobject\n $newRow | Add-Member -NotePropertyName Name -NotePropertyValue $group.Name\n $newRow | Add-Member -NotePropertyName Count -NotePropertyValue $group.Count\n $tableCount.Add($newRow) | Out-Null \n\n}\n$tableCount | Format-Table\n"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74494281",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11125687/"
] |
74,494,293
|
<p>I want the values in the array to be between 1 & 100 because they’re grades for a test. How do I do this? Is it possible?</p>
<p>I’ve used a for loop to take in the contents of the array</p>
|
[
{
"answer_id": 74494327,
"author": "Giusek keisuG",
"author_id": 18689184,
"author_profile": "https://Stackoverflow.com/users/18689184",
"pm_score": -1,
"selected": false,
"text": "int[] array = new int[100];\n List<int> list = new List<int>();\n"
},
{
"answer_id": 74494573,
"author": "Narish",
"author_id": 12229910,
"author_profile": "https://Stackoverflow.com/users/12229910",
"pm_score": 0,
"selected": false,
"text": "int[] rawGrades = {100, 87, 999};\nint[] validGrades = rawGrades\n .Where(g => g <= 100 && g >=0)\n .ToArray(); // {100, 87}\n Grade Score public class Grade\n{\n private int _score;\n public int Score\n {\n get => _score;\n set => _score = value >= 0 && value <= 100 ? value : throw new ArgumentException(\"Grades must be from 0-100 inclusive\");\n }\n}\n\nGrade[] grades = new Grade[];\ngrades[0] = new Grade { Score = 99 }; //valid\ngrades[1] = new Grade { Score = 99999 }; //invalid, will throw exception\n\n//get the grades as int's with some LINQ also\nint[] scores = grades.Select(g => g.Score).ToArray()\n"
},
{
"answer_id": 74494582,
"author": "Scott Hannen",
"author_id": 5101046,
"author_profile": "https://Stackoverflow.com/users/5101046",
"pm_score": 0,
"selected": false,
"text": "int single decimal public class TestScore\n{\n public byte Score { get; }\n\n public TestScore(byte score)\n {\n if (score < 1 || score > 100)\n {\n throw new ArgumentOutOfRangeException(\n $\"{nameof(score)} must be in the range of 1 to 100.\");\n }\n Score = score;\n }\n}\n TestScore Score TestScore TestScore var testScores = new TestScore[5];\n var testScores = new List<TestScore>();\n byte int single single"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74494293",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20542482/"
] |
74,494,301
|
<p>I would like to be able to keep NAs for only groups that have more than two entries and just want to leave alone any groups that have 1 entry (regardless if they have NAs or not). That is, if the group has two elements, keep only the NA. If it has one then just take whatever is there. Here is a reprex of the type of data I have:</p>
<pre class="lang-r prettyprint-override"><code>library(dplyr)
data <- data.frame(
x = c(1, NA_real_, 3, NA_real_),
y = c("grp1", "grp2", "grp2", "grp3")
)
data
#> x y
#> 1 1 grp1
#> 2 NA grp2
#> 3 3 grp2
#> 4 NA grp3
</code></pre>
<p>Then here is the fairly ugly way I have achieved what I want:</p>
<pre class="lang-r prettyprint-override"><code>raw <- data %>%
group_by(y) %>%
mutate(n = n())
results <- bind_rows(
raw %>%
filter(n == 2) %>%
filter(is.na(x)),
raw %>%
filter(n == 1)
) %>%
ungroup() %>%
select(-n)
results
#> # A tibble: 3 × 2
#> x y
#> <dbl> <chr>
#> 1 NA grp2
#> 2 1 grp1
#> 3 NA grp3
</code></pre>
|
[
{
"answer_id": 74494395,
"author": "TarJae",
"author_id": 13321647,
"author_profile": "https://Stackoverflow.com/users/13321647",
"pm_score": 2,
"selected": false,
"text": "! == > library(dplyr)\ndata %>% \n group_by(y) %>% \n filter(!(!is.na(x) & n() > 1))\n\n x y \n <dbl> <chr>\n1 1 grp1 \n2 NA grp2 \n3 NA grp3 \n filter max(row_number() max(row_number() n() library(dplyr)\ndata %>% \n group_by(y) %>% \n filter(!(is.na(x) & n() == 1))\n # filter(!(is.na(x) & max(row_number()) == 1))\n x y \n <dbl> <chr>\n1 1 grp1 \n2 NA grp2 \n3 3 grp2 \n"
},
{
"answer_id": 74494423,
"author": "Josh White",
"author_id": 20289207,
"author_profile": "https://Stackoverflow.com/users/20289207",
"pm_score": 3,
"selected": true,
"text": "data %>% \n group_by(y) %>% \n filter(!(!is.na(x) & n() > 1))\n # A tibble: 3 × 2\n# Groups: y [3]\n x y \n <dbl> <chr>\n1 1 grp1 \n2 NA grp2 \n3 NA grp3\n\n"
},
{
"answer_id": 74494447,
"author": "Neeraj",
"author_id": 5047311,
"author_profile": "https://Stackoverflow.com/users/5047311",
"pm_score": 1,
"selected": false,
"text": "dplyr data.table library(data.table)\nsetDT(data)\ndata <- data[, N := .N, by = y][N <= 1 | !is.na(x)][, N := NULL]\ndata\n x y\n1: 1 grp1\n2: 3 grp2\n3: NA grp3\n data <- data[, N := .N, by = y][N <= 1 | is.na(x)][, N := NULL]\ndata\n x y\n1: 1 grp1\n2: NA grp2\n3: NA grp3\n"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74494301",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5596534/"
] |
74,494,331
|
<p>What is a good way to ignore the tags/variables in a jQuery HTML method?</p>
<p>For instance, if there was no value for company, it would not be included in the HTML.</p>
<pre><code>$('.modal-body').html(`
<p><span style="font-weight:bold;">Name:</span> ${name}</p>
<p><span style="font-weight:bold;">Company:</span> ${company}</p>
<p><span style="font-weight:bold;">Job:</span> ${job}</p>
<p><span style="font-weight:bold;">Title:</span> ${title}</p>
<p><span style="font-weight:bold;">Phone:</span> ${phone}</p>
<p><span style="font-weight:bold;">Email:</span> ${email}</p>
<p><span style="font-weight:bold;">Event Loc:</span> ${addressResult}</p>
`)
</code></pre>
|
[
{
"answer_id": 74494631,
"author": "Amirhossein",
"author_id": 11342834,
"author_profile": "https://Stackoverflow.com/users/11342834",
"pm_score": 1,
"selected": false,
"text": "let htmlContent = `<p><span style=\"font-weight:bold;\">Job:</span> ${job}</p>`;\nif(company) {\n htmlContent += `<p><span style=\"font-weight:bold;\">Company:</span> ${company}</p>`;\n}\n$('.modal-body').html(htmlContent);\n $('.modal-body').html(`\n ${job ? `<p><span style=\"font-weight:bold;\">Job:</span> ${job}</p>` : ''}\n ${company ? `<p><span style=\"font-weight:bold;\">Company:</span> ${company}</p>` : ''}\n`);\n"
},
{
"answer_id": 74494705,
"author": "human bean",
"author_id": 17186475,
"author_profile": "https://Stackoverflow.com/users/17186475",
"pm_score": 2,
"selected": true,
"text": "const name = \"John Smith\",\n company = \"1-800-Flowers\",\n job = \"Software Developer\",\n title = undefined,\n phone = \"(123)-456-7890\",\n email = \"john@smith.com\",\n addressResult = \"123 Big Street, Town, MA\"\n\n$('.modal-body').html(`\n ${name ? `<p><span style=\"font-weight:bold;\">Name:</span> ${name}</p>` : \"\"}\n ${company ? `<p><span style=\"font-weight:bold;\">Company:</span> ${company}</p>` : \"\"}\n ${job ? `<p><span style=\"font-weight:bold;\">Job:</span> ${job}</p>` : \"\"}\n ${title ? `<p><span style=\"font-weight:bold;\">Title:</span> ${title}</p>` : \"\"}\n ${phone ? `<p><span style=\"font-weight:bold;\">Phone:</span> ${phone}</p>` : \"\"}\n ${email ? `<p><span style=\"font-weight:bold;\">Email:</span> ${email}</p>` : \"\"}\n ${addressResult ? `<p><span style=\"font-weight:bold;\">Event Loc:</span> ${addressResult}</p>` : \"\"}\n `) <script src=\"https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js\"></script>\n<div class=\"modal-body\"></div>"
},
{
"answer_id": 74495382,
"author": "dale landry",
"author_id": 1533592,
"author_profile": "https://Stackoverflow.com/users/1533592",
"pm_score": 0,
"selected": false,
"text": "const customers = [{\n name: 'John Doe',\n company: null,\n job: 'Front-End Developer',\n title: 'manager',\n phone: '555-555-5555',\n email: 'jdoe@gmail.com',\n addressResult: null\n}]\n\nfunction getInfo(k, v){\n return v !== null ? $('.modal-body').append(`<p><span style=\"font-weight:bold;\">${k}:</span> ${v}</p>`) : null \n}\n\n$.each(customers, function(index, value){\n $.each(value, function(i,v){ \n getInfo(i,v)\n })\n}) <script src=\"https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js\"></script>\n<div class=\"modal-body\"></div>"
},
{
"answer_id": 74496064,
"author": "zer00ne",
"author_id": 2813224,
"author_profile": "https://Stackoverflow.com/users/2813224",
"pm_score": 1,
"selected": false,
"text": "<!-- Simple modal with a unordered list. The <ul> will be the targeted element -->\n<dialog>\n <ul></ul>\n</dialog>\n // Data source as an array of objects (simular to JSON)\nconst data = [\n { \"keyA\": \"value1\", \"keyB\": \"value2\" }, \n { \"keyA\": \"value3\", \"keyB\": \"\" }, \n { \"keyA\": \"value5\", \"keyB\": \"value6\" }\n]; \n\n// Select object by index number and extract data\nlet index = 1; // Second object\n\nfunction displayData(data, index) {\n // Clear <ul>\n $(\"ul\").html(\"\");\n\n /* Convert object into an array of key/value pairs\n || keyValuePairs = [[\"keyA\": \"value3\"], [\"keyB\", \"\"]];\n */\n const keyValuePairs = Object.entries(data[index]);\n \n // Add and format each key/value pair into <ul>\n keyValuePairs.forEach(([key, value]) => {\n // IF value exists...\n if (value) {\n $(\"ul\").append(\n `<li>\n <b> // Same as <span style=\"font-weight: bold\">\n ${key.charAt(0).toUpperCase()+key.slice(1)}: // Capitalize key\n </b> \n ${value}\n </li>`\n );\n }\n });\n}\n <!-- \nResult is the data of the second object is displayed in <ul>\nNote, keyB is excluded since it had no value\n-->\n<dialog>\n <ul>\n <li><b>KeyA:</b> value3</li>\n </ul>\n</dialog>\n <select> const profiles = [{\n \"name\": \"Lucille Blay\",\n \"company\": \"Tambee\",\n \"title\": \"Technical Writer\",\n \"phone\": \"\",\n \"email\": \"lblay0@arstechnica.com\",\n \"address\": \"\"\n}, {\n \"name\": \"Baudoin Macauley\",\n \"company\": \"\",\n \"title\": \"\",\n \"phone\": \"877-812-9835\",\n \"email\": \"bmacauley1@utexas.edu\",\n \"address\": \"415 David Way\"\n}, {\n \"name\": \"Aurora Garside\",\n \"company\": \"\",\n \"title\": \"Nuclear Power Engineer\",\n \"phone\": \"823-514-0402\",\n \"email\": \"agarside2@linkedin.com\",\n \"address\": \"\"\n}];\n\nfunction displayProfile(profiles, index) {\n $(\"ul\").html(\"\");\n let data = Object.entries(profiles[index]);\n data.forEach(([key, value]) => {\n if (value) {\n $(\"ul\").append(\n `<li>\n <b>\n ${key.charAt(0).toUpperCase()+key.slice(1)}:\n </b> \n ${value}\n </li>`);\n }\n });\n}\n\n/**\n * For Demo Purposes Only [START]\n */\n$(\"select\").on(\"input\", function(e) {\n displayProfile(profiles, this.value);\n this.value = \"Pick Index Number\";\n $(\"dialog\")[0].showModal();\n});\n\n$(\"button\").on(\"click\", function(e) {\n $(\"dialog\")[0].close();\n});\n// [END] :root {\n font: 300 2ch/1.2 \"Segoe UI\"\n}\n\nselect {\n padding: 4px;\n font: inherit;\n text-align: center;\n}\n\ndialog {\n padding-top: 15px;\n padding-right: 25px;\n}\n\ndialog::backdrop {\n background: rgba(0, 0, 0, 0.4);\n}\n\nbutton {\n position: relative;\n top: -6px;\n left: 16px;\n float: right;\n height: 1.2rem;\n padding-bottom: 4px;\n line-height: 1.1;\n vertical-align: top;\n cursor: pointer;\n}\n\nul {\n list-style: none;\n margin-left: -30px;\n} <!-- For Demo Purposes Only [START] -->\n<select>\n <option selected>Pick Index Number</option>\n <option>0</option>\n <option>1</option>\n <option>2</option>\n</select>\n<!-- [END] -->\n\n<dialog>\n <button>X</button>\n <ul></ul>\n</dialog>\n<script src=\"https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js\"></script>"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74494331",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4957270/"
] |
74,494,343
|
<p>so I got some divs, something like this:</p>
<pre><code><div class="personal-events-list">
<div class="specific-event black-font">Something</div>
<div class="specific-event black-font">Something else</div>
<div class="specific-event black-font">Something more</div>
</div>
</code></pre>
<p>and I want them to have the same size (assuming that what makes sense is the size of the biggest one), something like this:
<a href="https://imgur.com/a/KsUm9JJ" rel="nofollow noreferrer">https://imgur.com/a/KsUm9JJ</a></p>
<p>and currently I have something like this:
<a href="https://imgur.com/a/IYSKRXJ" rel="nofollow noreferrer">https://imgur.com/a/IYSKRXJ</a></p>
<p>Currently I have CSS with "width: fit-content" but that just makes them all different sizes. The only real solution I came up with was making them all a fixed size, like "width: 300px" but that would make some bigger/smaller names look kinda funky... is there a way to do what I want?</p>
<p>Thanks alot for your time!</p>
<p><strong>Edit 1: Added CSS</strong></p>
<pre><code>.specific-event {
width: fit-content;
margin-bottom: 10px;
text-decoration: none;
color: black;
padding: 5px 10px;
background-color: #d1d1d1;
border-radius: 8px;
}
.specific-event:hover {
background-color: #9c9c9c;
color: white;
}
</code></pre>
|
[
{
"answer_id": 74494495,
"author": "John",
"author_id": 11111119,
"author_profile": "https://Stackoverflow.com/users/11111119",
"pm_score": 1,
"selected": false,
"text": "width: fit-content .personal-events-list .specific-event .specific-event {\n margin-bottom: 10px;\n text-decoration: none;\n color: black;\n padding: 5px 10px;\n background-color: #d1d1d1;\n border-radius: 8px;\n}\n\n.specific-event:hover {\n background-color: #9c9c9c;\n color: white;\n}\n\n.personal-events-list {\n width: fit-content;\n} <div class=\"personal-events-list\">\n <div class=\"specific-event black-font\">Something</div>\n <div class=\"specific-event black-font\">Something else</div>\n <div class=\"specific-event black-font\">Something more</div>\n</div>"
},
{
"answer_id": 74495100,
"author": "Emre",
"author_id": 6468955,
"author_profile": "https://Stackoverflow.com/users/6468955",
"pm_score": 0,
"selected": false,
"text": ".specific-event {\n width: fit-content;\n margin-bottom: 10px;\n text-decoration: none;\n color: black;\n padding: 5px 10px;\n background-color: #d1d1d1;\n border-radius: 8px;\n /* You should add these lines. */\n word-wrap: break-word;\n width:300px;\n}\n\n.specific-event:hover {\n background-color: #9c9c9c;\n color: white;\n} <div class=\"personal-events-list\">\n <div class=\"specific-event black-font\">Something</div>\n <div class=\"specific-event black-font\">Something else, and some things.</div>\n <div class=\"specific-event black-font\">Something more. For example, I am writing the long sentence.</div>\n</div>"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74494343",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15775091/"
] |
74,494,357
|
<p>I have a query that return values based on a boolean column: if the <code>id_crsp</code> includes a boolean true AND false, then it is selected.
Values of <code>id_crsp</code> that have only a true or false value are not selected.</p>
<p>From this result, I sort the <code>id_crsp</code> which have duplicates, and select only the one with the oldest date.</p>
<p>Database values :</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th style="text-align: center;">id</th>
<th style="text-align: center;">idcrsp</th>
<th>date_false</th>
<th>boolean</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align: center;">1</td>
<td style="text-align: center;">100</td>
<td>01-01-2023</td>
<td>true</td>
</tr>
<tr>
<td style="text-align: center;">2</td>
<td style="text-align: center;">100</td>
<td>01-07-2022</td>
<td>false</td>
</tr>
<tr>
<td style="text-align: center;">3</td>
<td style="text-align: center;">200</td>
<td>01-06-2022</td>
<td>false</td>
</tr>
<tr>
<td style="text-align: center;">4</td>
<td style="text-align: center;">300</td>
<td>01-02-2023</td>
<td>true</td>
</tr>
<tr>
<td style="text-align: center;">5</td>
<td style="text-align: center;">300</td>
<td>01-08-2022</td>
<td>false</td>
</tr>
<tr>
<td style="text-align: center;">6</td>
<td style="text-align: center;">400</td>
<td>01-10-2022</td>
<td>false</td>
</tr>
<tr>
<td style="text-align: center;">7</td>
<td style="text-align: center;">100</td>
<td>01-01-2022</td>
<td>false</td>
</tr>
<tr>
<td style="text-align: center;">8</td>
<td style="text-align: center;">100</td>
<td>01-02-2022</td>
<td>false</td>
</tr>
<tr>
<td style="text-align: center;">9</td>
<td style="text-align: center;">100</td>
<td>01-11-2022</td>
<td>true</td>
</tr>
</tbody>
</table>
</div>
<p>My actual request :</p>
<pre><code>SELECT *
FROM
(SELECT
true_table.*,
ROW_NUMBER() OVER (PARTITION BY id_crsp ORDER BY date ASC) rn
FROM
mydb AS true_table
INNER JOIN
(SELECT *
FROM mydb
WHERE requalif = TRUE) AS false_table ON true_table.idcrsp = false_table.idcrsp
AND true_table.requalif = FALSE)
WHERE rn = 1
</code></pre>
<p>This returns:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th style="text-align: left;">id</th>
<th style="text-align: center;">idcrsp</th>
<th>date_false</th>
<th>boolean</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align: left;">7</td>
<td style="text-align: center;">100</td>
<td>01-01-2022</td>
<td>false</td>
</tr>
<tr>
<td style="text-align: left;">5</td>
<td style="text-align: center;">300</td>
<td>01-08-2022</td>
<td>false</td>
</tr>
</tbody>
</table>
</div>
<p>I would like to enrich my request with :</p>
<ul>
<li>new column for my select, with the most recent date for the <code>idcrsp</code> with true boolean</li>
<li>new column with the difference between this two dates in days</li>
</ul>
<p>Return expected :</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th style="text-align: center;">id</th>
<th style="text-align: center;">idcrsp</th>
<th>date_false</th>
<th>boolean</th>
<th>date_true</th>
<th style="text-align: right;">difference_in_days</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align: center;">7</td>
<td style="text-align: center;">100</td>
<td>01-01-2022</td>
<td>false</td>
<td>01-01-2023</td>
<td style="text-align: right;">365</td>
</tr>
<tr>
<td style="text-align: center;">5</td>
<td style="text-align: center;">300</td>
<td>01-08-2022</td>
<td>false</td>
<td>01-02-2023</td>
<td style="text-align: right;">180</td>
</tr>
</tbody>
</table>
</div>
<p>01-01-2023 = idcrsp: 100, boolean: true, date: most recent</p>
<p>01-02-2023 = idcrsp: 300, boolean: true, date: most recent</p>
<p>Thanks for your help !</p>
|
[
{
"answer_id": 74494495,
"author": "John",
"author_id": 11111119,
"author_profile": "https://Stackoverflow.com/users/11111119",
"pm_score": 1,
"selected": false,
"text": "width: fit-content .personal-events-list .specific-event .specific-event {\n margin-bottom: 10px;\n text-decoration: none;\n color: black;\n padding: 5px 10px;\n background-color: #d1d1d1;\n border-radius: 8px;\n}\n\n.specific-event:hover {\n background-color: #9c9c9c;\n color: white;\n}\n\n.personal-events-list {\n width: fit-content;\n} <div class=\"personal-events-list\">\n <div class=\"specific-event black-font\">Something</div>\n <div class=\"specific-event black-font\">Something else</div>\n <div class=\"specific-event black-font\">Something more</div>\n</div>"
},
{
"answer_id": 74495100,
"author": "Emre",
"author_id": 6468955,
"author_profile": "https://Stackoverflow.com/users/6468955",
"pm_score": 0,
"selected": false,
"text": ".specific-event {\n width: fit-content;\n margin-bottom: 10px;\n text-decoration: none;\n color: black;\n padding: 5px 10px;\n background-color: #d1d1d1;\n border-radius: 8px;\n /* You should add these lines. */\n word-wrap: break-word;\n width:300px;\n}\n\n.specific-event:hover {\n background-color: #9c9c9c;\n color: white;\n} <div class=\"personal-events-list\">\n <div class=\"specific-event black-font\">Something</div>\n <div class=\"specific-event black-font\">Something else, and some things.</div>\n <div class=\"specific-event black-font\">Something more. For example, I am writing the long sentence.</div>\n</div>"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74494357",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14131200/"
] |
74,494,368
|
<p>I am using <code>fs.readFile</code> to read the content of <code>config.json</code> in <code>readCredentials.js</code>. Then I am exporting the function so I can use it it <code>config.js</code>.</p>
<p>When I run <code>node config.js</code> I get two <code>undefined</code> and then real values of <code>username</code> and <code>password</code> in <code>config.js</code>. Any idea how i can fix this?</p>
<p><strong>readCredentials.js</strong></p>
<pre><code>const fs = require("fs");
fs.readFile("./config.json", (err, data) => {
if (err) {
console.log(err);
}
const config = JSON.parse(data);
const username = config.username;
const password = config.password;
console.log(username, password);
module.exports = { username, password };
});
</code></pre>
<p><strong>config.json</strong></p>
<p>{
"username": "xyz",
"password": "xyz"
}</p>
<p><strong>config.js</strong></p>
<pre><code>const { username, password } = require("./readCredentials.js");
const usernameValue = username;
const passwordValue = password;
console.log(usernameValue, passwordValue);
</code></pre>
|
[
{
"answer_id": 74494500,
"author": "jfriend00",
"author_id": 816620,
"author_profile": "https://Stackoverflow.com/users/816620",
"pm_score": 3,
"selected": true,
"text": "module.exports await fs.readFileSync() require() .json const { username, password } = require(\"./config.json\");\nmodule.exports = { username, password };\n"
},
{
"answer_id": 74494511,
"author": "Nikolay",
"author_id": 929187,
"author_profile": "https://Stackoverflow.com/users/929187",
"pm_score": 2,
"selected": false,
"text": "require readFileSync const config = require(\"./config.json\");\nconst username = config.username;\nconst password = config.password;\nconsole.log(username, password);\nmodule.exports = { username, password };\n"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74494368",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16603880/"
] |
74,494,380
|
<p>My plan is to allow the protocols ICMP and TCP on the same security rule but I'm having problems related the "attribute value typ"</p>
<p>My Terraform code:</p>
<pre><code>resource "azurerm_network_security_group" "example" {
name = "01-tf-SG"
location = azurerm_resource_group.main.location
resource_group_name = azurerm_resource_group.main.name
security_rule {
name = "test123"
priority = 100
direction = "Inbound"
access = "Allow"
protocol = **["Icmp", "Tcp"]** ---> iT FAILS!!!
source_port_range = "*"
destination_port_range = "*"
source_address_prefix = "172.16.25.10/32"
destination_address_prefix = "10.0.1.10/32"
}
</code></pre>
<p>I didn't find any example in terraform repo: <a href="https://registry.terraform.io/providers/hashicorp/azurerm/latest/docs/resources/network_security_rule" rel="nofollow noreferrer">https://registry.terraform.io/providers/hashicorp/azurerm/latest/docs/resources/network_security_rule</a></p>
<p>Be able to use multiple protocols on the same security rule protocol field.</p>
|
[
{
"answer_id": 74494753,
"author": "Mark B",
"author_id": 13070,
"author_profile": "https://Stackoverflow.com/users/13070",
"pm_score": 0,
"selected": false,
"text": "*"
},
{
"answer_id": 74498502,
"author": "Chris Doyle",
"author_id": 1212401,
"author_profile": "https://Stackoverflow.com/users/1212401",
"pm_score": 2,
"selected": true,
"text": "Mark B protocol resource \"azurerm_network_security_group\" \"example\" {\n name = \"01-tf-SG\"\n location = azurerm_resource_group.main.location\n resource_group_name = azurerm_resource_group.main.name\n\n dynamic \"security_rule\" {\n for_each = toset([\"Icmp\", \"Tcp\"])\n content {\n name = \"test123\"\n priority = 100\n direction = \"Inbound\"\n access = \"Allow\"\n protocol = security_rule.value\n source_port_range = \"*\"\n destination_port_range = \"*\"\n source_address_prefix = \"172.16.25.10/32\"\n destination_address_prefix = \"10.0.1.10/32\"\n }\n }\n}\n"
},
{
"answer_id": 74499189,
"author": "NinjaCloud",
"author_id": 20432287,
"author_profile": "https://Stackoverflow.com/users/20432287",
"pm_score": 1,
"selected": false,
"text": "resource \"azurerm_network_security_group\" \"example\" {\n name = \"01-tf-SG\"\n location = azurerm_resource_group.main.location\n resource_group_name = azurerm_resource_group.main.name\n\n dynamic \"security_rule\" {\n for_each = toset([\"Icmp\", \"Tcp\"])\n content {\n name = \"test123\"\n priority = 100\n direction = \"Inbound\"\n access = \"Allow\"\n protocol = security_rule.value\n source_port_range = \"*\"\n destination_port_range = \"*\"\n source_address_prefix = \"172.16.25.10/32\"\n destination_address_prefix = \"10.0.1.10/32\"\n }\n }\n} # azurerm_network_security_group.example will be created\n + resource \"azurerm_network_security_group\" \"example\" {\n + id = (known after apply)\n + location = \"westeurope\"\n + name = \"01-tf-SG\"\n + resource_group_name = \"RG_AZ_Terraform\"\n + security_rule = [\n + {\n + access = \"Allow\"\n + description = \"\"\n + destination_address_prefix = \"10.0.1.10/32\"\n + destination_address_prefixes = []\n + destination_application_security_group_ids = []\n + destination_port_range = \"*\"\n + destination_port_ranges = []\n + direction = \"Inbound\"\n + name = \"test123\"\n + priority = 100\n + protocol = \"Icmp\"\n + source_address_prefix = \"172.16.25.10/32\"\n + source_address_prefixes = []\n + source_application_security_group_ids = []\n + source_port_range = \"*\"\n + source_port_ranges = []\n },\n + {\n + access = \"Allow\"\n + description = \"\"\n + destination_address_prefix = \"10.0.1.10/32\"\n + destination_address_prefixes = []\n + destination_application_security_group_ids = []\n + destination_port_range = \"*\"\n + destination_port_ranges = []\n + direction = \"Inbound\"\n + name = \"test123\"\n + priority = 100\n + protocol = \"Tcp\"\n + source_address_prefix = \"172.16.25.10/32\"\n + source_address_prefixes = []\n + source_application_security_group_ids = []\n + source_port_range = \"*\"\n + source_port_ranges = []\n },\n ]\n }"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74494380",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20432287/"
] |
74,494,441
|
<p>I want to calculate the percentage change for the following data frame.</p>
<pre><code>import pandas as pd
df = pd.DataFrame({'team': ['A', 'A', 'A', 'B', 'B', 'B', 'C', 'C'],
'points': [12, 0, 19, 22, 0, 25, 0, 30],
'score': [12, 0, 19, 22, 0, 25, 0, 30]
})
print(df)
</code></pre>
<p>When I applied this step, it returns inf which is obvious because we are dividing by zero.</p>
<pre><code>df['score'] = df.groupby('team', sort=False)['score'].apply(
lambda x: x.pct_change()).to_numpy()
</code></pre>
<p>But if we see in each column the change from 0 to 19 the change is 100%, from 0 to 25 the change is 100%, and from 0 to 30 the change is 100%. So, I was wondering how can I calculate those values.</p>
<p>current result
<a href="https://i.stack.imgur.com/NIws7.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/NIws7.png" alt="enter image description here" /></a></p>
<p>Expected result is
<a href="https://i.stack.imgur.com/8PmH6.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/8PmH6.png" alt="enter image description here" /></a></p>
|
[
{
"answer_id": 74494610,
"author": "Allan Elder",
"author_id": 1703491,
"author_profile": "https://Stackoverflow.com/users/1703491",
"pm_score": 0,
"selected": false,
"text": "df = pd.DataFrame({'team': ['A', 'A', 'A', 'B', 'B', 'B', 'C', 'C'],\n 'points': [12, 0, 19, 22, 0, 25, 0, 30],\n 'score': [12, 0, 19, 22, 0, 25, 0, 30]\n\n })\n\ndf[\"score\"] = df.groupby('team', sort=False)['score'].diff() * 100\n\nprint(df)\n df.loc[df[\"score\"] < 0, \"score\"] = -1\ndf.loc[df[\"score\"] > 0, \"score\"] = 1\n"
},
{
"answer_id": 74494712,
"author": "mozway",
"author_id": 16343464,
"author_profile": "https://Stackoverflow.com/users/16343464",
"pm_score": 1,
"selected": false,
"text": "import numpy as np\n\ndf[['points', 'score']] = (\n df.groupby('team')\n .pct_change()\n .replace(np.inf, 1)\n)\n team points score\n0 A NaN NaN\n1 A -1.0 -1.0\n2 A 1.0 1.0\n3 B NaN NaN\n4 B -1.0 -1.0\n5 B 1.0 1.0\n6 C NaN NaN\n7 C 1.0 1.0\n"
},
{
"answer_id": 74494726,
"author": "Naveed",
"author_id": 3494754,
"author_profile": "https://Stackoverflow.com/users/3494754",
"pm_score": 0,
"selected": false,
"text": "# take the sign using np.sign for the diff b/w two consecutive rows\ndf['chg']=np.sign(df.groupby('team')['score'].diff())\ndf\n team points score chg\n0 A 12 12 NaN\n1 A 0 0 -1.0\n2 A 19 19 1.0\n3 B 22 22 NaN\n4 B 0 0 -1.0\n5 B 25 25 1.0\n6 C 0 0 NaN\n7 C 30 30 1.0\n"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74494441",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16875907/"
] |
74,494,458
|
<p>As stated in the question, you can drag an IMG element from a web page into any other application that accepts it. You can also right-click to select "Save Image As...".</p>
<p>Is there a way to make this work with images (which are dynamically generated)? I had some luck converting the SVGs to data urls and passing them to IMG tags, but this doesn't seem to work on all browsers and is cumbersome.</p>
<p>EDIT: the one answer lead me to consider using Blobs and URL.createObjectURL(). Not sure if this would be less brittle than data urls.</p>
|
[
{
"answer_id": 74494571,
"author": "human bean",
"author_id": 17186475,
"author_profile": "https://Stackoverflow.com/users/17186475",
"pm_score": 1,
"selected": false,
"text": "img <img src=\"https://dev.w3.org/SVG/tools/svgweb/samples/svg-files/410.svg\" />"
},
{
"answer_id": 74498653,
"author": "Danny '365CSI' Engelman",
"author_id": 2520800,
"author_profile": "https://Stackoverflow.com/users/2520800",
"pm_score": 1,
"selected": false,
"text": "<img> src <img> <style>\n img { height:140px }\n</style>\n\n<svg-to-img src=\"//svg-cdn.github.io/heart.svg\"></svg-to-img>\n<svg-to-img src=\"//svg-cdn.github.io/joker-card.svg\"></svg-to-img>\n<svg-to-img src=\"//svg-cdn.github.io/svg_circle_spinner.svg\"></svg-to-img>\n\n<script>\n customElements.define(\"svg-to-img\", class extends HTMLElement {\n async connectedCallback() {\n let src = this.getAttribute(\"src\");\n let options = { /* fix potential CORS issues, client AND server side */ };\n let svg = await (await fetch(src,options)).text();\n let img = Object.assign(document.createElement(\"img\"), {\n src: \"data:image/svg+xml,\" + svg.replace(/\"/g, \"'\").replace(/#/g, '%23'),\n onload: (e) => console.log(\"Loaded SVG as IMG\", src),\n onerror: (e) => console.error(e)\n });\n this.replaceWith(img);\n }\n })\n</script> xmlns=\"http://www.w3.org/2000/svg\""
},
{
"answer_id": 74511109,
"author": "Scott Schafer",
"author_id": 2325033,
"author_profile": "https://Stackoverflow.com/users/2325033",
"pm_score": 0,
"selected": false,
"text": "xmlns=\"\" <svg>"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74494458",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2325033/"
] |
74,494,476
|
<p>I have this dataset in R:</p>
<pre><code>id = 1:5
col1 = c("12 ABC", "123", "AB", "123344567", "1345677.")
col2 = c("gggw", "12", "567", "abc 123", "p")
col3 = c("abw", "abi", "klo", "poy", "17df")
col4 = c("13 AB", "344", "Huh8", "98", "b")
my_data = data.frame(id, col1, col2, col3, col4)
id col1 col2 col3 col4
1 1 12 ABC gggw abw 13 AB
2 2 123 12 abi 344
3 3 AB 567 klo Huh8
4 4 123344567 abc 123 poy 98
5 5 1345677. p 17df b
</code></pre>
<p>I then used the following code to check to see if a specific cell contains AT LEAST one number:</p>
<pre><code>my_data$col1_check = grepl("\\d", my_data$col1)
my_data$col2_check = grepl("\\d", my_data$col2)
my_data$col3_check = grepl("\\d", my_data$col3)
my_data$col4_check = grepl("\\d", my_data$col4)
id col1 col2 col3 col4 col1_check col2_check col3_check col4_check
1 1 12 ABC gggw abw 13 AB TRUE FALSE FALSE TRUE
2 2 123 12 abi 344 TRUE TRUE FALSE TRUE
3 3 AB 567 klo Huh8 FALSE TRUE FALSE TRUE
4 4 123344567 abc 123 poy 98 TRUE TRUE FALSE TRUE
5 5 1345677. p 17df b TRUE FALSE TRUE FALSE
</code></pre>
<p>What I am trying to do, is for each row : <strong>I would like to take all columns in which the value is FALSE, and paste (with a space) the contents of these columns into a single cell.</strong></p>
<p>This would look something like this:</p>
<pre><code> id new_col
1 1 gggw abw
2 2 abi
3 3 AB klo
4 4 poy
5 5 p b
</code></pre>
<p>I have been trying to read about "conditional concatenation" (e.g. <a href="https://stackoverflow.com/questions/49822698/conditional-concatenation-in-r">conditional concatenation in R</a>), but so far nothing I have read matches the problem I am working on.</p>
<p>Can someone please suggest what to do from here?</p>
<p>Thanks!</p>
|
[
{
"answer_id": 74494507,
"author": "akrun",
"author_id": 3732271,
"author_profile": "https://Stackoverflow.com/users/3732271",
"pm_score": 4,
"selected": true,
"text": "tidyverse across get paste _check cur_column() case_when unite new_col library(stringr)\nlibrary(dplyr)\nlibrary(tidyr)\n my_data %>%\n transmute(id, across(col1:col4, \n ~ case_when(!get(str_c(cur_column(), \"_check\"))~ .x))) %>% \n unite(new_col, col1:col4, sep = \" \", na.rm = TRUE)\n id new_col\n1 1 gggw abw\n2 2 abi\n3 3 AB klo\n4 4 poy\n5 5 p b\n _check NA unite my_data %>%\n mutate(across(col1:col4,\n ~ case_when(str_detect(.x, \"\\\\d+\", negate = TRUE) ~.x))) %>% \n unite(new_col, col1:col4, sep = \" \", na.rm = TRUE)\n id new_col\n1 1 gggw abw\n2 2 abi\n3 3 AB klo\n4 4 poy\n5 5 p b\n base R cbind(my_data[1], new_col = gsub(\"\\\\s{2,}\", \" \", \n trimws(do.call(paste, replace(my_data[2:5], \n as.matrix(my_data[6:9]), '')))))\n id new_col\n1 1 gggw abw\n2 2 abi\n3 3 AB klo\n4 4 poy\n5 5 p b\n"
},
{
"answer_id": 74494590,
"author": "Martin Gal",
"author_id": 12505251,
"author_profile": "https://Stackoverflow.com/users/12505251",
"pm_score": 2,
"selected": false,
"text": "my_data library(dplyr)\nlibrary(tidyr)\nlibrary(stringr)\n\nmy_data %>% \n pivot_longer(-id) %>% \n filter(!str_detect(value, \"\\\\d\")) %>% \n group_by(id) %>% \n summarise(new_col = paste(value, collapse = \" \"))\n # A tibble: 5 × 2\n id new_col \n <int> <chr> \n1 1 gggw abw\n2 2 abi \n3 3 AB klo \n4 4 poy \n5 5 p b \n"
},
{
"answer_id": 74494593,
"author": "Andre Wildberg",
"author_id": 9462095,
"author_profile": "https://Stackoverflow.com/users/9462095",
"pm_score": 3,
"selected": false,
"text": "data.frame(id = my_data$id, new_col = apply(my_data[,-1], 1, function(x) \n paste(x[!grepl(\"[[:digit:]]\", x)], collapse=\" \")))\n id new_col\n1 1 gggw abw\n2 2 abi\n3 3 AB klo\n4 4 poy\n5 5 p b\n"
},
{
"answer_id": 74494645,
"author": "Neeraj",
"author_id": 5047311,
"author_profile": "https://Stackoverflow.com/users/5047311",
"pm_score": 1,
"selected": false,
"text": "apply data.frame(id, new_col = apply(my_data[, -1], 1, FUN = function(x) {\n paste(x[!grepl(\"\\\\d\", x)], collapse = \" \") }))\n \nmy_data\n\n id new_col\n1 1 gggw abw\n2 2 abi\n3 3 AB klo\n4 4 poy\n5 5 p b\n"
},
{
"answer_id": 74494661,
"author": "TarJae",
"author_id": 13321647,
"author_profile": "https://Stackoverflow.com/users/13321647",
"pm_score": 2,
"selected": false,
"text": "library(tidyverse)\n\nmy_data %>% \n transmute(across(-id, ~case_when(!str_detect(., '\\\\d') ~ .))) %>% \n unite(\"New_col\", col1:col4, na.rm = TRUE, sep = \" \")\n library(dplyr)\nlibrary(tidyr)\nlibrary(stringr)\n\nmy_data %>% \n transmute(across(-id, ~case_when(!str_detect(., '\\\\d')== TRUE ~ .), .names = 'new_{col}')) %>% \n unite(New_col, starts_with('new'), na.rm = TRUE, sep = ' ')\n New_col\n1 gggw abw\n2 abi\n3 AB klo\n4 poy\n5 p b\n"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74494476",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13203841/"
] |
74,494,478
|
<p>I´m a very beginner in Pine editor, I´m trying to refine my Highs and Lows indicator but I don´t know how to do it. The issue is that I want to get the Highs and Lows but only of those ones whose highs and lows are higher or lower than the previous or next candle, and so on for the 3 left and right candles.
This is what I got so far...</p>
<pre><code>//@version=5
indicator("Test_H_L", overlay=true)
leftBars = input(3)
rightBars=input(3)
ph = ta.pivothigh(leftBars, rightBars)
pl = ta.pivotlow(leftBars, rightBars)
plot(ph, style=plot.style_linebr, linewidth=4, color= color.green, offset=-rightBars)
plot(pl, style=plot.style_linebr, linewidth=4, color= color.red, offset=-rightBars)
</code></pre>
<p>Thanks</p>
<p>I tried to use arrays but It´s very confusing right now.</p>
|
[
{
"answer_id": 74494507,
"author": "akrun",
"author_id": 3732271,
"author_profile": "https://Stackoverflow.com/users/3732271",
"pm_score": 4,
"selected": true,
"text": "tidyverse across get paste _check cur_column() case_when unite new_col library(stringr)\nlibrary(dplyr)\nlibrary(tidyr)\n my_data %>%\n transmute(id, across(col1:col4, \n ~ case_when(!get(str_c(cur_column(), \"_check\"))~ .x))) %>% \n unite(new_col, col1:col4, sep = \" \", na.rm = TRUE)\n id new_col\n1 1 gggw abw\n2 2 abi\n3 3 AB klo\n4 4 poy\n5 5 p b\n _check NA unite my_data %>%\n mutate(across(col1:col4,\n ~ case_when(str_detect(.x, \"\\\\d+\", negate = TRUE) ~.x))) %>% \n unite(new_col, col1:col4, sep = \" \", na.rm = TRUE)\n id new_col\n1 1 gggw abw\n2 2 abi\n3 3 AB klo\n4 4 poy\n5 5 p b\n base R cbind(my_data[1], new_col = gsub(\"\\\\s{2,}\", \" \", \n trimws(do.call(paste, replace(my_data[2:5], \n as.matrix(my_data[6:9]), '')))))\n id new_col\n1 1 gggw abw\n2 2 abi\n3 3 AB klo\n4 4 poy\n5 5 p b\n"
},
{
"answer_id": 74494590,
"author": "Martin Gal",
"author_id": 12505251,
"author_profile": "https://Stackoverflow.com/users/12505251",
"pm_score": 2,
"selected": false,
"text": "my_data library(dplyr)\nlibrary(tidyr)\nlibrary(stringr)\n\nmy_data %>% \n pivot_longer(-id) %>% \n filter(!str_detect(value, \"\\\\d\")) %>% \n group_by(id) %>% \n summarise(new_col = paste(value, collapse = \" \"))\n # A tibble: 5 × 2\n id new_col \n <int> <chr> \n1 1 gggw abw\n2 2 abi \n3 3 AB klo \n4 4 poy \n5 5 p b \n"
},
{
"answer_id": 74494593,
"author": "Andre Wildberg",
"author_id": 9462095,
"author_profile": "https://Stackoverflow.com/users/9462095",
"pm_score": 3,
"selected": false,
"text": "data.frame(id = my_data$id, new_col = apply(my_data[,-1], 1, function(x) \n paste(x[!grepl(\"[[:digit:]]\", x)], collapse=\" \")))\n id new_col\n1 1 gggw abw\n2 2 abi\n3 3 AB klo\n4 4 poy\n5 5 p b\n"
},
{
"answer_id": 74494645,
"author": "Neeraj",
"author_id": 5047311,
"author_profile": "https://Stackoverflow.com/users/5047311",
"pm_score": 1,
"selected": false,
"text": "apply data.frame(id, new_col = apply(my_data[, -1], 1, FUN = function(x) {\n paste(x[!grepl(\"\\\\d\", x)], collapse = \" \") }))\n \nmy_data\n\n id new_col\n1 1 gggw abw\n2 2 abi\n3 3 AB klo\n4 4 poy\n5 5 p b\n"
},
{
"answer_id": 74494661,
"author": "TarJae",
"author_id": 13321647,
"author_profile": "https://Stackoverflow.com/users/13321647",
"pm_score": 2,
"selected": false,
"text": "library(tidyverse)\n\nmy_data %>% \n transmute(across(-id, ~case_when(!str_detect(., '\\\\d') ~ .))) %>% \n unite(\"New_col\", col1:col4, na.rm = TRUE, sep = \" \")\n library(dplyr)\nlibrary(tidyr)\nlibrary(stringr)\n\nmy_data %>% \n transmute(across(-id, ~case_when(!str_detect(., '\\\\d')== TRUE ~ .), .names = 'new_{col}')) %>% \n unite(New_col, starts_with('new'), na.rm = TRUE, sep = ' ')\n New_col\n1 gggw abw\n2 abi\n3 AB klo\n4 poy\n5 p b\n"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74494478",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20542252/"
] |
74,494,497
|
<p>I'm new to C#. Have a question about IQueryable.</p>
<p>From what I understand IQueryable queries the database every time it gets called. In my case, I need to put the IQueryable inside a for each loop with more than 50k of loops, so it will be good to convert it to a list first to reduce database calls? Or is there any other good approach? Thanks</p>
|
[
{
"answer_id": 74494507,
"author": "akrun",
"author_id": 3732271,
"author_profile": "https://Stackoverflow.com/users/3732271",
"pm_score": 4,
"selected": true,
"text": "tidyverse across get paste _check cur_column() case_when unite new_col library(stringr)\nlibrary(dplyr)\nlibrary(tidyr)\n my_data %>%\n transmute(id, across(col1:col4, \n ~ case_when(!get(str_c(cur_column(), \"_check\"))~ .x))) %>% \n unite(new_col, col1:col4, sep = \" \", na.rm = TRUE)\n id new_col\n1 1 gggw abw\n2 2 abi\n3 3 AB klo\n4 4 poy\n5 5 p b\n _check NA unite my_data %>%\n mutate(across(col1:col4,\n ~ case_when(str_detect(.x, \"\\\\d+\", negate = TRUE) ~.x))) %>% \n unite(new_col, col1:col4, sep = \" \", na.rm = TRUE)\n id new_col\n1 1 gggw abw\n2 2 abi\n3 3 AB klo\n4 4 poy\n5 5 p b\n base R cbind(my_data[1], new_col = gsub(\"\\\\s{2,}\", \" \", \n trimws(do.call(paste, replace(my_data[2:5], \n as.matrix(my_data[6:9]), '')))))\n id new_col\n1 1 gggw abw\n2 2 abi\n3 3 AB klo\n4 4 poy\n5 5 p b\n"
},
{
"answer_id": 74494590,
"author": "Martin Gal",
"author_id": 12505251,
"author_profile": "https://Stackoverflow.com/users/12505251",
"pm_score": 2,
"selected": false,
"text": "my_data library(dplyr)\nlibrary(tidyr)\nlibrary(stringr)\n\nmy_data %>% \n pivot_longer(-id) %>% \n filter(!str_detect(value, \"\\\\d\")) %>% \n group_by(id) %>% \n summarise(new_col = paste(value, collapse = \" \"))\n # A tibble: 5 × 2\n id new_col \n <int> <chr> \n1 1 gggw abw\n2 2 abi \n3 3 AB klo \n4 4 poy \n5 5 p b \n"
},
{
"answer_id": 74494593,
"author": "Andre Wildberg",
"author_id": 9462095,
"author_profile": "https://Stackoverflow.com/users/9462095",
"pm_score": 3,
"selected": false,
"text": "data.frame(id = my_data$id, new_col = apply(my_data[,-1], 1, function(x) \n paste(x[!grepl(\"[[:digit:]]\", x)], collapse=\" \")))\n id new_col\n1 1 gggw abw\n2 2 abi\n3 3 AB klo\n4 4 poy\n5 5 p b\n"
},
{
"answer_id": 74494645,
"author": "Neeraj",
"author_id": 5047311,
"author_profile": "https://Stackoverflow.com/users/5047311",
"pm_score": 1,
"selected": false,
"text": "apply data.frame(id, new_col = apply(my_data[, -1], 1, FUN = function(x) {\n paste(x[!grepl(\"\\\\d\", x)], collapse = \" \") }))\n \nmy_data\n\n id new_col\n1 1 gggw abw\n2 2 abi\n3 3 AB klo\n4 4 poy\n5 5 p b\n"
},
{
"answer_id": 74494661,
"author": "TarJae",
"author_id": 13321647,
"author_profile": "https://Stackoverflow.com/users/13321647",
"pm_score": 2,
"selected": false,
"text": "library(tidyverse)\n\nmy_data %>% \n transmute(across(-id, ~case_when(!str_detect(., '\\\\d') ~ .))) %>% \n unite(\"New_col\", col1:col4, na.rm = TRUE, sep = \" \")\n library(dplyr)\nlibrary(tidyr)\nlibrary(stringr)\n\nmy_data %>% \n transmute(across(-id, ~case_when(!str_detect(., '\\\\d')== TRUE ~ .), .names = 'new_{col}')) %>% \n unite(New_col, starts_with('new'), na.rm = TRUE, sep = ' ')\n New_col\n1 gggw abw\n2 abi\n3 AB klo\n4 poy\n5 p b\n"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74494497",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19638654/"
] |
74,494,570
|
<p>I've recently tried getting into the whole Node ecosystem and am trying to set up some continuous deployment for my app to AWS Amplify.</p>
<p>For background, my project structure looks like this:</p>
<pre><code>project
public
index.html
src
App.tsx/App.js
package.json
</code></pre>
<p>As far as I know, this is basically what create-react-app gave me to start with, and I didn't change the file structure.</p>
<p>For most of my time working on the app, I've been able to go to the base project directory and use</p>
<pre><code>npm start
</code></pre>
<p>to launch the app. This will bring me to the App.tsx/js homepage.</p>
<p>However, when I hosted this to AWS Amplify via GitHub, the default build settings actually point to the public directory, so the published site is actually point to index.html (which is basically just an empty placeholder).</p>
<p>While debugging, I ran</p>
<pre><code>npm build
</code></pre>
<p>in my root project directory, which constructed a build folder, so now the overall project looks like this:</p>
<pre><code>project
build
index.html
public
index.html
src
App.tsx/App.js
package.json
</code></pre>
<p>Now, running</p>
<pre><code>npm start
</code></pre>
<p>will bring me to the index.html from the build directory, instead of App.js/tsx as it used to.</p>
<p>The AWS setup says that it will run</p>
<pre><code>npm build
</code></pre>
<p>so I assume that what I've done on my local machine is mirroring what the AWS server is doing behind the scenes and explains why AWS is serving the empty index.html.</p>
<p>I've read a few articles and watched some videos about hosting a create-react-app on AWS, and in every version, it looks like AWS will serve the App.tsx/App.js right out of the box, rather than build/index.html, and I've not been able to find a good guide on how to configure this behavior. Quite frankly, there is an overwhelming number of similar-but-slightly-different answers for questions like this, which use different combinations of package managers, packages, hosting services, all on different release versions, with different setups, and it's very difficult for me to tell which ones apply to my scenario.</p>
<p>So I'm hoping someone can help straighten some of this out for me, or point me towards a good resource for learning more about this type of thing. Particularly interested in learning the <em>right</em> way to do these things, rather than a quick hack around whatever my particular issue is.</p>
<p>Some specific questions...</p>
<ul>
<li>Is deploying things from a /build folder standard convention?</li>
<li>Why does create-react-app create a separate /src/app.tsx and /public/index.html that seem to be competing with one another as the app's "homepage"?</li>
<li>Why does the behavior of</li>
</ul>
<pre><code>npm start
</code></pre>
<p>change depending on whether</p>
<pre><code>npm build
</code></pre>
<p>has been run?</p>
<ul>
<li>Is the correct fix here to just insert my App.tsx component into the index.html? This doesn't seem hard, but doesn't seem <em>right</em> either</li>
<li>I have seen a lot of answers discussing tweaks to webpack.config.js to solve issues like this one. My project does have webpack installed, but as best I can tell, there is no webpack.config.js anywhere. Am I expected to create this file, or should it exist already? In either case, in which directory is it supposed to live? I've seen a couple answers saying it should be in /node_modules/webpack/, but also some saying it needs to live in the same directory as package.json</li>
</ul>
<p>Things I've tried already: Spent a bunch of time reading through other StackOverflows and watching a few videos, but as outlined above, I'm finding it difficult to tell which could apply to my situation and which are unrelated, given the huge number of unique combinations of build/packages/platforms/versions. Also spent some time monkeying around with file structure/moving code around, but not very productively.</p>
|
[
{
"answer_id": 74496562,
"author": "Evans Wanjau",
"author_id": 4812835,
"author_profile": "https://Stackoverflow.com/users/4812835",
"pm_score": 0,
"selected": false,
"text": "create-react-app react-scripts start react-scripts build create-react-app"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74494570",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9659759/"
] |
74,494,604
|
<p>How can I make it so the game is infinite? and is there a way to simplify this code?</p>
<p>I have tried to work around but can't seem to figure it out.</p>
<pre><code># A rock paper scissors game.
import random
Move1=input("Enter your move: (r)ock (p)aper (s)cissors or (q)uit: ").lower()
Move2=["r","p","s"]
while Move1 != "q":
if Move1 == "r" or "p" or "s" or "q":
# print(random.choice(Move2))
Move2=random.choice(Move2)
if Move1=="r" and Move2=="s":
print("You've won")
break
elif Move2=="p":
print("You lost!")
break
elif Move2=="r":
print("You went even!")
break
if Move1=="p" and Move2=="s":
print("You lost!")
break
elif Move2=="p":
print("You went even!")
break
elif Move2=="r":
print("You won!")
break
if Move1=="s" and Move2=="s":
print("You went even!")
break
elif Move2=="p":
print("You won!")
break
elif Move2=="r":
print("You lost!")
break
else:
print("You've quit the game!")
exit()
</code></pre>
<p>Tried to remove break</p>
|
[
{
"answer_id": 74496562,
"author": "Evans Wanjau",
"author_id": 4812835,
"author_profile": "https://Stackoverflow.com/users/4812835",
"pm_score": 0,
"selected": false,
"text": "create-react-app react-scripts start react-scripts build create-react-app"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74494604",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15221342/"
] |
74,494,676
|
<p>I am working with a huge dataset in sas trying to use proc sql and I need help setting up a like statement. I'm trying to extract all the columns that have 'eco' in the name</p>
<p>I'm getting an error in the where statement as it is not registering the second *.
Any help?</p>
<p>proc sql
select *
from cfy19e8
where * LIKE %eco%;</p>
|
[
{
"answer_id": 74496562,
"author": "Evans Wanjau",
"author_id": 4812835,
"author_profile": "https://Stackoverflow.com/users/4812835",
"pm_score": 0,
"selected": false,
"text": "create-react-app react-scripts start react-scripts build create-react-app"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74494676",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20542633/"
] |
74,494,700
|
<p>The below code is a 4 year old example I found in a Youtube video. When I run it, I get</p>
<pre><code>TypeError: Cannot read properties of undefined (reading 'push')
</code></pre>
<p>Can someone figure out what the new syntax is?</p>
<pre><code>const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test');
const Schema = mongoose.Schema;
const commentSchema = new Schema({
text: String,
username: String,
});
const postSchema = new Schema({
text: String,
username: String,
comments: [commentSchema],
});
const PostModel = mongoose.model('post_coll', postSchema);
const CommentModel = mongoose.model('comment_coll', commentSchema);
const aPost = new PostModel({
text: 'one',
username: 'two',
});
aPost.comment.push({
text: 'one',
username: 'two',
});
aPost.save((err, res) => {});
</code></pre>
|
[
{
"answer_id": 74496562,
"author": "Evans Wanjau",
"author_id": 4812835,
"author_profile": "https://Stackoverflow.com/users/4812835",
"pm_score": 0,
"selected": false,
"text": "create-react-app react-scripts start react-scripts build create-react-app"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74494700",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/256439/"
] |
74,494,736
|
<pre><code>A2:A&COUNTIF(A2:A,"<>")
</code></pre>
<p>Instead of simply <code>A2:A</code>, I am trying to build a A1Notation that would only refer to column A that contains actual content. (There won't be empty rows in between non-empty rows)
But this doesn't work. I need to use this A1notation as the first parameter of a <code>Filter</code> function.</p>
<p>How should I do it?</p>
|
[
{
"answer_id": 74494836,
"author": "Martín",
"author_id": 20363318,
"author_profile": "https://Stackoverflow.com/users/20363318",
"pm_score": 2,
"selected": true,
"text": "INDIRECT(\"A2:A\"&COUNTIF(A2:A,\"<>\"))"
},
{
"answer_id": 74494839,
"author": "The God of Biscuits",
"author_id": 18645332,
"author_profile": "https://Stackoverflow.com/users/18645332",
"pm_score": 0,
"selected": false,
"text": "=filter(A2:A,A2:A<>\"\")\n"
},
{
"answer_id": 74500542,
"author": "player0",
"author_id": 5632629,
"author_profile": "https://Stackoverflow.com/users/5632629",
"pm_score": 0,
"selected": false,
"text": "=A2:INDEX(A2:A, COUNTA(A2:A))\n"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74494736",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2302661/"
] |
74,494,740
|
<p>I have a CSV file and I read the contents. I need to verify that every element of each row is not empty:</p>
<pre><code>fname = row[0]
if fname is None:
flag = -1
lname = row[1]
if lname is None:
flag = -1
phone = row[2]
if phone is None:
flag = -1
email = row[3]
if email is None:
flag = -1
[...]
</code></pre>
<p>Is there a way to optimize this code? Is there a way to do something like this in Python:</p>
<pre><code>fname = row[0] if None else flag = -1 ?
[...]
</code></pre>
<p>At the end I will check if flag is -1, I send an error notification (because this is a background task)</p>
|
[
{
"answer_id": 74494886,
"author": "aaf1097",
"author_id": 13637760,
"author_profile": "https://Stackoverflow.com/users/13637760",
"pm_score": 0,
"selected": false,
"text": "with open('testdata1.csv', 'r') as csv_file:\ncsv_reader = csv.reader(csv_file)\nfor row in csv_reader:\n if not row[0]:\n continue # this will skip to the next for loop iteration\n # do your processing here\n"
},
{
"answer_id": 74495098,
"author": "nigh_anxiety",
"author_id": 17030540,
"author_profile": "https://Stackoverflow.com/users/17030540",
"pm_score": 1,
"selected": false,
"text": "if all([len(e) for e in row]):\n # Row is good\nelse:\n # Row is bad\n\n all(row)"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74494740",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9999674/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.