qid int64 4 22.2M | question stringlengths 18 48.3k | answers list | date stringlengths 10 10 | metadata list |
|---|---|---|---|---|
74,382,696 | <p>i'm having a real brain fart atm. i have a simple getBalance function on a contract that accepts a wallet. this returns the balance, but as you know it's the BigNumber of the balance and doesnt factor in the decimals. So how do i turn:</p>
<p>806179086037007</p>
<p>into 806179.086037007</p>
<p>where the decimals for this given contract is 9.</p>
<pre><code>const contract = new web3.eth.Contract(minABI, contractName);
const decimals = await contract.methods.decimals().call();
const balance = await contract.methods
.balanceOf(address)
.call();
</code></pre>
<p>Ive tried varous solutions that i've found online and cant seem to get the value i want.</p>
| [
{
"answer_id": 74382824,
"author": "pilchard",
"author_id": 13762301,
"author_profile": "https://Stackoverflow.com/users/13762301",
"pm_score": 2,
"selected": true,
"text": "current.type"
},
{
"answer_id": 74383084,
"author": "dtm",
"author_id": 20320613,
"author_profile": "https://Stackoverflow.com/users/20320613",
"pm_score": -1,
"selected": false,
"text": "const a = [\n {\n type: \"heading\",\n content: \"whatever\"\n },\n {\n type: \"para\",\n content: \"whatever\"\n },\n {\n type: \"para\",\n content: \"whatever\"\n },\n {\n type: \"list_item\",\n content: \"whatever 1\"\n },\n {\n type: \"list_item\",\n content: \"whatever 2\"\n },\n {\n type: \"list_item\",\n content: \"whatever 3\"\n },\n {\n type: \"para\",\n content: \"whatever\"\n },\n {\n type: \"heading\",\n content: \"whatever\"\n },\n {\n type: \"para\",\n content: \"whatever\"\n },\n {\n type: \"para\",\n content: \"whatever\"\n },\n {\n type: \"list_item\",\n content: \"whatever 4\"\n },\n {\n type: \"list_item\",\n content: \"whatever 5\"\n },\n {\n type: \"list_item\",\n content: \"whatever 6\"\n },\n {\n type: \"list_item\",\n content: \"whatever 7\"\n },\n {\n type: \"para\",\n content: \"whatever\"\n },\n ]\n let listItemContent = [];\n const res = a.reduce((total, v) => {\n if(v.type === \"list_item\") {\n listItemContent.push(v.content);\n }\n else if(listItemContent.length > 0) {\n total.push({type: \"list\", content: listItemContent});\n listItemContent = [];\n } else {\n total.push(v);\n }\n return total;\n }, []);\n if(listItemContent.length > 0) {\n res.push({type: \"list\", content: listItemContent});\n }\n console.log(res)"
},
{
"answer_id": 74385378,
"author": "trincot",
"author_id": 5459839,
"author_profile": "https://Stackoverflow.com/users/5459839",
"pm_score": 1,
"selected": false,
"text": "reduce"
}
] | 2022/11/09 | [
"https://Stackoverflow.com/questions/74382696",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/652318/"
] |
74,382,707 | <p>I am very new to Python (Only a couple weeks) and I'm trying to make a rock paper scissors game for Replits 100 days of code. My previous game was very simple and worked fine but it wont fly as a template for this lesson so I've started from scratch but I'm having trouble.</p>
<pre><code>from getpass import getpass as hinput
ch1 = hinput("Enter",p1,"choice: ")
</code></pre>
<p>I keep getting this error after the players enter the names</p>
<pre><code>Traceback (most recent call last):
File "main.py", line 2, in <module>
ch1 = hinput("Enter",p1,"choice: ")
TypeError: unix_getpass() takes from 0 to 2 positional arguments but 3 were given
</code></pre>
| [
{
"answer_id": 74382734,
"author": "Geoffrey Negiar",
"author_id": 5173924,
"author_profile": "https://Stackoverflow.com/users/5173924",
"pm_score": 0,
"selected": false,
"text": "hinput(f\"Enter {p1} choice: \")\n"
},
{
"answer_id": 74382736,
"author": "Silvio Mayolo",
"author_id": 2288659,
"author_profile": "https://Stackoverflow.com/users/2288659",
"pm_score": 3,
"selected": true,
"text": "getpass"
}
] | 2022/11/09 | [
"https://Stackoverflow.com/questions/74382707",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20095437/"
] |
74,382,713 | <p>I am getting a build error when using the <code>vision-camera-code-scanner</code> package for my react native project.</p>
<p>The short hand error is:</p>
<blockquote>
<p>Undefined symbols for architecture x86_64</p>
</blockquote>
<p>The full error is the following:</p>
<pre><code>ld: warning: ignoring file /XXXXXXXXXXXXXXXXXXX/Build/Products/Debug-iphonesimulator/vision-camera-code-scanner/libvision-camera-code-scanner.a, building for iOS Simulator-x86_64 but attempting to link with file built for iOS Simulator-arm64
Undefined symbols for architecture x86_64:
Undefined symbols for architecture x86_64:
"_GPBClearOneof", referenced from:
_MLKITx_EPTFlagValue_ClearValueOneOfCase in MLKitCommon(FlagValues.pbobjc.o)
_MLKITx_PHENORegistrationInfo_ClearPackageVersionOneOfCase in MLKitCommon(RegistrationInfo.pbobjc.o)
_MLKITx_PHENORegistrationInfo_ClearApplicationInfoOneOfCase in MLKitCommon(RegistrationInfo.pbobjc.o)
_MLKITx_CLCCCounter_ClearCounterIdOneOfCase in MLKitCommon(Counters.pbobjc.o)
"_GULLogBasic", referenced from:
_MLKLog in MLKitCommon(MLKLogger.o)
"_OBJC_CLASS_$_GDTCORTransport", referenced from:
objc-class-ref in MLKitCommon(MLKFirelogTransport.o)
"_OBJC_CLASS_$_GPBCodedOutputStream", referenced from:
objc-class-ref in MLKitCommon(CCTLogOutputStream.o)
"_OBJC_CLASS_$_GPBDescriptor", referenced from:
objc-class-ref in MLKitCommon(Experiments.pbobjc.o)
objc-class-ref in MLKitCommon(Metalog.pbobjc.o)
objc-class-ref in MLKitCommon(FlatFile.pbobjc.o)
objc-class-ref in MLKitCommon(Clientanalytics.pbobjc.o)
objc-class-ref in MLKitCommon(FirebaseMlSdk.pbobjc.o)
objc-class-ref in MLKitCommon(UploaderState.pbobjc.o)
objc-class-ref in MLKitCommon(DeviceExperimentIds.pbobjc.o)
...
"_OBJC_CLASS_$_GPBEnumArray", referenced from:
objc-class-ref in MLKitBarcodeScanning
objc-class-ref in MLKitVision(GMVLogger.o)
"_OBJC_CLASS_$_GPBEnumDescriptor", referenced from:
objc-class-ref in MLKitCommon(Experiments.pbobjc.o)
objc-class-ref in MLKitCommon(FlatFile.pbobjc.o)
objc-class-ref in MLKitCommon(Clientanalytics.pbobjc.o)
objc-class-ref in MLKitCommon(FirebaseMlSdk.pbobjc.o)
objc-class-ref in MLKitCommon(Barhopper.pbobjc.o)
objc-class-ref in MLKitCommon(IosAccessibilityState.pbobjc.o)
objc-class-ref in MLKitCommon(PhenotypeLog.pbobjc.o)
...
"_OBJC_CLASS_$_GPBFileDescriptor", referenced from:
objc-class-ref in MLKitCommon(Experiments.pbobjc.o)
objc-class-ref in MLKitCommon(Metalog.pbobjc.o)
objc-class-ref in MLKitCommon(FlatFile.pbobjc.o)
objc-class-ref in MLKitCommon(Clientanalytics.pbobjc.o)
objc-class-ref in MLKitCommon(FirebaseMlSdk.pbobjc.o)
objc-class-ref in MLKitCommon(UploaderState.pbobjc.o)
objc-class-ref in MLKitCommon(DeviceExperimentIds.pbobjc.o)
...
"_OBJC_CLASS_$_GPBInt32Array", referenced from:
objc-class-ref in MLKitCommon(CCTClearcutLogEvent.o)
"_OBJC_CLASS_$_GPBMessage", referenced from:
_OBJC_CLASS_$_MLKITx_EXHParam in MLKitCommon(Experiments.pbobjc.o)
_OBJC_CLASS_$_MLKITx_EXHParam_ExtensionValue in MLKitCommon(Experiments.pbobjc.o)
_OBJC_CLASS_$_MLKITx_EXHDeviceAccount in MLKitCommon(Experiments.pbobjc.o)
_OBJC_CLASS_$_MLKITx_EXHScope in MLKitCommon(Experiments.pbobjc.o)
_OBJC_CLASS_$_MLKITx_EXHParamPartition in MLKitCommon(Experiments.pbobjc.o)
_OBJC_CLASS_$_MLKITx_EXHCrossAppDescriptor in MLKitCommon(Experiments.pbobjc.o)
_OBJC_CLASS_$_MLKITx_EXHConfigurationTier in MLKitCommon(Experiments.pbobjc.o)
...
"_OBJC_CLASS_$_GPBRootObject", referenced from:
_OBJC_CLASS_$_MLKITx_EXHExperimentsRoot in MLKitCommon(Experiments.pbobjc.o)
_OBJC_CLASS_$_MLKITx_CADPMetalogRoot in MLKitCommon(Metalog.pbobjc.o)
_OBJC_CLASS_$_MLKITx_EPIFlatFileRoot in MLKitCommon(FlatFile.pbobjc.o)
_OBJC_CLASS_$_MLKITx_CADPClientanalyticsRoot in MLKitCommon(Clientanalytics.pbobjc.o)
_OBJC_CLASS_$_MLKITx_FBMLFirebaseMlSdkRoot in MLKitCommon(FirebaseMlSdk.pbobjc.o)
_OBJC_CLASS_$_MLKITx_CCTUploaderStateRoot in MLKitCommon(UploaderState.pbobjc.o)
_OBJC_CLASS_$_MLKITx_EXHDeviceExperimentIdsRoot in MLKitCommon(DeviceExperimentIds.pbobjc.o)
...
"_OBJC_CLASS_$_GTMLogMininumLevelFilter", referenced from:
objc-class-ref in MLKitCommon(GIPLoggingReroutingGTMLogger.o)
"_OBJC_CLASS_$_GTMLogger", referenced from:
objc-class-ref in MLKitCommon(PHTInternalHeterodyneSyncer.o)
objc-class-ref in MLKitCommon(PHTHeterodyneSyncer.o)
objc-class-ref in MLKitCommon(GIPPseudonymousIDStore.o)
objc-class-ref in MLKitCommon(CCTLogOutputStream.o)
objc-class-ref in MLKitCommon(CCTClearcutUploader.o)
objc-class-ref in MLKitCommon(CCTClearcutMetaLogger.o)
objc-class-ref in MLKitCommon(CCTClearcutFileUtility.o)
...
"_OBJC_CLASS_$_GTMSessionCookieStorage", referenced from:
objc-class-ref in MLKitCommon(CCTClearcutUploader.o)
"_OBJC_CLASS_$_GTMSessionFetcher", referenced from:
objc-class-ref in MLKitCommon(CCTClearcutUploader.o)
"_OBJC_CLASS_$_GTMSessionFetcherService", referenced from:
objc-class-ref in MLKitCommon(PHTFlatFilePhenotype.o)
objc-class-ref in MLKitCommon(MLKModelDownloader.o)
objc-class-ref in MLKitVision(GMVCloudVisionClient.o)
"_OBJC_CLASS_$_GULCCComponent", referenced from:
objc-class-ref in MLKitCommon(MLKCustomModelManager.o)
"_OBJC_CLASS_$_GULCCComponentContainer", referenced from:
objc-class-ref in MLKitCommon(MLKContext.o)
objc-class-ref in MLKitCommon(MLKCustomModelManager.o)
"_OBJC_CLASS_$_GULCCComponentType", referenced from:
objc-class-ref in MLKitCommon(MLKModelManager.o)
objc-class-ref in MLKitCommon(MLKContext.o)
objc-class-ref in MLKitCommon(MLKCustomModelManager.o)
"_OBJC_CLASS_$_GULUserDefaults", referenced from:
objc-class-ref in MLKitCommon(MLKModelPreferencesManager.o)
objc-class-ref in MLKitCommon(MLKAnalyticsLogger.o)
objc-class-ref in MLKitCommon(MLKModelDownloader.o)
"_OBJC_CLASS_$_RCTBridge", referenced from:
objc-class-ref in AppDelegate.o
"_OBJC_CLASS_$_RCTBundleURLProvider", referenced from:
objc-class-ref in AppDelegate.o
"_OBJC_METACLASS_$_GPBMessage", referenced from:
_OBJC_METACLASS_$_MLKITx_EXHParam in MLKitCommon(Experiments.pbobjc.o)
_OBJC_METACLASS_$_MLKITx_EXHParam_ExtensionValue in MLKitCommon(Experiments.pbobjc.o)
_OBJC_METACLASS_$_MLKITx_EXHDeviceAccount in MLKitCommon(Experiments.pbobjc.o)
_OBJC_METACLASS_$_MLKITx_EXHScope in MLKitCommon(Experiments.pbobjc.o)
_OBJC_METACLASS_$_MLKITx_EXHParamPartition in MLKitCommon(Experiments.pbobjc.o)
_OBJC_METACLASS_$_MLKITx_EXHCrossAppDescriptor in MLKitCommon(Experiments.pbobjc.o)
_OBJC_METACLASS_$_MLKITx_EXHConfigurationTier in MLKitCommon(Experiments.pbobjc.o)
...
"_OBJC_METACLASS_$_GPBRootObject", referenced from:
_OBJC_METACLASS_$_MLKITx_EXHExperimentsRoot in MLKitCommon(Experiments.pbobjc.o)
_OBJC_METACLASS_$_MLKITx_CADPMetalogRoot in MLKitCommon(Metalog.pbobjc.o)
_OBJC_METACLASS_$_MLKITx_EPIFlatFileRoot in MLKitCommon(FlatFile.pbobjc.o)
_OBJC_METACLASS_$_MLKITx_CADPClientanalyticsRoot in MLKitCommon(Clientanalytics.pbobjc.o)
_OBJC_METACLASS_$_MLKITx_FBMLFirebaseMlSdkRoot in MLKitCommon(FirebaseMlSdk.pbobjc.o)
_OBJC_METACLASS_$_MLKITx_CCTUploaderStateRoot in MLKitCommon(UploaderState.pbobjc.o)
_OBJC_METACLASS_$_MLKITx_EXHDeviceExperimentIdsRoot in MLKitCommon(DeviceExperimentIds.pbobjc.o)
...
"_OBJC_METACLASS_$_GTMLogger", referenced from:
_OBJC_METACLASS_$_MLKITx_GIPLoggingReroutingGTMLogger in MLKitCommon(GIPLoggingReroutingGTMLogger.o)
"_RCTAppSetupDefaultRootView", referenced from:
-[AppDelegate application:didFinishLaunchingWithOptions:] in AppDelegate.o
"_RCTAppSetupPrepareApp", referenced from:
-[AppDelegate application:didFinishLaunchingWithOptions:] in AppDelegate.o
"_kGTMSessionFetcherStatusDomain", referenced from:
___91-[MLKITx_PHTInternalHeterodyneSyncer syncHoldingLockWithSyncedScopes:fetchReason:callback:]_block_invoke in MLKitCommon(PHTInternalHeterodyneSyncer.o)
___150-[MLKITx_PHTHeterodyneSyncer batchSyncWithAccounts:syncedScopes:fetchReason:throttlingCache:heterodyneSyncInfo:accountToAuthToken:lastError:callback:]_block_invoke in MLKitCommon(PHTHeterodyneSyncer.o)
___69-[MLKModelDownloader beginModelDownloadWithURL:modelInfo:conditions:]_block_invoke.285 in MLKitCommon(MLKModelDownloader.o)
___63-[MLKITx_GMVCloudVisionClient initWithCloudUri:apiKey:options:]_block_invoke in MLKitVision(GMVCloudVisionClient.o)
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
</code></pre>
<p>I have tried to fix the issue by running: <code>pod deintegrate && pod cache clean --all</code> and then <code>pod install</code> in the ios directory as per the following similar <a href="https://stackoverflow.com/questions/42292090/firebase-undefined-symbols-for-architecture-x86-64">question</a>.</p>
<p>Sadly this didnt fix the issue i also tried the steps suggested in the following <a href="https://github.com/mrousavy/react-native-vision-camera/issues/914" rel="nofollow noreferrer">thread</a>: namely excluding the target arm64. But this also didnt fix the error.</p>
<p>I also read the following on this github <a href="https://github.com/rodgomesc/vision-camera-code-scanner/issues/79#issuecomment-1303777013" rel="nofollow noreferrer">thread</a>:</p>
<blockquote>
<p>It's related to the fact that Google MLKit Team does not ship ARM simulator binaries and we can't compile ourselves because the source code is not public</p>
</blockquote>
<p>So now i am a bit lost what to do.<br />
Any help or suggestions greatly appreciated.</p>
<p>Working on mac book pro M1 14 inch<br />
running latest version of react native</p>
<p>If additional information is needed please let me know so i can add it to the question.</p>
| [
{
"answer_id": 74382734,
"author": "Geoffrey Negiar",
"author_id": 5173924,
"author_profile": "https://Stackoverflow.com/users/5173924",
"pm_score": 0,
"selected": false,
"text": "hinput(f\"Enter {p1} choice: \")\n"
},
{
"answer_id": 74382736,
"author": "Silvio Mayolo",
"author_id": 2288659,
"author_profile": "https://Stackoverflow.com/users/2288659",
"pm_score": 3,
"selected": true,
"text": "getpass"
}
] | 2022/11/09 | [
"https://Stackoverflow.com/questions/74382713",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5716477/"
] |
74,382,727 | <p>I would like to allow the user to select multiple times the same choice. It implies that when the user selects some element, it should not be removed from the choices' dropdown menu.</p>
<p>Here is a minimal reproducible example:</p>
<pre><code>library(shiny)
ui <- fluidPage(
selectInput(
inputId = "ManyDuplicated",
label = 'SelectInput',
choices = c('Hello', 'World'),
selected = NULL,
multiple = TRUE
)
)
server <- function(input, output) {
}
shinyApp(ui = ui, server = server)
</code></pre>
<p>How it is:</p>
<p><a href="https://i.stack.imgur.com/mVXtq.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/mVXtq.png" alt="How it is" /></a></p>
<p>How I would like it to be:</p>
<p><a href="https://i.stack.imgur.com/p3DYG.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/p3DYG.png" alt="How I would like it to be" /></a></p>
<hr />
<p>What I tried and may be of help:</p>
<p>This code (<a href="https://github.com/rstudio/shiny/issues/2939#issuecomment-678269674" rel="nofollow noreferrer">https://github.com/rstudio/shiny/issues/2939#issuecomment-678269674</a>) works perfectly for a single choice ("^" in the case). However, I can't make it work for more choices (c("^", "a"), for example).</p>
<pre><code>library(shiny)
ui <- fluidPage(
selectInput("x", "choose", c("^" = 1), multiple = TRUE)
)
server <- function(input, output, session) {
observeEvent(input$x, {
choices <- seq_len(length(input$x)+1)
names(choices) <- rep("^", length(choices))
updateSelectInput(session, "x", choices = choices, selected = isolate(input$x))
})
}
shinyApp(ui, server)
</code></pre>
| [
{
"answer_id": 74382734,
"author": "Geoffrey Negiar",
"author_id": 5173924,
"author_profile": "https://Stackoverflow.com/users/5173924",
"pm_score": 0,
"selected": false,
"text": "hinput(f\"Enter {p1} choice: \")\n"
},
{
"answer_id": 74382736,
"author": "Silvio Mayolo",
"author_id": 2288659,
"author_profile": "https://Stackoverflow.com/users/2288659",
"pm_score": 3,
"selected": true,
"text": "getpass"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74382727",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15881999/"
] |
74,382,739 | <p>How can I make sure that the postcode corresponding to a name in worksheet 1 matches the address for the same name in worksheet 2.</p>
<p>For example, I would need a column with a vlookup or index/match formula that would check <code>Alice</code>'s postcode from worksheet 1 against <code>Alice</code>s postcode in worksheet 2 and return true for a match of the postcode or false if the postcode is different.</p>
<p>Worksheet 1</p>
<pre><code>Name Address DOB Post code
Alice Berlin 1980 W2
Bob London 1979 EC1
</code></pre>
<p>Worksheet 2</p>
<pre><code>Name Address Post Code DOB
Alice London EC 1979
Alice Berlin W2 1980
</code></pre>
<p>I don't think a vlookup is ideal because of performance and column positioning.</p>
| [
{
"answer_id": 74382953,
"author": "David Leal",
"author_id": 6237093,
"author_profile": "https://Stackoverflow.com/users/6237093",
"pm_score": 2,
"selected": true,
"text": "VLOOKUP"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74382739",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1016900/"
] |
74,382,754 | <p>I am using excel 2019 and I am trying to extract from a bunch of messed up text cells any (up to 5) word ending with dot that comes after a ].</p>
<p>This is a sample of the text I am trying to parse/clean
`</p>
<pre><code>some text [asred.] ost. |Monday - Ribben (ult.) lot. ac, sino. other maybe long text; collan.
</code></pre>
<p>`</p>
<p>I expect to get this:
<code>ost. ult. lot. sino. collan.</code></p>
<p>I am using this Function found somewhere on the internet which appears to do the job:
`</p>
<pre><code>Public Function RegExtract(Txt As String, Pattern As String) As String
With CreateObject("vbscript.regexp")
'.Global = True
.Pattern = Pattern
If .test(Txt) Then
RegExtract = .Execute(Txt)(0)
Else
RegExtract = "No match found"
End If
End With
End Function
</code></pre>
<p>`</p>
<p>and I call it from an empty cell:
<code>=RegExtract(D2; "([\]])(\s\w+[.]){0,5}")</code></p>
<p>It's the first time I am using regexp, so I might have done terrible things in the eyes of an expert.</p>
<p>So this is my expression: ([]])(\s\w+[.]){0,5}</p>
<p>Right now it returns only
<code>] ost.</code></p>
<p>Which is much more than I was expecting to be able to do on my first approach to regex, but:</p>
<ol>
<li>I am not able to get rid of the first ] which is needed to find the place where my useful bits start inside the text block, since \K does not work in excel. I might "find and replace" it later as a smart barbarian, but I'd like to know the way to do it clean, if any clean way exists :)</li>
</ol>
<p>2)I don't understand how iterators work to get all my "up to 5 occurrencies": I was expecting that {0,5} after the second group meant exactly: "repeat the previous group again until the end of the text block (or until you manage to do it 5 times)".</p>
<p>Thank you for your time :)</p>
<p>--Added after JdvD accepted answer for the records--</p>
<p>I am using this pattern to get all the words ending with dot, after the FIRST occurrence of the closing bracket.</p>
<pre><code>^.*?\]|(\w+\.\s?)|.
</code></pre>
<p>This one (without the question mark) instead gets all the words ending with dot, after the LAST occurrence of the closing bracket.</p>
<pre><code>^.*\]|(\w+\.\s?)|.
</code></pre>
<p>I was even missing something in my regExtract function: I needed to store the matches into an array through a for loop and then output this array as a string.
I was wrongly assuming that the regex engine was already storing matches as a unique string.</p>
<p>The correct RegExtract function to extract EVERY match is the following:</p>
<pre><code>Public Function RegExtract(Txt As String, Pattern As String) As String
Dim rMatch As Object, arrayMatches(), i As Long
With CreateObject("vbscript.regexp")
.Global = True
.Pattern = Pattern
If .Test(Txt) Then
For Each rMatch In .Execute(Txt)
If Not IsEmpty(rMatch.SubMatches(0)) Then
ReDim Preserve arrayMatches(i)
arrayMatches(i) = rMatch.SubMatches(0)
i = i + 1
End If
Next
RegExtract = Join(arrayMatches, " ")
Else
RegExtract = "No match found"
End If
End With
End Function
</code></pre>
| [
{
"answer_id": 74383189,
"author": "RemDosal",
"author_id": 20452901,
"author_profile": "https://Stackoverflow.com/users/20452901",
"pm_score": 1,
"selected": false,
"text": "([a-zA-Z]+)\\.\n"
},
{
"answer_id": 74383421,
"author": "Ron Rosenfeld",
"author_id": 2872922,
"author_profile": "https://Stackoverflow.com/users/2872922",
"pm_score": 2,
"selected": false,
"text": "]"
},
{
"answer_id": 74386101,
"author": "JvdV",
"author_id": 9758194,
"author_profile": "https://Stackoverflow.com/users/9758194",
"pm_score": 3,
"selected": true,
"text": "^.*\\]|(\\w+\\.)\n"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74382754",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20463613/"
] |
74,382,776 | <p>In the code shown below, I have a function that adds an object to an array. This object has a property named status which has a value of true. An addEventListener for a button named "check for true object" is able to access the 'true' object and log it in the console. I also have an addEventListener for a button which adds another object to the array. This added object also has a property named status which has a value of false. Then, there is an addEventListener for a button named "check for false object" which is to access the added 'false' object and log it in the console. However, when this "check for false object" button is clicked, it logs <code>undefined</code> even though the 'false' object has already been aded to the array. How can I solve this problem?</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 button1 = document.querySelector('#btn-one');
const button2 = document.querySelector('#btn-two');
const button3 = document.querySelector('#btn-three');
const MainArrayModule = (() => {
let mainArray = [];
function MainArrayObjCreator(name, status) {
return {name, status};
}
function createMainArrayObj() {
let mainObj = MainArrayObjCreator('main', true);
mainArray.push(mainObj);
console.log(mainArray);
button1.addEventListener('click', () => {
let otherObj = MainArrayObjCreator('other', false);
mainArray.push(otherObj);
console.log(mainArray);
});
}
return {mainArray, createMainArrayObj};
})();
const CheckArrayModule = (() => {
MainArrayModule.createMainArrayObj();
let trueObject = MainArrayModule.mainArray.find(object => object.status === true);
let falseObject = MainArrayModule.mainArray.find(object => object.status === false);
function logObject() {
button2.addEventListener('click', () => {
console.log(trueObject);
});
button3.addEventListener('click', () => {
console.log(falseObject);
});
}
return {logObject};
})();
const runFunctions = (() => {
CheckArrayModule.logObject();
})();</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
display: flex;
height: 100vh;
justify-content: space-evenly;
align-items: center;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><button id="btn-one">
Add 'false' object
</button>
<button id="btn-two">
Check for 'true' object
</button>
<button id="btn-three">
Check for 'false' object
</button></code></pre>
</div>
</div>
</p>
| [
{
"answer_id": 74383189,
"author": "RemDosal",
"author_id": 20452901,
"author_profile": "https://Stackoverflow.com/users/20452901",
"pm_score": 1,
"selected": false,
"text": "([a-zA-Z]+)\\.\n"
},
{
"answer_id": 74383421,
"author": "Ron Rosenfeld",
"author_id": 2872922,
"author_profile": "https://Stackoverflow.com/users/2872922",
"pm_score": 2,
"selected": false,
"text": "]"
},
{
"answer_id": 74386101,
"author": "JvdV",
"author_id": 9758194,
"author_profile": "https://Stackoverflow.com/users/9758194",
"pm_score": 3,
"selected": true,
"text": "^.*\\]|(\\w+\\.)\n"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74382776",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19747345/"
] |
74,382,817 | <p>I am new to python and I seem to be unable to understand the concept in Start:Stop:Step. For example</p>
<p>word = "Champ"
print (word[0:5:2])</p>
<p>why do I get cap as I result ? if someone could help me with this I would truly appreciated</p>
<p>I tried using different numbers to see what the outcome was but even there I was not able to understand why was I getting that outcome</p>
| [
{
"answer_id": 74382853,
"author": "MM-Borhan ",
"author_id": 20463099,
"author_profile": "https://Stackoverflow.com/users/20463099",
"pm_score": 1,
"selected": false,
"text": "word = \"Champ\"\n\nprint (word[0:5:2])\n# you are taking index=0, then index=0+2, then index=0+2+2\n# then index=0+2+2+2 (don't have this)\n# so you got 0,2, and 4\n# Hope, makes sense\n\nprint(word[0])\nprint(word[2])\nprint(word[4])\n"
},
{
"answer_id": 74389870,
"author": "Steinn Hauser Magnusson",
"author_id": 13819183,
"author_profile": "https://Stackoverflow.com/users/13819183",
"pm_score": 0,
"selected": false,
"text": "while"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74382817",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19411276/"
] |
74,382,820 | <p>Right now the text aligns underneath the image. I want the text to be beside the image vertically. I tried to add <code>flex-direction: column</code> and <code>justify-content: center</code> but it's not working. I also tried <code>float</code> and it didn't work. I can't figure out how to align the text and image side by side. How can I make it so that they align beside each other? Are there errors in my 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>.whoweare {
padding: 80px 0px 50px;
background-color: #000000;
}
.whoweare #whoweareimg {
width: 100%;
min-width: 200px;
}
.whoweare .content {
-webkit-display: flex;
display: flex;
flex-wrap: wrap;
/* flex-direction: column; */
/* justify-content: center; */
}
.whoweare .content .box {
/* padding:5px;
flex:0 0 100%;
max-width: 100%; */
padding: 5px;
flex: 0 0 100%;
max-width: 100%;
}
.whoweare .content #whoweareimg {
width: 50%;
-webkit-transform: rotateY(180deg);
transform: rotateY(180deg);
padding: 30px;
}
.whoweare .content h2 {
font-size: 50px;
font-weight: 500;
margin: 20px;
color: #ffffff;
padding: 0px 0px 20px;
}
.whoweare .content p {
font-size: 20px;
line-height: 50px;
color: #ffffff;
margin: 20px;
padding: 0px 0px 20px;
font-family: 'Open Sans', sans-serif;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><section class="whoweare" id="whoweare">
<div class="container">
<div class="content">
<div class="box text wow slideInRight">
<!-- <div class="class-items"> -->
<div class="item wow bounceInUp">
<!-- <div class="item-img"> -->
<img id="whoweareimg" src="https://via.placeholder.com/50" alt="classes" />
</div>
<div class="box text wow slideInRight">
<h2>Who we are</h2>
<p>UNDRGRND Muscle & Fitness, where street culture meets the bodybuilding and fitness lifestyle. Our goal is to provide our members with a unique state of the art training experience in the Vaughan/GTA.
</br>
</br>
Experience a one of a kind training atmosphere to help fuel workouts like no other. Exclusive training sessions from IFBB pro athletes will be available in order for members to reach their lifestyle and/or contest prep goals. The facility will provide the best fitness equipment on the market ranging from Atlantis, Cyber, Arsenal, and more.
</br>
</br>
We are all part of a family and all in this together here at UNDRNRGD.</p>
</div>
</div>
</div>
</div>
</section></code></pre>
</div>
</div>
</p>
| [
{
"answer_id": 74382853,
"author": "MM-Borhan ",
"author_id": 20463099,
"author_profile": "https://Stackoverflow.com/users/20463099",
"pm_score": 1,
"selected": false,
"text": "word = \"Champ\"\n\nprint (word[0:5:2])\n# you are taking index=0, then index=0+2, then index=0+2+2\n# then index=0+2+2+2 (don't have this)\n# so you got 0,2, and 4\n# Hope, makes sense\n\nprint(word[0])\nprint(word[2])\nprint(word[4])\n"
},
{
"answer_id": 74389870,
"author": "Steinn Hauser Magnusson",
"author_id": 13819183,
"author_profile": "https://Stackoverflow.com/users/13819183",
"pm_score": 0,
"selected": false,
"text": "while"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74382820",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20413531/"
] |
74,382,856 | <p>My CSV files with whitespace:</p>
<pre><code>Id ; FirstName ; LastName ; email
123; Marc ; TOTO ; marc@toto.com
</code></pre>
<p>I would like delete whitespace in my csv by line like this :</p>
<pre><code>Id;FirstName;LastName;email
123;Marc;TOTO;marc@toto.com
</code></pre>
<p>I would use a regex in Perl.</p>
| [
{
"answer_id": 74382946,
"author": "Dave Pritlove",
"author_id": 2005666,
"author_profile": "https://Stackoverflow.com/users/2005666",
"pm_score": 0,
"selected": false,
"text": "awk '{OFS=\"\";$1=$1;print $0}' file.csv;\n"
},
{
"answer_id": 74383677,
"author": "tshiono",
"author_id": 8572380,
"author_profile": "https://Stackoverflow.com/users/8572380",
"pm_score": 0,
"selected": false,
"text": "remove spaces at the end of each line"
},
{
"answer_id": 74385557,
"author": "zdim",
"author_id": 4653379,
"author_profile": "https://Stackoverflow.com/users/4653379",
"pm_score": 2,
"selected": false,
"text": ";"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74382856",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12750226/"
] |
74,382,857 | <p>I have 2 tables Customer and Orders.</p>
<p>1st question:</p>
<p>That is a master table for Customers that have a few columns like Customer number, customer name, Active flag, etc. Table may contain 2 or more records for the same customer number but as per the business logic only 1 records at a time should ideally be ACTIVE. I need to find customers that have only 1 record and it should be active.</p>
<p>query that I have written:</p>
<pre><code>select customer_number, count(*)
from customers c
where active = false
group by customer_number
having count(*) = 1;
</code></pre>
<p>This returns me the customers that have 2 records and only 1 is NOT ACTIVE.</p>
<p>Question 2:</p>
<p>Apart from customer table we have another table that is Orders table, it contains columns like Customer number(as same in Customers table), deliver date, order number, insert time.
I need to find the customers whose ACTIVE is false, and have not given any orders since 180 days. (INSERT TIME::date - 180).</p>
<p>what I have tried is not giving me the desired output, as on back testing I found that the data is wrong</p>
<pre><code>select om.customer_number,
c.customer_name,
om.deliverydate,
om.insert_time
from customers c, order_master om
where
om.customer_number in
(
select c2.customer_number
from customers c2
where c2.active = false
group by c2.customer_number
having count(*) =1
)
and c.customer_number = om.customer_number
group by om.customer_number, c.customer_name,
om.deliverydate, om.insert_time
having max(om.insert_time::date) < '2022-06-01' ;
</code></pre>
<p>The queries that I have tried, I have already mentioned them in my question. Please check that.</p>
| [
{
"answer_id": 74382946,
"author": "Dave Pritlove",
"author_id": 2005666,
"author_profile": "https://Stackoverflow.com/users/2005666",
"pm_score": 0,
"selected": false,
"text": "awk '{OFS=\"\";$1=$1;print $0}' file.csv;\n"
},
{
"answer_id": 74383677,
"author": "tshiono",
"author_id": 8572380,
"author_profile": "https://Stackoverflow.com/users/8572380",
"pm_score": 0,
"selected": false,
"text": "remove spaces at the end of each line"
},
{
"answer_id": 74385557,
"author": "zdim",
"author_id": 4653379,
"author_profile": "https://Stackoverflow.com/users/4653379",
"pm_score": 2,
"selected": false,
"text": ";"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74382857",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20463793/"
] |
74,382,862 | <p>I have a "default" image file that's meant to be used if the "proper" image file doesn't exist. I'm using Maven to create the <code>jar</code> and have placed the file under <code>resources/images</code>, along with the other images I already have.</p>
<p>The file is defined in a class that has a few defaults:</p>
<pre><code>public class Defaults {
public static final File BLANK_IMAGE = new File(relative_path_to_image);
//Other defaults
}
</code></pre>
<p>This works within the IDE, but not if I try to create a <code>jar</code> - if I do and run it from the Command Prompt, it spits out the message I wrote for when a specific file can't be found.</p>
<p>I've looked at several potential solutions, but they all rely on non-static methods, which can't be used here since the <code>File</code> is static (also, it makes no sense to instantiate something when all its instances would be identical - that's just a waste of time and resources).</p>
<p>Am I just stuck converting the <code>File</code> to a <code>String</code> and processing it inside every <code>Object</code> that needs it with <code>getResourceAsStream()</code>?</p>
<p>The file is placed on a few <code>JLabel</code> instances (ones that are meant to have images that haven't been created yet) by first converting it into a <code>BufferedImage</code>. I mention this in case there are better ways of achieving the same result that bypass the problem I'm having.</p>
| [
{
"answer_id": 74383530,
"author": "rzwitserloot",
"author_id": 768644,
"author_profile": "https://Stackoverflow.com/users/768644",
"pm_score": 3,
"selected": true,
"text": "new File"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74382862",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12247094/"
] |
74,382,869 | <p><a href="https://i.stack.imgur.com/k3jQ3.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/k3jQ3.png" alt="This is the file directory and server.js and a preview of what the website looks like with the error " /></a></p>
<p>I was excpeting the partial to show up as the header and the partial code is this
`</p>
<pre><code><header>
<a href="/">Home</a>
<ul>
<li><a href="/upload">upload</a></li>
<li><a href="/library">Library</a></li>
</ul>
</header>
</code></pre>
<p>`</p>
<p>along with this I call the partial from my template and I call it here.</p>
<p>`</p>
<pre><code><body>
{{> header}}
{{{body}}}
</body>
</code></pre>
<p>`
My template works just fine and switching pages works fine to I just cant get the partial to work.</p>
<p>I have tried changing the file name, tried all diffrent file paths, printed the file path. (it was the right file path) I have also tried all the solutions I could find on here and took a look at the docs. I have double checked my code and file path with a 3 tutorials on youtube all of them are the same as what I have. None of these changed the output any help is greatly appreciated.</p>
| [
{
"answer_id": 74383530,
"author": "rzwitserloot",
"author_id": 768644,
"author_profile": "https://Stackoverflow.com/users/768644",
"pm_score": 3,
"selected": true,
"text": "new File"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74382869",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14216814/"
] |
74,382,919 | <p>Drag a corner of an image in DM triggers the image content refreshed to the new window size. What is the DM script command to trigger that refreshing?</p>
<p>Specifically, I want to add a text below the image. So, I get the imageDocument as root component, add a text annotation below the image (the vertical position of the text is beyond the bottom border of the image). Without "imgDoc.ImageDocumentSwitchToPageMode()", the text is not visible. When I change the image size with mouse, the image content is updated and the text is shown. Looking for script doing that.</p>
<p>Thanks,</p>
| [
{
"answer_id": 74383530,
"author": "rzwitserloot",
"author_id": 768644,
"author_profile": "https://Stackoverflow.com/users/768644",
"pm_score": 3,
"selected": true,
"text": "new File"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74382919",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6406828/"
] |
74,382,927 | <p>I am trying to install the macport demeter using the following line in mac terminal:</p>
<pre><code>sudo port install demeter
</code></pre>
<p>I get the error message</p>
<pre><code>Error: Failed to activate demeter: Image error: /opt/local/lib/perl5/vendor_perl/5.34/darwin-thread-multi-2level/Ifeffit.pm is being used by the active p5.34-ifeffit port. Please deactivate this port first, or use 'port -f activate demeter' to force the activation.
</code></pre>
<p>I have two questions:
(1) Why am I getting this error message? Have I accidentally got two copies of demeter?
(2) How can I deactivate this port? (I'd rather deactivate it then use the force activate option)</p>
<p>When I run</p>
<pre><code>sudo lsof -i -n -P | grep TCP
</code></pre>
<p>I can't actually see 'p5.34-ifeffit port' in the list of ports.</p>
| [
{
"answer_id": 74383530,
"author": "rzwitserloot",
"author_id": 768644,
"author_profile": "https://Stackoverflow.com/users/768644",
"pm_score": 3,
"selected": true,
"text": "new File"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74382927",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1798869/"
] |
74,382,971 | <p>I have this graph that I made using this code:</p>
<pre><code>df3 <- data.frame(outcome=c("Any complication", "Cardiac complication",
"Vascular Complication","Vascular complication",
"Respiratory complication", "Infectious complication",
"Neurological complication"),
index=1:7,
effect=c(-.4, -.25, -.1, .1, .15, .2, .3),
lower=c(-.43, -.29, -.17, -.02, .04, .17, .27),
upper=c(-.37, -.21, -.03, .22, .24, .23, .33))
plot2 <- ggplot(data=df3, aes(y=index, x=effect, xmin=lower, xmax=upper))+
geom_point(shape="diamond", colour="royalblue4", size=5) +
geom_errorbarh(height=.2, colour="royalblue4") +
scale_y_continuous(breaks=1:nrow(df3), labels=df3$outcome) +
labs(title="Adjusted Relative Risk for Complications", x="Relative Risk", y = "Type of complication") +
geom_vline(xintercept=0, color='gray', linetype='dashed', alpha=.5) +
theme_minimal()+
plots_theme
</code></pre>
<p><a href="https://i.stack.imgur.com/qqLgL.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/qqLgL.jpg" alt="My graph" /></a></p>
<p>But I would like to add the RR, the 95% confidence interval and some other things there, as shown here:</p>
<p><a href="https://i.stack.imgur.com/Vtlsu.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Vtlsu.jpg" alt="The graph I want :)" /></a></p>
<p>I could really use some help! Quite new in R here :(</p>
| [
{
"answer_id": 74383530,
"author": "rzwitserloot",
"author_id": 768644,
"author_profile": "https://Stackoverflow.com/users/768644",
"pm_score": 3,
"selected": true,
"text": "new File"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74382971",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19141802/"
] |
74,382,986 | <p>I am using "react-native-paper": "^4.12.5" & "react-native": "0.70.4"</p>
<p>I want to transform the layout on the left to the one on the right using react-native-paper. But I have found a problem. I don't know how to center the input, and the placeholder of a TextInput. I would also like to hide the cursor.</p>
<p><a href="https://i.stack.imgur.com/Vc0iZ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Vc0iZ.png" alt="what I have and what I want" /></a></p>
<p>I have tried to inject "textAlign" using the style prop of the paper component, but it does not seem to work, and the native props of paper do not allow this transformation.
Do you know how I can adapt the paper component, or do you think I have to design my own?</p>
<pre><code>import * as React from 'react';
import {StyleSheet} from 'react-native';
import {TextInput} from 'react-native-paper';
import {useTheme} from 'react-native-paper';
type textInputProps = {
placeholder: string;
style: object;
};
const CustomInput = ({placeholder, style}: textInputProps) => {
const {colors} = useTheme();
return (
<TextInput
mode="outlined"
placeholder={placeholder}
outlineColor={colors.border}
style={(styles.custom, style)} // Here is the error!
// style={[styles.custom, style]} This is how to do it
theme={{roundness: 30}}
/>
);
};
const styles = StyleSheet.create({
custom: {
textAlign: 'center',
},
});
export default CustomInput;
</code></pre>
<p>----- Edit -----</p>
<p>As pointed out by Vu and Nitin, it is perfectly possible to style a paper TextInput to center the cursor using the style prop and the textAlign property. My error was in the way I was passing the style prop, not the style itself.</p>
| [
{
"answer_id": 74383703,
"author": "Vu Phung",
"author_id": 12040727,
"author_profile": "https://Stackoverflow.com/users/12040727",
"pm_score": 2,
"selected": true,
"text": "style={(styles.custom, style)}"
},
{
"answer_id": 74383945,
"author": "M Naufal Helmi",
"author_id": 15103163,
"author_profile": "https://Stackoverflow.com/users/15103163",
"pm_score": 0,
"selected": false,
"text": "textAlignHorizontal : 'right'"
},
{
"answer_id": 74386111,
"author": "Nitin Kudesia",
"author_id": 20459187,
"author_profile": "https://Stackoverflow.com/users/20459187",
"pm_score": 1,
"selected": false,
"text": "<TextInput\n mode=\"outlined\"\n placeholder={placeholder}\n outlineColor={colors.border}\n style={styles.custom}\n theme={{roundness: 30}}\n/>\n\nor you can directly add inLine style\n\n<TextInput\n mode=\"outlined\"\n placeholder={placeholder}\n outlineColor={colors.border}\n style={{\n textAlign: 'center'\n }}\n"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74382986",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11596081/"
] |
74,382,992 | <p>I am new to <strong>jq</strong> and this one seems impossible to write. So need some help from jq gurus out there:</p>
<p>So I have an Open API spec file, let's take version 3.0 for example:</p>
<p>The <code>paths</code> element has <code>endpoints</code> listed, and each of them has methods(<code>get</code>, <code>post</code>, etc.)</p>
<p>I need a jq filter to select ONLY those methods marked with <code>"x-visibility": "public"</code> and leave everything else out.</p>
<h2>So far, I've tried this:</h2>
<pre><code>.paths |= map(select(.[]."x-visibility" == "public" | not))
</code></pre>
<p>Obviously, it doesn't work.</p>
<h2>Any help/pointers will be appreciated!</h2>
<p>Here is the OpenAPI 3.0 spec file (extra stuff stripped off):</p>
<pre><code>{
"openapi": "3.0.1",
"info": {
"title": "API service",
"description": "Exposing useful methods",
"x-descriptionForPublicDocs": "This is a test description for public docs specifically",
"contact": {
"name": "Message me",
"url": "https://message.me"
},
"version": "1.0"
},
"servers": [
{
"url": "http://localhost:9090",
"description": "Generated server url"
}
],
"tags": [
{
"name": "AccountGroups"
}
],
"x-tags": [
{
"name": "TestResourceLists"
}
],
"paths": {
"/crane/v1/resource_list/{id}": {
"get": {
"tags": [
"ResourceLists"
],
"x-tags": "TestResourceLists",
"x-visibility": "public",
"summary": "Get Resource List by ID",
"description": "Returns the resource list that has the specified ID.",
"operationId": "getById",
"parameters": [
{
"name": "id",
"in": "path",
"description": "ResourceList Id",
"required": true,
"schema": {
"type": "string"
}
}
],
"responses": {
"200": {
"description": "Successful operation",
"content": {
"application/json; charset=UTF-8": {
"schema": {
"$ref": "#/components/schemas/ResourceListModel"
}
}
}
},
"400": {
"description": "Bad Request",
"content": {
"*/*": {
"schema": {
"type": "object"
}
}
}
},
"403": {
"description": "Forbidden",
"content": {
"*/*": {
"schema": {
"type": "object"
}
}
}
},
"500": {
"description": "Internal Server Error",
"content": {
"*/*": {
"schema": {
"type": "object"
}
}
}
},
"4XX": {
"description": "Client error",
"content": {
"application/json; charset=UTF-8": {
"schema": {
"$ref": "#/components/schemas/SpringErrorResponse"
}
}
}
}
}
},
"put": {
"tags": [
"ResourceLists"
],
"x-visibility": "internal",
"summary": "Update Resource List",
"description": "Updates the resource list that has the specified ID.",
"operationId": "update",
"parameters": [
{
"name": "id",
"in": "path",
"description": "ResourceList Id",
"required": true,
"schema": {
"type": "string"
}
}
],
"requestBody": {
"description": "Model for Resource List",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/ResourceListModel"
},
"examples": {
"TAG": {
"description": "Tag ResourceList",
"value": {
"members": [
{
"string": "string"
}
],
"name": "string",
"resourceListType": "TAG",
"description": "string"
}
},
"RESOURCE_GROUP": {
"description": "RESOURCE_GROUP ResourceList",
"value": {
"description": "string",
"members": [
"string",
"string"
],
"name": "string",
"resourceListType": "RESOURCE_GROUP"
}
},
"COMPUTE_ACCESS_GROUP": {
"description": "COMPUTE_ACCESS_GROUP ResourceList",
"value": {
"description": "string",
"members": [
{
"appIDs": [
"*"
],
"clusters": [
"*"
],
"codeRepos": [
"*"
],
"containers": [
"*"
],
"functions": [
"*"
],
"hosts": [
"*"
],
"images": [
"*"
],
"labels": [
"*"
],
"namespaces": [
"*"
]
}
],
"name": "string",
"resourceListType": "COMPUTE_ACCESS_GROUP"
}
}
}
}
},
"required": true
},
"responses": {
"200": {
"description": "Successful operation",
"content": {
"application/json; charset=UTF-8": {
"schema": {
"$ref": "#/components/schemas/ResourceListModel"
}
}
}
},
"400": {
"description": "Bad Request",
"content": {
"*/*": {
"schema": {
"type": "object"
}
}
}
},
"403": {
"description": "Forbidden",
"content": {
"*/*": {
"schema": {
"type": "object"
}
}
}
},
"500": {
"description": "Internal Server Error",
"content": {
"*/*": {
"schema": {
"type": "object"
}
}
}
},
"4XX": {
"description": "Client error",
"content": {
"application/json; charset=UTF-8": {
"schema": {
"$ref": "#/components/schemas/SpringErrorResponse"
}
}
}
}
}
},
"delete": {
"tags": [
"ResourceLists"
],
"x-visibility": "internal",
"summary": "Delete Resource List",
"description": "Deletes the resource list that has the specified ID.",
"operationId": "delete",
"parameters": [
{
"name": "id",
"in": "path",
"description": "ResourceList Id",
"required": true,
"schema": {
"type": "string"
}
}
],
"responses": {
"204": {
"description": "Successful operation"
},
"400": {
"description": "Bad Request",
"content": {
"*/*": {
"schema": {
"type": "object"
}
}
}
},
"403": {
"description": "Forbidden",
"content": {
"*/*": {
"schema": {
"type": "object"
}
}
}
},
"500": {
"description": "Internal Server Error",
"content": {
"*/*": {
"schema": {
"type": "object"
}
}
}
},
"4XX": {
"description": "Client error",
"content": {
"*/*": {
"schema": {
"$ref": "#/components/schemas/SpringErrorResponse"
}
}
}
}
}
}
},
"/crane/v1/account_group/{id}": {
"get": {
"tags": [
"AccountGroups"
],
"x-visibility": "public",
"summary": "Get resource",
"description": "Returns something",
"operationId": "getById_1",
"parameters": [
{
"name": "id",
"in": "path",
"description": "Account Group ID",
"required": true,
"schema": {
"type": "string"
}
},
{
"name": "includeAccountInfo",
"in": "query",
"description": "Include Cloud Account details",
"required": false,
"schema": {
"type": "boolean"
}
}
],
"responses": {
"200": {
"description": "Successful operation",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/AccountGroupModel"
}
}
}
},
"400": {
"description": "Bad Request",
"content": {
"*/*": {
"schema": {
"type": "object"
}
}
}
},
"403": {
"description": "Forbidden",
"content": {
"*/*": {
"schema": {
"type": "object"
}
}
}
},
"500": {
"description": "Internal Server Error",
"content": {
"*/*": {
"schema": {
"type": "object"
}
}
}
},
"4XX": {
"description": "Client error",
"content": {
"application/json; charset=UTF-8": {
"schema": {
"$ref": "#/components/schemas/SpringErrorResponse"
}
}
}
}
},
},
"put": {
"tags": [
"AccountGroups"
],
"x-visibility": "internal",
"summary": "Update resource",
"description": "Update information",
"operationId": "update_1",
"parameters": [
{
"name": "id",
"in": "path",
"description": "AccountGroup Id",
"required": true,
"schema": {
"type": "string"
}
}
],
"requestBody": {
"content": {
"application/json; charset=UTF-8": {
"schema": {
"$ref": "#/components/schemas/AccountGroupModel"
}
}
},
"required": true
},
"responses": {
"200": {
"description": "Successful operation"
},
"400": {
"description": "Bad Request",
"content": {
"*/*": {
"schema": {
"type": "object"
}
}
}
},
"403": {
"description": "Forbidden",
"content": {
"*/*": {
"schema": {
"type": "object"
}
}
}
},
"500": {
"description": "Internal Server Error",
"content": {
"*/*": {
"schema": {
"type": "object"
}
}
}
},
"4XX": {
"description": "Client error",
"content": {
"application/json; charset=UTF-8": {
"schema": {
"$ref": "#/components/schemas/SpringErrorResponse"
}
}
}
}
}
},
"delete": {
"tags": [
"AccountGroups"
],
"x-visibility": "internal",
"summary": "Delete resource",
"description": "Deletes the resource",
"operationId": "delete_1",
"parameters": [
{
"name": "id",
"in": "path",
"description": "Delete resource",
"required": true,
"schema": {
"type": "string"
}
}
],
"responses": {
"200": {
"description": "Successful operation"
},
"400": {
"description": "Bad Request",
"content": {
"*/*": {
"schema": {
"type": "object"
}
}
}
},
"403": {
"description": "Forbidden",
"content": {
"*/*": {
"schema": {
"type": "object"
}
}
}
},
"500": {
"description": "Internal Server Error",
"content": {
"*/*": {
"schema": {
"type": "object"
}
}
}
},
"4XX": {
"description": "Client error",
"content": {
"*/*": {
"schema": {
"$ref": "#/components/schemas/SpringErrorResponse"
}
}
}
}
}
}
}
}
}
</code></pre>
| [
{
"answer_id": 74383703,
"author": "Vu Phung",
"author_id": 12040727,
"author_profile": "https://Stackoverflow.com/users/12040727",
"pm_score": 2,
"selected": true,
"text": "style={(styles.custom, style)}"
},
{
"answer_id": 74383945,
"author": "M Naufal Helmi",
"author_id": 15103163,
"author_profile": "https://Stackoverflow.com/users/15103163",
"pm_score": 0,
"selected": false,
"text": "textAlignHorizontal : 'right'"
},
{
"answer_id": 74386111,
"author": "Nitin Kudesia",
"author_id": 20459187,
"author_profile": "https://Stackoverflow.com/users/20459187",
"pm_score": 1,
"selected": false,
"text": "<TextInput\n mode=\"outlined\"\n placeholder={placeholder}\n outlineColor={colors.border}\n style={styles.custom}\n theme={{roundness: 30}}\n/>\n\nor you can directly add inLine style\n\n<TextInput\n mode=\"outlined\"\n placeholder={placeholder}\n outlineColor={colors.border}\n style={{\n textAlign: 'center'\n }}\n"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74382992",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20463822/"
] |
74,383,033 | <p>I have a function, findnums(v) that is intended to append 5 numbers taken from user input to list v, which starts in main as an empty list. I have a nested try-except loop in my for loop for the function findnums(v) to try and reject non float user input.</p>
<p>I want my except condition to ignore the iteration that had the bad user input, not pass this bad input back to list v, and prompt the user to enter good input. While the condition doesn't pass bad input to the list, and does prompt the user to reenter good input, the bad data counts for an iteration and is not ignored. Ideally, I want the number of bad input iterations to be uncounted/infinite, and the number of good input iterations to always equal to 5.</p>
<p>Here is my code:</p>
<pre><code>def main():
v=[]
findnums(v)
printlist(v)
def findnums(v):
for n in range(0,5):
try:
val=float(input('Please enter you number: '))
v.append(val)
except ValueError:
print("That is an invalid input, please start over.")
#main()
#findnums(v)
return(v)
def printlist(v):
print(v)
</code></pre>
<p>I've tried calling main() and the findnums(v) function in the except condition to have the program restart in the case of bad data, but in both cases it won't ignore the data as I want it to, but it will just rerun the program for each time the bad input is given, counting each piece of bad data for the final list. So if three pieces of bad data are entered, the program will ask for user input 12 time, and add those 12 items to the list v.</p>
<p>I think understand why this is happening. The data, good or bad is always being passed to v, I just can't think of a way of passing only good data to v.</p>
| [
{
"answer_id": 74383703,
"author": "Vu Phung",
"author_id": 12040727,
"author_profile": "https://Stackoverflow.com/users/12040727",
"pm_score": 2,
"selected": true,
"text": "style={(styles.custom, style)}"
},
{
"answer_id": 74383945,
"author": "M Naufal Helmi",
"author_id": 15103163,
"author_profile": "https://Stackoverflow.com/users/15103163",
"pm_score": 0,
"selected": false,
"text": "textAlignHorizontal : 'right'"
},
{
"answer_id": 74386111,
"author": "Nitin Kudesia",
"author_id": 20459187,
"author_profile": "https://Stackoverflow.com/users/20459187",
"pm_score": 1,
"selected": false,
"text": "<TextInput\n mode=\"outlined\"\n placeholder={placeholder}\n outlineColor={colors.border}\n style={styles.custom}\n theme={{roundness: 30}}\n/>\n\nor you can directly add inLine style\n\n<TextInput\n mode=\"outlined\"\n placeholder={placeholder}\n outlineColor={colors.border}\n style={{\n textAlign: 'center'\n }}\n"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74383033",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20161630/"
] |
74,383,037 | <p>I'm using pypika to build some queries. It used to work great but I have an issue with subqueries on an oracle database. The query reads as follow</p>
<pre><code>fake_query = Query().from_(my_table).where(my_table.ID == "12345").select(my_table.ID)
QN = AliasedQuery("fake_query_with")
query = (
Query()
.with_(fake_query, "fake_query_with")
.from_(QN)
.select(
QN.star. # problematic line
)
)
df_temp = claim_conn.read_dataframe(query.get_sql())
</code></pre>
<p>So when I run the script, I got an error:</p>
<pre><code>DatabaseError: ORA-00904: "fake_query_with": invalid identifier
</code></pre>
<p>The pypika query is translated as expected as the string</p>
<pre><code>WITH fake_query_with AS
(
SELECT "ID"
FROM "MYTABLE"
WHERE "ID"=12345
)
SELECT "fake_query_with".*
FROM fake_query_with
</code></pre>
<p>So this query fails, but if I replace <code>QN.star</code> by simply <code>*</code>, it works, but of course I loose the interesting usage of the alias. I know this is just a dummy snippet but the it is just to demonstrate the error.</p>
| [
{
"answer_id": 74383703,
"author": "Vu Phung",
"author_id": 12040727,
"author_profile": "https://Stackoverflow.com/users/12040727",
"pm_score": 2,
"selected": true,
"text": "style={(styles.custom, style)}"
},
{
"answer_id": 74383945,
"author": "M Naufal Helmi",
"author_id": 15103163,
"author_profile": "https://Stackoverflow.com/users/15103163",
"pm_score": 0,
"selected": false,
"text": "textAlignHorizontal : 'right'"
},
{
"answer_id": 74386111,
"author": "Nitin Kudesia",
"author_id": 20459187,
"author_profile": "https://Stackoverflow.com/users/20459187",
"pm_score": 1,
"selected": false,
"text": "<TextInput\n mode=\"outlined\"\n placeholder={placeholder}\n outlineColor={colors.border}\n style={styles.custom}\n theme={{roundness: 30}}\n/>\n\nor you can directly add inLine style\n\n<TextInput\n mode=\"outlined\"\n placeholder={placeholder}\n outlineColor={colors.border}\n style={{\n textAlign: 'center'\n }}\n"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74383037",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1141818/"
] |
74,383,044 | <p>I have a problem... thant's a code:</p>
<pre><code>class Currency {
cosnstructor() {
this.currencyInfo = [];
}
getCurrency(getInfo) {
this.currencyInfo = getInfo;
}
}
const actuallyCurrency = new Currency;
(async () => {
const response = await fetch(`http://api.nbp.pl/api/exchangerates/tables/A`);
const data = await response.json();
const currency = data[0].rates;
currency.map(element => curArr.push(element));
})();
const curArr = [];
actuallyCurrency.getCurrency(curArr);
</code></pre>
<p>this code working good, but I need in this.currencyInfo a new array, not reference to array curArr.</p>
| [
{
"answer_id": 74383703,
"author": "Vu Phung",
"author_id": 12040727,
"author_profile": "https://Stackoverflow.com/users/12040727",
"pm_score": 2,
"selected": true,
"text": "style={(styles.custom, style)}"
},
{
"answer_id": 74383945,
"author": "M Naufal Helmi",
"author_id": 15103163,
"author_profile": "https://Stackoverflow.com/users/15103163",
"pm_score": 0,
"selected": false,
"text": "textAlignHorizontal : 'right'"
},
{
"answer_id": 74386111,
"author": "Nitin Kudesia",
"author_id": 20459187,
"author_profile": "https://Stackoverflow.com/users/20459187",
"pm_score": 1,
"selected": false,
"text": "<TextInput\n mode=\"outlined\"\n placeholder={placeholder}\n outlineColor={colors.border}\n style={styles.custom}\n theme={{roundness: 30}}\n/>\n\nor you can directly add inLine style\n\n<TextInput\n mode=\"outlined\"\n placeholder={placeholder}\n outlineColor={colors.border}\n style={{\n textAlign: 'center'\n }}\n"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74383044",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14809861/"
] |
74,383,145 | <p>I am getting the date as below</p>
<pre><code>2022-10-25 11:00:00
</code></pre>
<p>which I need to convert to</p>
<pre><code>2022-10-25T11:00:00
</code></pre>
<p>Please let me know the appropriate data weave to achieve the above output.</p>
| [
{
"answer_id": 74383703,
"author": "Vu Phung",
"author_id": 12040727,
"author_profile": "https://Stackoverflow.com/users/12040727",
"pm_score": 2,
"selected": true,
"text": "style={(styles.custom, style)}"
},
{
"answer_id": 74383945,
"author": "M Naufal Helmi",
"author_id": 15103163,
"author_profile": "https://Stackoverflow.com/users/15103163",
"pm_score": 0,
"selected": false,
"text": "textAlignHorizontal : 'right'"
},
{
"answer_id": 74386111,
"author": "Nitin Kudesia",
"author_id": 20459187,
"author_profile": "https://Stackoverflow.com/users/20459187",
"pm_score": 1,
"selected": false,
"text": "<TextInput\n mode=\"outlined\"\n placeholder={placeholder}\n outlineColor={colors.border}\n style={styles.custom}\n theme={{roundness: 30}}\n/>\n\nor you can directly add inLine style\n\n<TextInput\n mode=\"outlined\"\n placeholder={placeholder}\n outlineColor={colors.border}\n style={{\n textAlign: 'center'\n }}\n"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74383145",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17642608/"
] |
74,383,148 | <p>I have an object like this :</p>
<pre><code>let data = {
approval: [{
name: 'XXXX',
kode: '10'
},
{
name: 'YYYY',
kode: '12'
},
{
name: 'ZZZZ',
kode: '14'
},
{
name: 'HHHH',
kode: '09'
}
],
batas: "10"
}
</code></pre>
<p>I want to display the data that is equal to this condition (kode >= 10) so if the 'kode' is less than 'batas' it shouldn't appear, any help?</p>
<p>So in that case the output should be like this</p>
<pre><code>approval: [{
name: 'XXXX',
kode: '10'
},
{
name: 'YYYY',
kode: '12'
},
{
name: 'ZZZZ',
kode: '14'
}
]
</code></pre>
<p>the data comes from ajax,
Thanks for your help.</p>
| [
{
"answer_id": 74383237,
"author": "Fauzan DP",
"author_id": 18874268,
"author_profile": "https://Stackoverflow.com/users/18874268",
"pm_score": 1,
"selected": false,
"text": " const batas = (data) => {\n let arr = data.approval\n let batas = data.batas\n for (let i = 0; i < arr.length; i++) {\n if (arr[i]['kode'] < batas) arr.splice(i, 1)\n }\n return data\n }\n \n let data = {\n approval: [\n {\n name: 'XXXX',\n kode: '10'\n },\n {\n name: 'YYYY',\n kode: '12'\n },\n {\n name: 'ZZZZ',\n kode: '14'\n },\n {\n name: 'HHHH',\n kode: '09'\n }\n ],\n batas: '10'\n }\n \n console.log(batas(data))"
},
{
"answer_id": 74383272,
"author": "Aleksandar",
"author_id": 12737879,
"author_profile": "https://Stackoverflow.com/users/12737879",
"pm_score": 0,
"selected": false,
"text": "filter"
},
{
"answer_id": 74383384,
"author": "Ping",
"author_id": 20288037,
"author_profile": "https://Stackoverflow.com/users/20288037",
"pm_score": 1,
"selected": true,
"text": " let data = {\n approval: [\n {\n name: 'XXXX',\n kode: '10'\n },\n {\n name: 'YYYY',\n kode: '12'\n },\n {\n name: 'ZZZZ',\n kode: '14'\n },\n {\n name: 'HHHH',\n kode: '09'\n }\n \n ],\n batas: \"10\"\n }\n\n // solution 1 > use for loop:\n const results_1 = [];\n for (let i=0; i<data.approval.length; i++) {\n if (data.approval[i].kode >= data.batas) results_1.push(data.approval[i]);\n }\n console.log(results_1);\n \n // solution 2 > use for...of loop:\n const results_2 = [];\n for (const obj of data.approval) {\n if (obj.kode >= data.batas) results_2.push(obj);\n }\n console.log(results_2);\n\n // solution 3 > use filter method:\n const results_3 = data.approval.filter(obj => obj.kode >= data.batas);\n console.log(results_3);"
},
{
"answer_id": 74383696,
"author": "PeterKA",
"author_id": 3558931,
"author_profile": "https://Stackoverflow.com/users/3558931",
"pm_score": 0,
"selected": false,
"text": "Array#filter"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74383148",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19396950/"
] |
74,383,155 | <p>How can I create a predicate so that when the user selects "Full Body" it returns the entire list with no predicate? Right now, it is returning "part" which corresponds to the muscle groups I have set (Abs, Legs, Push, Pull). I want to return all of the options when "Full Body" is selected. How could I write an If statement so that the predicate is not used?</p>
<pre><code>import SwiftUI
var parts = ["Abs", "Legs", "Push", "Pull", "Full Body"]
struct ExerciseList: View {
@State private var selectedPart = " "
var body: some View {
NavigationView {
VStack (alignment: .leading) {
NavigationLink(destination: AddExerciseView()){
Text("Add Exercise")
.fontWeight(.bold)
}
Picker("Body Part", selection: $selectedPart) {
ForEach(parts, id:\.self) { part in
Text(part)
}
}.pickerStyle(.segmented)
ListView(part:selectedPart)
}
}
}
}
</code></pre>
<pre><code>import SwiftUI
struct ListView: View {
var part: String
@FetchRequest var exercises: FetchedResults<Exercise>
init(part: String) {
self.part = part
self._exercises = FetchRequest(
entity: Exercise.entity(),
sortDescriptors: [],
predicate: NSPredicate(format: "musclegroup == %@", part as any CVarArg)
)
}
var body: some View {
List(exercises) { e in
Text(e.exercisename)
}
}
}
</code></pre>
| [
{
"answer_id": 74383237,
"author": "Fauzan DP",
"author_id": 18874268,
"author_profile": "https://Stackoverflow.com/users/18874268",
"pm_score": 1,
"selected": false,
"text": " const batas = (data) => {\n let arr = data.approval\n let batas = data.batas\n for (let i = 0; i < arr.length; i++) {\n if (arr[i]['kode'] < batas) arr.splice(i, 1)\n }\n return data\n }\n \n let data = {\n approval: [\n {\n name: 'XXXX',\n kode: '10'\n },\n {\n name: 'YYYY',\n kode: '12'\n },\n {\n name: 'ZZZZ',\n kode: '14'\n },\n {\n name: 'HHHH',\n kode: '09'\n }\n ],\n batas: '10'\n }\n \n console.log(batas(data))"
},
{
"answer_id": 74383272,
"author": "Aleksandar",
"author_id": 12737879,
"author_profile": "https://Stackoverflow.com/users/12737879",
"pm_score": 0,
"selected": false,
"text": "filter"
},
{
"answer_id": 74383384,
"author": "Ping",
"author_id": 20288037,
"author_profile": "https://Stackoverflow.com/users/20288037",
"pm_score": 1,
"selected": true,
"text": " let data = {\n approval: [\n {\n name: 'XXXX',\n kode: '10'\n },\n {\n name: 'YYYY',\n kode: '12'\n },\n {\n name: 'ZZZZ',\n kode: '14'\n },\n {\n name: 'HHHH',\n kode: '09'\n }\n \n ],\n batas: \"10\"\n }\n\n // solution 1 > use for loop:\n const results_1 = [];\n for (let i=0; i<data.approval.length; i++) {\n if (data.approval[i].kode >= data.batas) results_1.push(data.approval[i]);\n }\n console.log(results_1);\n \n // solution 2 > use for...of loop:\n const results_2 = [];\n for (const obj of data.approval) {\n if (obj.kode >= data.batas) results_2.push(obj);\n }\n console.log(results_2);\n\n // solution 3 > use filter method:\n const results_3 = data.approval.filter(obj => obj.kode >= data.batas);\n console.log(results_3);"
},
{
"answer_id": 74383696,
"author": "PeterKA",
"author_id": 3558931,
"author_profile": "https://Stackoverflow.com/users/3558931",
"pm_score": 0,
"selected": false,
"text": "Array#filter"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74383155",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20186634/"
] |
74,383,187 | <p>`</p>
<pre><code>import csv
record={}
with open( 'subject-info.csv') as f:
reader = csv.DictReader(f)
for row in reader:
record[row['ID']]=row['Age_group']
</code></pre>
<p>`
now the dictionary has ID number as keys and the value of each key has one number between 1 and 13. each number represents an age group.</p>
<p>I need to put together all the IDs that are in the same age group in seprate lists or dictionaries . How do I do that please?
thank you</p>
<p>I am not sure how to continue</p>
| [
{
"answer_id": 74383237,
"author": "Fauzan DP",
"author_id": 18874268,
"author_profile": "https://Stackoverflow.com/users/18874268",
"pm_score": 1,
"selected": false,
"text": " const batas = (data) => {\n let arr = data.approval\n let batas = data.batas\n for (let i = 0; i < arr.length; i++) {\n if (arr[i]['kode'] < batas) arr.splice(i, 1)\n }\n return data\n }\n \n let data = {\n approval: [\n {\n name: 'XXXX',\n kode: '10'\n },\n {\n name: 'YYYY',\n kode: '12'\n },\n {\n name: 'ZZZZ',\n kode: '14'\n },\n {\n name: 'HHHH',\n kode: '09'\n }\n ],\n batas: '10'\n }\n \n console.log(batas(data))"
},
{
"answer_id": 74383272,
"author": "Aleksandar",
"author_id": 12737879,
"author_profile": "https://Stackoverflow.com/users/12737879",
"pm_score": 0,
"selected": false,
"text": "filter"
},
{
"answer_id": 74383384,
"author": "Ping",
"author_id": 20288037,
"author_profile": "https://Stackoverflow.com/users/20288037",
"pm_score": 1,
"selected": true,
"text": " let data = {\n approval: [\n {\n name: 'XXXX',\n kode: '10'\n },\n {\n name: 'YYYY',\n kode: '12'\n },\n {\n name: 'ZZZZ',\n kode: '14'\n },\n {\n name: 'HHHH',\n kode: '09'\n }\n \n ],\n batas: \"10\"\n }\n\n // solution 1 > use for loop:\n const results_1 = [];\n for (let i=0; i<data.approval.length; i++) {\n if (data.approval[i].kode >= data.batas) results_1.push(data.approval[i]);\n }\n console.log(results_1);\n \n // solution 2 > use for...of loop:\n const results_2 = [];\n for (const obj of data.approval) {\n if (obj.kode >= data.batas) results_2.push(obj);\n }\n console.log(results_2);\n\n // solution 3 > use filter method:\n const results_3 = data.approval.filter(obj => obj.kode >= data.batas);\n console.log(results_3);"
},
{
"answer_id": 74383696,
"author": "PeterKA",
"author_id": 3558931,
"author_profile": "https://Stackoverflow.com/users/3558931",
"pm_score": 0,
"selected": false,
"text": "Array#filter"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74383187",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20027429/"
] |
74,383,188 | <p>I am trying to figure out how to run two different loops on the same code. I am trying to create a matrix where I am filling a column with the mean of a variable for each year.</p>
<p>Here's the code I am using to do it right now:</p>
<pre class="lang-r prettyprint-override"><code>matplot2 = as.data.frame(matrix(NA, nrow=16, ncol=4))
matplot2[1,1] = mean(matplot[matplot$Year==2003, 'TotalTime'])
matplot2[2,1] = mean(matplot[matplot$Year==2004, 'TotalTime'])
matplot2[3,1] = mean(matplot[matplot$Year==2005, 'TotalTime'])
matplot2[4,1] = mean(matplot[matplot$Year==2006, 'TotalTime'])
matplot2[5,1] = mean(matplot[matplot$Year==2007, 'TotalTime'])
matplot2[6,1] = mean(matplot[matplot$Year==2008, 'TotalTime'])
matplot2[7,1] = mean(matplot[matplot$Year==2009, 'TotalTime'])
matplot2[8,1] = mean(matplot[matplot$Year==2010, 'TotalTime'])
matplot2[9,1] = mean(matplot[matplot$Year==2011, 'TotalTime'])
matplot2[10,1] = mean(matplot[matplot$Year==2012, 'TotalTime'])
matplot2[11,1] = mean(matplot[matplot$Year==2013, 'TotalTime'])
matplot2[12,1] = mean(matplot[matplot$Year==2014, 'TotalTime'])
matplot2[13,1] = mean(matplot[matplot$Year==2015, 'TotalTime'])
matplot2[14,1] = mean(matplot[matplot$Year==2016, 'TotalTime'])
matplot2[15,1] = mean(matplot[matplot$Year==2017, 'TotalTime'])
matplot2[16,1] = mean(matplot[matplot$Year==2018, 'TotalTime'])
</code></pre>
<p>If it were just the year changing, I would write the loop like this:</p>
<pre class="lang-r prettyprint-override"><code>for(i in 2003:2018) {
matplot2[1,1] = mean(matplot[matplot$Year==i, 'TotalTime'])
}
</code></pre>
<p>But, I need the row number in the matrix I'm printing the results into to change as well. How can I write a loop where I am printing the results of all these means into one column of a matrix?</p>
<p>In other words, I need to be able to have it loop <code>matplot2[j,1]</code> in addition to the <code>matplot$Year==i</code>.</p>
<p>Any suggestions would be greatly appreciated!</p>
| [
{
"answer_id": 74383220,
"author": "Dave2e",
"author_id": 5792244,
"author_profile": "https://Stackoverflow.com/users/5792244",
"pm_score": 2,
"selected": false,
"text": "i<-1:16\nmatplot2[i,1] = mean(matplot[matplot$Year==(2002 + i), 'TotalTime'])\n"
},
{
"answer_id": 74383224,
"author": "r2evans - GO NAVY BEAT ARMY",
"author_id": 3358272,
"author_profile": "https://Stackoverflow.com/users/3358272",
"pm_score": 3,
"selected": true,
"text": "mean(TotalTime)"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74383188",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20464109/"
] |
74,383,234 | <p>I am getting the following error when I try 'npm install prisma'</p>
<pre><code>npm ERR! code 1
npm ERR! path /Users/path/to/project/node_modules/prisma
npm ERR! command failed
npm ERR! command sh -c -- node scripts/preinstall-entry.js
npm ERR! ┌───────────────────────────────────────────┐
npm ERR! │ Prisma only supports Node.js >= 14.17 │
npm ERR! └───────────────────────────────────────────┘
npm ERR! A complete log of this run can be found in:
npm ERR! /Users/me/.npm/_logs/2022-11-09T20_20_18_706Z-debug-0.log
</code></pre>
<p>I am using Node 18 which I installed through nvm on Mac OS.</p>
<pre><code>$ node --version
v18.12.1
$ nvm version
v18.12.1
</code></pre>
<p>I tried using pnpm, deleting and reinstalling nvm, and removing all other node versions, or downgrading to 16, or 18.8.0, but none of these worked.
Is this a known error? Can someone help me figure out the issue?</p>
| [
{
"answer_id": 74383220,
"author": "Dave2e",
"author_id": 5792244,
"author_profile": "https://Stackoverflow.com/users/5792244",
"pm_score": 2,
"selected": false,
"text": "i<-1:16\nmatplot2[i,1] = mean(matplot[matplot$Year==(2002 + i), 'TotalTime'])\n"
},
{
"answer_id": 74383224,
"author": "r2evans - GO NAVY BEAT ARMY",
"author_id": 3358272,
"author_profile": "https://Stackoverflow.com/users/3358272",
"pm_score": 3,
"selected": true,
"text": "mean(TotalTime)"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74383234",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2076046/"
] |
74,383,259 | <p>I have a bit of a complicated scenario. I have two tables, <code>employee</code> and <code>agency</code>. An employee may or may not have an agency, but if an employee has an agency I want the select clause to check another condition on the agency, but if the employee does not have an agency its fine I want to fetch the employee. I'm not sure how to write the select statement for this. This is what I have come up with so far</p>
<pre><code>select * from employee e left join
agency a on a.id = e.agencyID and a.valid = true;
</code></pre>
<p>However the problem with this is that it fetches both employees without agencies which is fine, but it also fetches employees with agencies where <code>a.valid = false</code>. The only option I can think of is to do an union but I'm looking for something more simpler.</p>
| [
{
"answer_id": 74383220,
"author": "Dave2e",
"author_id": 5792244,
"author_profile": "https://Stackoverflow.com/users/5792244",
"pm_score": 2,
"selected": false,
"text": "i<-1:16\nmatplot2[i,1] = mean(matplot[matplot$Year==(2002 + i), 'TotalTime'])\n"
},
{
"answer_id": 74383224,
"author": "r2evans - GO NAVY BEAT ARMY",
"author_id": 3358272,
"author_profile": "https://Stackoverflow.com/users/3358272",
"pm_score": 3,
"selected": true,
"text": "mean(TotalTime)"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74383259",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7385798/"
] |
74,383,308 | <p>Environment: vs 2022 v 17.4.0, with NET7 sdk installed</p>
<p>I have a multi target project <code>net7.0;net472</code>:</p>
<pre><code><PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFrameworks>net7.0;net472</TargetFrameworks>
<LangVersion>11.0</LangVersion>
<!--others-->
</PropertyGroup>
</code></pre>
<p>I tried to use the new feature <a href="https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/required" rel="nofollow noreferrer">required</a> in c# 11 as given below:</p>
<pre><code>public class Person
{
public required int Id { get; set; }
}
</code></pre>
<p>I get a compilation error in net472:</p>
<blockquote>
<p>Error CS0656 Missing compiler required member 'System.Runtime.CompilerServices.CompilerFeatureRequiredAttribute..ctor'<br />
Error CS0656 Missing compiler required member 'System.Runtime.CompilerServices.RequiredMemberAttribute..ctor'</p>
</blockquote>
<p>My workaround solution is using conditional compilation as:</p>
<pre><code> public class Person
{
public
#if NET7_0
required
#endif
int Id { get; set; }
}
</code></pre>
<p>What should I do to support the new features 'required' of c# 11 in a multi target project has net47x?</p>
| [
{
"answer_id": 74383220,
"author": "Dave2e",
"author_id": 5792244,
"author_profile": "https://Stackoverflow.com/users/5792244",
"pm_score": 2,
"selected": false,
"text": "i<-1:16\nmatplot2[i,1] = mean(matplot[matplot$Year==(2002 + i), 'TotalTime'])\n"
},
{
"answer_id": 74383224,
"author": "r2evans - GO NAVY BEAT ARMY",
"author_id": 3358272,
"author_profile": "https://Stackoverflow.com/users/3358272",
"pm_score": 3,
"selected": true,
"text": "mean(TotalTime)"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74383308",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3142139/"
] |
74,383,322 | <p><code>$course_hour = 1; $starttime = '07:00'; $endtime = '16:00';</code></p>
<p>I wish if it could return an array of values like below:
If</p>
<pre><code>$course_hour = 1;
</code></pre>
<p>$return_array = array('07:00 - 08:00', '08:00 - 09:00', '09:00 - 10:00', '10:00 - 11:00', '11:00 - 12:00', '12:00 - 13:00', '13:00 - 14:00', '14:00 - 15:00', '15:00 - 16:00');
If</p>
<pre><code>$course_hour = 1.5;
</code></pre>
<p>$return_array = array('07:00 - 08:30', '8:30 - 10:00', '10:00 - 11:30', '11:30 - 13:00', '13:00 - 14:30', '14:30 - 16:00');
If</p>
<pre><code>$course_hour = 2;
</code></pre>
<p>$return_array = array('07:00 - 09:00', '09:00 - 11:00', '11:00 - 13:00', '13:00 - 15:00');</p>
<pre><code>function get_session_times($course_hour, $start_time, $end_time){
if(strlen($start_time) < 5) $start_time = '0'.$start_time;
if(strlen($end_time) < 5) $end_time = '0'.$end_time;
$current_time = date("Y-m-d H:i");
$session_starttime = date("Y-m-d H:i", strtotime(date("Y-m-d ").$start_time));
$session_endtime = date("Y-m-d H:i", strtotime(date("Y-m-d ").$end_time));
$session_starttime_ms = strtotime($session_starttime);
$session_endtime_ms = strtotime($session_endtime);
$session_times_array = array();
for ($i = $session_starttime_ms; $i < $session_endtime_ms; ) {
$session_times_array[] = date("H:i", $i)."<br/>";
$i = $i + ($course_hour * 60 * 60);
}
return $session_times_array;
}
</code></pre>
| [
{
"answer_id": 74383220,
"author": "Dave2e",
"author_id": 5792244,
"author_profile": "https://Stackoverflow.com/users/5792244",
"pm_score": 2,
"selected": false,
"text": "i<-1:16\nmatplot2[i,1] = mean(matplot[matplot$Year==(2002 + i), 'TotalTime'])\n"
},
{
"answer_id": 74383224,
"author": "r2evans - GO NAVY BEAT ARMY",
"author_id": 3358272,
"author_profile": "https://Stackoverflow.com/users/3358272",
"pm_score": 3,
"selected": true,
"text": "mean(TotalTime)"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74383322",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2289225/"
] |
74,383,360 | <p>Given the below string, what would be the most efficient way to get the file ID? The portion wanted: <code>XXXXXXXXXXXxxxxxxxxXXX</code>, which is between <code>/</code> and <code>/view</code></p>
<p>The attempt below works, but is it really needed to reverse the string twice?</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>let = url = 'https://drive.google.com/file/d/1pnEX1OXXXXXXu6z9dPV5ZZ5VHqPU--6/view?usp=share_link'
url = reverseString(url)
let id = url.split('weiv/').pop().split('/')[0]
id = reverseString(id)
console.log('URL:' + id)
function reverseString(str) {
var splitString = str.split("");
var reverseArray = splitString.reverse();
var joinArray = reverseArray.join("");
return joinArray;
}</code></pre>
</div>
</div>
</p>
| [
{
"answer_id": 74383220,
"author": "Dave2e",
"author_id": 5792244,
"author_profile": "https://Stackoverflow.com/users/5792244",
"pm_score": 2,
"selected": false,
"text": "i<-1:16\nmatplot2[i,1] = mean(matplot[matplot$Year==(2002 + i), 'TotalTime'])\n"
},
{
"answer_id": 74383224,
"author": "r2evans - GO NAVY BEAT ARMY",
"author_id": 3358272,
"author_profile": "https://Stackoverflow.com/users/3358272",
"pm_score": 3,
"selected": true,
"text": "mean(TotalTime)"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74383360",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11832197/"
] |
74,383,379 | <p>I am making a very creative tetris clone for a project with a friend and we have custom sprites for every shape (including the rotations) and we made a wall of else if statements for the rotations. It's supposed to work like this: It calls a random shape out of list of the main 7 shapes and every time the user presses "a" it changes the left facing gif of that shape using the giant el if wall. However, we ran unto an error where instead of executing the elif statements, it just skips to the last line and changes to the J shape no matter what shape was called in the random statement. Any help would be awesome, thank you! (We are still learning btw) also the rotate function is also supposed to happen when the user presses the "d" key but its supposed to change to the other direction.</p>
<pre><code>
import turtle as trtl
import random as rand
wn = trtl.Screen()
#configurations
tetris = trtl.Turtle()
drawer = trtl.Turtle()
background = trtl.Turtle()
starty = int(-400)
square = ("sqaure_block.gif")
s_block_normal = ("S_block_norm.gif")
s_block_standing = ("S_block_right.gif")
invert_s_block_normal = ("Z_block_norm.gif")
invert_s_block_standing = ("Z_block_right.gif")
l_block_normal = ("L_block_norm.gif")
l_block_180 = ("L_block_180.gif")
l_block_right = ("L_block_right.gif")
l_block_left = ("L_block_left.gif")
line_normal = ("line_block_norm.gif")
line_standing = ("line_block_standing.gif")
t_block_normal = ("T_block_norm.gif")
t_block_180 = ("T_block_180.gif")
t_block_right = ("T_BLOCK_RIGHT.gif")
t_block_left = ("T_block_left.gif")
j_block_normal = ("J_block_norm.gif")
j_block_180 = ("J_block_180.gif")
j_block_right = ("J_block_right.gif")
j_block_left = ("J_block_left.gif")
wn.addshape (square)
wn.addshape(s_block_normal)
wn.addshape(s_block_standing)
wn.addshape(invert_s_block_normal)
wn.addshape(invert_s_block_standing)
wn.addshape(l_block_normal)
wn.addshape(l_block_180)
wn.addshape(l_block_right)
wn.addshape(l_block_left)
wn.addshape(line_normal)
wn.addshape(line_standing)
wn.addshape(t_block_normal)
wn.addshape(t_block_180)
wn.addshape(t_block_right)
wn.addshape(t_block_left)
wn.addshape(j_block_normal)
wn.addshape(j_block_180)
wn.addshape(j_block_right)
wn.addshape(j_block_left)
Tshape = [square, s_block_normal, invert_s_block_normal, l_block_normal, line_normal, t_block_normal, j_block_normal]
squarecor = [-50, -25, -100, -50]
wn.bgcolor("lightblue")
background.speed("fastest")
background.hideturtle()
background.pu()
background.goto(-400,-200)
background.fillcolor("blue")
background.pencolor("blue")
background.begin_fill()
background.pd()
background.goto(400,-200)
background.goto(400,-350)
background.goto(-400,-350)
background.goto(-400,-200)
background.end_fill()
#sprite direction change
def sprite_right():
global tetris
tetris.hideturtle()
if (tetris.shape(s_block_normal)):
tetris.shape(s_block_standing)
elif (tetris.shape(invert_s_block_normal)):
tetris.shape(invert_s_block_standing)
elif (tetris.shape(line_normal)):
tetris.shape(line_standing)
elif (tetris.shape(l_block_normal)):
tetris.shape(l_block_right)
elif (tetris.shape(t_block_normal)):
tetris.shape(t_block_right)
elif (tetris.shape(j_block_normal)):
tetris.shape(j_block_right)
elif (tetris.shape(l_block_right)):
tetris.shape(l_block_180)
elif (tetris.shape(t_block_right)):
tetris.shape(t_block_180)
elif (tetris.shape(j_block_right)):
tetris.shape(j_block_180)
elif (tetris.shape(s_block_standing)):
tetris.shape(s_block_normal)
elif (tetris.shape(invert_s_block_standing)):
tetris.shape(invert_s_block_normal)
elif (tetris.shape(line_standing)):
tetris.shape(line_normal)
elif (tetris.shape(l_block_180)):
tetris.shape(l_block_left)
elif (tetris.shape(t_block_180)):
tetris.shape(t_block_left)
elif (tetris.shape(j_block_180)):
tetris.shape(j_block_left)
elif (tetris.shape(l_block_left)):
tetris.shape(l_block_normal)
elif (tetris.shape(t_block_left)):
tetris.shape(t_block_normal)
elif (tetris.shape(j_block_left)):
tetris.shape(j_block_normal)
tetris.showturtle()
def sprite_left():
tetris.hideturtle()
if (tetris.shape(s_block_normal)):
tetris.shape(s_block_standing)
elif (tetris.shape(invert_s_block_normal)):
tetris.shape(invert_s_block_standing)
elif (tetris.shape(line_normal)):
tetris.shape(line_standing)
elif (tetris.shape(l_block_normal)):
tetris.shape(l_block_left)
elif (tetris.shape(t_block_normal)):
tetris.shape(t_block_left)
elif (tetris.shape(j_block_normal)):
tetris.shape(j_block_left)
elif (tetris.shape(l_block_left)):
tetris.shape(l_block_180)
elif (tetris.shape(t_block_left)):
tetris.shape(t_block_180)
elif (tetris.shape(j_block_left)):
tetris.shape(j_block_180)
elif (tetris.shape(s_block_standing)):
tetris.shape(s_block_normal)
elif (tetris.shape(invert_s_block_standing)):
tetris.shape(invert_s_block_normal)
elif (tetris.shape(line_standing)):
tetris.shape(line_normal)
elif (tetris.shape(l_block_180)):
tetris.shape(l_block_right)
elif (tetris.shape(t_block_180)):
tetris.shape(t_block_right)
elif (tetris.shape(j_block_180)):
tetris.shape(j_block_right)
elif (tetris.shape(l_block_right)):
tetris.shape(l_block_normal)
elif (tetris.shape(t_block_right)):
tetris.shape(t_block_normal)
elif (tetris.shape(j_block_right)):
tetris.shape(j_block_normal)
tetris.showturtle()
'''
def (fast_down):
global tetris
tetris.setheading(270)
tetris.forward(10)
'''
#turn right
def turn_right():
tetris.speed("fastest")
tetris.setheading(0)
tetris.speed(1)
tetris.forward(10)
tetris.speed("fastest")
tetris.setheading(270)
#turn left
def turn_left():
tetris.speed("fastest")
tetris.setheading(180)
tetris.speed(1)
tetris.forward(10)
tetris.speed("fastest")
tetris.setheading(270)
#down
#tetris container/backround
drawer.pensize(5)
drawer.speed("fastest")
drawer.penup()
drawer.goto(150, 200)
drawer.pendown()
drawer.setheading(270)
drawer.forward(400)
drawer.setheading(180)
drawer.forward(300)
drawer.setheading(90)
drawer.forward(400)
drawer.hideturtle()
#game WIP!!!!!!!!!!
y = 0
space = int(1)
tracer = True
def spawn_T():
new_T=rand.choice(Tshape)
tetris.shape(t_block_180)
tetris.pu()
tetris.goto(0, 200)
tetris.setheading(270)
tetris.forward(10)
'''
if ((abs(space - starty)) < 200):
tetris.forward(2)
else:
'''
tetris.stamp()
'''
space = space =+ 1
'''
tetris.hideturtle()
tetris.goto(0,200)
tetris.showturtle()
if (y == 0):
spawn_T()
#changeing the directions of the sprites
#events
wn.onkeypress(turn_right, "Right")
wn.onkeypress(turn_left, "Left")
wn.onkeypress(sprite_right, "a")
wn.onkeypress(sprite_left, "d")
'''
wn.onkeypress(fast_down, "s")
'''
wn.listen()
wn.mainloop()
</code></pre>
<p>Here is the google drive file <a href="https://drive.google.com/drive/folders/1Q_zXEqm4aFHQ4RV-ZvEXCK2Wi7SHMxrW?usp=share_link" rel="nofollow noreferrer">https://drive.google.com/drive/folders/1Q_zXEqm4aFHQ4RV-ZvEXCK2Wi7SHMxrW?usp=share_link</a></p>
| [
{
"answer_id": 74383220,
"author": "Dave2e",
"author_id": 5792244,
"author_profile": "https://Stackoverflow.com/users/5792244",
"pm_score": 2,
"selected": false,
"text": "i<-1:16\nmatplot2[i,1] = mean(matplot[matplot$Year==(2002 + i), 'TotalTime'])\n"
},
{
"answer_id": 74383224,
"author": "r2evans - GO NAVY BEAT ARMY",
"author_id": 3358272,
"author_profile": "https://Stackoverflow.com/users/3358272",
"pm_score": 3,
"selected": true,
"text": "mean(TotalTime)"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74383379",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20464220/"
] |
74,383,394 | <p>I am trying to concatenate every element in a slice of <code>&str</code>s (<code>&[&str]</code>) into a single owned <code>String</code>. For example, I want to turn <code>&['Hello', ' world!']</code> into <code>"Hello world!"</code>.</p>
<p>I tried to do this by converting the slice into an iterator, then mapping over the iterator and converting each <code>&str</code> into an owned <code>String</code>, then collect them all into a <code>Vec<String></code> and running <code>.join("")</code>, but I keep getting a type error.</p>
<p>Here is my code:</p>
<pre class="lang-rust prettyprint-override"><code>fn concat_str(a: &[&str]) -> String {
a.into_iter().map(|s| s.to_owned()).collect::<Vec<String>>().join("")
}
fn main() {
let arr = ["Dog", "Cat", "Bird", "Lion"];
println!("{}", concat_str(&arr[..3])); // should print "DogCatBird"
println!("{}", concat_str(&arr[2..])); // should print "BirdLion"
println!("{}", concat_str(&arr[1..3])); // should print "CatBird"
}
</code></pre>
<p>And here is the compiler error that I am getting:</p>
<pre class="lang-rust prettyprint-override"><code>error[E0277]: a value of type `Vec<String>` cannot be built from an iterator over elements of type `&str`
--> code.rs:2:38
|
2 | a.into_iter().map(|s| s.to_owned()).collect::<Vec<String>>().join("")
| ^^^^^^^ value of type `Vec<String>` cannot be built from `std::iter::Iterator<Item=&str>`
|
= help: the trait `FromIterator<&str>` is not implemented for `Vec<String>`
note: required by a bound in `collect`
--> /Users/michaelfm1211/.rustup/toolchains/stable-x86_64-apple-darwin/lib/rustlib/src/rust/library/core/src/iter/traits/iterator.rs:1780:19
|
1780 | fn collect<B: FromIterator<Self::Item>>(self) -> B
| ^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `collect`
error: aborting due to previous error
For more information about this error, try `rustc --explain E0277`.
</code></pre>
<p>It says that I cannot collect into a <code>Vec<String></code> because the iterator is not of a <code>String</code>, but I thought that I had converted it to a <code>String</code> with <code>.map(|s| s.to_owned())</code>.</p>
<p>How can I fix this? I am also new to rust, so it would be very helpful is someone could explain what I did wrong.</p>
| [
{
"answer_id": 74383433,
"author": "Mikdore",
"author_id": 8309536,
"author_profile": "https://Stackoverflow.com/users/8309536",
"pm_score": 3,
"selected": true,
"text": "into_iter"
},
{
"answer_id": 74387720,
"author": "Miiao",
"author_id": 20028181,
"author_profile": "https://Stackoverflow.com/users/20028181",
"pm_score": 0,
"selected": false,
"text": "fn concat_str(a: &[&str]) -> String {\n a.iter()\n .cloned()\n .collect()\n}\n"
},
{
"answer_id": 74390274,
"author": "hellow",
"author_id": 1021920,
"author_profile": "https://Stackoverflow.com/users/1021920",
"pm_score": 2,
"selected": false,
"text": "join"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74383394",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13376511/"
] |
74,383,395 | <p>This code used to get a xlsx file and write over it, but after updating from pandas 1.1.5 to 1.5.1 I got <code>zipfile.badzipfile file is not a zip file</code></p>
<p>Then I read <a href="https://stackoverflow.com/a/66472617/13274766">here</a> that after pandas 1.2.0 the <code>pd.ExcelWriter(report_path, engine='openpyxl')</code> creates a new file but as this is a completely empty file, openpyxl cannot load it.</p>
<p>Knowing that, I changed the code to this one, but now I'm getting <code>AttributeError: property 'sheets' of 'OpenpyxlWriter' object has no setter</code>. How should I handle this?</p>
<pre><code>book = load_workbook('Resultados.xlsx')
writer = pd.ExcelWriter('Resultados.xlsx', engine='openpyxl')
writer.book = book
writer.sheets = dict((ws.title, ws) for ws in book.worksheets)
reader = pd.read_excel(r'Resultados.xlsx')
df = pd.DataFrame.from_dict(dict_)
df.to_excel(writer, index=False, header=False, startrow=len(reader) + 1)
writer.close()
</code></pre>
| [
{
"answer_id": 74383433,
"author": "Mikdore",
"author_id": 8309536,
"author_profile": "https://Stackoverflow.com/users/8309536",
"pm_score": 3,
"selected": true,
"text": "into_iter"
},
{
"answer_id": 74387720,
"author": "Miiao",
"author_id": 20028181,
"author_profile": "https://Stackoverflow.com/users/20028181",
"pm_score": 0,
"selected": false,
"text": "fn concat_str(a: &[&str]) -> String {\n a.iter()\n .cloned()\n .collect()\n}\n"
},
{
"answer_id": 74390274,
"author": "hellow",
"author_id": 1021920,
"author_profile": "https://Stackoverflow.com/users/1021920",
"pm_score": 2,
"selected": false,
"text": "join"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74383395",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13274766/"
] |
74,383,418 | <p>I have an HTML content and I am trying to extract the text. In the HTML content, I have gif images. Due to this the extract text process is taking longer time with InnerHTML.</p>
<p>Is there any way to extract text from HTML tags without using InnerHTML?</p>
<p>Right now I am using the below code.</p>
<pre><code> function extractText(html) {
const span = document.createElement('span');
span.innerHTML = html;
return span.textContext || span.innerText;
}
</code></pre>
<p>Is there any alternative to above approach? Any regular expression we can use?</p>
| [
{
"answer_id": 74383433,
"author": "Mikdore",
"author_id": 8309536,
"author_profile": "https://Stackoverflow.com/users/8309536",
"pm_score": 3,
"selected": true,
"text": "into_iter"
},
{
"answer_id": 74387720,
"author": "Miiao",
"author_id": 20028181,
"author_profile": "https://Stackoverflow.com/users/20028181",
"pm_score": 0,
"selected": false,
"text": "fn concat_str(a: &[&str]) -> String {\n a.iter()\n .cloned()\n .collect()\n}\n"
},
{
"answer_id": 74390274,
"author": "hellow",
"author_id": 1021920,
"author_profile": "https://Stackoverflow.com/users/1021920",
"pm_score": 2,
"selected": false,
"text": "join"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74383418",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11855535/"
] |
74,383,426 | <p>Is it possible to combine together addClass and fadeIn in JS?
I'm trying to develop a script where on text hover (the title), the div container change background fading in/out (the whole section).</p>
<pre><code>$(document).ready(function () {
$('#1st').hover(function () {
$('#BG').addClass('first');
$('#BG').removeClass('second');
});
$('#2nd').hover(function () {
$('#BG').addClass('second');
$('#BG').removeClass('first');
});
});
</code></pre>
<p>I tried to add the fading effect but without success.</p>
<pre><code>$(document).ready(function () {
$('#1st').hover(function () {
$('#BG').stop(true, true).addClass('first', 400);
$('#BG').stop(true, true).removeClass('second', 400);
});
$('#2nd').hover(function () {
$('#BG').stop(true, true).addClass('second', 400);
$('#BG').stop(true, true).removeClass('first', 400);
});
});
</code></pre>
<p>Is there a way to make them working together?</p>
<p>Thanks in advance for any kind of suggestions :-)</p>
| [
{
"answer_id": 74383433,
"author": "Mikdore",
"author_id": 8309536,
"author_profile": "https://Stackoverflow.com/users/8309536",
"pm_score": 3,
"selected": true,
"text": "into_iter"
},
{
"answer_id": 74387720,
"author": "Miiao",
"author_id": 20028181,
"author_profile": "https://Stackoverflow.com/users/20028181",
"pm_score": 0,
"selected": false,
"text": "fn concat_str(a: &[&str]) -> String {\n a.iter()\n .cloned()\n .collect()\n}\n"
},
{
"answer_id": 74390274,
"author": "hellow",
"author_id": 1021920,
"author_profile": "https://Stackoverflow.com/users/1021920",
"pm_score": 2,
"selected": false,
"text": "join"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74383426",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19764257/"
] |
74,383,440 | <p>I am trying to mark the index number for each duplicated item in the below dataframe.</p>
<pre><code> Column_A
0 Kitten
1 Kitten
2 Judy
3 Lamb
4 Momo
5 Judy
</code></pre>
<p>The new dataframe I want is as follows. As you can see, the items which have more than one (such as "Judy") are marked.</p>
<pre><code> Column_B Column_A
0 Kitten_1 Kitten
1 Kitten_2 Kitten
2 Judy_1 Judy
3 Lamb_1 Lamb
4 Momo _2 Momo
5 Judy_2 Judy
</code></pre>
<p>My code is as follows.</p>
<pre><code>import pandas as pd
# My dataframe
data = {'Column_A':['Kitten','Kitten','Judy','Lamb','Momo','Judy']}
df = pd.DataFrame(data)
df = df.sort_values("Column_A", axis = 0, ascending = False)
df_list = df['Column_A'].tolist()
df_list.sort()
new_df_list = list(set(df_list))
new_list = []
for k in new_df_list:
ori_list = df[df["Column_A"] == k ]['Column_A'].tolist()
number = len(ori_list)
for n in range(number):
new_list.append(k+'_'+str(n+1))
print(k+'_'+str(n+1))
print(len(new_list))
new_list.sort(reverse=True)
new_DF=pd.DataFrame(new_list, columns = ['Column_B'])
final_df = pd.concat([new_DF,df],axis=1)
print(final_df)
</code></pre>
<p>However, the output is as below, which is out of order.</p>
<pre><code> Column_B Column_A
0 Momo_1 Kitten
1 Lamb_1 Kitten
2 Kitten_2 Judy
3 Kitten_1 Lamb
4 Judy_2 Momo
5 Judy_1 Judy
</code></pre>
<p>Please help me fix this issue.</p>
| [
{
"answer_id": 74383600,
"author": "Sheldon",
"author_id": 6440589,
"author_profile": "https://Stackoverflow.com/users/6440589",
"pm_score": 1,
"selected": true,
"text": "import pandas as pd\nmylist = ['Kitten', 'Kitten', 'Judy', 'Lamb', 'Momo', 'Judy']\ndf=pd.DataFrame()\ndf['Column_A'] = mylist\n"
},
{
"answer_id": 74383968,
"author": "ziying35",
"author_id": 16755671,
"author_profile": "https://Stackoverflow.com/users/16755671",
"pm_score": 2,
"selected": false,
"text": "out = (df.Column_A.str.cat((df.groupby('Column_A')\n .cumcount()+1).astype('str'), sep='_')\n .rename('Column_B')\n .to_frame()\n .join(df))\nprint(out)\n>>>\n\n Column_B Column_A\n0 Kitten_1 Kitten\n1 Kitten_2 Kitten\n2 Judy_1 Judy\n3 Lamb_1 Lamb\n4 Momo_1 Momo\n5 Judy_2 Judy\n"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74383440",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16277415/"
] |
74,383,448 | <p>I am trying to create a simple function that returns the least value passed to the function... but when running it doesn't work it just returns the same values I pass into the function 15,2,3 which should return 2... can someone help me and tell me why it doesn't work?</p>
<pre><code>CREATE OR REPLACE
function
GET_LEAST_VALUE(in_numbers IN VARCHAR2)
RETURN VARCHAR2
IS
vReturn varchar2(50);
BEGIN
vReturn := least(in_numbers);
return vReturn;
END;
</code></pre>
| [
{
"answer_id": 74384809,
"author": "Littlefoot",
"author_id": 9097906,
"author_profile": "https://Stackoverflow.com/users/9097906",
"pm_score": 1,
"selected": false,
"text": "regexp_substr"
},
{
"answer_id": 74385976,
"author": "p3consulting",
"author_id": 4956336,
"author_profile": "https://Stackoverflow.com/users/4956336",
"pm_score": 0,
"selected": false,
"text": "CREATE OR REPLACE FUNCTION get_least_value (in_numbers IN VARCHAR2) RETURN NUMBER IS\n w_result NUMBER ;\nBEGIN\n SELECT MIN(value) INTO w_result FROM \n json_table (\n '[' || in_numbers || ']',\n '$[*]'\n columns (\n value NUMBER PATH '$'\n )\n )\n ;\n RETURN w_result ;\nEND ;\n/\n\n\nSELECT get_least_value('4,1,9,0,-5') from dual ;\n\n\n-5\n"
},
{
"answer_id": 74386519,
"author": "MT0",
"author_id": 1509264,
"author_profile": "https://Stackoverflow.com/users/1509264",
"pm_score": 0,
"selected": false,
"text": "LEAST"
},
{
"answer_id": 74408318,
"author": "d r",
"author_id": 19023353,
"author_profile": "https://Stackoverflow.com/users/19023353",
"pm_score": 0,
"selected": false,
"text": "create or replace Function Get_Least(P_LIST VARCHAR2, P_DELIMITER VARCHAR2 := ',') Return NUMBER AS\nBEGIN\n Declare\n elements STRING_ARRAY := STRING_ARRAY();\n least_element Number(12) := 999999999999;\n Begin\n elements := split(P_LIST , P_DELIMITER);\n For i In 1..elements.count Loop\n If To_Number(elements(i)) < least_element Then\n least_element := To_Number(elements(i));\n End If;\n End Loop;\n RETURN least_element;\n End;\nEND get_Least;\n"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74383448",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13936549/"
] |
74,383,472 | <p>ALL,</p>
<p>I just tried the query found <a href="https://learn.microsoft.com/en-us/sql/relational-databases/databases/view-a-list-of-databases-on-an-instance-of-sql-server?view=sql-server-ver16#TsqlProcedure" rel="nofollow noreferrer">here</a>, but it gave me all names.</p>
<p>How do I filter out system databases names?</p>
<p>TIA!</p>
<p>EDIT:</p>
<p>The suggested solutions contains hardcoded values, either names or hardcoded number.
However, those are different depending on some other parameters.</p>
| [
{
"answer_id": 74384809,
"author": "Littlefoot",
"author_id": 9097906,
"author_profile": "https://Stackoverflow.com/users/9097906",
"pm_score": 1,
"selected": false,
"text": "regexp_substr"
},
{
"answer_id": 74385976,
"author": "p3consulting",
"author_id": 4956336,
"author_profile": "https://Stackoverflow.com/users/4956336",
"pm_score": 0,
"selected": false,
"text": "CREATE OR REPLACE FUNCTION get_least_value (in_numbers IN VARCHAR2) RETURN NUMBER IS\n w_result NUMBER ;\nBEGIN\n SELECT MIN(value) INTO w_result FROM \n json_table (\n '[' || in_numbers || ']',\n '$[*]'\n columns (\n value NUMBER PATH '$'\n )\n )\n ;\n RETURN w_result ;\nEND ;\n/\n\n\nSELECT get_least_value('4,1,9,0,-5') from dual ;\n\n\n-5\n"
},
{
"answer_id": 74386519,
"author": "MT0",
"author_id": 1509264,
"author_profile": "https://Stackoverflow.com/users/1509264",
"pm_score": 0,
"selected": false,
"text": "LEAST"
},
{
"answer_id": 74408318,
"author": "d r",
"author_id": 19023353,
"author_profile": "https://Stackoverflow.com/users/19023353",
"pm_score": 0,
"selected": false,
"text": "create or replace Function Get_Least(P_LIST VARCHAR2, P_DELIMITER VARCHAR2 := ',') Return NUMBER AS\nBEGIN\n Declare\n elements STRING_ARRAY := STRING_ARRAY();\n least_element Number(12) := 999999999999;\n Begin\n elements := split(P_LIST , P_DELIMITER);\n For i In 1..elements.count Loop\n If To_Number(elements(i)) < least_element Then\n least_element := To_Number(elements(i));\n End If;\n End Loop;\n RETURN least_element;\n End;\nEND get_Least;\n"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74383472",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/945871/"
] |
74,383,473 | <p>I am trying to send a string to a stored procedure which single quotes of multiple Id's. I am going use that string in IN clause in the stored procedure.</p>
<p>In order to test this I set string to like below but I am getting error. Help me out how to pass this to the stored procedure?</p>
<pre><code>DECLARE @str1 AS NVARCHAR(max)
SET @str1 = '3229622','4183229','3257553','3003673','3358312','0682773','4069249','0854620','4667379','0013862','1319623','3220826','3405633','0797654','3240120'
--print @str1
EXEC [GetMemberInfoAndMemberSubscriptions] @str1
</code></pre>
<p>I'm getting an error</p>
<blockquote>
<p>Msg 102, Level 15, State 1, Line 2<br />
Incorrect syntax near ','</p>
</blockquote>
<p>This is the stored procedure:</p>
<pre><code>CREATE OR ALTER PROCEDURE [dbo].[GetMemberInfoAndMemberSubscriptions]
(@ip_master_customer_ids AS NVARCHAR(max))
AS
BEGIN
SELECT
[MASTER_CUSTOMER_ID], USR_SPE_Membership_Status
FROM
CUSTOMER
WHERE
[MASTER_CUSTOMER_ID] IN (@ip_master_customer_ids)
END
</code></pre>
<p>And this is my C# code calling it:</p>
<pre><code>string MemberNumbers = "'3229622','4183229','3257553','3003673','3358312','0682773','4069249','0854620','4667379','0013862','1319623','3220826','3405633','0797654','3240120'";
</code></pre>
<p>@Nick suggest to table valued parameter with link <a href="https://gavilan.blog/2022/04/20/passing-a-list-of-values-to-a-stored-procedure-from-c/" rel="nofollow noreferrer">https://gavilan.blog/2022/04/20/passing-a-list-of-values-to-a-stored-procedure-from-c/</a></p>
<pre><code>CREATE TYPE StringList AS TABLE (Id nvarchar(50));
</code></pre>
<p>What other workaround we have to implement this?</p>
| [
{
"answer_id": 74383785,
"author": "Patrick Hurst",
"author_id": 18522514,
"author_profile": "https://Stackoverflow.com/users/18522514",
"pm_score": 0,
"selected": false,
"text": "DECLARE @string NVARCHAR(10) = '''apple'''\nPRINT @string\n"
},
{
"answer_id": 74384069,
"author": "Nick.McDermaid",
"author_id": 1690193,
"author_profile": "https://Stackoverflow.com/users/1690193",
"pm_score": 0,
"selected": false,
"text": "string MemberNumbers = '1234|324763|234879|23879476|238478|23872|23178'\n"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74383473",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/158008/"
] |
74,383,476 | <p>I need to make a Quadtree in Haskell. But I never used the language before. As I understand, there is no null pointers in Haskell. So how could I instantiate a null version of Group for the pointers of the Quadtree(if there is even a way)?</p>
<pre><code>data Group = Group {
idf :: Int,
name :: String,
lat :: Int,
long :: Int,
nw :: Group,
ne :: Group,
sw :: Group,
se :: Group
} deriving Show
main :: IO()
main = do
let g1 = Group { idf = 0, name = "Ababa", lat = 32, long = 40, nw = ???}
print g1
</code></pre>
<p>I know Maybe exists. No idea how to use it in this context though.</p>
| [
{
"answer_id": 74383784,
"author": "Fyodor Soikin",
"author_id": 180286,
"author_profile": "https://Stackoverflow.com/users/180286",
"pm_score": 4,
"selected": true,
"text": "Maybe"
},
{
"answer_id": 74385289,
"author": "Daniel Wagner",
"author_id": 791604,
"author_profile": "https://Stackoverflow.com/users/791604",
"pm_score": 2,
"selected": false,
"text": "Group"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74383476",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20464350/"
] |
74,383,478 | <p>I want to add two shorts as if they are unsigned and get the carry bit from the addition.</p>
<p>So for example, the following shorts represented in binary</p>
<pre><code>1111111111111111 (-1) +
0000000000000001 (1)
----------------
0000000000000000 (0)
</code></pre>
<p>Their addition has the carry bit of <code>1</code>.</p>
<p>Is there a way to obtain this carry bit from two's compliment addition?</p>
<p><strong>The only restriction to any solution is that the following data types cannot be used: int, long, char because I'm working on the Java Card platform</strong></p>
<hr />
<p><strong>UPDATE:</strong></p>
<p>The reason I need this is to re-create integer addition with two shorts. I am working with the Java Card platform, which doesn't support integers, hence I wanted to use two shorts to represent one integer.</p>
<p><a href="https://stackoverflow.com/users/1552534/wjs">WJS</a>'s answer was perfect for what I needed. The following code block illustrates what I wanted to create:</p>
<pre class="lang-java prettyprint-override"><code>short xA = (short) 0b1111111111111111, xB = (short) 0b1111111111111111;
short yA = (short) 0b0000000000000000, yB = (short) 0b0000000000000001;
short targetA, targetB;
targetA = (short) (xA + yA + (xB < 0 && yB < 0 || xB < 0 && yB >= -xB || yB < 0 && xB >= -yB ? 1 : 0));
targetB = (short) (xB + yB);
</code></pre>
<p>Where <code>A</code> is the high part and <code>B</code> is the low part of the integer.</p>
<p>This code block is the short equivalent of <code>target = x + y</code>.</p>
| [
{
"answer_id": 74384004,
"author": "WJS",
"author_id": 1552534,
"author_profile": "https://Stackoverflow.com/users/1552534",
"pm_score": 3,
"selected": true,
"text": "short a = some short;\nshort b = some short;\nshort carry = getCarry(a, b);\n\npublic static short getCarry(short a, short b) {\n if (a < 0 && b < 0 || a < 0 && b >= -a || b < 0 && a >= -b) {\n return 1;\n }\n return 0;\n}\n\n"
},
{
"answer_id": 74384147,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "public static void main(String[] args) {\n short a = -1;\n short b = 1;\n short sum = (short)(a + b);\n int carry = Short.compareUnsigned(sum, a) < 0 ? 1 : 0;\n System.out.printf(\"sum = %d carry = %d%n\", sum, carry);\n}\n"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74383478",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9700478/"
] |
74,383,504 | <p>In my js file I have a class <em>slideshow</em> and an array <em>slideshows</em> which I fill with instances of the slideshow class. Later in my code I use a for loop, where I iterate over each element in <em>slideshows</em> and try to get a specific value from it. However, when trying to run my code I get the following error message:</p>
<blockquote>
<p>Uncaught TypeError: slideshows[i].images[slideshows[i].shownImage] is undefined</p>
</blockquote>
<p>My code looks like this:</p>
<pre><code>let slideshows = [];
class slideshow{
constructor(images){
this._images = images;
this._shownImage = 0;
}
get images() {return this._images;}
get shownImage() {return this._shownImage;}
set images(images) {this._images = images;}
set shownImage(shownImage) {this._shownImage = shownImage;}
}
// This function is called when the page has loaded in
function setupSlideshow(){
// Create Array of all slideshows
slideshowDivs = document.querySelectorAll("div.slideshow");
for(i = 0; i < slideshowDivs.length; i++){
slideshows.push(new slideshow(slideshowDivs[i].querySelectorAll("slideshow-image")));
}
// Show Active Image
for(i = 0; i < slideshows.length; i++){
slideshows[i].images[slideshows[i].shownImage].style.display = 'block';
// The line above this one triggers the error
}
}
</code></pre>
<p>I believe the syntax isn't the problem, although I don't have a lot of experience with js classes. The only thing I can think of that could be the problem is that js doesn't know that slideshows[i] is of class slideshow and thus doesn't look at the functions I declared in my class.</p>
<p>Edits:</p>
<ul>
<li>added declaration of slideshows</li>
<li>changed slideshowDivs += ... to slideshowDivs.push(...)</li>
</ul>
| [
{
"answer_id": 74384004,
"author": "WJS",
"author_id": 1552534,
"author_profile": "https://Stackoverflow.com/users/1552534",
"pm_score": 3,
"selected": true,
"text": "short a = some short;\nshort b = some short;\nshort carry = getCarry(a, b);\n\npublic static short getCarry(short a, short b) {\n if (a < 0 && b < 0 || a < 0 && b >= -a || b < 0 && a >= -b) {\n return 1;\n }\n return 0;\n}\n\n"
},
{
"answer_id": 74384147,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "public static void main(String[] args) {\n short a = -1;\n short b = 1;\n short sum = (short)(a + b);\n int carry = Short.compareUnsigned(sum, a) < 0 ? 1 : 0;\n System.out.printf(\"sum = %d carry = %d%n\", sum, carry);\n}\n"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74383504",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20361715/"
] |
74,383,527 | <p>I am trying to combine 2 tables in such a way that rows with the same ID (the ID may be a combination of multiple columns) are summed together. Rows without a match of either table are still retained.</p>
<p>Here is an illustration of what I had in mind. <code>C1</code> & <code>C2</code> are the ID columns whilst <code>W1</code> and <code>W2</code> are the rows to be summed.</p>
<p>DF A:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>C1</th>
<th>C2</th>
<th>W1</th>
<th>W2</th>
</tr>
</thead>
<tbody>
<tr>
<td>A</td>
<td>A</td>
<td>5</td>
<td>3</td>
</tr>
<tr>
<td>A</td>
<td>B</td>
<td>6</td>
<td>7</td>
</tr>
<tr>
<td>B</td>
<td>A</td>
<td>2</td>
<td>3</td>
</tr>
<tr>
<td>B</td>
<td>B</td>
<td>8</td>
<td>8</td>
</tr>
</tbody>
</table>
</div>
<p><a href="https://i.stack.imgur.com/O9YWH.png" rel="nofollow noreferrer">DFA</a></p>
<p>DF B:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>C1</th>
<th>C2</th>
<th>W1</th>
<th>W2</th>
</tr>
</thead>
<tbody>
<tr>
<td>A</td>
<td>A</td>
<td>2</td>
<td>7</td>
</tr>
<tr>
<td>A</td>
<td>C</td>
<td>4</td>
<td>8</td>
</tr>
<tr>
<td>B</td>
<td>A</td>
<td>9</td>
<td>1</td>
</tr>
<tr>
<td>B</td>
<td>D</td>
<td>3</td>
<td>5</td>
</tr>
</tbody>
</table>
</div>
<p><a href="https://i.stack.imgur.com/rRLnJ.png" rel="nofollow noreferrer">DFB</a></p>
<p>Resulting dataframe</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>C1</th>
<th>C2</th>
<th>W1</th>
<th>W2</th>
</tr>
</thead>
<tbody>
<tr>
<td>A</td>
<td>A</td>
<td>7</td>
<td>10</td>
</tr>
<tr>
<td>A</td>
<td>B</td>
<td>6</td>
<td>7</td>
</tr>
<tr>
<td>A</td>
<td>C</td>
<td>4</td>
<td>8</td>
</tr>
<tr>
<td>B</td>
<td>A</td>
<td>11</td>
<td>4</td>
</tr>
<tr>
<td>B</td>
<td>B</td>
<td>8</td>
<td>8</td>
</tr>
<tr>
<td>B</td>
<td>D</td>
<td>3</td>
<td>5</td>
</tr>
</tbody>
</table>
</div>
<p><a href="https://i.stack.imgur.com/7aQZF.png" rel="nofollow noreferrer">Resulting DF</a></p>
<p>I had two ideas, but I can't get either implemented at the moment. The first is to do a union on both dataframes and then do a groupby aggregation but I am unsure if this is the most efficient approach.</p>
<p>The other was doing an outer join on both Data frames and then summing the common columns. I had trouble implementing this as the ID columns come from a list and are variables that change from time to time and so the join can't be hard coded.</p>
| [
{
"answer_id": 74384004,
"author": "WJS",
"author_id": 1552534,
"author_profile": "https://Stackoverflow.com/users/1552534",
"pm_score": 3,
"selected": true,
"text": "short a = some short;\nshort b = some short;\nshort carry = getCarry(a, b);\n\npublic static short getCarry(short a, short b) {\n if (a < 0 && b < 0 || a < 0 && b >= -a || b < 0 && a >= -b) {\n return 1;\n }\n return 0;\n}\n\n"
},
{
"answer_id": 74384147,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "public static void main(String[] args) {\n short a = -1;\n short b = 1;\n short sum = (short)(a + b);\n int carry = Short.compareUnsigned(sum, a) < 0 ? 1 : 0;\n System.out.printf(\"sum = %d carry = %d%n\", sum, carry);\n}\n"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74383527",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19621357/"
] |
74,383,540 | <p>I am trying to use this service getTodaysRoute() where I figure out what is today's route node key using .equalTo and from what I understand then I have to use this .on function snapshot from which then I can finally get the key after that I use this key to get data as an observable. The problem happens that the code inside .on function gets executed last and the first time page load my todaysroutekey is undefined. How can I avoid a situation like this?</p>
<pre><code>getTodaysRoute(): Observable<Location[]> {
const date = new Date().toISOString().replace(/\T.*/, '');
const userdate = `${this.useremail}${date}`;
let todaysroutekey;
this.db.database
.ref()
.child('routes')
.orderByChild('user_date')
.equalTo(userdate)
.on('child_added', function ( snapshot) {
todaysroutekey = snapshot.key;
});
console.log(todaysroutekey);
return this.db
.list(`${this.routesUrl}/${todaysroutekey}/locations`)
.snapshotChanges()
.pipe(
map((locations) =>
locations.map(
(location) =>
({
key: location.payload.key,
...(location.payload.val() as {}),
} as unknown as Location)
)
)
);
}
</code></pre>
<p>And this is my component code</p>
<pre><code> routeLocations: any[];
constructor(private firebase: FirebaseService) { }
ngOnInit(): void {
this.firebase.getTodaysRoute().subscribe((value) => {
this.routeLocations = value;
});
}
</code></pre>
| [
{
"answer_id": 74384004,
"author": "WJS",
"author_id": 1552534,
"author_profile": "https://Stackoverflow.com/users/1552534",
"pm_score": 3,
"selected": true,
"text": "short a = some short;\nshort b = some short;\nshort carry = getCarry(a, b);\n\npublic static short getCarry(short a, short b) {\n if (a < 0 && b < 0 || a < 0 && b >= -a || b < 0 && a >= -b) {\n return 1;\n }\n return 0;\n}\n\n"
},
{
"answer_id": 74384147,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "public static void main(String[] args) {\n short a = -1;\n short b = 1;\n short sum = (short)(a + b);\n int carry = Short.compareUnsigned(sum, a) < 0 ? 1 : 0;\n System.out.printf(\"sum = %d carry = %d%n\", sum, carry);\n}\n"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74383540",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13454000/"
] |
74,383,574 | <p>I am trying to do some coniditonal styling in react js. Very new to react, so there may be a better way to do this, but have searched the internet to no avail. I am trying to check the screen size and style based off of said screen size. In this use case I am wanting to center some text based off of screen size. Can someone please tell me if there is a better way to do this? This is not working for me currently.</p>
<p>Edit: Placed some logs in there and what it is doing exactly is when the page loads "textAlign" is not applied to the element at all even though the screen size is > 993px. Once I shrink the screen down to < 993px and > 578px is applies the "textAlign: center" to the element and then once it shrinks down < 578px it does not set it back to none. It keeps it centered.</p>
<pre><code>const styles = {
footerColOne:{
textAlign: deviceSize > 993 ? "none" : (deviceSize < 993 && deviceSize > 578) ? "center" : "none",
paddingLeft: deviceSize < 993 ? "26px" : "80px",
paddingTop: deviceSize < 993 ? "28px" : "63px",
},
footerColTwo:{
textAlign: deviceSize > 993 ? "none" : (deviceSize < 993 && deviceSize > 578) ? "center" : "none",
paddingLeft: deviceSize < 993 ? "26px" : deviceSize < 578 ? "51px" : "50px",
paddingTop: deviceSize < 993 ? "40px" : "86px",
},
}
</code></pre>
<p>I am then calling that style like this</p>
<pre><code><Col lg={3} style={ styles.footerColOne }>
</code></pre>
<p>Any help is greatly appreciated.</p>
<p><strong>Last Edit:</strong></p>
<p>So I have found media queries is indeed the preferred way to go here, my ternary condition above worked though I made an idiot mistake and was setting <code>textAlign</code> to <code>none</code> when that value does not exist for that property. It should be set to <code>initial</code> in this case.</p>
| [
{
"answer_id": 74383691,
"author": "Mohammed Shahed",
"author_id": 19067773,
"author_profile": "https://Stackoverflow.com/users/19067773",
"pm_score": 2,
"selected": true,
"text": "media query"
},
{
"answer_id": 74383727,
"author": "jeongjuyoung",
"author_id": 20463972,
"author_profile": "https://Stackoverflow.com/users/20463972",
"pm_score": 0,
"selected": false,
"text": "const getDevice = (deviceSize) => \n deviceSize < 993 \n ? (deviceSize < 993 && deviceSize > 578) \n ? 'tablet'\n : 'mobile'\n : 'web'\n\n\n// if declare css -> return class\n// component use className instead of styles\n// <Col lg={3} className={...} />\nconst footerColOne = {\n 'web': () => {\n\n return {\n textAlign: 'none',\n paddingLeft: '26px',\n paddingTop: '28px'\n }\n },\n 'tablet': () => {\n return {\n textAlign: 'center',\n paddingLeft: '80px',\n paddingTop: '63px'\n }\n },\n 'mobile': () => {\n return {\n textAlign: 'none',\n paddingLeft: '80px',\n paddingTop: '63px'\n }\n }\n}\n\n\nconst styles = {\n footerColOne: footerColOne[getDevice(deviceSize)]()\n}\n\nconsole.log(styles.footerColOne)\n\n// <Col lg={3} style={ styles.footerColOne }>\n\n\n"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74383574",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4131053/"
] |
74,383,647 | <pre class="lang-lua prettyprint-override"><code>function string.split(input, delimiter)
input = tostring(input)
delimiter = tostring(delimiter)
if (delimiter=='') then return false end
local pos,arr = 0, {}
-- for each divider found
for st,sp in function() return string.find(input, delimiter, pos, true) end do
table.insert(arr, string.sub(input, pos, st - 1))
pos = sp + 1
end
table.insert(arr, string.sub(input, pos))
return arr
end
</code></pre>
<p>why use</p>
<pre class="lang-lua prettyprint-override"><code>function() return string.find(input, delimiter, pos, true) end
</code></pre>
<p>after <code>in</code> , rather then use</p>
<pre class="lang-lua prettyprint-override"><code>for st,sp in string.find(input, delimiter, pos, true) do
table.insert(arr, string.sub(input, pos, st - 1))
pos = sp + 1
end
</code></pre>
<p>I just want to know why do this</p>
| [
{
"answer_id": 74383957,
"author": "pynexj",
"author_id": 900078,
"author_profile": "https://Stackoverflow.com/users/900078",
"pm_score": 2,
"selected": false,
"text": "for .. in"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74383647",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14375125/"
] |
74,383,685 | <p>So i am practicing header files and implementation files for c++ and i cannot seem to display the letter grade for this program. Everything else is working as it should and displaying the correct data except for the letter grade. I have been trying to figure it out and i think it may be something so simple that i am missing but i need an extra set of eyes. i would really appreciate the help!</p>
<hr />
<pre><code>//Main program
#include <iostream>
#include <string>
#include "studentType.h"
using namespace std;
int main()
{
studentType student;
studentType newStudent("Brain", "Johnson", '*', 85, 95, 3.89);
student.print();
cout << "***************" << endl << endl;
newStudent.print();
cout << "***************" << endl << endl;
return 0;
}
</code></pre>
<hr />
<p>Header File:</p>
<pre><code>#include <string>
using namespace std;
class studentType
{
private:
string firstName;
string lastName;
int grade;
int average;
char courseGrade;
int testScore;
int progScore;
double GPA;
public:
studentType(string fn = "", string ln = "", char courseGrade = '*', int tscore = 0, int pscore = 0, double gpa = 0);
string getFirstName() const;
string getLastName() const;
int getGrade();
char getCourseGrade() const;
int getTestScore() const;
int getProgScore() const;
double getGPA() const;
void setFirstName(string fn);
void setLastName(string ln);
void setGrade();
void setCourseGrade(char courseGrade);
void setTestScore(int tscore);
void setProgScore(int pscore);
void setGPA(double gpa);
void print();
};
</code></pre>
<hr />
<p>Implementation file:</p>
<pre><code>#include <iostream>
#include <string>
#include <iomanip>
#include "studentType.h"
using namespace std;
studentType::studentType(string fn, string ln, char courseGrade, int tscore, int pscore, double gpa)
{
firstName = fn;
lastName = ln;
courseGrade = courseGrade;
testScore = tscore;
progScore = pscore;
GPA = gpa;
}
string studentType::getFirstName() const
{
return firstName;
}
string studentType::getLastName() const
{
return lastName;
}
int studentType::getGrade()
{
return grade;
}
char studentType::getCourseGrade() const
{
return courseGrade;
}
int studentType::getTestScore() const
{
return testScore;
}
int studentType::getProgScore() const
{
return progScore;
}
double studentType::getGPA() const
{
return GPA;
}
void studentType::setFirstName(string fn)
{
firstName = fn;
}
void studentType::setLastName(string ln)
{
lastName = ln;
}
void studentType::setGrade()
{
int average = (testScore + progScore) / 2;
if(average >= 90){
courseGrade = 'A';
}
else if(average >= 80){
courseGrade = 'B';
}
else if(average >= 70){
courseGrade = 'C';
}
else if(average >= 60){
courseGrade = 'D';
}
else{
courseGrade = 'F';
}
}
void studentType::setCourseGrade(char courseGrade)
{
courseGrade = courseGrade;
}
void studentType::setTestScore(int tscore)
{
testScore = tscore;
}
void studentType::setProgScore(int pscore)
{
progScore = pscore;
}
void studentType::setGPA(double gpa)
{
GPA = gpa;
}
void studentType::print()
{
cout << "Name: " << firstName << " " << lastName << endl;
cout << "Grade: " << courseGrade << endl;
cout << "Test Score: " << testScore << endl;
cout << "Programming Score: " << progScore << endl;
cout << "GPA: " << GPA << endl;
}
</code></pre>
<p>I think it has something to do with the constructor like adding my grade() function but to be honest my brain is fried and i just need some help i have been staring at this for way to long...</p>
| [
{
"answer_id": 74383957,
"author": "pynexj",
"author_id": 900078,
"author_profile": "https://Stackoverflow.com/users/900078",
"pm_score": 2,
"selected": false,
"text": "for .. in"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74383685",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20464489/"
] |
74,383,695 | <pre><code>#include <stdio.h>
#include <stdlib.h>
void Increase(int *array1,int *Nums) {
int*array2 = realloc(array1,(*Nums+1)*sizeof(int));
array2[*Nums] = 13;
array2[*Nums-1] = 14;
++(*Nums);
}
int main() {
int NumOfElements=0,i;
int*array=(int*)malloc(0*sizeof(int));
Increase(array,&NumOfElements);
for(i=0;i<NumOfElements;i++) {
printf("%d ", array[i]);
}
free(array);
}
</code></pre>
<p>How many elements will be in the array in <code>main()</code> if I run this program?</p>
<p>Does the <code>Increase()</code> function increase the number of memory cells of the array in <code>main()</code>, or will the array in <code>main()</code> still just have 0 memory cells?</p>
| [
{
"answer_id": 74383909,
"author": "Jeremy Friesner",
"author_id": 131930,
"author_profile": "https://Stackoverflow.com/users/131930",
"pm_score": 2,
"selected": true,
"text": "realloc()"
},
{
"answer_id": 74384370,
"author": "Neil",
"author_id": 2472827,
"author_profile": "https://Stackoverflow.com/users/2472827",
"pm_score": 0,
"selected": false,
"text": "#include <stddef.h>\n\nstruct int_stack { int *data; size_t size, capacity; };\n\nstruct int_stack int_stack(void);\nvoid int_stack_(struct int_stack *);\nint *int_stack_new(struct int_stack *);\n"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74383695",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18265473/"
] |
74,383,775 | <pre><code>Name date leave marked_leave_bfr_days
A 8/1/2021 1 3
A 8/2/2021 1 4
A 8/3/2021 1 5
A 8/4/2021 1 5
A 8/5/2021 1 6
A 8/6/2021 1 7
A 8/7/2021 1 8
A 8/8/2021 0 -1
A 8/9/2021 0 -1
A 8/10/2021 1 12
A 8/11/2021 1 13
A 8/12/2021 0 -1
B 8/4/2021 1 1
B 8/5/2021 1 1
B 8/6/2021 1 3
B 8/7/2021 0 -1
B 8/8/2021 0 -1
B 8/9/2021 0 -1
B 8/10/2021 0 -1
B 8/11/2021 0 -1
</code></pre>
<p>My df is like above. Name is employee code, leave is boolean (=1 means leave, =0 means no leave), marked_leave_bfr_days is how many days prior to date was leave applied.</p>
<p>I wish to transform it to this df:</p>
<pre><code>Name date leave marked_leave_bfr_days leave_applied leave_start leave_end no_of_leaves
A 8/1/2021 1 3 7/29/2021 8/1/2021 8/3/2021 3
A 8/2/2021 1 4 7/29/2021 8/1/2021 8/3/2021 3
A 8/3/2021 1 5 7/29/2021 8/1/2021 8/3/2021 3
A 8/4/2021 1 5 7/30/2021 8/4/2021 8/7/2021 4
A 8/5/2021 1 6 7/30/2021 8/4/2021 8/7/2021 4
A 8/6/2021 1 7 7/30/2021 8/4/2021 8/7/2021 4
A 8/7/2021 1 8 7/30/2021 8/4/2021 8/7/2021 4
A 8/8/2021 0 -1 -1 -1 -1 -1
A 8/9/2021 0 -1 -1 -1 -1 -1
A 8/10/2021 1 12 7/29/2021 8/10/2021 8/11/2021 2
A 8/11/2021 1 13 7/29/2021 8/10/2021 8/11/2021 2
A 8/12/2021 0 -1 -1 -1 -1 -1
B 8/4/2021 1 1 8/3/2021 8/4/2021 8/4/2021 1
B 8/5/2021 1 1 8/4/2021 8/5/2021 8/5/2021 1
B 8/6/2021 1 3 8/3/2021 8/6/2021 8/6/2021 1
B 8/7/2021 0 -1 -1 -1 -1 -1
B 8/8/2021 0 -1 -1 -1 -1 -1
B 8/9/2021 0 -1 -1 -1 -1 -1
B 8/10/2021 0 -1 -1 -1 -1 -1
B 8/11/2021 0 -1 -1 -1 -1 -1
</code></pre>
<p>I am doing this:</p>
<pre><code>df.loc[df.leave==1, 'leave_applied'] = (df['date'] - df['marked_leave_bfr_days'].map(timedelta))
df = df[df.leave==1].groupby(['Name', 'leave_applied').agg({'date':['min', 'max']}).reset_index()
</code></pre>
<p>But, this is not working as there are two separate chunk of leaves applied on same date by User. Is there a way to work around this?</p>
| [
{
"answer_id": 74387985,
"author": "cg-zhou",
"author_id": 5844918,
"author_profile": "https://Stackoverflow.com/users/5844918",
"pm_score": 0,
"selected": false,
"text": "import pandas as pd\nfrom datetime import datetime, timedelta\n\nfile = 'D:/test/TestPython/leave.csv' \ndf = pd.read_csv(file)\n\ndf['leave_applied'] = ''\ndf['leave_start'] = ''\ndf['leave_end'] = ''\ndf['no_of_leaves'] = ''\n\nindexes = []\nprevious_leave_applied = ''\nleave_start = ''\nleave_end = ''\n\n# when a leave duration ends, fill values in the leave duration.\ndef fill_leave_duration(indexes, leave_start, leave_end):\n for index in indexes:\n df.loc[index, 'leave_start'] = leave_start.strftime('%#m/%#d/%Y')\n df.loc[index, 'leave_end'] = leave_end.strftime('%#m/%#d/%Y')\n df.loc[index, 'no_of_leaves'] = (leave_end - leave_start).days + 1\n\nfor index, row in df.iterrows():\n if (row.leave == 0):\n df.loc[index, 'leave_applied'] = -1\n df.loc[index, 'leave_start'] = -1\n df.loc[index, 'leave_end'] = -1\n df.loc[index, 'no_of_leaves'] = -1\n else:\n date = datetime.strptime(row.date, \"%m/%d/%Y\")\n leave_applied = date - timedelta(row.marked_leave_bfr_days)\n df.loc[index, 'leave_applied'] = leave_applied.strftime('%#m/%#d/%Y')\n\n # check whether it is a new start of leave duration.\n if (leave_applied != previous_leave_applied):\n # clear previous row indexes.\n indexes = []\n leave_start = date\n indexes.append(index)\n\n leave_end = date\n fill_leave_duration(indexes, leave_start, leave_end)\n previous_leave_applied = leave_applied\n\ndf.to_csv('D:/test/TestPython/leave_result.csv', index=False)\n\n"
},
{
"answer_id": 74419575,
"author": "sadegh arefizadeh",
"author_id": 19401288,
"author_profile": "https://Stackoverflow.com/users/19401288",
"pm_score": 1,
"selected": false,
"text": "import pandas as pd\nimport numpy as np\nfrom pandas import Timedelta\nfrom itertools import compress\ndate = [pd.Timestamp('8/{}/2021'.format(i)) for i in range(1,13) ]\ndate.extend([pd.Timestamp('8/{}/2021'.format(i)) for i in range(4,12) ])\nname = ['A']*12+['B']*8\nleave = [1]*7+[0]*2 + [1]*2 + [0]+ [1]*3 + [0]*5\nmarked_leave_bfr_days = [3,4,5,5,6,7,8,-1,-1,12,13,-1,1,1,3,-1,-1,-1,-1,-1]\ndata = {'Name': name, 'date':date, 'leave': leave,'marked_leave_bfr_days': marked_leave_bfr_days}\ndf = pd.DataFrame(data=data)\n\ndf.loc[df.leave==1, 'leave_applied'] = (df['date'] - df['marked_leave_bfr_days'].map(Timedelta))\ndf.loc[df.leave==0 ,'leave_applied'] = -1\ndf = df[df.leave==1].groupby(['Name', 'leave_applied']).agg({'date':['min', 'max']}).reset_index()\n"
},
{
"answer_id": 74420712,
"author": "igrinis",
"author_id": 8505817,
"author_profile": "https://Stackoverflow.com/users/8505817",
"pm_score": 2,
"selected": false,
"text": "df['leave_applied'] = (df['date'] - df['marked_leave_bfr_days'].map(lambda x: pd.Timedelta(days=x))).dt.date\n\n# create helper\ndf['hlp_idx'] = (df.leave_applied != df.leave_applied.shift()).cumsum()\n\n# use helper column to create proper date groups \ndate_grp = df.groupby(['Name', 'leave_applied','hlp_idx'])['date']\n\n# create desired values\ndf['leave_start'] = date_grp.transform('min').dt.date\ndf['leave_end'] = date_grp.transform('max').dt.date\ndf['no_of_leaves'] = date_grp.transform('count')\n\n# clean up\ndf.loc[df['marked_leave_bfr_days']==-1,['leave_applied', 'leave_start', 'leave_end','no_of_leaves']] = -1\ndf = df.drop(columns='hlp_idx')\n"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74383775",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19741064/"
] |
74,383,788 | <p>How to reverse a string using pointers. I don't understand any of the answers online. I need it to be explained really slowly.</p>
<p>For an assignment, I need to use pointers to reverse a string (and to use that to test if something is a palindrome), and I cannot for the life of me understand any of the answers to similar questions online. In <a href="https://stackoverflow.com/questions/17200259/">this question</a>, for instance, the top answer is:</p>
<pre><code>void rev_string(char *str)
{
char *p = str, *s = str + strlen(str) - 1;
while (p < s) {
char tmp = *p;
*p++ = *s;
*s-- = tmp;
}
}
</code></pre>
<p>This barely makes sense to me.</p>
<p>First of all, why is the input a <code>char</code> when we're looking to reverse a string? The <code>*</code> marks it as a pointer as well, right? Why is the input a pointer when we're looking to reverse a string?</p>
<p>I understand the first line of code with the variable initialization is meant to set pointer <code>p</code> equal to the start of the string, and pointer <code>s</code> to the tail of the string, but why?</p>
<p>I get the feeling that <code>*p++</code> and <code>*s--</code> are supposed to go to the next letter or the previous letter of the string, respectively, but why does that work?</p>
<p>Please assist.</p>
| [
{
"answer_id": 74384111,
"author": "Pepijn Kramer",
"author_id": 16649550,
"author_profile": "https://Stackoverflow.com/users/16649550",
"pm_score": 1,
"selected": false,
"text": "#include <iostream>\n\nvoid reverse(char* input)\n{\n const std::size_t offset_of_last_character = strlen(input) - 1; \n\n char* begin_pointer = &input[0]; // front_pointer now contains address of first character in string\n char* end_pointer = &input[offset_of_last_character]; // end_pointer now contains address of last character in the string\n\n while (begin_pointer < end_pointer) // as long as pointers don't cross-over in memory continue\n {\n // swap the characters pointed to \n // first iteration this will be first and last character, \n // second iteration this will be the second and the character and last but one character, etc...\n std::swap(*begin_pointer, *end_pointer);\n\n ++begin_pointer; // move one address up in memory, this is where the next character is found\n --end_pointer; // move on address down in memory, this is where the previous character is found\n }\n}\n\nint main()\n{ \n char input[] = \"!dlrow olleH\";\n reverse(input);\n std::cout << input;\n \n return 0;\n}\n"
},
{
"answer_id": 74387225,
"author": "Igor S.K.",
"author_id": 1556829,
"author_profile": "https://Stackoverflow.com/users/1556829",
"pm_score": 0,
"selected": false,
"text": "char"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74383788",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18865975/"
] |
74,383,791 | <p>I have a relative gravity dataset of 697 measurements taken at points with latitude and longitude. I am having trouble converting to an Xarray dataset so that I can inevitably create an interpolated grid with Xarray.interp_like.</p>
<p>I tried creating the DataArray from a series and from a Dataframe using the following article: <a href="https://towardsdatascience.com/basic-data-structures-of-xarray-80bab8094efa" rel="nofollow noreferrer">https://towardsdatascience.com/basic-data-structures-of-xarray-80bab8094efa</a></p>
<p>Using the series method:</p>
<pre><code>idx = pd.MultiIndex.from_arrays(arrays=[lat_grav,long_grav],names=["lat","lon"])
s = pd.Series(data=rel_grav,index=idx)
s
lat lon
36.713923 -116.120574 NaN
-116.120574 NaN
-116.120574 NaN
36.712458 -116.125034 NaN
-116.125034 NaN
..
36.703896 -116.116244 NaN
-116.116244 NaN
36.725249 -116.124976 NaN
-116.124976 NaN
-116.124976 NaN
</code></pre>
<p>The relative gravity measurements remain as NaNs so I decided to check with the DataFrame method:</p>
<pre><code>rel_grav_df = pd.DataFrame({"relativegrav":rel_grav,"lat":lat_grav,"lon":lon_grav})
rel_grav_df = rel_grav_df.reset_index(drop = True)
rel_grav_df
relativegrav lat lon
0 979517.368887 36.713923 -116.120574
1 979517.369767 36.713923 -116.120574
2 979517.370685 36.713923 -116.120574
3 979519.096209 36.712458 -116.125034
</code></pre>
<p>Trying to pivot the table in the example I use the following code and get the error:</p>
<pre><code>df_pv = rel_grav_df.pivot(index="lat",columns="lon")
Index contains duplicate entries, cannot reshape
</code></pre>
<p>That's why I originally tried to reset_index but neither method worked. For my final result I would like to interpolate the gravity to the same size as a topography grid I have using the following code:</p>
<pre><code>gravity_interp = gravity.interp_like(topography,kwargs={"fill_value":None})
</code></pre>
<p>Any help would be appreciated!
<em><strong>Below edited</strong></em>
I found duplicates in the data so here is the updated dataframe:</p>
<pre><code>rel_grav_df = pd.DataFrame({"relativegrav":rel_grav,"lat":lat_grav,"lon":long_grav})
rel_grav_df = rel_grav_df.drop_duplicates(subset=['lat'])
rel_grav_df = rel_grav_df.reset_index(drop = True)
rel_grav_df.to_csv(r'rel_grav_data.txt',sep=' ', mode = 'a')
</code></pre>
<p>For data that looks like:</p>
<pre><code> relativegrav lat lon
0 979517.3688865899 36.7139233 -116.1205735
1 979519.096208526 36.7124585 -116.1250345
2 979518.8915050578 36.71282822 -116.1316972
3 979531.2591178748 36.70126449 -116.1439218
4 979526.3018131296 36.70558774 -116.1420382
5 979524.8843729249 36.70548686 -116.1359999
6 979521.9290486736 36.70901614 -116.1335681
7 979514.2801810974 36.71966692 -116.1100001
8 979528.4878656694 36.72797377 -116.0854069
9 979521.5282591976 36.72430037 -116.0944469
10 979517.7510474161 36.72091093 -116.1030826
11 979515.6928347832 36.7191884 -116.1074014
12 979516.3006383271 36.71579345 -116.1160991
</code></pre>
<p>Now creating the DataArray:</p>
<pre><code>df_pv = rel_grav_df.pivot(index="lat",columns="lon")
df_pv = df_pv.droplevel(0,axis=1)
da = xr.DataArray(data = df_pv)
da
xarray.DataArraylat: 212lon: 212
array([[nan, nan, nan, ..., nan, nan, nan],
[nan, nan, nan, ..., nan, nan, nan],
[nan, nan, nan, ..., nan, nan, nan],
...,
[nan, nan, nan, ..., nan, nan, nan],
[nan, nan, nan, ..., nan, nan, nan],
[nan, nan, nan, ..., nan, nan, nan]])
Coordinates:
lat
(lat)
float64
36.69 36.69 36.69 ... 36.76 36.76
lon
(lon)
float64
-116.1 -116.1 ... -116.1 -116.1
</code></pre>
<p>The gravity values are not populating the DataArray for some reason still.</p>
| [
{
"answer_id": 74384111,
"author": "Pepijn Kramer",
"author_id": 16649550,
"author_profile": "https://Stackoverflow.com/users/16649550",
"pm_score": 1,
"selected": false,
"text": "#include <iostream>\n\nvoid reverse(char* input)\n{\n const std::size_t offset_of_last_character = strlen(input) - 1; \n\n char* begin_pointer = &input[0]; // front_pointer now contains address of first character in string\n char* end_pointer = &input[offset_of_last_character]; // end_pointer now contains address of last character in the string\n\n while (begin_pointer < end_pointer) // as long as pointers don't cross-over in memory continue\n {\n // swap the characters pointed to \n // first iteration this will be first and last character, \n // second iteration this will be the second and the character and last but one character, etc...\n std::swap(*begin_pointer, *end_pointer);\n\n ++begin_pointer; // move one address up in memory, this is where the next character is found\n --end_pointer; // move on address down in memory, this is where the previous character is found\n }\n}\n\nint main()\n{ \n char input[] = \"!dlrow olleH\";\n reverse(input);\n std::cout << input;\n \n return 0;\n}\n"
},
{
"answer_id": 74387225,
"author": "Igor S.K.",
"author_id": 1556829,
"author_profile": "https://Stackoverflow.com/users/1556829",
"pm_score": 0,
"selected": false,
"text": "char"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74383791",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16042238/"
] |
74,383,797 | <p>I have excel with Survey Results.
There are multiple submissions(rows) by the same email.
I want to find the most filled / most completed row and delete the rest of the duplicate rows with the same email address.</p>
<p>I have a table like this. Multiple Submissions from a single email.</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Email</th>
<th>Question 1</th>
<th>Question 2</th>
<th>Question 3</th>
</tr>
</thead>
<tbody>
<tr>
<td>Email1</td>
<td>Answer</td>
<td>Answer</td>
<td>Answer</td>
</tr>
<tr>
<td>Email1</td>
<td>Answer</td>
<td></td>
<td>Answer</td>
</tr>
<tr>
<td>Email2</td>
<td>Answer</td>
<td></td>
<td></td>
</tr>
<tr>
<td>Email2</td>
<td></td>
<td>Answer</td>
<td></td>
</tr>
<tr>
<td>Email2</td>
<td>Answer</td>
<td>Answer</td>
<td></td>
</tr>
</tbody>
</table>
</div>
<p>I need to delete the least filed duplicated rows. and get Results like bellow.</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Email</th>
<th>Question 1</th>
<th>Question 2</th>
<th>Question 3</th>
</tr>
</thead>
<tbody>
<tr>
<td>Email1</td>
<td>Answer</td>
<td>Answer</td>
<td>Answer</td>
</tr>
<tr>
<td>Email2</td>
<td>Answer</td>
<td>Answer</td>
<td></td>
</tr>
</tbody>
</table>
</div>
<p>How can I do this using openrefine or Excel?</p>
| [
{
"answer_id": 74516117,
"author": "b2m",
"author_id": 16592991,
"author_profile": "https://Stackoverflow.com/users/16592991",
"pm_score": 1,
"selected": false,
"text": "forEach(\n row.columnNames,\n colName,\n if(isNonBlank(row.cells[colName].value), 1, 0))\n .sum()\n"
},
{
"answer_id": 74517322,
"author": "GWD",
"author_id": 12287457,
"author_profile": "https://Stackoverflow.com/users/12287457",
"pm_score": 4,
"selected": true,
"text": "COUNTA(%RowRange%)"
},
{
"answer_id": 74518095,
"author": "Robert Mearns",
"author_id": 5050,
"author_profile": "https://Stackoverflow.com/users/5050",
"pm_score": 2,
"selected": false,
"text": "=COUNTA($B$2:$D$2)\n"
},
{
"answer_id": 74528493,
"author": "David Leal",
"author_id": 6237093,
"author_profile": "https://Stackoverflow.com/users/6237093",
"pm_score": 2,
"selected": false,
"text": "F2"
},
{
"answer_id": 74542392,
"author": "VBasic2008",
"author_id": 9814069,
"author_profile": "https://Stackoverflow.com/users/9814069",
"pm_score": 2,
"selected": false,
"text": "Email2"
},
{
"answer_id": 74583677,
"author": "P.b",
"author_id": 12634230,
"author_profile": "https://Stackoverflow.com/users/12634230",
"pm_score": 1,
"selected": false,
"text": "=LET(data, A2:D6,\n count, MMULT(--(data<>\"\"),TRANSPOSE(COLUMN(data)^0)),\n e, TAKE(data,,1),\n ue, UNIQUE(e),\n mec, DROP(REDUCE(0,e,LAMBDA(a,b,HSTACK(a,(e=b)*count))),,1),\n emec, BYCOL(mec,LAMBDA(x,MAX(x))),\n uec, UNIQUE(e&\"|\"&TRANSPOSE(emec)),\n ec, e&\"|\"&count,\nSUBSTITUTE(\n INDEX(data,\n XMATCH(uec,ec),\n SEQUENCE(1,COLUMNS(data)))\n ,\"\",\"\"))\n"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74383797",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/82457/"
] |
74,383,808 | <p>I would like to take the different values from my data frame and replace these values for the variables zip_code and id in the string query.</p>
<p>Example</p>
<p>This is my query</p>
<p>UPDATE <code>hospitals</code>
SET zip_code = 96761
WHERE id =
'o5FOLOdM1UtOXDB5_WDbWA'
AND zip_code = 9676</p>
<p>This is the input data frame</p>
<pre><code>name zip_code new_zip_code id
------------------------------------------------------------
Jeffrey 85698 75813 o5FOLOdM1UtOXDB5_WDbWA
Palmas 89723 36712 9567LEKDKLD95DDF_67_DD
... ... ... ...
</code></pre>
<p>I would like to have a new column called query and replace the values for the variables zip_code and id with zip_code and new_zip_code in the string of the column query.</p>
<p>Expected output</p>
<pre><code>name zip_code new_zip_code id query
-------------------------------------------------------------------------------------
Jeffrey 85698 75813 o5FOLOdM1UtOXDB5_WDbWA "UPDATE hospitals SET zip_code = 75813 WHERE id = 'o5FOLOdM1UtOXDB5_WDbWA' AND zip_code = 85698"
Palmas 89723 36712 9567LEKDKLD95DDF_67_DD "UPDATE hospitals SET zip_code = 36712 WHERE id = '9567LEKDKLD95DDF_67_DD' AND zip_code = 89723"
... ... ... ...
</code></pre>
| [
{
"answer_id": 74516117,
"author": "b2m",
"author_id": 16592991,
"author_profile": "https://Stackoverflow.com/users/16592991",
"pm_score": 1,
"selected": false,
"text": "forEach(\n row.columnNames,\n colName,\n if(isNonBlank(row.cells[colName].value), 1, 0))\n .sum()\n"
},
{
"answer_id": 74517322,
"author": "GWD",
"author_id": 12287457,
"author_profile": "https://Stackoverflow.com/users/12287457",
"pm_score": 4,
"selected": true,
"text": "COUNTA(%RowRange%)"
},
{
"answer_id": 74518095,
"author": "Robert Mearns",
"author_id": 5050,
"author_profile": "https://Stackoverflow.com/users/5050",
"pm_score": 2,
"selected": false,
"text": "=COUNTA($B$2:$D$2)\n"
},
{
"answer_id": 74528493,
"author": "David Leal",
"author_id": 6237093,
"author_profile": "https://Stackoverflow.com/users/6237093",
"pm_score": 2,
"selected": false,
"text": "F2"
},
{
"answer_id": 74542392,
"author": "VBasic2008",
"author_id": 9814069,
"author_profile": "https://Stackoverflow.com/users/9814069",
"pm_score": 2,
"selected": false,
"text": "Email2"
},
{
"answer_id": 74583677,
"author": "P.b",
"author_id": 12634230,
"author_profile": "https://Stackoverflow.com/users/12634230",
"pm_score": 1,
"selected": false,
"text": "=LET(data, A2:D6,\n count, MMULT(--(data<>\"\"),TRANSPOSE(COLUMN(data)^0)),\n e, TAKE(data,,1),\n ue, UNIQUE(e),\n mec, DROP(REDUCE(0,e,LAMBDA(a,b,HSTACK(a,(e=b)*count))),,1),\n emec, BYCOL(mec,LAMBDA(x,MAX(x))),\n uec, UNIQUE(e&\"|\"&TRANSPOSE(emec)),\n ec, e&\"|\"&count,\nSUBSTITUTE(\n INDEX(data,\n XMATCH(uec,ec),\n SEQUENCE(1,COLUMNS(data)))\n ,\"\",\"\"))\n"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74383808",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11985685/"
] |
74,383,814 | <p>I have a strange problem that I can't seem to solve. At an impasse and I could really use your help. Here are the key characteristics of the problem.</p>
<ol>
<li><p>I CAN send an SMS via Twilio using <code>curl</code> (see below) at the command line and I CAN successfully receive it via T-mobile or Google Voice. Twilio delivery status is 'delivered', as expected.</p>
</li>
<li><p>If I send the SMS using any of the <code>npm</code> packages (listed below) via
a Cloud Run express API that I wrote, then:</p>
</li>
</ol>
<p>a. I CAN successfully send the message, and the Twilio delivery status reads: 'delivered'.</p>
<p>b. I CAN successfully receive the message at a Google Voice number.</p>
<p>c. I CANNOT successfully receive the message on a device where T-mobile is the carrier. (Or any other carrier for that matter.) Yet, the Twilio delivery status still reads 'delivered' in this case.</p>
<p>Is there an IP whitelist I should be using at the Twilio console, maybe? Perhaps there's some other configuration I should be making at the console? Sure seems strange that Google Voice receives messages from a Google cloud service, but that the carriers do not. Any help, advice, or insight would be greatly appreciated. Thanks so much in advance.</p>
<pre><code>curl -X POST -d "Body=Hi, this is the message" -d "From=+14155551212" -d "To=+19251012002" "https://api.twilio.com/2010-04-01/Accounts/<SID>/Messages" -u "SID:AUTH_TOKEN"
</code></pre>
<p>npm packages tried:</p>
<pre><code> "axios": "^0.27.2",
"request": "^2.88.2",
"twilio": "^3.80.0"
</code></pre>
| [
{
"answer_id": 74397260,
"author": "Misunderstood",
"author_id": 3813605,
"author_profile": "https://Stackoverflow.com/users/3813605",
"pm_score": 1,
"selected": false,
"text": "fetch('https://api.twilio.com/2010-04-01/Accounts/<SID>/Messages', {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/x-www-form-urlencoded',\n 'Authorization': 'Basic ' + btoa('SID:AUTH_TOKEN')\n },\n body: 'Body=Hi, this is the message&From=+14155551212&To=+19251012002'\n});\n"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74383814",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19345701/"
] |
74,383,830 | <p>Suppose I have a texture, what I want to do is for each pixel, return only the biggest channel as 1 and the rest as 0.</p>
<p>For instance:</p>
<pre><code> | INPUT | OUTPUT
------|-------------------------|-----------------
RGBA | (0.5, 0.3, 0.4, 0.3) | (1, 0, 0, 0)
RGBA | ( 0 , 0.8, 0.9, 1 ) | (0, 0, 0, 1)
</code></pre>
<p>I'm using shader graph and I'm searching for an optimal approach to avoid using a lot of nodes.</p>
<p>My thought was taking the maximum <strong>m</strong> of all channels, then let each channel <strong>c<sub>i</sub> = (c<sub>i</sub> >= m)</strong>, so the channel greater equal to <strong>m</strong> would be 1 and the rest would be 0, but I'm guessing there might be a better/more performant way.</p>
<p>PS: If there are 2 or more channels with the same value, the correctness doesn't matter, is a problem of the texture. It's possible to suppose there will always be a channel with biggest value.</p>
| [
{
"answer_id": 74383921,
"author": "Deleted",
"author_id": 585968,
"author_profile": "https://Stackoverflow.com/users/585968",
"pm_score": 1,
"selected": false,
"text": " Red\nRGBA -------- \n | \\ \n | Maximum -------- Maximum --- (max of R, G, B)\n | Green / /\n |----------/ /\n | /\n | Blue /\n |----------------------/\n"
},
{
"answer_id": 74383940,
"author": "Milan Egon Votrubec",
"author_id": 8051819,
"author_profile": "https://Stackoverflow.com/users/8051819",
"pm_score": 2,
"selected": true,
"text": "float check = -1;\nif ( inputColour.x > check )\n{\n check = inputColour.x;\n outputColour = float4(1,0,0,0);\n}\nif ( inputColour.y > check )\n{\n check = inputColour.y;\n outputColour = float4(0,1,0,0);\n}\nif ( inputColour.z > check )\n{\n check = inputColour.z;\n outputColour = float4(0,0,1,0);\n}\nif ( inputColour.w > check )\n{\n outputColour = float4(0,0,0,1);\n}\n"
},
{
"answer_id": 74384412,
"author": "uberflut",
"author_id": 17329141,
"author_profile": "https://Stackoverflow.com/users/17329141",
"pm_score": 0,
"selected": false,
"text": "inputTex1 = float4(r,g,b,a);\ninputTex2 = float4(r,g,b,a);\n\n\noutputTex1 = float4 ( \n\n r = ((inputTex1.r / inputTex2.r) >= 1),\n g = ((inputTex1.r / inputTex2.r) >= 1),\n b = ((inputTex1.r / inputTex2.r) >= 1),\n a = ((inputTex1.r / inputTex2.r) >= 1));\n\noutputTex2 = float4 ( \n\n r = ((inputTex1.r / inputTex2.r) <= 1),\n g = ((inputTex1.r / inputTex2.r) <= 1),\n b = ((inputTex1.r / inputTex2.r) <= 1),\n a = ((inputTex1.r / inputTex2.r) <= 1));\n"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74383830",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5348875/"
] |
74,383,862 | <p>I currently have a DataFrame with a shape of (16280, 13). I want to assign values to specific rows in a single column. I was originally doing so with:</p>
<pre><code>for idx, row in enumerate(df.to_dict('records')):
instances = row['instances']
labels = row['labels'].split('|')
for instance in instances:
if instance not in relevant_labels:
labels = ['O' if instance in l else l for l in labels]
df.iloc[idx]['labels'] = '|'.join(labels)
</code></pre>
<p>But this kept returning the <code>SettingWithCopyWarning</code> due to the last line. I tried changing this to <code>df.loc[idx, 'labels'] = '|'.join(labels)</code> which doesn't return the warning anymore but caused errors in the latter parts of my code.</p>
<p>I noticed that the sizes of the DataFrames were (16280, 13) when using <code>iloc</code> and (16751, 13) when using <code>loc</code>.</p>
<p>How can I prevent the warning from printing and get the same functionality as using <code>iloc</code>?</p>
| [
{
"answer_id": 74385348,
"author": "Zelemist",
"author_id": 7512185,
"author_profile": "https://Stackoverflow.com/users/7512185",
"pm_score": 2,
"selected": false,
"text": ".iterrows()"
},
{
"answer_id": 74481766,
"author": "wavetitan",
"author_id": 19069334,
"author_profile": "https://Stackoverflow.com/users/19069334",
"pm_score": 0,
"selected": false,
"text": "SettingWithCopyWarning"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74383862",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7766024/"
] |
74,383,879 | <p>In my flutter project I have created an api_service.dart which sends username and password and returns back with the Token authorization.</p>
<p>I am currently not able to send the authorization Token in the header to allow fetching information from dj-rest-auth/user and I am getting <code>Forbidden: /api/dj-rest-auth/user/</code></p>
<p>Here is the <code>api_service.dart</code>:</p>
<pre><code>class APIService {
static var client = http.Client();
static Future<bool> login(
LoginRequestModel model,
) async {
Map<String, String> requestHeaders = {
'Content-Type': 'application/json',
};
var url = Uri.parse(
Config.apiURL + Config.loginAPI,
);
print(url);
var response = await client.post(
url,
headers: requestHeaders,
body: jsonEncode(model.toJson()),
);
print(response.body);
if (response.statusCode == 200) {
await SharedService.setLoginDetails(
loginResponseJson(
response.body,
),
);
print(response.body);
return true;
} else {
return false;
}
}
</code></pre>
<p>Here is the function to call the user details:</p>
<pre><code>Future<User> fetchUser() async {
final response = await http.get("url");
Map<String, String> requestHeaders = {
'Content-Type': 'application/json',
'Authorization': loginResponseJson(response.body),
};
if (response.statusCode == 200) {
return User.fromJson(jsonDecode(response.body));
} else {
throw Exception('Failed to load User');
}
}
</code></pre>
<p>I am receiving the following error:</p>
<pre><code>error: The element type 'LoginResponseModel' can't be assigned to the map value type 'String'.
</code></pre>
<p>the loginResponseJson(response.body):</p>
<pre><code>{"key":"............."}
</code></pre>
<p><strong>My Question:</strong></p>
<p>What is the best way to add the token to the header to allow user authentication to fetch data from Django Rest Framework. How can I fix this error?</p>
| [
{
"answer_id": 74385348,
"author": "Zelemist",
"author_id": 7512185,
"author_profile": "https://Stackoverflow.com/users/7512185",
"pm_score": 2,
"selected": false,
"text": ".iterrows()"
},
{
"answer_id": 74481766,
"author": "wavetitan",
"author_id": 19069334,
"author_profile": "https://Stackoverflow.com/users/19069334",
"pm_score": 0,
"selected": false,
"text": "SettingWithCopyWarning"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74383879",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13176726/"
] |
74,383,907 | <p>So I have this code right here (<a href="https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=4cdc318db136b2cd5e381b32039845d4" rel="nofollow noreferrer">playground</a>):</p>
<pre class="lang-rs prettyprint-override"><code>use std::error::Error;
struct Foo {
data: Vec<i32>,
counter: i32
}
impl Foo {
fn new(counter: i32) -> Self {
Self { data: vec![1, 2, 3], counter }
}
fn some_method(&mut self) -> Result<(), Box<dyn Error>> {
for num in self.data.iter() {
println!("{num}");
self.some_mut_recursive_method()?;
}
Ok(())
}
/// A useless recursive method that takes in a number, decrements it, checks if its greater than 0. If so it then
/// pushes the number onto the list of numbers and call it on the decremented number.
fn some_mut_recursive_method(&mut self) -> Result<(), Box<dyn Error>> {
self.counter -= 1;
if self.counter > 0 {
self.data.push(self.counter);
self.some_mut_recursive_method()?;
}
Ok(())
}
}
fn main() {
let mut foo = Foo::new(10);
foo.some_method();
}
</code></pre>
<p>It's a struct <code>Foo</code> that has a method that iterates over some internal data and calls a mutable recursive function that manipulates the internal state and possibly calls itself again. Now the problem is on line 16. You see, <code>self </code>is already borrowed immutably in <code>self.data.iter()</code>. But it has to call a mutable function on line 16, but it can't! I get an error saying</p>
<pre><code>cannot borrow `*self` as mutable because it is also borrowed as immutable
</code></pre>
<p>Again, it's borrowed as immutable in <code>self.data.iter()</code>. Can anybody help me with this?</p>
| [
{
"answer_id": 74383986,
"author": "Nikolay Zakirov",
"author_id": 9023490,
"author_profile": "https://Stackoverflow.com/users/9023490",
"pm_score": 2,
"selected": true,
"text": "use std::cell::RefCell;\nuse std::error::Error;\n\nstruct Foo {\n data: RefCell<Vec<i32>>,\n counter: RefCell<i32>,\n}\n\nimpl Foo {\n fn new(counter: i32) -> Self {\n Self {\n data: RefCell::new(vec![1, 2, 3]), counter: RefCell::new(counter)\n }\n }\n\n fn some_method(& self) -> Result<(), Box<dyn Error>> {\n for num in self.data.borrow().iter() {\n println!(\"{num}\");\n self.some_mut_recursive_method()?;\n }\n\n\n Ok(())\n }\n\n /// A useless recursive method that takes in a number, decrements it, checks if its greater than 0. If so it then\n /// pushes the number onto the list of numbers and call it on the decremented number.\n fn some_mut_recursive_method(& self) -> Result<(), Box<dyn Error>> {\n let mut counter = self.counter.borrow_mut();\n *counter -= 1;\n\n // if counter is greater than 0, push it onto the list of numbers and call this method again\n if *counter > 0 {\n self.data.borrow_mut().push(*counter);\n self.some_mut_recursive_method()?;\n }\n\n Ok(())\n }\n}\n\nfn main() {\n let mut foo = Foo::new(10);\n\n foo.some_method();\n}\n"
},
{
"answer_id": 74384982,
"author": "GrvTyagi",
"author_id": 3405842,
"author_profile": "https://Stackoverflow.com/users/3405842",
"pm_score": 0,
"selected": false,
"text": "use std::error::Error;\n\nstruct Foo {\n data: Vec<i32>,\n counter: i32\n}\n\nimpl Foo {\n fn new(counter: i32) -> Self {\n Self { data: vec![1, 2, 3], counter }\n }\n\n fn some_method(&mut self) -> Result<(), Box<dyn Error>> {\n let mut result = vec![];\n for num in self.data.iter() {\n println!(\"{num}\");\n let mut counter = self.counter;\n self.some_mut_recursive_method(&mut result, counter)?;\n }\n \n println!(\"{:?}\", result);\n\n Ok(())\n }\n\n /// A useless recursive method that takes in a number, decrements it, checks if its greater than 0. If so it then \n /// pushes the number onto the list of numbers and call it on the decremented number.\n fn some_mut_recursive_method(&self, res: &mut Vec<i32>, mut counter: i32) -> Result<(), Box<dyn Error>> {\n counter -= 1;\n\n if counter > 0 {\n res.push(counter);\n self.some_mut_recursive_method(res, counter)?;\n }\n\n Ok(())\n }\n}\n\nfn main() {\n let mut foo = Foo::new(10);\n\n foo.some_method();\n}\n"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74383907",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13512544/"
] |
74,383,917 | <p>I'm making a tutorial on how to use my app for the first time.</p>
<p>So it looks like a popup about how to use a button</p>
<p>during the tutorial, I want to make the background darker and a circle appears that will circle the button and there is a tutorial text</p>
<p>So, I want to make a container that has circular holes</p>
<p>here's a simple example:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
*{
margin: 0;
padding: 0;
}
.dark{
height: 100%;
width: 100%;
position: fixed;
background-color: rgba(0, 0, 0, 0.377);
}
.circle{
height: 150px;
width: 150px;
border-radius: 50%;
background-color: white;
}
</style>
</head>
<body>
<div class="dark">
<p style="color:white;font-family: system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;font-size: 23px;">This button is used to delete your file.</p>
<div class="circle"></div>
</div>
<button style="margin:200px;">The Button</button>
</body></code></pre>
</div>
</div>
</p>
<p>but I want the hole to be in the button</p>
| [
{
"answer_id": 74384020,
"author": "John Li",
"author_id": 20436957,
"author_profile": "https://Stackoverflow.com/users/20436957",
"pm_score": 0,
"selected": false,
"text": "<head>\n <meta charset=\"UTF-8\" />\n <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\" />\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />\n <title>Document</title>\n <style>\n * {\n margin: 0;\n padding: 0;\n box-sizing: border-box;\n }\n\n section {\n min-height: 300px;\n background: pink;\n display: flex;\n justify-content: center;\n align-items: center;\n flex-direction: column;\n gap: 16px;\n font-family: sans-serif;\n background: pink;\n }\n\n div {\n display: flex;\n background: pink;\n justify-content: center;\n align-items: center;\n flex-direction: column;\n gap: 8px;\n }\n\n button {\n padding: 5px;\n }\n\n .highlight {\n position: relative;\n isolation: isolate;\n }\n\n .btn-wrap.highlight::before {\n content: \"\";\n position: absolute;\n top: 50%;\n left: 50%;\n transform: translate(-50%, -50%);\n width: 10000px;\n height: 10000px;\n border-radius: 50%;\n background: radial-gradient(\n circle,\n rgba(0, 0, 0, 0) 1%,\n rgba(0, 0, 0, 0.377) 1.01%\n );\n z-index: -1;\n }\n </style>\n </head>\n <body>\n <section>\n <h3>This button is used to delete your file</h3>\n <div class=\"btn-wrap highlight\">\n <button>The Button</button>\n </div>\n </section>\n </body>"
},
{
"answer_id": 74384552,
"author": "Carol McKay",
"author_id": 1540570,
"author_profile": "https://Stackoverflow.com/users/1540570",
"pm_score": 2,
"selected": true,
"text": "<head>\n <meta charset=\"UTF-8\">\n <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n <title>Document</title>\n <style>\n *{\n margin: 0;\n padding: 0;\n }\n .dark{\n height: 100%;\n width: 100%;\n position: fixed;\n background-color: rgba(0, 0, 0, 0.377);\n }\n .circle{\n height: 150px;\n width: 150px;\n border-radius: 50%;\n background-color: white;\n }\n button {\n position:relative; /* ::before position absolute relative to this. */\n isolation: isolate; /* contain z-index; */\n overflow: visible; /* cater for circle pseudo element */\n color: white;\n background-color: purple; /* this not seen because ::after used for background colour */\n }\n button::before {\n content: \" \";\n position: absolute;\n z-index: -2;\n inset: -4.5em -2.5em;\n /* .circle code */\n width: 200%;\n aspect-ratio: 1;\n border-radius: 50%;\n background-color: white;\n }\n button::after {\n content: \" \";\n position: absolute;\n z-index: -1;\n inset: 0;\n background-color: purple;\n}\n </style>\n</head>\n<body>\n <div class=\"dark\">\n <p style=\"color:white;font-family: system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;font-size: 23px;\">This button is used to delete your file.</p>\n <!-- <div class=\"circle\"></div> -->\n </div>\n <button style=\"margin:200px;\">The Button</button>\n</body>"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74383917",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19811641/"
] |
74,383,924 | <p>I have 80 folders, and inside every folder, there are between 1 to 30 images.</p>
<p>I'm looking for a way to rename every image to random 20 digits.
<strong>Here is an example:</strong></p>
<pre><code>Folder_1
|
--- J0tNNchs7U.png -> 59106128950679048106.png
--- nB9HodYxov.png -> 95787130775876521419.png
--- 4yZswgC7xh.png -> 86675183902449304154.png
--- Ax9xwx1e4L.png -> 00276988431900233660.png
Folder_2
|
--- a1yoCwGeUE.png -> 82032328129568492832.png
--- xwItDSLNg4.png -> 98505854158768600999.png
--- 5beJ52yhD1.png -> 90915835999997422646.png
Folder_3
|
--- oSWqLBsymz.png -> 42132595053848488418.png
--- AgoS8guAxi.png -> 76836254163466666967.png
Folder_4
|
--- 5xLO5IXwRd.png -> 39762534969789244484.png
Etc...
</code></pre>
<p>It may take 2 to 4 hours if I want to do it manually, is it possible to do that in Windows 10 using <code>cmd</code>?</p>
<p>Thank you.</p>
| [
{
"answer_id": 74384020,
"author": "John Li",
"author_id": 20436957,
"author_profile": "https://Stackoverflow.com/users/20436957",
"pm_score": 0,
"selected": false,
"text": "<head>\n <meta charset=\"UTF-8\" />\n <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\" />\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />\n <title>Document</title>\n <style>\n * {\n margin: 0;\n padding: 0;\n box-sizing: border-box;\n }\n\n section {\n min-height: 300px;\n background: pink;\n display: flex;\n justify-content: center;\n align-items: center;\n flex-direction: column;\n gap: 16px;\n font-family: sans-serif;\n background: pink;\n }\n\n div {\n display: flex;\n background: pink;\n justify-content: center;\n align-items: center;\n flex-direction: column;\n gap: 8px;\n }\n\n button {\n padding: 5px;\n }\n\n .highlight {\n position: relative;\n isolation: isolate;\n }\n\n .btn-wrap.highlight::before {\n content: \"\";\n position: absolute;\n top: 50%;\n left: 50%;\n transform: translate(-50%, -50%);\n width: 10000px;\n height: 10000px;\n border-radius: 50%;\n background: radial-gradient(\n circle,\n rgba(0, 0, 0, 0) 1%,\n rgba(0, 0, 0, 0.377) 1.01%\n );\n z-index: -1;\n }\n </style>\n </head>\n <body>\n <section>\n <h3>This button is used to delete your file</h3>\n <div class=\"btn-wrap highlight\">\n <button>The Button</button>\n </div>\n </section>\n </body>"
},
{
"answer_id": 74384552,
"author": "Carol McKay",
"author_id": 1540570,
"author_profile": "https://Stackoverflow.com/users/1540570",
"pm_score": 2,
"selected": true,
"text": "<head>\n <meta charset=\"UTF-8\">\n <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n <title>Document</title>\n <style>\n *{\n margin: 0;\n padding: 0;\n }\n .dark{\n height: 100%;\n width: 100%;\n position: fixed;\n background-color: rgba(0, 0, 0, 0.377);\n }\n .circle{\n height: 150px;\n width: 150px;\n border-radius: 50%;\n background-color: white;\n }\n button {\n position:relative; /* ::before position absolute relative to this. */\n isolation: isolate; /* contain z-index; */\n overflow: visible; /* cater for circle pseudo element */\n color: white;\n background-color: purple; /* this not seen because ::after used for background colour */\n }\n button::before {\n content: \" \";\n position: absolute;\n z-index: -2;\n inset: -4.5em -2.5em;\n /* .circle code */\n width: 200%;\n aspect-ratio: 1;\n border-radius: 50%;\n background-color: white;\n }\n button::after {\n content: \" \";\n position: absolute;\n z-index: -1;\n inset: 0;\n background-color: purple;\n}\n </style>\n</head>\n<body>\n <div class=\"dark\">\n <p style=\"color:white;font-family: system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;font-size: 23px;\">This button is used to delete your file.</p>\n <!-- <div class=\"circle\"></div> -->\n </div>\n <button style=\"margin:200px;\">The Button</button>\n</body>"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74383924",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7474282/"
] |
74,383,933 | <p>I have two Google sheets. Sheet1 are the employees, Sheet2 are the job titles, and Sheet3 I would like to find all employees with the specified job titles.</p>
<p>Sheet1 (thousands of rows)<br>
<a href="https://i.stack.imgur.com/emz2H.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/emz2H.png" alt="enter image description here" /></a></p>
<p>Sheet2 (there are over 100 different)<br>
<a href="https://i.stack.imgur.com/8qxfF.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/8qxfF.png" alt="enter image description here" /></a></p>
<p>Sheet3 (expected output of Sheet1 using terms from Sheet2)<br>
<a href="https://i.stack.imgur.com/x5Acb.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/x5Acb.png" alt="enter image description here" /></a></p>
<p>Trying to figure it out and so far no luck trying something like
<code>=query('Sheet1'!1:100000, "Select \* Where LOWER(F) = LOWER('Sheet2!'2:300)")</code></p>
<p><a href="https://docs.google.com/spreadsheets/d/15bWJTKmIKh1AEZERb_y3Jnwn0g_5EnpBoq54G46rMKA/edit?usp=sharing" rel="nofollow noreferrer">Demo sheet</a></p>
| [
{
"answer_id": 74383994,
"author": "Harun24hr",
"author_id": 5514747,
"author_profile": "https://Stackoverflow.com/users/5514747",
"pm_score": 1,
"selected": false,
"text": "=QUERY(Sheet1!A:C,\"select * where B matches '\" & TEXTJOIN(\"|\",TRUE,Sheet2!A2:A) & \"'\",1)\n"
},
{
"answer_id": 74384104,
"author": "Ping",
"author_id": 20288037,
"author_profile": "https://Stackoverflow.com/users/20288037",
"pm_score": 1,
"selected": true,
"text": "=ArrayFormula(QUERY({$A$1:$C,XLOOKUP($B:$B,sheet2!$A$2:$A$8,sheet2!$A$2:$A$8,\"\")},\n\"SELECT Col1,Col2,Col3 WHERE Col4 IS NOT NULL\",1\n))\n"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74383933",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4889910/"
] |
74,383,936 | <p>I'm not able to see my data on the map when I run the following script. I can see the map, the temporal slider is present at the bottom and scrolls through the dates I provided, however, I do not see a heat signature at any of the locations. Is there something I'm leaving off of this?</p>
<p>This is the table I'm working with:
<a href="https://i.stack.imgur.com/lzq5Q.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/lzq5Q.png" alt="enter image description here" /></a></p>
<pre><code># HEATMAP OVER TIME WITH MY DATA
import folium
from folium import plugins
import pandas as pd
ASOS_DATA = r"C:\Users\ASOS_Cali_Weather_Stations.csv"
df = pd.read_csv(ASOS_DATA)
latlon = (df[["lon", "lat"]]).values.tolist()
date = (df["test_date"]).values.tolist()
# MAP
map_heatmap_time = folium.Map([37, -122], tiles='CartoDB Dark_Matter', zoom_start = 6)
# HEATMAP PLUGIN
heatmap_time_plugin = plugins.HeatMapWithTime(latlon, index= date)
# ADD HEATMAP PLUGIN TO MAP
heatmap_time_plugin.add_to(map_heatmap_time)
# DISPLAY THE MAP
map_heatmap_time
</code></pre>
| [
{
"answer_id": 74386367,
"author": "r-beginners",
"author_id": 13107804,
"author_profile": "https://Stackoverflow.com/users/13107804",
"pm_score": 1,
"selected": false,
"text": "import folium\nimport folium.plugins as plugins\nimport pandas as pd\nimport numpy as np\nimport random\n\n# sample data\ndf = pd.DataFrame({'test_date': np.repeat(pd.date_range('2022-09-01', periods=30), 30),\n 'lon': [random.uniform(36.5, 37.5) for _ in range(900)],\n 'lat':[random.uniform(-121.5, -122.5) for _ in range(900)],\n 'value': np.random.rand(900)})\ndf['test_date'] = pd.to_datetime(df['test_date'])\n\n# heatmap data by date\nlatlon = []\nfor d in df['test_date'].unique():\n dff = df.query('test_date == @d')\n latlon.append(dff[['lon','lat','value']].values.tolist())\n\n# convert date to str(date) \ndate = [k.strftime(\"%Y-%m-%d\") for k in pd.date_range('2022-09-01', periods=30)]\n\nmap_heatmap_time = folium.Map([37, -122], tiles='OpenStreetMap', zoom_start=8)\n\nheatmap_time_plugin = plugins.HeatMapWithTime(latlon, index=date)\n\nheatmap_time_plugin.add_to(map_heatmap_time)\n\nmap_heatmap_time\n"
},
{
"answer_id": 74441454,
"author": "Geno",
"author_id": 2877327,
"author_profile": "https://Stackoverflow.com/users/2877327",
"pm_score": 1,
"selected": true,
"text": "import folium\nfrom folium import plugins\nimport pandas as pd\n\nASOS_DATA = r\"C:\\Users\\ASOS_Cali_Weather_Stations.xlsx\"\ndf = pd.read_excel(ASOS_DATA)\n\ntime_index= list(df[\"test_date\"].sort_values().astype('str').unique())\ndf[\"test_date\"] = df[\"test_date\"].sort_values(ascending=True)\n\ndata = []\nfor _, d in df.groupby(\"test_date\"):\n data.append([[row['lat'], row[\"lon\"], row[\"norm_temp\"]] for _,row in d.iterrows()])\n\nmap_heatmap_time = folium.Map([37, -122], tiles='CartoDB Dark_Matter', zoom_start = 7)\n \nheatmap_time_plugin = plugins.HeatMapWithTime(data, index= time_index)\n\nheatmap_time_plugin.add_to(map_heatmap_time)\n\nmap_heatmap_time\n"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74383936",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2877327/"
] |
74,383,937 | <p>I get a Laravel collection from a Eloquent query and I converted into an array using <code>toArray()</code> method. The sample output is mentioned below.</p>
<pre class="lang-php prettyprint-override"><code>Array ( [0] => Array ( [id] => 1 [details] => routes [level] => beginner [created_at] => 2022-11-16T11:09:48.000000Z [updated_at] => 2022-11-09T11:09:48.000000Z [pivot] => Array ( [user_id] => 1 [milestone_id] => 1 ) ) [1] => Array ( [id] => 2 [details] => router 2 [level] => beginner [created_at] => 2022-11-09T11:09:48.000000Z [updated_at] => 2022-11-18T11:09:48.000000Z [pivot] => Array ( [user_id] => 1 [milestone_id] => 2 ) ) [2] => Array ( [id] => 3 [details] => route [level] => route 3 [created_at] => 2022-11-15T09:05:46.000000Z [updated_at] => 2022-11-17T09:05:46.000000Z [pivot] => Array ( [user_id] => 1 [milestone_id] => 3 ) ) ) 1
</code></pre>
<p>I only need the values of <code>milestone_id</code>s from <code>pivot</code> index. As an example like this <code>[1,2,3]</code></p>
<p>I tried different PHP methods and notations to access these values but couldn't succeed.</p>
| [
{
"answer_id": 74383965,
"author": "dvnc0",
"author_id": 20464681,
"author_profile": "https://Stackoverflow.com/users/20464681",
"pm_score": 0,
"selected": false,
"text": "foreach"
},
{
"answer_id": 74384103,
"author": "keyboardSmasher",
"author_id": 1801623,
"author_profile": "https://Stackoverflow.com/users/1801623",
"pm_score": 3,
"selected": true,
"text": "$milestoneIds = $collection->pluck('pivot.milestone_id')->toArray();\n"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74383937",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16484935/"
] |
74,383,938 | <p>So I'm trying to create at REST API using DRF and Swagger for API Documentation, But I notice that Swagger UI Parameter doesn't match the given Serializer.
<strong>MailSerializer.py</strong>
`</p>
<pre><code>from main.BusinessLayer.Model.Mails import Mails
from rest_framework import serializers
class MailSerializer(serializers.Serializer):
class Meta:
model = Mails
fields = '__all__'
# Mail Properties
Subject = serializers.CharField(max_length = 30, allow_blank = False)
Sender = serializers.CharField(max_length = 30, allow_blank = False)
Recipients = serializers.CharField(allow_blank = False)
ReplyToAddress = serializers.CharField(max_length = 30)
Importance = serializers.CharField(max_length = 30, allow_blank = False)
ApplicationId = serializers.CharField(max_length = 30, allow_blank = False)
# Mail Content
Body = serializers.CharField(allow_blank = False)
Attachments = serializers.CharField(allow_blank = False)
# Other Parameters
UseDefaultHeader = serializers.IntegerField(default = 0)
UseDefaultFooter = serializers.IntegerField(default = 0)
def create(self, validated_data):
return Mails.objects.create(**validated_data)
</code></pre>
<p>`</p>
<pre><code> @swagger_auto_schema(
operation_description="",
operation_summary="create a mail",
request_body=MailSerializer
)
def create(self, request, *args, **kwargs):
try:
serializer = self.serializer_class(data=request.data)
serializer.is_valid(raise_exception=True)
self.perform_create(serializer)
return Response({
'code': 200,
'success': True,
'message': '%s successfully created.' % (OBJECT_NAME),
'data': []
}, status= status.HTTP_200_OK)
</code></pre>
<p><a href="https://i.stack.imgur.com/PJcyo.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/PJcyo.png" alt="enter image description here" /></a></p>
<p>I tried to use @swagger_auto_schema and a request_body parameters, but still not working</p>
| [
{
"answer_id": 74384293,
"author": "Ersain",
"author_id": 11544538,
"author_profile": "https://Stackoverflow.com/users/11544538",
"pm_score": 0,
"selected": false,
"text": "Meta.fields"
},
{
"answer_id": 74397779,
"author": "ilyasbbu",
"author_id": 16475089,
"author_profile": "https://Stackoverflow.com/users/16475089",
"pm_score": 2,
"selected": true,
"text": "allow_blank"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74383938",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20464787/"
] |
74,383,941 | <p>I have a project build with Laravel 8. My project will use for creating dynamic report that run with SQL query. So i must save the SQL query in my database to run dynamic every report.</p>
<p>It's all fine since i faced problem if my query are dynamic.</p>
<p>my code on Controller:</p>
<pre><code>public function data(){
$id = 1092
$var = DB::table('abc')->where('id', $id)->first();
$query = $var->query;
return $query
}
</code></pre>
<p>If i run that code, will result like this:</p>
<pre><code>SELECT * FROM V_REPORT WHERE PRQ_DATE BETWEEN '$start_date' AND '$end_date' AND COMPANY = '$company'
</code></pre>
<p>And i will run that query using <code>DB::raw</code> on other function.</p>
<pre><code>public function runDb(Request $request){
$start_date = $request->start_date; // ex: 2022-10-01
$end_date = $request->end_date; // ex: 2022-10-05
$company = $request-> company; // ex: A
$query = $this->data();
$sql = DB::select(DB::raw("$query"));
return $sql;
}
</code></pre>
<p><em>output: []</em></p>
<p>I expect will get data from V_REPORT, but its null. whereas when I run in the database, there is a lot of data that appears.</p>
<p>I think the problem are because the "query" read as string. and the <code>DB::raw</code> function not read that "variable" on query <code>('$start_date', $end_date, '$company')</code>.</p>
<p>FYI, there are no error response from my code. It just return <code>[]</code>, which means there are no data.</p>
<p>Is there any way to run my "dynamic query" from table on <code>DB::raw()</code> ?</p>
<p>Please help, i am stuck on this thing.</p>
| [
{
"answer_id": 74384293,
"author": "Ersain",
"author_id": 11544538,
"author_profile": "https://Stackoverflow.com/users/11544538",
"pm_score": 0,
"selected": false,
"text": "Meta.fields"
},
{
"answer_id": 74397779,
"author": "ilyasbbu",
"author_id": 16475089,
"author_profile": "https://Stackoverflow.com/users/16475089",
"pm_score": 2,
"selected": true,
"text": "allow_blank"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74383941",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9786205/"
] |
74,383,946 | <p>I love when simple things you think will take all of two minutes ends up taking over an hour! </p>
<p>When writing unit tests, we need to test for several specific error types, some of which have associated values. We also need access to the error itself so we can unit-test the localized description.</p>
<p>The issue is, if you pattern-match on an error type, you can get the associated values, but you lose access to the error itself so you can't get things like <code>localizedDescription</code>, etc.</p>
<p>Here's the (over-simplified) code showing the two cases...</p>
<pre class="lang-swift prettyprint-override"><code>public enum MyError: LocalizedError {
case missingKey(in: String, at: String.Index)
public var errorDescription: String { "I Need To Get This Too" }
}
</code></pre>
<p>And here's how you can pattern-match to get only the error you're interested in, and it's associated values, but again, <code>error</code> is not available within your catch block so you can't also check the localized description.</p>
<pre class="lang-swift prettyprint-override"><code>do {
throw MyError.missingKey(in: "A", at: "A".startIndex)
}
catch let MyError.missingKey(in: string, at: location) {
// Got the string and location associated values,
// but how do I get the localized description?
print(string, location)
}
catch OtherErr {
print(error)
}
</code></pre>
<p>Of course you can use the 'broad hammer' <code>catch</code> command, but that really is not advisable. It may catch something you weren't expecting, hiding it from you, meaning you now have to actively plan for handling such unexpected cases inside your own block, cluttering responsibilities. All around a bad approach.</p>
<p>But it also works (sigh)...</p>
<pre class="lang-swift prettyprint-override"><code>do {
throw Error.missingKey(in: "A", at: "A".startIndex)
}
catch {
switch error {
// Handle your specific case
case let Error.missingKey(in: string, at: location):
print(string, location, error.localizedDescription) // <-- Finally!!!
// BUT... You're also now responsible to handle all unexpected errors
// since your 'catch' case catches everything and there is no 'fallthrough'
case OtherError:
print(error)
default:
throw error
}
}
</code></pre>
<p>So... is there a better way to do this?</p>
| [
{
"answer_id": 74384036,
"author": "HangarRash",
"author_id": 20287183,
"author_profile": "https://Stackoverflow.com/users/20287183",
"pm_score": 0,
"selected": false,
"text": "do/catch"
},
{
"answer_id": 74384063,
"author": "matt",
"author_id": 341994,
"author_profile": "https://Stackoverflow.com/users/341994",
"pm_score": 1,
"selected": false,
"text": "catch"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74383946",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/168179/"
] |
74,383,950 | <p>I have two divs within a <code>main</code> tag and a div. I'm trying to align them horizontally besides each other but nothing I've tried is working. I've tried <code>display:inline, flex, float, block, flex-direction</code>... but none are working. Some help would be great, thanks.</p>
<p>css:</p>
<pre><code><div class="flexbox">
<main>
<div class="playlist-box">
<div class="site-playlist">
ex
</div>
</div>
<div class="right-column">
<div class="main-heading">
What I've Been Up To:
</div>
</div>
</main>
</div>
</code></pre>
<pre><code>.flexbox {
display: flex;
}
main {
width: 100%;
flex-direction: row;
flex-wrap: nowrap;
}
.site-playlist {
height: 200px;
width: 25%;
margin-left: 0;
padding-left: 5px;
text-align: center;
padding-top: 5px;
overflow: scroll;
}
</code></pre>
| [
{
"answer_id": 74384077,
"author": "Suresh Ponnukalai",
"author_id": 3607064,
"author_profile": "https://Stackoverflow.com/users/3607064",
"pm_score": 2,
"selected": true,
"text": "flex"
},
{
"answer_id": 74384098,
"author": "MrPatel2021",
"author_id": 19671394,
"author_profile": "https://Stackoverflow.com/users/19671394",
"pm_score": 0,
"selected": false,
"text": "<!DOCTYPE html>\n<html>\n <style>\n .flexbox {\n display: flex;\n }\n main {\n width: 100%;\n flex-direction: row;\n flex-wrap: nowrap;\n display:flex;\n }\n .site-playlist {\n height: 200px;\n width: 100%;\n margin-left: 0;\n padding-left: 5px;\n text-align: center;\n padding-top: 5px;\n overflow: scroll;\n }\n .playlist-box {\n width:25%\n }\n .right-column {\n width:75%\n }\n </style>\n <body>\n <div class=\"flexbox\">\n <main>\n <div class=\"playlist-box\">\n <div class=\"site-playlist\">\n ex\n </div>\n </div>\n <div class=\"right-column\">\n <div class=\"main-heading\">\n What I've Been Up To:\n </div>\n </div>\n </main>\n </div>\n </body>\n</html>\n"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74383950",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19730514/"
] |
74,383,962 | <p>I have a nested json value in flutter. I wanna get the value from nested json. But I can't do it.</p>
<p>I already tried to make a Class of nested json object. But it seems cannot cast to that object. I used jsonDecode() which is not work.
When I call the Data.fromJson, ParentData is null</p>
<pre><code>factory Data.fromJson(dynamic json) {
return ReferenceData._(
id: json["id"],
code: json["code"],
parentData: (json["ParentData"] != null)
? ParentData.fromJson(json["ParentData"])
: json["parentRefDataValue"],
translations: json["translations"],
createdAt: json["createdAt"],
updatedAt: json["updatedAt"],
);
}
class ParentData {
int? id;
String? code;
int? sortOrder;
List<dynamic>? translations;
dynamic? ParentData;
String? createdBy;
String? updatedBy;
parentData._({
this.id,
this.code,
this.sortOrder,
this.translations,
this.ParentData,
this.createdBy,
this.updatedBy,
});
factory ParentData.fromJson(dynamic json) {
return ParentData._(
id: json['id'],
code: json['code'],
sortOrder: json['sortOrder'],
translations: json["translations"],
ParentData: json['ParentData'],
createdBy: json['createdBy'],
updatedBy: json['updatedBy'],
}
}
</code></pre>
| [
{
"answer_id": 74384077,
"author": "Suresh Ponnukalai",
"author_id": 3607064,
"author_profile": "https://Stackoverflow.com/users/3607064",
"pm_score": 2,
"selected": true,
"text": "flex"
},
{
"answer_id": 74384098,
"author": "MrPatel2021",
"author_id": 19671394,
"author_profile": "https://Stackoverflow.com/users/19671394",
"pm_score": 0,
"selected": false,
"text": "<!DOCTYPE html>\n<html>\n <style>\n .flexbox {\n display: flex;\n }\n main {\n width: 100%;\n flex-direction: row;\n flex-wrap: nowrap;\n display:flex;\n }\n .site-playlist {\n height: 200px;\n width: 100%;\n margin-left: 0;\n padding-left: 5px;\n text-align: center;\n padding-top: 5px;\n overflow: scroll;\n }\n .playlist-box {\n width:25%\n }\n .right-column {\n width:75%\n }\n </style>\n <body>\n <div class=\"flexbox\">\n <main>\n <div class=\"playlist-box\">\n <div class=\"site-playlist\">\n ex\n </div>\n </div>\n <div class=\"right-column\">\n <div class=\"main-heading\">\n What I've Been Up To:\n </div>\n </div>\n </main>\n </div>\n </body>\n</html>\n"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74383962",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20297139/"
] |
74,384,011 | <p>Let's say I have a dataframe, called <code>original_df</code>, of 20,000 rows. I split the first 18,000 rows to be used as my training set and the last 2,000 rows to be used as my testing set. When I use the <code>sample</code> function on the <code>original_df</code> <em>before splitting</em> and run a classifier model on the training set, it produces reasonable prediction results: some false positives, some false negatives, some true positives, and some true negatives.</p>
<p>However, when I use the <code>sample</code> function on the training set and the testing set after splitting the non-shuffled <code>original_df</code>, the classifier is never able to make a positive prediction: I would only get true negatives and false negatives; and zero false positives and true positives.</p>
<p>I'm just trying to understand why this happens despite having the same sampling techniques, below are some example snippets.</p>
<pre><code># This example samples the original dataset directly
training_len = math.ceil(len(X) * 0.9)
X.sample(frac=1, random_state=2) # Features
Y.sample(frac=1, random_state=2) # Labels
X_train = X.loc[:training_len]
Y_train = Y.loc[:training_len]
X_test = X.loc[training_len+1:]
Y_test = Y.loc[training_len+1:]
# fp, fn, tp, tn
# 1314, 1703, 455, 8842
</code></pre>
<pre><code># This example samples the training set directly
training_len = math.ceil(len(X) * 0.9)
X # Features
Y # Labels
X_train = X.loc[:training_len].sample(frac=1, random_state=2)
Y_train = Y.loc[:training_len].sample(frac=1, random_state=2)
X_test = X.loc[training_len+1:]
Y_test = Y.loc[training_len+1:]
# fp, fn, tp, tn
# 0, 425, 0, 2518
</code></pre>
<p>I'm using <code>GaussianNB()</code> from <code>sklearn.naive_bayes</code></p>
<p>I tried checking to see if there were any index mismatching between the training and testing sets, but it wasn't.</p>
<p>I tried to not sample anything from the training and original sets and it had the same prediction results as when sampling just the training sets dataset. This made me think that <code>X_train</code> and <code>Y_train</code> was not being shuffled at all, but I printed the contents of the training sets after sampling and they were indeed shuffled(with matching indices for <code>X_train</code> and <code>Y_train</code>).</p>
| [
{
"answer_id": 74384077,
"author": "Suresh Ponnukalai",
"author_id": 3607064,
"author_profile": "https://Stackoverflow.com/users/3607064",
"pm_score": 2,
"selected": true,
"text": "flex"
},
{
"answer_id": 74384098,
"author": "MrPatel2021",
"author_id": 19671394,
"author_profile": "https://Stackoverflow.com/users/19671394",
"pm_score": 0,
"selected": false,
"text": "<!DOCTYPE html>\n<html>\n <style>\n .flexbox {\n display: flex;\n }\n main {\n width: 100%;\n flex-direction: row;\n flex-wrap: nowrap;\n display:flex;\n }\n .site-playlist {\n height: 200px;\n width: 100%;\n margin-left: 0;\n padding-left: 5px;\n text-align: center;\n padding-top: 5px;\n overflow: scroll;\n }\n .playlist-box {\n width:25%\n }\n .right-column {\n width:75%\n }\n </style>\n <body>\n <div class=\"flexbox\">\n <main>\n <div class=\"playlist-box\">\n <div class=\"site-playlist\">\n ex\n </div>\n </div>\n <div class=\"right-column\">\n <div class=\"main-heading\">\n What I've Been Up To:\n </div>\n </div>\n </main>\n </div>\n </body>\n</html>\n"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74384011",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12208412/"
] |
74,384,043 | <div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Contact</th>
<th>Old Contact</th>
</tr>
</thead>
<tbody>
<tr>
<td>234255</td>
<td>987778</td>
</tr>
<tr>
<td>343556</td>
<td>987877</td>
</tr>
<tr>
<td>Missing</td>
<td>984567</td>
</tr>
<tr>
<td>Missing</td>
<td></td>
</tr>
<tr>
<td>Missing</td>
<td>845665</td>
</tr>
<tr>
<td>343556</td>
<td>789998</td>
</tr>
</tbody>
</table>
</div>
<p>Given the table above, I wish to go through each row under "Contact" and check if Missing. If the row has Missing, use corresponding "Old Contact" values inplace of the text 'Missing'. If old contact is empty, then leave it as 'Missing'</p>
<p>Desired table:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Contact</th>
<th>Old Contact</th>
</tr>
</thead>
<tbody>
<tr>
<td>234255</td>
<td>987778</td>
</tr>
<tr>
<td>343556</td>
<td>987877</td>
</tr>
<tr>
<td><strong>984567</strong></td>
<td>984567</td>
</tr>
<tr>
<td><em>Missing</em></td>
<td></td>
</tr>
<tr>
<td><strong>845665</strong></td>
<td>845665</td>
</tr>
<tr>
<td>343556</td>
<td>789998</td>
</tr>
</tbody>
</table>
</div>
<pre><code>df['Contact'] = df['Contact'].apply(
lambda x: df['Old Contact'] if "Missing" in x else x)
</code></pre>
<p>the line above gives me the whole column of 'Old Contact' where there is Missing. I'm not sure how to use index here to get what I want. Thanks in advance!</p>
| [
{
"answer_id": 74384091,
"author": "Panda Kim",
"author_id": 20430449,
"author_profile": "https://Stackoverflow.com/users/20430449",
"pm_score": 2,
"selected": true,
"text": "mask"
},
{
"answer_id": 74384168,
"author": "Python16367225",
"author_id": 16367225,
"author_profile": "https://Stackoverflow.com/users/16367225",
"pm_score": 0,
"selected": false,
"text": "df.index"
},
{
"answer_id": 74384369,
"author": "RufusVS",
"author_id": 925592,
"author_profile": "https://Stackoverflow.com/users/925592",
"pm_score": 0,
"selected": false,
"text": "for idx in df.index:\n if (df.iloc[idx]['Contact']=='Missing'):\n if len(df.iloc[idx]['Old Contact'].strip()):\n df.iloc[idx]['Contact']=df.iloc[idx]['Old Contact']\n"
},
{
"answer_id": 74384427,
"author": "Jason Baker",
"author_id": 3249641,
"author_profile": "https://Stackoverflow.com/users/3249641",
"pm_score": 0,
"selected": false,
"text": "df = df.assign(\n Contact=df[\"Contact\"].where(df[\"Contact\"].ne(\"Missing\"), df[\"Old Contact\"]).fillna(\"Missing\")\n).fillna(\"\")\nprint(df)\n\n Contact Old Contact\n0 234255 987778.0\n1 343556 987877.0\n2 984567.0 984567.0\n3 Missing \n4 845665.0 845665.0\n5 343556 789998.0\n"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74384043",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6048779/"
] |
74,384,046 | <p>I have a process with repetitive events with an order, you can see an example in the table</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>User</th>
<th>Event</th>
<th>Date</th>
</tr>
</thead>
<tbody>
<tr>
<td>XYZ</td>
<td>Event 1</td>
<td>2022-01-01</td>
</tr>
<tr>
<td>XYZ</td>
<td>Event 2</td>
<td>2022-01-02</td>
</tr>
<tr>
<td>XYZ</td>
<td>Event 3</td>
<td>2022-01-03</td>
</tr>
<tr>
<td>XYZ</td>
<td>Event 4</td>
<td>2022-01-04</td>
</tr>
<tr>
<td>XYZ</td>
<td>Event 3</td>
<td>2022-01-05</td>
</tr>
<tr>
<td>XYZ</td>
<td>Event 4</td>
<td>2022-01-06</td>
</tr>
</tbody>
</table>
</div>
<p>I need to select those users that have been stuck in the second "event 3" (2022-01-05) but haven´t pass to the second "event 4". This is repetetive like I said before, it could be 3 "events 3" but I need to select the max "event 3" but for those users that their last evenet isn't "event 4"</p>
<p>Was using rank but didn't solve my problem and honestly don't know how to do it. Thanks in advance.</p>
| [
{
"answer_id": 74384091,
"author": "Panda Kim",
"author_id": 20430449,
"author_profile": "https://Stackoverflow.com/users/20430449",
"pm_score": 2,
"selected": true,
"text": "mask"
},
{
"answer_id": 74384168,
"author": "Python16367225",
"author_id": 16367225,
"author_profile": "https://Stackoverflow.com/users/16367225",
"pm_score": 0,
"selected": false,
"text": "df.index"
},
{
"answer_id": 74384369,
"author": "RufusVS",
"author_id": 925592,
"author_profile": "https://Stackoverflow.com/users/925592",
"pm_score": 0,
"selected": false,
"text": "for idx in df.index:\n if (df.iloc[idx]['Contact']=='Missing'):\n if len(df.iloc[idx]['Old Contact'].strip()):\n df.iloc[idx]['Contact']=df.iloc[idx]['Old Contact']\n"
},
{
"answer_id": 74384427,
"author": "Jason Baker",
"author_id": 3249641,
"author_profile": "https://Stackoverflow.com/users/3249641",
"pm_score": 0,
"selected": false,
"text": "df = df.assign(\n Contact=df[\"Contact\"].where(df[\"Contact\"].ne(\"Missing\"), df[\"Old Contact\"]).fillna(\"Missing\")\n).fillna(\"\")\nprint(df)\n\n Contact Old Contact\n0 234255 987778.0\n1 343556 987877.0\n2 984567.0 984567.0\n3 Missing \n4 845665.0 845665.0\n5 343556 789998.0\n"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74384046",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20325690/"
] |
74,384,057 | <p><strong>SplashActivity.cs</strong></p>
<p>namespace Splash12.Droid
{
[Activity(Theme = "@style/MyTheme.Splash", MainLauncher = true, NoHistory = true)]
public class SplashActivity : AppCompatActivity
{
static readonly string TAG = "X:" + typeof(SplashActivity).Name;</p>
<pre><code> public override void OnCreate(Bundle savedInstanceState, PersistableBundle persistentState)
{
base.OnCreate(savedInstanceState, persistentState);
Log.Debug(TAG, "SplashActivity.OnCreate");
}
// Launches the startup task
protected override void OnResume()
{
base.OnResume();
Task startupWork = new Task(() => { SimulateStartup(); });
startupWork.Start();
}
// Simulates background work that happens behind the splash screen
async void SimulateStartup()
{
Log.Debug(TAG, "Performing some startup work that takes a bit of time.");
await Task.Delay(8000); // Simulate a bit of startup work.
Log.Debug(TAG, "Startup work is finished - starting MainActivity.");
StartActivity(new Intent(Application.Context, typeof(MainActivity)));
}
}
</code></pre>
<p>}</p>
<p><strong>MainActivity.cs</strong></p>
<pre><code>[Activity(Label = "Splash12", Theme = "@style/MainTheme", Icon = "@mipmap/icon", MainLauncher = false, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation | ConfigChanges.UiMode | ConfigChanges.ScreenLayout | ConfigChanges.SmallestScreenSize )]
public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
{
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
Xamarin.Essentials.Platform.Init(this, savedInstanceState);
global::Xamarin.Forms.Forms.Init(this, savedInstanceState);
LoadApplication(new App());
}
public override void OnRequestPermissionsResult(int requestCode, string[] permissions, [GeneratedEnum] Android.Content.PM.Permission[] grantResults)
{
Xamarin.Essentials.Platform.OnRequestPermissionsResult(requestCode, permissions, grantResults);
base.OnRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
</code></pre>
<p>}</p>
<p><strong>styles.xml</strong></p>
<pre><code><style name="MyTheme.Splash" parent ="Theme.AppCompat.Light.NoActionBar">
<item name="android:windowBackground">@drawable/splash_screen</item>
<item name="android:windowNoTitle">true</item>
<item name="android:windowFullscreen">true</item>
<item name="android:windowContentOverlay">@null</item>
<item name="android:windowActionBar">true</item>
</style>
</code></pre>
<p><strong>splash_screen.xml</strong></p>
| [
{
"answer_id": 74384091,
"author": "Panda Kim",
"author_id": 20430449,
"author_profile": "https://Stackoverflow.com/users/20430449",
"pm_score": 2,
"selected": true,
"text": "mask"
},
{
"answer_id": 74384168,
"author": "Python16367225",
"author_id": 16367225,
"author_profile": "https://Stackoverflow.com/users/16367225",
"pm_score": 0,
"selected": false,
"text": "df.index"
},
{
"answer_id": 74384369,
"author": "RufusVS",
"author_id": 925592,
"author_profile": "https://Stackoverflow.com/users/925592",
"pm_score": 0,
"selected": false,
"text": "for idx in df.index:\n if (df.iloc[idx]['Contact']=='Missing'):\n if len(df.iloc[idx]['Old Contact'].strip()):\n df.iloc[idx]['Contact']=df.iloc[idx]['Old Contact']\n"
},
{
"answer_id": 74384427,
"author": "Jason Baker",
"author_id": 3249641,
"author_profile": "https://Stackoverflow.com/users/3249641",
"pm_score": 0,
"selected": false,
"text": "df = df.assign(\n Contact=df[\"Contact\"].where(df[\"Contact\"].ne(\"Missing\"), df[\"Old Contact\"]).fillna(\"Missing\")\n).fillna(\"\")\nprint(df)\n\n Contact Old Contact\n0 234255 987778.0\n1 343556 987877.0\n2 984567.0 984567.0\n3 Missing \n4 845665.0 845665.0\n5 343556 789998.0\n"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74384057",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20464856/"
] |
74,384,059 | <p>I am trying to validate a restclientexception error. My code is below and help would be appreciated. This is from my test class:`</p>
<p>`</p>
<pre><code>@Test
void test_update_customer_in_ath0_server_error(){
//given
ResponseEntity<String> responseEntity = new ResponseEntity<>(HttpStatus.SERVICE_UNAVAILABLE);
doReturn(responseEntity)
.when(restTemplate).exchange(any(), eq(HttpMethod.PATCH), any(HttpEntity.class), (Class<String>)any());
idpFacadeClient.updateCustomerFirstNameInIdp(updateRecordsDto);
//then
verify(restTemplate).exchange(any(), eq(HttpMethod.PATCH), argThat(this::verifyUpdatedCustomerBody), (Class<String>)any());
}
</code></pre>
<p>This is from my injectMock class</p>
<p>`</p>
<pre><code>try {
response = restTemplate.exchange(URI.create(idpFacadeUpdateUrl), HttpMethod.PATCH, entity, String.class);
if (response.getStatusCode() == HttpStatus.OK) {
log.info("customer first name update success {} with status {}", customerUpdateRecordsDto.getFirstName(), response.getStatusCode());
}else {
log.error("Customer first name update failed in IDP for {} with status {}", customerUpdateRecordsDto.getFirstName(), response.getStatusCode());
}
} catch (RestClientException e) {
throw new RestClientException("Idp facade API error for user first name " + customerUpdateRecordsDto.getFirstName(), e);
}
</code></pre>
<p>`</p>
| [
{
"answer_id": 74384091,
"author": "Panda Kim",
"author_id": 20430449,
"author_profile": "https://Stackoverflow.com/users/20430449",
"pm_score": 2,
"selected": true,
"text": "mask"
},
{
"answer_id": 74384168,
"author": "Python16367225",
"author_id": 16367225,
"author_profile": "https://Stackoverflow.com/users/16367225",
"pm_score": 0,
"selected": false,
"text": "df.index"
},
{
"answer_id": 74384369,
"author": "RufusVS",
"author_id": 925592,
"author_profile": "https://Stackoverflow.com/users/925592",
"pm_score": 0,
"selected": false,
"text": "for idx in df.index:\n if (df.iloc[idx]['Contact']=='Missing'):\n if len(df.iloc[idx]['Old Contact'].strip()):\n df.iloc[idx]['Contact']=df.iloc[idx]['Old Contact']\n"
},
{
"answer_id": 74384427,
"author": "Jason Baker",
"author_id": 3249641,
"author_profile": "https://Stackoverflow.com/users/3249641",
"pm_score": 0,
"selected": false,
"text": "df = df.assign(\n Contact=df[\"Contact\"].where(df[\"Contact\"].ne(\"Missing\"), df[\"Old Contact\"]).fillna(\"Missing\")\n).fillna(\"\")\nprint(df)\n\n Contact Old Contact\n0 234255 987778.0\n1 343556 987877.0\n2 984567.0 984567.0\n3 Missing \n4 845665.0 845665.0\n5 343556 789998.0\n"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74384059",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20464887/"
] |
74,384,074 | <p>I'm trying to remove the last comma at the end of my string, plain and simply because it looks WRONG.</p>
<pre><code>while($row = mysqli_fetch_assoc($query)){
$category = $row['category'];
$string = "<a href='category.php'>".$category.",</a> ";
echo $string;
}
</code></pre>
<p>For Example (because this type of question has been getting downvotes).</p>
<p>With comma at the end:</p>
<p>1, 2, 3, 4, 5, 6,</p>
<p>Without comma at the end (what I want the end result to be):</p>
<p>1, 2, 3, 4, 5, 6</p>
<p>How do I remove that annoying little annoying comma at the end? I've used rtrim() but apparently it's not a good function to use.</p>
| [
{
"answer_id": 74384188,
"author": "dvnc0",
"author_id": 20464681,
"author_profile": "https://Stackoverflow.com/users/20464681",
"pm_score": -1,
"selected": false,
"text": "substr"
},
{
"answer_id": 74384204,
"author": "Ram",
"author_id": 3680844,
"author_profile": "https://Stackoverflow.com/users/3680844",
"pm_score": 1,
"selected": false,
"text": "// get last item\n$last = end(mysqli_fetch_assoc($query));\nwhile($row = mysqli_fetch_assoc($query)){\n $category = $row['category'];\n $string = \"<a href='category.php'>\".$category.\"</a> \";\n // check if current item is not the last item; add a comma\n if($row != $last):\n $string .= ', ';\n endif;\n echo $string;\n}\n"
},
{
"answer_id": 74384323,
"author": "kmoser",
"author_id": 378779,
"author_profile": "https://Stackoverflow.com/users/378779",
"pm_score": 2,
"selected": true,
"text": "$a = []; // Array of <a href>'s\nwhile($row = mysqli_fetch_assoc($query)){\n $category = $row['category'];\n $a[] = \"<a href='category.php'>$category</a>\";\n}\necho join(', ', $a);\n"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74384074",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19670004/"
] |
74,384,075 | <p>I have a javascript array that contains 40 items in it. I want to create a function so that the function cycles through of item in the array and makes an api call based on the current value of the array.</p>
<p>The catch is that I want there to be a 3 second timer between each of the api calls in order to prevent exceeding the number of allows api calls per second.</p>
<p>This function gets the list of properties in an array. This is what I attempted so far.</p>
<pre><code>const getPropertiesInCity = (properties) => {
for(i = 0; i < properties.length; i++){
let property = properties[i]
setTimeout(() => {
getPropertyDetails(property.zpid)
}, 5000)
}
}
</code></pre>
<p>what I get is this:</p>
<pre><code>error
error
error
error
error
error
error
error
error
error
error
error
error
error
error
error
error
error
error
error
error
error
error
error
error
error
error
error
error
error
error
error
error
error
error
error
error
have the property
have the property
have the property
</code></pre>
<p>the error is because I am sending to many request within a specific time. It waits 5 seconds and the gives me all the errors and then 3 positive responses.</p>
| [
{
"answer_id": 74384167,
"author": "vitaly-t",
"author_id": 1102051,
"author_profile": "https://Stackoverflow.com/users/1102051",
"pm_score": 1,
"selected": false,
"text": "import {pipeAsync, map, wait, delay} from 'iter-ops';\n\nconst properties = [...]; // your list of objects\n\nconst i = pipeAsync(\n properties,\n map(p => getPropertyDetails(p.zpid)), // re-map into requests\n wait(), // wait for the request to finish\n delay(5000) // wait for 5 seconds\n); //=> AsyncIterable\n\n// to handle all iteration errors:\ni.catch(err => {\n console.log('CAUGHT:', err);\n});\n\n(async function () {\n for await (const a of i) {\n console.log(a); // whatever getPropertyDetails resolves with\n }\n})();\n"
},
{
"answer_id": 74384285,
"author": "jfriend00",
"author_id": 816620,
"author_profile": "https://Stackoverflow.com/users/816620",
"pm_score": 3,
"selected": true,
"text": "setTimeout()"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74384075",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19124184/"
] |
74,384,076 | <p>How can i only let tid length 7 at level <strong>one</strong> and tid length 10 go to show at level <strong>two</strong>. I tried to use v-if to make as filter but only show the level <strong>one</strong>, but level <strong>two</strong> doesn't show.</p>
<p>Tid</p>
<p><img src="https://i.stack.imgur.com/Dt7OM.png" alt="Tid" /></p>
<p>Current problem</p>
<p><img src="https://i.stack.imgur.com/jy7Oy.png" alt="Current Problem" /></p>
<p>Treelist</p>
<p><img src="https://i.stack.imgur.com/3NKNm.png" alt="Treelist" /></p>
<p>What I'm looking for</p>
<p><img src="https://i.stack.imgur.com/yCv3w.png" alt="Example" /></p>
<p><a href="https://ibb.co/GdPf8yd" rel="nofollow noreferrer">https://ibb.co/GdPf8yd</a> << Example Tid</p>
<p>Example : level one <code>8000001</code> so under will be <code>8000001000, 8000001001, 8000001002, 8000001003, 8000001004</code></p>
<pre class="lang-html prettyprint-override"><code><template>
<div class="css-treeview">
<template v-for="item in treelist" :key="item">
<ul>
<li v-if="item.t.length == 7"><input type="checkbox" id="item-0" /><label for="item-0">{{ item.mAcName }} ---
{{ item.mName }}</label>
<ul>
<li v-if="item.t.length == 10"><input type="checkbox" id="item-0-0" /><label for="item-0-0">{{ item.mAcName }}
--- {{ item.mName }}</label>
</li>
</ul>
</li>
</ul>
</template>
</div>
</template>
</code></pre>
| [
{
"answer_id": 74384228,
"author": "O-h-y-o",
"author_id": 20417954,
"author_profile": "https://Stackoverflow.com/users/20417954",
"pm_score": 1,
"selected": false,
"text": "<template>\n <div class=\"css-treeview\">\n <template v-for=\"item in treelist\" :key=\"item\">\n <ul>\n <li v-if=\"item.t.length === 7\">\n <input type=\"checkbox\" id=\"item-0\" /><label for=\"item-0\">{{ item.mAcName }} --- {{ item.mName }}</label>\n <ul>\n <template v-for=\"item2 in treelist\" :key=\"item2\">\n <li v-if=\"item2.t.length === 10\">\n <input type=\"checkbox\" id=\"item-0-0\" />\n <label for=\"item-0-0\">{{ item2.mAcName }} --- {{ item2.mName }}</label>\n </li>\n </template>\n </ul>\n </li>\n </ul>\n </template>\n </div>\n</template>\n"
},
{
"answer_id": 74385053,
"author": "Deny Kristianto Pamuji",
"author_id": 9515988,
"author_profile": "https://Stackoverflow.com/users/9515988",
"pm_score": 0,
"selected": false,
"text": "<template>\n <div>\n <ul>\n <li v-for=\"item in treeGrouped\">\n {{item.value}}\n <ul>\n <li v-for=\"child in item.children\">\n {{child}}\n </li>\n </ul>\n </li>\n </ul>\n </div>\n</template>\n\n<script>\n export default {\n data() {\n return {\n treelist: [\n 'aaaaabb',\n 'aaaaabbbbb',\n 'aaaaabb',\n 'aaaaabbbbb',\n 'aaaaabbbbb',\n 'aaaaabb',\n 'aaaaabb',\n 'aaaaabbbbb',\n 'aaaaabbbbb',\n 'aaaaabbbbb',\n 'aaaaabb',\n ]\n }\n },\n computed: {\n treeGrouped() {\n const result = []\n this.treelist.forEach((item)=>{\n if (item.length === 7) {\n result.push({\n value: item,\n children: [], \n })\n } else if (item.length === 10) {\n if (result.length) {\n result[result.length-1].children.push(item)\n }\n }\n })\n return result;\n }\n }\n }\n</script>\n"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74384076",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20181506/"
] |
74,384,114 | <p>I need to filter the df based on 2 criteria: where Name != jack and ignore all dates for jack where Date <= 2020-04-01</p>
<pre><code> # List of Tuples
df = [ ('jack', 'Apples' , '2020-01-01') ,
('Riti', 'Mangos' , '2020-02-01') ,
('Aadi', 'Grapes' , '2020-03-01') ,
('jack', 'Oranges', '2020-04-01') ,
('Lucy', 'Mangos' , '2020-05-01') ,
('jack', 'Apples' , '2020-12-01')
]
#Create a DataFrame object
df1 = pd.DataFrame(df, columns = ['Name' , 'Product', 'Date'])
df1
</code></pre>
<p>Expected result being:</p>
<pre><code> Name Product Date
0 Riti Mangos 2020-02-01
1 Aadi Grapes 2020-03-01
2 Lucy Mangos 2020-05-01
3 jack Apples 2020-12-01
</code></pre>
| [
{
"answer_id": 74384239,
"author": "Panda Kim",
"author_id": 20430449,
"author_profile": "https://Stackoverflow.com/users/20430449",
"pm_score": 3,
"selected": true,
"text": "boolean indexing"
},
{
"answer_id": 74384292,
"author": "kavigun",
"author_id": 3202440,
"author_profile": "https://Stackoverflow.com/users/3202440",
"pm_score": 0,
"selected": false,
"text": "import pandas as pd\n # List of Tuples\ndf = [('jack', 'Apples' , '2020-01-01'), \n('Riti', 'Mangos' , '2020-02-01'),\n('Aadi', 'Grapes' , '2020-03-01'),\n('jack', 'Oranges', '2020-04-01'),\n('Lucy', 'Mangos' , '2020-05-01'),\n('jack', 'Apples' , '2020-12-01')\n]\n#Create a DataFrame object\ndf1 = pd.DataFrame(df, columns = ['Name', 'Product', 'Date']) \n\n# Filtering for condition Name = !jack\ndf1 = df1[df1['Name'] != 'jack']\n\n# Convert the date to datetime64\ndf1['Date'] = pd.to_datetime(df1['Date'], format='%Y-%m-%d')\n\n# Filter by specified date\nfiltered_df = df1.loc[(df1['Date'] <= '2020-04-01')]\n\n# print the filtered result\nprint(filtered_df)\n"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74384114",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19046169/"
] |
74,384,135 | <p>I have asked the user for input and set out while true,try and expect blocks. I keep getting valueError even though I have set out that integer required should be displayed if I enter a letter.</p>
<pre><code>pass_credit=int(input("please enter your credits at pass:"))
defer_credit=int(input("Please enter your credits at defer:"))
fail_credit=int(input("please enter your credits at fail:"))
</code></pre>
<p>I tried everything to correct but I do not understand</p>
| [
{
"answer_id": 74384189,
"author": "Aftab_Udaipurwala",
"author_id": 20417129,
"author_profile": "https://Stackoverflow.com/users/20417129",
"pm_score": 0,
"selected": false,
"text": "if __name__ =='__main__':\n pass_credit=int(float(input(\"please enter your credits at pass:\")))\n defer_credit=int(float(input(\"Please enter your credits at defer:\")))\n fail_credit=int(float(input(\"please enter your credits at fail:\")))\n"
},
{
"answer_id": 74384301,
"author": "RufusVS",
"author_id": 925592,
"author_profile": "https://Stackoverflow.com/users/925592",
"pm_score": 1,
"selected": false,
"text": "while True:\n try: \n pass_credit=int(input(\"please enter your credits at pass:\"))\n break\n except ValueError as e:\n print (\"Bad integer value entered, try again.\")\n\nwhile True:\n try: \n defer_credit=int(input(\"please enter your credits at defer:\"))\n break\n except ValueError as e:\n print (\"Bad integer value entered, try again.\")\n\nwhile True:\n try: \n fail_credit=int(input(\"please enter your credits at fail:\"))\n break\n except ValueError as e:\n print (\"Bad integer value entered, try again.\")\n\nprint(f\"You entered: {pass_credit=}, {defer_credit=}, {fail_credit=}\")\n"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74384135",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20463955/"
] |
74,384,145 | <p>I have this data <strong>:</strong></p>
<pre><code>let obj = {
"additional_image_link": [
[
"https://2ccdn.celestino.gr/small/SK7732.1825-7@2.jpg",
"https://2ccdn.celestino.gr/small/SK7732.1825-7@2F.jpg",
]
],
"aff_link": "https://go.linkwi.se/z/11593-0/CD24352/?lnkurl=https%3A%2F%2Fwww.celestino.gr%2Fel-GR%2Fpanteloni-me-pietes-lefko%2Fprd%2FSK7732.1825%2F7%3Faffiliate%3Dlinkwise%26utm_source%3Dlinkwise%26utm_medium%3Dlw%26utm_campaign%3Dlw",
"all_sizes": [
"S",
"M",
"L"
],
"availability": "Y",
"brand": "Celestino",
"breadcrumbs": [
"ΡΟΥΧΑ",
"ΠΑΝΤΕΛΟΝΙΑ"
],
"breadcrumbs_url": [
"/el-gr/gynaikeia-rouxa/r=0000000006",
"/el-gr/gynaikeia-pantelonia/r=0101000000",
"/el-gr/pantelonia/r=0101001800"
],
"description": "Παντελόνι με πιέτες, κλείσιμο με φερμουάρ και κουμπί, θηλιές στη μέση, με τσέπες, λευκο",
"id": "SK7732.1825+1",
"image_link": "https://2ccdn.celestino.gr/small/SK7732.1825-7@1F.JPG",
"link": "https://www.celestino.gr/el-GR/panteloni-me-pietes-lefko/prd/SK7732.1825/7?affiliate=linkwise&utm_source=linkwise&utm_medium=lw&utm_campaign=lw",
"sizes_in_stock": [
"S",
"M"
],
"sizes_in_stock_feed": "S,M,L",
};
</code></pre>
<p>Now, I want to loop through all the <code>property</code> of this object and make a new array of object. I mean <code>property</code> will be same but if the property value has array or array of array I want to make it a single array.</p>
<p>What I tried <strong>:</strong></p>
<pre><code>let additional = [];
for( property in obj ) {
if( Array.isArray( obj[ property ] ) ) {
additional.push({
[property] : obj[property]
});
} else if ( isValidUrl ( obj[ property ] ) ) {
additional.push({
[property] : '<a href="' + obj[ property ] + '">' + obj[ property ] + '</a>'
});
} else {
additional.push({
[property] : obj[property]
});
}
}
console.log(additional)
</code></pre>
<p>The output is <strong>:</strong></p>
<pre><code>[ { additional_image_link: [ [Array] ] },
{ aff_link:
'<a href="https://go.linkwi.se/z/11593-0/CD24352/?lnkurl=https%3A%2F%2Fwww.celestino.gr%2Fel-GR%2Fpanteloni-me-pietes-lefko%2Fprd%2FSK7732.1825%2F7%3Faffiliate%3Dlinkwise%26utm_source%3Dlinkwise%26utm_medium%3Dlw%26utm_campaign%3Dlw">https://go.linkwi.se/z/11593-0/CD24352/?lnkurl=https%3A%2F%2Fwww.celestino.gr%2Fel-GR%2Fpanteloni-me-pietes-lefko%2Fprd%2FSK7732.1825%2F7%3Faffiliate%3Dlinkwise%26utm_source%3Dlinkwise%26utm_medium%3Dlw%26utm_campaign%3Dlw</a>' },
{ all_sizes: [ 'S', 'M', 'L' ] },
{ availability: 'Y' },
{ brand: 'Celestino' },
{ breadcrumbs: [ 'ΡΟΥΧΑ', 'ΠΑΝΤΕΛΟΝΙΑ' ] },
{ breadcrumbs_url:
[ '/el-gr/gynaikeia-rouxa/r=0000000006',
'/el-gr/gynaikeia-pantelonia/r=0101000000',
'/el-gr/pantelonia/r=0101001800' ] },
{ description:
'Παντελόνι με πιέτες, κλείσιμο με φερμουάρ και κουμπί, θηλιές στη μέση, με τσέπες, λευκο' },
{ id: 'SK7732.1825+1' },
{ image_link: 'https://2ccdn.celestino.gr/small/SK7732.1825-7@1F.JPG' },
{ link:
'<a href="https://www.celestino.gr/el-GR/panteloni-me-pietes-lefko/prd/SK7732.1825/7?affiliate=linkwise&utm_source=linkwise&utm_medium=lw&utm_campaign=lw">https://www.celestino.gr/el-GR/panteloni-me-pietes-lefko/prd/SK7732.1825/7?affiliate=linkwise&utm_source=linkwise&utm_medium=lw&utm_campaign=lw</a>' },
{ sizes_in_stock: [ 'S', 'M' ] },
{ sizes_in_stock_feed: 'S,M,L' } ]
</code></pre>
<p>But as you can see the <code>additional_image_link</code> has an array of array that's why the output is showing <code>[Array]</code>. But I want it's should be single array link <code>all_sizes</code>.</p>
<p><strong>I have recursive function to loop through array of array :</strong></p>
<pre><code>function loop(data, outputArray) {
if(!Array.isArray(data)) {
outputArray.push(data);
} else {
data.forEach( ( element ) => {
if(Array.isArray(element)) {
loop(element, outputArray);
} else {
outputArray.push(element);
}
})
}
}
</code></pre>
<p>But no idea how to use it to the function.</p>
<p>May be I need to work on this block:</p>
<pre><code>if( Array.isArray( obj[ property ] ) ) {
additional.push({
[property] : obj[property]
});
}
</code></pre>
| [
{
"answer_id": 74384230,
"author": "Rajesh",
"author_id": 3783478,
"author_profile": "https://Stackoverflow.com/users/3783478",
"pm_score": 0,
"selected": false,
"text": "Array.concat"
},
{
"answer_id": 74385169,
"author": "Rohìt Jíndal",
"author_id": 4116300,
"author_profile": "https://Stackoverflow.com/users/4116300",
"pm_score": 1,
"selected": false,
"text": "Array.isArray()"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74384145",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1091439/"
] |
74,384,170 | <p>I am working on BPM project and using Activiti for the BPM configuration.</p>
<p>While executing the process I am facing one issue, where one of the property which is I am passing from one of the task expecting to meet to other task wont work.</p>
<p>This is the error I am facing:</p>
<blockquote>
<p>Activiti Caused by: javax.el.PropertyNotFoundException: Cannot resolve
identifier ''</p>
</blockquote>
<p>I data is passes from User Task to Service Task.</p>
<p><a href="https://i.stack.imgur.com/VP2v8.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/VP2v8.jpg" alt="enter image description here" /></a></p>
<p>I am expecting that the based on the property the "Exclusive Gateway" should work.
The criteria I mentioned like:</p>
<p><a href="https://i.stack.imgur.com/vEx4Y.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/vEx4Y.jpg" alt="enter image description here" /></a></p>
<p>The property which I mentioned in the "Condition" is not found while the process execution.(The Name right now, first part is dark out).</p>
<p>Any idea what issue it is or how can I get the property?</p>
<p>Thanks,
Atul</p>
| [
{
"answer_id": 74384230,
"author": "Rajesh",
"author_id": 3783478,
"author_profile": "https://Stackoverflow.com/users/3783478",
"pm_score": 0,
"selected": false,
"text": "Array.concat"
},
{
"answer_id": 74385169,
"author": "Rohìt Jíndal",
"author_id": 4116300,
"author_profile": "https://Stackoverflow.com/users/4116300",
"pm_score": 1,
"selected": false,
"text": "Array.isArray()"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74384170",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3948697/"
] |
74,384,200 | <p>I'm getting a json format like this and I want to get the value of <em>"Duration", "Id", "LoadCumulLimit" and "Notes"</em>.</p>
<p><code>QJsonDocument({"d":{"results":[{"Duration":"420.000","Id":"123456789XYZ","LoadCumulLimit":"15.000","NavWpNioshToOpNoish":{"__deferred":{"uri":"http://xxx/WorkplaceNOISHDataSet('123456789XYZ')/NavWpNioshToOpNoish"}},"Notes":"123456789XYZ","__metadata":{"id":"xxx/WorkplaceNOISHDataSet('123456789XYZ')","type":"xxx.WorkplaceNOISHData","uri":"xxx/WorkplaceNOISHDataSet('123456789XYZ')"}}]}})</code></p>
<p>I tried to do this but it doesn't work and it return empty with array
`</p>
<pre><code>QJsonDocument document = QJsonDocument::fromJson(content.toUtf8());
QJsonArray documentArray = document.array();
QStringList wordList;
for (const QJsonValue &i : documentArray)
{
//qInfo() << i.toString() << endl;
wordList << i.toString();
}
</code></pre>
<p>Could you guys give me a help or any suggest?</p>
| [
{
"answer_id": 74384230,
"author": "Rajesh",
"author_id": 3783478,
"author_profile": "https://Stackoverflow.com/users/3783478",
"pm_score": 0,
"selected": false,
"text": "Array.concat"
},
{
"answer_id": 74385169,
"author": "Rohìt Jíndal",
"author_id": 4116300,
"author_profile": "https://Stackoverflow.com/users/4116300",
"pm_score": 1,
"selected": false,
"text": "Array.isArray()"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74384200",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8296423/"
] |
74,384,244 | <p>The red border is only for reference. I have tried <code>overflow: hidden</code> but it didn't work. I am trying to have the same border radius as the red border. Is there anything that I am doing wrong? Thank you.</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>*,*::before, *::after {
margin: 0;
padding: 0;
box-sizing: border-box;
--violet: #8F00FF;
}
.rating {
border: 1px solid red;
border-radius: 8px;
width: 30px;
margin-left: 100px;
margin-top: 100px;
background-color: #f0f0f0;
display: flex;
flex-direction: column;
box-shadow: -5px 0px 8px rgba(172, 169, 169, 0.1);
}
button {
border: none;
border-radius: 8px;
align-items: center;
color: var(--violet);
font-weight: bold;
cursor: pointer;
-webkit-border-radius:10px;
overflow: hidden;
}
.rating span {
display: flex;
justify-content: center;
color: var(--violet);
font-weight: bold;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Interface</title>
<!-- CSS Link -->
<link rel="stylesheet" href="style.css">
<!-- Boxicons -->
<script src="https://unpkg.com/boxicons@2.1.4/dist/boxicons.js"></script>
<!-- Bootstrap -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/css/bootstrap.min.css" rel="stylesheet">
<!-- JS Link -->
<script src="script.js" defer></script>
</head>
<body>
<!-- <div class="single-card">
</div> -->
<div class="rating">
<button>+</button>
<span>12</span>
<button>-</button>
</div>
</body>
</html></code></pre>
</div>
</div>
</p>
| [
{
"answer_id": 74384291,
"author": "Nick Vu",
"author_id": 9201587,
"author_profile": "https://Stackoverflow.com/users/9201587",
"pm_score": 0,
"selected": false,
"text": "overflow: hidden"
},
{
"answer_id": 74384296,
"author": "Anh Le Hoang",
"author_id": 16315750,
"author_profile": "https://Stackoverflow.com/users/16315750",
"pm_score": 1,
"selected": false,
"text": "overflow: hidden;"
},
{
"answer_id": 74384367,
"author": "Saad1430",
"author_id": 19199222,
"author_profile": "https://Stackoverflow.com/users/19199222",
"pm_score": 0,
"selected": false,
"text": "<button>"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74384244",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20464992/"
] |
74,384,254 | <p>I'm using <strong>ScalingLazyColumn</strong> with a very long <strong>Text</strong> inside as follows:</p>
<pre><code>@Preview(device = Devices.WEAR_OS_SMALL_ROUND, showSystemUi = true)
@Composable
fun Test(modifier: Modifier = Modifier) {
val scalingLazyState = remember { ScalingLazyListState() }
val focusRequester = remember { FocusRequester() }
Scaffold(
modifier = modifier,
positionIndicator = { PositionIndicator(scalingLazyListState = scalingLazyState) }
) {
ScalingLazyColumn(
modifier = Modifier.scrollableColumn(focusRequester, scalingLazyState),
state = scalingLazyState,
) {
item {
Text(
longText,
Modifier
.padding(top = 20.dp, start = 16.dp, end = 16.dp, bottom = 48.dp),
textAlign = TextAlign.Center,
)
}
}
}
}
val longText =
"Take the plunge\n" +
"\n" +
"commit oneself to a course of action about which one is nervous.\n" +
"\n" +
"\"she wondered whether to enter for the race, but decided to take the plunge\"\n" +
"\"They're finally taking the plunge and getting married.\"\n" +
"\n" +
"\n" +
"plunge:\n" +
"jump or dive quickly and energetically.\n" +
"\"our daughters whooped as they plunged into the sea\"\n"
</code></pre>
<p>But for some reason when I launch the app the <strong>focus goes to the bottom</strong> of the text, instead of the <strong>beginning</strong>, which looks like a bug. I've tried playing with different parameters of <strong>ScalingLazyColumn</strong> (<em>anchorType</em>, <em>autoCentering</em>, <em>scalingParams</em>) to no avail.</p>
<p><a href="https://i.stack.imgur.com/XRedI.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/XRedI.gif" alt="demo" /></a></p>
<p>Any idea how to fix it and make the <strong>ScalingLazyColumn</strong> focus on the beginning of the first element when I launch the app?</p>
| [
{
"answer_id": 74385014,
"author": "Yuri Schimke",
"author_id": 1542667,
"author_profile": "https://Stackoverflow.com/users/1542667",
"pm_score": 0,
"selected": false,
"text": "\n val scalingLazyState = remember { ScalingLazyListState(initialCenterItemIndex = 0) }\n val focusRequester = remember { FocusRequester() }\n\n Scaffold(\n modifier = Modifier,\n positionIndicator = { PositionIndicator(scalingLazyListState = scalingLazyState) }\n ) {\n ScalingLazyColumn(\n modifier = Modifier.scrollableColumn(focusRequester, scalingLazyState),\n state = scalingLazyState,\n anchorType = ScalingLazyListAnchorType.ItemStart\n ) {\n item {\n Text(\n longText,\n Modifier\n .padding(top = 20.dp, start = 16.dp, end = 16.dp, bottom = 48.dp),\n textAlign = TextAlign.Center,\n )\n }\n }\n\n }\n"
},
{
"answer_id": 74385454,
"author": "konnovdev",
"author_id": 7219194,
"author_profile": "https://Stackoverflow.com/users/7219194",
"pm_score": 1,
"selected": false,
"text": " val scalingLazyState = remember { ScalingLazyListState() }\n val focusRequester = remember { FocusRequester() }\n\n Scaffold(\n modifier = modifier,\n positionIndicator = { PositionIndicator(scalingLazyListState = scalingLazyState) }\n ) {\n ScalingLazyColumn(\n modifier = Modifier.scrollableColumn(focusRequester, scalingLazyState),\n state = scalingLazyState,\n autoCentering = null,\n ) {\n item {\n Text(\n longText,\n Modifier\n .padding(top = 20.dp, start = 16.dp, end = 16.dp, bottom = 48.dp),\n textAlign = TextAlign.Center,\n )\n }\n }\n }"
},
{
"answer_id": 74389129,
"author": "John Nichol",
"author_id": 7756277,
"author_profile": "https://Stackoverflow.com/users/7756277",
"pm_score": 4,
"selected": true,
"text": "ScalingLazyListAnchorType.ItemStart"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74384254",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7219194/"
] |
74,384,258 | <p>I have a selectpicker inside a table. I am passing the selected value into it but it shows the first value. why?</p>
<pre><code><td>
<select name="select[]" id="select" data-selected="224515"
class="selectpicker form-control select" data-live-search="true"
data-show-subtext="true" data-size="5"
data-container="body" title="Search Parts..">
@foreach ($list as $p)
<option data-id="{{ $p->id }}"
data-subtext="{{ $p->code }}"
data-tokens="{{ $p->id }}"
data-name="{{ $p->name }}" data-price="{{ $p->price }}"
data-code="{{ $p->code }}">
{{ $p->name }}</option>
@endforeach
</select>
</td>
</code></pre>
| [
{
"answer_id": 74387919,
"author": "Shreya Desai",
"author_id": 11439701,
"author_profile": "https://Stackoverflow.com/users/11439701",
"pm_score": 0,
"selected": false,
"text": "<td>\n <select name=\"select[]\" id=\"select\"\n class=\"selectpicker form-control select\" data-live-search=\"true\" data-show- \n subtext=\"true\" data-size=\"5\" data-container=\"body\" title=\"Search Parts..\">\n @foreach ($list as $p)\n <option data-id=\"{{ $p->id }}\" \n value=\"{{ $p->value }}\" \"{{ ( $p->value == \"224515\") ? 'selected' : '' }}\"\n data-subtext=\"{{ $p->code }}\"\n data-tokens=\"{{ $p->id }}\" \n data-name=\"{{ $p->name }}\" \n data-price=\"{{ $p->price }}\" \n data-code=\"{{ $p->code }}\">{{ $p->name }}\n </option>\n @endforeach\n</select></td> \n"
},
{
"answer_id": 74388023,
"author": "Douwe de Haan",
"author_id": 1336174,
"author_profile": "https://Stackoverflow.com/users/1336174",
"pm_score": 2,
"selected": true,
"text": "@selected"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74384258",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15787350/"
] |
74,384,329 | <p>I have this component:</p>
<pre><code><div #widget
class="widget">
</div>
@ViewChild('widget') widget!: any;
ngOnInit() {
console.log(this.widget.nativeElement) //returns undedined
}
</code></pre>
<p>However it is working if I use native api:</p>
<pre><code>console.log(document.querySelector('.widget'));
</code></pre>
<p>Then I've done some research and figure out that:</p>
<pre><code> @ViewChild('widget', {static: true}) widget!: any;
</code></pre>
<p>It is fixed the native element looking to the answers to this <a href="https://stackoverflow.com/a/56359612">question</a>, however the <a href="https://stackoverflow.com/a/56359612/415078">main answers</a> there is quite confusing:</p>
<blockquote>
<p>In most cases you will want to use {static: false}. Setting it like
this will ensure query matches that are dependent on binding
resolution (like structural directives *ngIf, etc...) will be found.</p>
</blockquote>
<p>and</p>
<blockquote>
<p>The { static: true } option was introduced to support creating
embedded views on the fly. When you are creating a view dynamically
and want to acces the TemplateRef, you won't be able to do so in
ngAfterViewInit as it will cause a ExpressionHasChangedAfterChecked
error. Setting the static flag to true will create your view in
ngOnInit.</p>
</blockquote>
<p>So now I do have a few questions</p>
<ol>
<li>Does it mean that <code>@ViewChild('widget', {static: true}) widget!</code> is equal to <code>document.querySelector('.widget')</code>?</li>
<li>Is they are not equal in what cases I have to use <code>@ViewChild('widget', {static: true}) widget!</code> vs <code>document.querySelector('.widget')</code>?</li>
<li>In what cases i should use <code>@ViewChild('widget', {static: true}) widget!</code> vs <code>@ViewChild('widget', {static: false}) widget!</code>?</li>
<li>In my case I am not using any dynamic views but the refered <a href="https://stackoverflow.com/a/56359612/415078">answer</a> suggesting to use <code>{static: false}</code> is quite bizarre.</li>
</ol>
| [
{
"answer_id": 74384431,
"author": "Khumo Mogorosi",
"author_id": 9674861,
"author_profile": "https://Stackoverflow.com/users/9674861",
"pm_score": 0,
"selected": false,
"text": "ngOnInit()"
},
{
"answer_id": 74385533,
"author": "Eliseo",
"author_id": 8558186,
"author_profile": "https://Stackoverflow.com/users/8558186",
"pm_score": 2,
"selected": true,
"text": "{static:true}"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74384329",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2926340/"
] |
74,384,336 | <p>I have an array which has keys <code>eventId</code> and <code>selectedNumber</code>. In the array same eventid can be present in multiple objects but <code>selectedNumber</code> value will be always different. My aim is to make a nested array in which each object will have unique <code>eventId</code> But <code>selectedNumber</code> will become an array having numbers from each of those objects having the same <code>eventId</code>. I tried using lodash _.groupBy() method but its just combines the objects into array and add it to the value with key as <code>eventId</code>. I don't want that. Anyway to do it?</p>
<pre><code>Input:--
[{
"eventId" : "636939dde9341f2fbbc7256e",
"selectedNumber" : "20"
},
{
"eventId" : "636939dde9341f2fbbc7256e",
"selectedNumber" : "30"
},
{
"eventId" : "63693a55e9341f2fbbc725c0",
"selectedNumber" : "50"
}]
Result:--
[{
"eventId" : "636939dde9341f2fbbc7256e",
"selectedNumber" : ["20", "30"]
},
{
"eventId" : "63693a55e9341f2fbbc725c0",
"selectedNumber" : "50"
}]
</code></pre>
| [
{
"answer_id": 74384431,
"author": "Khumo Mogorosi",
"author_id": 9674861,
"author_profile": "https://Stackoverflow.com/users/9674861",
"pm_score": 0,
"selected": false,
"text": "ngOnInit()"
},
{
"answer_id": 74385533,
"author": "Eliseo",
"author_id": 8558186,
"author_profile": "https://Stackoverflow.com/users/8558186",
"pm_score": 2,
"selected": true,
"text": "{static:true}"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74384336",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5392636/"
] |
74,384,354 | <p>I have a model that uses an attention mechanism as below:</p>
<pre><code>def create_model(feature_size, max_features, num_class):
feature_input = Input((max_features,feature_size), dtype=tf.float32)
feature_vectors = TimeDistributed(Dense(feature_size, use_bias=False, activation='tanh'))(feature_input)
# Attention Layer
attention_vectors = Dense(1,)(feature_vectors)
attention_weights = Softmax()(attention_vectors)
# Generating code vectors
text_vectors = K.sum(feature_vectors * attention_weights, axis=1)
# Prediction layer
output_class = Dense(num_class, use_bias=False, activation='softmax')(text_vectors)
model = Model(inputs=feature_input, outputs=output_class)
return model
</code></pre>
<p>The training and testing codes are given below:</p>
<pre><code>model = create_model(feature_size, max_features, num_class)
#compile model
model.compile(loss='categorical_crossentropy',
optimizer='adam',
metrics=['acc'])
# check summary of model
model.summary()
# Early stopping
earlystopping = callbacks.EarlyStopping(monitor ="val_loss",
mode ="min", patience = 20,
restore_best_weights = True)
# train model
model.fit(x=X_train, y=Y_train,batch_size=64,epochs=200,validation_data=(X_test, Y_test), callbacks =[earlystopping])
# Performance
predicted = model.predict(x=X_test)
</code></pre>
<p>Here, the input has the dimension (<strong>batch_size, max_feature, feature_size</strong>). <strong>max_feature</strong> is the number of features for a given input and each feature is a vector of <strong>feature_size</strong> length. After that, I have calculated attention weights for each feature which is later used to calculate one single vector (<strong>text_vectors</strong>) with a weighted sum using these attention weights (<strong>feature_vectors X attention weights</strong>). After training the model, I want to have the attention weights for each test data point which were used to calculate the <strong>text_vector</strong> for that test data input. How can I achieve that?</p>
<p>I have already seen several SO posts such as in this <a href="https://stackoverflow.com/questions/49129858/how-to-extract-weights-of-hidden-layers-with-keras-api">answer</a>, one single line of code is being used.</p>
<pre><code>weights = [layer.get_weights() for layer in model.layers]
</code></pre>
<p>But, I am confused about how to put that in my code and how to get these attention weights for each feature for a given test data point. Can anyone please give me any direction?</p>
| [
{
"answer_id": 74384930,
"author": "V.M",
"author_id": 8143158,
"author_profile": "https://Stackoverflow.com/users/8143158",
"pm_score": 3,
"selected": true,
"text": "attention scores"
},
{
"answer_id": 74385028,
"author": "Jirayu Kaewprateep",
"author_id": 7848579,
"author_profile": "https://Stackoverflow.com/users/7848579",
"pm_score": -1,
"selected": false,
"text": "import os\nfrom os.path import exists\n\nimport tensorflow as tf\nimport tensorflow_text as tft\n\nimport matplotlib.pyplot as plt\nimport sklearn.metrics\nfrom sklearn.svm import SVC\n\n\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\n[PhysicalDevice(name='/physical_device:GPU:0', device_type='GPU')]\nNone\n\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\nphysical_devices = tf.config.experimental.list_physical_devices('GPU')\nassert len(physical_devices) > 0, \"Not enough GPU hardware devices available\"\nconfig = tf.config.experimental.set_memory_growth(physical_devices[0], True)\nprint(physical_devices)\nprint(config)\n\n\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\n: Variables\n\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\ninput_word = tf.constant(' \\'Cause it\\'s easy as an ice cream sundae Slipping outta your hand into the dirt Easy as an ice cream sundae Every dancer gets a little hurt Easy as an ice cream sundae Slipping outta your hand into the dirt Easy as an ice cream sundae Every dancer gets a little hurt Easy as an ice cream sundae Oh, easy as an ice cream sundae ')\ndataset = tf.data.Dataset.from_tensors( tf.strings.bytes_split(input_word) )\nprint( dataset )\n\nwindow_size = 6\nvocab = [ \"a\", \"b\", \"c\", \"d\", \"e\", \"f\", \"g\", \"h\", \"I\", \"j\", \"k\", \"l\", \"m\", \"n\", \"o\", \"p\", \"q\", \"r\", \"s\", \"t\", \"u\", \"v\", \"w\", \"x\", \"y\", \"z\", \"_\" ]\nlayer = tf.keras.layers.StringLookup(vocabulary=vocab)\nZeroPadding1D = tf.keras.layers.ZeroPadding1D(padding=(2))\n\n\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\n: Class and Functions\n\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\nclass MyDenseLayer(tf.keras.layers.Layer):\n def __init__(self, num_outputs):\n super(MyDenseLayer, self).__init__()\n self.num_outputs = num_outputs\n \n def build(self, input_shape):\n self.kernel = self.add_weight(\"kernel\",\n shape=[int(input_shape[-1]),\n self.num_outputs])\n\n def call(self, inputs):\n \n inputs_vocab = tf.constant( tf.cast( layer( inputs ), dtype=tf.float32 ), shape=(1, 6, 1) )\n Zero_padding = tf.constant( ZeroPadding1D( inputs_vocab ), shape=(10, 1) )\n \n print( inputs )\n print( Zero_padding )\n\n softmax = tf.keras.layers.Softmax( axis=-1 )\n # temp = softmax( Zero_padding )\n temp = Zero_padding\n ############################################################################################\n \n clf = SVC(random_state=0)\n clf.fit(tf.constant( temp, shape=(10, 1) ).numpy(), tf.cast( tf.linspace( 0, 9, 10, name='linspace', axis=0 ), dtype=tf.int64 ).numpy())\n predictions = clf.predict(tf.constant( temp, shape=(10, 1) ).numpy())\n \n cm = sklearn.metrics.confusion_matrix( [temp[0], temp[1], temp[2], temp[3], temp[4], temp[5], temp[6], temp[7], temp[8], temp[9]], [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], labels=clf.classes_)\n disp = sklearn.metrics.ConfusionMatrixDisplay(confusion_matrix=cm, display_labels=clf.classes_)\n disp.plot()\n plt.show()\n ############################################################################################\n \n return temp\n\n\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\n: Datasets\n\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\ndataset = dataset.map(lambda x: tft.sliding_window(x, width=window_size, axis=0)).flat_map(tf.data.Dataset.from_tensor_slices)\n\n\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\n: Tasks\n\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\nlayer_dense = MyDenseLayer(10)\nfor sample in dataset:\n result = layer_dense( sample )\n print(result)\n"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74384354",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4299527/"
] |
74,384,371 | <p>How would I go about adding a column to a MudBlazor DataGrid that uses a nested object?</p>
<p>For example, I have a basic entity called Foo which has the following makeup:</p>
<pre><code>public class Foo
{
public int Id {get; set;}
public Bar Bar {get; set;}
}
public class Bar
{
public string Name {get; set;}
}
</code></pre>
<p>How would I add Bar.Name to a column in <a href="https://mudblazor.com/components/datagrid" rel="nofollow noreferrer">MudBlazor's DataGrid</a>?</p>
<pre><code><MudDataGrid Items="@someIEnumerableOfTypeFoo">
<Columns>
<Column T="Foo" Field="Id" Title="Id" />
<Column T="Foo" Field="Bar.Name" /> <!-- This Fails -->
</Columns>
</MudDataGrid>
</code></pre>
| [
{
"answer_id": 74448511,
"author": "LYass",
"author_id": 15592966,
"author_profile": "https://Stackoverflow.com/users/15592966",
"pm_score": 1,
"selected": false,
"text": "public class Bar \n{\n public string Name {get; set;}\n public override string ToString(){\n return Name;\n }\n}\n"
},
{
"answer_id": 74525938,
"author": "user20567356",
"author_id": 20567356,
"author_profile": "https://Stackoverflow.com/users/20567356",
"pm_score": 1,
"selected": true,
"text": "<Column T=\"Foo\">\n <CellTemplate>\n <h1>@context.Item.Bar.Name</h1>\n </CellTemplate>\n</Column>\n"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74384371",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6490191/"
] |
74,384,372 | <p>Help me pls.
I have this error.
10Q</p>
<p>Unhandled Exception: NoSuchMethodError: Class 'FirebaseAuthException' has no instance getter '_message'.
E/flutter ( 5700): Receiver: Instance of 'FirebaseAuthException'
E/flutter ( 5700): Tried calling: _message</p>
<pre><code>await _auth
.signInWithEmailAndPassword(
email: _emailTextEditingController.text.trim(),
password: _passwordTextEditingController.text.trim(),
)
.then((authUser) {
setState(() {
firebaseUser = authUser.user;
});
}).catchError((error) {
showDialog(
context: context,
builder: (c) {
return ErrorAlertDialog(
message: error._message == '[firebase_auth/user-not-found] There is no user record corresponding to this identifier. The user may have been deleted.'
? 'Email or password incorrect' : 'Error',
);
});
});
</code></pre>
<pre><code>error._message == '[firebase_auth/user-not-found] There is no user record corresponding to this identifier. The user may have been deleted.'
? 'Email or password incorrect' : 'Error',
</code></pre>
| [
{
"answer_id": 74448511,
"author": "LYass",
"author_id": 15592966,
"author_profile": "https://Stackoverflow.com/users/15592966",
"pm_score": 1,
"selected": false,
"text": "public class Bar \n{\n public string Name {get; set;}\n public override string ToString(){\n return Name;\n }\n}\n"
},
{
"answer_id": 74525938,
"author": "user20567356",
"author_id": 20567356,
"author_profile": "https://Stackoverflow.com/users/20567356",
"pm_score": 1,
"selected": true,
"text": "<Column T=\"Foo\">\n <CellTemplate>\n <h1>@context.Item.Bar.Name</h1>\n </CellTemplate>\n</Column>\n"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74384372",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19936765/"
] |
74,384,395 | <p>Good morning
I've been sitting for 5 hours on what should be a simple problem. I would be grateful if you could end my suffering.
It is about a dashboard page. I want the user to be greeted with his name (Hello, ....) after he has registered with his email address. When registering, the email address is always the same, name.example@hotmail.de. I want to split the email address and display only the name, but I can only manage to display the whole email address.</p>
<p>view.py</p>
<pre><code>@login_required(login_url='login')
def Example_dashboard(request):
form = MembersForm()
current_user = request.user #current_user.split is not working!
context = {'form': form, "cunrrent_user": current_user}
return render(request, 'example_dashboard.html', context)
</code></pre>
<p>html</p>
<pre><code><p>Welcome, {{ current_user}} </p>
<form action='' method='POST'>
{%csrf_token%}
{{ form }}
</code></pre>
<p>models.py</p>
<pre><code>class Members(models.Model):
email = models.CharField(max_length=200, null=True)
passwort = models.CharField(max_length=200, null=True)
</code></pre>
<p>forms.py</p>
<pre><code>class MembersForm(ModelForm):
class Meta:
model = Members
fields = ["studiengang", "kategorien"]
</code></pre>
| [
{
"answer_id": 74384556,
"author": "ilyasbbu",
"author_id": 16475089,
"author_profile": "https://Stackoverflow.com/users/16475089",
"pm_score": 0,
"selected": false,
"text": "current_user = request.user"
},
{
"answer_id": 74384583,
"author": "Ankit Tiwari",
"author_id": 14457833,
"author_profile": "https://Stackoverflow.com/users/14457833",
"pm_score": 1,
"selected": false,
"text": "current_user = request.user #current_user.split is not working!\n"
},
{
"answer_id": 74387077,
"author": "August Infotech",
"author_id": 20289335,
"author_profile": "https://Stackoverflow.com/users/20289335",
"pm_score": 0,
"selected": false,
"text": "request.user"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74384395",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19433213/"
] |
74,384,403 | <p>I'm trying to avoid having a bunch of <code>if</code>s or <code>assert</code>s in the code using this class.</p>
<pre class="lang-py prettyprint-override"><code>class TemplateRow(tp.NamedTuple):
"""Parsed template row, if not error."""
template: Template | None = None
error: str | None = None
@property
def valid(self) -> bool:
"""Determine if this row is valid.
Returns:
bool: is this template row valid
"""
return self.error is None
def read_template(filename: str | Path) -> tp.Iterator[TemplateRow]:
"""Read a TSV file into a list of templates.
Args:
filename (str): Path to the TSV file
Yields:
TemplateRow : parsed template row, or error message
"""
with open(filename, "r", encoding="utf-8") as f:
reader = csv.DictReader(f, dialect=csv.excel_tab)
for row in reader:
try:
yield TemplateRow(template=Template.parse_obj(row))
except pydantic.ValidationError as e:
yield TemplateRow(error=str(e))
</code></pre>
<p>So, I read in a TSV and try to convert it to a Pydantic model with a bunch of validators. If it works, I return the filled-in model.
If it fails, I return the validation error string</p>
<p>To make the caller be able to just expect one type, I return a NamedTuple which can contain the parsed model instance, or an error string.</p>
<p>There's a simple property to say if it's valid, mainly for readability and for a possible future enhancement.</p>
<p>Anyway, if I have a loop such as:</p>
<pre class="lang-py prettyprint-override"><code>ok: list[Template]=[]
notok: list[str] = []
for row in read_template(file):
if row.valid:
ok.append(row.template)
else:
notok.append(row.error)
</code></pre>
<p>I will get mypy errors that row.error might be None</p>
<p>As I've already checked the <code>.valid</code> property, it can't be.</p>
<p>Is there anyway to communicate this to type checkers?</p>
<p>thanks</p>
| [
{
"answer_id": 74386094,
"author": "Paweł Rubin",
"author_id": 8091093,
"author_profile": "https://Stackoverflow.com/users/8091093",
"pm_score": 3,
"selected": true,
"text": "TypeGuard"
},
{
"answer_id": 74386418,
"author": "Daniil Fajnberg",
"author_id": 19770795,
"author_profile": "https://Stackoverflow.com/users/19770795",
"pm_score": 1,
"selected": false,
"text": "import csv\nfrom collections.abc import Iterator\nfrom pathlib import Path\n\nfrom pydantic import BaseModel, ValidationError\n\n\nclass Template(BaseModel):\n foo: str\n bar: int\n\n\ndef read_template(filename: str | Path) -> Iterator[Template | ValidationError]:\n with open(filename, \"r\", encoding=\"utf-8\") as f:\n reader = csv.DictReader(f, dialect=csv.excel_tab)\n for row in reader:\n try:\n yield Template.parse_obj(row)\n except ValidationError as e:\n yield e\n\n\ndef main() -> None:\n ok: list[Template] = []\n notok: list[str] = []\n for obj in read_template(\"path/to/file.tsv\"):\n if isinstance(obj, Template):\n ok.append(obj)\n else:\n notok.append(str(obj))\n ...\n"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74384403",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4574182/"
] |
74,384,406 | <p>Sort the k arrays individually and concatenate them.
Input Description:
First line contains the number of arrays. Subsequent lines contain the size of the array followed by the elements of the array.</p>
<p>Output Description:
An array containing the sorted elements of k sorted arrays</p>
<p>Sample Input :
3
2
98 12
6
1 2 3 8 5 9
1
11
Sample Output :
12 98 1 2 3 5 8 9 11</p>
<pre><code>
a=input()
b=input()
c= input().split()
C=str(sorted(c))
d=input()
e=input().split()
E=str(sorted(e))
f=input()
g=input().split()
G=str(sorted(g))
x=C+E+G
print(*x)````
#output
[ ' 1 2 ' , ' 9 8 ' ] [ ' 1 ' , ' 2 ' , ' 3 ' , ' 5 ' , ' 8 ' , ' 9 ' ] [ ' 1 1 ' ]````
`desired output`
#i want my output as
Sample Output :
12 98 1 2 3 5 8 9 11
</code></pre>
| [
{
"answer_id": 74385084,
"author": "creatorpravin",
"author_id": 17981270,
"author_profile": "https://Stackoverflow.com/users/17981270",
"pm_score": 2,
"selected": false,
"text": "import re\nval = \"[ ' 1 2 ' , ' 9 8 ' ] [ ' 1 ' , ' 2 ' , ' 3 ' , ' 5 ' , ' 8 ' , ' 9 ' ] [ ' 1 1 ' ]\"\nprint(re.sub(r'[^\\w]', ' ', val))\n"
},
{
"answer_id": 74385497,
"author": "Nazmul Hasan",
"author_id": 20173161,
"author_profile": "https://Stackoverflow.com/users/20173161",
"pm_score": 0,
"selected": false,
"text": "x = C + E + G\nx = x.replace('[', '').replace(']', ' ').replace(\"'\", '').replace(',', '')\nprint(x)\n"
},
{
"answer_id": 74403145,
"author": "Bhavesh Achhada",
"author_id": 14399624,
"author_profile": "https://Stackoverflow.com/users/14399624",
"pm_score": 0,
"selected": false,
"text": "a=input() # Number of arrays (let's say 3)\n\nb=input() # Length of first array (let's say 3)\n\nc= list(map(int, input().split())) # read a list of integer from user\n\n# C=str(sorted(c)) this line is a bug. sorting on strings (i.e. 100 is bigger than 2)\n\nc.sort() # here we sorted a list of integers which is correct\n\nd=input() # length of second array (let's say 6)\n\ne= list(map(int, input().split())) # again reading list of integers\n\n# E=str(sorted(e)) # again a bug. Sorting the strings\n\ne.sort() # sorting list of INT\n\nf=input() # length of 3rd array (let's say 1)\n\ng= list(map(int, input().split())) # reading list of INT\n\n# G=str(sorted(g)) # again a bug : )\ng.sort()\n\nx = c + e + g # '+' operator on a list concatenates them\n\nprint(*x)\n"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74384406",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18381720/"
] |
74,384,416 | <p>I am new to python and I've been trying to wrap my head around this code:</p>
<pre><code>stop = int(input())
result = 0
for a in range(4):
print(a, end=': ')
for b in range(2):
result += a + b
if result > stop:
print('-', end=' ')
continue
print(result, end=' ')
print()
</code></pre>
<p>When I input <code>6</code>, the output is</p>
<pre><code>0: 0 1
1: 2 4
2: 6 -
3: - -
</code></pre>
<p>why isn't it</p>
<pre><code>0: 0 1
1: 3 4 --> since we're starting out with a = 1 and b = 2 so result is 1 + 2 = 3.
etc
</code></pre>
<p>I feel like I'm missing something fundamental.</p>
| [
{
"answer_id": 74384882,
"author": "Nazmul Hasan",
"author_id": 20173161,
"author_profile": "https://Stackoverflow.com/users/20173161",
"pm_score": 0,
"selected": false,
"text": "when a = 0 and b = 1, result = 0 + 0 + 1 = 1, \n\nso, for a = 1 and b = 0, result = 1 + 1 + 0 = 2\nwhen a = 1 and b = 1, result = 2 + 1 + 1 = 4\n\nso, it will print 1: 2 4\n"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74384416",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20103444/"
] |
74,384,437 | <p>I would like to define the content of a file in a <code>wstring</code>, so I can print it with an <code>ofstream</code> later on.</p>
<p>Example:</p>
<pre><code>// Working
std::wstring file_content=L"€";
</code></pre>
<pre><code>// Working
file_content=L"€"
L"€"
L"€";
</code></pre>
<pre><code>// NOT Working
file_content=L"€"
L"€""
L"€";
</code></pre>
<pre><code>// Working
file_content=LR"SOMETHING(multiline
with
no
issues)SOMETHING";
</code></pre>
<p>For some reason, the last solution is not working for me WHEN I paste in the file content (Multibyte).</p>
<p>Errors:</p>
<blockquote>
<p>E0065 expected a ';'</p>
</blockquote>
<blockquote>
<p>E2452 ending delimiter for raw string not found</p>
</blockquote>
<p><a href="https://i.stack.imgur.com/DEp9K.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/DEp9K.png" alt="image" /></a></p>
| [
{
"answer_id": 74384488,
"author": "Özgür Murat Sağdıçoğlu",
"author_id": 5106317,
"author_profile": "https://Stackoverflow.com/users/5106317",
"pm_score": 0,
"selected": false,
"text": "std::wstring file_content=LR\"SOMETHING(\n€\n€\"\n€\n)SOMETHING\";\n"
},
{
"answer_id": 74384794,
"author": "Remy Lebeau",
"author_id": 65863,
"author_profile": "https://Stackoverflow.com/users/65863",
"pm_score": 2,
"selected": true,
"text": "// Working\nfile_content=L\"€\"\nL\"€\\\"\" // <--\nL\"€\";\n"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74384437",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18376025/"
] |
74,384,454 | <p>Im working on a new social media app and Im having and issue with my navigation code.</p>
<p>Once a user fills out the registration form I want them to be prompted to upload the profile picture. The issue I am having is that it shows the intended view for a half second then moves right back to the registration view.</p>
<p>I have a RegistrationView that handles the UI and and a AuthViewModel that is taking care of the server side communications. Essentially when the user finishes entering the information and hits the button. The AuthViewModel takes over and send the info to firebase then triggers a Bool to be true.</p>
<p>I then had a NagivationLink on the RegistrationView that listens for that bool and when true, changes the view on the UI. Here is the code for that.</p>
<pre><code>NavigationLink(destination: ProfilePhotoSelectorView(), isActive: $viewModel.didAuthenticateUser, label:{} )
</code></pre>
<p>XCode is spitting out that its been deprecated in iOS 16 and to move to the NavigationStack system they developed. But, with every guide I can see I cant get this to work. The only time I can get it to work is though the code above and returns this UI glitch.</p>
<p>Here is the full code for the RegistrationView</p>
<pre><code>import SwiftUI
struct RegistrationView: View {
@State private var email = ""
@State private var username = ""
@State private var fullName = ""
@State private var password = ""
@State private var isVerified = false
@Environment(\.presentationMode) var presentationMode
@EnvironmentObject var viewModel: AuthViewModel
var body: some View {
VStack{
NavigationLink(destination: ProfilePhotoSelectorView(), isActive: $viewModel.didAuthenticateUser, label:{} )
AuthHeaderView(title1: "Get Started.", title2: "Create Your Account.")
VStack(spacing: 40) {
CustomInputFields(imageName: "envelope", placeholderText: "Email", isSecureField: false, text: $email)
CustomInputFields(imageName: "person", placeholderText: "Username", isSecureField: false, text: $username)
CustomInputFields(imageName: "person", placeholderText: "Full Name", isSecureField: false, text: $fullName)
CustomInputFields(imageName: "lock", placeholderText: "Password", isSecureField: true, text: $password)
}
.padding(32)
Button {
viewModel.register(withEmail: email, password: password, fullname: fullName, username: username, isVerified: isVerified)
} label: {
Text("Sign Up")
.font(.headline)
.foregroundColor(.white)
.frame(width: 340, height: 50)
.background(Color("AppGreen"))
.clipShape(Capsule())
.padding()
}
.shadow(color: .gray.opacity(0.5), radius: 10, x:0, y:0)
Spacer()
Button {
presentationMode.wrappedValue.dismiss()
} label: {
HStack {
Text("Already Have And Account?")
.font(.caption)
Text("Sign In")
.font(.footnote)
.fontWeight(.semibold)
}
}
.padding(.bottom, 32)
.foregroundColor(Color("AppGreen"))
}
.ignoresSafeArea()
.preferredColorScheme(.dark)
}
}
struct RegistrationView_Previews: PreviewProvider {
static var previews: some View {
RegistrationView()
}
}
</code></pre>
<p>And here is the full code for the AuthViewModel</p>
<pre><code>import SwiftUI
import Firebase
class AuthViewModel: ObservableObject {
@Published var userSession: Firebase.User?
@Published var didAuthenticateUser = false
init() {
self.userSession = Auth.auth().currentUser
print("DEBUG: User session is \(String(describing: self.userSession?.uid))")
}
func login(withEmail email: String, password: String){
Auth.auth().signIn(withEmail: email, password: password) { result, error in
if let error = error {
print("DEBUG: Failed to sign in with error\(error.localizedDescription)")
return
}
guard let user = result?.user else { return }
self.userSession = user
print("Did log user in")
}
}
func register(withEmail email: String, password: String, fullname: String, username: String, isVerified: Bool){
Auth.auth().createUser(withEmail: email, password: password) { result, error in
if let error = error {
print("DEBUG: Failed to register with error\(error.localizedDescription)")
return
}
guard let user = result?.user else { return }
print("DEBUG: Registerd User Succesfully")
let data = ["email": email, "username" :username.lowercased(), "fullname": fullname, "isVerified": isVerified, "uid": user.uid]
Firestore.firestore().collection("users")
.document(user.uid)
.setData(data) { _ in
self.didAuthenticateUser = true
}
}
}
func signOut() {
userSession = nil
try? Auth.auth().signOut()
}
}
</code></pre>
<p>Here is the code for the ProfilePhotoSelectorView</p>
<pre><code>import SwiftUI
struct ProfilePhotoSelectorView: View {
var body: some View {
VStack {
AuthHeaderView(title1: "Account Creation:", title2: "Add A Profile Picture")
Button {
print("Pick Photo Here")
} label: {
VStack{
Image("PhotoIcon")
.resizable()
.renderingMode(.template)
.frame(width: 180, height: 180)
.scaledToFill()
.padding(.top, 44)
.foregroundColor(Color("AppGreen"))
Text("Tap To Add Photo")
.font(.title3).bold()
.padding(.top, 10)
.foregroundColor(Color("AppGreen"))
}
}
Spacer()
}
.ignoresSafeArea()
.preferredColorScheme(.dark)
}
}
struct ProfilePhotoSelectorView_Previews: PreviewProvider {
static var previews: some View {
ProfilePhotoSelectorView()
}
}
</code></pre>
<p>Tried all variations of the new NavigationStack and tried some other button code to see if i could trigger it from there. No Reso</p>
| [
{
"answer_id": 74385211,
"author": "workingdog support Ukraine",
"author_id": 11969817,
"author_profile": "https://Stackoverflow.com/users/11969817",
"pm_score": 0,
"selected": false,
"text": "NavigationStack"
},
{
"answer_id": 74387133,
"author": "Cheezzhead",
"author_id": 2542661,
"author_profile": "https://Stackoverflow.com/users/2542661",
"pm_score": 2,
"selected": true,
"text": "NavigationLink"
},
{
"answer_id": 74393337,
"author": "malhal",
"author_id": 259521,
"author_profile": "https://Stackoverflow.com/users/259521",
"pm_score": 0,
"selected": false,
"text": "NavigationLink"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74384454",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20441037/"
] |
74,384,455 | <pre><code>return [
'contract_code' => 'required',
'name' => 'required|string',
'abbreviation' => 'required|string',
'linecount_divisor' => 'required|integer'
];
</code></pre>
<pre><code>// into input fields => 'required'
</code></pre>
<p>How to shorten the validation rule in multiple inputs?</p>
| [
{
"answer_id": 74385211,
"author": "workingdog support Ukraine",
"author_id": 11969817,
"author_profile": "https://Stackoverflow.com/users/11969817",
"pm_score": 0,
"selected": false,
"text": "NavigationStack"
},
{
"answer_id": 74387133,
"author": "Cheezzhead",
"author_id": 2542661,
"author_profile": "https://Stackoverflow.com/users/2542661",
"pm_score": 2,
"selected": true,
"text": "NavigationLink"
},
{
"answer_id": 74393337,
"author": "malhal",
"author_id": 259521,
"author_profile": "https://Stackoverflow.com/users/259521",
"pm_score": 0,
"selected": false,
"text": "NavigationLink"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74384455",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16847167/"
] |
74,384,464 | <p>I am using CMake 3.23 and the build directory is <code>C:\Dev\MyProject\LibA\cmake-build-debug-vs</code>. <code>${CMAKE_CURRENT_BINARY_DIR}</code> provide the full path to the build directory. Is there any way to only get <code>cmake-build-debug-vs</code>?</p>
<p>Does CMake have a dedicated variable for only the name of the build directory? I tried several built-in variables and they all return the full path.</p>
| [
{
"answer_id": 74385211,
"author": "workingdog support Ukraine",
"author_id": 11969817,
"author_profile": "https://Stackoverflow.com/users/11969817",
"pm_score": 0,
"selected": false,
"text": "NavigationStack"
},
{
"answer_id": 74387133,
"author": "Cheezzhead",
"author_id": 2542661,
"author_profile": "https://Stackoverflow.com/users/2542661",
"pm_score": 2,
"selected": true,
"text": "NavigationLink"
},
{
"answer_id": 74393337,
"author": "malhal",
"author_id": 259521,
"author_profile": "https://Stackoverflow.com/users/259521",
"pm_score": 0,
"selected": false,
"text": "NavigationLink"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74384464",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1227860/"
] |
74,384,468 | <p>I am trying to find the way of making a formula that will auto generate the "id" number like we do in mySql auto-generate.</p>
<p>If I explain more, it would be like (number of A1 + 1).</p>
| [
{
"answer_id": 74384538,
"author": "hello world",
"author_id": 11209333,
"author_profile": "https://Stackoverflow.com/users/11209333",
"pm_score": 3,
"selected": true,
"text": "=SUM((INDIRECT(\"A\" & ROW() - 1)),1)\n"
},
{
"answer_id": 74386343,
"author": "player0",
"author_id": 5632629,
"author_profile": "https://Stackoverflow.com/users/5632629",
"pm_score": 0,
"selected": false,
"text": "SEQUENCE"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74384468",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15225193/"
] |
74,384,470 | <pre><code>url = "https://www.ebay.com/sch/i.html?_from=R40&_trksid=p2380057.m570.l1313&_nkw=electronics"
response = requests.get(url)
soup = BeautifulSoup(response.text, "html.parser")
names = soup.find_all("div", class_="s-item__title")
prices = soup.find_all("span", class_="s-item__price")
shippings = soup.find_all("span", class_="s-item__shipping s-item__logisticsCost"
for name,price,shipping in zip(names,prices,shippings):
print(name.text, price.text, shipping.text)
</code></pre>
<p>Right now, this script works perfectly. It prints everything that needs to be printed.
But... I want to be able to go to the next page and scrape everything off of there as well.
The class for the next page is "pagination__next icon-link"
I'm not sure how I would go about it.</p>
| [
{
"answer_id": 74384538,
"author": "hello world",
"author_id": 11209333,
"author_profile": "https://Stackoverflow.com/users/11209333",
"pm_score": 3,
"selected": true,
"text": "=SUM((INDIRECT(\"A\" & ROW() - 1)),1)\n"
},
{
"answer_id": 74386343,
"author": "player0",
"author_id": 5632629,
"author_profile": "https://Stackoverflow.com/users/5632629",
"pm_score": 0,
"selected": false,
"text": "SEQUENCE"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74384470",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.