qid
int64 4
19.1M
| question
stringlengths 18
48.3k
| answers
list | date
stringlengths 10
10
| metadata
list |
|---|---|---|---|---|
74,560,073
|
<p>I have a large dataset where one column contains free text. I wish to create a new column based on whether this free text contains a regular expression.</p>
<p>Eg:
I want to know whether this column contains the text GnRH, or those letters in any case, and create a new column with a flag to indicate if this is true or not.</p>
|
[
{
"answer_id": 74560441,
"author": "PeterClemmensen",
"author_id": 4044936,
"author_profile": "https://Stackoverflow.com/users/4044936",
"pm_score": 0,
"selected": false,
"text": "data have;\ninput text $20.;\ndatalines;\nNot in this line \nIn GnRH this line \nNot here either \nThis one GNRH too \n;\n\ndata want;\n set have;\n dummy = prxmatch('/gnrh/i', text) > 0;\nrun;\n"
},
{
"answer_id": 74565818,
"author": "Reeza",
"author_id": 1919583,
"author_profile": "https://Stackoverflow.com/users/1919583",
"pm_score": 2,
"selected": false,
"text": "DUMMY = find(text, \"gnrh\", 'it') > 0;\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74560073",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19414769/"
] |
74,560,075
|
<p>consider this method inside a class the return value of this method is used to calculate a value in <code>compute()</code> so the compute method shouldn't run if return value of <code>BS()</code> "BM" is <code>NaN</code>
so I added <code>if(this.BS()== null) return</code>, however when I don't enter a weight value the alert method runs twice one time for BS() and another time for compute()</p>
<pre><code>BS() {
this.weight = document.getElementById('first').value
this.height = document.getElementById('second').value
if (this.weight == '') return alert('please enter weight')
let w = parseFloat(this.weight)
let h = parseFloat(this.height)
let BM
BM = w*h
return BM
compute(){
if(this.BS()== null) return
let val= this.BS()/10
return val
}
</code></pre>
<p>I tried to use <code>if(this.BS()== undefined) return</code> but it also didn't work still the alert runs twice so how to fix it?</p>
|
[
{
"answer_id": 74560441,
"author": "PeterClemmensen",
"author_id": 4044936,
"author_profile": "https://Stackoverflow.com/users/4044936",
"pm_score": 0,
"selected": false,
"text": "data have;\ninput text $20.;\ndatalines;\nNot in this line \nIn GnRH this line \nNot here either \nThis one GNRH too \n;\n\ndata want;\n set have;\n dummy = prxmatch('/gnrh/i', text) > 0;\nrun;\n"
},
{
"answer_id": 74565818,
"author": "Reeza",
"author_id": 1919583,
"author_profile": "https://Stackoverflow.com/users/1919583",
"pm_score": 2,
"selected": false,
"text": "DUMMY = find(text, \"gnrh\", 'it') > 0;\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74560075",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19582350/"
] |
74,560,088
|
<p>In Cython one can use exact-width integral types by importing them from <code>stdint</code>, e.g.</p>
<pre><code>from libc.stdint cimport int32_t
</code></pre>
<p>Looking through <a href="https://github.com/cython/cython/blob/master/Cython/Includes/libc/stdint.pxd" rel="nofollow noreferrer">stdint.pxd</a>, we see that <code>int32_t</code> is defined as</p>
<pre><code>cdef extern from "<stdint.h>" nogil:
...
ctypedef signed int int32_t
</code></pre>
<p>Does this mean that if I use <code>int32_t</code> in my Cython code, this type is just an alias for <code>signed int</code> (<code>int</code>), which might in fact be <a href="https://en.wikipedia.org/wiki/C_data_types#Main_types" rel="nofollow noreferrer">only 16 bits wide</a>?</p>
<p>The issue is the same for all the other integral types.</p>
|
[
{
"answer_id": 74560162,
"author": "DevSolar",
"author_id": 60281,
"author_profile": "https://Stackoverflow.com/users/60281",
"pm_score": 0,
"selected": false,
"text": "signed int int32_t typedef CHAR_BIT signed int"
},
{
"answer_id": 74561167,
"author": "DavidW",
"author_id": 4657412,
"author_profile": "https://Stackoverflow.com/users/4657412",
"pm_score": 3,
"selected": true,
"text": "ctypedef signed int int32_t\n cdef extern"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74560088",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4056181/"
] |
74,560,132
|
<p>I'm trying to create a multi-stage Dockerfile</p>
<pre><code>FROM openjdk:11.0.7-jre-slim-buster AS build
... additional commands
RUN mkdir -p target/exploded && (cd target/exploded; jar -xf ../*.jar)
</code></pre>
<p>But it fails when trying to explode the .jar file, it is present under the target directory:</p>
<p><a href="https://i.stack.imgur.com/ef9dI.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ef9dI.png" alt="enter image description here" /></a></p>
<pre><code> => ERROR [build 7/7] RUN mkdir -p target/exploded && (cd
target/exploded; jar -xf ../*.jar)
/bin/sh: 1: jar: not found
------
executor failed running [/bin/sh -c mkdir -p target/exploded && (cd target/exploded;
jar -xf ../*.jar)]: exit code: 127
</code></pre>
|
[
{
"answer_id": 74560162,
"author": "DevSolar",
"author_id": 60281,
"author_profile": "https://Stackoverflow.com/users/60281",
"pm_score": 0,
"selected": false,
"text": "signed int int32_t typedef CHAR_BIT signed int"
},
{
"answer_id": 74561167,
"author": "DavidW",
"author_id": 4657412,
"author_profile": "https://Stackoverflow.com/users/4657412",
"pm_score": 3,
"selected": true,
"text": "ctypedef signed int int32_t\n cdef extern"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74560132",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1949114/"
] |
74,560,133
|
<p>In my SPA, I have a function that needs to:</p>
<ol>
<li>Create an object (e.g. a "tag" for a user)</li>
<li>Post it to our API</li>
</ol>
<pre class="lang-js prettyprint-override"><code>type UserId = string;
type User = {id: UserId};
type TagType = "NEED_HELP" | "NEED_STORAGE"
type Tag = {
id: string;
type: TagType;
userId: UserId;
}
type TagDraft = Omit<Tag, "id">
// ----
const createTagDraft = ({tagType, user} : {tagType: TagType, userId: UserID}): TagDraft => ({
type: tagType, userId: userId
})
const postTag = (tagDraft) => pipe(
TE.tryCatch(
() => axios.post('https://myTagEndpoint', tagDraft),
(reason) => new Error(`${reason}`),
),
TE.map((resp) => resp.data),
)
</code></pre>
<p>I can combine the entire task with</p>
<pre class="lang-js prettyprint-override"><code>const createTagTask = flow(createTagDraft, postTag)
</code></pre>
<p>Now I would like to also clear some client cache that I have for Tags. Since the cache object has nothing to do with the arguments needed for the tag, I would like to provide it separately. I do:</p>
<pre class="lang-js prettyprint-override"><code>function createTagAndCleanTask(queryCache) {
return flow(
createTagDraft,
postTag,
TE.chainFirstTaskK((flag) =>
T.of(
queryCache.clean("tagCache")
)
)
)
}
// which I call like this
createTagAndCleanTask(queryCache)({tagType: "NEED_HELP", user: bob})
</code></pre>
<p>This works, but I wonder if this is not exactly what I could use <code>ReaderTaskEither</code> for?</p>
<p><strong>Idea 1:</strong> I tried to use <code>RTE.fromTaskEither</code> on <code>createTagTask</code>, but <code>createTagTask</code> is a function that returns a TaskEither, not a TaskEither...</p>
<p><strong>Idea 2:</strong> I tried to use <code>RTE.fromTaskEither</code> as a third step in the <code>flow</code> after <code>postTag</code> but I don't know how to provide proper typing then and make it aware of a env config object.</p>
<p>My understanding of <a href="https://dev.to/gcanti/getting-started-with-fp-ts-reader-1ie5" rel="nofollow noreferrer">this article</a> is that I should aim at something like <code>(args) => (env) => body</code> instead of <code>(env) => (args) => body</code> for each functions. But I cannot find a way to invert arguments that are provided directly via <code>flow</code>.</p>
<p>Is there a way that can I rewrite this code so that I can provide env objects like queryCache in a cleaner way?</p>
|
[
{
"answer_id": 74560162,
"author": "DevSolar",
"author_id": 60281,
"author_profile": "https://Stackoverflow.com/users/60281",
"pm_score": 0,
"selected": false,
"text": "signed int int32_t typedef CHAR_BIT signed int"
},
{
"answer_id": 74561167,
"author": "DavidW",
"author_id": 4657412,
"author_profile": "https://Stackoverflow.com/users/4657412",
"pm_score": 3,
"selected": true,
"text": "ctypedef signed int int32_t\n cdef extern"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74560133",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2008527/"
] |
74,560,136
|
<p>The following code is used as an offline monitor within a RN app - its basically used to display a warning if connection drops.</p>
<pre><code> export default function InternetCheck() {
const [isConnected, setIsConnected] = useState(false);
const [mounted, setMounted] = useState(false);
useEffect(() => {
//Intial status
NetInfo.fetch().then(state => {
if (state.isInternetReachable == false) {
setIsConnected(state.isInternetReachable);
}
});
//Internet connection listener
NetInfo.addEventListener(state => {
setIsConnected(state.isInternetReachable);
});
}, []);
</code></pre>
<p>I am receiving the following error in the console -</p>
<blockquote>
<p>Warning: Can't perform a React state update on an unmounted component.
This is a no-op, but it indicates a memory leak in your application.
To fix, cancel all subscriptions and asynchronous tasks in a useEffect
cleanup function.</p>
</blockquote>
<p>Can anyone please explain how to apply a cleanup function in this scenario please? I have read through various other questions but cant get my head around the logic approach.</p>
|
[
{
"answer_id": 74560212,
"author": "jsejcksn",
"author_id": 438273,
"author_profile": "https://Stackoverflow.com/users/438273",
"pm_score": 3,
"selected": true,
"text": "NetInfo export default function InternetCheck () {\n const [isConnected, setIsConnected] = useState(false);\n const [mounted, setMounted] = useState(false);\n\n useEffect(() => {\n let cleanupStarted = false;\n\n // Initial status\n\n NetInfo.fetch().then(state => {\n if (state.isInternetReachable == false) {\n if (!cleanupStarted) setIsConnected(state.isInternetReachable);\n }\n });\n\n // Internet connection listener\n const unsubscribe = NetInfo.addEventListener(state => {\n if (!cleanupStarted) setIsConnected(state.isInternetReachable);\n });\n\n return () => {\n cleanupStarted = true;\n unsubscribe();\n };\n }, []);\n}\n"
},
{
"answer_id": 74560230,
"author": "Jawad Fadel",
"author_id": 12626795,
"author_profile": "https://Stackoverflow.com/users/12626795",
"pm_score": -1,
"selected": false,
"text": " export default function InternetCheck() {\n const [isConnected, setIsConnected] = useState(false);\n const [mounted, setMounted] = useState(false);\n \n useEffect(() => {\n //Intial status\n \n NetInfo.fetch().then(state => {\n if (state.isInternetReachable == false) {\n setIsConnected(state.isInternetReachable);\n }\n });\n //Internet connection listener\n NetInfo.addEventListener(state => {\n setIsConnected(state.isInternetReachable);\n });\n//----> add the removeEventListener \nreturn ()=>{\nNetInfo.removeEventListener(...)\n......\n}\n }, []);\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74560136",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/385563/"
] |
74,560,166
|
<p>In console.log I can see the array is not empty,as well it's shown on the image below. However, when I send the data to the endpoint the array is 0. I notice the other element MaterialId has value, so must be some problem with the array only. The data is sent through axios.</p>
<p>Any help is appreciated.</p>
<p>C# Model data:</p>
<pre><code>public class axiosChangeMaterialPictureModel
{
public Array[] Image { get; set; }
public int MaterialId { get; set; }
}
</code></pre>
<p>C# Endpoint:</p>
<pre><code> [HttpPost]
public IActionResult ChangeMaterialPicture([FromBody] axiosChangeMaterialPictureModel data)
{
string defaultPath = _webHostEnvironment.WebRootPath;
string oldPicture = _warehouseService.ChangeMaterialPicture(data.Image, data.MaterialId, defaultPath);
if (!string.IsNullOrEmpty(oldPicture))
{
// Delete the old image
_convertService.DeleteMaterialFile(oldPicture);
return Ok();
}
else
{
return BadRequest();
}
}
</code></pre>
<p>Javascript:</p>
<pre><code>let arrBinaryFile = [];
let file = document.getElementById(`file-${materialId}`).files[0];
let reader = new FileReader();
// Array
reader.readAsArrayBuffer(file);
reader.onloadend = function (evt) {
if (evt.target.readyState == FileReader.DONE) {
var arrayBuffer = evt.target.result,
array = new Uint8Array(arrayBuffer);
for (var i = 0; i < array.length; i++) {
arrBinaryFile.push(array[i]);
}
}
}
console.log(arrBinaryFile);
let baseUrl = `${baseSharedUrl}/Warehouse/ChangeMaterialPicture`;
var data = {
Image : arrBinaryFile,
MaterialId: materialId
}
axios.post(baseUrl, data)
.then(function (response) {
})
.catch(function (error) {
})
</code></pre>
<p>Javascript Array Image:
<a href="https://i.stack.imgur.com/kt3uF.png" rel="nofollow noreferrer">ImageFromTheArray</a></p>
<p><strong>UPDATE:</strong>
After some research, to send array data I had to add the header with octet-stream. I'm getting 415 Unsupported Media Type, however, in the request I can see the data-with the array. Now the problem is how can I solve this 415?</p>
<pre><code>let config = {
headers: {
"Content-Type": "application/octet-stream",
}
}
</code></pre>
|
[
{
"answer_id": 74560310,
"author": "Michał Zych",
"author_id": 7449914,
"author_profile": "https://Stackoverflow.com/users/7449914",
"pm_score": 1,
"selected": false,
"text": "public Array[] Image { get; set; } public byte[] Image { get; set; }"
},
{
"answer_id": 74561081,
"author": "Michał Zych",
"author_id": 7449914,
"author_profile": "https://Stackoverflow.com/users/7449914",
"pm_score": 0,
"selected": false,
"text": "reader.onloadend = function (evt) {\nif (evt.target.readyState == FileReader.DONE) {\n var arrayBuffer = evt.target.result,\n array = new Uint8Array(arrayBuffer);\n for (var i = 0; i < array.length; i++) {\n arrBinaryFile.push(array[i]);\n }\n \n //post data when arrBinaryFile is ready\n console.log(arrBinaryFile);\n let baseUrl = `${baseSharedUrl}/Warehouse/ChangeMaterialPicture`;\n \n var data = {\n Image : arrBinaryFile,\n MaterialId: materialId \n }\n axios.post(baseUrl, data)\n .then(function (response) {\n })\n .catch(function (error) {\n }) \n}\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74560166",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20338580/"
] |
74,560,198
|
<p>I am trying for an hour's and not getting the satisfied output.</p>
<p>Below in the code, the first variable <strong>db</strong> fetching the value from database. And, the second variable <strong>api</strong> sending the value into api request.</p>
<p>When I comparing these two variables, getting the <strong>not equal</strong> output. I don't know why?</p>
<p>Please give your suggestions.</p>
<p>One more thing, from the next time How do I compare these two values using which methods.</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>const db = 'Sales E-mail'
const api = 'Sales E-mail'
console.log(db==api?'equal':'not equal')
console.log(api.length,db.length)
console.log(typeof api,typeof db)</code></pre>
</div>
</div>
</p>
|
[
{
"answer_id": 74560310,
"author": "Michał Zych",
"author_id": 7449914,
"author_profile": "https://Stackoverflow.com/users/7449914",
"pm_score": 1,
"selected": false,
"text": "public Array[] Image { get; set; } public byte[] Image { get; set; }"
},
{
"answer_id": 74561081,
"author": "Michał Zych",
"author_id": 7449914,
"author_profile": "https://Stackoverflow.com/users/7449914",
"pm_score": 0,
"selected": false,
"text": "reader.onloadend = function (evt) {\nif (evt.target.readyState == FileReader.DONE) {\n var arrayBuffer = evt.target.result,\n array = new Uint8Array(arrayBuffer);\n for (var i = 0; i < array.length; i++) {\n arrBinaryFile.push(array[i]);\n }\n \n //post data when arrBinaryFile is ready\n console.log(arrBinaryFile);\n let baseUrl = `${baseSharedUrl}/Warehouse/ChangeMaterialPicture`;\n \n var data = {\n Image : arrBinaryFile,\n MaterialId: materialId \n }\n axios.post(baseUrl, data)\n .then(function (response) {\n })\n .catch(function (error) {\n }) \n}\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74560198",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9342432/"
] |
74,560,208
|
<p>i am a newbie to WPF mvvm, i created a treeview and i want to set isSelected value of a specific treeviewitem in this tree (for example, item with "19-ASDFDSSD") but i dont know how to do it. Can you help me? Any help will be appreciated.</p>
<p><a href="https://i.stack.imgur.com/Le5xo.png" rel="nofollow noreferrer">treeview</a>
<a href="https://i.stack.imgur.com/RaAQy.png" rel="nofollow noreferrer">wpf code</a></p>
<p><a href="https://i.stack.imgur.com/iXTBe.png" rel="nofollow noreferrer">JobsDTOClass</a></p>
|
[
{
"answer_id": 74560310,
"author": "Michał Zych",
"author_id": 7449914,
"author_profile": "https://Stackoverflow.com/users/7449914",
"pm_score": 1,
"selected": false,
"text": "public Array[] Image { get; set; } public byte[] Image { get; set; }"
},
{
"answer_id": 74561081,
"author": "Michał Zych",
"author_id": 7449914,
"author_profile": "https://Stackoverflow.com/users/7449914",
"pm_score": 0,
"selected": false,
"text": "reader.onloadend = function (evt) {\nif (evt.target.readyState == FileReader.DONE) {\n var arrayBuffer = evt.target.result,\n array = new Uint8Array(arrayBuffer);\n for (var i = 0; i < array.length; i++) {\n arrBinaryFile.push(array[i]);\n }\n \n //post data when arrBinaryFile is ready\n console.log(arrBinaryFile);\n let baseUrl = `${baseSharedUrl}/Warehouse/ChangeMaterialPicture`;\n \n var data = {\n Image : arrBinaryFile,\n MaterialId: materialId \n }\n axios.post(baseUrl, data)\n .then(function (response) {\n })\n .catch(function (error) {\n }) \n}\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74560208",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20389096/"
] |
74,560,217
|
<p>In an application where I make a base64 encoded Vcard , I have the problem that I can't encode special characters like in the string "Zone d'activité" , which should become "Wm9uZSBkJ2FjdGl2aXTDqQ==' (encoded by using <a href="https://base64.guru/converter/encode" rel="nofollow noreferrer">https://base64.guru/converter/encode</a>)</p>
<p>I'm using the script I found on <a href="https://openntf.org/XSnippets.nsf/snippet.xsp?id=encode-decode-base-64" rel="nofollow noreferrer">https://openntf.org/XSnippets.nsf/snippet.xsp?id=encode-decode-base-64</a> , which works fine for normal text to encode.</p>
<p>With this encoder I get "Wm9uZSBkJ2FjdGl2aXTp" for the above string ,which isn't correct for my vcard.
I guess I need to replace special characters like "'" or "é" with something else to get it encoded correctly , because base64 can only be normal characters ...?</p>
<pre><code>function base64_encode (data) {
// http://kevin.vanzonneveld.net
// + original by: Tyler Akins (http://rumkin.com)
// + improved by: Bayron Guevara
// + improved by: Thunder.m
// + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
// + bugfixed by: Pellentesque Malesuada
// + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
// + improved by: Rafał Kukawski (http://kukawski.pl)
// * example 1: base64_encode('Kevin van Zonneveld');
// * returns 1: 'S2V2aW4gdmFuIFpvbm5ldmVsZA=='
// mozilla has this native
// - but breaks in 2.0.0.12!
//if (typeof this.window['btoa'] == 'function') {
// return btoa(data);
//}
var b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
var o1, o2, o3, h1, h2, h3, h4, bits, i = 0,
ac = 0,
enc = "",
tmp_arr = [];
if (!data) {
return data;
}
do { // pack three octets into four hexets
o1 = data.charCodeAt(i++);
o2 = data.charCodeAt(i++);
o3 = data.charCodeAt(i++);
bits = o1 << 16 | o2 << 8 | o3;
h1 = bits >> 18 & 0x3f;
h2 = bits >> 12 & 0x3f;
h3 = bits >> 6 & 0x3f;
h4 = bits & 0x3f;
// use hexets to index into b64, and append result to encoded string
tmp_arr[ac++] = b64.charAt(h1) + b64.charAt(h2) + b64.charAt(h3) + b64.charAt(h4);
} while (i < data.length);
enc = tmp_arr.join('');
var r = data.length % 3;
return (r ? enc.slice(0, r - 3) : enc) + '==='.slice(r || 3);
}
var demo = "Zone d'activité"
var test = base64_encode(demo);
return test;
</code></pre>
|
[
{
"answer_id": 74560310,
"author": "Michał Zych",
"author_id": 7449914,
"author_profile": "https://Stackoverflow.com/users/7449914",
"pm_score": 1,
"selected": false,
"text": "public Array[] Image { get; set; } public byte[] Image { get; set; }"
},
{
"answer_id": 74561081,
"author": "Michał Zych",
"author_id": 7449914,
"author_profile": "https://Stackoverflow.com/users/7449914",
"pm_score": 0,
"selected": false,
"text": "reader.onloadend = function (evt) {\nif (evt.target.readyState == FileReader.DONE) {\n var arrayBuffer = evt.target.result,\n array = new Uint8Array(arrayBuffer);\n for (var i = 0; i < array.length; i++) {\n arrBinaryFile.push(array[i]);\n }\n \n //post data when arrBinaryFile is ready\n console.log(arrBinaryFile);\n let baseUrl = `${baseSharedUrl}/Warehouse/ChangeMaterialPicture`;\n \n var data = {\n Image : arrBinaryFile,\n MaterialId: materialId \n }\n axios.post(baseUrl, data)\n .then(function (response) {\n })\n .catch(function (error) {\n }) \n}\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74560217",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1302906/"
] |
74,560,234
|
<p>I am finding it difficult to understand why my code is returning my memory address. I have tried to use <code>__str__</code> and <code>__repr__</code> respectively but maybe I am unfamiliar with how these work exactly.</p>
<pre><code>import random
class Card:
def __init__(self, suit, value):
self.suit = suit #['H','D','C','S']
self.value = value #['A',2,3,4,5,6,7,8,9,10,'J','Q','K']
class Deck:
def __init__(self):
self.cards =[]
def __repr__(self):
return f'Card("{self.card}")'
def build(self):
for x in['H','D','C','S']:
for y in range(1,14):
self.cards.append(Card(x,y))
if(y==1):
self.cards.append(Card(x,'A'))
elif(y==11):
self.cards.append(Card(x,'J'))
elif(y==12):
self.cards.append(Card(x,'Q'))
elif(y==13):
self.cards.append(Card(x,'K'))
def shuffle(self):
for i in range(len(self.cards)-1,0,-1):
r = random.randint(0,i)
self.cards[i], self.cards[r]= self.cards[r], self.cards[i]
def deal(self):
card = self.cards.pop()
print(repr(card))
d = Deck()
d.build()
d.shuffle()
d.deal()
</code></pre>
<pre><code><__main__.Card object at 0x7f836e0ed070>
</code></pre>
<p>Above is the Code and the output that I am getting, any help would be really appreciated.</p>
|
[
{
"answer_id": 74560310,
"author": "Michał Zych",
"author_id": 7449914,
"author_profile": "https://Stackoverflow.com/users/7449914",
"pm_score": 1,
"selected": false,
"text": "public Array[] Image { get; set; } public byte[] Image { get; set; }"
},
{
"answer_id": 74561081,
"author": "Michał Zych",
"author_id": 7449914,
"author_profile": "https://Stackoverflow.com/users/7449914",
"pm_score": 0,
"selected": false,
"text": "reader.onloadend = function (evt) {\nif (evt.target.readyState == FileReader.DONE) {\n var arrayBuffer = evt.target.result,\n array = new Uint8Array(arrayBuffer);\n for (var i = 0; i < array.length; i++) {\n arrBinaryFile.push(array[i]);\n }\n \n //post data when arrBinaryFile is ready\n console.log(arrBinaryFile);\n let baseUrl = `${baseSharedUrl}/Warehouse/ChangeMaterialPicture`;\n \n var data = {\n Image : arrBinaryFile,\n MaterialId: materialId \n }\n axios.post(baseUrl, data)\n .then(function (response) {\n })\n .catch(function (error) {\n }) \n}\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74560234",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12532178/"
] |
74,560,237
|
<p>Here is the link</p>
<p><a href="https://github.com/noel020395/projectno1" rel="nofollow noreferrer">https://github.com/noel020395/projectno1</a>
<a href="https://i.stack.imgur.com/kuEVh.jpg" rel="nofollow noreferrer">enter image description here</a></p>
<p>I m stuck here, unable to fix the layout issue. Any one could guide me the errors?</p>
|
[
{
"answer_id": 74560531,
"author": "Coopero",
"author_id": 2421346,
"author_profile": "https://Stackoverflow.com/users/2421346",
"pm_score": 0,
"selected": false,
"text": "max-width margin:auto section {\n max-width: 1280px;\n margin: auto;\n}\n"
},
{
"answer_id": 74560657,
"author": "NAZIR HUSSAIN",
"author_id": 20587701,
"author_profile": "https://Stackoverflow.com/users/20587701",
"pm_score": 0,
"selected": false,
"text": " <div class=\"col-4 d-flex align-items-center bg-info justify-content-center flex-column\">\n <a href=\"target_blank\"><img src=\"https://baaylimo.sg/wp-content/uploads/2020/10/voxy-600x380.jpg\"\n width=\"300px\" /></a>\n <p>Toyota </p>\n </div>\n"
},
{
"answer_id": 74562987,
"author": "Crystal",
"author_id": 16255006,
"author_profile": "https://Stackoverflow.com/users/16255006",
"pm_score": 0,
"selected": false,
"text": "@media screen and (max-width: 100%){\nbody{width: 100%;}}\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74560237",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20318276/"
] |
74,560,242
|
<p>I have a BoxComponent that has only one field, an array of numbers. The selector for this Component is <code>app-box</code></p>
<p><code>box.component.html</code></p>
<pre><code><p>
<span *ngFor="let num of cards">Number is {{num}}</span>
</p>
</code></pre>
<p><code>box.component.ts</code></p>
<pre><code>export class BoxComponent {
cards: number[] = [];
top_up(val: number) {
this.cards.push(val);
}
}
</code></pre>
<p>In its parent AppComponent, I added a single field that stores a BoxComponent object.</p>
<p><code>app.component.html</code></p>
<pre><code><app-box></app-box>
<button (click)="push()">Top-up</button>
</code></pre>
<p><code>app.component.ts</code></p>
<pre><code>export class AppComponent {
title = 'test';
box: BoxComponent = new BoxComponent();
push() {
this.box.top_up(Math.floor(Math.random() * 10));
}
}
</code></pre>
<p>I wish to make the click in the appcomponent template to modify the contents of <code>app-box</code>.
However angular does not update the app-box when the button is clicked. I somehow was able to confirm that the field box of appcomponent actually gets updated, the change just doesn't show in the browser. Based on this I have concluded that the <code>app-box</code> tag creates a different <code>BoxComponent</code> rather than use the one I have created within the AppComponent class.</p>
<p>Am I right? How do I make angular render my box and respond to changes I make to it from the AppComponent click event?</p>
<p>Edit: I have simplified the problem to its simplest form.</p>
|
[
{
"answer_id": 74560536,
"author": "Vishnu Prabhu",
"author_id": 20587586,
"author_profile": "https://Stackoverflow.com/users/20587586",
"pm_score": 0,
"selected": false,
"text": "export class Card {\n suit: number | undefined;\n rank: number | undefined;\n\n constructor(suit: number, rank: number) {\n this.suit = suit;\n this.rank = rank;\n }\n}\n import { Component } from '@angular/core';\nimport { Card } from '../card';\n\n@Component({\n selector: 'app-player',\n templateUrl: './player.component.html',\n styleUrls: ['./player.component.css'],\n})\nexport class PlayerComponent {\n cards: Card[] = [];\n\n constructor() {\n this.cards = [new Card(2, 4), new Card(3, 7)];\n }\n\n add_card() {\n return this.cards.push(new Card(2, 4));\n }\n}\n <div class=\"card-container\">\n <ng-content></ng-content>\n <div class=\"inner\">\n <div class=\"card\" *ngFor=\"let card of cards\">\n <span>suit {{card.suit}}</span>\n <span>rank {{card.rank}}</span>\n </div>\n </div>\n <button (click)=\"add_card()\">Add</button>\n</div>\n"
},
{
"answer_id": 74563246,
"author": "shubham sharma",
"author_id": 18827509,
"author_profile": "https://Stackoverflow.com/users/18827509",
"pm_score": 0,
"selected": false,
"text": "@ViewChild(BoxComponent)BoxComponentRef:BoxComponent;\npush()\n{\nthis.BoxComponentRef.top_up(Math.floor(Math.random());\n}\n"
},
{
"answer_id": 74564416,
"author": "Vahid18u",
"author_id": 1302157,
"author_profile": "https://Stackoverflow.com/users/1302157",
"pm_score": 2,
"selected": true,
"text": "export class AppComponent {\n title = 'test';\n @ViewChild('bComponent') boxComponent!: BoxComponent;\n\n push() {\n this.boxComponent.top_up(Math.floor(Math.random() * 10));\n }\n}\n <app-box #bComponent></app-box>\n<button (click)=\"push()\">Top-up</button>\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74560242",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18494246/"
] |
74,560,269
|
<p>I'm looking for vocabulary or for a library that supports the following behaviour:</p>
<p>Imagine a Javascript object like the following one:</p>
<pre><code>const foo = {
id: 1,
name: 'Some String value',
supplier: async () => {
return 'Some supplier name'
},
nested: async () => {
return [
{
id: 2,
name: async () => {
return 'this is a name'
}
}
]
}
}
</code></pre>
<p>It is composed by native types (numbers, strings...) and by functions.</p>
<p>I'd like this object being transformed to the following one:</p>
<pre><code>const resolved = {
id: 1,
name: 'Some string value',
supplier: 'Some supplier name',
nested: [
{
id: 2,
name: 'this is a name'
}
]
}
</code></pre>
<p>As you see the transformed object does not have functions anymore but only native values.</p>
<p>If you are familiar with GraphQL resolvers, it might ring a bell to you.</p>
<p>I know I can write my own implementation of the behaviour but I'm sure this is something that already exists somewhere.</p>
<p>Do you have some keywords to share?</p>
|
[
{
"answer_id": 74606482,
"author": "Peter Seliger",
"author_id": 2627243,
"author_profile": "https://Stackoverflow.com/users/2627243",
"pm_score": 1,
"selected": false,
"text": "function isAsynFunction(value) {\n return (/^\\[object\\s+AsyncFunction\\]$/)\n .test(Object.prototype.toString.call(value));\n}\nfunction isObject(value) {\n return (value && ('object' === typeof value));\n}\n\nfunction collectAsyncEntriesRecursively(obj, resolved = {}) {\n return Object\n .entries(obj)\n .reduce((result, [key, value]) => {\n\n if (isAsynFunction(value)) {\n\n result.push({ type: obj, key });\n\n } else if (isObject(value)) {\n result\n .push(\n // recursion.\n ...collectAsyncEntriesRecursively(value)\n );\n }\n return result;\n\n }, []);\n}\n\n// - recursively aggregates (one deferred data layer\n// after the other) a real but deferred resolved\n// copy of the initially provided data-structure.\nasync function resolveLazyInitializableObject(obj) {\n const deferred = Object.assign({}, obj);\n\n // - in order to entirely mutate the initially provided\n // data-structure delete the above assignement and\n // replace every occurrence of `deferred` with `obj`.\n\n const deferredEntries = collectAsyncEntriesRecursively(deferred);\n if (deferredEntries.length >= 1) {\n\n const results = await Promise\n .all(\n deferredEntries\n .map(({ type, key }) => type[key]())\n );\n deferredEntries\n .forEach(({ type, key }, idx) => type[key] = results[idx]);\n\n // recursion.\n await resolveLazyInitializableObject(results);\n }\n return deferred;\n}\n\n\nconst foo = {\n id: 1,\n name: 'Some String value',\n supplier: async () => {\n return 'Some supplier name'\n },\n nested: async () => {\n return [\n {\n id: 2,\n name: async () => {\n return 'this is a name'\n }\n }\n ]\n }\n};\nconst complexDeferred = {\n id: 1,\n name: 'Some String value',\n supplier: async () => {\n return 'Some supplier name'\n },\n nested: async () => {\n return [{\n id: 2,\n name: async () => {\n return 'this is a name'\n }\n }, {\n id: 3,\n name: async () => {\n return 'this is another name'\n }\n }, {\n id: 4,\n nested: async () => {\n return [{\n id: 5,\n name: async () => {\n return 'this is yet another name'\n }\n }];\n }\n }];\n }\n};\n\n(async () => {\n const resolved = await resolveLazyInitializableObject(foo);\n console.log({ foo, resolved })\n})();\n\nresolveLazyInitializableObject(complexDeferred)\n .then(complexResolved =>\n console.log({ complexDeferred, complexResolved })\n ); .as-console-wrapper { min-height: 100%!important; top: 0; }"
},
{
"answer_id": 74606618,
"author": "Bergi",
"author_id": 1048572,
"author_profile": "https://Stackoverflow.com/users/1048572",
"pm_score": 3,
"selected": true,
"text": "execute async function initialised(value) {\n if (typeof value == 'function') return initialised(await value());\n if (typeof value != 'object' || !value) return value;\n if (Array.isArray(value)) return Promise.all(value.map(initialised));\n return Object.fromEntries(await Promise.all(Object.entries(value).map(([k, v]) =>\n initialised(v).then(r => [k, r])\n )));\n}\n async function initialised(value) {\n if (typeof value == 'function') return initialised(await value());\n if (typeof value != 'object' || !value) return value;\n if (Array.isArray(value)) return Promise.all(value.map(initialised));\n return Object.fromEntries(await Promise.all(Object.entries(value).map(([k, v]) =>\n initialised(v).then(r => [k, r])\n )));\n}\n\nconst foo = {\n id: 1,\n name: 'Some String value',\n supplier: async () => {\n return 'Some supplier name'\n },\n nested: async () => {\n return [\n {\n id: 2,\n name: async () => {\n return 'this is a name'\n }\n }\n ]\n }\n};\n\ninitialised(foo).then(resolved => {\n console.log(resolved);\n})"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74560269",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4547701/"
] |
74,560,276
|
<p>I need to combine two arrays of objects:</p>
<pre><code>const local: [
{id: 1, balance: 2200, ref: 'A'},
{id: 2, balance: 2100, ref: 'C'}
]
const remote: [
{id: 1, balance: 3300, ref: 'B'},
]
</code></pre>
<p>I need to merge these arrays, such any two objects with the same id are merged - keeping the same ID, keeping the balance from <code>remote</code> and combining their <code>ref</code> values, so the ideal output of this example would be:</p>
<pre><code> [
{ id: 1, balance: 3300, text: 'A / B' },
{ id: 2, balance: 2100, text: 'C' }
]
</code></pre>
<p>How would I do this? Ive tried the following:</p>
<pre><code>function mergeFunc(remoteArray, localArray) {
const newArray = [];
//loop over one of the arrays
for (const localObj of localArray) {
//for each iteration, search for object with matching id in other array
if(remoteArray.some(remoteObj => remoteObj.id === localObj.id)){
//if found matching id, fetch this other object
const id:matchingRemoteObj = remoteArray.find(item => item.id === localObj.id);
//create new, merged, object
const newObj = {id:matchingRemoteObj.id, balance: id:matchingRemoteObj.balance, text:`${localObj.text} / ${id:matchingRemoteObj.text}`}
//push new value to array
newArray.push(newObj);
}
}
return newArray;
}
</code></pre>
<p>The issue is, this solution gives me an array of merged objects that had matching ID's. I need an array with <em>all</em> objects, only merging the ones with matching id's...</p>
|
[
{
"answer_id": 74560422,
"author": "flyingfox",
"author_id": 3176419,
"author_profile": "https://Stackoverflow.com/users/3176419",
"pm_score": 2,
"selected": true,
"text": "if(remoteArray.some(remoteObj => remoteObj.id === localObj.id))\n Array.map() Array.find() const local = [\n {id: 1, balance: 2200, ref: 'A'},\n {id: 2, balance: 2100, ref: 'C'}\n]\nconst remote = [\n {id: 1, balance: 3300, ref: 'B'},\n]\n\nlet result = local.map(e =>{\n let r = remote.find(i => i.id === e.id)\n let ref = r?.ref\n if(ref){\n e.balance = r.balance\n e.ref += ' / ' + ref\n }\n return e\n})\nconsole.log(result) else const local = [\n {id: 1, balance: 2200, ref: 'A'},\n {id: 2, balance: 2100, ref: 'C'}\n]\nconst remote = [\n {id: 1, balance: 3300, ref: 'B'},\n]\n\n\nfunction mergeFunc(remoteArray, localArray) {\n const newArray = [];\n //loop over one of the arrays\n for (const localObj of localArray) {\n //for each time, search for object with matching id in other array\n if(remoteArray.some(remoteObj => remoteObj.id === localObj.id)){\n //if found matching id, fetch this other object\n const matchingRemoteObj = remoteArray.find(item => item.id === localObj.id);\n //create new, merged, object\n const newObj = {id:matchingRemoteObj.id, balance: matchingRemoteObj.balance, text:`${localObj.ref} / ${matchingRemoteObj.ref}`}\n //push new value to array\n newArray.push(newObj);\n }else{\n // this will add not match record into result array\n newArray.push(localObj) \n }\n }\n return newArray;\n}\n\nlet result = mergeFunc(remote,local)\nconsole.log(result)"
},
{
"answer_id": 74560529,
"author": "Maniraj Murugan",
"author_id": 7785337,
"author_profile": "https://Stackoverflow.com/users/7785337",
"pm_score": 2,
"selected": false,
"text": "array.map array.find obj.balance = o.balance\n obj.ref = `${obj.ref} / ${o.ref}`\n const local = [\n { id: 1, balance: 2200, ref: \"A\" },\n { id: 2, balance: 2100, ref: \"C\" },\n ];\n const remote = [{ id: 1, balance: 3300, ref: \"B\" }];\n\n const result = local.map((obj) => {\n remote.find((o) => {\n if (o.id === obj.id) {\n obj.balance = o.balance;\n obj.ref = `${obj.ref} / ${o.ref}`;\n }\n });\n return obj;\n });\n\n console.log(result);"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74560276",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7217840/"
] |
74,560,307
|
<p>I have a request body like this for post method.</p>
<pre><code>{
"emp_id" : "1234"
}
</code></pre>
<p>Controller is like this.</p>
<pre><code>@PostMapping("/employees)
public ResponseEntity<EmployeeResponse> getMatchingValues(@RequestBody HashMap<String,String> params){
}
</code></pre>
<p>Now my request body will be updated to the one as shown below.</p>
<pre><code>{
"emp_id" : "1234",
"ids" : ["4567","9087"]
}
</code></pre>
<p>How can I update the post mapping in controller?
Can someone help on this?</p>
|
[
{
"answer_id": 74560764,
"author": "Abirami Balasubramaniyan",
"author_id": 5755531,
"author_profile": "https://Stackoverflow.com/users/5755531",
"pm_score": 0,
"selected": false,
"text": "@PostMapping(\"/employees)\npublic ResponseEntity<EmployeeResponse> getMatchingValues(@RequestBody HashMap<String,Object> params){\n System.out.println(\"params = \"+params);\n \n}\n"
},
{
"answer_id": 74561203,
"author": "Leonardo Emmanuel de Azevedo",
"author_id": 19979867,
"author_profile": "https://Stackoverflow.com/users/19979867",
"pm_score": 2,
"selected": true,
"text": "public RequestData{\n private String emp_id;\n private List<String> ids;\n...\n//TODO: getters and setters here\n}\n @PostMapping(\"/employees)\npublic ResponseEntity<EmployeeResponse> getMatchingValues(@RequestBody RequestData requestData){\n}\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74560307",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18109095/"
] |
74,560,320
|
<h2>Approach I</h2>
<p>While trying to get a hierarchical tree of all the xpaths in a website (<a href="https://startpagina.nl" rel="nofollow noreferrer">https://startpagina.nl</a>) using Python, I first tried to get the xpath for the branch: <code>/html/body</code> using:</p>
<pre class="lang-py prettyprint-override"><code>from selenium import webdriver
url = 'https://startpagina.nl'
driver = webdriver.Firefox()
driver.get(url)
test = driver.find_elements_by_xpath('//*')
print(len(test))
driver.close()
</code></pre>
<p>and that yields a list of all elements in the website, according to the answer by @Prophet. However, I did not yet determine how to get the xpaths of these elements, nor how to sort them into a tree-like structure.</p>
<p>And the <code>/html/body/div[6]</code> option yields a length of 1 instead of a tree.</p>
<h2>Approach II</h2>
<p>Based on the answer by @Micheal Kay, I tried to "Walk the xml" using the following Python code:</p>
<pre class="lang-py prettyprint-override"><code>import requests
from bs4 import BeautifulSoup
import xml.etree.cElementTree as ET
from lxml import etree
unformatted_filename = "first.xml"
formatted_filename = "first.xml"
# Get XML from url.
resp = requests.get("https://startpagina.nl")
# resp = requests.get('https://stackoverflow.com')
with open(unformatted_filename, "wb") as foutput:
foutput.write(resp.content)
# Improve XML formatting
with open(unformatted_filename) as fp:
soup = BeautifulSoup(fp, "xml")
print(f"soup={soup}")
with open(formatted_filename, "w") as f:
f.write(soup.prettify())
# Parse XML
tree = ET.parse(formatted_filename, parser=ET.XMLParser(encoding="utf-8"))
root = tree.getroot()
for child in root:
child.tag, child.attrib
tree = ET.parse(formatted_filename)
for elem in tree.getiterator():
if elem.tag:
print("my name:")
print("\t" + elem.tag)
if elem.text:
print("my text:")
print("\t" + (elem.text).strip())
if elem.attrib.items():
print("my attributes:")
for key, value in elem.attrib.items():
print("\t" + "\t" + key + " : " + value)
if list(elem): # use elem.getchildren() for python2.6 or before
print("my no of child: %d" % len(list(elem)))
else:
print("No child")
if elem.tail:
print("my tail:")
print("\t" + "%s" % elem.tail.strip())
print("$$$$$$$$$$")
</code></pre>
<p>However, I did not yet determine how to get the xpaths of the respective elements.</p>
<h2>Question</h2>
<p>Hence, I would like to ask:</p>
<p><em>How does one get a tree of all the xpaths in website, using Python?</em>
(And I wondered whether this tree will be cyclic or not, though I expect I will find out once I know how to get the Tree.).</p>
<h2>Expected Output</h2>
<p>Based on manually going through the HTML:
<a href="https://i.stack.imgur.com/68lvt.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/68lvt.png" alt="enter image description here" /></a>
I would expect the output to look something like this:</p>
<pre><code>
| /html
|-- //*[@id="browser-upgrade-notification"]
|-- //*[@id="app"]
|-- /html/head
|-- /html/body
|--/-- /html/body/noscript
|--/-- /html/body/div[2]
|--/-- /html/body/header/section
|--/--/-- /html/body/header/section/div
|--/--/--/-- /html/body/header/section/div/div[1]
....
</code></pre>
<p>This would be an example of the list of tree.</p>
|
[
{
"answer_id": 74560523,
"author": "Prophet",
"author_id": 3485434,
"author_profile": "https://Stackoverflow.com/users/3485434",
"pm_score": 1,
"selected": false,
"text": "/html/body/ /html/body /html/body/div[6] /html/body/div[6]/* //* driver.find_elements_by_xpath"
},
{
"answer_id": 74560555,
"author": "Michael Kay",
"author_id": 415448,
"author_profile": "https://Stackoverflow.com/users/415448",
"pm_score": 2,
"selected": false,
"text": "/a/b/../b/../b/../b /a[i]/b[j]/c[k] /a/b/c /a/b/d /html/body/ /"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74560320",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7437143/"
] |
74,560,321
|
<p>I want to make a <strong>AlertDialog</strong> which is included a slider (especially <code>SfRangeSlider()</code>).</p>
<p>My AlertDialog Image:</p>
<p><a href="https://i.stack.imgur.com/uoNFC.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/uoNFC.png" alt="enter image description here" /></a></p>
<p>There is a problem with the height of AlertDialog.</p>
<p>My question is how to reduce the dialog size including the <code>SfRangeSlider()</code>.</p>
<p>My <code>_showDialog()</code> as below:</p>
<pre><code>void _showDialog() async {
await showDialog<String>(
context: context,
builder: (BuildContext context) => AlertDialog(
title: const Text('총톤수'),
content: SfRangeSlider(
min: 0.0,
max: 100.0,
values: _values,
interval: 10,
showTicks: false,
showLabels: true,
enableTooltip: true,
minorTicksPerInterval: 1,
onChanged: (SfRangeValues values) {
setState(() {
_values = values;
});
},
),
actions: <Widget>[
TextButton(
onPressed: () => Navigator.pop(context, 'Cancel'),
child: const Text('Cancel'),
),
TextButton(
onPressed: () => Navigator.pop(context, 'OK'),
child: const Text('OK'),
),
],
),
);
}
</code></pre>
<p>Thank you.</p>
|
[
{
"answer_id": 74560473,
"author": "Yeasin Sheikh",
"author_id": 10157127,
"author_profile": "https://Stackoverflow.com/users/10157127",
"pm_score": 2,
"selected": false,
"text": "SfRangeSlider void _showDialog() async {\n await showDialog<String>(\n context: context,\n builder: (BuildContext context) => AlertDialog(\n title: const Text('총톤수'),\n content: SizedBox(\n height: x, // x= hard-coded value or you can use MediaQuery.of(context).size.height *.5 ,,50% height \n child: SfRangeSlider(\n min: 0.0,\n"
},
{
"answer_id": 74560617,
"author": "eamirho3ein",
"author_id": 10306997,
"author_profile": "https://Stackoverflow.com/users/10306997",
"pm_score": 2,
"selected": true,
"text": "SfRangeSlider Column mainAxisSize min showDialog<String>(\n context: context,\n builder: (BuildContext context) => AlertDialog(\n title: const Text('총톤수'),\n content: Column(\n mainAxisSize: MainAxisSize.min,\n children: [\n SfRangeSlider(\n min: 0.0,\n max: 100.0,\n values: _values,\n interval: 10,\n showTicks: false,\n showLabels: true,\n enableTooltip: true,\n minorTicksPerInterval: 1,\n onChanged: (SfRangeValues values) {\n setState(() {\n _values = values;\n });\n },\n ),\n ],\n ),\n actions: <Widget>[\n TextButton(\n onPressed: () => Navigator.pop(context, 'Cancel'),\n child: const Text('Cancel'),\n ),\n TextButton(\n onPressed: () => Navigator.pop(context, 'OK'),\n child: const Text('OK'),\n ),\n ],\n ),\n );\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74560321",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19443112/"
] |
74,560,371
|
<p>I'm trying to access the values of a python dictionary, but the line is too long so it doesn't match PEP-8 rules. (I'm using flake8 linter on vscode)</p>
<p>example:</p>
<pre><code>class GoFirstSpider():
def __init__(self, flight_search_request):
self.name = 'goFirst'
-> self.date = flight_search_request["FlightSearchRequest"]["FlightDetails"]["DepartureDate"]
</code></pre>
<p>I've tried:</p>
<pre><code>self.date = flight_search_request["FlightSearchRequest"]\
["FlightDetails"]["DepartureDate"]
</code></pre>
<p>and got:</p>
<pre><code>whitespace before '['
</code></pre>
<p>Thanks.</p>
|
[
{
"answer_id": 74560473,
"author": "Yeasin Sheikh",
"author_id": 10157127,
"author_profile": "https://Stackoverflow.com/users/10157127",
"pm_score": 2,
"selected": false,
"text": "SfRangeSlider void _showDialog() async {\n await showDialog<String>(\n context: context,\n builder: (BuildContext context) => AlertDialog(\n title: const Text('총톤수'),\n content: SizedBox(\n height: x, // x= hard-coded value or you can use MediaQuery.of(context).size.height *.5 ,,50% height \n child: SfRangeSlider(\n min: 0.0,\n"
},
{
"answer_id": 74560617,
"author": "eamirho3ein",
"author_id": 10306997,
"author_profile": "https://Stackoverflow.com/users/10306997",
"pm_score": 2,
"selected": true,
"text": "SfRangeSlider Column mainAxisSize min showDialog<String>(\n context: context,\n builder: (BuildContext context) => AlertDialog(\n title: const Text('총톤수'),\n content: Column(\n mainAxisSize: MainAxisSize.min,\n children: [\n SfRangeSlider(\n min: 0.0,\n max: 100.0,\n values: _values,\n interval: 10,\n showTicks: false,\n showLabels: true,\n enableTooltip: true,\n minorTicksPerInterval: 1,\n onChanged: (SfRangeValues values) {\n setState(() {\n _values = values;\n });\n },\n ),\n ],\n ),\n actions: <Widget>[\n TextButton(\n onPressed: () => Navigator.pop(context, 'Cancel'),\n child: const Text('Cancel'),\n ),\n TextButton(\n onPressed: () => Navigator.pop(context, 'OK'),\n child: const Text('OK'),\n ),\n ],\n ),\n );\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74560371",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18464138/"
] |
74,560,395
|
<p>Code:</p>
<pre><code>import logging
def main(name: str) -> str:
return f"Hello {name}!"
print({name})
</code></pre>
<p>I wanna get main function output store in variable and use in outside the function. I'm new in python, I cannot see exact same example on net, Check multiple ways but not getting value.</p>
<p>There is no any value getting inside the print({name}) or print({main}).</p>
|
[
{
"answer_id": 74560500,
"author": "Guf",
"author_id": 17444641,
"author_profile": "https://Stackoverflow.com/users/17444641",
"pm_score": 2,
"selected": true,
"text": "def main(name: str) -> str:\n return f\"Hello {name}!\"\n\n# You can use\nprint(main(\"world\"))\n# or\nvar = main(\"world\")\nprint(var)\n# or Under the current file\nif __name__ == '__main__':\n var = main(\"world\")\n print(var)\n"
},
{
"answer_id": 74560528,
"author": "Alec Cureau",
"author_id": 20590353,
"author_profile": "https://Stackoverflow.com/users/20590353",
"pm_score": 0,
"selected": false,
"text": "import logging\n\ndef main(name: str) -> str:\n return f\"Hello {name}!\"\n\nreturn_value = main(\"your name\")\n"
},
{
"answer_id": 74560592,
"author": "Orfeas Bourchas",
"author_id": 16781682,
"author_profile": "https://Stackoverflow.com/users/16781682",
"pm_score": 0,
"selected": false,
"text": "main(f'{name}') f'{name}' import logging\nname = 'world'\ndef main(name: str) -> str:\n return f\"Hello {name}!\"\n\nprint(main(f'{name}')) # If you just want to print it.\n\nval = main(f'{name}') # If you want to store the output as[Guf] said.\n\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74560395",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16727671/"
] |
74,560,417
|
<blockquote>
<p>Column Alignment</p>
</blockquote>
<pre><code>columnDefs: [
{ targets: [1, 2], className: "cssMyRightAlign" },
],
</code></pre>
<blockquote>
<p>CSS</p>
</blockquote>
<pre><code>.cssMyRightAlign{
text-align: right;
}
</code></pre>
<p>But its not aligning column 1 & 2 in right.</p>
<p>Codepen Link
<a href="https://codepen.io/Sixthsense6/pen/KKeRPXJ" rel="nofollow noreferrer">https://codepen.io/Sixthsense6/pen/KKeRPXJ</a></p>
|
[
{
"answer_id": 74561629,
"author": "ruleboy21",
"author_id": 6214210,
"author_profile": "https://Stackoverflow.com/users/6214210",
"pm_score": 1,
"selected": false,
"text": ".cssMyRightAlign !important .cssMyRightAlign{\n text-align: right !important;\n}\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74560417",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4025652/"
] |
74,560,435
|
<p>I just started python yesterday so I was trying to make this python code to make a calculator that adds, multiplies, divides, and subtracts. When I started testing the code just wasn't working even though I did similar things and to me, the code looked right this is the code:</p>
<pre><code>op =input("which operation would you like to use (type m for multiply d for divide s for subtract a for addition): ")
first_number =float(input("please enter your first number: "))
second_number =float(input("please enter your second number: "))
if op.upper()=="m" or op.lower()=="m":
print("multiply")
elif op.upper()=="d" or op.lower()=="d":
print("divide")
elif op.upper()=="s" or op.lower()=="s":
print("subtract")
elif op.upper()=="a" or op.lower()=="a":
print("addition")
else:print("the operation you entered is not available")
</code></pre>
<p>I was expecting it to take input and based on this it would know what operation I wanted to make but this is the error I got:</p>
<pre><code>elif op.upper()=="d" or op.lower()=="d":
^
IndentationError: unindent does not match any outer indentation level
</code></pre>
|
[
{
"answer_id": 74560495,
"author": "rtoth",
"author_id": 20589189,
"author_profile": "https://Stackoverflow.com/users/20589189",
"pm_score": -1,
"selected": false,
"text": "op =input(\"which operation would you like to use (type m for multiply d for divide s for subtract a for addition): \")\nfirst_number =float(input(\"please enter your first number: \"))\nsecond_number =float(input(\"please enter your second number: \"))\nif op.upper()==\"m\" or op.lower()==\"m\":\n print(\"multiply\")\nelif op.upper()==\"d\" or op.lower()==\"d\":\n print(\"divide\")\nelif op.upper()==\"s\" or op.lower()==\"s\":\n print(\"subtract\")\nelif op.upper()==\"a\" or op.lower()==\"a\":\n print(\"addition\")\nelse:\n print(\"the operation you entered is not available\")\n"
},
{
"answer_id": 74560514,
"author": "Manish",
"author_id": 12172071,
"author_profile": "https://Stackoverflow.com/users/12172071",
"pm_score": 1,
"selected": true,
"text": "op =input(\"which operation would you like to use (type m for multiply d for divide s for subtract a for addition): \")\nfirst_number =float(input(\"please enter your first number: \"))\nsecond_number =float(input(\"please enter your second number: \"))\nif op.upper()==\"m\" or op.lower()==\"m\":\n print(\"multiply\")\nelif op.upper()==\"d\" or op.lower()==\"d\":\n print(\"divide\")\nelif op.upper()==\"s\" or op.lower()==\"s\":\n print(\"subtract\")\nelif op.upper()==\"a\" or op.lower()==\"a\":\n print(\"addition\")\nelse:\n print(\"the operation you entered is not available\")\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74560435",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20590423/"
] |
74,560,439
|
<p>I have this code snippet that uses OpenCSV:</p>
<pre><code>class Pojo {
@CsvBindByName(column="point")
Integer point;
@CsvBindByName(column="name")
String name;
}
</code></pre>
<p>And:</p>
<pre><code>class Main {
readFile(){
CsvReader reader = new Csv(.....);
CsvToBean<Pojo> bean = new CsvToBeanBuilder<Pojo>(reader)...;
List<Pojo> list = bean.parse();
}
}
</code></pre>
<p>Why is it - while parsing - not considering header coming with <em><a href="https://www.fileformat.info/info/unicode/char/feff/index.htm" rel="nofollow noreferrer">zwnbsp</a></em> and that column value I am getting as <code>null</code>?</p>
<p>Example input data:</p>
<p><em>ZWNBSPpoint</em></p>
|
[
{
"answer_id": 74560495,
"author": "rtoth",
"author_id": 20589189,
"author_profile": "https://Stackoverflow.com/users/20589189",
"pm_score": -1,
"selected": false,
"text": "op =input(\"which operation would you like to use (type m for multiply d for divide s for subtract a for addition): \")\nfirst_number =float(input(\"please enter your first number: \"))\nsecond_number =float(input(\"please enter your second number: \"))\nif op.upper()==\"m\" or op.lower()==\"m\":\n print(\"multiply\")\nelif op.upper()==\"d\" or op.lower()==\"d\":\n print(\"divide\")\nelif op.upper()==\"s\" or op.lower()==\"s\":\n print(\"subtract\")\nelif op.upper()==\"a\" or op.lower()==\"a\":\n print(\"addition\")\nelse:\n print(\"the operation you entered is not available\")\n"
},
{
"answer_id": 74560514,
"author": "Manish",
"author_id": 12172071,
"author_profile": "https://Stackoverflow.com/users/12172071",
"pm_score": 1,
"selected": true,
"text": "op =input(\"which operation would you like to use (type m for multiply d for divide s for subtract a for addition): \")\nfirst_number =float(input(\"please enter your first number: \"))\nsecond_number =float(input(\"please enter your second number: \"))\nif op.upper()==\"m\" or op.lower()==\"m\":\n print(\"multiply\")\nelif op.upper()==\"d\" or op.lower()==\"d\":\n print(\"divide\")\nelif op.upper()==\"s\" or op.lower()==\"s\":\n print(\"subtract\")\nelif op.upper()==\"a\" or op.lower()==\"a\":\n print(\"addition\")\nelse:\n print(\"the operation you entered is not available\")\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74560439",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3070677/"
] |
74,560,448
|
<p>I am trying to use different fill for <code>geom_ribbon</code> according to the x-values (For Temp = 0-20 one fill, 20-30.1 another fill and > 30.1 another fill). I am using the following code</p>
<pre><code>library(tidyverse)
bounds2 <- df %>%
mutate(ymax = pmax(Growth.rate, slope),
ymin = pmin(Growth.rate, slope),
x_bins = cut(Temp, breaks = c(0,20,30.1,max(Temp)+5)))
ggplot(df, aes(x = Temp, y = Growth.rate)) +
geom_line(colour = "blue") +
geom_line(aes(y = slope), colour = "red") +
scale_y_continuous(sec.axis = sec_axis(~ .^1, name = "slope")) +
geom_ribbon(data = bounds2, aes(Temp, ymin = ymin, ymax = ymax, fill = x_bins),
alpha = 0.4)
</code></pre>
<p>It is returning me following output
<a href="https://i.stack.imgur.com/jy5nF.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/jy5nF.png" alt="enter image description here" /></a></p>
<p>As you can see from the output some regions are remaining empty. Now how can I fill those parts in the curve?
Here is the data</p>
<pre><code>df = structure(list(Temp = c(10, 13, 17, 20, 25, 28, 30, 32, 35, 38
), Growth.rate = c(0, 0.02, 0.19, 0.39, 0.79, 0.96, 1, 0.95,
0.65, 0), slope = c(0, 0.02, 0.16, 0.2, 0.39, 0.1, 0.03, -0.04,
-0.29, -0.65)), row.names = c(NA, 10L), class = "data.frame")
</code></pre>
|
[
{
"answer_id": 74560828,
"author": "George Savva",
"author_id": 12176280,
"author_profile": "https://Stackoverflow.com/users/12176280",
"pm_score": 3,
"selected": true,
"text": "approx ymin ymax Temp=30.1 cut bounds2 <- df %>% \n mutate(ymax = pmax(Growth.rate, slope),\n ymin = pmin(Growth.rate, slope))\nbounds2 <- bounds2 |> \n add_case(Temp=30.1, \n ymax=approx(bounds2$Temp,bounds2$ymax,xout = 30.1)$y,\n ymin=approx(bounds2$Temp,bounds2$ymin,xout = 30.1)$y) |>\n mutate(x_bins2 = cut(Temp, breaks = c(0,20,30.1,max(Temp)+5),right=FALSE, labels=c(\"0-20\",\"20-30.1\",\"30.1-max\")),\n x_bins = cut(Temp, breaks = c(0,20,30.1,max(Temp)+5), labels=c(\"0-20\",\"20-30.1\",\"30.1-max\"))) |> \n tidyr::pivot_longer(cols=c(x_bins2, x_bins), names_to = NULL, values_to = \"xb\") |> \n distinct()\n\nggplot(df, aes(x = Temp, y = Growth.rate)) +\n geom_line(colour = \"blue\") +\n geom_line(aes(y = slope), colour = \"red\") +\n scale_y_continuous(sec.axis = sec_axis(~ .^1, name = \"slope\")) +\n geom_ribbon(data = bounds2, aes(Temp, ymin = ymin, ymax = ymax, fill = xb), \n alpha = 0.4)\n"
},
{
"answer_id": 74560858,
"author": "Yacine Hajji",
"author_id": 17049772,
"author_profile": "https://Stackoverflow.com/users/17049772",
"pm_score": 2,
"selected": false,
"text": "### Dupplicate the 2 last x_bins from each category and move them into the next ### Libraries\nlibrary(tidyverse)\n\ndf <- structure(list(Temp = c(10, 13, 17, 20, 25, 28, 30, 32, 35, 38\n), Growth.rate = c(0, 0.02, 0.19, 0.39, 0.79, 0.96, 1, 0.95, \n 0.65, 0), slope = c(0, 0.02, 0.16, 0.2, 0.39, 0.1, 0.03, -0.04, \n -0.29, -0.65)), row.names = c(NA, 10L), class = \"data.frame\")\n\n### Preprocessing\nbounds2 <- df %>% \n mutate(ymax = pmax(Growth.rate, slope),\n ymin = pmin(Growth.rate, slope),\n x_bins = cut(Temp, breaks = c(0, 20, 30.1, max(Temp)+5)))\n\n### Dupplicate the 2 last x_bins from each category and move them into the next category\nbounds2 <- rbind(bounds2, bounds2[c(4, 7), ])\nbounds2$x_bins[c(11, 12)] <- bounds2[c(5, 8), ]$x_bins\n\n### Plot\nggplot(df, aes(x = Temp, y = Growth.rate)) +\n geom_line(colour = \"blue\") +\n geom_line(aes(y = slope), colour = \"red\") +\n scale_y_continuous(sec.axis = sec_axis(~ .^1, name = \"slope\")) +\n geom_ribbon(data = bounds2, aes(Temp, ymin = ymin, ymax = ymax, fill = x_bins), \n alpha = 0.4)\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74560448",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6123824/"
] |
74,560,468
|
<p>My code works fine last week, then when the credentials expire, i recreate another credentials and replace the credentials, now the code doesnt work anymore and show the error<br />
[ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: LateInitializationError: Field 'dialogflow' has not been initialized.</p>
<pre><code>import 'package:dialogflow_grpc/dialogflow_grpc.dart';
import 'package:dialogflow_grpc/generated/google/cloud/dialogflow/v2beta1/session.pb.dart';
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
class Chat extends StatefulWidget {
Chat({Key? key}) : super(key: key);
@override
_ChatState createState() => _ChatState();
}
class _ChatState extends State<Chat> {
final List<ChatMessage> _messages = <ChatMessage>[];
final TextEditingController _textController = TextEditingController();
late DialogflowGrpcV2Beta1 dialogflow;
@override
void initState() {
super.initState();
initPlugin();
}
Future<void> initPlugin()async{
final serviceAccount = ServiceAccount.fromString(
'${(await rootBundle.loadString('assets/credentials2.json'))}');
// Create a DialogflowGrpc Instance
dialogflow = DialogflowGrpcV2Beta1.viaServiceAccount(serviceAccount);
}
void handleSubmitted(text) async {
print(text);
_textController.clear();
ChatMessage message = ChatMessage(
text: text,
name: "You",
type: true,
);
setState(() {
_messages.insert(0, message);
});
DetectIntentResponse data = await dialogflow.detectIntent(text, 'en-US');
String fulfillmentText = data.queryResult.fulfillmentText;
if(fulfillmentText.isNotEmpty) {
ChatMessage botMessage = ChatMessage(
text: fulfillmentText,
name: "Bot",
type: false,
);
setState(() {
_messages.insert(0, botMessage);
});
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Chatbot Page'),
),
body: Column(children: <Widget>[
Flexible(
child: ListView.builder(
padding: EdgeInsets.all(8.0),
reverse: true,
itemBuilder: (_, int index) => _messages[index],
itemCount: _messages.length,
)),
Divider(height: 1.0),
Container(
decoration: BoxDecoration(color: Theme.of(context).cardColor),
child: IconTheme(
data: IconThemeData(color: Theme.of(context).accentColor),
child: Container(
margin: const EdgeInsets.symmetric(horizontal: 8.0),
child: Row(
children: <Widget>[
Flexible(
child: TextField(
controller: _textController,
onSubmitted: handleSubmitted,
decoration: InputDecoration.collapsed(hintText: "Send a message to begin"),
),
),
Container(
margin: EdgeInsets.symmetric(horizontal: 4.0),
child: IconButton(
icon: Icon(Icons.send),
onPressed: () => handleSubmitted(_textController.text),
),
),
],
),
),
)
),
]),
);
}
}
class ChatMessage extends StatelessWidget {
ChatMessage({required this.text, required this.name, required this.type});
final String text;
final String name;
final bool type;
List<Widget> otherMessage(context) {
return <Widget>[
new Container(
margin: const EdgeInsets.only(right: 16.0),
child: CircleAvatar(child: new Text('B')),
),
new Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(this.name,
style: TextStyle(fontWeight: FontWeight.bold)),
Container(
margin: const EdgeInsets.only(top: 5.0),
child: Text(text),
),
],
),
),
];
}
List<Widget> myMessage(context) {
return <Widget>[
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.end,
children: <Widget>[
Text(this.name, style: Theme.of(context).textTheme.subtitle1),
Container(
margin: const EdgeInsets.only(top: 5.0),
child: Text(text),
),
],
),
),
Container(
margin: const EdgeInsets.only(left: 16.0),
child: CircleAvatar(
child: Text(
this.name[0],
style: TextStyle(fontWeight: FontWeight.bold),
)),
),
];
}
@override
Widget build(BuildContext context) {
return Container(
margin: const EdgeInsets.symmetric(vertical: 10.0),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: this.type ? myMessage(context) : otherMessage(context),
),
);
}
}
</code></pre>
|
[
{
"answer_id": 74560828,
"author": "George Savva",
"author_id": 12176280,
"author_profile": "https://Stackoverflow.com/users/12176280",
"pm_score": 3,
"selected": true,
"text": "approx ymin ymax Temp=30.1 cut bounds2 <- df %>% \n mutate(ymax = pmax(Growth.rate, slope),\n ymin = pmin(Growth.rate, slope))\nbounds2 <- bounds2 |> \n add_case(Temp=30.1, \n ymax=approx(bounds2$Temp,bounds2$ymax,xout = 30.1)$y,\n ymin=approx(bounds2$Temp,bounds2$ymin,xout = 30.1)$y) |>\n mutate(x_bins2 = cut(Temp, breaks = c(0,20,30.1,max(Temp)+5),right=FALSE, labels=c(\"0-20\",\"20-30.1\",\"30.1-max\")),\n x_bins = cut(Temp, breaks = c(0,20,30.1,max(Temp)+5), labels=c(\"0-20\",\"20-30.1\",\"30.1-max\"))) |> \n tidyr::pivot_longer(cols=c(x_bins2, x_bins), names_to = NULL, values_to = \"xb\") |> \n distinct()\n\nggplot(df, aes(x = Temp, y = Growth.rate)) +\n geom_line(colour = \"blue\") +\n geom_line(aes(y = slope), colour = \"red\") +\n scale_y_continuous(sec.axis = sec_axis(~ .^1, name = \"slope\")) +\n geom_ribbon(data = bounds2, aes(Temp, ymin = ymin, ymax = ymax, fill = xb), \n alpha = 0.4)\n"
},
{
"answer_id": 74560858,
"author": "Yacine Hajji",
"author_id": 17049772,
"author_profile": "https://Stackoverflow.com/users/17049772",
"pm_score": 2,
"selected": false,
"text": "### Dupplicate the 2 last x_bins from each category and move them into the next ### Libraries\nlibrary(tidyverse)\n\ndf <- structure(list(Temp = c(10, 13, 17, 20, 25, 28, 30, 32, 35, 38\n), Growth.rate = c(0, 0.02, 0.19, 0.39, 0.79, 0.96, 1, 0.95, \n 0.65, 0), slope = c(0, 0.02, 0.16, 0.2, 0.39, 0.1, 0.03, -0.04, \n -0.29, -0.65)), row.names = c(NA, 10L), class = \"data.frame\")\n\n### Preprocessing\nbounds2 <- df %>% \n mutate(ymax = pmax(Growth.rate, slope),\n ymin = pmin(Growth.rate, slope),\n x_bins = cut(Temp, breaks = c(0, 20, 30.1, max(Temp)+5)))\n\n### Dupplicate the 2 last x_bins from each category and move them into the next category\nbounds2 <- rbind(bounds2, bounds2[c(4, 7), ])\nbounds2$x_bins[c(11, 12)] <- bounds2[c(5, 8), ]$x_bins\n\n### Plot\nggplot(df, aes(x = Temp, y = Growth.rate)) +\n geom_line(colour = \"blue\") +\n geom_line(aes(y = slope), colour = \"red\") +\n scale_y_continuous(sec.axis = sec_axis(~ .^1, name = \"slope\")) +\n geom_ribbon(data = bounds2, aes(Temp, ymin = ymin, ymax = ymax, fill = x_bins), \n alpha = 0.4)\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74560468",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20413390/"
] |
74,560,472
|
<p>I've created an API with rest_framework and can receive API calls that updates the database, but I can't figure how to query the database and return any row where the field "Endtime" is NULL.</p>
<p>In the function below I'm updating the database with the received JSON-data and this fails to return any result where the value is NULL for Endtime. Below is the error I get. How should I write the view to return rows where endtime column is NULL?</p>
<p>ValidationError at /durationupdate/
['“NULL” value has an invalid format. It must be in YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ] format.']
Request Method: POST
Request URL: http://127.0.0.1:8000/durationupdate/
Django Version: 4.1.1
Exception Type: ValidationError
Exception Value:<br />
['“NULL” value has an invalid format. It must be in YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ] format.']</p>
<p>views.py
`</p>
<pre><code>@api_view(['POST', 'GET'])
def durationUpdate(request):
if request.method == 'POST':
serializer = RigstateSerializer(data=request.data)
wherenull = Rigstate.objects.get(endtime='NULL')
wherenullserializer = DurationSerializer(wherenull, many=True)
if serializer.is_valid():
serializer.save()
return Response(wherenullserializer.data)
</code></pre>
<p>`</p>
<p>models.py
`</p>
<pre><code>class Rigstate(models.Model):
rigname = models.CharField(max_length=255)
rigmode = models.IntegerField(default=0)
starttime = models.DateTimeField()
endtime = models.DateTimeField(blank=True, null=True)
duration = models.IntegerField(default=0)
def __str__(self):
return self.rigname
</code></pre>
<p>`</p>
<p>I've tried changing from 'NULL' to NULL but then I get a different error</p>
|
[
{
"answer_id": 74560828,
"author": "George Savva",
"author_id": 12176280,
"author_profile": "https://Stackoverflow.com/users/12176280",
"pm_score": 3,
"selected": true,
"text": "approx ymin ymax Temp=30.1 cut bounds2 <- df %>% \n mutate(ymax = pmax(Growth.rate, slope),\n ymin = pmin(Growth.rate, slope))\nbounds2 <- bounds2 |> \n add_case(Temp=30.1, \n ymax=approx(bounds2$Temp,bounds2$ymax,xout = 30.1)$y,\n ymin=approx(bounds2$Temp,bounds2$ymin,xout = 30.1)$y) |>\n mutate(x_bins2 = cut(Temp, breaks = c(0,20,30.1,max(Temp)+5),right=FALSE, labels=c(\"0-20\",\"20-30.1\",\"30.1-max\")),\n x_bins = cut(Temp, breaks = c(0,20,30.1,max(Temp)+5), labels=c(\"0-20\",\"20-30.1\",\"30.1-max\"))) |> \n tidyr::pivot_longer(cols=c(x_bins2, x_bins), names_to = NULL, values_to = \"xb\") |> \n distinct()\n\nggplot(df, aes(x = Temp, y = Growth.rate)) +\n geom_line(colour = \"blue\") +\n geom_line(aes(y = slope), colour = \"red\") +\n scale_y_continuous(sec.axis = sec_axis(~ .^1, name = \"slope\")) +\n geom_ribbon(data = bounds2, aes(Temp, ymin = ymin, ymax = ymax, fill = xb), \n alpha = 0.4)\n"
},
{
"answer_id": 74560858,
"author": "Yacine Hajji",
"author_id": 17049772,
"author_profile": "https://Stackoverflow.com/users/17049772",
"pm_score": 2,
"selected": false,
"text": "### Dupplicate the 2 last x_bins from each category and move them into the next ### Libraries\nlibrary(tidyverse)\n\ndf <- structure(list(Temp = c(10, 13, 17, 20, 25, 28, 30, 32, 35, 38\n), Growth.rate = c(0, 0.02, 0.19, 0.39, 0.79, 0.96, 1, 0.95, \n 0.65, 0), slope = c(0, 0.02, 0.16, 0.2, 0.39, 0.1, 0.03, -0.04, \n -0.29, -0.65)), row.names = c(NA, 10L), class = \"data.frame\")\n\n### Preprocessing\nbounds2 <- df %>% \n mutate(ymax = pmax(Growth.rate, slope),\n ymin = pmin(Growth.rate, slope),\n x_bins = cut(Temp, breaks = c(0, 20, 30.1, max(Temp)+5)))\n\n### Dupplicate the 2 last x_bins from each category and move them into the next category\nbounds2 <- rbind(bounds2, bounds2[c(4, 7), ])\nbounds2$x_bins[c(11, 12)] <- bounds2[c(5, 8), ]$x_bins\n\n### Plot\nggplot(df, aes(x = Temp, y = Growth.rate)) +\n geom_line(colour = \"blue\") +\n geom_line(aes(y = slope), colour = \"red\") +\n scale_y_continuous(sec.axis = sec_axis(~ .^1, name = \"slope\")) +\n geom_ribbon(data = bounds2, aes(Temp, ymin = ymin, ymax = ymax, fill = x_bins), \n alpha = 0.4)\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74560472",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19955692/"
] |
74,560,475
|
<p>I am using this code to create folders based on names mentioned in Column A, however at times this does not create folders and at times it does not create all the folders. I could not figure out the issue or if anything is missing in it.</p>
<p>I will really appreciate if any amendment could be made where if a particular folder is already available (based on cell value) it does not show error.</p>
<pre><code>Sub MakeFolders()
Dim Rng As Range
Dim maxRows, maxCols, r, c As Integer
Set Rng = Selection
maxRows = Rng.Rows.Count
maxCols = Rng.Columns.Count
For c = 1 To maxCols
r = 1
Do While r <= maxRows
If Len(Dir(ActiveWorkbook.Path & "\" & Rng(r, c), vbDirectory)) = 0 Then
MkDir (ActiveWorkbook.Path & "\" & Rng(r, c))
On Error Resume Next
End If
r = r + 1
Loop
Next c
End Sub
</code></pre>
|
[
{
"answer_id": 74560828,
"author": "George Savva",
"author_id": 12176280,
"author_profile": "https://Stackoverflow.com/users/12176280",
"pm_score": 3,
"selected": true,
"text": "approx ymin ymax Temp=30.1 cut bounds2 <- df %>% \n mutate(ymax = pmax(Growth.rate, slope),\n ymin = pmin(Growth.rate, slope))\nbounds2 <- bounds2 |> \n add_case(Temp=30.1, \n ymax=approx(bounds2$Temp,bounds2$ymax,xout = 30.1)$y,\n ymin=approx(bounds2$Temp,bounds2$ymin,xout = 30.1)$y) |>\n mutate(x_bins2 = cut(Temp, breaks = c(0,20,30.1,max(Temp)+5),right=FALSE, labels=c(\"0-20\",\"20-30.1\",\"30.1-max\")),\n x_bins = cut(Temp, breaks = c(0,20,30.1,max(Temp)+5), labels=c(\"0-20\",\"20-30.1\",\"30.1-max\"))) |> \n tidyr::pivot_longer(cols=c(x_bins2, x_bins), names_to = NULL, values_to = \"xb\") |> \n distinct()\n\nggplot(df, aes(x = Temp, y = Growth.rate)) +\n geom_line(colour = \"blue\") +\n geom_line(aes(y = slope), colour = \"red\") +\n scale_y_continuous(sec.axis = sec_axis(~ .^1, name = \"slope\")) +\n geom_ribbon(data = bounds2, aes(Temp, ymin = ymin, ymax = ymax, fill = xb), \n alpha = 0.4)\n"
},
{
"answer_id": 74560858,
"author": "Yacine Hajji",
"author_id": 17049772,
"author_profile": "https://Stackoverflow.com/users/17049772",
"pm_score": 2,
"selected": false,
"text": "### Dupplicate the 2 last x_bins from each category and move them into the next ### Libraries\nlibrary(tidyverse)\n\ndf <- structure(list(Temp = c(10, 13, 17, 20, 25, 28, 30, 32, 35, 38\n), Growth.rate = c(0, 0.02, 0.19, 0.39, 0.79, 0.96, 1, 0.95, \n 0.65, 0), slope = c(0, 0.02, 0.16, 0.2, 0.39, 0.1, 0.03, -0.04, \n -0.29, -0.65)), row.names = c(NA, 10L), class = \"data.frame\")\n\n### Preprocessing\nbounds2 <- df %>% \n mutate(ymax = pmax(Growth.rate, slope),\n ymin = pmin(Growth.rate, slope),\n x_bins = cut(Temp, breaks = c(0, 20, 30.1, max(Temp)+5)))\n\n### Dupplicate the 2 last x_bins from each category and move them into the next category\nbounds2 <- rbind(bounds2, bounds2[c(4, 7), ])\nbounds2$x_bins[c(11, 12)] <- bounds2[c(5, 8), ]$x_bins\n\n### Plot\nggplot(df, aes(x = Temp, y = Growth.rate)) +\n geom_line(colour = \"blue\") +\n geom_line(aes(y = slope), colour = \"red\") +\n scale_y_continuous(sec.axis = sec_axis(~ .^1, name = \"slope\")) +\n geom_ribbon(data = bounds2, aes(Temp, ymin = ymin, ymax = ymax, fill = x_bins), \n alpha = 0.4)\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74560475",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20141828/"
] |
74,560,491
|
<p>I've been having some troubles with combining typeclasses with higher-rank types in haskell.</p>
<p>The project I'm working on is an interpreter based around an evaluation monad. I'm currently attempting to transition my central evaluation monad from a stack of transformers to a set of mtl constraints. Many of the functions I'm using have type signatures like:</p>
<pre class="lang-hs prettyprint-override"><code>(MonadReader Environment m, MonadError String m, MonadState ProgState m) => <something involving m>
</code></pre>
<p>In addition, I'm placing higher-rank polymorphic functions inside of some datastructures, e.g.</p>
<pre class="lang-hs prettyprint-override"><code>data Foo =
...
| forall m. MonadReader Environment m, ..., ... => <something involving m>
</code></pre>
<p>I've been using several language extensions, but I think the relevant ones are <code>{-# LANGUAGE RankNTypes, FlexibleContexts #-}</code>.</p>
<p>As part of this transition, I'm running into two type errors throughout the codebase, but there's one snippet which demonstrates both (below).</p>
<p>At the surface level, it'd be nice if I can fix these issues, but I feel that all these type errors are related to my lack of understanding of how higher-rank types in Haskell work, so if there are any papers or articles that you feel may help they'd be much appreciated.</p>
<h3>The Problem</h3>
<p>The below snippet demonstrates both type-errors I'm getting:</p>
<pre class="lang-hs prettyprint-override"><code>normSubst :: (MonadReader Environment m, MonadError String m, MonadState ProgState m) => (Normal, String) -> Normal -> m Normal
normSubst (val, var) ty = case ty of
-- ...
NormCoVal pats ty -> do
let pats' = map substCoPat pats
ty' <- normSubst (val, var) ty
pure (NormCoVal pats' ty')
</code></pre>
<p>Relevant type signatures include:</p>
<pre class="lang-hs prettyprint-override"><code>data Normal =
...
| NormCoVal (forall m. (MonadReader Environment m, MonadError String m, MonadState ProgState m) => [(CoPattern, m Normal)]) Normal
substCoPat :: (MonadReader Environment m, MonadError String m, MonadState ProgState m) => (CoPattern, m Normal) -> (CoPattern, m Normal)
</code></pre>
<h3>Error 1</h3>
<p>This error seems to be related to the line <code>let pats' = map substCoPat pats</code>, and has occurred a couple times. Several of these seem related to uses of combinators from the <code>Lens</code> library.</p>
<pre><code>error:
• Could not deduce (MonadReader Environment m0)
arising from a use of ‘substCoPat’
from the context: (MonadReader Environment m, MonadError String m,
MonadState ProgState m)
bound by the type signature for:
normSubst :: forall (m :: * -> *).
(MonadReader Environment m, MonadError String m,
MonadState ProgState m) =>
(Normal, String) -> Normal -> m Normal
at src/Interpret/Eval.hs:386:1-128
The type variable ‘m0’ is ambiguous
Relevant bindings include
pats' :: [(CoPattern, m0 Normal)]
</code></pre>
<h3>Error 2</h3>
<p>This error is related to the line <code>pure (NormCoVal pats' ty')</code>, specifically the <code>pats</code> variable.
I've found something relating to this second error
<a href="https://mail.haskell.org/pipermail/haskell-cafe/2012-August/103041.html" rel="nofollow noreferrer">here</a>, but can't quite make sense of what the article is saying.</p>
<pre><code>error:
• Couldn't match type ‘m0’ with ‘m1’
Expected: [(CoPattern, m1 Normal)]
Actual: [(CoPattern, m0 Normal)]
because type variable ‘m1’ would escape its scope
This (rigid, skolem) type variable is bound by
a type expected by the context:
forall (m1 :: * -> *).
(MonadReader Environment m1, MonadError String m1,
MonadState ProgState m1) =>
[(CoPattern, m1 Normal)]
</code></pre>
|
[
{
"answer_id": 74560733,
"author": "Noughtmare",
"author_id": 15207568,
"author_profile": "https://Stackoverflow.com/users/15207568",
"pm_score": 2,
"selected": false,
"text": "normSubst :: \n ( MonadReader Environment m\n , MonadError String m\n , MonadState ProgState m\n ) => (Normal m, String) -> Normal m -> m (Normal m)\nnormSubst (val, var) ty = case ty of \n -- ...\n NormCoVal pats ty -> do\n let pats' = map substCoPat pats\n ty' <- normSubst (val, var) ty\n pure (NormCoVal pats' ty')\n data Normal m = \n ...\n | NormCoVal [(CoPattern, m (Normal m))] (Normal m)\n\n\nsubstCoPat :: \n ( MonadReader Environment m\n , MonadError String m\n , MonadState ProgState m\n ) => (CoPattern, m (Normal m)) -> (CoPattern, m (Normal m))\n"
},
{
"answer_id": 74565580,
"author": "K. A. Buhr",
"author_id": 7203016,
"author_profile": "https://Stackoverflow.com/users/7203016",
"pm_score": 0,
"selected": false,
"text": "pats' m0 substCoPat m0 pats' m0 forall m1. (...constraints...) => ... m1 {-# LANGUAGE NoMonomorphismRestricition #-} pats' NormCoVal pats ty -> do\n let pats' :: (MonadReader Environment m, MonadError String m, MonadState ProgState m) => [(CoPattern, m Normal)]\n pats' = map substCoPat pats\n ty' <- normSubst (val, var) ty\n pure (NormCoVal pats' ty')\n let NormCoVal pats ty -> do\n ty' <- normSubst (val, var) ty\n pure (NormCoVal (map substCoPat pats) ty')\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74560491",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6540935/"
] |
74,560,521
|
<p>So I was tasked to produced a series of numbers based on what I input on START, STEP, and END.
For example: If I input 5 on the START, 2 on the STEP, and 13 on the end, then the output would be:</p>
<p>5, 7, 9, 11, 13</p>
<pre><code>import java.util.Scanner;
public class SeriesOfNumbers {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int [] numbers = {1 ,2 ,3 ,4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20};
int start = 0;
int step = 0;
int end = 0;
boolean foundNum = false;
System.out.print("START: ");
start = scan.nextInt();
for(start = 0; start <= numbers.length; start++) {
if(start == numbers.length) {
foundNum = true;
break;
}
}
System.out.print("STEP: ");
step = scan.nextInt();
for(step = 0; step <= numbers.length; step++) {
if(start == numbers.length) {
foundNum = true;
break;
}
}
System.out.print("END:");
end = scan.nextInt();
for(end = 0; end <= numbers.length; end++) {
if(end == numbers.length) {
foundNum = true;
break;
}
}
if(foundNum) {
System.out.print("The output will be: ");
}
}
}
</code></pre>
<p>Expected output:</p>
<pre><code>START: 5
STEP: 3
END: 20
The output will be: 5 8 11 14 17 20
</code></pre>
<p>Since I'm new to JAVA and it's my first programming language, I have no idea what I am doing. A little assistance might help. Thank you!</p>
|
[
{
"answer_id": 74560733,
"author": "Noughtmare",
"author_id": 15207568,
"author_profile": "https://Stackoverflow.com/users/15207568",
"pm_score": 2,
"selected": false,
"text": "normSubst :: \n ( MonadReader Environment m\n , MonadError String m\n , MonadState ProgState m\n ) => (Normal m, String) -> Normal m -> m (Normal m)\nnormSubst (val, var) ty = case ty of \n -- ...\n NormCoVal pats ty -> do\n let pats' = map substCoPat pats\n ty' <- normSubst (val, var) ty\n pure (NormCoVal pats' ty')\n data Normal m = \n ...\n | NormCoVal [(CoPattern, m (Normal m))] (Normal m)\n\n\nsubstCoPat :: \n ( MonadReader Environment m\n , MonadError String m\n , MonadState ProgState m\n ) => (CoPattern, m (Normal m)) -> (CoPattern, m (Normal m))\n"
},
{
"answer_id": 74565580,
"author": "K. A. Buhr",
"author_id": 7203016,
"author_profile": "https://Stackoverflow.com/users/7203016",
"pm_score": 0,
"selected": false,
"text": "pats' m0 substCoPat m0 pats' m0 forall m1. (...constraints...) => ... m1 {-# LANGUAGE NoMonomorphismRestricition #-} pats' NormCoVal pats ty -> do\n let pats' :: (MonadReader Environment m, MonadError String m, MonadState ProgState m) => [(CoPattern, m Normal)]\n pats' = map substCoPat pats\n ty' <- normSubst (val, var) ty\n pure (NormCoVal pats' ty')\n let NormCoVal pats ty -> do\n ty' <- normSubst (val, var) ty\n pure (NormCoVal (map substCoPat pats) ty')\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74560521",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19907769/"
] |
74,560,522
|
<p>I'm building a distributed application using ZMQ framework that needs to assure the integrity of the packages exchanged. My question is whether or not do I need to perform integrity checks on the client and server on the application layer.</p>
<p>I have implemented a checksum approach using MD5 hash in both client's and server's side. However, I suspect that this might be redundant since zmq might be already handling integrity checks in the background. I have read <a href="https://zguide.zeromq.org/" rel="nofollow noreferrer">ZMQ - The guide</a> and found scarce information on this matter rather than small references that indicate that zmq already does integrity checks:</p>
<blockquote>
<p>It delivers whole messages exactly as they were sent, using a simple
framing on the wire. If you write a 10k message, you will receive a
10k message.</p>
</blockquote>
<p>I also searched in forums, including SO and couldn't found any solid reference that could confirm the reference. I would appreciate if someone could confirm it and ideally include a useful source.</p>
<br>
<p><strong>EDIT</strong></p>
<hr />
<p>I am looking for answers other than "trust the docs" or "implement checksums" for two reasons:</p>
<ul>
<li><p>I think that there need to be clear and easy-to-find references to what seems to be one of the key selling points of ZMQ.</p>
</li>
<li><p>The system under design must be fast, thus not wasting time in redundant ops.</p>
</li>
</ul>
|
[
{
"answer_id": 74560733,
"author": "Noughtmare",
"author_id": 15207568,
"author_profile": "https://Stackoverflow.com/users/15207568",
"pm_score": 2,
"selected": false,
"text": "normSubst :: \n ( MonadReader Environment m\n , MonadError String m\n , MonadState ProgState m\n ) => (Normal m, String) -> Normal m -> m (Normal m)\nnormSubst (val, var) ty = case ty of \n -- ...\n NormCoVal pats ty -> do\n let pats' = map substCoPat pats\n ty' <- normSubst (val, var) ty\n pure (NormCoVal pats' ty')\n data Normal m = \n ...\n | NormCoVal [(CoPattern, m (Normal m))] (Normal m)\n\n\nsubstCoPat :: \n ( MonadReader Environment m\n , MonadError String m\n , MonadState ProgState m\n ) => (CoPattern, m (Normal m)) -> (CoPattern, m (Normal m))\n"
},
{
"answer_id": 74565580,
"author": "K. A. Buhr",
"author_id": 7203016,
"author_profile": "https://Stackoverflow.com/users/7203016",
"pm_score": 0,
"selected": false,
"text": "pats' m0 substCoPat m0 pats' m0 forall m1. (...constraints...) => ... m1 {-# LANGUAGE NoMonomorphismRestricition #-} pats' NormCoVal pats ty -> do\n let pats' :: (MonadReader Environment m, MonadError String m, MonadState ProgState m) => [(CoPattern, m Normal)]\n pats' = map substCoPat pats\n ty' <- normSubst (val, var) ty\n pure (NormCoVal pats' ty')\n let NormCoVal pats ty -> do\n ty' <- normSubst (val, var) ty\n pure (NormCoVal (map substCoPat pats) ty')\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74560522",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11494333/"
] |
74,560,534
|
<p>How to select rows from table that matches where clause on two columns? I came up with below query. Please advice if there is better way with less text.</p>
<pre><code>SELECT name, number
FROM namenumber
WHERE name IN (“Car”) AND number = “1234"
UNION
SELECT name, number
FROM namenumber
WHERE name IN ("Train") AND number = "5678"
UNION
SELECT name, number
FROM namenumber
WHERE name IN ("Flight") AND number = "9012";
</code></pre>
|
[
{
"answer_id": 74560573,
"author": "Nikita Chayka",
"author_id": 7064030,
"author_profile": "https://Stackoverflow.com/users/7064030",
"pm_score": 0,
"selected": false,
"text": " SELECT name, number FROM namenumber \n WHERE (name in (“Car”) and number = “1234\") OR \n (name in (\"Train\") and number = \"5678\") OR \n (name in (\"Flight\") and number = \"9012\")\n"
},
{
"answer_id": 74560867,
"author": "p3consulting",
"author_id": 4956336,
"author_profile": "https://Stackoverflow.com/users/4956336",
"pm_score": 3,
"selected": true,
"text": "SELECT name, number FROM namenumber \nWHERE (name, number) IN ( \n (“Car”,“1234\"), (\"Train\", \"5678\"), (\"Flight\", \"9012\") \n) ;\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74560534",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6623338/"
] |
74,560,547
|
<p>I have a column in a DF as below</p>
<pre><code>| Column A |
| ab, bce, bc |
| bc, abcd, ab |
| ab, cd, abc |
</code></pre>
<p>and i want to create a new column that only takes the first sequence, as showed below</p>
<pre><code>| Column A | Column B |
| ab, bce, bc | ab |
| bc, abcd, ab | bc |
| ab, cd, abc | ab |
</code></pre>
<p>I tried with this code but it only gives me the first letter of the first sequence, not the entire abbrevation</p>
<pre><code>df.loc[:, 'ColumnB'] = df.ColumnA.map(lambda x: x[0])
</code></pre>
|
[
{
"answer_id": 74560629,
"author": "Orfeas Bourchas",
"author_id": 16781682,
"author_profile": "https://Stackoverflow.com/users/16781682",
"pm_score": 2,
"selected": false,
"text": "df.loc[:, 'ColumnB'] = df.ColumnA.map(lambda x: x.split(',')[0])\n"
},
{
"answer_id": 74560663,
"author": "Bhargav",
"author_id": 15358800,
"author_profile": "https://Stackoverflow.com/users/15358800",
"pm_score": 1,
"selected": false,
"text": "df['Column B'] = df['Column A'].str.split(',').str[0]\n Column A Column B \nab, bce, bc ab \nbc, abcd, ab bc \nab, cd, abc ab \n"
},
{
"answer_id": 74560677,
"author": "abokey",
"author_id": 16120011,
"author_profile": "https://Stackoverflow.com/users/16120011",
"pm_score": 1,
"selected": false,
"text": "pandas.Series.split df[\"Column B\"]= df[\"Column A\"].str.split(\",\").map(lambda x: x[0])\n pandas.Series.get df[\"Column B\"]= df[\"Column A\"].str.split(\",\").str.get(0)\n df[\"Column B\"]= [el[0] for el in df[\"Column A\"].str.split(\",\")]\n print(df)\n\n Column A Column B\n0 ab, bce, bc ab\n1 bc, abcd, ab bc\n2 ab, cd, abc ab\n"
},
{
"answer_id": 74560822,
"author": "Prachi Patel",
"author_id": 15425970,
"author_profile": "https://Stackoverflow.com/users/15425970",
"pm_score": 1,
"selected": false,
"text": "df.loc[:, 'ColumnB'] = df.ColumnA.map(lambda x: x.split(\",\")[0])\n"
},
{
"answer_id": 74561527,
"author": "mozway",
"author_id": 16343464,
"author_profile": "https://Stackoverflow.com/users/16343464",
"pm_score": 0,
"selected": false,
"text": "split extract , df['Column B'] = df['Column A'].str.extract('([^,]+)')\n Column A Column B\n0 ab, bce, bc ab\n1 bc, abcd, ab bc\n2 ab, cd, abc ab\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74560547",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20590519/"
] |
74,560,557
|
<p>I use Expo 46.</p>
<p>I would like to change some config in my <code>AndroidManifest</code> so I run an <code>npx expo prebuild</code> that generates an android folder without error.</p>
<p>But then my <code>eas build</code> is not working anymore (it is if I don't run <code>prebuild</code>).<br />
I get this error:</p>
<pre><code>Failed to find 'build.gradle' file for project: /home/expo/workingdir/build/android/app.
</code></pre>
<p>Am I missing something?</p>
|
[
{
"answer_id": 74560629,
"author": "Orfeas Bourchas",
"author_id": 16781682,
"author_profile": "https://Stackoverflow.com/users/16781682",
"pm_score": 2,
"selected": false,
"text": "df.loc[:, 'ColumnB'] = df.ColumnA.map(lambda x: x.split(',')[0])\n"
},
{
"answer_id": 74560663,
"author": "Bhargav",
"author_id": 15358800,
"author_profile": "https://Stackoverflow.com/users/15358800",
"pm_score": 1,
"selected": false,
"text": "df['Column B'] = df['Column A'].str.split(',').str[0]\n Column A Column B \nab, bce, bc ab \nbc, abcd, ab bc \nab, cd, abc ab \n"
},
{
"answer_id": 74560677,
"author": "abokey",
"author_id": 16120011,
"author_profile": "https://Stackoverflow.com/users/16120011",
"pm_score": 1,
"selected": false,
"text": "pandas.Series.split df[\"Column B\"]= df[\"Column A\"].str.split(\",\").map(lambda x: x[0])\n pandas.Series.get df[\"Column B\"]= df[\"Column A\"].str.split(\",\").str.get(0)\n df[\"Column B\"]= [el[0] for el in df[\"Column A\"].str.split(\",\")]\n print(df)\n\n Column A Column B\n0 ab, bce, bc ab\n1 bc, abcd, ab bc\n2 ab, cd, abc ab\n"
},
{
"answer_id": 74560822,
"author": "Prachi Patel",
"author_id": 15425970,
"author_profile": "https://Stackoverflow.com/users/15425970",
"pm_score": 1,
"selected": false,
"text": "df.loc[:, 'ColumnB'] = df.ColumnA.map(lambda x: x.split(\",\")[0])\n"
},
{
"answer_id": 74561527,
"author": "mozway",
"author_id": 16343464,
"author_profile": "https://Stackoverflow.com/users/16343464",
"pm_score": 0,
"selected": false,
"text": "split extract , df['Column B'] = df['Column A'].str.extract('([^,]+)')\n Column A Column B\n0 ab, bce, bc ab\n1 bc, abcd, ab bc\n2 ab, cd, abc ab\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74560557",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3581976/"
] |
74,560,561
|
<p>I have one query, something like this:</p>
<pre><code> select col1,col2 from (
with RESULTSET as (
select * from t1 where rank_val=1
)
select T1.col1, T1.col2
FROM RESULTSET T1, t88a, t88b
where T1.col1=T88a.col1 and T88a.col2 = T1.col2
AND T1.col2=T88b.col2 and T88b.col1 <> T1.col1
) where NOT (c1 IS NULL AND c2 IS NULL) ORDER BY col1, col2;
</code></pre>
<p>I have a requirement where I need to use one outer <code>With As</code>, something like below:</p>
<pre><code>WITH NEW AS(select col1,col2 from (
with RESULTSET as (
select * from t1 where rank_val=1
)
select T1.col1, T1.col2
FROM RESULTSET T1, t88a, t88b
where T1.col1=T88a.col1 and T88a.col2 = T1.col2
AND T1.col2=T88b.col2 and T88b.col1 <> T1.col1
) where NOT (c1 IS NULL AND c2 IS NULL) ORDER BY col1, col2)
SELECT * FROM NEW;
</code></pre>
<p>Its giving me the exception:</p>
<pre><code> ORA-32034: unsupported use of WITH clause
32034. 00000 - "unsupported use of WITH clause"
</code></pre>
<p>How can I re write the query by removing the inner <code>With As</code>.</p>
|
[
{
"answer_id": 74560629,
"author": "Orfeas Bourchas",
"author_id": 16781682,
"author_profile": "https://Stackoverflow.com/users/16781682",
"pm_score": 2,
"selected": false,
"text": "df.loc[:, 'ColumnB'] = df.ColumnA.map(lambda x: x.split(',')[0])\n"
},
{
"answer_id": 74560663,
"author": "Bhargav",
"author_id": 15358800,
"author_profile": "https://Stackoverflow.com/users/15358800",
"pm_score": 1,
"selected": false,
"text": "df['Column B'] = df['Column A'].str.split(',').str[0]\n Column A Column B \nab, bce, bc ab \nbc, abcd, ab bc \nab, cd, abc ab \n"
},
{
"answer_id": 74560677,
"author": "abokey",
"author_id": 16120011,
"author_profile": "https://Stackoverflow.com/users/16120011",
"pm_score": 1,
"selected": false,
"text": "pandas.Series.split df[\"Column B\"]= df[\"Column A\"].str.split(\",\").map(lambda x: x[0])\n pandas.Series.get df[\"Column B\"]= df[\"Column A\"].str.split(\",\").str.get(0)\n df[\"Column B\"]= [el[0] for el in df[\"Column A\"].str.split(\",\")]\n print(df)\n\n Column A Column B\n0 ab, bce, bc ab\n1 bc, abcd, ab bc\n2 ab, cd, abc ab\n"
},
{
"answer_id": 74560822,
"author": "Prachi Patel",
"author_id": 15425970,
"author_profile": "https://Stackoverflow.com/users/15425970",
"pm_score": 1,
"selected": false,
"text": "df.loc[:, 'ColumnB'] = df.ColumnA.map(lambda x: x.split(\",\")[0])\n"
},
{
"answer_id": 74561527,
"author": "mozway",
"author_id": 16343464,
"author_profile": "https://Stackoverflow.com/users/16343464",
"pm_score": 0,
"selected": false,
"text": "split extract , df['Column B'] = df['Column A'].str.extract('([^,]+)')\n Column A Column B\n0 ab, bce, bc ab\n1 bc, abcd, ab bc\n2 ab, cd, abc ab\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74560561",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1784675/"
] |
74,560,565
|
<p>I`ve got code that shows all of the placements for a user. Is there a way to narrow this down to only show placements that are in the future? I've tried to do this using where and carbon::now to no avail.</p>
<p>My current code to show all of the placements :</p>
<pre><code>$placements = Auth::user()->placementsAuthored;
$placements->load('keystage', 'subject', 'dates');
</code></pre>
<p>Placements Authored connection to connect a user to a placement :</p>
<pre><code>public function placementsAuthored()
{
return $this->hasMany(Placement::class, 'author_id');
}
</code></pre>
<p>My attempt at trying to do this. I get no errors but the code doesn't work. It doesn't seem to take any effect of my where clause any ideas?</p>
<pre><code>$placements ->where('date','>',Carbon::now()->format('Y-m-d'));
</code></pre>
|
[
{
"answer_id": 74560728,
"author": "Lokendra Singh Panwar",
"author_id": 5602878,
"author_profile": "https://Stackoverflow.com/users/5602878",
"pm_score": -1,
"selected": false,
"text": "name date column date PHP function"
},
{
"answer_id": 74561175,
"author": "Jac Phillipps",
"author_id": 17732797,
"author_profile": "https://Stackoverflow.com/users/17732797",
"pm_score": 0,
"selected": false,
"text": "// Only load future placements\n$placements = Placement::whereHas( 'dates',\n function ($q) {\n $user_id = Auth::user()->id;\n $q->where('author_id', $user_id)->where('date','>=' ,Carbon::now()->format('Y-m-d'));})->get();\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74560565",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17732797/"
] |
74,560,578
|
<p>I have two list of the same type of object (X)</p>
<p>X has this properties:</p>
<ul>
<li>Id: int</li>
<li>Name: string</li>
<li>Month: string</li>
<li>ISSPA: string</li>
</ul>
<p>I want to get the items which has the same value in the properties Month and ISSPA.
For example:</p>
<p>List 1</p>
<pre><code>Item 1
{
Id = 1,
Name = "John",
Month = "October"
ISSPA = "1234"
}
Item 2
{
Id = 2,
Name = "Ryan",
Month = "September"
ISSPA = "1234"
}
</code></pre>
<p>List 2</p>
<pre><code>Item 1
{
Id = 1,
Name = "Chris",
Month = "September"
ISSPA = "1234"
}
</code></pre>
<p>In this case I need to get Item 2 (List1) and Item 1 (List2).
I tried a lot of things to get something decent but all failed.</p>
|
[
{
"answer_id": 74562145,
"author": "Marvin Klein",
"author_id": 13440841,
"author_profile": "https://Stackoverflow.com/users/13440841",
"pm_score": 0,
"selected": false,
"text": "var filteredList = yourList.Where(x => x.Month == \"September\" && x.ISSPA == \"1234\").ToList();\n"
},
{
"answer_id": 74562304,
"author": "Magnus",
"author_id": 468973,
"author_profile": "https://Stackoverflow.com/users/468973",
"pm_score": 2,
"selected": true,
"text": "var result = list1\n .Concat(list2)\n .GroupBy(x => (x.Month, x.ISSPA))\n .Where(g => g.Count() > 1)\n .SelectMany(g => g);\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74560578",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11223567/"
] |
74,560,585
|
<p>Looking for a linq query solve this problem.
Here are two lists : PartOrders and ServiceOrders
there is orderNumber for example 1001X and createdDate on same day for each partOrders and might be many items having same orderNumber so i would sort this list to get only one orderNumber , createdDate and then a list of type .
There is also a another list of type ServiceOrders needs also to be sorted the same way as PartOrders list.
Finally check if the orderNumber match in booth lists(PartOrders and ServiceOrders) and join them in one orderNumber to get new list of Type .</p>
<pre><code>public class PartOrders
{
public string orderNumber{ get; set; }
public DateTime createdDate { get; set; }
public string orderDescription { get; set; }
public string OderNote { get; set; }
}
public class ServiceOrders
{
public string orderNumber{ get; set; }
public DateTime createdDate { get; set; }
public string ServiceDescription { get; set; }
public string ServiceNote { get; set; }
}
</code></pre>
<p>So the new list would be with type</p>
<pre><code>public class Result
{
public string orderNumber{ get; set; }
public DateTime createdDate { get; set; }
public List<TheRestOfOrdersData> theRestOfOrdersData { get; set; }
public List<TheRestOfServiceData> theRestOfServiceData{ get; set; }
}
</code></pre>
<p>I hope this example helps to understand my question.</p>
<pre><code>// PartOrder
List<PartOrders> partOrder = new List<PartOrders>
{
new PartOrders() { orderNumber = "1001", createdDate = DateTime.Today, orderDescription = "Order spare part", OderNote = "urgent" },
new PartOrders() { orderNumber = "1002", createdDate = DateTime.Today, orderDescription = "Not Available", OderNote = "Low" },
new PartOrders() { orderNumber = "1002", createdDate = DateTime.Today, orderDescription = "Available", OderNote = "urgent" },
new PartOrders() { orderNumber = "1003", createdDate = DateTime.Today, orderDescription = "text", OderNote = "High" },
new PartOrders() { orderNumber = "1004", createdDate = DateTime.Today, orderDescription = "Order without services", OderNote = "High" },
};
/// ServiceOrders
List<ServiceOrders> serviceOrders = new List<ServiceOrders>
{
new ServiceOrders() { orderNumber = "1000", createdDate = DateTime.Today, ServiceDescription = "repair", ServiceNote = "medium" },
new ServiceOrders() { orderNumber = "1002", createdDate = DateTime.Today, ServiceDescription = "delivery", ServiceNote = "Low" },
new ServiceOrders() { orderNumber = "1003", createdDate = DateTime.Today, ServiceDescription = "Not Available", ServiceNote = "medium" },
new ServiceOrders() { orderNumber = "1003", createdDate = DateTime.Today, ServiceDescription = "delivery", ServiceNote = "medium" },
new ServiceOrders() { orderNumber = "1005", createdDate = DateTime.Today, ServiceDescription = "Service Without Order", ServiceNote = "medium" },
};
</code></pre>
<p>the list of type List will contain the data :</p>
<pre><code>// first item of type Result
{
orderNumber: "1001",
createdDate: "Date",
List<TheRestOfOrdersData> { orderDescription = "Order spare part", OderNote = "urgent" },
List<TheRestOfServiceData>{ }
}
// Second
{
orderNumber: "1002",
createdDate: "Date",
List<TheRestOfOrdersData> { orderDescription = "Not Available", OderNote = "Low" },{ orderDescription = " Available", OderNote = "urgent" }
List<TheRestOfServiceData> { ServiceDescription = "delivery", ServiceNote = "Low" }
}
// and so on
</code></pre>
<p>Based on the input data you need to groupe</p>
|
[
{
"answer_id": 74562145,
"author": "Marvin Klein",
"author_id": 13440841,
"author_profile": "https://Stackoverflow.com/users/13440841",
"pm_score": 0,
"selected": false,
"text": "var filteredList = yourList.Where(x => x.Month == \"September\" && x.ISSPA == \"1234\").ToList();\n"
},
{
"answer_id": 74562304,
"author": "Magnus",
"author_id": 468973,
"author_profile": "https://Stackoverflow.com/users/468973",
"pm_score": 2,
"selected": true,
"text": "var result = list1\n .Concat(list2)\n .GroupBy(x => (x.Month, x.ISSPA))\n .Where(g => g.Count() > 1)\n .SelectMany(g => g);\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74560585",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20164392/"
] |
74,560,589
|
<p>I have the folder structure thus</p>
<pre><code>project/
----A/
----B/
-1.txt
-2.txt
-.gitignore [ content is: (Line1) * (Line2) !1.txt ]
-.gitignore [ content is: (Line1) /B/* ]
-.gitignore [ content is: (Line1) /A/*
.git/
-.gitignore [content is: (Line1) /project/*]
</code></pre>
<p>The above does not track <code>1.txt</code> nor does it track <code>2.txt</code></p>
<p>My understanding of <code>project/.gitignore</code> which contains:</p>
<pre><code>/A/*
</code></pre>
<p>was:</p>
<p>Ignore everything under folder <code>A/</code> <em>except</em> for exceptions you may encounter in deeper <code>.gitignore</code>s in subfolders, for instance, due to, say <code>project/A/B/.gitignore</code> which is:</p>
<pre><code>*
!1.txt
</code></pre>
<p>that force you to track <code>1.txt</code>. That was also my interpretation of <code>project/A/.gitignore</code> which is:</p>
<pre><code>/B/*
</code></pre>
<p>That is, ignore everything under folder <code>B/</code> <em>except</em> for exceptions you may encounter in deeper <code>.gitignore</code>s in subfolders, for instance, due to, say <code>project/A/B/.gitignore</code>.</p>
<p>Since in the example above neither <code>1.txt</code> nor <code>2.txt</code> are tracked, I am unclear what the right interpretation of <code>/A/*</code> and <code>/B/*</code> mean in the context above.</p>
<p>Everything else being the same, the following change to <code>project/.gitignore</code> of:</p>
<pre><code>!A/
</code></pre>
<p>tracks <code>1.txt</code> while not tracking <code>2.txt</code>.</p>
<p>I would like to understand clearly why <code>/A/*</code> does not work while <code>!A/</code> works in this case.</p>
|
[
{
"answer_id": 74562145,
"author": "Marvin Klein",
"author_id": 13440841,
"author_profile": "https://Stackoverflow.com/users/13440841",
"pm_score": 0,
"selected": false,
"text": "var filteredList = yourList.Where(x => x.Month == \"September\" && x.ISSPA == \"1234\").ToList();\n"
},
{
"answer_id": 74562304,
"author": "Magnus",
"author_id": 468973,
"author_profile": "https://Stackoverflow.com/users/468973",
"pm_score": 2,
"selected": true,
"text": "var result = list1\n .Concat(list2)\n .GroupBy(x => (x.Month, x.ISSPA))\n .Where(g => g.Count() > 1)\n .SelectMany(g => g);\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74560589",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/492307/"
] |
74,560,627
|
<p>I got 2 columns grid with following layout:</p>
<p><a href="https://i.stack.imgur.com/4TvtK.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/4TvtK.png" alt="enter image description here" /></a></p>
<p>My issue is that when I use images inside the right column (1 image inside each box)..Images overflow and whole grid kind of acts weird.</p>
<p>It looks something like this:
<a href="https://i.stack.imgur.com/9GELF.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/9GELF.png" alt="enter image description here" /></a></p>
<p>Codepen Link: <a href="https://codepen.io/kazmi066/pen/MWXGgaL?editors=1100" rel="nofollow noreferrer">https://codepen.io/kazmi066/pen/MWXGgaL?editors=1100</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>* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
.grid {
background: green;
width: 100%;
max-height: 70vh;
display: grid;
gap: 20px;
grid-template-columns: repeat(auto-fit, minmax(340px, 1fr));
}
.col1 {
height: 100%;
background: red;
}
.col2 {
height: 100%;
background: orange;
}
.box1 {
width: 100%;
height: 50%;
border: 1px solid black;
}
.box2 {
width: 100%;
height: 50%;
border: 1px solid blue;
}
img {
width: 100%;
height: 100%;
object-fit: cover;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="grid">
<div class="col1"></div>
<div class="col2">
<div class="box1"><img src="https://images.unsplash.com/photo-1600585154340-be6161a56a0c?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxleHBsb3JlLWZlZWR8N3x8fGVufDB8fHx8&w=1000&q=80" alt="property"/></div>
<div class="box2"><img src="https://images.unsplash.com/photo-1600585154340-be6161a56a0c?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxleHBsb3JlLWZlZWR8N3x8fGVufDB8fHx8&w=1000&q=80" alt="property" /></div>
</div>
</div></code></pre>
</div>
</div>
</p>
<p>I want the images to adjust inside the boxes perfectly without the need of custom height and width so that any size of image can work in this scenario.</p>
|
[
{
"answer_id": 74562145,
"author": "Marvin Klein",
"author_id": 13440841,
"author_profile": "https://Stackoverflow.com/users/13440841",
"pm_score": 0,
"selected": false,
"text": "var filteredList = yourList.Where(x => x.Month == \"September\" && x.ISSPA == \"1234\").ToList();\n"
},
{
"answer_id": 74562304,
"author": "Magnus",
"author_id": 468973,
"author_profile": "https://Stackoverflow.com/users/468973",
"pm_score": 2,
"selected": true,
"text": "var result = list1\n .Concat(list2)\n .GroupBy(x => (x.Month, x.ISSPA))\n .Where(g => g.Count() > 1)\n .SelectMany(g => g);\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74560627",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14061728/"
] |
74,560,633
|
<p>I am trying to get good at Monads and have written the following Monads and functions in which I use the <code>>></code> (in the <code>apply</code>-function) although it is not declared in the Monad itself. How come this is possible to compile, as I understand <a href="http://learnyouahaskell.com/a-fistful-of-monads#walk-the-line" rel="nofollow noreferrer">http://learnyouahaskell.com/a-fistful-of-monads#walk-the-line</a> it is required to declare it in the instantiation of the Monad as is the case with the <code>Maybe Monad</code>.</p>
<pre><code>data Value =
NoneVal
| TrueVal | FalseVal
| IntVal Int
| StringVal String
| ListVal [Value]
deriving (Eq, Show, Read)
data RunErr = EBadV VName | EBadF FName | EBadA String
deriving (Eq, Show)
newtype CMonad a = CMonad {runCMonad :: Env -> (Either RunErr a, [String]) }
instance Monad CMonad where
return a = CMonad (\_ -> (Right a, []))
m >>= f = CMonad (\env -> case runCMonad m env of
(Left a, strLst) -> (Left a, strLst)
(Right a, strLst) -> let (a', strLst') = runCMonad (f a) env in (a', strLst ++ strLst'))
output :: String -> CMonad ()
output s = CMonad(\env -> (Right (), [] ++ [s]))
apply :: FName -> [Value] -> CMonad Value
apply "print" [] = output "" >> return NoneVal
</code></pre>
<p>Furthermore, how would I make it possible to show the output (print it) from the console when running apply. Currently I get the following error message, although my types have <code>derive Show</code>:</p>
<pre><code><interactive>:77:1: error:
* No instance for (Show (CMonad Value)) arising from a use of `print'
* In a stmt of an interactive GHCi command: print it
</code></pre>
|
[
{
"answer_id": 74560947,
"author": "Mark Seemann",
"author_id": 126014,
"author_profile": "https://Stackoverflow.com/users/126014",
"pm_score": 4,
"selected": true,
"text": ">> >>= >> return >> Applicative pure class Applicative m => Monad m where\n (>>=) :: forall a b. m a -> (a -> m b) -> m b\n\n (>>) :: forall a b. m a -> m b -> m b\n m >> k = m >>= \\_ -> k\n \n return :: a -> m a\n return = pure\n >>= Show"
},
{
"answer_id": 74560960,
"author": "Ari Fordsham",
"author_id": 12153248,
"author_profile": "https://Stackoverflow.com/users/12153248",
"pm_score": 2,
"selected": false,
"text": "Monad class Applicative m => Monad m where\n (>>=) :: forall a b. m a -> (a -> m b) -> m b\n\n (>>) :: forall a b. m a -> m b -> m b\n m >> k = m >>= \\_ -> k\n {-# INLINE (>>) #-}\n\n return :: a -> m a\n return = pure\n (>>=) (>>) return Monad Applicative return pure Monad (>>=) Monad (>>) (>>) :: (Monad m) => forall a b. m a -> m b -> m b\nm >> k = m >>= \\_ -> k\n Monad (>>=) Traversable traverse sequenceA MINIMAL -Werror=missing-methods"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74560633",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18049138/"
] |
74,560,644
|
<p>I have a df = desc with a variable "value" that holds long text and would like to remove every word in that variable that ends with ".htm" . I looked for a long time around here and regex expressions and cannot find a solution.</p>
<p>Can anyone help? Thank you so much!</p>
<p>I tried things like:</p>
<pre><code>library(stringr)
desc <- str_replace_all(desc$value, "\*.htm*$", "")
</code></pre>
<p>But I get:</p>
<pre><code>Error: '\*' is an unrecognized escape in character string starting ""\*"
</code></pre>
|
[
{
"answer_id": 74560947,
"author": "Mark Seemann",
"author_id": 126014,
"author_profile": "https://Stackoverflow.com/users/126014",
"pm_score": 4,
"selected": true,
"text": ">> >>= >> return >> Applicative pure class Applicative m => Monad m where\n (>>=) :: forall a b. m a -> (a -> m b) -> m b\n\n (>>) :: forall a b. m a -> m b -> m b\n m >> k = m >>= \\_ -> k\n \n return :: a -> m a\n return = pure\n >>= Show"
},
{
"answer_id": 74560960,
"author": "Ari Fordsham",
"author_id": 12153248,
"author_profile": "https://Stackoverflow.com/users/12153248",
"pm_score": 2,
"selected": false,
"text": "Monad class Applicative m => Monad m where\n (>>=) :: forall a b. m a -> (a -> m b) -> m b\n\n (>>) :: forall a b. m a -> m b -> m b\n m >> k = m >>= \\_ -> k\n {-# INLINE (>>) #-}\n\n return :: a -> m a\n return = pure\n (>>=) (>>) return Monad Applicative return pure Monad (>>=) Monad (>>) (>>) :: (Monad m) => forall a b. m a -> m b -> m b\nm >> k = m >>= \\_ -> k\n Monad (>>=) Traversable traverse sequenceA MINIMAL -Werror=missing-methods"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74560644",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20566781/"
] |
74,560,667
|
<p>Hello StackOverflow People! I have some trouble here, I do some research but I still can't make it. I have two columns that are substracted from a Dataset, the columns are "# Externo" and "Nro Envio ML".</p>
<p>I want that the result of the code gives me only the numbers that exist in "# Externo" but no in "Nro Envio ML"</p>
<p>For Example:</p>
<p><a href="https://i.stack.imgur.com/cTDHp.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/cTDHp.png" alt="enter image description here" /></a></p>
<p>If 41765931626 is only in "# Externo" column but no in "Nro Envio ML", I want to print that number. Also if no exist any number in "# Externo" that is not on "Nro Envio ML" I want to print some text print("No strange sales")</p>
<p>Here its the code I tried. Sorry for my bad english</p>
<pre><code> import numpy as np
df2=df2.dropna(subset=['Unnamed: 13'])
df2 = df2[df2['Unnamed: 13'] != 'Nro. Envío']
df2['Nro Envio ML']=df2['Unnamed: 13']
dfn=df2[["# Externo","Nro Envio ML"]]
dfn1 = dfn[dfn['# Externo'] != dfn['Nro Envio ML']]
dfn1
</code></pre>
<p>Also with diff It gives me values that are on 'Nro Envio ML'</p>
<p><a href="https://i.stack.imgur.com/zzu4L.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/zzu4L.png" alt="enter image description here" /></a></p>
<p>Link for Sample:
<a href="https://github.com/francoveracallorda/sample" rel="nofollow noreferrer">https://github.com/francoveracallorda/sample</a></p>
|
[
{
"answer_id": 74561506,
"author": "Chrysophylaxs",
"author_id": 9499196,
"author_profile": "https://Stackoverflow.com/users/9499196",
"pm_score": 2,
"selected": false,
"text": "set import pandas as pd\n\ndf = pd.DataFrame({\n \"# Externo\": [3, 5, 4, 2, 1, 7, 8],\n \"Nro Envio ML\": [4, 9, 0, 2, 1, 3, 5]\n})\n\ndiff = set(df[\"# Externo\"]) - set(df[\"Nro Envio ML\"])\n# diff contains the values that are in df[\"# Externo\"] but not in df[\"Nro Envio ML\"].\n\nprint(f\"Weird sales: {diff}\" if diff else \"No strange sales\")\n# Output:\n# Weird sales: {8, 7}\n diff = df.loc[~df[\"# Externo\"].isin(df[\"Nro Envio ML\"]), \"# Externo\"] pd.Series"
},
{
"answer_id": 74561628,
"author": "GenZ",
"author_id": 19921706,
"author_profile": "https://Stackoverflow.com/users/19921706",
"pm_score": 0,
"selected": false,
"text": "~ isin series1 = pd.Series([2, 4, 8, 20, 10, 47, 99])\nseries2= pd.Series([1, 3, 6, 4, 10, 99, 50])\nseries3 = pd.Series([2, 4, 8, 20, 10, 47, 99])\ndf = pd.concat([series1, series2,series3], axis=1)\n diff = series1[~series1.isin(series2)]\n same = series1[~series1.isin(series3)]\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74560667",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20533290/"
] |
74,560,670
|
<p>I have an array <strong>x</strong> of 30 samples, and I wish to separate it out into chunks of 8 samples each in 2 different ways.</p>
<p>First, I want to separate it avoiding any overlap so that I end up with 3 arrays of length 8 and the final array will be only 6 (due to some samples being missing).</p>
<p>Secondly, I want to separate it so that the final array will be the last 2 samples of the previous array plus the final 6.</p>
<p>Both methods preferably without for loops as I'm trying to optimise this for when I expand it to arrays with lengths in the ten thousands.</p>
<p>I have tried using np.array_split as follows</p>
<pre><code>x = np.array([1 ,1, 2 ,1 ,1 ,2 ,1, 0 ,3, 1, 2 ,2, 1, 2, 1, 1,50,1 ,1, 1, 1, 4, 1, 11, 15, 0, 0, 1, 1,0])
y = np.array_split(x,np.ceil(len(x)/8))
</code></pre>
<p>However, that results in:</p>
<pre><code>y = [array([1, 1, 2, 1, 1, 2, 1, 0]),
array([3, 1, 2, 2, 1, 2, 1, 1]),
array([50, 1, 1, 1, 1, 4, 1]),
array([11, 15, 0, 0, 1, 1, 0])]
</code></pre>
<p>so <strong>y</strong> is clearly made up of 2x8 length arrays and 2x7 length arrays, not what I want. How do I go about achieving it the way I want. The first method is the more important, the second is a bonus.</p>
<p>Thanks</p>
|
[
{
"answer_id": 74560898,
"author": "Tat",
"author_id": 19269506,
"author_profile": "https://Stackoverflow.com/users/19269506",
"pm_score": 0,
"selected": false,
"text": "\"\"\"for the first you can use range\"\"\"\nx = np.array([1 ,1, 2 ,1 ,1 ,2 ,1, 0 ,3, 1, 2 ,2, 1, 2, 1, 1,50,1 ,1, 1, 1, 4, 1, 11, 15, 0, 0, 1, 1,0])\nres = [x[i:i+8] for i in range(0, len(x), 8)]\n\"\"\"for the second you could just pop the first item\"\"\"\nres.pop(0)\nprint(res)\n"
},
{
"answer_id": 74561047,
"author": "harry_09",
"author_id": 14515470,
"author_profile": "https://Stackoverflow.com/users/14515470",
"pm_score": 1,
"selected": false,
"text": "import numpy as np\n\nx = np.array([1 ,1, 2 ,1 ,1 ,2 ,1, 0 ,3, 1, 2 ,2, 1, 2, 1, 1,50 ,1 ,1, 1, 1, 4, 1, 11, 15, 0, 0, 1, 1,0])\n\ndef split_reminder(x, chunk_size, axis=0):\n indices = np.arange(chunk_size, x.shape[axis], chunk_size)\n return np.array_split(x, indices, axis)\n\nsplit_reminder(x, 8)\n"
},
{
"answer_id": 74561082,
"author": "Bhargav",
"author_id": 15358800,
"author_profile": "https://Stackoverflow.com/users/15358800",
"pm_score": 0,
"selected": false,
"text": "from utilspie import iterutils\n\nx = np.array([1 ,1, 2 ,1 ,1 ,2 ,1, 0 ,3, 1, 2 ,2, 1, 2, 1, 1,50,1 ,1, 1, 1, 4, 1, 11, 15, 0, 0, 1, 1,0])\n\nprint(list(iterutils.get_chunks(x, 8)))\n [array([1, 1, 2, 1, 1, 2, 1, 0]), #Length 8\n array([3, 1, 2, 2, 1, 2, 1, 1]), #Length 8\n array([50, 1, 1, 1, 1, 4, 1, 11]), #Length 8\n array([15, 0, 0, 1, 1, 0])] #Length 6\n import numpy as np\nfrom utilspie import iterutils\nimport itertools\nfrom bottleneck import push\n\nx = np.array([1 ,1, 2 ,1 ,1 ,2 ,1, 0 ,3, 1, 2 ,2, 1, 2, 1, 1,50,1 ,1, 1, 1, 4, 1, 11, 15, 0, 0, 1, 1,0])\n\nx =(list(iterutils.get_chunks(x, 8)))\n\nx_new=np.array(list(itertools.zip_longest(*x, fillvalue=np.nan))).T\n\nx_new=push(x_new, axis=0)\nprint(x_new)\n [[ 1. 1. 2. 1. 1. 2. 1. 0.] #Length 8\n [ 3. 1. 2. 2. 1. 2. 1. 1.] #Length 8\n [50. 1. 1. 1. 1. 4. 1. 11.] #Length 8\n [15. 0. 0. 1. 1. 0. 1. 11.]] #Length 8\n"
},
{
"answer_id": 74561140,
"author": "user19077881",
"author_id": 19077881,
"author_profile": "https://Stackoverflow.com/users/19077881",
"pm_score": 0,
"selected": false,
"text": "num = int(len(x)/8)\ny = np.array_split(x[:num*8], num)\ny += [x[-9:-1]]\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74560670",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4879524/"
] |
74,560,689
|
<p>Can somebody please explain why the following loop for thread creation fails without the sleep function call?</p>
<pre><code> for(t=0; t<NUM_THREADS; t++) {
printf("Main: creating thread %d\n", t);
rc = pthread_create(&thread[t], NULL, BusyWork, (void *)&t);
sleep(1);
if (rc) {
perror("pthread_create");
exit(EXIT_FAILURE);
}
}
</code></pre>
<p>If sleep is not inserted then thread function seems to take as an argument
an arbitrary integer between 0 ad NUM_THREADS.</p>
<p>I'm running this on an Ubuntu machine.</p>
|
[
{
"answer_id": 74560898,
"author": "Tat",
"author_id": 19269506,
"author_profile": "https://Stackoverflow.com/users/19269506",
"pm_score": 0,
"selected": false,
"text": "\"\"\"for the first you can use range\"\"\"\nx = np.array([1 ,1, 2 ,1 ,1 ,2 ,1, 0 ,3, 1, 2 ,2, 1, 2, 1, 1,50,1 ,1, 1, 1, 4, 1, 11, 15, 0, 0, 1, 1,0])\nres = [x[i:i+8] for i in range(0, len(x), 8)]\n\"\"\"for the second you could just pop the first item\"\"\"\nres.pop(0)\nprint(res)\n"
},
{
"answer_id": 74561047,
"author": "harry_09",
"author_id": 14515470,
"author_profile": "https://Stackoverflow.com/users/14515470",
"pm_score": 1,
"selected": false,
"text": "import numpy as np\n\nx = np.array([1 ,1, 2 ,1 ,1 ,2 ,1, 0 ,3, 1, 2 ,2, 1, 2, 1, 1,50 ,1 ,1, 1, 1, 4, 1, 11, 15, 0, 0, 1, 1,0])\n\ndef split_reminder(x, chunk_size, axis=0):\n indices = np.arange(chunk_size, x.shape[axis], chunk_size)\n return np.array_split(x, indices, axis)\n\nsplit_reminder(x, 8)\n"
},
{
"answer_id": 74561082,
"author": "Bhargav",
"author_id": 15358800,
"author_profile": "https://Stackoverflow.com/users/15358800",
"pm_score": 0,
"selected": false,
"text": "from utilspie import iterutils\n\nx = np.array([1 ,1, 2 ,1 ,1 ,2 ,1, 0 ,3, 1, 2 ,2, 1, 2, 1, 1,50,1 ,1, 1, 1, 4, 1, 11, 15, 0, 0, 1, 1,0])\n\nprint(list(iterutils.get_chunks(x, 8)))\n [array([1, 1, 2, 1, 1, 2, 1, 0]), #Length 8\n array([3, 1, 2, 2, 1, 2, 1, 1]), #Length 8\n array([50, 1, 1, 1, 1, 4, 1, 11]), #Length 8\n array([15, 0, 0, 1, 1, 0])] #Length 6\n import numpy as np\nfrom utilspie import iterutils\nimport itertools\nfrom bottleneck import push\n\nx = np.array([1 ,1, 2 ,1 ,1 ,2 ,1, 0 ,3, 1, 2 ,2, 1, 2, 1, 1,50,1 ,1, 1, 1, 4, 1, 11, 15, 0, 0, 1, 1,0])\n\nx =(list(iterutils.get_chunks(x, 8)))\n\nx_new=np.array(list(itertools.zip_longest(*x, fillvalue=np.nan))).T\n\nx_new=push(x_new, axis=0)\nprint(x_new)\n [[ 1. 1. 2. 1. 1. 2. 1. 0.] #Length 8\n [ 3. 1. 2. 2. 1. 2. 1. 1.] #Length 8\n [50. 1. 1. 1. 1. 4. 1. 11.] #Length 8\n [15. 0. 0. 1. 1. 0. 1. 11.]] #Length 8\n"
},
{
"answer_id": 74561140,
"author": "user19077881",
"author_id": 19077881,
"author_profile": "https://Stackoverflow.com/users/19077881",
"pm_score": 0,
"selected": false,
"text": "num = int(len(x)/8)\ny = np.array_split(x[:num*8], num)\ny += [x[-9:-1]]\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74560689",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20590631/"
] |
74,560,711
|
<p>I am trying to make the text sit vertically in the middle next to the diamond box with the number like this:</p>
<p><a href="https://i.stack.imgur.com/AJYP4.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/AJYP4.jpg" alt="Text aligned centrally to the box" /></a></p>
<p>Currently I have this code:</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>.diamond {
width: 50px;
aspect-ratio: 1;
font: 20pt Arial, sans-serif;
color: white;
display: flex;
justify-content: center;
align-items: center;
background: #EB008B;
margin: 20px;
margin-bottom: 0px;
clip-path: polygon(50% 0, 100% 50%, 50% 100%, 0 50%);
}
.image-txt-container {
display: flex;
align-items: center;
flex-direction: row;
}
.pf-title {
margin-right :auto;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="image-txt-container">
<div class="diamond">1
</div>
<h4 class="pf-title">BRIDGING / SHORT-TERM FINANCE</h4>
</div></code></pre>
</div>
</div>
</p>
|
[
{
"answer_id": 74560851,
"author": "Mike Attal",
"author_id": 13418034,
"author_profile": "https://Stackoverflow.com/users/13418034",
"pm_score": 0,
"selected": false,
"text": ".diamond {\n width: 50px;\n aspect-ratio: 1;\n font: 20pt Arial, sans-serif;\n color: white;\n display: flex;\n justify-content: center;\n align-items: center;\n background: #EB008B;\n margin-right: 20px;\n clip-path: polygon(50% 0, 100% 50%, 50% 100%, 0 50%);\n}\n\n.image-txt-container {\n display: flex;\n align-items: center;\n flex-direction: row;\n}\n\n.pf-title {\n margin-right :auto;\n} <div class=\"image-txt-container\">\n <div class=\"diamond\">1\n </div>\n <h4 class=\"pf-title\">BRIDGING / SHORT-TERM FINANCE</h4>\n</div>"
},
{
"answer_id": 74560863,
"author": "Vikas Patel",
"author_id": 8852469,
"author_profile": "https://Stackoverflow.com/users/8852469",
"pm_score": 2,
"selected": true,
"text": ".diamond {\n width: 50px;\n aspect-ratio: 1;\n font: 20pt Arial, sans-serif;\n color: white;\n display: flex;\n justify-content: center;\n align-items: center;\n background: #EB008B;\n margin: 20px;\n margin-bottom: 0px;\n clip-path: polygon(50% 0, 100% 50%, 50% 100%, 0 50%);\n}\n\n.image-txt-container {\n display: flex;\n align-items: baseline;\n flex-direction: row;\n}\n\n.pf-title {\n margin-right: auto;\n font-size: 30px;\n} <div class=\"image-txt-container\">\n <div class=\"diamond\">1\n </div>\n <h4 class=\"pf-title\">BRIDGING / SHORT-TERM FINANCE</h4>\n</div>"
},
{
"answer_id": 74560959,
"author": "AWM",
"author_id": 20570458,
"author_profile": "https://Stackoverflow.com/users/20570458",
"pm_score": 0,
"selected": false,
"text": ".diamond .pf-title .diamond {\n width: 50px;\n aspect-ratio: 1;\n font: 20pt Arial, sans-serif;\n color: white;\n display: flex;\n justify-content: center;\n align-items: center;\n background: #EB008B;\n /* margin: 20px; */ <--- remove\n margin-bottom: 0px;\n clip-path: polygon(50% 0, 100% 50%, 50% 100%, 0 50%);\n}\n\n.image-txt-container {\n display: flex;\n align-items: center;\n flex-direction: row;\n}\n\n.pf-title {\n padding: 10px; <--- add\n margin-right :auto;\n} <div class=\"image-txt-container\">\n <div class=\"diamond\">1</div>\n <h4 class=\"pf-title\">BRIDGING / SHORT-TERM FINANCE</h4>\n</div>\n "
},
{
"answer_id": 74561109,
"author": "reza hrkeng",
"author_id": 20517507,
"author_profile": "https://Stackoverflow.com/users/20517507",
"pm_score": 0,
"selected": false,
"text": ".diamond {\n width: 60%;\n aspect-ratio: 1;\n font: 20pt Arial, sans-serif;\n color: white;\n display: flex;\n flex:30%;\n justify-content: center;\n align-items: center;\n background: #EB008B;\n clip-path: polygon(50% 0, 100% 50%, 50% 100%, 0 50%);\n}\n\n.image-txt-container {\n display: flex;\n align-items: center;\n justify-content:space-evently;\n flex-direction: row;\n padding:0 5%;\n gap: 6%;\n}\n\n <div class=\"image-txt-container\">\n <div class=\"diamond\">1\n </div>\n <h4 class=\"pf-title\">BRIDGING / SHORT-TERM FINANCE</h4>\n</div>"
},
{
"answer_id": 74561165,
"author": "Salwa A. Soliman",
"author_id": 18270700,
"author_profile": "https://Stackoverflow.com/users/18270700",
"pm_score": 0,
"selected": false,
"text": ".diamond {\n width: 50px;\n aspect-ratio: 1;\n font: 20pt Arial, sans-serif;\n color: white;\n display: flex;\n justify-content: center;\n align-items: center;\n background: #EB008B;\n /*margin: 20px;\n margin-bottom: 0px;*/\n /* Add margin right only*/\n margin-right: 20px;\n clip-path: polygon(50% 0, 100% 50%, 50% 100%, 0 50%);\n}\n\n.image-txt-container {\n display: flex;\n align-items: center;\n flex-direction: row;\n /*Add margin to the container*/\n margin: 20px;\n}\n\n\n/* No need for this \n.pf-title {\n margin-right: auto;\n}*/ <div class=\"image-txt-container\">\n <div class=\"diamond\">1</div>\n <h4 class=\"pf-title\">BRIDGING / SHORT-TERM FINANCE</h4>\n</div>"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74560711",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8105415/"
] |
74,560,735
|
<p>Hi I have some json which is kinda awkward due to its nested/dynamic nature.</p>
<p>It looks something like below. Apologies if it's slightly off. I am trying to create a dictionary like <code>Dictionary <string, Dictionary<string,long>></code>, where each date value is the first key and the item1 is the second key etc.</p>
<pre><code>xyz {
xyzcharacteristic1{
"2022/10/01": {
"item1": 0000,
"item4": 11111,
"item2": 33333,
"item3": 33333,
}
"2022-09-05": {
"item2": 0000,
"item1": 11111,
"item3": 22222,
"item4": 22222,
}...
}, xyzcharacteristic2{...}, xyzcharacteristic3{...}
xyy {
xyycharacteristic1{...}...
}
</code></pre>
<p>I have tried to parse it using a few methods ive seen on stack overflow but I just cant get access the key / values individually.</p>
<pre><code>string json = r.ReadToEnd();
var rss = JObject.Parse(json);
var dates= ((JObject)rss["xyz"]["xyzcharacteristic1"]).Properties();
}
foreach (var item in dates)
{
Console.WriteLine(item);
}
</code></pre>
|
[
{
"answer_id": 74560851,
"author": "Mike Attal",
"author_id": 13418034,
"author_profile": "https://Stackoverflow.com/users/13418034",
"pm_score": 0,
"selected": false,
"text": ".diamond {\n width: 50px;\n aspect-ratio: 1;\n font: 20pt Arial, sans-serif;\n color: white;\n display: flex;\n justify-content: center;\n align-items: center;\n background: #EB008B;\n margin-right: 20px;\n clip-path: polygon(50% 0, 100% 50%, 50% 100%, 0 50%);\n}\n\n.image-txt-container {\n display: flex;\n align-items: center;\n flex-direction: row;\n}\n\n.pf-title {\n margin-right :auto;\n} <div class=\"image-txt-container\">\n <div class=\"diamond\">1\n </div>\n <h4 class=\"pf-title\">BRIDGING / SHORT-TERM FINANCE</h4>\n</div>"
},
{
"answer_id": 74560863,
"author": "Vikas Patel",
"author_id": 8852469,
"author_profile": "https://Stackoverflow.com/users/8852469",
"pm_score": 2,
"selected": true,
"text": ".diamond {\n width: 50px;\n aspect-ratio: 1;\n font: 20pt Arial, sans-serif;\n color: white;\n display: flex;\n justify-content: center;\n align-items: center;\n background: #EB008B;\n margin: 20px;\n margin-bottom: 0px;\n clip-path: polygon(50% 0, 100% 50%, 50% 100%, 0 50%);\n}\n\n.image-txt-container {\n display: flex;\n align-items: baseline;\n flex-direction: row;\n}\n\n.pf-title {\n margin-right: auto;\n font-size: 30px;\n} <div class=\"image-txt-container\">\n <div class=\"diamond\">1\n </div>\n <h4 class=\"pf-title\">BRIDGING / SHORT-TERM FINANCE</h4>\n</div>"
},
{
"answer_id": 74560959,
"author": "AWM",
"author_id": 20570458,
"author_profile": "https://Stackoverflow.com/users/20570458",
"pm_score": 0,
"selected": false,
"text": ".diamond .pf-title .diamond {\n width: 50px;\n aspect-ratio: 1;\n font: 20pt Arial, sans-serif;\n color: white;\n display: flex;\n justify-content: center;\n align-items: center;\n background: #EB008B;\n /* margin: 20px; */ <--- remove\n margin-bottom: 0px;\n clip-path: polygon(50% 0, 100% 50%, 50% 100%, 0 50%);\n}\n\n.image-txt-container {\n display: flex;\n align-items: center;\n flex-direction: row;\n}\n\n.pf-title {\n padding: 10px; <--- add\n margin-right :auto;\n} <div class=\"image-txt-container\">\n <div class=\"diamond\">1</div>\n <h4 class=\"pf-title\">BRIDGING / SHORT-TERM FINANCE</h4>\n</div>\n "
},
{
"answer_id": 74561109,
"author": "reza hrkeng",
"author_id": 20517507,
"author_profile": "https://Stackoverflow.com/users/20517507",
"pm_score": 0,
"selected": false,
"text": ".diamond {\n width: 60%;\n aspect-ratio: 1;\n font: 20pt Arial, sans-serif;\n color: white;\n display: flex;\n flex:30%;\n justify-content: center;\n align-items: center;\n background: #EB008B;\n clip-path: polygon(50% 0, 100% 50%, 50% 100%, 0 50%);\n}\n\n.image-txt-container {\n display: flex;\n align-items: center;\n justify-content:space-evently;\n flex-direction: row;\n padding:0 5%;\n gap: 6%;\n}\n\n <div class=\"image-txt-container\">\n <div class=\"diamond\">1\n </div>\n <h4 class=\"pf-title\">BRIDGING / SHORT-TERM FINANCE</h4>\n</div>"
},
{
"answer_id": 74561165,
"author": "Salwa A. Soliman",
"author_id": 18270700,
"author_profile": "https://Stackoverflow.com/users/18270700",
"pm_score": 0,
"selected": false,
"text": ".diamond {\n width: 50px;\n aspect-ratio: 1;\n font: 20pt Arial, sans-serif;\n color: white;\n display: flex;\n justify-content: center;\n align-items: center;\n background: #EB008B;\n /*margin: 20px;\n margin-bottom: 0px;*/\n /* Add margin right only*/\n margin-right: 20px;\n clip-path: polygon(50% 0, 100% 50%, 50% 100%, 0 50%);\n}\n\n.image-txt-container {\n display: flex;\n align-items: center;\n flex-direction: row;\n /*Add margin to the container*/\n margin: 20px;\n}\n\n\n/* No need for this \n.pf-title {\n margin-right: auto;\n}*/ <div class=\"image-txt-container\">\n <div class=\"diamond\">1</div>\n <h4 class=\"pf-title\">BRIDGING / SHORT-TERM FINANCE</h4>\n</div>"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74560735",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8684461/"
] |
74,560,767
|
<p>Created a contract a basic one to deploy on the Mumbai BC.</p>
<p>The same one of uni swaps the basic one, just with different addresses. Since this is in Mumbai BC, so I created it with wmatic.</p>
<p>then after approving all the addresses, I get this error without any explanation or option to understand where it failed when i try to singleswap.
<div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity =0.7.6;
pragma abicoder v2;
import "hardhat/console.sol";
import '@uniswap/v3-periphery/contracts/libraries/TransferHelper.sol';
import '@uniswap/v3-periphery/contracts/interfaces/ISwapRouter.sol';
contract SwapExamples {
// For the scope of these swap examples,
// we will detail the design considerations when using
// `exactInput`, `exactInputSingle`, `exactOutput`, and `exactOutputSingle`.
// It should be noted that for the sake of these examples, we purposefully pass in the swap router instead of inherit the swap router for simplicity.
// More advanced example contracts will detail how to inherit the swap router safely.
ISwapRouter public immutable swapRouter;
address public constant WMATIC = 0x9c3C9283D3e44854697Cd22D3Faa240Cfb032889;
address public constant WETH = 0xA6FA4fB5f76172d178d61B04b0ecd319C5d1C0aa;
// For this example, we will set the pool fee to 0.3%.
uint24 public constant poolFee = 3000;
constructor(ISwapRouter _swapRouter) {
swapRouter = _swapRouter;
}
/// @notice swapExactInputSingle swaps a fixed amount of WMATIC for a maximum possible amount of WETH
/// using the WMATIC/WETH 0.3% pool by calling `exactInputSingle` in the swap router.
/// @dev The calling address must approve this contract to spend at least `amountIn` worth of its WMATIC for this function to succeed.
/// @param amountIn The exact amount of WMATIC that will be swapped for WETH.
/// @return amountOut The amount of WETH received.
function swapExactInputSingle(uint256 amountIn) external returns (uint256 amountOut) {
// msg.sender must approve this contract
// Transfer the specified amount of WMATIC to this contract.
TransferHelper.safeTransferFrom(WMATIC, msg.sender, address(this), amountIn);
// Approve the router to spend WMATIC.
TransferHelper.safeApprove(WMATIC, address(swapRouter), amountIn);
// Naively set amountOutMinimum to 0. In production, use an oracle or other data source to choose a safer value for amountOutMinimum.
// We also set the sqrtPriceLimitx96 to be 0 to ensure we swap our exact input amount.
ISwapRouter.ExactInputSingleParams memory params =
ISwapRouter.ExactInputSingleParams({
tokenIn: WMATIC,
tokenOut: WETH,
fee: poolFee,
recipient: msg.sender,
deadline: block.timestamp,
amountIn: amountIn,
amountOutMinimum: 0,
sqrtPriceLimitX96: 0
});
// The call to `exactInputSingle` executes the swap.
amountOut = swapRouter.exactInputSingle(params);
}
/// @notice swapExactOutputSingle swaps a minimum possible amount of WMATIC for a fixed amount of WETH.
/// @dev The calling address must approve this contract to spend its WMATIC for this function to succeed. As the amount of input WMATIC is variable,
/// the calling address will need to approve for a slightly higher amount, anticipating some variance.
/// @param amountOut The exact amount of WETH to receive from the swap.
/// @param amountInMaximum The amount of WMATIC we are willing to spend to receive the specified amount of WETH.
/// @return amountIn The amount of WMATIC actually spent in the swap.
function swapExactOutputSingle(uint256 amountOut, uint256 amountInMaximum) external returns (uint256 amountIn) {
// Transfer the specified amount of WMATIC to this contract.
TransferHelper.safeTransferFrom(WMATIC, msg.sender, address(this), amountInMaximum);
// Approve the router to spend the specifed `amountInMaximum` of WMATIC.
// In production, you should choose the maximum amount to spend based on oracles or other data sources to acheive a better swap.
TransferHelper.safeApprove(WMATIC, address(swapRouter), amountInMaximum);
ISwapRouter.ExactOutputSingleParams memory params =
ISwapRouter.ExactOutputSingleParams({
tokenIn: WMATIC,
tokenOut: WETH,
fee: poolFee,
recipient: msg.sender,
deadline: block.timestamp,
amountOut: amountOut,
amountInMaximum: amountInMaximum,
sqrtPriceLimitX96: 0
});
// Executes the swap returning the amountIn needed to spend to receive the desired amountOut.
amountIn = swapRouter.exactOutputSingle(params);
// For exact output swaps, the amountInMaximum may not have all been spent.
// If the actual amount spent (amountIn) is less than the specified maximum amount, we must refund the msg.sender and approve the swapRouter to spend 0.
if (amountIn < amountInMaximum) {
TransferHelper.safeApprove(WMATIC, address(swapRouter), 0);
TransferHelper.safeTransfer(WMATIC, msg.sender, amountInMaximum - amountIn);
}
}
}</code></pre>
</div>
</div>
</p>
|
[
{
"answer_id": 74634130,
"author": "djchals",
"author_id": 14168808,
"author_profile": "https://Stackoverflow.com/users/14168808",
"pm_score": 0,
"selected": false,
"text": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity =0.7.6;\npragma abicoder v2;\nimport '@uniswap/v3-core/contracts/libraries/LowGasSafeMath.sol';\n\nimport \"./SwapRouter02lib/ISwapRouter02.sol\";\nimport \"./SwapRouter02lib/IV3SwapRouter.sol\";\nimport '@openzeppelin/contracts/token/ERC20/IERC20.sol';\n\ncontract TestSwap {\n using LowGasSafeMath for uint256;\n\n ISwapRouter02 public immutable uniswapRouter;\n\n constructor(address _uniswapRouter) {\n uniswapRouter = ISwapRouter02(_uniswapRouter);\n }\n\n function swapUniswap(\n address token0, \n address token1, \n uint256 amount, \n uint256 fee \n ) external returns (uint256 amountOut) {\n require(IERC20(token0).transferFrom(msg.sender, address(this), amount),\"STF v2\");\n require(IERC20(token0).approve(address(uniswapRouter), amount),\"SA v2\");\n\n uint256 amountMin = LowGasSafeMath.add(amount, fee);\n IV3SwapRouter.ExactInputSingleParams memory params = IV3SwapRouter.ExactInputSingleParams({\n tokenIn: token0,\n tokenOut: token1,\n fee: uint24(fee),\n recipient: msg.sender,\n amountIn: amount,\n amountOutMinimum: 0,\n sqrtPriceLimitX96: 0\n });\n\n (bool success, bytes memory amountBytes) = address(uniswapRouter).call(\n abi.encodeWithSelector(\n IV3SwapRouter.exactInputSingle.selector,\n params\n )\n );\n\n return bytesToUint(amountBytes);\n }\n\n function bytesToUint(bytes memory _bytes) internal pure returns (uint256 value) {\n assembly {\n value := mload(add(_bytes, 0x20))\n }\n }\n}\n const hre = require('hardhat');\nconst ethers = hre.ethers;\nconst { abi: abiERC20 } = require(\"../artifacts/contracts/IERC20.sol/IERC20.json\");\nconst uniswapRouter = \"0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45\"; //ROUTER 02\nconst uniswapFactory = \"0x1F98431c8aD98523631AE4a59f267346ea31F984\"; //FACTORY\n\nconst wmatic = \"0x9c3C9283D3e44854697Cd22D3Faa240Cfb032889\"; //wmatic mumbai\nconst weth = \"0xA6FA4fB5f76172d178d61B04b0ecd319C5d1C0aa\"; //weth mumbai\n\nconst fee1 = 500;\n\nconst signerAddress = \"0x1234567890123456789012345678901234567890\";//this must be one of your address with wmatic tokens (I tested on mumbai)\n\nasync function main() {\n \n await hre.network.provider.request({\n method: 'hardhat_impersonateAccount',\n params: [signerAddress],\n });\n const signer = await ethers.provider.getSigner(signerAddress);\n\n var wmaticContract = new ethers.Contract(\n wmatic,\n abiERC20,\n signer\n );\n\n var wethContract = new ethers.Contract(\n weth,\n abiERC20,\n signer\n );\n\n const TestSwap = await ethers.getContractFactory(\"TestSwap\");\n const testSwap = await TestSwap.deploy(\n uniswapRouter\n );\n await testSwap.deployed();\n\n console.log((await wmaticContract.balanceOf(signer._address)).toString());\n console.log((await wethContract.balanceOf(signer._address)).toString());\n\n console.log((await wmaticContract.balanceOf(testSwap.address)).toString());\n console.log((await wethContract.balanceOf(testSwap.address)).toString());\n\n const amountApprove = ethers.utils.parseEther('1'); \n const amount = ethers.utils.parseEther('0.5');\n\n const GAS_PARAMS = {\n gasLimit: \"1250000\",//exagerate amount of gas, must be adjusted\n gasPrice: ethers.utils.parseUnits('100','gwei').toString(),\n };\n const txApproveWMatic = await wmaticContract.connect(signer).approve(\n testSwap.address, \n amountApprove, \n GAS_PARAMS);\n await txApproveWMatic.wait();\n\n const tx = await testSwap.connect(signer).swapUniswap(\n wmatic,\n weth,\n amount,\n fee1, \n GAS_PARAMS\n );\n\n console.log(tx);\n const txResponse = await tx.wait();\n console.log(txResponse);\n\n console.log((await wmaticContract.balanceOf(signer._address)).toString());\n console.log((await wethContract.balanceOf(signer._address)).toString());\n console.log((await wmaticContract.balanceOf(testSwap.address)).toString());\n console.log((await wethContract.balanceOf(testSwap.address)).toString());\n}\n\nmain();\n\n $ npx hardhat run scripts/deploy-test.js\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74560767",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14200659/"
] |
74,560,780
|
<p>I have a long pipeline that I'm constantly reusing in my script, and to make it easy to read I want to put the pipeline in a variable. Is it possible?</p>
<pre><code>cat miami.tmp | grep -A5 "$date" | grep -A3 "$nexthour" | grep "celsius" | grep -E -o '[-]?[0-9].[0-9]' | head -n 1 >> miami.txt
</code></pre>
<p>I have tried</p>
<pre><code>temperature=$( | grep -A5 "$date" | grep -A3 "$nexthour" | grep "celsius" | grep -E -
o '[-]?[0-9].[0-9]' | head -n 1 )
</code></pre>
<p>or</p>
<pre><code>temperature="| grep -A5 "$date" | grep -A3 "$nexthour" | grep "celsius" | grep -E -o '[-]?[0-9].[0-9]' | head -n 1"
</code></pre>
<p>but get errors saying the commands weren't found.</p>
|
[
{
"answer_id": 74634130,
"author": "djchals",
"author_id": 14168808,
"author_profile": "https://Stackoverflow.com/users/14168808",
"pm_score": 0,
"selected": false,
"text": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity =0.7.6;\npragma abicoder v2;\nimport '@uniswap/v3-core/contracts/libraries/LowGasSafeMath.sol';\n\nimport \"./SwapRouter02lib/ISwapRouter02.sol\";\nimport \"./SwapRouter02lib/IV3SwapRouter.sol\";\nimport '@openzeppelin/contracts/token/ERC20/IERC20.sol';\n\ncontract TestSwap {\n using LowGasSafeMath for uint256;\n\n ISwapRouter02 public immutable uniswapRouter;\n\n constructor(address _uniswapRouter) {\n uniswapRouter = ISwapRouter02(_uniswapRouter);\n }\n\n function swapUniswap(\n address token0, \n address token1, \n uint256 amount, \n uint256 fee \n ) external returns (uint256 amountOut) {\n require(IERC20(token0).transferFrom(msg.sender, address(this), amount),\"STF v2\");\n require(IERC20(token0).approve(address(uniswapRouter), amount),\"SA v2\");\n\n uint256 amountMin = LowGasSafeMath.add(amount, fee);\n IV3SwapRouter.ExactInputSingleParams memory params = IV3SwapRouter.ExactInputSingleParams({\n tokenIn: token0,\n tokenOut: token1,\n fee: uint24(fee),\n recipient: msg.sender,\n amountIn: amount,\n amountOutMinimum: 0,\n sqrtPriceLimitX96: 0\n });\n\n (bool success, bytes memory amountBytes) = address(uniswapRouter).call(\n abi.encodeWithSelector(\n IV3SwapRouter.exactInputSingle.selector,\n params\n )\n );\n\n return bytesToUint(amountBytes);\n }\n\n function bytesToUint(bytes memory _bytes) internal pure returns (uint256 value) {\n assembly {\n value := mload(add(_bytes, 0x20))\n }\n }\n}\n const hre = require('hardhat');\nconst ethers = hre.ethers;\nconst { abi: abiERC20 } = require(\"../artifacts/contracts/IERC20.sol/IERC20.json\");\nconst uniswapRouter = \"0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45\"; //ROUTER 02\nconst uniswapFactory = \"0x1F98431c8aD98523631AE4a59f267346ea31F984\"; //FACTORY\n\nconst wmatic = \"0x9c3C9283D3e44854697Cd22D3Faa240Cfb032889\"; //wmatic mumbai\nconst weth = \"0xA6FA4fB5f76172d178d61B04b0ecd319C5d1C0aa\"; //weth mumbai\n\nconst fee1 = 500;\n\nconst signerAddress = \"0x1234567890123456789012345678901234567890\";//this must be one of your address with wmatic tokens (I tested on mumbai)\n\nasync function main() {\n \n await hre.network.provider.request({\n method: 'hardhat_impersonateAccount',\n params: [signerAddress],\n });\n const signer = await ethers.provider.getSigner(signerAddress);\n\n var wmaticContract = new ethers.Contract(\n wmatic,\n abiERC20,\n signer\n );\n\n var wethContract = new ethers.Contract(\n weth,\n abiERC20,\n signer\n );\n\n const TestSwap = await ethers.getContractFactory(\"TestSwap\");\n const testSwap = await TestSwap.deploy(\n uniswapRouter\n );\n await testSwap.deployed();\n\n console.log((await wmaticContract.balanceOf(signer._address)).toString());\n console.log((await wethContract.balanceOf(signer._address)).toString());\n\n console.log((await wmaticContract.balanceOf(testSwap.address)).toString());\n console.log((await wethContract.balanceOf(testSwap.address)).toString());\n\n const amountApprove = ethers.utils.parseEther('1'); \n const amount = ethers.utils.parseEther('0.5');\n\n const GAS_PARAMS = {\n gasLimit: \"1250000\",//exagerate amount of gas, must be adjusted\n gasPrice: ethers.utils.parseUnits('100','gwei').toString(),\n };\n const txApproveWMatic = await wmaticContract.connect(signer).approve(\n testSwap.address, \n amountApprove, \n GAS_PARAMS);\n await txApproveWMatic.wait();\n\n const tx = await testSwap.connect(signer).swapUniswap(\n wmatic,\n weth,\n amount,\n fee1, \n GAS_PARAMS\n );\n\n console.log(tx);\n const txResponse = await tx.wait();\n console.log(txResponse);\n\n console.log((await wmaticContract.balanceOf(signer._address)).toString());\n console.log((await wethContract.balanceOf(signer._address)).toString());\n console.log((await wmaticContract.balanceOf(testSwap.address)).toString());\n console.log((await wethContract.balanceOf(testSwap.address)).toString());\n}\n\nmain();\n\n $ npx hardhat run scripts/deploy-test.js\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74560780",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20400773/"
] |
74,560,806
|
<p>I have a custom object:</p>
<pre><code>data class MoneyTransaction(
val amount: Double,
val category: String
)
</code></pre>
<p>I have a list of <code>MoneyTransaction</code>. I want to create a map out of that list where keys are categories, and the values are the total amount according to the category. Kotlin has functions like <code>groupBy</code>, <code>groupByTo</code>, <code>groupingBy</code>. But there is no tutorial or documentation about those, so I can't figure it out. So far I got this:</p>
<pre><code> val map = transactionList.groupBy({it.category},{it.amount})
</code></pre>
<p>But this doesn't give the total amount, just separate amounts on each category</p>
<p>Any help would be much appreciated.</p>
|
[
{
"answer_id": 74561012,
"author": "Markus Heider",
"author_id": 866904,
"author_profile": "https://Stackoverflow.com/users/866904",
"pm_score": 3,
"selected": true,
"text": "transactionList.groupBy { it.category }\n Map<String, List<MoneyTransaction>> transactionList.groupBy { it.category }\n .mapValues { (_, transactionsInCategory) -> \n transactionsInCategory.sumOf { it.amount }\n }\n Map<String, Double>"
},
{
"answer_id": 74561177,
"author": "Sweeper",
"author_id": 5133585,
"author_profile": "https://Stackoverflow.com/users/5133585",
"pm_score": 1,
"selected": false,
"text": "groupingBy fold transactions.groupingBy(MoneyTransaction::category)\n .fold(0.0) { acc, next -> acc + next.amount }\n groupingBy Grouping<MoneyTransaction, String> fold groupingBy Grouping"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74560806",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12431078/"
] |
74,560,820
|
<p>I need an advice how to center text on line vertically. I have basically a data grid that can have rows and cells and within the cell you can put text on multiple lines which have fixed height of 34px. So I need to center text on its own line, but not within the row because then if on the same row you had one cell which has 2 line and the other has just one line the latter one would be centered in the middle of 64px.</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>.container {
width: 100%;
border: 1px solid black;
display: flex;
flex-wrap: wrap;
}
.text {
height: 34px;
border: 1px solid red
}
.cell {
padding: 3px;
border: 1px solid black;
}
.line1 {
display: flex;
width: 100%;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
<div class="line1">
<div class="cell">
<div class="text">
Text 1
</div>
<div class="text">
Text 2
</div>
</div>
<div class="cell">
<div class="text">
Text 2
</div>
</div>
</div>
</div></code></pre>
</div>
</div>
</p>
<p><a href="https://jsfiddle.net/ve4qauz0/34/" rel="nofollow noreferrer">https://jsfiddle.net/ve4qauz0/34/</a></p>
|
[
{
"answer_id": 74560878,
"author": "Coopero",
"author_id": 2421346,
"author_profile": "https://Stackoverflow.com/users/2421346",
"pm_score": 2,
"selected": false,
"text": ".text{\n display:flex;\n align-items: center;\n}\n"
},
{
"answer_id": 74560912,
"author": "Abhishek Kokate",
"author_id": 17349359,
"author_profile": "https://Stackoverflow.com/users/17349359",
"pm_score": 2,
"selected": true,
"text": "height line-height .text line-height: 34px; .container {\n width: 100%;\n border: 1px solid black;\n display: flex;\n flex-wrap: wrap;\n}\n\n.text {\n height: 34px;\n border: 1px solid red;\n line-height: 34px;\n}\n\n.cell {\n padding: 3px;\n border: 1px solid black;\n}\n\n.line1 {\n display: flex;\n width: 100%;\n} <div class=\"container\">\n <div class=\"line1\">\n <div class=\"cell\">\n <div class=\"text\">\n Text 1\n </div>\n <div class=\"text\">\n Text 2\n </div>\n </div>\n <div class=\"cell\">\n <div class=\"text\">\n Text 2\n </div>\n </div>\n </div>\n</div>"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74560820",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8336738/"
] |
74,560,829
|
<p>I have a given text string:
text = """Alice has two apples and bananas. Apples are very healty."""</p>
<p>and a dataframe:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>word</th>
</tr>
</thead>
<tbody>
<tr>
<td>apples</td>
</tr>
<tr>
<td>bananas</td>
</tr>
<tr>
<td>company</td>
</tr>
</tbody>
</table>
</div>
<p>I would like to add a column "frequency" which will count occurrences of each word in column "word" in the text.</p>
<p>So the output should be as below:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>word</th>
<th>frequency</th>
</tr>
</thead>
<tbody>
<tr>
<td>apples</td>
<td>2</td>
</tr>
<tr>
<td>bananas</td>
<td>1</td>
</tr>
<tr>
<td>company</td>
<td>0</td>
</tr>
</tbody>
</table>
</div>
|
[
{
"answer_id": 74560878,
"author": "Coopero",
"author_id": 2421346,
"author_profile": "https://Stackoverflow.com/users/2421346",
"pm_score": 2,
"selected": false,
"text": ".text{\n display:flex;\n align-items: center;\n}\n"
},
{
"answer_id": 74560912,
"author": "Abhishek Kokate",
"author_id": 17349359,
"author_profile": "https://Stackoverflow.com/users/17349359",
"pm_score": 2,
"selected": true,
"text": "height line-height .text line-height: 34px; .container {\n width: 100%;\n border: 1px solid black;\n display: flex;\n flex-wrap: wrap;\n}\n\n.text {\n height: 34px;\n border: 1px solid red;\n line-height: 34px;\n}\n\n.cell {\n padding: 3px;\n border: 1px solid black;\n}\n\n.line1 {\n display: flex;\n width: 100%;\n} <div class=\"container\">\n <div class=\"line1\">\n <div class=\"cell\">\n <div class=\"text\">\n Text 1\n </div>\n <div class=\"text\">\n Text 2\n </div>\n </div>\n <div class=\"cell\">\n <div class=\"text\">\n Text 2\n </div>\n </div>\n </div>\n</div>"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74560829",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17277677/"
] |
74,560,838
|
<p>I'm trying to get profiles from database using EntityFramework.</p>
<p>But every time I am getting the following error:</p>
<p>The operation cannot be completed because the DbContext has been disposed.</p>
<p>My code :</p>
<pre><code>private readonly IDbContextDMO _globalContext;
</code></pre>
<pre><code>using (IProfilService profilService = _profilService ?? new ProfilService(Settings, _globalContext))
{
//doing something here
}
</code></pre>
<pre><code>var r_GetHigherProfileAsync = await _profilService.GetHigherProfileByIntervenantIdAsync();
</code></pre>
<p>I can't understand why I am getting this error. Can anyone help me please?</p>
|
[
{
"answer_id": 74561068,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 1,
"selected": false,
"text": "using ProfilService Dispose() _globalContext ProfilService ProfilService _profilService var profilService = _profilService;\nbool disposeSvc = false;\ntry {\n if (profilService is null)\n { // temporary just for this call\n profilService = new ProfilService(Settings, _globalContext);\n disposeSvc = true;\n }\n //doing something here\n} finally {\n if (disposeSvc) profilService?.Dispose();\n}\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74560838",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18838653/"
] |
74,560,842
|
<p>Hi all I have the following <a href="https://codesandbox.io/s/jolly-lederberg-qf8hym" rel="nofollow noreferrer">code</a></p>
<p>the data that I want to transform.</p>
<pre><code> const obj = {
numbers: {
label: "main numbers",
pageTitle: "Numbers",
key: "1",
items: {
firstNumber: {
label: "first number",
pageTitle: "first",
key: "first"
},
secondNumber: {
label: "second number",
pageTitle: "second",
key: "second"
}
}
},
letters: {
label: "main Letters",
pageTitle: "Letters",
key: "2",
items: {
firstLetter: {
label: "first Letter",
pageTitle: "first",
key: "first"
}
}
},
signs: {
label: "main sign",
pageTitle: "Sign",
key: "3"
}
};
</code></pre>
<p>In my <code>obj</code> variable I have 3 other objects</p>
<p><code>numbers</code> object which has <code>items</code> property which includes 2 other objects.</p>
<p><code>letters</code> object which has <code>items</code> property which includes only one object.</p>
<p><code>signs</code> object.</p>
<p>I need to transform my <code>obj</code> to the following way.</p>
<pre><code> [
{
label:"main numbers",
pageTitle:"Numbers",
key:1,
children: [{label,pageTitle,key},{label,pageTitle,key}]
},
{
label:"main Letters",
pageTitle:"Letters",
key:1,
children: [{label,pageTitle,key}]
},
{
label:"main sign",
pageTitle:"Sign",
key:1,
children: []
},
]
</code></pre>
<p>for that transformation, I wrote the following code.</p>
<pre><code> const transformedData = Object.values(obj).map((menuitem) => menuitem);
const data = [];
transformedData?.map((x) => {
const newData = {};
newData.label = x.label;
newData.pageTitle = x.pageTitle;
newData.key = x.key;
newData.children = x?.Object?.values(items)?.map((el) => {
newData.children.label = el.label;
newData.children.pageTitle = el.pageTitle;
newData.children.key = el.key;
});
data.push(newData);
});
</code></pre>
<p>Everything was working, but for <code>children</code> instead of printing an array it prints <code>undefined</code>.</p>
<p>Please help me to resolve this issue.</p>
|
[
{
"answer_id": 74560924,
"author": "MoxxiManagarm",
"author_id": 11011793,
"author_profile": "https://Stackoverflow.com/users/11011793",
"pm_score": 1,
"selected": false,
"text": "x Objects newData.children = Object.values(x.items)?.map(/*...*/);\n"
},
{
"answer_id": 74562325,
"author": "Marios",
"author_id": 20229075,
"author_profile": "https://Stackoverflow.com/users/20229075",
"pm_score": 1,
"selected": false,
"text": "const transformedData = Object.values(obj).map((menuitem) => menuitem);\n\nconst data = [];\n\ntransformedData?.map((x) => {\n const newData = {};\n newData.label = x.label;\n newData.pageTitle = x.pageTitle;\n newData.key = x.key;\n if(x.hasOwnProperty('items')){\n newData.children = Object.values(x.items).map((el) => {\n const obj={\n label:el.label,\n pageTitle:el.pageTitle,\n key:el.key\n }\n return obj\n })};\n data.push(newData);\n});\n\nconsole.log(data)\n undefined newData.children newData.children.label newData.children obj items"
},
{
"answer_id": 74572072,
"author": "Vardan Hambardzumyan",
"author_id": 13082654,
"author_profile": "https://Stackoverflow.com/users/13082654",
"pm_score": 3,
"selected": true,
"text": " const convert = data =>\n Object.values(data)?.map(x => ({\n label: x.label,\n pageTitle :x.pageTitle ,\n key: x.pathname,\n children: x.items\n ? Object.values(x.items || {}).map(el => ({ label: el.label, \n key:el.pathname,pageTitle:el.pageTitle }))\n : null,\n }));\n const items = convert(obj)"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74560842",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13859363/"
] |
74,560,862
|
<p>Its asked to create a table to maintain details by using a stored procedure. Do I need to use a procedure to create the table or do I need to use a procedure to insert values?</p>
<blockquote>
<ol>
<li><p>Create a table to maintain company details by using a stored procedure
by passing company id and name as input parameters.</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Company ID</th>
<th>Name</th>
</tr>
</thead>
<tbody>
<tr>
<td>COMP_A</td>
<td>Company A</td>
</tr>
<tr>
<td>COMP_B</td>
<td>Company B</td>
</tr>
</tbody>
</table>
</div></li>
</ol>
</blockquote>
|
[
{
"answer_id": 74560924,
"author": "MoxxiManagarm",
"author_id": 11011793,
"author_profile": "https://Stackoverflow.com/users/11011793",
"pm_score": 1,
"selected": false,
"text": "x Objects newData.children = Object.values(x.items)?.map(/*...*/);\n"
},
{
"answer_id": 74562325,
"author": "Marios",
"author_id": 20229075,
"author_profile": "https://Stackoverflow.com/users/20229075",
"pm_score": 1,
"selected": false,
"text": "const transformedData = Object.values(obj).map((menuitem) => menuitem);\n\nconst data = [];\n\ntransformedData?.map((x) => {\n const newData = {};\n newData.label = x.label;\n newData.pageTitle = x.pageTitle;\n newData.key = x.key;\n if(x.hasOwnProperty('items')){\n newData.children = Object.values(x.items).map((el) => {\n const obj={\n label:el.label,\n pageTitle:el.pageTitle,\n key:el.key\n }\n return obj\n })};\n data.push(newData);\n});\n\nconsole.log(data)\n undefined newData.children newData.children.label newData.children obj items"
},
{
"answer_id": 74572072,
"author": "Vardan Hambardzumyan",
"author_id": 13082654,
"author_profile": "https://Stackoverflow.com/users/13082654",
"pm_score": 3,
"selected": true,
"text": " const convert = data =>\n Object.values(data)?.map(x => ({\n label: x.label,\n pageTitle :x.pageTitle ,\n key: x.pathname,\n children: x.items\n ? Object.values(x.items || {}).map(el => ({ label: el.label, \n key:el.pathname,pageTitle:el.pageTitle }))\n : null,\n }));\n const items = convert(obj)"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74560862",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12864747/"
] |
74,560,953
|
<p>I have tried to create a registration for with DB using ajax and PHP but the results is not what I am looking for. It always return the 201 status code.</p>
<p>here's the code I have</p>
<pre><code> <script>
$(document).ready(function() {
$('#butregister').on('click', function() {
$("#butregister").attr("disabled", "disabled");
var fullname = $('#fullname').val();
var username = $('#username').val();
var password = $('#password').val();
var mobilenumber = $('#mobilenumber').val();
if(fullname!="" && username!="" && mobilenumber!="" && password !=""){
$.ajax({
url: "includes/save",
datatype: "JSON",
type: "POST",
data: {
type: 1,
fullname: fullname,
username: username,
password: password,
mobilenumber: mobilenumber
},
cache: false,
success: function(dataResult){
var dataResult = JSON.parse(dataResult);
if(dataResult.statusCode==200){
$("#butregister").removeAttr("disabled");
$('#register_form').find('input:text').val('');
$("#success").show();
$('#success').html('Registration successful !');
}
else if(dataResult.statusCode==201){
$("#error").show();
$('#error').html('Username already exists !');
}
}
});
}
else{
alert('Please fill all the field !');
}
});
});
</script>
</code></pre>
<p>here's the code for the php I created</p>
<pre><code><?php
include 'connect.php';
session_start();
if($_POST['type']==1){
$fullname=$_POST['fullname'];
$username=$_POST['username'];
$password=$_POST['password'];
$mobilenumber=$_POST['mobilenumber'];
$md5password=md5($password);
$datetime = new DateTime();
$timezone = new DateTimeZone('Asia/Manila');
$datetime->setTimezone($timezone);
$dateregistered = $datetime->format('m/d/Y g:i A');
$duplicate=mysqli_query($conn,"select * from userlists where username='$username'");
if (mysqli_num_rows($duplicate)<0)
{
$sql = "INSERT INTO `userlists`( `realname`, `contactnumber`, `username`, `md5password`, `dateregistered`)
VALUES ('$fullname','$mobilenumber','$username','$md5password','$dateregistered')";
if (mysqli_query($conn, $sql)) {
echo json_encode(array("statusCode"=>200));
}
}
else{
echo json_encode(array("statusCode"=>201));
}
mysqli_close($conn);
}
</code></pre>
<p>now, after I run it, it result is always the statusCode=>201</p>
<p>is there anything I can do in this one? thanks</p>
|
[
{
"answer_id": 74561117,
"author": "vipin",
"author_id": 4902567,
"author_profile": "https://Stackoverflow.com/users/4902567",
"pm_score": -1,
"selected": false,
"text": "if (mysqli_num_rows($duplicate) > 0) {\n"
},
{
"answer_id": 74562367,
"author": "Searle",
"author_id": 7993773,
"author_profile": "https://Stackoverflow.com/users/7993773",
"pm_score": -1,
"selected": false,
"text": "if (mysqli_num_rows($duplicate)==0)\n {\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74560953",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20590785/"
] |
74,560,977
|
<p>My question is <em>similar</em> to <a href="https://stackoverflow.com/questions/37573155/showing-different-axis-labels-using-ggplot2-with-facet-wrap">this question</a> but differs in an important aspect. I want to use different labelling functions created with the <code>{scales}</code> package for the <em>tick mark</em> labels (not the axis labels). Here's a reproducible example:</p>
<pre><code>library(ggplot2)
library(scales)
mill <- number_format(scale = 1/1000000, suffix = " M")
thou <- number_format(scale = 1/1000, suffix = " k")
df <- data.frame(cond = rep(c("A", "B", "C"), each = 5),
x_unit = rep(1:5, 3),
y_unit = round(c(rnorm(5, 5e6, 10000),
rnorm(5, 5e6, 10000),
rnorm(5, 5000, 1000))))
ggplot(df, aes(x = x_unit, y = y_unit)) +
geom_line() +
scale_y_continuous(labels = mill) +
facet_wrap(~ cond, scales = "free_y")
</code></pre>
<p><a href="https://i.stack.imgur.com/inRea.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/inRea.png" alt="Example Output" /></a></p>
<p>You might already see where I'm going with this: For facet C, I want to use the labelling function <code>thou</code> and not <code>mill</code>. How would I do that? I'm pretty sure that the solution with the <code>labeller</code> argument in <code>facet_wrap()</code> from the question I linked above does not apply here, right?</p>
|
[
{
"answer_id": 74561040,
"author": "teunbrand",
"author_id": 11374827,
"author_profile": "https://Stackoverflow.com/users/11374827",
"pm_score": 3,
"selected": true,
"text": "ggh4x::scale_y_facet() cond == \"C\" library(ggplot2)\nlibrary(scales)\n\nmill <- number_format(scale = 1/1000000, suffix = \" M\")\nthou <- number_format(scale = 1/1000, suffix = \" k\")\n\ndf <- data.frame(cond = rep(c(\"A\", \"B\", \"C\"), each = 5),\n x_unit = rep(1:5, 3),\n y_unit = round(c(rnorm(5, 5e6, 10000),\n rnorm(5, 5e6, 10000),\n rnorm(5, 5000, 1000))))\n\nggplot(df, aes(x = x_unit, y = y_unit)) +\n geom_line() +\n scale_y_continuous(labels = mill) +\n facet_wrap(~ cond, scales = \"free_y\") +\n ggh4x::scale_y_facet(cond == \"C\", labels = thou)\n"
},
{
"answer_id": 74589416,
"author": "Robert Lew",
"author_id": 5838847,
"author_profile": "https://Stackoverflow.com/users/5838847",
"pm_score": 1,
"selected": false,
"text": "cut_long_scale() scale_cut library(ggplot2)\nlibrary(scales)\n\ndf <- data.frame(cond = rep(c(\"A\", \"B\", \"C\"), each = 5),\n x_unit = rep(1:5, 3),\n y_unit = round(c(rnorm(5, 5e6, 10000),\n rnorm(5, 5e6, 10000),\n rnorm(5, 5000, 1000))))\n\nggplot(df, aes(x = x_unit, y = y_unit)) +\n geom_line() +\n scale_y_continuous(labels = number_format(scale_cut = cut_long_scale())) +\n facet_wrap(~ cond, scales = \"free_y\")\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74560977",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2433233/"
] |
74,560,979
|
<p>I have a dataframe dfsorted :</p>
<pre class="lang-py prettyprint-override"><code>dfsorted = df.sort_values(["sku"], ascending=[True])
print(dfsorted.head())
</code></pre>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>id</th>
<th>sku</th>
<th>bill</th>
<th>qty_left</th>
</tr>
</thead>
<tbody>
<tr>
<td>186</td>
<td>01-04</td>
<td>50469</td>
<td>0</td>
</tr>
<tr>
<td>16</td>
<td>01-20</td>
<td>50262</td>
<td>15</td>
</tr>
<tr>
<td>267</td>
<td>01-20</td>
<td>50460</td>
<td>1</td>
</tr>
<tr>
<td>18</td>
<td>01-20</td>
<td>50262</td>
<td>5</td>
</tr>
<tr>
<td>17</td>
<td>01-20</td>
<td>50262</td>
<td>5</td>
</tr>
</tbody>
</table>
</div>
<p>How can I group / aggregate the dfsorted into this desired result:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>sku</th>
<th>bill</th>
<th>qty_left</th>
</tr>
</thead>
<tbody>
<tr>
<td>01-04</td>
<td>50469</td>
<td>0</td>
</tr>
<tr>
<td>01-20</td>
<td>50262, 50460</td>
<td>26</td>
</tr>
</tbody>
</table>
</div>
<p>So :</p>
<ul>
<li>group the dataframe by 'sku'</li>
<li>for each 'sku', concatenate the 'bill' values (these are already formatted as strings, I don't care if there are duplicates but unique values would be nice too)</li>
<li>for each 'sku', sum the 'qty_left' values.</li>
</ul>
<p>Thanks!</p>
|
[
{
"answer_id": 74561112,
"author": "Paul",
"author_id": 7194474,
"author_profile": "https://Stackoverflow.com/users/7194474",
"pm_score": 3,
"selected": true,
"text": "agg lambda sum df.groupby('sku').agg({'bill': lambda x: set(x), 'qty_left':'sum'})\n set list bill qty_left\nsku \n01-04 {50469} 0\n01-20 {50460, 50262} 26\n df2.bill.apply(lambda s: ', '.join(list(map(str, s))))\n df2 groupby.agg"
},
{
"answer_id": 74561356,
"author": "jezrael",
"author_id": 2901002,
"author_profile": "https://Stackoverflow.com/users/2901002",
"pm_score": 1,
"selected": false,
"text": "GroupBy.agg df1 = (df.groupby('sku', as_index=False)\n .agg({'bill': lambda x:','.join(dict.fromkeys(x)), \n 'qty_left':'sum'}))\nprint (df1)\n sku bill qty_left\n0 01-04 50469 0\n1 01-20 50262,50460 26\n bfill df1 = (df.astype({'bill':str})\n .groupby('sku', as_index=False)\n .agg({'bill': lambda x:','.join(dict.fromkeys(x)), \n 'qty_left':'sum'}))\nprint (df1)\n sku bill qty_left\n0 01-04 50469 0\n1 01-20 50262,50460 26\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74560979",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1692094/"
] |
74,561,014
|
<p>I am developing an upload api using Go.
I can upload one file at a time via postman with body >> form-data
but I can't upload more than 1 file, any solution?
code:</p>
<pre><code>package main
import (
"fmt"
"mime/multipart"
"net/http"
"path/filepath"
"github.com/gin-gonic/gin"
)
type BindFile struct {
Name string `form:"name" binding:"required"`
Email string `form:"email" binding:"required"`
File *multipart.FileHeader `form:"file" binding:"required"`
}
func main() {
router := gin.Default()
router.POST("/upload", func(c *gin.Context) {
var bindFile BindFile
c.ShouldBind(&bindFile)
file := bindFile.File
dst := filepath.Base(file.Filename)
c.SaveUploadedFile(file, dst)
c.String(http.StatusOK, fmt.Sprintf("arquivo %s upado com sucesso", file.Filename))
})
router.Run(":8080")
}
</code></pre>
<p>I tried to put a file array in my form-data: file[] but it didn't work</p>
|
[
{
"answer_id": 74561386,
"author": "vageeshabr",
"author_id": 3413403,
"author_profile": "https://Stackoverflow.com/users/3413403",
"pm_score": 0,
"selected": false,
"text": "package main\n\nimport (\n \"github.com/gin-gonic/gin\"\n \"log\"\n \"mime/multipart\"\n)\n\ntype BindFile struct {\n Name string `form:\"name\" binding:\"required\"`\n Email string `form:\"email\" binding:\"required\"`\n Files []*multipart.FileHeader `form:\"file\" binding:\"required\"`\n}\n\nfunc main() {\n router := gin.Default()\n\n router.POST(\"/upload\", func(c *gin.Context) {\n var bindFile BindFile\n\n c.ShouldBind(&bindFile)\n for _, f := range bindFile.Files {\n log.Println(f.Filename)\n }\n })\n\n router.Run(\":3000\")\n}\n"
},
{
"answer_id": 74563305,
"author": "Guilherme Rodrigues",
"author_id": 19896535,
"author_profile": "https://Stackoverflow.com/users/19896535",
"pm_score": 2,
"selected": false,
"text": "package main\n\nimport (\n \"net/http\"\n \"path/filepath\"\n\n \"github.com/gin-gonic/gin\"\n)\n\nfunc main() {\n router := gin.Default()\n\n router.Static(\"/\", \".public\")\n router.POST(\"/\", func(c *gin.Context) {\n\n form, _ := c.MultipartForm()\n\n files := form.File[\"files\"]\n\n for _, file := range files {\n filename := filepath.Base(file.Filename)\n if err := c.SaveUploadedFile(file, filename); err != nil {\n c.String(http.StatusBadRequest, \"erro ao carregar arquivo\")\n }\n }\n c.String(http.StatusOK, \"upload realizado, %d files \", len(files))\n })\n router.Run(\":8080\")\n}"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74561014",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19896535/"
] |
74,561,023
|
<p>Suppose I am trying to filter out based on <code>gpus</code>'s field/property. Which is a collection of <code>device</code> namespace.</p>
<p>I have a query, which gives results: (so i believe it's syntactically and semantically correct)</p>
<p><code>devices | where gpus != null | list gpus</code></p>
<p>and get results like:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>gpus</th>
</tr>
</thead>
<tbody>
<tr>
<td>Nvidia xyz</td>
</tr>
<tr>
<td>GeForce abc; ASUS GTx</td>
</tr>
</tbody>
</table>
</div>
<p>But none of the query gives a result:, why?</p>
<p><code>devices | where gpus == "*Nvidia*" | list gpus</code> or</p>
<p><code>devices | where gpus == "Nvidia xyz" | list gpus</code></p>
|
[
{
"answer_id": 74561386,
"author": "vageeshabr",
"author_id": 3413403,
"author_profile": "https://Stackoverflow.com/users/3413403",
"pm_score": 0,
"selected": false,
"text": "package main\n\nimport (\n \"github.com/gin-gonic/gin\"\n \"log\"\n \"mime/multipart\"\n)\n\ntype BindFile struct {\n Name string `form:\"name\" binding:\"required\"`\n Email string `form:\"email\" binding:\"required\"`\n Files []*multipart.FileHeader `form:\"file\" binding:\"required\"`\n}\n\nfunc main() {\n router := gin.Default()\n\n router.POST(\"/upload\", func(c *gin.Context) {\n var bindFile BindFile\n\n c.ShouldBind(&bindFile)\n for _, f := range bindFile.Files {\n log.Println(f.Filename)\n }\n })\n\n router.Run(\":3000\")\n}\n"
},
{
"answer_id": 74563305,
"author": "Guilherme Rodrigues",
"author_id": 19896535,
"author_profile": "https://Stackoverflow.com/users/19896535",
"pm_score": 2,
"selected": false,
"text": "package main\n\nimport (\n \"net/http\"\n \"path/filepath\"\n\n \"github.com/gin-gonic/gin\"\n)\n\nfunc main() {\n router := gin.Default()\n\n router.Static(\"/\", \".public\")\n router.POST(\"/\", func(c *gin.Context) {\n\n form, _ := c.MultipartForm()\n\n files := form.File[\"files\"]\n\n for _, file := range files {\n filename := filepath.Base(file.Filename)\n if err := c.SaveUploadedFile(file, filename); err != nil {\n c.String(http.StatusBadRequest, \"erro ao carregar arquivo\")\n }\n }\n c.String(http.StatusOK, \"upload realizado, %d files \", len(files))\n })\n router.Run(\":8080\")\n}"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74561023",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1327585/"
] |
74,561,024
|
<p>I am developing a recording app in React Native. For that, I use <a href="https://www.npmjs.com/package/expo-av" rel="nofollow noreferrer">expo-av</a>. I've noticed recently that on Android 12 when a user picks up a call, the app keeps recording but when listening to it later, there is silence while the user was on the phone, but also after he hung up till the end of the recording. On older versions of Android, there is silence while the user was on a call, but it starts capturing audio again when he hangs up. Any idea how to fix that it keeps capturing audio after the user hangs up?</p>
<p>I am on expo 45, btw.</p>
|
[
{
"answer_id": 74561386,
"author": "vageeshabr",
"author_id": 3413403,
"author_profile": "https://Stackoverflow.com/users/3413403",
"pm_score": 0,
"selected": false,
"text": "package main\n\nimport (\n \"github.com/gin-gonic/gin\"\n \"log\"\n \"mime/multipart\"\n)\n\ntype BindFile struct {\n Name string `form:\"name\" binding:\"required\"`\n Email string `form:\"email\" binding:\"required\"`\n Files []*multipart.FileHeader `form:\"file\" binding:\"required\"`\n}\n\nfunc main() {\n router := gin.Default()\n\n router.POST(\"/upload\", func(c *gin.Context) {\n var bindFile BindFile\n\n c.ShouldBind(&bindFile)\n for _, f := range bindFile.Files {\n log.Println(f.Filename)\n }\n })\n\n router.Run(\":3000\")\n}\n"
},
{
"answer_id": 74563305,
"author": "Guilherme Rodrigues",
"author_id": 19896535,
"author_profile": "https://Stackoverflow.com/users/19896535",
"pm_score": 2,
"selected": false,
"text": "package main\n\nimport (\n \"net/http\"\n \"path/filepath\"\n\n \"github.com/gin-gonic/gin\"\n)\n\nfunc main() {\n router := gin.Default()\n\n router.Static(\"/\", \".public\")\n router.POST(\"/\", func(c *gin.Context) {\n\n form, _ := c.MultipartForm()\n\n files := form.File[\"files\"]\n\n for _, file := range files {\n filename := filepath.Base(file.Filename)\n if err := c.SaveUploadedFile(file, filename); err != nil {\n c.String(http.StatusBadRequest, \"erro ao carregar arquivo\")\n }\n }\n c.String(http.StatusOK, \"upload realizado, %d files \", len(files))\n })\n router.Run(\":8080\")\n}"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74561024",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6470918/"
] |
74,561,027
|
<p>On OS X I can check which version of homebrew I have installed with <code>brew -v</code>. Is there a way to check what the latest version available for installation is?</p>
|
[
{
"answer_id": 74561467,
"author": "Andre Wildberg",
"author_id": 9462095,
"author_profile": "https://Stackoverflow.com/users/9462095",
"pm_score": 1,
"selected": false,
"text": "$ curl -s \"https://github.com/Homebrew/brew/releases\" | \n awk '/true\" class=\"Link--primary\"/{gsub(/<\\/a.*|.*\">/, \"\", $NF); print $NF}' | \n head -1\n3.6.12\n $ curl -s \"https://github.com/Homebrew/brew/releases\" | \n awk '/relative-time.*prefix=\"\" datetime/{sub(/T/, \" \", $NF)\n gsub(/.*e=\"|\">/, \"\", $NF); date = $NF}\n /true\" class=\"Link--primary\"/{gsub(/<\\/a.*|.*\">/, \"\", $NF)\n print $NF\"\\t\"date}'\n3.6.12 2022-11-21 14:24:13Z\n3.6.11 2022-11-14 14:35:38Z\n3.6.10 2022-11-09 17:03:46Z\n3.6.9 2022-11-07 14:22:45Z\n3.6.8 2022-11-01 12:20:01Z\n3.6.7 2022-10-24 12:27:21Z\n3.6.6 2022-10-17 13:29:39Z\n3.6.5 2022-10-10 11:37:32Z\n3.6.4 2022-10-03 09:09:57Z\n3.6.3 2022-09-26 13:06:10Z\n"
},
{
"answer_id": 74633880,
"author": "chenrui",
"author_id": 791609,
"author_profile": "https://Stackoverflow.com/users/791609",
"pm_score": 0,
"selected": false,
"text": "brew update brew $ brew update --help\nUsage: brew update [options]\n\nFetch the newest version of Homebrew and all formulae from GitHub using git(1)\nand perform any necessary migrations.\n\n --merge Use git merge to apply updates (rather than\n git rebase).\n --auto-update Run on auto-updates (e.g. before brew\n install). Skips some slower steps.\n -f, --force Always do a slower, full update check (even\n if unnecessary).\n -q, --quiet Make some output more quiet\n -v, --verbose Print the directories checked and git\n operations performed.\n -d, --debug Display a trace of all shell commands as they\n are executed.\n -h, --help Show this message.\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74561027",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10864356/"
] |
74,561,039
|
<p>I got a little question.</p>
<p>I would like to select N rows from 5 id.</p>
<p>I already tried this request :</p>
<pre><code>SELECT a.fk_produit_id, a.id, a.titre, a.prix, a.description, a.short_description, a.image_url
from produits p, articles a
WHERE p.id = a.fk_produit_id AND p.fk_category_id IN (2, 248, 335, 493, 1038)
GROUP BY p.fk_category_id;
</code></pre>
<p>Or this one :</p>
<pre><code>SELECT a.fk_produit_id, a.id, a.titre, a.prix
from articles a
inner join produits p
WHERE p.id = a.fk_produit_id AND p.fk_category_id IN (2, 248, 335, 493, 1038)
order by a.fk_produit_id limit 5
</code></pre>
<p>I would like that the result be like this :</p>
<pre><code>id: 1 : -> record 1
-> record 1
-> record 1
-> record 1
-> record 1
id: 2 : -> record 2
-> record 2
-> record 2
-> record 2
-> record 2
id: 3 : -> record 3
-> record 3
-> record 3
-> record 3
-> record 3
id: 4 : -> record 4
-> record 4
-> record 4
-> record 4
-> record 4
id: 5 : -> record 5
-> record 5
-> record 5
-> record 5
-> record 5
</code></pre>
<p>But they didn't work as i want.
If someone coul help me or explain how can I solve it.
Thanks you in advance guys I continue my research by my side.</p>
|
[
{
"answer_id": 74561193,
"author": "GarethD",
"author_id": 1048425,
"author_profile": "https://Stackoverflow.com/users/1048425",
"pm_score": 2,
"selected": true,
"text": "ROW_NUMBER() SELECT a.fk_produit_id, \n a.id, \n a.titre, \n a.prix, \n a.description, \n a.short_description, \n a.image_url\nFROM ( SELECT a.fk_produit_id, \n a.id, \n a.titre, \n a.prix, \n a.description, \n a.short_description, \n a.image_url,\n ROW_NUMBER() OVER(PARTITION BY p.fk_category_id \n ORDER BY a.fk_produit_id) AS RowNumber\n FROM produits AS p\n INNER JOIN articles AS a\n ON p.id = a.fk_produit_id\n WHERE p.fk_category_id IN (2, 248, 335, 493, 1038)\n \n ) AS a\nWHERE a.RowNumber <= 5; -- Change 5 to whatever \"n\" is\n"
},
{
"answer_id": 74562255,
"author": "jarlh",
"author_id": 3706016,
"author_profile": "https://Stackoverflow.com/users/3706016",
"pm_score": 0,
"selected": false,
"text": "SELECT p.*, a.fk_produit_id, a.id, a.titre, a.prix \nfrom produits p\ncross join\n lateral (select * from articles\n WHERE p.id = fk_produit_id\n order by fk_produit_id\n limit 5) a\nwhere p.fk_category_id IN (2, 248, 335, 493, 1038) \n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74561039",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17190769/"
] |
74,561,070
|
<p>I'm writing a simple program that takes user input and prints the number of even, odd and zeros.</p>
<p>The program doesn't yield any errors but it seems to skip line 5 and 15
I want to count and display the zeroes in the <code>numbers</code> list</p>
<pre><code>numbers = input("Numbers seperated by space:").split()
print("Numbers:" + str(numbers))
zero = numbers.count(0)
even = 0
odd = 0
for i in numbers:
if int(i) % 2 == 0:
even += 1
else:
odd += 1
even = even - zero
print("Even:" + str(even))
print("Odd:" + str(odd))
print("Zero:" + str(zero))
</code></pre>
|
[
{
"answer_id": 74561193,
"author": "GarethD",
"author_id": 1048425,
"author_profile": "https://Stackoverflow.com/users/1048425",
"pm_score": 2,
"selected": true,
"text": "ROW_NUMBER() SELECT a.fk_produit_id, \n a.id, \n a.titre, \n a.prix, \n a.description, \n a.short_description, \n a.image_url\nFROM ( SELECT a.fk_produit_id, \n a.id, \n a.titre, \n a.prix, \n a.description, \n a.short_description, \n a.image_url,\n ROW_NUMBER() OVER(PARTITION BY p.fk_category_id \n ORDER BY a.fk_produit_id) AS RowNumber\n FROM produits AS p\n INNER JOIN articles AS a\n ON p.id = a.fk_produit_id\n WHERE p.fk_category_id IN (2, 248, 335, 493, 1038)\n \n ) AS a\nWHERE a.RowNumber <= 5; -- Change 5 to whatever \"n\" is\n"
},
{
"answer_id": 74562255,
"author": "jarlh",
"author_id": 3706016,
"author_profile": "https://Stackoverflow.com/users/3706016",
"pm_score": 0,
"selected": false,
"text": "SELECT p.*, a.fk_produit_id, a.id, a.titre, a.prix \nfrom produits p\ncross join\n lateral (select * from articles\n WHERE p.id = fk_produit_id\n order by fk_produit_id\n limit 5) a\nwhere p.fk_category_id IN (2, 248, 335, 493, 1038) \n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74561070",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20590574/"
] |
74,561,083
|
<pre><code>void find_substring(char * str_for_search_in, char * substring)
{
bool flag = false;
for (int i = 0; i < strlen(str_for_search_in) - strlen(substring); i++)
{
if (str_for_search_in.substr(i, strlen(substring)) == substring)
{
cout << i << " ";
flag = true;
break;
}
}
if (flag == false)
cout << "NONE";
}
</code></pre>
<p>I am converting my program from C++ strings to C strings and stuck on this issue in line 6</p>
<p>What's the issue here?</p>
<p>It was length.substring everywhere previously, i changed them to strlen() so they fit char *</p>
<p>I've tried changing data types somewhere but that didn't work</p>
|
[
{
"answer_id": 74561193,
"author": "GarethD",
"author_id": 1048425,
"author_profile": "https://Stackoverflow.com/users/1048425",
"pm_score": 2,
"selected": true,
"text": "ROW_NUMBER() SELECT a.fk_produit_id, \n a.id, \n a.titre, \n a.prix, \n a.description, \n a.short_description, \n a.image_url\nFROM ( SELECT a.fk_produit_id, \n a.id, \n a.titre, \n a.prix, \n a.description, \n a.short_description, \n a.image_url,\n ROW_NUMBER() OVER(PARTITION BY p.fk_category_id \n ORDER BY a.fk_produit_id) AS RowNumber\n FROM produits AS p\n INNER JOIN articles AS a\n ON p.id = a.fk_produit_id\n WHERE p.fk_category_id IN (2, 248, 335, 493, 1038)\n \n ) AS a\nWHERE a.RowNumber <= 5; -- Change 5 to whatever \"n\" is\n"
},
{
"answer_id": 74562255,
"author": "jarlh",
"author_id": 3706016,
"author_profile": "https://Stackoverflow.com/users/3706016",
"pm_score": 0,
"selected": false,
"text": "SELECT p.*, a.fk_produit_id, a.id, a.titre, a.prix \nfrom produits p\ncross join\n lateral (select * from articles\n WHERE p.id = fk_produit_id\n order by fk_produit_id\n limit 5) a\nwhere p.fk_category_id IN (2, 248, 335, 493, 1038) \n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74561083",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12987362/"
] |
74,561,088
|
<p>This is the programm I wrote:</p>
<pre><code>#include <stdio.h>
#include <assert.h>
#include <stdlib.h>
void meanVariance(double* x, int n, double* mean, double* variance);
double* scanVector(int length);
void meanVariance(double* x, int n, double* mean, double* variance){
double sum = 0;
for (int i = 0; i < n; i++){
sum += x[i];
}
*mean = sum / ((double)n);
sum = 0;
for (int i = 0; i < n; i++)
{
double sq = x[i] - *mean;
sum += sq * sq;
}
if (n != 1)
{
*variance = sum / ((double)n );
}
else
{
*variance = 1;
}
}
int main() {
double *x = malloc(sizeof(double)), mean = 0, variance = 0;
int n = 0;
do {
n++;
x = realloc(x, sizeof(double) * (n));
printf("Type in the %d- Number
: ", n);
scanf("%lf", (x+(n-1)));
meanVariance(x, n, &mean, &variance);
printf("Mittelwert: %f\n", mean);
printf("Varianz: %f\n", variance);
} while(*(x+(n-1)) != 0);
free(x);
}
</code></pre>
<p>I don't unterstand why there is no & in the scanf function. The program works but I just don't unterstand why cause the & is missing. I'm guessing it has something to do with the pointer x however i'm not sure at all.</p>
|
[
{
"answer_id": 74561170,
"author": "Thomas",
"author_id": 14637,
"author_profile": "https://Stackoverflow.com/users/14637",
"pm_score": 2,
"selected": false,
"text": "& x & & x+(n-1) n-1 sizeof(double) x &x[n-1] n-1"
},
{
"answer_id": 74561197,
"author": "Lundin",
"author_id": 584518,
"author_profile": "https://Stackoverflow.com/users/584518",
"pm_score": 2,
"selected": true,
"text": "x+(n-1) [] array[i] *((array) + (i)) &x[n-1] &*( (x) + (n-1) ) & * x + (n-1) scanf(\"%lf\", &x[n-1]);"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74561088",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20581352/"
] |
74,561,096
|
<p>I'm getting this error when trying to start my Spring application. My classes are attached below but in a simplified manner.</p>
<p>The projet uses the pattern dto → service → serviceImpl → repository.</p>
<p><strong>DentistDto.java</strong></p>
<pre><code>@Data
public class DentistDto {
@NotBlank
@Size(max = 11)
private String croNumber;
@Valid
Person person;
}
</code></pre>
<p><strong>DentistModel.java</strong></p>
<pre><code>@Data
@Entity
@Table(name = "dentists")
@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id")
public class DentistModel {
@Id
@GeneratedValue(generator = "UUID")
@GenericGenerator(name = "UUID", strategy = "org.hibernate.id.UUIDGenerator")
@Column(name = "dentist_id", updatable = false, nullable = false)
@Type(type = "org.hibernate.type.UUIDCharType")
private UUID id;
@Column(nullable = false, unique = true, length = 10)
private String croNumber;
...
</code></pre>
<p><strong>DentistController.java</strong></p>
<pre><code> @CrossOrigin
@RequestMapping("/dentists")
@RestController
public class DentistController {
private final DentistService dentistService;
public DentistController(DentistService dentistService) {
this.dentistService = dentistService;
}
@PostMapping
public ResponseEntity<Object> saveDentist(@RequestBody @Valid DentistDto dentistDto) {
return dentistService.save(dentistDto);
}
@GetMapping
public ResponseEntity<Object> getAllDentists() throws NotFoundException {
return dentistService.findAll();
}
...
</code></pre>
<p><strong>DentistServiceImpl.java</strong></p>
<pre><code> @Service
public class DentistServiceImpl implements DentistService {
private final DentistRepository dentistRepository;
private final DentistMapper dentistMapper = DentistMapper.INSTANCE;
public DentistServiceImpl(DentistRepository dentistRepository) {
this.dentistRepository = dentistRepository;
}
@Override
public DentistDto findById(UUID id) throws NotFoundException {
var dentist = dentistRepository.findById(id).orElseThrow(() -> new NotFoundException());
return dentistMapper.toDto(dentist);
}
...
</code></pre>
<p><strong>DentistService.java</strong></p>
<pre><code>public interface DentistService {
DentistDto findById(UUID id) throws NotFoundException;
ResponseEntity<Object> findAll() throws NotFoundException;
ResponseEntity<Object> save(DentistDto dto);
...
</code></pre>
<p><strong>DentistRepository.java</strong></p>
<pre><code>@Repository
public interface DentistRepository extends JpaRepository<DentistModel, UUID> {
Optional<Object> findByCroNumber(String croNumber);
}
</code></pre>
<p><strong>DentistMapper.java</strong></p>
<pre><code>import org.mapstruct.Mapper;
import org.mapstruct.factory.Mappers;
@Mapper
public interface DentistMapper {
DentistMapper INSTANCE = Mappers.getMapper(DentistMapper.class);
DentistModel toModel(DentistDto dto);
DentistDto toDto(DentistModel model);
}
</code></pre>
<p><strong>Full error</strong></p>
<blockquote>
<p>24-11-2022 09:46:41.159 | 178 | [main] | INFO |
com.api.lores.LoresApplication - Starting the Lores API 24-11-2022
09:46:41.312 | 331 | [Thread-0] | DEBUG |
o.s.b.d.r.c.RestartClassLoader - Created RestartClassLoader
org.springframework.boot.devtools.restart.classloader.RestartClassLoader@4fb091b
24-11-2022 09:46:41.315 | 334 | [restartedMain] | INFO |
com.api.lores.LoresApplication - Starting the Lores API 24-11-2022
09:46:41.605 | 624 | [restartedMain] | INFO |
com.api.lores.LoresApplication - Starting LoresApplication using Java
17.0.4.1 on DESKTOP-733E7TU with PID 13984 (C:\Users\Guilherme Lopes\repos\lores\target\classes started by Guilherme Lopes in
C:\Users\Guilherme Lopes\repos\lores) 24-11-2022 09:46:41.606 | 625 |
[restartedMain] | INFO | com.api.lores.LoresApplication - No active
profile set, falling back to 1 default profile: "default" 24-11-2022
09:46:44.565 | 3584 | [restartedMain] | WARN |
o.s.b.w.s.c.AnnotationConfigServletWebServerApplicationContext -
Exception encountered during context initialization - cancelling
refresh attempt:
org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'dentistController' defined in file
[C:\Users\Guilherme
Lopes\repos\lores\target\classes\com\api\lores\controller\DentistController.class]:
Unsatisfied dependency expressed through constructor parameter 0;
nested exception is
org.springframework.beans.factory.BeanCreationException: Error
creating bean with name 'dentistServiceImpl' defined in file
[C:\Users\Guilherme
Lopes\repos\lores\target\classes\com\api\lores\service\dentist\DentistServiceImpl.class]:
Bean instantiation via constructor failed; nested exception is
org.springframework.beans.BeanInstantiationException: Failed to
instantiate [com.api.lores.service.dentist.DentistServiceImpl]:
Constructor threw exception; nested exception is
java.lang.ExceptionInInitializerError 24-11-2022 09:46:44.599 | 3618 |
[restartedMain] | ERROR | o.s.boot.SpringApplication - Application run
failed
org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'dentistController' defined in file
[C:\Users\Guilherme
Lopes\repos\lores\target\classes\com\api\lores\controller\DentistController.class]:
Unsatisfied dependency expressed through constructor parameter 0;
nested exception is
org.springframework.beans.factory.BeanCreationException: Error
creating bean with name 'dentistServiceImpl' defined in file
[C:\Users\Guilherme
Lopes\repos\lores\target\classes\com\api\lores\service\dentist\DentistServiceImpl.class]:
Bean instantiation via constructor failed; nested exception is
org.springframework.beans.BeanInstantiationException: Failed to
instantiate [com.api.lores.service.dentist.DentistServiceImpl]:
Constructor threw exception; nested exception is
java.lang.ExceptionInInitializerError at
org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:800)
at
org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:229)
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1372)
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1222)
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:582)
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:542)
at
org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:335)
at
org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234)
at
org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:333)
at
org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:208)
at
org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:955)
at
org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:918)
at
org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:583)
at
org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:147)
at
org.springframework.boot.SpringApplication.refresh(SpringApplication.java:734)
at
org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:408)
at
org.springframework.boot.SpringApplication.run(SpringApplication.java:308)
at
org.springframework.boot.SpringApplication.run(SpringApplication.java:1306)
at
org.springframework.boot.SpringApplication.run(SpringApplication.java:1295)
at com.api.lores.LoresApplication.main(LoresApplication.java:17) at
java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native
Method) at
java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77)
at
java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:568) at
org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49)
Caused by: org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'dentistServiceImpl' defined in file
[C:\Users\Guilherme
Lopes\repos\lores\target\classes\com\api\lores\service\dentist\DentistServiceImpl.class]:
Bean instantiation via constructor failed; nested exception is
org.springframework.beans.BeanInstantiationException: Failed to
instantiate [com.api.lores.service.dentist.DentistServiceImpl]:
Constructor threw exception; nested exception is
java.lang.ExceptionInInitializerError at
org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:315)
at
org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:296)
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1372)
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1222)
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:582)
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:542)
at
org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:335)
at
org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234)
at
org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:333)
at
org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:208)
at
org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:276)
at
org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1391)
at
org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1311)
at
org.springframework.beans.factory.support.ConstructorResolver.resolveAutowiredArgument(ConstructorResolver.java:887)
at
org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:791)
... 24 common frames omitted Caused by:
org.springframework.beans.BeanInstantiationException: Failed to
instantiate [com.api.lores.service.dentist.DentistServiceImpl]:
Constructor threw exception; nested exception is
java.lang.ExceptionInInitializerError at
org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:224)
at
org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:117)
at
org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:311)
... 38 common frames omitted Caused by:
java.lang.ExceptionInInitializerError: null at
com.api.lores.service.dentist.DentistServiceImpl.(DentistServiceImpl.java:23)
at
java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native
Method) at
java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:77)
at
java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at
java.base/java.lang.reflect.Constructor.newInstanceWithCaller(Constructor.java:499)
at
java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:480)
at
org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:211)
... 40 common frames omitted Caused by: java.lang.RuntimeException:
java.lang.ClassNotFoundException: Cannot find implementation for
com.api.lores.mapper.DentistMapper at
org.mapstruct.factory.Mappers.getMapper(Mappers.java:61) at
com.api.lores.mapper.DentistMapper.(DentistMapper.java:10)
... 47 common frames omitted Caused by:
java.lang.ClassNotFoundException: Cannot find implementation for
com.api.lores.mapper.DentistMapper at
org.mapstruct.factory.Mappers.getMapper(Mappers.java:75) at
org.mapstruct.factory.Mappers.getMapper(Mappers.java:58) ... 48
common frames omitted</p>
</blockquote>
<p><strong>How can I fix this type of error?</strong></p>
|
[
{
"answer_id": 74561586,
"author": "Hamza Khadhri",
"author_id": 9523051,
"author_profile": "https://Stackoverflow.com/users/9523051",
"pm_score": -1,
"selected": false,
"text": "@Service\npublic interface DentistService {\n\n DentistDto findById(UUID id) throws NotFoundException;\n\n ResponseEntity<Object> findAll() throws NotFoundException;\n\n ResponseEntity<Object> save(DentistDto dto);\n\n}\n"
},
{
"answer_id": 74561825,
"author": "meriton",
"author_id": 183406,
"author_profile": "https://Stackoverflow.com/users/183406",
"pm_score": 2,
"selected": true,
"text": "Caused by: java.lang.ClassNotFoundException: Cannot find implementation for com.api.lores.mapper.DentistMapper\n at org.mapstruct.factory.Mappers.getMapper(Mappers.java:75)\n at org.mapstruct.factory.Mappers.getMapper(Mappers.java:58) \n ... 48 common frames omitted\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74561096",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17111090/"
] |
74,561,136
|
<p>This is the code where the initState is not working</p>
<pre><code>class _MyAppState extends State<MyApp> {
late bool _nightMode;
Future<void> _loadNightMode() async {
final prefs = await SharedPreferences.getInstance();
setState(() {
_nightMode = (prefs.getBool('nightMode') ?? false);
});
}
@override
void initState() {
super.initState();
_loadNightMode();
print("HELLO");
}
@override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData.light(),
darkTheme: ThemeData.dark(),
themeMode: _nightMode ? ThemeMode.dark : ThemeMode.light,
debugShowCheckedModeBanner: false,
home: const LandingPage(),
);
}
}
</code></pre>
<p>I tried printing HELLO as a testing but it resulted in nothing actually.</p>
<p>This is how I call it.</p>
<pre><code>
logout() {
FirebaseAuth.instance.signOut();
Navigator.of(context).push(
MaterialPageRoute(
builder: (BuildContext context) {
return const MyApp();
},
),
);
}
</code></pre>
<p>As you can see, I am trying to pass the sharedpreferences to get a bool but with the initState not working it's actually not getting passed.
There is also no error popping out.</p>
|
[
{
"answer_id": 74561586,
"author": "Hamza Khadhri",
"author_id": 9523051,
"author_profile": "https://Stackoverflow.com/users/9523051",
"pm_score": -1,
"selected": false,
"text": "@Service\npublic interface DentistService {\n\n DentistDto findById(UUID id) throws NotFoundException;\n\n ResponseEntity<Object> findAll() throws NotFoundException;\n\n ResponseEntity<Object> save(DentistDto dto);\n\n}\n"
},
{
"answer_id": 74561825,
"author": "meriton",
"author_id": 183406,
"author_profile": "https://Stackoverflow.com/users/183406",
"pm_score": 2,
"selected": true,
"text": "Caused by: java.lang.ClassNotFoundException: Cannot find implementation for com.api.lores.mapper.DentistMapper\n at org.mapstruct.factory.Mappers.getMapper(Mappers.java:75)\n at org.mapstruct.factory.Mappers.getMapper(Mappers.java:58) \n ... 48 common frames omitted\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74561136",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20307720/"
] |
74,561,139
|
<pre><code>protocol BackgroundContent: View{
}
struct BlueDivider: BackgroundContent {
var body: some View {
Divider()
.frame(minHeight: 1)
.background(.blue)
}
}
struct RedDivider: BackgroundContent {
var body: some View {
Divider()
.frame(minHeight: 1)
.background(.red)
}
}
var p: BackgroundContent = BlueDivider()
// Use of protocol 'BackgroundContent' as a type must be written 'any BackgroundContent'
p = RedDivider()
</code></pre>
<p>This always ask me to use</p>
<pre><code>var p: any BackgroundContent = BlueDivider()
</code></pre>
<p>Is there any way to use <strong>generic</strong> type which <strong>accept any kind view</strong>?</p>
<p>Actually, I want to use view as a state like<code> @State private var bgView: BackgroundContent = BlueDivider()</code> which i want to change at runtime like <code>bgView = RedDivider()</code></p>
<p>I have made my custome view to place some other view at runtime by using this state.</p>
|
[
{
"answer_id": 74561586,
"author": "Hamza Khadhri",
"author_id": 9523051,
"author_profile": "https://Stackoverflow.com/users/9523051",
"pm_score": -1,
"selected": false,
"text": "@Service\npublic interface DentistService {\n\n DentistDto findById(UUID id) throws NotFoundException;\n\n ResponseEntity<Object> findAll() throws NotFoundException;\n\n ResponseEntity<Object> save(DentistDto dto);\n\n}\n"
},
{
"answer_id": 74561825,
"author": "meriton",
"author_id": 183406,
"author_profile": "https://Stackoverflow.com/users/183406",
"pm_score": 2,
"selected": true,
"text": "Caused by: java.lang.ClassNotFoundException: Cannot find implementation for com.api.lores.mapper.DentistMapper\n at org.mapstruct.factory.Mappers.getMapper(Mappers.java:75)\n at org.mapstruct.factory.Mappers.getMapper(Mappers.java:58) \n ... 48 common frames omitted\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74561139",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12071432/"
] |
74,561,212
|
<p>im working on a simple html/css website in an apache server</p>
<p>i changed urls from <a href="http://www.mydomain.com/about.html" rel="nofollow noreferrer">www.mydomain.com/about.html</a> to <a href="http://www.mydomain.com/a-propos-de-nous" rel="nofollow noreferrer">www.mydomain.com/a-propos-de-nous</a> for all fils in main directory with a htaccess file :</p>
<pre><code>Options +FollowSymlinks
RewriteEngine On
RewriteRule a-propos-de-nous /about.html
</code></pre>
<p>its working perfectly!</p>
<p>but when i try to do the same for files in a sub directory /en , it gives me error 404 :
i created a new file (en.htaccess) in sub directory /en , the content of the file is :</p>
<pre><code>Options +FollowSymlinks
RewriteEngine On
RewriteBase /en/
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule about-us /en/about.html [L]
</code></pre>
<p>i expected to have <a href="http://www.mydomain.com/about-us" rel="nofollow noreferrer">www.mydomain.com/about-us</a> working, but its gives me error 404.</p>
<p>but i have always the 404 error ,
i missed something ?</p>
<p>Thanks for help</p>
|
[
{
"answer_id": 74562742,
"author": "RavinderSingh13",
"author_id": 5866580,
"author_profile": "https://Stackoverflow.com/users/5866580",
"pm_score": 1,
"selected": false,
"text": "RewriteOptions InheritBefore\n\nOptions +FollowSymlinks \nRewriteEngine On\nRewriteBase /en/\nRewriteCond %{REQUEST_FILENAME} !-d\nRewriteCond %{REQUEST_FILENAME} !-f\nRewriteRule about-us en/about.html [L]\n"
},
{
"answer_id": 74568731,
"author": "anubhava",
"author_id": 548225,
"author_profile": "https://Stackoverflow.com/users/548225",
"pm_score": 2,
"selected": false,
"text": "www.mydomain.com/about-us /en/ Options +FollowSymlinks \nRewriteEngine On\n\nRewriteRule a-propos-de-nous about.html [L,NC]\n\nRewriteRule ^about-us en/about.html [L,NC]\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74561212",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4170650/"
] |
74,561,229
|
<p>I have a ReactJS render function where I iterate over an array to display the contents like this:</p>
<pre><code>render() {
let object = eval('('+this.props.objectData+')');
let cd = object.objColAliases;
return (
<div>
{
cd.map(o=>{
return <p>{o}</p>
})
}
</div>
);
}
</code></pre>
<p>This code is working but at the console I have an warning:</p>
<blockquote>
<p>react-jsx-dev-runtime.development.js:87 Warning: Each child in a list
should have a unique "key" prop.</p>
</blockquote>
<p>, the warning makes sense, map is used to iterate over Maps not over simple arrays.</p>
<p>So I try to iterate like a normal array, like this:</p>
<pre><code>render() {
let object = eval('('+this.props.objectData+')');
let cd = object.objColAliases;
return (
<div>
{
for (let i = 0; i < cd.length; i++) {
return <p>{o}</p>
}
}
</div>
);
}
</code></pre>
<p>But now I have a syntax error on the line with "for (let i = 0; i < cd.length; i++)".
How do I write the correct code in this context?</p>
<p><a href="https://codesandbox.io/s/objective-spence-tjb8k1" rel="nofollow noreferrer">This</a> is a sandbox with the problem.</p>
<p><a href="https://i.stack.imgur.com/pXUnG.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/pXUnG.png" alt="enter image description here" /></a></p>
|
[
{
"answer_id": 74561272,
"author": "Jonathan Wieben",
"author_id": 7879109,
"author_profile": "https://Stackoverflow.com/users/7879109",
"pm_score": 1,
"selected": true,
"text": "key .map render() {\n let object = eval('('+this.props.objectData+')');\n let cd = object.objColAliases;\n return (\n <div>\n {\n cd.map(o=>{\n return <p key={o.id}>{o}</p>\n })\n }\n </div>\n );\n}\n o render() {\n let object = eval('('+this.props.objectData+')');\n let cd = object.objColAliases;\n return (\n <div>\n {\n cd.map((o, index) =>{\n return <p key={index}>{o}</p>\n })\n }\n </div>\n );\n}\n"
},
{
"answer_id": 74561414,
"author": "tpstlk",
"author_id": 12822004,
"author_profile": "https://Stackoverflow.com/users/12822004",
"pm_score": 1,
"selected": false,
"text": "key <div>{cd.map((o) => <p key={o}>{o}</p>)}</div>\n index key <div>{cd.map((o, index) => <p key={index}>{o}</p>)}</div>\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74561229",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1510155/"
] |
74,561,245
|
<p>Suppose that I have a table with the following two columns:</p>
<pre><code>create table contacts (
first_name varchar[],
last_name varchar[]
);
</code></pre>
<p>And I have the following two rows:</p>
<pre><code>INSERT INTO contacts (first_name, last_name)
VALUES (ARRAY['Samin'] , Array['Var']),
(ARRAY['Sara', 'pooya'] , Array['Rad', 'Mohammadi']);
select * from contacts;
</code></pre>
<p>I want to do a query that results in the following output:</p>
<pre><code>#row1: {Samin-Var}
#row2: {Sara-Rad, pooya-Mohammadi}
</code></pre>
|
[
{
"answer_id": 74561272,
"author": "Jonathan Wieben",
"author_id": 7879109,
"author_profile": "https://Stackoverflow.com/users/7879109",
"pm_score": 1,
"selected": true,
"text": "key .map render() {\n let object = eval('('+this.props.objectData+')');\n let cd = object.objColAliases;\n return (\n <div>\n {\n cd.map(o=>{\n return <p key={o.id}>{o}</p>\n })\n }\n </div>\n );\n}\n o render() {\n let object = eval('('+this.props.objectData+')');\n let cd = object.objColAliases;\n return (\n <div>\n {\n cd.map((o, index) =>{\n return <p key={index}>{o}</p>\n })\n }\n </div>\n );\n}\n"
},
{
"answer_id": 74561414,
"author": "tpstlk",
"author_id": 12822004,
"author_profile": "https://Stackoverflow.com/users/12822004",
"pm_score": 1,
"selected": false,
"text": "key <div>{cd.map((o) => <p key={o}>{o}</p>)}</div>\n index key <div>{cd.map((o, index) => <p key={index}>{o}</p>)}</div>\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74561245",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16445477/"
] |
74,561,270
|
<p>I have a route with dynamic path, using params:</p>
<pre><code><Route
path="/main/:id"
element={
<Page />
}
/>
</code></pre>
<p>When I reach that page, using React Router <code>useLocation</code>, I'm able to get the full path:</p>
<pre><code>"/main/5432gt34"
</code></pre>
<p>Is there a way to retrieve the path with the params name instead of the actual path?
(output I'm looking for is:)</p>
<pre><code>"/main/:id"
</code></pre>
<p>I'm hoping this might be possible since React Router is aware of the params inside the path and you can extract those with <code>useParams</code></p>
|
[
{
"answer_id": 74561272,
"author": "Jonathan Wieben",
"author_id": 7879109,
"author_profile": "https://Stackoverflow.com/users/7879109",
"pm_score": 1,
"selected": true,
"text": "key .map render() {\n let object = eval('('+this.props.objectData+')');\n let cd = object.objColAliases;\n return (\n <div>\n {\n cd.map(o=>{\n return <p key={o.id}>{o}</p>\n })\n }\n </div>\n );\n}\n o render() {\n let object = eval('('+this.props.objectData+')');\n let cd = object.objColAliases;\n return (\n <div>\n {\n cd.map((o, index) =>{\n return <p key={index}>{o}</p>\n })\n }\n </div>\n );\n}\n"
},
{
"answer_id": 74561414,
"author": "tpstlk",
"author_id": 12822004,
"author_profile": "https://Stackoverflow.com/users/12822004",
"pm_score": 1,
"selected": false,
"text": "key <div>{cd.map((o) => <p key={o}>{o}</p>)}</div>\n index key <div>{cd.map((o, index) => <p key={index}>{o}</p>)}</div>\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74561270",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9856049/"
] |
74,561,280
|
<p>I have 5 migration files created. But when I run <code>./manage.py migrate</code>
it always tries to apply the migrations file "3". Even though the latest one is file 5.</p>
<p>How can I fix this issue?</p>
<p>I have tried:</p>
<pre><code>./manage.py makemigrations app_name
./manage.py migrate app_name
./manage.py migrate --run-syncdb
</code></pre>
<p>Also, I checked the dbshell, and there is a table already created for the model which is part of migrations file 5.</p>
|
[
{
"answer_id": 74561272,
"author": "Jonathan Wieben",
"author_id": 7879109,
"author_profile": "https://Stackoverflow.com/users/7879109",
"pm_score": 1,
"selected": true,
"text": "key .map render() {\n let object = eval('('+this.props.objectData+')');\n let cd = object.objColAliases;\n return (\n <div>\n {\n cd.map(o=>{\n return <p key={o.id}>{o}</p>\n })\n }\n </div>\n );\n}\n o render() {\n let object = eval('('+this.props.objectData+')');\n let cd = object.objColAliases;\n return (\n <div>\n {\n cd.map((o, index) =>{\n return <p key={index}>{o}</p>\n })\n }\n </div>\n );\n}\n"
},
{
"answer_id": 74561414,
"author": "tpstlk",
"author_id": 12822004,
"author_profile": "https://Stackoverflow.com/users/12822004",
"pm_score": 1,
"selected": false,
"text": "key <div>{cd.map((o) => <p key={o}>{o}</p>)}</div>\n index key <div>{cd.map((o, index) => <p key={index}>{o}</p>)}</div>\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74561280",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12917990/"
] |
74,561,289
|
<p>I have a table for learner as learner_lesson</p>
<pre><code>learnerlessonid learnerid lessonid
1 24 42
</code></pre>
<p>and another table as learner_lesson_log</p>
<pre><code>lessonlogid learnerlessonid progress maxprogress. interactionType createdAt
1 1 0 15 Start 2022-11-02 07:50:30
1 1 0 15 Start 2022-11-02 07:51:30
2 1 4 15 Pause 2022-11-02 07:51:34
3 1 4 15 Play 2022-11-02 07:52:20
4 1 14 15 Run 2022-11-02 07:52:30
5 1 15 15 Stop 2022-11-02 07:52:31
</code></pre>
<p>What I am trying to get is the number of seconds watched by a learner. But, it could happen that a learner started a lesson and doesn't complete it or pause it, comes back later and then complete the lesson. For example in the above example, a learner started a lesson and dropped it, came back again and started the lesson again before pausing it after 4 seconds. I want the result to look like</p>
<pre><code>Learner ID Length of Interaction Start Timestamp
24 4 2022-11-02 07:51:30
24 11 2022-11-02 07:52:20
</code></pre>
<p>But with the query I have</p>
<pre><code>Learner ID Length of Interaction Start Timestamp
24 64 2022-11-02 07:50:30
24 4 2022-11-02 07:51:30
24 11 2022-11-02 07:52:20
</code></pre>
<p>I want the query to count the number of seconds only between <code>Start -> Pause, Start->Stop, Play -> Pause, Play -> Stop</code> combination. How can I achieve this result? This is the query that I have</p>
<pre><code>SELECT
c.learnerid AS "Learner ID",
TIMESTAMPDIFF(SECOND, a.createdAt,
(SELECT b.createdAt
FROM learner_lesson_log b
INNER JOIN learner_lessons d
ON b.learnerLessonId = d.learnerLessonId
WHERE b.learnerLessonId = a.learnerLessonId
AND d.learnerId = c.learnerId
AND b.createdAt > a.createdAt
AND b.interactionType IN ('Stop', 'Pause')
ORDER BY b.createdAt ASC LIMIT 1)) AS "Length of Interaction",
a.createdAt AS "Start Timestamp"
FROM learner_lesson_log a
INNER JOIN learner_lessons c
ON c.learnerLessonId = a.learnerLessonId
WHERE a.interactionType IN ('Start', 'Play')
ORDER BY a.createdAt ASC;
</code></pre>
<p>This is the <a href="https://dbfiddle.uk/eyzIUvuJ" rel="nofollow noreferrer">fiddle</a></p>
|
[
{
"answer_id": 74561272,
"author": "Jonathan Wieben",
"author_id": 7879109,
"author_profile": "https://Stackoverflow.com/users/7879109",
"pm_score": 1,
"selected": true,
"text": "key .map render() {\n let object = eval('('+this.props.objectData+')');\n let cd = object.objColAliases;\n return (\n <div>\n {\n cd.map(o=>{\n return <p key={o.id}>{o}</p>\n })\n }\n </div>\n );\n}\n o render() {\n let object = eval('('+this.props.objectData+')');\n let cd = object.objColAliases;\n return (\n <div>\n {\n cd.map((o, index) =>{\n return <p key={index}>{o}</p>\n })\n }\n </div>\n );\n}\n"
},
{
"answer_id": 74561414,
"author": "tpstlk",
"author_id": 12822004,
"author_profile": "https://Stackoverflow.com/users/12822004",
"pm_score": 1,
"selected": false,
"text": "key <div>{cd.map((o) => <p key={o}>{o}</p>)}</div>\n index key <div>{cd.map((o, index) => <p key={index}>{o}</p>)}</div>\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74561289",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4502950/"
] |
74,561,297
|
<p>I would like to create a section component that takes the html specified between the start and end tag and adds a header. The primary reason for me to want this is to make sure the margins of headers and content are consistent across the entire site. I have tried to find how to do this but I don't really know how to formulate the question to get the answer i need.
Here is an example of the component html usage and result I'm looking for</p>
<p>usage:</p>
<pre><code><custom-component [headerText]='example text'>
<button>example content</button>
</custom-component>
</code></pre>
<p>result:</p>
<pre><code><custom-component
<div>
<h1>example text</h1>
<button>example content</button>
</div>
</custom-component>
</code></pre>
|
[
{
"answer_id": 74561272,
"author": "Jonathan Wieben",
"author_id": 7879109,
"author_profile": "https://Stackoverflow.com/users/7879109",
"pm_score": 1,
"selected": true,
"text": "key .map render() {\n let object = eval('('+this.props.objectData+')');\n let cd = object.objColAliases;\n return (\n <div>\n {\n cd.map(o=>{\n return <p key={o.id}>{o}</p>\n })\n }\n </div>\n );\n}\n o render() {\n let object = eval('('+this.props.objectData+')');\n let cd = object.objColAliases;\n return (\n <div>\n {\n cd.map((o, index) =>{\n return <p key={index}>{o}</p>\n })\n }\n </div>\n );\n}\n"
},
{
"answer_id": 74561414,
"author": "tpstlk",
"author_id": 12822004,
"author_profile": "https://Stackoverflow.com/users/12822004",
"pm_score": 1,
"selected": false,
"text": "key <div>{cd.map((o) => <p key={o}>{o}</p>)}</div>\n index key <div>{cd.map((o, index) => <p key={index}>{o}</p>)}</div>\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74561297",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3978394/"
] |
74,561,308
|
<p>I have Multiple Sections Each Containing Subsections and inside I have Questions that I need to validate, The Thing is:</p>
<p>I have a save button for each section.</p>
<p>Edit: I Don't know how many Sections I will have from Api and how many Subsections or Questions its all dynamic</p>
<p>how do I make:
FormGroup for each Subsection. and inside Subsections I have array of questions(fields) that I need to have FormControls for.
what I want to achieve is: SectionForm1.isValid save();, SectionForm2.isValid save()...</p>
<p><a href="https://i.stack.imgur.com/rtYrC.png" rel="nofollow noreferrer">sections</a></p>
<p>I've tried doing this.
but it adds formControl for all fields.
<a href="https://stackblitz.com/edit/angular-dynamic-form-builder-fqhyvh?file=app%2Fdynamic-form-builder%2Fdynamic-form-builder.module.ts,app%2Fdynamic-form-builder%2Ffield-builder%2Ffield-builder.component.ts" rel="nofollow noreferrer">Demo</a></p>
|
[
{
"answer_id": 74561272,
"author": "Jonathan Wieben",
"author_id": 7879109,
"author_profile": "https://Stackoverflow.com/users/7879109",
"pm_score": 1,
"selected": true,
"text": "key .map render() {\n let object = eval('('+this.props.objectData+')');\n let cd = object.objColAliases;\n return (\n <div>\n {\n cd.map(o=>{\n return <p key={o.id}>{o}</p>\n })\n }\n </div>\n );\n}\n o render() {\n let object = eval('('+this.props.objectData+')');\n let cd = object.objColAliases;\n return (\n <div>\n {\n cd.map((o, index) =>{\n return <p key={index}>{o}</p>\n })\n }\n </div>\n );\n}\n"
},
{
"answer_id": 74561414,
"author": "tpstlk",
"author_id": 12822004,
"author_profile": "https://Stackoverflow.com/users/12822004",
"pm_score": 1,
"selected": false,
"text": "key <div>{cd.map((o) => <p key={o}>{o}</p>)}</div>\n index key <div>{cd.map((o, index) => <p key={index}>{o}</p>)}</div>\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74561308",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19665689/"
] |
74,561,313
|
<p>Hello guys I got the following code inside my App.js file:</p>
<pre><code>const history = createHistory();
function App({ calendarStore }) {
const [isLoggedIn, setIsLoggedIn] = useState(
!!localStorage.getItem("isLoggedIn")
);
return (
<div>
<Router history={history}>
<Navbar bg="primary" expand="lg" variant="dark">
<Navbar.Brand href="/">Home</Navbar.Brand>
<Navbar.Toggle aria-controls="basic-navbar-nav" />
<Navbar.Collapse id="basic-navbar-nav">
<Navbar.Brand href="/">About Us</Navbar.Brand>
<Navbar.Brand href="/register">Register</Navbar.Brand>
<Navbar.Brand href="/login">Login</Navbar.Brand>
</Navbar.Collapse>
</Navbar>
<Route
path="/"
exact
component={props => (
<HomePage {...props} calendarStore={calendarStore} />
)}
/>
<Route
path='/login'
exact
component={login}
/>
<Route
path='/register'
exact
component={register}
/>
</Router>
</div>
);
}
export default App;
</code></pre>
<p>I was wandering How i can attach LoggedIn value inside my Code so if user is notLoggedIn he can see only Register and Login page and when he logs he will only can see the homepage from the Navbar.</p>
|
[
{
"answer_id": 74561728,
"author": "Sandil Ranasinghe",
"author_id": 12036671,
"author_profile": "https://Stackoverflow.com/users/12036671",
"pm_score": 0,
"selected": false,
"text": "{isLoggedIn && <Navbar.Brand href=\"/\">Home</Navbar.Brand>} // show only if logged in\n<Navbar.Toggle aria-controls=\"basic-navbar-nav\" />\n<Navbar.Collapse id=\"basic-navbar-nav\">\n<Navbar.Brand href=\"/\">About Us</Navbar.Brand>\n{!isLoggedIn && <Navbar.Brand href=\"/register\">Register</Navbar.Brand>} // show only if not logged in\n{!isLoggedIn && <Navbar.Brand href=\"/login\">Login</Navbar.Brand>}\n"
},
{
"answer_id": 74562211,
"author": "Ahmad Nasser",
"author_id": 20591288,
"author_profile": "https://Stackoverflow.com/users/20591288",
"pm_score": 0,
"selected": false,
"text": "const [loggedIn, setLoggedIn] = useState(false)\n {loggedIn ? <NavbarLoggedIn /> : <Navbar />}\n"
},
{
"answer_id": 74562426,
"author": "Venex",
"author_id": 17968946,
"author_profile": "https://Stackoverflow.com/users/17968946",
"pm_score": 2,
"selected": true,
"text": "useEffect(() => {\nif(localStorage.getItem(\"isLoggedIn\")){\n setIsLoggedIn(true)\n } else {\n setIsLoggedIn(false)\n }\n})\n const [isLoggedIn, setIsLoggedIn]=useState(false)\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74561313",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20109764/"
] |
74,561,344
|
<p>We just upgraded to .net 7, and all the http calls in our integration tests started breaking with the error:</p>
<pre><code>Message:
System.FormatException : The format of value '' is invalid.
Stack Trace:
HttpHeaderParser.ParseValue(String value, Object storeValue, Int32& index)
HttpHeaders.ParseAndAddValue(HeaderDescriptor descriptor, HeaderStoreItemInfo info, String value)
HttpHeaders.Add(HeaderDescriptor descriptor, String value)
CookieContainerHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
RedirectHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
HttpClient.<SendAsync>g__Core|83_0(HttpRequestMessage request, HttpCompletionOption completionOption, CancellationTokenSource cts, Boolean disposeCts, CancellationTokenSource pendingRequestsCts, CancellationToken originalCancellationToken)
</code></pre>
<p><strong>These tests are working fine in .net 5 and .net 6.</strong></p>
<p>Here's an example test -</p>
<pre><code>public async Task ShouldGetStatusOfRunFromAPI()
{
var client = CreateClient(this.mockApiServer.Uri.ToString());
HttpResponseMessage response = await client.GetAsync(StatusAPIForAuroraRun1ContextPath);
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}
</code></pre>
<p>I'm not explicitly setting any headers, but the error doesn't make it clear which value it is expecting that cannot be empty.</p>
<p>Here's the CreateClient method in the TestStartup -</p>
<pre><code>protected HttpClient CreateClient(string uri)
{
var projectDir = Directory.GetCurrentDirectory();
var factory = new WebApplicationFactory<Program>();
var config = TestConfigurationHelper.LoadConfiguration();
return factory
.WithWebHostBuilder(builder =>
{
builder.ConfigureTestServices(services =>
{
services.Configure<ClassOptions>(options => config.GetSection(ClassOptions.Name).Bind(options));
SomeService someService = NewService(config);
services.AddSingleton(someService);
Kubernetes kubernetesClient = NewKubernetesClient(uri);
services.AddSingleton<IKubernetes, Kubernetes>((svcProvider) => kubernetesClient);
services.AddSingleton<ISecretProvider, SecretProvider>((svcProvider) => NewSecretProvider());
})
.ConfigureAppConfiguration((context, builder) =>
{
builder.AddConfiguration(config);
});
})
.CreateClient();
}
</code></pre>
<p>The error message shows it's failing while adding some header, but how do I know which header value is failing?
The value for Accept is set, and I also tried setting it explicitly using -</p>
<pre><code>client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
</code></pre>
<p>But this also failed with the same error.</p>
<p>The calls are failing at the line where GetAsync() is being called.
These are the header values at the time of the call -
<a href="https://i.stack.imgur.com/4KCYK.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/4KCYK.png" alt="enter image description here" /></a></p>
|
[
{
"answer_id": 74561728,
"author": "Sandil Ranasinghe",
"author_id": 12036671,
"author_profile": "https://Stackoverflow.com/users/12036671",
"pm_score": 0,
"selected": false,
"text": "{isLoggedIn && <Navbar.Brand href=\"/\">Home</Navbar.Brand>} // show only if logged in\n<Navbar.Toggle aria-controls=\"basic-navbar-nav\" />\n<Navbar.Collapse id=\"basic-navbar-nav\">\n<Navbar.Brand href=\"/\">About Us</Navbar.Brand>\n{!isLoggedIn && <Navbar.Brand href=\"/register\">Register</Navbar.Brand>} // show only if not logged in\n{!isLoggedIn && <Navbar.Brand href=\"/login\">Login</Navbar.Brand>}\n"
},
{
"answer_id": 74562211,
"author": "Ahmad Nasser",
"author_id": 20591288,
"author_profile": "https://Stackoverflow.com/users/20591288",
"pm_score": 0,
"selected": false,
"text": "const [loggedIn, setLoggedIn] = useState(false)\n {loggedIn ? <NavbarLoggedIn /> : <Navbar />}\n"
},
{
"answer_id": 74562426,
"author": "Venex",
"author_id": 17968946,
"author_profile": "https://Stackoverflow.com/users/17968946",
"pm_score": 2,
"selected": true,
"text": "useEffect(() => {\nif(localStorage.getItem(\"isLoggedIn\")){\n setIsLoggedIn(true)\n } else {\n setIsLoggedIn(false)\n }\n})\n const [isLoggedIn, setIsLoggedIn]=useState(false)\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74561344",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4234855/"
] |
74,561,394
|
<p>I am trying to pass default value in JOLT. While passing I am getting the default value multiple times in an array. I tried cardinality with "*" but still I am getting error.</p>
<p>I tried-</p>
<p>"*":"ONE" in cardinality spec.</p>
<p>Below are the input, spec and output ss. Any idea on how to solve this. If any more information is required then please let me know.</p>
<p><strong>Input</strong>-</p>
<pre class="lang-json prettyprint-override"><code>{
"PURCHASE_ORDER_DISPATCH": {
"MsgData": {
"Transaction": {
"PO_POD_HDR_EVW1": {
"WG_ADDR_SEQ_NUM": 1,
"WG_PO_CNTCT_EMAIL": "dwevc@xyzgrp.com",
"WG_REQUESTOR_EMAIL": "ddds@xyzgrp.com",
"WG_REQ_FIRST_NAME": "addy",
"WG_REQ_LAST_NAME": "Easdls",
"WG_DELIVER_TO": "asdee@xyzgrp.com",
"BUSINESS_UNIT": "OFIC",
"PO_ID": 25052,
"VENDOR_SETID": "WCOS",
"VENDOR_ID": 35958,
"VNDR_LOC": 1,
"PO_DT": "2020-01-24",
"DB_NUMBER_BU": "",
"DESCR_BU": "asdddsuranceCo",
"ADDRESS1_BU": "xyzCOMPANIES",
"ADDRESS2_BU": "HOMEOsdFFIsdCE",
"ADDRESS3_BU": "1PsddARKCIsdRddsdCLE",
"ADDRESS4_BU": "",
"CITY_BU": "xyzCENTER",
"STATE_BU": "OH",
"POSTAL_BU": "44251-5001",
"COUNTRY_BU": "USA",
"ADDRESS1_BILL": "",
"ADDRESS2_BILL": "",
"ADDRESS3_BILL": "",
"ADDRESS4_BILL": "",
"CITY_BILL": "",
"STATE_BILL": "",
"POSTAL_BILL": "",
"COUNTRY_BILL": "",
"CURRENCY_CD": "USD",
"TAX_EXEMPT_ID": "",
"STD_ID_NUM_VNDR": "",
"NAME1_VNDR": "asdsdsd",
"ADDRESS1_VNDR": "410TERRYAVEN",
"ADDRESS2_VNDR": "",
"ADDRESS3_VNDR": "",
"ADDRESS4_VNDR": "",
"CITY_VNDR": "SEATTLE",
"STATE_VNDR": "WA",
"POSTAL_VNDR": 98109,
"COUNTRY_VNDR": "USA",
"PYMNT_TERMS_CD": "NET30",
"DESCR50_PAY": "Net30",
"BUYER_ID": 1083,
"PO_AMT_TTL": 14.99,
"TEXT254_CC1": "",
"TEXT254_CC2": "",
"VNDR_UPN_FLG": "N",
"STD_ID_NUM_VNDRGLN": "",
"STD_ID_NUM_BILLTO": "",
"ATTN_TO": "asdsdsd",
"PO_POD_LN_EVW1": {
"WG_REQ_ID": 25694,
"WG_CATEGORY_CD": "FSSUP",
"WG_ITEM_TYPE": 0,
"WG_ACCOUNT": 641100,
"WG_DEPT_ID": 30400,
"WG_PRODUCT": "",
"BUSINESS_UNIT": "OFIC",
"PO_ID": 25052,
"WG_ASSET_GROUP": "",
"WG_CAPITALIZE": "NO",
"WG_PROFILE_ID": "",
"WG_SPLIT_TYPE": 1,
"WG_ASSET_LOC": "HOME",
"WG_PROJECT": "",
"VENDOR_SETID": "WCOS",
"VENDOR_ID": 35958,
"VNDR_LOC": 1,
"LINE_NBR": 1,
"INV_ITEM_ID": "",
"DESCR254_MIXED": "sdasdadspPods,LightRoastCoffee,32Count",
"UNIT_OF_MEASURE": "EA",
"ITM_ID_VNDR": "B0798CX2Q9",
"INV_ITEM_WEIGHT": 0,
"INV_ITEM_HEIGHT": 0,
"INV_ITEM_VOLUME": 0,
"INV_ITEM_LENGTH": 0,
"INV_ITEM_WIDTH": 0,
"VNDR_CATALOG_ID": "",
"MFG_ID": "",
"MFG_ITM_ID": 5000196305,
"CNTRCT_ID": "",
"VERSION_NBR": 0,
"CNTRCT_LINE_NBR": 0,
"CAT_LINE_NBR": 0,
"RELEASE_NBR": 0,
"CANCEL_STATUS": "A",
"UPN_ID": "",
"PO_POD_SHP_EVW1": {
"WG_SHIP_ADDR_TYPE": 0,
"WG_CUST_ADDR_CODE": "OFIC",
"BUSINESS_UNIT": "OFIC",
"PO_ID": 25052,
"VENDOR_SETID": "WCOS",
"VENDOR_ID": 35958,
"VNDR_LOC": 1,
"LINE_NBR": 1,
"SCHED_NBR": 1,
"DUE_DT": "2020-01-29",
"SHIPTO_ID": "OFIC",
"DESCR_SHIPTO": "asdasddOMPANY",
"ADDRESS1_SHIPTO": "asdsdsdCOMPANY",
"ADDRESS2_SHIPTO": "1PARKCIRCLE",
"ADDRESS3_SHIPTO": "POBOX5001",
"ADDRESS4_SHIPTO": "",
"CITY_SHIPTO": "xyzCENTER",
"STATE_SHIPTO": "OH",
"POSTAL_SHIPTO": "44251-5001",
"COUNTRY_SHIPTO": "USA",
"PRICE_PO": 14.99,
"FREIGHT_TERMS": "FOBDEST",
"QTY_PO": 1,
"SHIP_TYPE_ID": "BEST_WAY",
"CANCEL_STATUS": "A",
"ATTN_TO": "",
"STD_ID_NUM_SHIPTO": ""
},
"PSCAMA": {
"AUDIT_ACTN": "A"
}
},
"PSCAMA": {
"AUDIT_ACTN": "A"
}
},
"PSCAMA": {
"LANGUAGE_CD": "ENG",
"AUDIT_ACTN": "A",
"BASE_LANGUAGE_CD": "ENG",
"MSG_SEQ_FLG": "",
"PROCESS_INSTANCE": 1199010,
"PUBLISH_RULE_ID": "WG_MAIN_RULE",
"MSGNODENAME": ""
}
}
}
}
}
</code></pre>
<p>Spec</p>
<pre class="lang-json prettyprint-override"><code>[
{
"operation": "shift",
"spec": {
"#UPSERT": "integration-inbound:IntegrationDetails.integrationEntities.integrationEntity.integrationEntityHeader.action",
"*": {
"*": {
"*": {
"*": {
"PO_ID": "integration-inbound:IntegrationDetails.integrationEntities.integrationEntity.integrationEntityDetails.poDetails.externalId",
"#APPROVED": "integration-inbound:IntegrationDetails.integrationEntities.integrationEntity.integrationEntityDetails.poDetails.status",
"*": {
"WG_REQ_ID": "integration-inbound:IntegrationDetails.integrationEntities.integrationEntity.integrationEntityDetails.poDetails.poHeader.poDescription",
"#STANDARD": "integration-inbound:IntegrationDetails.integrationEntities.integrationEntity.integrationEntityDetails.poDetails.poHeader.poType",
"*": {
"FREIGHT_TERMS": "integration-inbound:IntegrationDetails.integrationEntities.integrationEntity.integrationEntityDetails.poDetails.poHeader.deliveryTermCode"
}
}
}
}
}
}
}
},
{
"operation": "shift",
"spec": {
"*": {
"*": {
"*": {
"integrationEntityHeader": "&3.&2.&1.&",
"integrationEntityDetails": {
"*": {
"externalId": "&5.&4.&3.&2.&1.&",
"status": "&5.&4.&3.&2.&1.&",
"poHeader": "&5.&4.&3.&2.&1.&"
}
}
}
}
}
}
},
{
"operation": "cardinality",
"spec": {
"*": {
"*": {
"*": {
"*": {
"*": {
"*": "ONE"
}
}
}
}
}
}
}
]
</code></pre>
<p>Output-</p>
<p><a href="https://i.stack.imgur.com/xHCKT.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/xHCKT.png" alt="enter image description here" /></a></p>
|
[
{
"answer_id": 74561728,
"author": "Sandil Ranasinghe",
"author_id": 12036671,
"author_profile": "https://Stackoverflow.com/users/12036671",
"pm_score": 0,
"selected": false,
"text": "{isLoggedIn && <Navbar.Brand href=\"/\">Home</Navbar.Brand>} // show only if logged in\n<Navbar.Toggle aria-controls=\"basic-navbar-nav\" />\n<Navbar.Collapse id=\"basic-navbar-nav\">\n<Navbar.Brand href=\"/\">About Us</Navbar.Brand>\n{!isLoggedIn && <Navbar.Brand href=\"/register\">Register</Navbar.Brand>} // show only if not logged in\n{!isLoggedIn && <Navbar.Brand href=\"/login\">Login</Navbar.Brand>}\n"
},
{
"answer_id": 74562211,
"author": "Ahmad Nasser",
"author_id": 20591288,
"author_profile": "https://Stackoverflow.com/users/20591288",
"pm_score": 0,
"selected": false,
"text": "const [loggedIn, setLoggedIn] = useState(false)\n {loggedIn ? <NavbarLoggedIn /> : <Navbar />}\n"
},
{
"answer_id": 74562426,
"author": "Venex",
"author_id": 17968946,
"author_profile": "https://Stackoverflow.com/users/17968946",
"pm_score": 2,
"selected": true,
"text": "useEffect(() => {\nif(localStorage.getItem(\"isLoggedIn\")){\n setIsLoggedIn(true)\n } else {\n setIsLoggedIn(false)\n }\n})\n const [isLoggedIn, setIsLoggedIn]=useState(false)\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74561394",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20530341/"
] |
74,561,403
|
<p>I am not sure if we can apply validator to a input type="file",All I am trying to do is show error message "special characters not allowed" if user tries to upload a file name containing special characters. But the following code not working as expected. It shows error message in all cases .</p>
<pre><code> <input #elementFileInput id="fileSelector" type="file" accept=".zip formControlName="filename" />
<div class="validation-message-container"
*ngIf="!form.controls['filename'].valid && form.controls['filename'].dirty">
<i class="fa fa-info-circle" aria-hidden="true"></i>
<span *ngIf="form.controls['filename'].errors?.pattern">special characters not allowed
</span>
{{form.controls['filename'].errors?.pattern|json}}
</div>
</code></pre>
<p>component.ts code:</p>
<pre><code>pattern = new RegExp(/^[^*|\"<>{}`\\()';@&$]+$/);
this.form = this.fb.group({
start_date: new FormControl(this.project.start_date, { validators: [Validators.required] }),
budget: new FormControl(''),
filename: new FormControl('', { validators: [Validators.pattern(this.pattern)] }),
})
</code></pre>
<p>here is what I see on my screen(even though file name does not contain special characters)</p>
<p><a href="https://i.stack.imgur.com/IQ4N6.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/IQ4N6.png" alt="enter image description here" /></a></p>
|
[
{
"answer_id": 74561728,
"author": "Sandil Ranasinghe",
"author_id": 12036671,
"author_profile": "https://Stackoverflow.com/users/12036671",
"pm_score": 0,
"selected": false,
"text": "{isLoggedIn && <Navbar.Brand href=\"/\">Home</Navbar.Brand>} // show only if logged in\n<Navbar.Toggle aria-controls=\"basic-navbar-nav\" />\n<Navbar.Collapse id=\"basic-navbar-nav\">\n<Navbar.Brand href=\"/\">About Us</Navbar.Brand>\n{!isLoggedIn && <Navbar.Brand href=\"/register\">Register</Navbar.Brand>} // show only if not logged in\n{!isLoggedIn && <Navbar.Brand href=\"/login\">Login</Navbar.Brand>}\n"
},
{
"answer_id": 74562211,
"author": "Ahmad Nasser",
"author_id": 20591288,
"author_profile": "https://Stackoverflow.com/users/20591288",
"pm_score": 0,
"selected": false,
"text": "const [loggedIn, setLoggedIn] = useState(false)\n {loggedIn ? <NavbarLoggedIn /> : <Navbar />}\n"
},
{
"answer_id": 74562426,
"author": "Venex",
"author_id": 17968946,
"author_profile": "https://Stackoverflow.com/users/17968946",
"pm_score": 2,
"selected": true,
"text": "useEffect(() => {\nif(localStorage.getItem(\"isLoggedIn\")){\n setIsLoggedIn(true)\n } else {\n setIsLoggedIn(false)\n }\n})\n const [isLoggedIn, setIsLoggedIn]=useState(false)\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74561403",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12354698/"
] |
74,561,434
|
<p>As title, here is 2 ways to binding a zeromq socket.</p>
<pre><code>socket.bind("tcp://*:port")
socket.bind("tcp://127.0.0.1:port")
</code></pre>
<p>Both these two way work for me, but I am still curious about it.</p>
|
[
{
"answer_id": 74561728,
"author": "Sandil Ranasinghe",
"author_id": 12036671,
"author_profile": "https://Stackoverflow.com/users/12036671",
"pm_score": 0,
"selected": false,
"text": "{isLoggedIn && <Navbar.Brand href=\"/\">Home</Navbar.Brand>} // show only if logged in\n<Navbar.Toggle aria-controls=\"basic-navbar-nav\" />\n<Navbar.Collapse id=\"basic-navbar-nav\">\n<Navbar.Brand href=\"/\">About Us</Navbar.Brand>\n{!isLoggedIn && <Navbar.Brand href=\"/register\">Register</Navbar.Brand>} // show only if not logged in\n{!isLoggedIn && <Navbar.Brand href=\"/login\">Login</Navbar.Brand>}\n"
},
{
"answer_id": 74562211,
"author": "Ahmad Nasser",
"author_id": 20591288,
"author_profile": "https://Stackoverflow.com/users/20591288",
"pm_score": 0,
"selected": false,
"text": "const [loggedIn, setLoggedIn] = useState(false)\n {loggedIn ? <NavbarLoggedIn /> : <Navbar />}\n"
},
{
"answer_id": 74562426,
"author": "Venex",
"author_id": 17968946,
"author_profile": "https://Stackoverflow.com/users/17968946",
"pm_score": 2,
"selected": true,
"text": "useEffect(() => {\nif(localStorage.getItem(\"isLoggedIn\")){\n setIsLoggedIn(true)\n } else {\n setIsLoggedIn(false)\n }\n})\n const [isLoggedIn, setIsLoggedIn]=useState(false)\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74561434",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14238789/"
] |
74,561,557
|
<p>I am trying to send a request with an authorization header with Angular to a Spring backend.</p>
<pre><code>export class TokenInterceptor implements HttpInterceptor{
constructor(public sharedService : SharedService){}
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const jwtToken = this.sharedService.getJwtToken();
if(jwtToken){
req = this.addToken(req, jwtToken)
}
return next.handle(req)
}
addToken(req: HttpRequest<any>, jwtToken: any){
return req.clone({
headers: req.headers.append('Authorization', 'Bearer ' + jwtToken)
});
}
}
</code></pre>
<p>This is what my interceptor looks like. If I try to console.log() the authorization header before returning the next().handle , I can see the correct token inside the request. The problem is that the backend instead recieves a null Authorization header.</p>
<p>Inside by backend I have a doFilterInternal() method that filters any request and gets the Authentication header.
I don't think the problem is inside this filter because the request sent with Postman are handled correctly.
I have already enabled CORS on my backend</p>
<pre><code>@Override
public void addCorsMappings(CorsRegistry corsRegistry){
corsRegistry.addMapping("/**")
.allowedOriginPatterns("*")
.allowedMethods("*")
.allowedHeaders("*")
.exposedHeaders("Authorization")
.allowCredentials(true)
.maxAge(3600L);
}
</code></pre>
|
[
{
"answer_id": 74561728,
"author": "Sandil Ranasinghe",
"author_id": 12036671,
"author_profile": "https://Stackoverflow.com/users/12036671",
"pm_score": 0,
"selected": false,
"text": "{isLoggedIn && <Navbar.Brand href=\"/\">Home</Navbar.Brand>} // show only if logged in\n<Navbar.Toggle aria-controls=\"basic-navbar-nav\" />\n<Navbar.Collapse id=\"basic-navbar-nav\">\n<Navbar.Brand href=\"/\">About Us</Navbar.Brand>\n{!isLoggedIn && <Navbar.Brand href=\"/register\">Register</Navbar.Brand>} // show only if not logged in\n{!isLoggedIn && <Navbar.Brand href=\"/login\">Login</Navbar.Brand>}\n"
},
{
"answer_id": 74562211,
"author": "Ahmad Nasser",
"author_id": 20591288,
"author_profile": "https://Stackoverflow.com/users/20591288",
"pm_score": 0,
"selected": false,
"text": "const [loggedIn, setLoggedIn] = useState(false)\n {loggedIn ? <NavbarLoggedIn /> : <Navbar />}\n"
},
{
"answer_id": 74562426,
"author": "Venex",
"author_id": 17968946,
"author_profile": "https://Stackoverflow.com/users/17968946",
"pm_score": 2,
"selected": true,
"text": "useEffect(() => {\nif(localStorage.getItem(\"isLoggedIn\")){\n setIsLoggedIn(true)\n } else {\n setIsLoggedIn(false)\n }\n})\n const [isLoggedIn, setIsLoggedIn]=useState(false)\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74561557",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19845343/"
] |
74,561,562
|
<p>I want to make a project with react.js and style it using tailwind.css, is that possible? and how</p>
<p>Hopefully the merging between react.js and styling tailwind.css can be done in one pack</p>
|
[
{
"answer_id": 74561728,
"author": "Sandil Ranasinghe",
"author_id": 12036671,
"author_profile": "https://Stackoverflow.com/users/12036671",
"pm_score": 0,
"selected": false,
"text": "{isLoggedIn && <Navbar.Brand href=\"/\">Home</Navbar.Brand>} // show only if logged in\n<Navbar.Toggle aria-controls=\"basic-navbar-nav\" />\n<Navbar.Collapse id=\"basic-navbar-nav\">\n<Navbar.Brand href=\"/\">About Us</Navbar.Brand>\n{!isLoggedIn && <Navbar.Brand href=\"/register\">Register</Navbar.Brand>} // show only if not logged in\n{!isLoggedIn && <Navbar.Brand href=\"/login\">Login</Navbar.Brand>}\n"
},
{
"answer_id": 74562211,
"author": "Ahmad Nasser",
"author_id": 20591288,
"author_profile": "https://Stackoverflow.com/users/20591288",
"pm_score": 0,
"selected": false,
"text": "const [loggedIn, setLoggedIn] = useState(false)\n {loggedIn ? <NavbarLoggedIn /> : <Navbar />}\n"
},
{
"answer_id": 74562426,
"author": "Venex",
"author_id": 17968946,
"author_profile": "https://Stackoverflow.com/users/17968946",
"pm_score": 2,
"selected": true,
"text": "useEffect(() => {\nif(localStorage.getItem(\"isLoggedIn\")){\n setIsLoggedIn(true)\n } else {\n setIsLoggedIn(false)\n }\n})\n const [isLoggedIn, setIsLoggedIn]=useState(false)\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74561562",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20570023/"
] |
74,561,564
|
<p>I hope you can assist.</p>
<p>I have a SAS data set which has two columns, ID and Date which looks like this:
<a href="https://i.stack.imgur.com/TUMDQ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/TUMDQ.png" alt="enter image description here" /></a>
In some instances, the date column skips a month. I need a code which will create the missing date for each ID e.g. for AY273, I need a code that will create date 2022/11/20 and for WG163, 2022/12/15.</p>
|
[
{
"answer_id": 74561728,
"author": "Sandil Ranasinghe",
"author_id": 12036671,
"author_profile": "https://Stackoverflow.com/users/12036671",
"pm_score": 0,
"selected": false,
"text": "{isLoggedIn && <Navbar.Brand href=\"/\">Home</Navbar.Brand>} // show only if logged in\n<Navbar.Toggle aria-controls=\"basic-navbar-nav\" />\n<Navbar.Collapse id=\"basic-navbar-nav\">\n<Navbar.Brand href=\"/\">About Us</Navbar.Brand>\n{!isLoggedIn && <Navbar.Brand href=\"/register\">Register</Navbar.Brand>} // show only if not logged in\n{!isLoggedIn && <Navbar.Brand href=\"/login\">Login</Navbar.Brand>}\n"
},
{
"answer_id": 74562211,
"author": "Ahmad Nasser",
"author_id": 20591288,
"author_profile": "https://Stackoverflow.com/users/20591288",
"pm_score": 0,
"selected": false,
"text": "const [loggedIn, setLoggedIn] = useState(false)\n {loggedIn ? <NavbarLoggedIn /> : <Navbar />}\n"
},
{
"answer_id": 74562426,
"author": "Venex",
"author_id": 17968946,
"author_profile": "https://Stackoverflow.com/users/17968946",
"pm_score": 2,
"selected": true,
"text": "useEffect(() => {\nif(localStorage.getItem(\"isLoggedIn\")){\n setIsLoggedIn(true)\n } else {\n setIsLoggedIn(false)\n }\n})\n const [isLoggedIn, setIsLoggedIn]=useState(false)\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74561564",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20204836/"
] |
74,561,593
|
<p>As we learn from <a href="https://stackoverflow.com/a/35713234/6105259">this answer</a>, there's a substantial performance increase when using <code>anyNA()</code> over <code>any(is.na())</code> to detect whether a vector has at least one <code>NA</code> element. This makes sense, as the algorithm of <code>anyNA()</code> stops after the first <code>NA</code> value it finds, whereas <code>any(is.na())</code> has to first run over the entire vector with <code>is.na()</code>.</p>
<p>By contrast, I want to know whether a vector has at least 1 <em>non</em>-<code>NA</code> value. This means that I'm looking for an implementation that would stop after the first encounter with a non-<code>NA</code> value. Yes, I can use <code>any(!is.na())</code>, but then I face the issue with having <code>is.na()</code> run over the entire vector first.</p>
<p>Is there a <em>performant</em> opposite equivalent to <code>anyNA()</code>, i.e., "anyNonNA()"?</p>
|
[
{
"answer_id": 74562414,
"author": "Allan Cameron",
"author_id": 12500315,
"author_profile": "https://Stackoverflow.com/users/12500315",
"pm_score": 4,
"selected": true,
"text": "Rcpp::cppFunction(\"bool any_NonNA(NumericVector v) {\n for(size_t i = 0; i < v.length(); i++) {\n if(!(Rcpp::traits::is_na<REALSXP>(v[i]))) return true;\n }\n return false;\n}\")\n any_NonNA test <- rep(NA, 1e5)\n\nany_NonNA(test)\n#> [1] FALSE\n\nany(!is.na(test))\n#> [1] FALSE\n test[1] <- 1\n\nany_NonNA(test)\n#> [1] TRUE\n\nany(!is.na(test))\n#> [1] TRUE\n microbenchmark::microbenchmark(\n baseR = any(!is.na(test)),\n Rcpp = any_NonNA(test)\n)\n#> Unit: microseconds\n#> expr min lq mean median uq max neval cld\n#> baseR 275.1 525.0 670.948 533.05 568.7 13029.9 100 b\n#> Rcpp 1.6 2.1 4.319 3.30 5.1 33.7 100 a \n test[1] <- NA\ntest[50000] <- 1\n\nmicrobenchmark::microbenchmark(\n baseR = any(!is.na(test)),\n Rcpp = any_NonNA(test)\n)\n#> Unit: microseconds\n#> expr min lq mean median uq max neval cld\n#> baseR 332.1 579.35 810.948 597.95 624.40 12010.4 100 b\n#> Rcpp 299.4 300.70 311.516 305.10 309.25 370.1 100 a \n test[50000] <- NA\ntest[100000] <- 1\n\nmicrobenchmark::microbenchmark(\n baseR = any(!is.na(test)),\n Rcpp = any_NonNA(test)\n)\n#> Unit: microseconds\n#> expr min lq mean median uq max neval cld\n#> baseR 395.6 631.65 827.173 642.6 663.8 11357.0 100 a\n#> Rcpp 596.3 602.25 608.011 605.8 612.6 632.6 100 a\n"
},
{
"answer_id": 74562438,
"author": "Ric Villalba",
"author_id": 6912817,
"author_profile": "https://Stackoverflow.com/users/6912817",
"pm_score": 2,
"selected": false,
"text": "anyNonNA <- Rcpp::cppFunction(\n'bool anyNonNA(NumericVector x){\n for (double i:x) if (!Rcpp::NumericVector::is_na(i)) return TRUE;\n return FALSE;}\n')\n\nvar <- rep(NA_real_, 1e7)\n\nany(!is.na(var)) #FALSE\nanyNonNA(var) #FALSE\n\nvar[5e6] <- 0\n\nany(!is.na(var)) #TRUE\nanyNonNA(var) #TRUE\n\nmicrobenchmark::microbenchmark(any(!is.na(var)))\n#Unit: milliseconds\n# expr min lq mean median uq max neval\n# any(!is.na(var)) 41.1922 46.6087 55.57655 59.1408 61.87265 74.4424 100\n\nmicrobenchmark::microbenchmark(anyNonNA(var))\n#Unit: milliseconds\n# expr min lq mean median uq max neval\n# anyNonNA(var) 10.6333 10.71325 11.05704 10.8553 11.2082 14.871 100\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74561593",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6105259/"
] |
74,561,603
|
<p>I want to draw a square and rotate it by 45deg.</p>
<p>It works, but I don't know why the transform applied is not the the center of the the square ( it's off by ~72px ) ?</p>
<p>How would I programatically calculate the transform required for any given square size ?</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>var canvas = document.querySelector('canvas');
canvas.width = 300;
canvas.height = 400;
let rotate = false;
let clear = true; // if set to false then compare the two squares.
let ctx = canvas.getContext('2d')
setInterval(() => {
ctx.fillStyle = 'white';
clear && ctx.fillRect(0,0,canvas.width,canvas.height);
ctx.fillStyle = 'black';
ctx.save();
rotate = !rotate;
if ( rotate ) {
ctx.translate(150,128); // the center of the square is 150 / 200 ??
ctx.rotate(45 * Math.PI / 180); // 45 deg
} else {
ctx.translate(100,150); // top left of square
}
ctx.fillRect(0,0,100,100);
ctx.restore();
},1000)</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><canvas style="border: 1px solid red"></canvas></code></pre>
</div>
</div>
</p>
|
[
{
"answer_id": 74562075,
"author": "Helder Sepulveda",
"author_id": 7599833,
"author_profile": "https://Stackoverflow.com/users/7599833",
"pm_score": 1,
"selected": false,
"text": "ctx.rect(-25, -25, 50, 50) var canvas = document.querySelector('canvas')\ncanvas.width = canvas.height = 160\nlet ctx = canvas.getContext('2d')\nctx.translate(canvas.width/2, canvas.height/2)\nctx.lineWidth = 5\n\nsetInterval(() => {\n ctx.beginPath()\n ctx.clearRect(-canvas.width, -canvas.height, canvas.width*2, canvas.height*2)\n ctx.rotate(45 * Math.PI / 180)\n ctx.rect(-25, -25, 50, 50)\n ctx.rect(10, 10, 8, 8)\n ctx.stroke()\n}, 500) <canvas style=\"border: 1px solid red\"></canvas>"
},
{
"answer_id": 74562226,
"author": "Ultrazz008",
"author_id": 7037331,
"author_profile": "https://Stackoverflow.com/users/7037331",
"pm_score": 0,
"selected": false,
"text": "let paint = {\"width\":75,\"height\":75}; 1.414 let paint = {\"width\":75,\"height\":75};\nvar canvas = document.querySelector('canvas');\ncanvas.width = 300;\ncanvas.height = 400;\nlet rotate = false;\nlet clear = true; // if set to false then compare the two squares.\nlet ctx = canvas.getContext('2d')\n setInterval(() => {\n ctx.fillStyle = 'white';\n clear && ctx.fillRect(0,0,canvas.width,canvas.height);\n ctx.fillStyle = 'black';\n ctx.save();\n rotate = !rotate;\n\n if ( rotate ) {\n \n ctx.translate((canvas.width/2),(canvas.height/2)-((paint.height*1.414)/2)); // the center of the square is 150 / 200 ?? \n ctx.rotate(45 * Math.PI / 180); // 45 deg\n } else {\n ctx.translate((canvas.width/2)-(paint.width/2),(canvas.height/2)-(paint.height/2)); // top left of square\n }\n \n ctx.fillRect(0,0,paint.width,paint.height);\n ctx.restore();\n },1000) <canvas style=\"border: 1px solid red\"></canvas>"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74561603",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3094755/"
] |
74,561,623
|
<p>I am making a "/bulk" endpoint for my API/REST made in Laravel 8.
My problem is that I don't know how to reuse the same FormRequest that I have for the create or update</p>
<p>json post to: /cars/bulk</p>
<pre class="lang-json prettyprint-override"><code>{
"cars": [{"model": "A", "year": 2021, "plate": "AA11BB"},{"model": "B", "year": 2021, "plate": "AA12BB"},{"model": "C", "plate": "AA13BB"}]
}
</code></pre>
<pre><code>// CarController.php
public function store(CarRequest $request)
{
$car = $this->carService->store($request, Car::class);
}
public function update(CarRequest $request, Car $car)
{
$this->carService->update($request, $car);
}
public function bulk(Request $request)
{
$this->carService->bulk($request);
}
</code></pre>
<pre><code>// CarService.php
public function store($request, $modelClass)
{
# My code....
}
public function update($request, $model)
{
# My code....
}
public function bulk($request)
{
foreach ($request->cars AS $carData )
{
$car = Car::where('plate','=',$carData->plate)->first()
# here is the problem,
# howto validate each $car by reusing CarRequest
if ($car){
$this->update($carData, $car);
} else {
$this->store($carData, Car::class);
}
}
}
</code></pre>
<p>This is de form request for each item, i have use to for bulk or one request</p>
<pre class="lang-php prettyprint-override"><code>class CarRequest extends BaseRequest
{
public function authorize()
{
$this->setModel(Car::class);
return $this->isAuthorized();
}
public function rules()
{
$this->setModel(Car::class);
$rules = parent::rules();
$rules = [
'model' => 'required',
'year' => 'required|numeric',
'plate' => 'required'
];
return $rules;
}
public function messages()
{
# multiples messages
}
}
</code></pre>
<p>I need reuse my request</p>
<p>Edit: add form request</p>
|
[
{
"answer_id": 74562075,
"author": "Helder Sepulveda",
"author_id": 7599833,
"author_profile": "https://Stackoverflow.com/users/7599833",
"pm_score": 1,
"selected": false,
"text": "ctx.rect(-25, -25, 50, 50) var canvas = document.querySelector('canvas')\ncanvas.width = canvas.height = 160\nlet ctx = canvas.getContext('2d')\nctx.translate(canvas.width/2, canvas.height/2)\nctx.lineWidth = 5\n\nsetInterval(() => {\n ctx.beginPath()\n ctx.clearRect(-canvas.width, -canvas.height, canvas.width*2, canvas.height*2)\n ctx.rotate(45 * Math.PI / 180)\n ctx.rect(-25, -25, 50, 50)\n ctx.rect(10, 10, 8, 8)\n ctx.stroke()\n}, 500) <canvas style=\"border: 1px solid red\"></canvas>"
},
{
"answer_id": 74562226,
"author": "Ultrazz008",
"author_id": 7037331,
"author_profile": "https://Stackoverflow.com/users/7037331",
"pm_score": 0,
"selected": false,
"text": "let paint = {\"width\":75,\"height\":75}; 1.414 let paint = {\"width\":75,\"height\":75};\nvar canvas = document.querySelector('canvas');\ncanvas.width = 300;\ncanvas.height = 400;\nlet rotate = false;\nlet clear = true; // if set to false then compare the two squares.\nlet ctx = canvas.getContext('2d')\n setInterval(() => {\n ctx.fillStyle = 'white';\n clear && ctx.fillRect(0,0,canvas.width,canvas.height);\n ctx.fillStyle = 'black';\n ctx.save();\n rotate = !rotate;\n\n if ( rotate ) {\n \n ctx.translate((canvas.width/2),(canvas.height/2)-((paint.height*1.414)/2)); // the center of the square is 150 / 200 ?? \n ctx.rotate(45 * Math.PI / 180); // 45 deg\n } else {\n ctx.translate((canvas.width/2)-(paint.width/2),(canvas.height/2)-(paint.height/2)); // top left of square\n }\n \n ctx.fillRect(0,0,paint.width,paint.height);\n ctx.restore();\n },1000) <canvas style=\"border: 1px solid red\"></canvas>"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74561623",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8645456/"
] |
74,561,631
|
<p>I have a simple list with two buttons. I want to be able to show one or the other depending on whether I'm logged in.</p>
<pre><code><div>
<li class="nav-item">
<button *ngIf="token === ''" type="button" class="btn btn-dark btn-lg fs-4" (click)="login()">Inicia sesión</button>
<button *ngIf="token != ''" type="button" class="btn btn-dark btn-lg fs-4" (click)="logout()">Cerrar sesión</button>
</li>
</div>
</code></pre>
<p>I tried simply putting the ngIf but it doesn't make it instant, besides that since the log in is in another component I don't really know how to change that from there.</p>
<p>this is my component:</p>
<pre><code>import { Component, ElementRef, ViewChild} from '@angular/core';
import { Router } from '@angular/router';
import { faHamburger } from '@fortawesome/free-solid-svg-icons';
import { UsersService } from './services/user.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'my-app';
token = this.userService.getToken();
@ViewChild('clickLogout')clickLogout:ElementRef;
faHamburger = faHamburger;
constructor(public userService: UsersService, public router: Router) { }
logout(){
this.userService.logout();
this.router.navigateByUrl('/login');
}
login(){
this.router.navigateByUrl('/login');
}
}
</code></pre>
<p>So as it is, I would need to reload the page every time I need one button or another and I need it to do it instantly when I log in or log out.</p>
|
[
{
"answer_id": 74562075,
"author": "Helder Sepulveda",
"author_id": 7599833,
"author_profile": "https://Stackoverflow.com/users/7599833",
"pm_score": 1,
"selected": false,
"text": "ctx.rect(-25, -25, 50, 50) var canvas = document.querySelector('canvas')\ncanvas.width = canvas.height = 160\nlet ctx = canvas.getContext('2d')\nctx.translate(canvas.width/2, canvas.height/2)\nctx.lineWidth = 5\n\nsetInterval(() => {\n ctx.beginPath()\n ctx.clearRect(-canvas.width, -canvas.height, canvas.width*2, canvas.height*2)\n ctx.rotate(45 * Math.PI / 180)\n ctx.rect(-25, -25, 50, 50)\n ctx.rect(10, 10, 8, 8)\n ctx.stroke()\n}, 500) <canvas style=\"border: 1px solid red\"></canvas>"
},
{
"answer_id": 74562226,
"author": "Ultrazz008",
"author_id": 7037331,
"author_profile": "https://Stackoverflow.com/users/7037331",
"pm_score": 0,
"selected": false,
"text": "let paint = {\"width\":75,\"height\":75}; 1.414 let paint = {\"width\":75,\"height\":75};\nvar canvas = document.querySelector('canvas');\ncanvas.width = 300;\ncanvas.height = 400;\nlet rotate = false;\nlet clear = true; // if set to false then compare the two squares.\nlet ctx = canvas.getContext('2d')\n setInterval(() => {\n ctx.fillStyle = 'white';\n clear && ctx.fillRect(0,0,canvas.width,canvas.height);\n ctx.fillStyle = 'black';\n ctx.save();\n rotate = !rotate;\n\n if ( rotate ) {\n \n ctx.translate((canvas.width/2),(canvas.height/2)-((paint.height*1.414)/2)); // the center of the square is 150 / 200 ?? \n ctx.rotate(45 * Math.PI / 180); // 45 deg\n } else {\n ctx.translate((canvas.width/2)-(paint.width/2),(canvas.height/2)-(paint.height/2)); // top left of square\n }\n \n ctx.fillRect(0,0,paint.width,paint.height);\n ctx.restore();\n },1000) <canvas style=\"border: 1px solid red\"></canvas>"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74561631",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20338186/"
] |
74,561,650
|
<p>I have a dataflie like this (in my original file i have 4 categories of organisms)</p>
<pre><code>organism length intersize
org1 201 38
org1 334 4221
org2 428 575
org2 573 639
org3 356 700
org3 2414 978
</code></pre>
<p>i created a dplyr object and i made plots for length and intersize. i would like to calculate and desing a plot of regression curves per organism and include global regression line. How can i do it in R ?</p>
|
[
{
"answer_id": 74562075,
"author": "Helder Sepulveda",
"author_id": 7599833,
"author_profile": "https://Stackoverflow.com/users/7599833",
"pm_score": 1,
"selected": false,
"text": "ctx.rect(-25, -25, 50, 50) var canvas = document.querySelector('canvas')\ncanvas.width = canvas.height = 160\nlet ctx = canvas.getContext('2d')\nctx.translate(canvas.width/2, canvas.height/2)\nctx.lineWidth = 5\n\nsetInterval(() => {\n ctx.beginPath()\n ctx.clearRect(-canvas.width, -canvas.height, canvas.width*2, canvas.height*2)\n ctx.rotate(45 * Math.PI / 180)\n ctx.rect(-25, -25, 50, 50)\n ctx.rect(10, 10, 8, 8)\n ctx.stroke()\n}, 500) <canvas style=\"border: 1px solid red\"></canvas>"
},
{
"answer_id": 74562226,
"author": "Ultrazz008",
"author_id": 7037331,
"author_profile": "https://Stackoverflow.com/users/7037331",
"pm_score": 0,
"selected": false,
"text": "let paint = {\"width\":75,\"height\":75}; 1.414 let paint = {\"width\":75,\"height\":75};\nvar canvas = document.querySelector('canvas');\ncanvas.width = 300;\ncanvas.height = 400;\nlet rotate = false;\nlet clear = true; // if set to false then compare the two squares.\nlet ctx = canvas.getContext('2d')\n setInterval(() => {\n ctx.fillStyle = 'white';\n clear && ctx.fillRect(0,0,canvas.width,canvas.height);\n ctx.fillStyle = 'black';\n ctx.save();\n rotate = !rotate;\n\n if ( rotate ) {\n \n ctx.translate((canvas.width/2),(canvas.height/2)-((paint.height*1.414)/2)); // the center of the square is 150 / 200 ?? \n ctx.rotate(45 * Math.PI / 180); // 45 deg\n } else {\n ctx.translate((canvas.width/2)-(paint.width/2),(canvas.height/2)-(paint.height/2)); // top left of square\n }\n \n ctx.fillRect(0,0,paint.width,paint.height);\n ctx.restore();\n },1000) <canvas style=\"border: 1px solid red\"></canvas>"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74561650",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3683485/"
] |
74,561,654
|
<p>If you have a component with 1 <strong>FromControl</strong>, connected to two input fields:</p>
<pre><code>@Component({
selector: 'my-app',
template: '<input [formControl]="ctrl"><input [formControl]="ctrl">',
})
export class AppComponent {
ctrl = new FormControl('x', { updateOn: 'change' });
}
</code></pre>
<p><a href="https://stackblitz.com/edit/angular-ivy-bqvmki?file=src%2Fapp%2Fapp.module.ts,src%2Fapp%2Fapp.component.ts,src%2Fapp%2Fapp.component.html" rel="nofollow noreferrer">Stackblitz</a></p>
<p>I was surprised to notice that when I type in one, the other was not updated. Can someone explain to me why this is not happening. After a made the following template modification</p>
<pre><code><input [formControl]="ctrl" (input)="onChange($event)" />
<input [formControl]="ctrl" />
</code></pre>
<p>With</p>
<pre><code>onChange(event) {
this.ctrl.patchValue(e.target.value);
}
</code></pre>
<p>they were in sync!</p>
|
[
{
"answer_id": 74561784,
"author": "Victoria Unizhona",
"author_id": 12844525,
"author_profile": "https://Stackoverflow.com/users/12844525",
"pm_score": -1,
"selected": false,
"text": "<input [formControl]=\"ctrl\" (input)=\"onChange($event)\" />\n<input [formControl]=\"ctrl\" (input)=\"onChange($event)\" />\n"
},
{
"answer_id": 74620472,
"author": "Jimmy",
"author_id": 4960765,
"author_profile": "https://Stackoverflow.com/users/4960765",
"pm_score": 0,
"selected": false,
"text": "export function setUpControl(\n control: FormControl, dir: NgControl,\n callSetDisabledState: SetDisabledStateOption = setDisabledStateDefault): void {\n \n\n //This is where the default value set\n dir.valueAccessor!.writeValue(control.value);\n\n //The names is descriptive\n //This is for input -> control\n setUpViewChangePipeline(control, dir);\n //This is for control -> input\n setUpModelChangePipeline(control, dir);\n}\n function setUpViewChangePipeline(control: FormControl, dir: NgControl): void {\n\n //this basically means when we enter some value into the form \n //-> it will trigger updateControl function\n dir.valueAccessor!.registerOnChange((newValue: any) => {\n updateControl(control, dir);\n });\n}\n function setUpModelChangePipeline(control: FormControl, dir: NgControl): void {\n\n //viewToModelUpdate will emit ngModelChange event \n const onChange = (newValue?: any, emitModelEvent?: boolean) => {\n // control -> view\n dir.valueAccessor!.writeValue(newValue);\n\n // control -> ngModel\n if (emitModelEvent) dir.viewToModelUpdate(newValue);\n };\n control.registerOnChange(onChange);\n}\n emitModelToViewChange //The think we care about is the setValue function\n//The second option: emitModelToViewChange is set to false\nfunction updateControl(control: FormControl, dir: NgControl): void {\n if (control._pendingDirty) control.markAsDirty();\n control.setValue(control._pendingValue, {emitModelToViewChange: false});\n dir.viewToModelUpdate(control._pendingValue);\n control._pendingChange = false;\n}\n patchValue setValue //if emitModelToViewChange === false => no trigger onChange function\n//if it is true, loop thru registered onChangeFns and trigger one by one\noverride setValue(value: TValue, options: {\n onlySelf?: boolean,\n emitEvent?: boolean,\n emitModelToViewChange?: boolean,\n emitViewToModelChange?: boolean\n } = {}): void {\n (this as {value: TValue}).value = this._pendingValue = value;\n if (this._onChange.length && options.emitModelToViewChange !== false) {\n this._onChange.forEach(\n (changeFn) => changeFn(this.value, options.emitViewToModelChange !== false));\n }\n this.updateValueAndValidity(options);\n }\n\n override patchValue(value: TValue, options: {\n onlySelf?: boolean,\n emitEvent?: boolean,\n emitModelToViewChange?: boolean,\n emitViewToModelChange?: boolean\n } = {}): void {\n this.setValue(value, options);\n }\n"
},
{
"answer_id": 74624270,
"author": "Eliseo",
"author_id": 8558186,
"author_profile": "https://Stackoverflow.com/users/8558186",
"pm_score": 1,
"selected": false,
"text": "<input [formControl]=\"ctrl\" />\n<input [ngModel]=\"ctrl.value\" \n (ngModelChange)=\"ctrl.setValue($event)\"\n [ngModelOptions]=\"{standalone:true}\"\n/> \n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74561654",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/419425/"
] |
74,561,663
|
<p>I tried some suggestion from <a href="https://stackoverflow.com/questions/28738089/how-to-change-datepicker-dialog-color-for-android-5-0">How to change DatePicker dialog color for Android 5.0</a> but the only problem is next the two of the buttons are not visible as after writing the code</p>
<pre><code>public static void showExpenseDate(final Context context, final EditText textView) {
final Calendar calendar = Calendar.getInstance();
int yy = calendar.get(Calendar.YEAR);
int mm = calendar.get(Calendar.MONTH);
int dd = calendar.get(Calendar.DAY_OF_MONTH);
DatePickerDialog datePicker = new DatePickerDialog(context, R.style.DialogTheme, new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
//String[] mons = new DateFormatSymbols(Locale.ENGLISH).getShortMonths();
//String mName = mons[monthOfYear];
expense_date = String.valueOf(year) + "-" + String.valueOf((monthOfYear + 1))
+ "-" + String.valueOf(dayOfMonth);
textView.setText(expense_date);
Log.d("djkjiksd", expense_date);
}
}, yy, mm, dd);
datePicker.show();
}
</code></pre>
<p>where as in theme.xml</p>
<pre><code><style name="DialogTheme" parent="Theme.AppCompat.Light.Dialog">
<item name="colorAccent">@color/light_yellow</item>
</style>
</code></pre>
<p><a href="https://i.stack.imgur.com/mW72n.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/mW72n.png" alt="enter image description here" /></a></p>
<p>but the button colors are not coming on UI. What is the solution and correct way to implement date picker theme according to application.</p>
|
[
{
"answer_id": 74561741,
"author": "Aditya Nandardhane",
"author_id": 12819796,
"author_profile": "https://Stackoverflow.com/users/12819796",
"pm_score": 1,
"selected": false,
"text": "<style name=\"DialogTheme\" parent=\"Theme.AppCompat.Light.Dialog\">\n <item name=\"colorAccent\">@color/light_yellow</item>\n <item name=\"android:colorAccent\">@color/light_yellow</item>\n <item name=\"android:buttonBarPositiveButtonStyle\">@style/DialogButtonStyled</item>\n <item name=\"android:buttonBarNegativeButtonStyle\">@style/DialogButtonStyled</item>\n <item name=\"android:buttonBarNeutralButtonStyle\">@style/DialogButtonStyled</item>\n </style>\n \n <style name=\"DialogButtonStyled\" parent=\"Theme.MaterialComponents.Light\">\n <item name=\"android:textColor\">@color/black</item>\n </style>\n"
},
{
"answer_id": 74569359,
"author": "Aimen Izhar",
"author_id": 17890931,
"author_profile": "https://Stackoverflow.com/users/17890931",
"pm_score": 1,
"selected": false,
"text": "<style name=\"DialogTheme\" parent=\"Theme.AppCompat.Light.Dialog\">\n <item name=\"colorAccent\">@color/yourColor</item>\n </style>\n DatePickerDialog datePicker = new DatePickerDialog(context, R.style.DialogTheme, new DatePickerDialog.OnDateSetListener() {\n \n}\n"
},
{
"answer_id": 74569800,
"author": "Gabriele Mariotti",
"author_id": 2016562,
"author_profile": "https://Stackoverflow.com/users/2016562",
"pm_score": 1,
"selected": false,
"text": "MaterialComponents DatePickerDialog <style name=\"ThemeOverlay.App.Dialog\" parent=\"@style/ThemeOverlay.MaterialComponents.Dialog\">\n <item name=\"colorSecondary\">@color/red500_light</item>\n <item name=\"colorPrimary\">@color/blu500_dark</item> <!-- button text color -->\n</style>\n AppCompat <style name=\"ThemeOverlay.AppCompat.Dialog\" parent=\"@style/Theme.AppCompat.Light.Dialog\">\n <item name=\"colorAccent\">@color/red500_light</item>\n <item name=\"android:buttonBarPositiveButtonStyle\">@style/DialogButtonStyled</item>\n <item name=\"android:buttonBarNegativeButtonStyle\">@style/DialogButtonStyled</item>\n</style>\n<style name=\"DialogButtonStyled\" parent=\"Widget.AppCompat.Button.Borderless\">\n <item name=\"android:textColor\">@color/blu500_dark</item> <!-- button text color -->\n</style>\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74561663",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12637592/"
] |
74,561,669
|
<p>I'm coming to the conclusion that Jolt is beyond me.</p>
<p>With this input data:-</p>
<pre class="lang-json prettyprint-override"><code>{
"cluster_id": "1",
"data": {
"id": 1,
"types": [
{
"incident_id": 10,
"incident_ref": "AAA",
"incident_code": "123",
"incident_date": "2010-11-15T00:01:00Z"
},
{
"incident_id": 20,
"incident_ref": "BBB",
"incident_code": "456",
"incident_date": "2020-11-15T00:01:00Z"
}
]
}
}
</code></pre>
<p>Spec:-</p>
<pre class="lang-json prettyprint-override"><code>[
{
"operation": "shift",
"spec": {
"cluster_id": "id",
"data": {
"types": {
"*": {
"incident_id": "incidents",
"incident_ref": "incidents"
}
}
}
}
}
]
</code></pre>
<p>Gives:-</p>
<pre class="lang-json prettyprint-override"><code>{
"id" : "1",
"incidents" : [ 10, "AAA", 20, "BBB" ]
}
</code></pre>
<p>How would I get the result of:-</p>
<pre class="lang-json prettyprint-override"><code>{
"id" : "1",
"incidents" : [
{"id": 10, "ref": "AAA", "code": "123", date: "2010-11-15T00:01:00Z"},
{"id": 20, "ref": "BBB", "code": "456", date: "2020-11-15T00:01:00Z"},
]
}
</code></pre>
<p>Tried a bunch of permutations but getting nowhere!</p>
|
[
{
"answer_id": 74561741,
"author": "Aditya Nandardhane",
"author_id": 12819796,
"author_profile": "https://Stackoverflow.com/users/12819796",
"pm_score": 1,
"selected": false,
"text": "<style name=\"DialogTheme\" parent=\"Theme.AppCompat.Light.Dialog\">\n <item name=\"colorAccent\">@color/light_yellow</item>\n <item name=\"android:colorAccent\">@color/light_yellow</item>\n <item name=\"android:buttonBarPositiveButtonStyle\">@style/DialogButtonStyled</item>\n <item name=\"android:buttonBarNegativeButtonStyle\">@style/DialogButtonStyled</item>\n <item name=\"android:buttonBarNeutralButtonStyle\">@style/DialogButtonStyled</item>\n </style>\n \n <style name=\"DialogButtonStyled\" parent=\"Theme.MaterialComponents.Light\">\n <item name=\"android:textColor\">@color/black</item>\n </style>\n"
},
{
"answer_id": 74569359,
"author": "Aimen Izhar",
"author_id": 17890931,
"author_profile": "https://Stackoverflow.com/users/17890931",
"pm_score": 1,
"selected": false,
"text": "<style name=\"DialogTheme\" parent=\"Theme.AppCompat.Light.Dialog\">\n <item name=\"colorAccent\">@color/yourColor</item>\n </style>\n DatePickerDialog datePicker = new DatePickerDialog(context, R.style.DialogTheme, new DatePickerDialog.OnDateSetListener() {\n \n}\n"
},
{
"answer_id": 74569800,
"author": "Gabriele Mariotti",
"author_id": 2016562,
"author_profile": "https://Stackoverflow.com/users/2016562",
"pm_score": 1,
"selected": false,
"text": "MaterialComponents DatePickerDialog <style name=\"ThemeOverlay.App.Dialog\" parent=\"@style/ThemeOverlay.MaterialComponents.Dialog\">\n <item name=\"colorSecondary\">@color/red500_light</item>\n <item name=\"colorPrimary\">@color/blu500_dark</item> <!-- button text color -->\n</style>\n AppCompat <style name=\"ThemeOverlay.AppCompat.Dialog\" parent=\"@style/Theme.AppCompat.Light.Dialog\">\n <item name=\"colorAccent\">@color/red500_light</item>\n <item name=\"android:buttonBarPositiveButtonStyle\">@style/DialogButtonStyled</item>\n <item name=\"android:buttonBarNegativeButtonStyle\">@style/DialogButtonStyled</item>\n</style>\n<style name=\"DialogButtonStyled\" parent=\"Widget.AppCompat.Button.Borderless\">\n <item name=\"android:textColor\">@color/blu500_dark</item> <!-- button text color -->\n</style>\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74561669",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/126893/"
] |
74,561,680
|
<p>I have a code that looks like:</p>
<pre><code><mat-panel-title>
{{data}}
</mat-panel-title>
</code></pre>
<p>This data is a variable that holds a sentence like <code>My name is so & so</code>.</p>
<p>I need to add CSS for "name" such that it is blue color. but since {{data}} holds the whole sentence I do not know how to split it up. I use TS files for this project. I'm new to angular could you please help me out.</p>
|
[
{
"answer_id": 74562137,
"author": "Chady BAGHDADI",
"author_id": 16227834,
"author_profile": "https://Stackoverflow.com/users/16227834",
"pm_score": 1,
"selected": false,
"text": "import { Directive, ElementRef } from '@angular/core';\n\n@Directive({\n selector: '[highlight]'\n})\nexport class HighlightDirective {\n\n \n constructor(el: ElementRef) {\n this.changeColor(el);\n }\n\n changeColor(el: ElementRef) {\n \n //call the el.nativeElement.style.color and put your logic.....\n \n }\n\n}\n <h1 highlight>{{data}}</h1>\n"
},
{
"answer_id": 74562229,
"author": "Vahid18u",
"author_id": 1302157,
"author_profile": "https://Stackoverflow.com/users/1302157",
"pm_score": 0,
"selected": false,
"text": "getPartsOfSentence(data: string){\nconst x = text.split(\" \");\n const name = x[x.length-1];\n const sentenceWithoutName = x.slice(0, -1).join(\" \");\nreturn ({name, sentenceWithoutName});\n}\n const {name, sentenceWithoutName} = getPartsOfSentence(data);\n"
},
{
"answer_id": 74567202,
"author": "Eliseo",
"author_id": 8558186,
"author_profile": "https://Stackoverflow.com/users/8558186",
"pm_score": 0,
"selected": false,
"text": "const regText = '(' + x + ')([.,\\\\s])|(\\\\s)(' + x + '$)';\nconst reg = new RegExp(regText, 'gi');\ntext = text.replace(reg, '$3<strong>$1$4</strong>$2');\n @Input() set showHighlight(words: any) {\n if (!Array.isArray(words)) this.words = [words];\n else this.words = words;\n this.oldValue=null\n }\n <strong>word</strong> @Pipe({\n name: 'highlight',\n})\nexport class HighlightPipe implements PipeTransform {\n constructor(private sanitize: DomSanitizer) {}\n transform(value: any, args?: any): any {\n let text = value;\n if (args) {\n if (!Array.isArray(args)) args = [args];\n\n args.forEach((x) => {\n const regText = '(' + x + ')([.,\\\\s])|(\\\\s)(' + x + '$)';\n const reg = new RegExp(regText, 'gi');\n text = text.replace(reg, '$3<strong>$1$4</strong>$2');\n });\n text =text.replace(/\\n/g,'<br/>')\n }\n return this.sanitize.bypassSecurityTrustHtml(text);\n }\n}\n '(' + x + ')([.,\\\\s])|(' + x + '$)' <div class=\"highlight\" [innerHTML]=\"data|highlight:'name'\"></div>\n <div class=\"highlight\" [innerHTML]=\"data|highlight:['name','boy']\"></div>\n <p [showHighlight]=\"['house','red']\" >In the house the red skin wait</p>\nor\n<p [showHighlight]=\"['house','red']\" >{{data}}</p>\n @Directive({\n selector: '[showHighlight]',\n})\nexport class HighlightDirective implements AfterContentChecked {\n constructor(private el: ElementRef, private renderer: Renderer2) {}\n private words: string[] = [];\n private div: any = null;\n private oldValue: any;\n\n //in Input use a setter to create an array if it's only one string\n @Input() set showHighlight(words: any) {\n if (!Array.isArray(words)) this.words = [words];\n else this.words = words;\n this.oldValue=null\n }\n ngAfterContentChecked() {\n //we get the el.nativeElement.innerHTML\n //If is diferent than the \"oldValue\"\n\n if (this.el.nativeElement.innerHTML != this.oldValue) {\n //we store the value\n this.oldValue = this.el.nativeElement.innerHTML;\n\n //get the text\n let text = this.el.nativeElement.innerHTML;\n\n //iterate over the words array\n this.words.forEach((x) => {\n\n //use the reg expresion to replace\n const regText = '(' + x + ')([.,\\\\s])|(\\\\s)(' + x + '$)';\n const reg = new RegExp(regText, 'gi');\n text = text.replace(reg, '$3<strong>$1$4</strong>$2');\n });\n\n //replace also \\n by <br/>\n text =text.replace(/\\n/g,'<br/>')\n\n //if we've not yet create the div \n if (!this.div) {\n //we create the div with the same \"tagName\" than the element\n this.div = this.renderer.createElement(\n this.el.nativeElement.tagName.toLowerCase()\n );\n\n //Add a class 'highlight'\n this.renderer.addClass(this.div, 'highlight');\n\n //And insert in parent just before the element\n this.renderer.insertBefore(\n this.el.nativeElement.parentElement,\n this.div,\n this.el.nativeElement\n );\n\n //finally we use style.display:'none' to hide the element\n this.renderer.setStyle(this.el.nativeElement, 'display', 'none');\n }\n\n //If there a change change the innerHTML of the div\n this.renderer.setProperty(this.div, 'innerHTML', text);\n }\n }\n}\n <strong>word</strong> .highlight strong {\n color: red;\n font-weight: normal;\n}\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74561680",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19950798/"
] |
74,561,725
|
<p>i'm using the discogs api to export my wantlist to a google spreadsheet</p>
<p>Is there a way to add the html to make the release-url (resource_url clickable? in the output?</p>
<p>`</p>
<pre><code>function logTheData (url){
var sheet = SpreadsheetApp.getActiveSheet();
var url ='https://api.discogs.com/users/bartvanbelle/wants?per_page=100';
var response = UrlFetchApp.fetch(url); // get feed
var json = response.getContentText(); //
var data = JSON.parse(response);
var counter = 100;
for (var i = 0; i< counter; i++) {
var stats = [];
// var instance_id = data.wants[i].instance_id;
//if (typeof data.wants[i].basic_information.formats[0].descriptions[0] !== "undefined"){
// var description = data.wants[i].basic_information.formats[0].descriptions[0]
// };
// stats.push(instance_id);//works a
stats.push(data.wants[i].basic_information.title); //works a
stats.push(data.wants[i].basic_information.formats[0].name);
// stats.push(description); //stringify array?
stats.push(String(data.wants[i].basic_information.formats[0].descriptions));
stats.push(data.wants[i].basic_information.labels[0].name); //works c
stats.push(data.wants[i].basic_information.labels[0].catno); // work d
stats.push(data.wants[i].basic_information.year); //l
stats.push(data.wants[i].basic_information.artists[0].name); //works j
stats.push(data.wants[i].basic_information.id); // m
stats.push(data.wants[i].basic_information.resource_url); // m
Logger.log(stats);
SpreadsheetApp.getActiveSpreadsheet().appendRow(stats);
}
var pages = data.pagination.pages;
for (var a = 1; a < pages; a++){
var next = data.pagination.urls.next;
var response = UrlFetchApp.fetch(next); // get feed
var json = response.getContentText(); //
var data = JSON.parse(response);
var counter = 100;
for (var i = 0; i< counter; i++) {
var stats = [];
stats.push(data.wants[i].basic_information.title); //works a
stats.push(data.wants[i].basic_information.formats[0].name);
stats.push(String(data.wants[i].basic_information.formats[0].descriptions));
stats.push(data.wants[i].basic_information.labels[0].name); //works c
stats.push(data.wants[i].basic_information.labels[0].catno); // work d
stats.push(data.wants[i].basic_information.year); //l
// stats.push(description); //stringify array?
stats.push(data.wants[i].basic_information.artists[0].name); //works j
stats.push(data.wants[i].basic_information.id); // m
stats.push(data.wants[i].basic_information.resource_url); // m
Logger.log(stats);
SpreadsheetApp.getActiveSpreadsheet().appendRow(stats);
}
}
}
</code></pre>
<p>`</p>
<p>the resource url is also formatted as <a href="http://api.discogs.com/.." rel="nofollow noreferrer">http://api.discogs.com/..</a>. Is there a way to convert that to <a href="http://www.discogs.com" rel="nofollow noreferrer">http://www.discogs.com</a> ?</p>
|
[
{
"answer_id": 74562137,
"author": "Chady BAGHDADI",
"author_id": 16227834,
"author_profile": "https://Stackoverflow.com/users/16227834",
"pm_score": 1,
"selected": false,
"text": "import { Directive, ElementRef } from '@angular/core';\n\n@Directive({\n selector: '[highlight]'\n})\nexport class HighlightDirective {\n\n \n constructor(el: ElementRef) {\n this.changeColor(el);\n }\n\n changeColor(el: ElementRef) {\n \n //call the el.nativeElement.style.color and put your logic.....\n \n }\n\n}\n <h1 highlight>{{data}}</h1>\n"
},
{
"answer_id": 74562229,
"author": "Vahid18u",
"author_id": 1302157,
"author_profile": "https://Stackoverflow.com/users/1302157",
"pm_score": 0,
"selected": false,
"text": "getPartsOfSentence(data: string){\nconst x = text.split(\" \");\n const name = x[x.length-1];\n const sentenceWithoutName = x.slice(0, -1).join(\" \");\nreturn ({name, sentenceWithoutName});\n}\n const {name, sentenceWithoutName} = getPartsOfSentence(data);\n"
},
{
"answer_id": 74567202,
"author": "Eliseo",
"author_id": 8558186,
"author_profile": "https://Stackoverflow.com/users/8558186",
"pm_score": 0,
"selected": false,
"text": "const regText = '(' + x + ')([.,\\\\s])|(\\\\s)(' + x + '$)';\nconst reg = new RegExp(regText, 'gi');\ntext = text.replace(reg, '$3<strong>$1$4</strong>$2');\n @Input() set showHighlight(words: any) {\n if (!Array.isArray(words)) this.words = [words];\n else this.words = words;\n this.oldValue=null\n }\n <strong>word</strong> @Pipe({\n name: 'highlight',\n})\nexport class HighlightPipe implements PipeTransform {\n constructor(private sanitize: DomSanitizer) {}\n transform(value: any, args?: any): any {\n let text = value;\n if (args) {\n if (!Array.isArray(args)) args = [args];\n\n args.forEach((x) => {\n const regText = '(' + x + ')([.,\\\\s])|(\\\\s)(' + x + '$)';\n const reg = new RegExp(regText, 'gi');\n text = text.replace(reg, '$3<strong>$1$4</strong>$2');\n });\n text =text.replace(/\\n/g,'<br/>')\n }\n return this.sanitize.bypassSecurityTrustHtml(text);\n }\n}\n '(' + x + ')([.,\\\\s])|(' + x + '$)' <div class=\"highlight\" [innerHTML]=\"data|highlight:'name'\"></div>\n <div class=\"highlight\" [innerHTML]=\"data|highlight:['name','boy']\"></div>\n <p [showHighlight]=\"['house','red']\" >In the house the red skin wait</p>\nor\n<p [showHighlight]=\"['house','red']\" >{{data}}</p>\n @Directive({\n selector: '[showHighlight]',\n})\nexport class HighlightDirective implements AfterContentChecked {\n constructor(private el: ElementRef, private renderer: Renderer2) {}\n private words: string[] = [];\n private div: any = null;\n private oldValue: any;\n\n //in Input use a setter to create an array if it's only one string\n @Input() set showHighlight(words: any) {\n if (!Array.isArray(words)) this.words = [words];\n else this.words = words;\n this.oldValue=null\n }\n ngAfterContentChecked() {\n //we get the el.nativeElement.innerHTML\n //If is diferent than the \"oldValue\"\n\n if (this.el.nativeElement.innerHTML != this.oldValue) {\n //we store the value\n this.oldValue = this.el.nativeElement.innerHTML;\n\n //get the text\n let text = this.el.nativeElement.innerHTML;\n\n //iterate over the words array\n this.words.forEach((x) => {\n\n //use the reg expresion to replace\n const regText = '(' + x + ')([.,\\\\s])|(\\\\s)(' + x + '$)';\n const reg = new RegExp(regText, 'gi');\n text = text.replace(reg, '$3<strong>$1$4</strong>$2');\n });\n\n //replace also \\n by <br/>\n text =text.replace(/\\n/g,'<br/>')\n\n //if we've not yet create the div \n if (!this.div) {\n //we create the div with the same \"tagName\" than the element\n this.div = this.renderer.createElement(\n this.el.nativeElement.tagName.toLowerCase()\n );\n\n //Add a class 'highlight'\n this.renderer.addClass(this.div, 'highlight');\n\n //And insert in parent just before the element\n this.renderer.insertBefore(\n this.el.nativeElement.parentElement,\n this.div,\n this.el.nativeElement\n );\n\n //finally we use style.display:'none' to hide the element\n this.renderer.setStyle(this.el.nativeElement, 'display', 'none');\n }\n\n //If there a change change the innerHTML of the div\n this.renderer.setProperty(this.div, 'innerHTML', text);\n }\n }\n}\n <strong>word</strong> .highlight strong {\n color: red;\n font-weight: normal;\n}\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74561725",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20591334/"
] |
74,561,735
|
<p>This is my first website project; I want the one <code><button></code> to change the <code>z-index</code> on two boxes. Two buttons would be no problem, but I want the script to do two things in one action. I couldn´t find any information about this subject online.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function myFunction() {
document.getElementById("DIV1").style.zIndex = "-1";
}</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>#DIV1 {
position: absolute;
width: 200px;
height: 100px;
background-color: lightblue;
border: 1px solid black;
}
#DIV2 {
position: relative;
top: 70px;
left: 30px;
width: 200px;
height: 100px;
background-color: coral;
border: 1px solid black;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><button onclick="myFunction()">Enter</button>
<div id="DIV1">
<h1>Gone fishing</h1>
</div>
<div id="DIV2">
<h1>Gone fishing</h1>
</div></code></pre>
</div>
</div>
</p>
|
[
{
"answer_id": 74562137,
"author": "Chady BAGHDADI",
"author_id": 16227834,
"author_profile": "https://Stackoverflow.com/users/16227834",
"pm_score": 1,
"selected": false,
"text": "import { Directive, ElementRef } from '@angular/core';\n\n@Directive({\n selector: '[highlight]'\n})\nexport class HighlightDirective {\n\n \n constructor(el: ElementRef) {\n this.changeColor(el);\n }\n\n changeColor(el: ElementRef) {\n \n //call the el.nativeElement.style.color and put your logic.....\n \n }\n\n}\n <h1 highlight>{{data}}</h1>\n"
},
{
"answer_id": 74562229,
"author": "Vahid18u",
"author_id": 1302157,
"author_profile": "https://Stackoverflow.com/users/1302157",
"pm_score": 0,
"selected": false,
"text": "getPartsOfSentence(data: string){\nconst x = text.split(\" \");\n const name = x[x.length-1];\n const sentenceWithoutName = x.slice(0, -1).join(\" \");\nreturn ({name, sentenceWithoutName});\n}\n const {name, sentenceWithoutName} = getPartsOfSentence(data);\n"
},
{
"answer_id": 74567202,
"author": "Eliseo",
"author_id": 8558186,
"author_profile": "https://Stackoverflow.com/users/8558186",
"pm_score": 0,
"selected": false,
"text": "const regText = '(' + x + ')([.,\\\\s])|(\\\\s)(' + x + '$)';\nconst reg = new RegExp(regText, 'gi');\ntext = text.replace(reg, '$3<strong>$1$4</strong>$2');\n @Input() set showHighlight(words: any) {\n if (!Array.isArray(words)) this.words = [words];\n else this.words = words;\n this.oldValue=null\n }\n <strong>word</strong> @Pipe({\n name: 'highlight',\n})\nexport class HighlightPipe implements PipeTransform {\n constructor(private sanitize: DomSanitizer) {}\n transform(value: any, args?: any): any {\n let text = value;\n if (args) {\n if (!Array.isArray(args)) args = [args];\n\n args.forEach((x) => {\n const regText = '(' + x + ')([.,\\\\s])|(\\\\s)(' + x + '$)';\n const reg = new RegExp(regText, 'gi');\n text = text.replace(reg, '$3<strong>$1$4</strong>$2');\n });\n text =text.replace(/\\n/g,'<br/>')\n }\n return this.sanitize.bypassSecurityTrustHtml(text);\n }\n}\n '(' + x + ')([.,\\\\s])|(' + x + '$)' <div class=\"highlight\" [innerHTML]=\"data|highlight:'name'\"></div>\n <div class=\"highlight\" [innerHTML]=\"data|highlight:['name','boy']\"></div>\n <p [showHighlight]=\"['house','red']\" >In the house the red skin wait</p>\nor\n<p [showHighlight]=\"['house','red']\" >{{data}}</p>\n @Directive({\n selector: '[showHighlight]',\n})\nexport class HighlightDirective implements AfterContentChecked {\n constructor(private el: ElementRef, private renderer: Renderer2) {}\n private words: string[] = [];\n private div: any = null;\n private oldValue: any;\n\n //in Input use a setter to create an array if it's only one string\n @Input() set showHighlight(words: any) {\n if (!Array.isArray(words)) this.words = [words];\n else this.words = words;\n this.oldValue=null\n }\n ngAfterContentChecked() {\n //we get the el.nativeElement.innerHTML\n //If is diferent than the \"oldValue\"\n\n if (this.el.nativeElement.innerHTML != this.oldValue) {\n //we store the value\n this.oldValue = this.el.nativeElement.innerHTML;\n\n //get the text\n let text = this.el.nativeElement.innerHTML;\n\n //iterate over the words array\n this.words.forEach((x) => {\n\n //use the reg expresion to replace\n const regText = '(' + x + ')([.,\\\\s])|(\\\\s)(' + x + '$)';\n const reg = new RegExp(regText, 'gi');\n text = text.replace(reg, '$3<strong>$1$4</strong>$2');\n });\n\n //replace also \\n by <br/>\n text =text.replace(/\\n/g,'<br/>')\n\n //if we've not yet create the div \n if (!this.div) {\n //we create the div with the same \"tagName\" than the element\n this.div = this.renderer.createElement(\n this.el.nativeElement.tagName.toLowerCase()\n );\n\n //Add a class 'highlight'\n this.renderer.addClass(this.div, 'highlight');\n\n //And insert in parent just before the element\n this.renderer.insertBefore(\n this.el.nativeElement.parentElement,\n this.div,\n this.el.nativeElement\n );\n\n //finally we use style.display:'none' to hide the element\n this.renderer.setStyle(this.el.nativeElement, 'display', 'none');\n }\n\n //If there a change change the innerHTML of the div\n this.renderer.setProperty(this.div, 'innerHTML', text);\n }\n }\n}\n <strong>word</strong> .highlight strong {\n color: red;\n font-weight: normal;\n}\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74561735",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20585966/"
] |
74,561,806
|
<p>I'm wondering if I can combine 2 rules applied on the same element and containing the same styles but one of the rules is in a media query and get something similar to :</p>
<pre><code>.a,
.b .a {
color: white;
background-color: black;
}
</code></pre>
<p>The rules are :</p>
<ul>
<li>Apply colors to the <code>.content</code> depending on the <code>prefers-color-scheme</code>,</li>
<li>Change the <code>.content</code> colors when an <code>input</code> is <code>checked</code></li>
</ul>
<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>:root {
--dark-color: white;
--dark-bg: black;
--light-color: black;
--light-bg: white;
}
@media (prefers-color-scheme: dark) {
.content {
color: var(--dark-color);
background-color: var(--dark-bg);
}
}
#dark-theme:checked~.content {
color: var(--dark-color);
background-color: var(--dark-bg);
}
@media (prefers-color-scheme: light) {
.content {
color: var(--light-color);
background-color: var(--light-bg);
}
}
#light-theme:checked~.content {
color: var(--light-color);
background-color: var(--light-bg);
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="radio" name="color-theme" id="dark-theme">
<label for="dark-theme">dark</label>
<input type="radio" name="color-theme" id="light-theme">
<label for="light-theme">light</label>
<input type="radio" name="color-theme" id="default-theme" checked>
<label for="default-theme">default</label>
<div class="content">Test</div></code></pre>
</div>
</div>
</p>
<p>Here <code>.content</code> will get a black background and a white color if the <code>prefer-color-scheme</code> is dark, or if <code>#dark-theme</code> is checked.</p>
<p>The same styles are applied for both rules.</p>
<p>Is there a way to combine these rules ?</p>
|
[
{
"answer_id": 74562677,
"author": "ksav",
"author_id": 5385381,
"author_profile": "https://Stackoverflow.com/users/5385381",
"pm_score": -1,
"selected": false,
"text": ":root {\n --dark-color: white;\n --dark-bg: black;\n --light-color: black;\n --light-bg: white;\n}\n\n@media (prefers-color-scheme: dark) {\n #default-theme:checked~.content {\n color: var(--dark-color);\n background-color: var(--dark-bg);\n }\n}\n#dark-theme:checked~.content {\n color: var(--dark-color);\n background-color: var(--dark-bg);\n}\n\n@media (prefers-color-scheme: light) {\n #default-theme:checked~.content {\n color: var(--light-color);\n background-color: var(--light-bg);\n }\n}\n#light-theme:checked~.content {\n color: var(--light-color);\n background-color: var(--light-bg);\n} <input type=\"radio\" name=\"color-theme\" id=\"dark-theme\">\n<label for=\"dark-theme\">dark</label>\n<input type=\"radio\" name=\"color-theme\" id=\"light-theme\">\n<label for=\"light-theme\">light</label>\n<input type=\"radio\" name=\"color-theme\" id=\"default-theme\" checked>\n<label for=\"default-theme\">default</label>\n\n<div class=\"content\">Test</div>"
},
{
"answer_id": 74602130,
"author": "user20624405",
"author_id": 20624405,
"author_profile": "https://Stackoverflow.com/users/20624405",
"pm_score": 0,
"selected": false,
"text": "@media prefers-color-scheme ~checked"
},
{
"answer_id": 74621996,
"author": "Alvin",
"author_id": 9239975,
"author_profile": "https://Stackoverflow.com/users/9239975",
"pm_score": 1,
"selected": false,
"text": "@mixin @mixin content-style($theme) {\n .content {\n color: var(--#{$theme}-color);\n background-color: var(--#{$theme}-bg);\n }\n}\n @mixin themed-style($theme) {\n @media (prefers-color-scheme: $theme) {\n @include content-style($theme);\n }\n ##{$theme}-theme:checked ~ {\n @include content-style(#{$theme});\n }\n}\n @include themed-style(dark);\n@include themed-style(light);\n :root {\n --dark-color: white;\n --dark-bg: black;\n --light-color: black;\n --light-bg: white;\n}\n\n@mixin content-style($theme) {\n .content {\n color: var(--#{$theme}-color);\n background-color: var(--#{$theme}-bg);\n }\n}\n\n@mixin themed-style($theme) {\n @media (prefers-color-scheme: $theme) {\n @include content-style($theme);\n }\n ##{$theme}-theme:checked ~ {\n @include content-style(#{$theme});\n }\n}\n\n@include themed-style(dark);\n@include themed-style(light);\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74561806",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17684809/"
] |
74,561,837
|
<p>so I'm kind of a beginner at JavaScript and APIs, things like that. I want to implement an API into my website that can detect whether an article is fake news or not based on the title. I already found the API, <a href="https://rapidapi.com/fangyiyu/api/fake-news-detection1" rel="nofollow noreferrer">which is this</a>, but I'm a bit confused with how to retrieve the form value from my HTML code, shown below:</p>
<pre><code><input type="text" name="check" id="check">
<button onClick="checkFakeNews" id="btn">Check</button>
<p id="result"></p>
</code></pre>
<p>I already tried typing up this function:</p>
<pre><code>function checkFakeNews() {
document.getElementById('check') = text
console.log(text)
}
</code></pre>
<p>to try to print out the value, but I didn't get anything.</p>
<p>I also want to get the result, stored in 'data' in the API I believe, and display it in the paragraph. I'd be very grateful to anyone who can help me!</p>
|
[
{
"answer_id": 74561907,
"author": "Shivangam Soni",
"author_id": 16659219,
"author_profile": "https://Stackoverflow.com/users/16659219",
"pm_score": 0,
"selected": false,
"text": "document.getElementById('check') = text onClick checkFakeNews() checkFakeNews function checkFakeNews() {\n const input = document.getElementById('check');\n const text = check.value;\n console.log(text);\n} <input type=\"text\" name=\"check\" id=\"check\">\n<button onClick=\"checkFakeNews()\" id=\"btn\">Check</button>\n\n<p id=\"result\"></p>"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74561837",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20591298/"
] |
74,561,852
|
<p>I am using pandas to import a dataframe, and want to drop certain rows before grouping the information.</p>
<p>How do I go from the following (example):</p>
<pre><code> Name1 Name2 Name3
0 A1 B1 1
1 NaN NaN 2
2 NaN NaN 3
3 NaN B2 4
4 NaN NaN 5
5 NaN NaN 6
6 NaN B3 7
7 NaN NaN 8
8 NaN NaN 9
9 A2 B4 1
10 NaN NaN 2
11 NaN NaN 3
12 NaN B5 4
13 NaN NaN 5
14 NaN NaN 6
15 NaN B6 7
16 NaN NaN 8
17 NaN NaN 9
</code></pre>
<p>to:</p>
<pre><code> Name1 Name2 Name3
0 A1 B1 1
3 NaN B2 4
6 NaN B3 7
8 NaN NaN 9
9 A2 B4 1
12 NaN B5 4
15 NaN B6 7
17 NaN NaN 9
</code></pre>
<p>(My actual case consists of several thousand lines with the same structure as the example)</p>
<p>I have tried removing rows with NaN in Name2 using df=df[df['Name2'].notna()] , but then I get this:</p>
<pre><code> Name1 Name2 Name3
0 A1 B1 1
3 NaN B2 4
6 NaN B3 7
9 A2 B4 1
12 NaN B5 4
15 NaN B6 7
</code></pre>
<p>I also need to keep line 8 and 17 in the example above.</p>
|
[
{
"answer_id": 74562018,
"author": "Vini",
"author_id": 6927944,
"author_profile": "https://Stackoverflow.com/users/6927944",
"pm_score": 0,
"selected": false,
"text": "thresh # toy data\ndata = {'name1': [np.nan, np.nan, np.nan, np.nan], 'name2': [np.nan, 1, 2, np.nan], 'name3': [1, 2, 3, 4]}\ndf = pd.DataFrame(data)\n\n name1 name2 name3\n0 NaN NaN 1\n1 NaN 1.0 2\n2 NaN 2.0 3\n3 NaN NaN 4\n df.dropna(thresh = 2)\n\n name1 name2 name3\n1 NaN 1.0 2\n2 NaN 2.0 3\n df.append"
},
{
"answer_id": 74562190,
"author": "mozway",
"author_id": 16343464,
"author_profile": "https://Stackoverflow.com/users/16343464",
"pm_score": 2,
"selected": true,
"text": "# is the row not-NA in Name2?\nm1 = df['Name2'].notna()\n# is is the last row of a group?\nm2 = df['Name1'].notna().shift(-1, fill_value=True)\n\n# keep if either of the above condition is True\nout = df[m1|m2]\n Name1 Name2 Name3\n0 A1 B1 1\n3 NaN B2 4\n6 NaN B3 7\n8 NaN NaN 9\n9 A2 B4 1\n12 NaN B5 4\n15 NaN B6 7\n17 NaN NaN 9\n Name1 Name2 Name3 m1 m2 m1|m2\n0 A1 B1 1 True False True\n1 NaN NaN 2 False False False\n2 NaN NaN 3 False False False\n3 NaN B2 4 True False True\n4 NaN NaN 5 False False False\n5 NaN NaN 6 False False False\n6 NaN B3 7 True False True\n7 NaN NaN 8 False False False\n8 NaN NaN 9 False True True\n9 A2 B4 1 True False True\n10 NaN NaN 2 False False False\n11 NaN NaN 3 False False False\n12 NaN B5 4 True False True\n13 NaN NaN 5 False False False\n14 NaN NaN 6 False False False\n15 NaN B6 7 True False True\n16 NaN NaN 8 False False False\n17 NaN NaN 9 False True True\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74561852",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20591390/"
] |
74,561,873
|
<p>I am on Application Express 21.1.0.</p>
<p>I added a column to a db table, and tried to add that column to the Form region based on that table.</p>
<p>I got error...</p>
<p>ORA-20999: Failed to parse SQL query! ORA-06550: line 4, column 15: ORA-00904: "NEEDED_EXAMS": invalid identifier
And I can not find the column in any "source> column" attribute of any page item of that form.</p>
<p>I can query the new column in "SQL COMMANDS".</p>
<p>The new column's name is "NEEDED_EXAMS". It's a varachar2(500).</p>
|
[
{
"answer_id": 74562018,
"author": "Vini",
"author_id": 6927944,
"author_profile": "https://Stackoverflow.com/users/6927944",
"pm_score": 0,
"selected": false,
"text": "thresh # toy data\ndata = {'name1': [np.nan, np.nan, np.nan, np.nan], 'name2': [np.nan, 1, 2, np.nan], 'name3': [1, 2, 3, 4]}\ndf = pd.DataFrame(data)\n\n name1 name2 name3\n0 NaN NaN 1\n1 NaN 1.0 2\n2 NaN 2.0 3\n3 NaN NaN 4\n df.dropna(thresh = 2)\n\n name1 name2 name3\n1 NaN 1.0 2\n2 NaN 2.0 3\n df.append"
},
{
"answer_id": 74562190,
"author": "mozway",
"author_id": 16343464,
"author_profile": "https://Stackoverflow.com/users/16343464",
"pm_score": 2,
"selected": true,
"text": "# is the row not-NA in Name2?\nm1 = df['Name2'].notna()\n# is is the last row of a group?\nm2 = df['Name1'].notna().shift(-1, fill_value=True)\n\n# keep if either of the above condition is True\nout = df[m1|m2]\n Name1 Name2 Name3\n0 A1 B1 1\n3 NaN B2 4\n6 NaN B3 7\n8 NaN NaN 9\n9 A2 B4 1\n12 NaN B5 4\n15 NaN B6 7\n17 NaN NaN 9\n Name1 Name2 Name3 m1 m2 m1|m2\n0 A1 B1 1 True False True\n1 NaN NaN 2 False False False\n2 NaN NaN 3 False False False\n3 NaN B2 4 True False True\n4 NaN NaN 5 False False False\n5 NaN NaN 6 False False False\n6 NaN B3 7 True False True\n7 NaN NaN 8 False False False\n8 NaN NaN 9 False True True\n9 A2 B4 1 True False True\n10 NaN NaN 2 False False False\n11 NaN NaN 3 False False False\n12 NaN B5 4 True False True\n13 NaN NaN 5 False False False\n14 NaN NaN 6 False False False\n15 NaN B6 7 True False True\n16 NaN NaN 8 False False False\n17 NaN NaN 9 False True True\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74561873",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13389582/"
] |
74,561,897
|
<p>I have a view that aggregates data about customers and shows the products they have access to, along with the status of whether they use those products on a trial basis or not (both as string comma seperated values):</p>
<pre><code>+----------+----------+-----------------------+
| customer | products | products_trial_status |
+----------+----------+-----------------------+
| 234253 | A,B,C | false,true,false |
| 923403 | A,C | true,true |
| 123483 | B | true |
| 239874 | B,C | false,false |
+----------+----------+-----------------------+
</code></pre>
<p>and I would like to write a query that returns a list of customers who are using a certain product on a trial.</p>
<p>e.g. I want to see which customers using product B are on a trial, I would get something like this:</p>
<pre><code>+----------+
| customer |
+----------+
| 234253 |
| 123483 |
+----------+
</code></pre>
<p>The only way I can think of doing this is by checking the <code>products</code> column for the position of the product in the string (if it exists there), then checking the corresponding value at the same position in the <code>products_trial_status</code> column and whether it is equal to true.</p>
<p>i.e. for customer 234253, product B is in position 2 (after the first comma), so it's corresponding trial status in the column would also be in position 2 after the first comma there.</p>
<p>How would I go about doing this?</p>
<p>I am aware that storing such data as a string of values is not good practice but it is not something i can change, so would need to work out using the format it is in</p>
|
[
{
"answer_id": 74562368,
"author": "Barbaros Özhan",
"author_id": 5841306,
"author_profile": "https://Stackoverflow.com/users/5841306",
"pm_score": 0,
"selected": false,
"text": "WITH t1 AS\n(\n SELECT customer,\n REGEXP_SUBSTR(products,'[^,]',1,level) AS products,\n REGEXP_SUBSTR(products_trial_status,'[^,]+',1,level) AS products_ts\n FROM t -- your data source\nCONNECT BY level <= REGEXP_COUNT(products,',')+1\n AND PRIOR customer = customer\n AND PRIOR sys_guid() IS NOT NULL \n)\nSELECT customer\n FROM t1\n WHERE products = 'B'\n AND products_ts = 'true' \n"
},
{
"answer_id": 74562392,
"author": "MT0",
"author_id": 1509264,
"author_profile": "https://Stackoverflow.com/users/1509264",
"pm_score": 2,
"selected": false,
"text": "B SELECT customer,\n COALESCE(\n SUBSTR(\n status,\n LENGTH(preceding_terms) - COALESCE(LENGTH(REPLACE(preceding_terms, ',')), 0),\n 1\n ),\n '0'\n ) AS hasB\nFROM (\n SELECT customer,\n SUBSTR(','||products, 1, INSTR(','||products||',', ',B,')) AS preceding_terms,\n TRANSLATE(products_trial_status, 'tfrueals,', '10') AS status\n FROM table_name\n)\n CREATE TABLE table_name ( customer, products, products_trial_status ) AS\nSELECT 234253, 'A,B,C', 'false,true,false' FROM DUAL UNION ALL\nSELECT 923403, 'A,C', 'true,true' FROM DUAL UNION ALL\nSELECT 123483, 'B', 'true' FROM DUAL UNION ALL\nSELECT 239874, 'B,C', 'false,false' FROM DUAL;\n SELECT customer\nFROM (\n SELECT customer,\n SUBSTR(','||products, 1, INSTR(','||products||',', ',B,')) AS preceding_terms,\n TRANSLATE(products_trial_status, 'tfrueals,', '10') AS status\n FROM table_name\n WHERE INSTR(','||products||',', ',B,') > 0\n)\nWHERE SUBSTR(\n status,\n LENGTH(preceding_terms) - COALESCE(LENGTH(REPLACE(preceding_terms, ',')), 0),\n 1\n ) = '1'\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74561897",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20591134/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.