qid int64 4 22.2M | question stringlengths 18 48.3k | answers list | date stringlengths 10 10 | metadata list |
|---|---|---|---|---|
74,386,385 | <p>When working in a class defined in a module, I'd like to access another class defined in the same module.</p>
<p>When using this code</p>
<pre class="lang-rb prettyprint-override"><code>module SomeModule
class Foo
def self.get_bar
Bar
end
end
end
module SomeModule
class Bar
end
end
# works and returns SomeModule::Bar
SomeModule::Foo.get_bar
</code></pre>
<p>Looking up <code>Bar</code> from <code>SomeModule::Foo</code> works. It is not found in local scope <code>SomeModule::Foo</code>, so it looks one level up to <code>SomeModule</code> and finds <code>SomeModule::Bar</code>.</p>
<p>But when using the shortcut notation <code>class A::B</code> to define the classes, the lookup does not work anymore:</p>
<pre class="lang-rb prettyprint-override"><code>module SomeModule
end
class SomeModule::Foo
def self.get_bar
Bar
end
end
class SomeModule::Bar
end
# does not work and raises a NameError
SomeModule::Foo.get_bar
</code></pre>
<p>It produces the error <code>NameError: uninitialized constant SomeModule::Foo::Bar</code>. But for me both codes look identical and should produce the same output. I'm obvisouly missing a key concept here.</p>
<p>Can someone explain why the lookup works in one case and not the other? And is it possible to know in advance if the lookup will work or fail by introspecting the class?</p>
| [
{
"answer_id": 74387001,
"author": "Rostislav Zhuravsky",
"author_id": 13875480,
"author_profile": "https://Stackoverflow.com/users/13875480",
"pm_score": 3,
"selected": true,
"text": "Module.nesting"
},
{
"answer_id": 74387248,
"author": "Konstantin Strukov",
"author_id": 8008340,
"author_profile": "https://Stackoverflow.com/users/8008340",
"pm_score": 1,
"selected": false,
"text": "module SomeModule\n puts Module.nesting.inspect #=> [SomeModule]\n puts Module.nesting.map(&:constants).inspect # => [[]], we didn't define Foo yet\n \n class Foo\n puts Module.nesting.inspect #=> [SomeModule::Foo, SomeModule]\n puts Module.nesting.map(&:constants).inspect #=> [[], [:Foo]], at this point SomeModule is already \"aware\" of Foo\n\n def self.get_bar\n Bar\n end\n end\nend\n\nmodule SomeModule\n puts Module.nesting.inspect #=> [SomeModule]\n puts Module.nesting.map(&:constants).inspect #=> [[:Foo]], we didn't define Bar yet\n \n class Bar\n puts Module.nesting.inspect #=> [SomeModule::Bar, SomeModule]\n puts Module.nesting.map(&:constants).inspect #=> [[], [:Foo, :Bar]]\n end\nend\n"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74386385",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/177665/"
] |
74,386,402 | <p>I am using</p>
<ul>
<li><code>coverlet.msbuild v3.2.0</code></li>
<li><code>coverlet.collector v3.2.0</code></li>
</ul>
<p>and <code>dotnet sdk v6.0.402</code></p>
<p>When I run this test command in powershell (restore and build ran before that)</p>
<pre><code>dotnet test --no-build --no-restore --collect:"XPlat Code Coverage" /p:Configuration=$Cfg /p:CollectCoverage=true /p:CoverletOutput=.\CodeCoverage\ --% /p:CoverletOutputFormat=\"cobertura,opencover\"
</code></pre>
<p>The report files</p>
<ul>
<li><code>coverage.cobertura.xml</code></li>
<li><code>coverage.opencover.xml</code></li>
</ul>
<p>are created and the powershell output is this:</p>
<pre><code>Test run for C:\Users\MyUser\repos\My.Project\Specs\bin\Release\net472\My.Project.Specs.dll (.NETFramework,Version=v4.7.2)
Microsoft (R) Test Execution Command Line Tool Version 17.3.1 (x64)
Copyright (c) Microsoft Corporation. All rights reserved.
Starting test execution, please wait...
A total of 1 test files matched the specified pattern.
Attachments:
C:\Users\MyUser\repos\My.Project\Specs\TestResults\dbe8cb53-3ec5-4227-a231-3bfedf94694f\coverage.cobertura.xml
Passed! - Failed: 0, Passed: 14, Skipped: 0, Total: 14, Duration: 910 ms - My.Project.Specs.dll (net472)
Calculating coverage result...
Generating report '.\CodeCoverage\coverage.cobertura.xml'
Generating report '.\CodeCoverage\coverage.opencover.xml'
+----------------------+--------+--------+--------+
| Module | Line | Branch | Method |
+----------------------+--------+--------+--------+
| My.Project | 20.23% | 18.53% | 20.09% |
+----------------------+--------+--------+--------+
+---------+--------+--------+--------+
| | Line | Branch | Method |
+---------+--------+--------+--------+
| Total | 20.23% | 18.53% | 20.09% |
+---------+--------+--------+--------+
| Average | 20.23% | 18.53% | 20.09% |
+---------+--------+--------+--------+
</code></pre>
<p>I have this azure-pipeline task:</p>
<pre class="lang-yaml prettyprint-override"><code>- task: DotNetCoreCLI@2
displayName: Test
inputs:
command: test
arguments: '--no-restore --no-build --collect:"XPlat Code Coverage" /p:Configuration=$(Build.Configuration) /p:CollectCoverage=true /p:CoverletOutput=$(Build.SourcesDirectory)\CodeCoverage --% /p:CoverletOutputFormat=\"cobertura,opencover\"'
publishTestResults: true
</code></pre>
<p>Which executes this command:</p>
<pre><code>C:\agent\_work\_tool\dotnet\dotnet.exe test --logger trx --results-directory C:\agent\_work\_temp --no-restore --no-build "--collect:XPlat Code Coverage" /p:Configuration=Release /p:CollectCoverage=true /p:CoverletOutput=C:\agent\_work\9\s\CodeCoverage --% "/p:CoverletOutputFormat=\cobertura,opencover\""
</code></pre>
<p>And has this output</p>
<pre><code>Test run for C:\agent\_work\9\s\My.Project.Specs\bin\Release\net472\My.Project.Specs.dll (.NETFramework,Version=v4.7.2)
Microsoft (R) Test Execution Command Line Tool Version 17.4.0 (x64)
Copyright (c) Microsoft Corporation. All rights reserved.
Starting test execution, please wait...
A total of 1 test files matched the specified pattern.
-> Loading plugin C:\agent\_work\9\s\My.Project.Specs\bin\Release\net472\LivingDoc.SpecFlowPlugin.dll
-> Loading plugin C:\agent\_work\9\s\My.Project.Specs\bin\Release\net472\TechTalk.SpecFlow.xUnit.SpecFlowPlugin.dll
-> Loading plugin C:\Windows\ServiceProfiles\NetworkService\AppData\Local\Temp\a4203b08-db42-449b-86d7-55cb48c54fc4\a4203b08-db42-449b-86d7-55cb48c54fc4\assembly\dl3\e501d05b\fee426f7_ddf4d801\My.Project.Specs.dll
-> Using specflow.json
-> LivingDocPlugin: Output generated in: C:\agent\_work\9\s\My.Project.Specs\bin\Release\net472\TestExecution.json
Results File: C:\agent\_work\_temp\BUILDMACHINE01$_BUILDMACHINE01_2022-11-10_09_25_37.trx
Passed! - Failed: 0, Passed: 14, Skipped: 0, Total: 14, Duration: 985 ms - My.Project.Specs.dll (net472)
Attachments:
C:\agent\_work\_temp\faa5dbb6-5931-43fe-880e-a37576815c1c\coverage.cobertura.xml
Result Attachments will be stored in LogStore
Run Attachments will be stored in LogStore
Info: Azure Pipelines hosted agents have been updated and now contain .Net 5.x SDK/Runtime along with the older .Net Core version which are currently lts. Unless you have locked down a SDK version for your project(s), 5.x SDK might be picked up which might have breaking behavior as compared to previous versions. You can learn more about the breaking changes here: https://docs.microsoft.com/en-us/dotnet/core/tools/ and https://docs.microsoft.com/en-us/dotnet/core/compatibility/ . To learn about more such changes and troubleshoot, refer here: https://docs.microsoft.com/en-us/azure/devops/pipelines/tasks/build/dotnet-core-cli?view=azure-devops#troubleshooting
Async Command Start: Publish test results
Publishing test results to test run '1436028'.
TestResults To Publish 12, Test run id:1436028
Test results publishing 12, remaining: 0. Test run id: 1436028
Published Test Run : https://dev.azure.com/orgteamservices/My.Project/_TestManagement/Runs?runId=1436028&_a=runCharts
Async Command End: Publish test results
Finishing: Test
</code></pre>
<p>No reports are generated on the on-prem agent machine in the expected directory.
The agent does create this though
<code>C:\agent\_work\_temp\faa5dbb6-5931-43fe-880e-a37576815c1c\coverage.cobertura.xml</code></p>
<p>Why is it not creating both reports in the expected directory?</p>
| [
{
"answer_id": 74399702,
"author": "mrt181",
"author_id": 114798,
"author_profile": "https://Stackoverflow.com/users/114798",
"pm_score": 0,
"selected": false,
"text": "coverlet.runsettings"
},
{
"answer_id": 74404585,
"author": "Thomas Heijtink",
"author_id": 976943,
"author_profile": "https://Stackoverflow.com/users/976943",
"pm_score": 4,
"selected": true,
"text": "Visual Studio Build tools 17.4.0"
},
{
"answer_id": 74577681,
"author": "Harikishore",
"author_id": 6638136,
"author_profile": "https://Stackoverflow.com/users/6638136",
"pm_score": 0,
"selected": false,
"text": "steps:\n - task: UseDotNet@2\n displayName: Install .NET Core 3.1 SDK\n inputs:\n version: '3.1.x'\n packageType: sdk\n\n - task: DotNetCoreCLI@2\n displayName: 'Run Unit Tests'\n condition: succeeded()\n inputs:\n projects: 'tests/**/*.csproj'\n arguments: '--logger trx --configuration Release /p:CollectCoverage=true /p:CoverletOutputFormat=cobertura /p:ExcludeByFile=\"**/*.cshtml\" --collect \"Code Coverage\"'\n command: test\n publishTestResults: true"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74386402",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/114798/"
] |
74,386,422 | <p>I am trying to add edited task to local storage. I don't know how to replace an element in the array with new element.</p>
<p><a href="https://i.stack.imgur.com/YhlIq.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/YhlIq.png" alt="enter image description here" /></a></p>
<p>I have tried to iterate through an array and if an element in the array is not equal to value of input(task) it will delete by the splice method and push a new element, but the problem is that push method adds an element to the end of the array.</p>
<pre class="lang-js prettyprint-override"><code>function editToLocal(todo) {
let todos;
if (localStorage.getItem("todos") === null) {
todos = [];
}
else {
todos = JSON.parse(localStorage.getItem("todos"));
}
const todoIndex = todo.indexOf(todo.value);
const todosIndex = todos.index0f(todoIndex);
todos.forEach((item) => {
if (item !== todo) {
todos.splice(todosIndex, 1);
todos.push(todo);
}
});
}
</code></pre>
| [
{
"answer_id": 74386604,
"author": "Brad",
"author_id": 6019903,
"author_profile": "https://Stackoverflow.com/users/6019903",
"pm_score": 3,
"selected": true,
"text": "let todos = ['job 1', 'job 2', 'job 3', 'job 4'];\n\nconsole.log(todos);\n\ntodos.splice(1, 1, 'job a');\n\nconsole.log(todos);"
},
{
"answer_id": 74386651,
"author": "Moises Rj",
"author_id": 13135250,
"author_profile": "https://Stackoverflow.com/users/13135250",
"pm_score": 0,
"selected": false,
"text": "let tasks = [\"task1\", \"task2\", \"task3\"];\n\nconst taskToReplaceIndex = tasks.indexOf(\"theTaskToBeReplaced\")\n\ntasks = tasks.map((task, index) => {\n if(index === taskToReplaceIndex) return \"someNewTask\"\n return task\n})"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74386422",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20466458/"
] |
74,386,488 | <p>So to start coding I have to ask for a user input. They have to place 4 cards like so</p>
<pre><code>A-S,A-H,A-C,A-D
</code></pre>
<p>Then I would create a list from their input. It should take the 2nd element then the 4th element from their input</p>
<pre><code>4cards = input()
List1 = []
List1.append(4cards[1], 4cards[3])
List1pair = ', '.join(P2)
print 'List1 cards: {0}.format(List1pair)'
</code></pre>
<p>This should or I hope it prints this (I haven't check yet)</p>
<pre><code>List1 cards: A-H,A-D
</code></pre>
<p>But my code returns with a syntax error "SyntaxError: invalid syntax"</p>
<pre><code>4cards = input()
</code></pre>
<p>How do I resolve this?</p>
| [
{
"answer_id": 74386604,
"author": "Brad",
"author_id": 6019903,
"author_profile": "https://Stackoverflow.com/users/6019903",
"pm_score": 3,
"selected": true,
"text": "let todos = ['job 1', 'job 2', 'job 3', 'job 4'];\n\nconsole.log(todos);\n\ntodos.splice(1, 1, 'job a');\n\nconsole.log(todos);"
},
{
"answer_id": 74386651,
"author": "Moises Rj",
"author_id": 13135250,
"author_profile": "https://Stackoverflow.com/users/13135250",
"pm_score": 0,
"selected": false,
"text": "let tasks = [\"task1\", \"task2\", \"task3\"];\n\nconst taskToReplaceIndex = tasks.indexOf(\"theTaskToBeReplaced\")\n\ntasks = tasks.map((task, index) => {\n if(index === taskToReplaceIndex) return \"someNewTask\"\n return task\n})"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74386488",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20143499/"
] |
74,386,524 | <p>everyone</p>
<p>I have a dataframe with 2 million unique codes for students and two other columns: initial and final year. I need to create a new dataframe with only two columns (student cod and year), with one row for each year the student remained studying. For instance, if student with code 1234567 studied from 2013 to 2015, the new dataframe must have three rows, as shown below:</p>
<pre><code>| COD | YEAR |
|-------- | ------ |
| 1234567 | 2013 |
| 1234567 | 2014 |
| 1234567 | 2015 |
</code></pre>
<p>I have the following for loop working:</p>
<pre><code>import pandas as pd
import numpy as np
# creating a df
df = pd.DataFrame({
'COD': np.random.randint(100, 1000000, size=18),
'YEAR_INCLUSION' : [2017, 2018, 2020] * 6,
'YEAR_END' : [2019, 2020, 2021] * 6,
})
newdf = pd.DataFrame(columns = ['COD', 'YEAR'])
for index, row in df.iterrows():
for i in range(row['YEAR_INCLUSION'], row['YEAR_END']+1):
newdf = pd.concat([df, pd.DataFrame.from_records([{ 'COD': row['BOLSISTA_CODIGO'], 'YEAR': i }])])
</code></pre>
<p>The problem is time. Even splitting the data into smaller df, it takes too long. With a 411,000 lines split the code takes 16~20 hours.</p>
<p>I tried the same code with itertuples, but times were significantly slower, though itertuples is known for being better then iterrows:</p>
<pre><code>newdf = pd.DataFrame(columns = ['COD', 'YEAR'])
for index, row in df.itertuples():
for i in range(row.YEAR_INCLUSION, row.YEAR_END+1):
newdf = pd.concat([df, pd.DataFrame.from_records([{ 'COD': row.BOLSISTA_CODIGO, 'YEAR': i }])])
</code></pre>
<p>I couldn't figure out a way to use <code>map</code> or <code>apply</code>, which allegedly would present much better results.</p>
<p>Thanks in advance for the help!</p>
<pre><code></code></pre>
| [
{
"answer_id": 74386604,
"author": "Brad",
"author_id": 6019903,
"author_profile": "https://Stackoverflow.com/users/6019903",
"pm_score": 3,
"selected": true,
"text": "let todos = ['job 1', 'job 2', 'job 3', 'job 4'];\n\nconsole.log(todos);\n\ntodos.splice(1, 1, 'job a');\n\nconsole.log(todos);"
},
{
"answer_id": 74386651,
"author": "Moises Rj",
"author_id": 13135250,
"author_profile": "https://Stackoverflow.com/users/13135250",
"pm_score": 0,
"selected": false,
"text": "let tasks = [\"task1\", \"task2\", \"task3\"];\n\nconst taskToReplaceIndex = tasks.indexOf(\"theTaskToBeReplaced\")\n\ntasks = tasks.map((task, index) => {\n if(index === taskToReplaceIndex) return \"someNewTask\"\n return task\n})"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74386524",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14612370/"
] |
74,386,537 | <p>I want to change the width of a component whenever I click a button from another component</p>
<p>This is the button in BiCarret:</p>
<pre><code>import { useState } from "react";
import { BiCaretLeft } from "react-icons/bi";
const SideBar = () => {
const [open, setOpen] = useState(true);
return (
<div className="relative">
<BiCaretLeft
className={`${
open ? "w-72" : "w-20"
} bg-red-400 absolute cursor-pointer -right-3 top-5 border rounded-full`}
color="#fff"
size={25}
onClick={setOpen(!true)}
/>
</div>
);
};
export default SideBar;
</code></pre>
<p>and this is the component I want to change the width on click</p>
<pre><code>import "./App.css";
import SideBar from "./components/SideBar/SideBar";
function App() {
return (
<div className="app flex">
<aside className="h-screen bg-slate-700"> // change the width here
<SideBar />
</aside>
<main className="flex-1 h-screen"></main>
</div>
);
}
export default App;
</code></pre>
| [
{
"answer_id": 74386581,
"author": "Abdulrahman Ali",
"author_id": 14876907,
"author_profile": "https://Stackoverflow.com/users/14876907",
"pm_score": -1,
"selected": false,
"text": "import { useState } from \"react\";\nimport { BiCaretLeft } from \"react-icons/bi\";\n\nconst SideBar = ({open, setOpen}) => {\n return (\n <div className=\"relative\">\n <BiCaretLeft \n className={`${\n open ? \"w-72\" : \"w-20\"\n } bg-red-400 absolute cursor-pointer -right-3 top-5 border rounded-full`}\n color=\"#fff\"\n size={25}\n onClick={setOpen(!open)}\n />\n </div>\n );\n};\n\nexport default SideBar;\n"
},
{
"answer_id": 74386613,
"author": "Lukáš Gibo Vaic",
"author_id": 4449862,
"author_profile": "https://Stackoverflow.com/users/4449862",
"pm_score": 0,
"selected": false,
"text": "document.getElementById(THE_ID).classList.add(\"new-class-for-increased-width\")"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74386537",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11249467/"
] |
74,386,538 | <p>A program that reads 3 numbers A, B and C and checks if each 3 numbers are greater than or equal to 20. Output should be single line containing a boolean. True should be printed if each number is greater than or equal to 20, Otherwise False should be printed.</p>
<p>I have tried using "and" operator and got result. Are there any other ways to solve this problem.</p>
<pre><code>A=int(input())
B=int(input())
C=int(input())
a= A>=20
b= B>=20
c= C>=20
abc= a and b and c
print(abc)
</code></pre>
| [
{
"answer_id": 74386592,
"author": "blhsing",
"author_id": 6890912,
"author_profile": "https://Stackoverflow.com/users/6890912",
"pm_score": 3,
"selected": true,
"text": "all"
},
{
"answer_id": 74386594,
"author": "0x0fba",
"author_id": 20339407,
"author_profile": "https://Stackoverflow.com/users/20339407",
"pm_score": 1,
"selected": false,
"text": "min()"
},
{
"answer_id": 74386599,
"author": "Vin",
"author_id": 7955271,
"author_profile": "https://Stackoverflow.com/users/7955271",
"pm_score": 2,
"selected": false,
"text": "abc = all(a, b, c)\n"
},
{
"answer_id": 74386656,
"author": "Talha Tayyab",
"author_id": 13086128,
"author_profile": "https://Stackoverflow.com/users/13086128",
"pm_score": 0,
"selected": false,
"text": "a = A>=20\nb = B>=20\nc = C>=20\n\nsum((a, b, c))==3\n"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74386538",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20466740/"
] |
74,386,543 | <p>In C++, how do I print the type contained in a variant at run time?</p>
<p>My use case: passing a dictionary of values from Python to C++ using <a href="https://pybind11.readthedocs.io/en/stable/advanced/cast/stl.html?highlight=variant#c-17-library-containers" rel="nofollow noreferrer">pybind11</a>, and I want to print out the types that are received.</p>
| [
{
"answer_id": 74386544,
"author": "Contango",
"author_id": 107409,
"author_profile": "https://Stackoverflow.com/users/107409",
"pm_score": -1,
"selected": false,
"text": "#include <string>\n#include <variant>\n#include <type_traits>\n\n/**\n * \\brief Variant type to string.\n * \\tparam T Variant type.\n * \\param v Variant.\n * \\return Variant type as a string.\n */\ntemplate<typename T>\nstd::string variant_type_string(T v)\n{\n std::string result;\n if constexpr(std::is_constructible_v<T, int>) { // Avoids compile error if variant does not contain this type.\n if (std::holds_alternative<int>(v)) { // Runtime check of type that variant holds.\n result = \"int\";\n }\n }\n else if constexpr(std::is_constructible_v<T, std::string>) {\n if (std::holds_alternative<std::string>(v)) {\n result = \"string\";\n }\n }\n else if constexpr(std::is_constructible_v<T, bool>) {\n if (std::holds_alternative<bool>(v)) {\n result = \"bool\";\n }\n }\n else {\n result = \"?\";\n }\n return result;\n}\n"
},
{
"answer_id": 74386766,
"author": "Daniel Langr",
"author_id": 580083,
"author_profile": "https://Stackoverflow.com/users/580083",
"pm_score": 3,
"selected": false,
"text": "std::visit"
},
{
"answer_id": 74386898,
"author": "Lasersköld",
"author_id": 3748275,
"author_profile": "https://Stackoverflow.com/users/3748275",
"pm_score": 3,
"selected": false,
"text": "#include <iostream>\n#include <variant>\n\nusing VariantT = std::variant<int, float>;\n\nnamespace {\nstd::string name(const float& ) {\n return \"float\";\n}\n\nstd::string name(const int& ) {\n return \"int\";\n}\n\nstd::string variantName(const VariantT& v) {\n return std::visit(\n [](const auto &v) { return name(v); },\n v\n );\n}\n\n}\n\nint main() {\n std::variant<int, float> v;\n\n v = 1;\n\n std::cout << variantName(v) << std::endl;\n\n v = 1.f;\n\n std::cout << variantName(v) << std::endl;\n}\n"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74386543",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/107409/"
] |
74,386,583 | <p>I have a folder (existing in the same directory as the python script) with a lot of csv files starting from 1st Jan to 31st Dec and I want to read only specific csv files within a certain date range from the folder into python and later appending the files into a list.</p>
<p>The files are named as below and there are files for each day of multiple months:</p>
<p>BANK_NIFTY_5MINs_2020-02-01.csv, BANK_NIFTY_5MINs_2020-02-02.csv, ... BANK_NIFTY_5MINs_2020-02-28.csv, BANK_NIFTY_5MINs_2020-03-01, .... BANK_NIFTY_5MINs_2020-03-31 and so on.</p>
<p>Currently, I have the code to fetch the csv files of the whole month of March by using the 'startswith' and 'endswith' syntax. However, doing this allows me to target files for only one month at a time.
I want to be able to read multiple months of csv files in within a specified date range for example Oct, Nov and Dec or Feb and March (Basically start and end at any month).</p>
<p>The following code gets only the files for March. I then fetch the files from the list and merge it into a dataframe.</p>
<pre><code>#Accessing csv files from directory
startdate = datetime.strptime("2022-05-01", "%Y-%m-%d")
enddate = datetime.strptime("2022-06-30", "%Y-%m-%d")
all_files = []
path = os.path.realpath(os.path.join(os.getcwd(),os.path.dirname('__file__')))
for root, dirs, files in os.walk(path):
for file in files:
if file.startswith("/BANK_NIFTY_5MINs_") and file.endswith(".csv"):
file_date = datetime.strptime(os.path.basename(file), "BANK_NIFTY_5MINs_%Y-%m-%d.csv")
if startdate <= file_date <= enddate:
all_files.append(os.path.join(root, file))
</code></pre>
<p>Output of the above looks :
<em>'BANK_NIFTY_5MINs_2020-03-01.csv'</em> and so on
but should be the entire path, for example:
<em>'c:\Users\User123\Desktop\Myfolder\2020\BANK\BANK_NIFTY_5MINs_2020-03-01.csv'</em>.
The merge function requires the complete path in list to be in this format to process further.</p>
| [
{
"answer_id": 74387069,
"author": "Klas Š.",
"author_id": 9288580,
"author_profile": "https://Stackoverflow.com/users/9288580",
"pm_score": 0,
"selected": false,
"text": "# replace `file.startswith(...) and file.endswith(...)`\nre.match('BANK_NIFTY_5MINs_2020-(02|03|10|11|12)-[0-9]+', file)\n### ^^^^^^^^^^^^^^ Feb, Mar, Oct-Dec\n"
},
{
"answer_id": 74387137,
"author": "Edo Akse",
"author_id": 9267296,
"author_profile": "https://Stackoverflow.com/users/9267296",
"pm_score": 2,
"selected": true,
"text": "import os\nfrom datetime import datetime\nfrom pprint import pprint\n\n\ndef quick_str_to_date(s: str) -> datetime:\n return datetime.strptime(s, \"%Y-%m-%d\")\n\n\ndef get_file_by_date_range(path: str, startdate: datetime or str, enddate: datetime or str) -> list:\n if type(startdate) == str:\n startdate = quick_str_to_date(startdate)\n if type(enddate) == str:\n enddate = quick_str_to_date(enddate)\n result = [] \n for root, dirs, files in os.walk(path):\n for filename in files:\n if filename.startswith(\"BANK_NIFTY_5MINs_\") and filename.lower().endswith(\".csv\"):\n file_date = datetime.strptime(os.path.basename(filename), \"BANK_NIFTY_5MINs_%Y-%m-%d.csv\")\n if startdate <= file_date <= enddate:\n result.append(filename)\n return result\n\n\nprint(\"all\")\npprint(get_file_by_date_range(\"/full/path/to/files\", \"2000-01-01\", \"2100-12-31\"))\n\nprint(\"\\nfebuari\")\npprint(get_file_by_date_range(\"/full/path/to/files\", \"2020-02-01\", \"2020-02-28\"))\n\nprint(\"\\none day\")\npprint(get_file_by_date_range(\"/full/path/to/files\", \"2020-02-01\", \"2020-02-01\"))\n"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74386583",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20059373/"
] |
74,386,607 | <p>the goal is to take the numbers in between 2 dashes and I was able to do that but the issue is that I need to remove the leading zero to the returned value. How can I incorporate the LTRIM function or other functions without removing all zeros?</p>
<p>Sample:</p>
<pre><code>123-010-456
</code></pre>
<p>Results should be 10</p>
<pre><code>SELECT[Phone],
REPLACE(SUBSTRING([Phone], CHARINDEX('-', [Phone]), CHARINDEX('-', [Phone])),'-','') AS substring
FROM [SalesLT].[Customer]
</code></pre>
| [
{
"answer_id": 74387069,
"author": "Klas Š.",
"author_id": 9288580,
"author_profile": "https://Stackoverflow.com/users/9288580",
"pm_score": 0,
"selected": false,
"text": "# replace `file.startswith(...) and file.endswith(...)`\nre.match('BANK_NIFTY_5MINs_2020-(02|03|10|11|12)-[0-9]+', file)\n### ^^^^^^^^^^^^^^ Feb, Mar, Oct-Dec\n"
},
{
"answer_id": 74387137,
"author": "Edo Akse",
"author_id": 9267296,
"author_profile": "https://Stackoverflow.com/users/9267296",
"pm_score": 2,
"selected": true,
"text": "import os\nfrom datetime import datetime\nfrom pprint import pprint\n\n\ndef quick_str_to_date(s: str) -> datetime:\n return datetime.strptime(s, \"%Y-%m-%d\")\n\n\ndef get_file_by_date_range(path: str, startdate: datetime or str, enddate: datetime or str) -> list:\n if type(startdate) == str:\n startdate = quick_str_to_date(startdate)\n if type(enddate) == str:\n enddate = quick_str_to_date(enddate)\n result = [] \n for root, dirs, files in os.walk(path):\n for filename in files:\n if filename.startswith(\"BANK_NIFTY_5MINs_\") and filename.lower().endswith(\".csv\"):\n file_date = datetime.strptime(os.path.basename(filename), \"BANK_NIFTY_5MINs_%Y-%m-%d.csv\")\n if startdate <= file_date <= enddate:\n result.append(filename)\n return result\n\n\nprint(\"all\")\npprint(get_file_by_date_range(\"/full/path/to/files\", \"2000-01-01\", \"2100-12-31\"))\n\nprint(\"\\nfebuari\")\npprint(get_file_by_date_range(\"/full/path/to/files\", \"2020-02-01\", \"2020-02-28\"))\n\nprint(\"\\none day\")\npprint(get_file_by_date_range(\"/full/path/to/files\", \"2020-02-01\", \"2020-02-01\"))\n"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74386607",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20465203/"
] |
74,386,629 | <p>I have a component ts file in which it is reusable by 2 HTML - one for privileged users and one for non-privileged users. Both HTMLs calls/reuse the same component ts file. However, I have 2 APIs - one for privileged and one for non-privileged. How do I integrate both APIs when the HTMLs are reusing the same component file?</p>
| [
{
"answer_id": 74387069,
"author": "Klas Š.",
"author_id": 9288580,
"author_profile": "https://Stackoverflow.com/users/9288580",
"pm_score": 0,
"selected": false,
"text": "# replace `file.startswith(...) and file.endswith(...)`\nre.match('BANK_NIFTY_5MINs_2020-(02|03|10|11|12)-[0-9]+', file)\n### ^^^^^^^^^^^^^^ Feb, Mar, Oct-Dec\n"
},
{
"answer_id": 74387137,
"author": "Edo Akse",
"author_id": 9267296,
"author_profile": "https://Stackoverflow.com/users/9267296",
"pm_score": 2,
"selected": true,
"text": "import os\nfrom datetime import datetime\nfrom pprint import pprint\n\n\ndef quick_str_to_date(s: str) -> datetime:\n return datetime.strptime(s, \"%Y-%m-%d\")\n\n\ndef get_file_by_date_range(path: str, startdate: datetime or str, enddate: datetime or str) -> list:\n if type(startdate) == str:\n startdate = quick_str_to_date(startdate)\n if type(enddate) == str:\n enddate = quick_str_to_date(enddate)\n result = [] \n for root, dirs, files in os.walk(path):\n for filename in files:\n if filename.startswith(\"BANK_NIFTY_5MINs_\") and filename.lower().endswith(\".csv\"):\n file_date = datetime.strptime(os.path.basename(filename), \"BANK_NIFTY_5MINs_%Y-%m-%d.csv\")\n if startdate <= file_date <= enddate:\n result.append(filename)\n return result\n\n\nprint(\"all\")\npprint(get_file_by_date_range(\"/full/path/to/files\", \"2000-01-01\", \"2100-12-31\"))\n\nprint(\"\\nfebuari\")\npprint(get_file_by_date_range(\"/full/path/to/files\", \"2020-02-01\", \"2020-02-28\"))\n\nprint(\"\\none day\")\npprint(get_file_by_date_range(\"/full/path/to/files\", \"2020-02-01\", \"2020-02-01\"))\n"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74386629",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
74,386,672 | <p>The naming of SAS library has 3 rules:</p>
<ol>
<li>no more than 8 character;</li>
<li>may consist with underscore, numbers and English letters;</li>
<li>start with underscore or English letters;</li>
</ol>
<p>Here comes my question: How to validate a string include invalid library name or not using perl regular expression?</p>
<p>The string is consist with words, which are separated by one space, like the following:</p>
<pre><code>sasuser work sashelp
sasuser work 7z sashelp
sasuser work dictionary
</code></pre>
<p><code>7z</code> and <code>dictionary</code> not statisfy the rules, so I want an output, with 0, 1, 1 corresponding with the three input strings.</p>
<p>I have trying this in SAS, but it doesn't work:</p>
<pre><code>data test;
input string&$42.;
x=prxmatch('/\b(?=\S+)(?![A-Za-z_][A-Za-z0-9_]{0,7})\b/',string);
put x=;
cards;
sasuser work sashelp
sasuser work 7z sashelp
sasuser work dictionary
;
run;
</code></pre>
<p>Thanks for any hint.</p>
<hr />
<p>Edit:2022-11-11<br />
I am really looking for a regex way, you may use SAS language or not. I have a thought as following:</p>
<ol>
<li>Judge if the string contains a word or not;</li>
<li>The word mismatch a regular expression;</li>
<li>The regular expression discribe the rules of SAS library naming;</li>
</ol>
<p>Is that possible?</p>
| [
{
"answer_id": 74389513,
"author": "gregor",
"author_id": 20198546,
"author_profile": "https://Stackoverflow.com/users/20198546",
"pm_score": 1,
"selected": false,
"text": "data test;\n input string&$42.;\n cards;\nsasuser work +sashelp\nsas_user _work 7z sashelp\nsasuser work77 dictionary\n;\nrun;\n"
},
{
"answer_id": 74390954,
"author": "Tom",
"author_id": 4965549,
"author_profile": "https://Stackoverflow.com/users/4965549",
"pm_score": 3,
"selected": true,
"text": "data test;\n input string $80. ;\n do index=1 to countw(string,' ');\n word = scan(string,index,' ');\n nvalid=nvalid(word,'v7') and lengthn(word) in (1:8);\n x=prxmatch('\\b[A-Za-z_][A-Za-z0-9_]{0,7}\\b/',word);\n output;\n end;\ncards;\nsasuser work sashelp\nsasuser work 7z sashelp\nsasuser work dictionary\n;\n"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74386672",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9876526/"
] |
74,386,691 | <p>i want to push an object into an empty array in useMemo method using typescript. i have code like below,</p>
<pre><code>const commonDetails = data?.CommonDetails;
const details: Details[] = [];
const selectedItems = React.useMemo(() => { // here selectedItems type is set to
// number or undefined. instead i expect it to be of type Details[] too as i push
// commonDetails which is an object into details which is array.
return commonDetails && details.push(commonDetails);
}, [commonDetails]);
console.log('selectedItems', selectedItems); //this outputs 1. but i expect an array
// of object
</code></pre>
<p>could someone help me with this. i am not sure why the selectedItems is number instead of array of object. thanks</p>
| [
{
"answer_id": 74386761,
"author": "Tushar Shahi",
"author_id": 10140124,
"author_profile": "https://Stackoverflow.com/users/10140124",
"pm_score": 0,
"selected": false,
"text": ".push()"
},
{
"answer_id": 74386765,
"author": "Bikas Lin",
"author_id": 17582798,
"author_profile": "https://Stackoverflow.com/users/17582798",
"pm_score": 2,
"selected": true,
"text": "Array.push()"
},
{
"answer_id": 74386772,
"author": "Azzy",
"author_id": 2122822,
"author_profile": "https://Stackoverflow.com/users/2122822",
"pm_score": 0,
"selected": false,
"text": "const details: Details[] = [];\n\nconst selectedItems = React.useMemo(() => { \n return commonDetails ? [ ...details, commonDetails] : [];\n}, [commonDetails, details]); // this will most likey need the dependencies\n"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74386691",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
74,386,694 | <p>I have the following dataframe:</p>
<pre><code># initialize list of lists
data = [['1', "Tag1, Tag323, Tag36"], ['2', "Tag11, Tag212"], ['4', "Tag1, Tag12, Tag3, Tag324"]]
# Create the pandas DataFrame
df = pd.DataFrame(data, columns = ['ID', 'Tag'])
</code></pre>
<pre><code>print(df)
ID Tag
1 Tag1, Tag323, Tag36
2 Tag11, Tag212
4 Tag1, Tag12, Tag3, Tag324
</code></pre>
<p>I would like to manipulate the string values (e.g. <code>"Tag1, Tag2, Tag3"</code>) in column <code>tag</code> with the follwing condition. In each row, if there are more than 2 tags, the output should look like <code>"Tag1, Tag2 .."</code>. The tag length can be different.</p>
<pre><code>print(df)
ID Tag
1 Tag1, Tag323 ..
2 Tag11, Tag212
4 Tag1, Tag12 ..
</code></pre>
<p>Does anyone know a Pandas apply and lambda method to solve this?</p>
| [
{
"answer_id": 74386761,
"author": "Tushar Shahi",
"author_id": 10140124,
"author_profile": "https://Stackoverflow.com/users/10140124",
"pm_score": 0,
"selected": false,
"text": ".push()"
},
{
"answer_id": 74386765,
"author": "Bikas Lin",
"author_id": 17582798,
"author_profile": "https://Stackoverflow.com/users/17582798",
"pm_score": 2,
"selected": true,
"text": "Array.push()"
},
{
"answer_id": 74386772,
"author": "Azzy",
"author_id": 2122822,
"author_profile": "https://Stackoverflow.com/users/2122822",
"pm_score": 0,
"selected": false,
"text": "const details: Details[] = [];\n\nconst selectedItems = React.useMemo(() => { \n return commonDetails ? [ ...details, commonDetails] : [];\n}, [commonDetails, details]); // this will most likey need the dependencies\n"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74386694",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11934963/"
] |
74,386,717 | <p>How to set minimum decimal digits but not maximum decimal digits. I tried with <code>number_format</code> but the results were unexpected.</p>
<pre class="lang-php prettyprint-override"><code><?php
echo number_format("1000000", 2) . "<br>";
echo number_format("1000000.6", 2) . "<br>";
echo number_format("1000000.63", 2) . "<br>";
echo number_format("1000000.68464", 2) . "<br>";
?>
</code></pre>
<p>Result:</p>
<pre><code>1,000,000.00
1,000,000.60
1,000,000.63
1,000,000.68
</code></pre>
<p>Expected Result:</p>
<pre><code>1,000,000.00
1,000,000.60
1,000,000.63
1,000,000.68464
</code></pre>
<p>How do I do this?</p>
| [
{
"answer_id": 74386998,
"author": "Chris Haas",
"author_id": 231316,
"author_profile": "https://Stackoverflow.com/users/231316",
"pm_score": 2,
"selected": true,
"text": "NumberFormatter"
},
{
"answer_id": 74387189,
"author": "khanh-ln",
"author_id": 9198687,
"author_profile": "https://Stackoverflow.com/users/9198687",
"pm_score": 0,
"selected": false,
"text": "function number_format_min_precision($v, $minPrecision) {\n $curentPrecision = strlen(explode('.', $v)[1] ?? 0);\n if ($curentPrecision < $minPrecision) return number_format($v, $minPrecision);\n return $v;\n}\necho number_format_min_precision('1000000', 2) . PHP_EOL;\necho number_format_min_precision('1000000.6', 2) . PHP_EOL;\necho number_format_min_precision('1000000.63', 2) . PHP_EOL;\necho number_format_min_precision('1000000.68464', 2) . PHP_EOL;\n"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74386717",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3774282/"
] |
74,386,720 | <p>I am trying to add files using file picker in .net MAUI I am getting error while adding files.
I am getting error on that await line. I tried to add oncreate method in maiacticity.cs file but it is showing same exception.
This is my Model:</p>
<pre><code>public class Data
{
public string fileName { get; set; }
public string FileName
{
get { return fileName; }
set { fileName = value; }
}
}
public partial class Item
{
ObservableCollection<Data> result = new ObservableCollection<Data>();
[RelayCommand]
public async void Add_File()
{
var CustomFileType = new FilePickerFileType(new Dictionary<DevicePlatform, IEnumerable<String>>
{
{
DevicePlatform.WinUI, new[] {"pdf"}
},
});
var results = await FilePicker.PickMultipleAsync(new PickOptions
{
FileTypes = CustomFileType,
});
foreach (var fileResult in results)
{
FileInfo fileInfo = new FileInfo(fileResult.FullPath);
bool fileExist = false;
foreach(Data data in result)
{
fileExist = true;
break;
}
if(!fileExist)
{
result.Add(new Data
{
fileName = fileResult.FullPath,
});
}
else
{
result = result;
}
}
Datas=result;
}
public ObservableCollection<Data> Datas { get; private set; }
public Item()
{
Add_File();
}
}
</code></pre>
<p>}
this is viewmodel:</p>
<pre><code> public Item Items;
public event PropertyChangedEventHandler PropertyChanged;
public ObservableCollection<Data> data { get => Items.Datas; }
public ParentViewModel()
{
Items = new Item();
}
protected void OnPropertyChanged(string name)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(name));
}
this is where I am trying to bind that data
<VerticalStackLayout>
<Label
Text="Hello from child view"
VerticalOptions="Center"
HorizontalOptions="Center" />
<CollectionView ItemsSource="{Binding Datas}">
<CollectionView.ItemTemplate>
<DataTemplate>
<Grid>
<Label Text="{Binding fileName}"/>
</Grid>
</DataTemplate>
</CollectionView.ItemTemplate>
</CollectionView>
</VerticalStackLayout>
</code></pre>
<p>I have main view where I have binded this child view. I have addfile button in my main view. If I am doing same code in code behind it is working fine. Even I have created same code in viewModel it is not showing any exception. I am not getting exact cause of this.</p>
| [
{
"answer_id": 74386998,
"author": "Chris Haas",
"author_id": 231316,
"author_profile": "https://Stackoverflow.com/users/231316",
"pm_score": 2,
"selected": true,
"text": "NumberFormatter"
},
{
"answer_id": 74387189,
"author": "khanh-ln",
"author_id": 9198687,
"author_profile": "https://Stackoverflow.com/users/9198687",
"pm_score": 0,
"selected": false,
"text": "function number_format_min_precision($v, $minPrecision) {\n $curentPrecision = strlen(explode('.', $v)[1] ?? 0);\n if ($curentPrecision < $minPrecision) return number_format($v, $minPrecision);\n return $v;\n}\necho number_format_min_precision('1000000', 2) . PHP_EOL;\necho number_format_min_precision('1000000.6', 2) . PHP_EOL;\necho number_format_min_precision('1000000.63', 2) . PHP_EOL;\necho number_format_min_precision('1000000.68464', 2) . PHP_EOL;\n"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74386720",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19836184/"
] |
74,386,752 | <p>I am learning prolog.</p>
<p>It seems to me that prolog's rules (relations and simple facts) are "positive" - they say what is or can be true.</p>
<p>Adding new such rules to a prolog program only adds "positive" knowledge. It can't add "negative" facts to say something isn't true.</p>
<p><strong>Question</strong></p>
<ol>
<li><p>Is this called <strong>monotonic</strong> logic?</p>
</li>
<li><p>The procedural (not logical) construct called "negation by failure" is the hack needed to add "negative" facts to break the otherwise monotonicity of purely logical prolog eg exceptions to rules.</p>
</li>
</ol>
<p>Am I correct?</p>
<hr />
<p><strong>Update</strong></p>
<p>A comment asked for an example.</p>
<pre><code>likes(mary, X) :- reptile(X), !, fail.
likes(mary, X) :- animal(X).
</code></pre>
<p>Without the procedural cut, there is no way in purely logical prolog to define that Mary likes animals except reptiles. (Is this correct?)</p>
| [
{
"answer_id": 74386998,
"author": "Chris Haas",
"author_id": 231316,
"author_profile": "https://Stackoverflow.com/users/231316",
"pm_score": 2,
"selected": true,
"text": "NumberFormatter"
},
{
"answer_id": 74387189,
"author": "khanh-ln",
"author_id": 9198687,
"author_profile": "https://Stackoverflow.com/users/9198687",
"pm_score": 0,
"selected": false,
"text": "function number_format_min_precision($v, $minPrecision) {\n $curentPrecision = strlen(explode('.', $v)[1] ?? 0);\n if ($curentPrecision < $minPrecision) return number_format($v, $minPrecision);\n return $v;\n}\necho number_format_min_precision('1000000', 2) . PHP_EOL;\necho number_format_min_precision('1000000.6', 2) . PHP_EOL;\necho number_format_min_precision('1000000.63', 2) . PHP_EOL;\necho number_format_min_precision('1000000.68464', 2) . PHP_EOL;\n"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74386752",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19713913/"
] |
74,386,764 | <p>I have a column of Hexadecimal strings with many TRAILING zeros.
The problem i have is that the trailing Zeros from the string, needs to be removed</p>
<p>I have searched for a VBA formula such as Trim but my solution has not worked.</p>
<p>Is there a VBA formula I can use to remove all these Trailing zeros from each of the strings.
An example of the HEX string is 4153523132633403277E7F0000000000000000000000000000. I would like to have it in a format of 4153523132633403277E7F</p>
<p>The big issue is that the Hexadecimal strings can be of various lengths.</p>
| [
{
"answer_id": 74386955,
"author": "virolino",
"author_id": 10988580,
"author_profile": "https://Stackoverflow.com/users/10988580",
"pm_score": 1,
"selected": false,
"text": "while last character is \"0\"\n remove last character\nend while\n"
},
{
"answer_id": 74386974,
"author": "JvdV",
"author_id": 9758194,
"author_profile": "https://Stackoverflow.com/users/9758194",
"pm_score": 3,
"selected": true,
"text": "B1"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74386764",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6126937/"
] |
74,386,787 | <p>Im getting an error when trying to Debug/Deploy my App (that works on UWP) to Android.
I have tried to run the App on the emulator in VS (Android 9) and my smartphone (Android12).</p>
<p>The error i am getting is "Default constructor not found on type [MyApp].Views.AboutPage".</p>
<p>The AboutPage class:</p>
<pre><code>public partial class AboutPage : ContentPage
{
public AboutPage()
{
InitializeComponent();
BindingContext = new AboutViewModel();
}
}
</code></pre>
<p>As in this class, I do not have any non default constructors in my entire Application.</p>
<p>I have already tried to set the linker setting to "Sdk Assemblies only", which resulted in a different error.
When trying to debug a Microsoft-Default project on my smartphone it worked with the same settings as in my app. The contents of the AboutPage class do not differ between these two projects.</p>
| [
{
"answer_id": 74386955,
"author": "virolino",
"author_id": 10988580,
"author_profile": "https://Stackoverflow.com/users/10988580",
"pm_score": 1,
"selected": false,
"text": "while last character is \"0\"\n remove last character\nend while\n"
},
{
"answer_id": 74386974,
"author": "JvdV",
"author_id": 9758194,
"author_profile": "https://Stackoverflow.com/users/9758194",
"pm_score": 3,
"selected": true,
"text": "B1"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74386787",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20466835/"
] |
74,386,809 | <p>For examle, I want to update the following materialized view everyday at 23:30.
What should I write after the START WITH and NEXT clause ?</p>
<pre><code>CREATE MATERIALIZED VIEW test_example REFRESH COMPLETE
START WITH
NEXT
AS
</code></pre>
| [
{
"answer_id": 74386917,
"author": "Littlefoot",
"author_id": 9097906,
"author_profile": "https://Stackoverflow.com/users/9097906",
"pm_score": 1,
"selected": false,
"text": "create materialized view test_example\nrefresh complete\nstart with sysdate \nnext trunc(sysdate) + 23/24 + 30/(24*60)\nas select ...\n"
},
{
"answer_id": 74592826,
"author": "tlauss",
"author_id": 20563077,
"author_profile": "https://Stackoverflow.com/users/20563077",
"pm_score": 0,
"selected": false,
"text": "create materialized view test_example\nrefresh complete\nstart with trunc(sysdate) + 23.5/24\nnext trunc(sysdate) + 23.5/24 + 1\nas select ...\n"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74386809",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20197912/"
] |
74,386,838 | <p>I am writing an application and I was wondering if I can make property "Name" unique - for example there cannot be more than one location with the same name</p>
<p>Code snippet:</p>
<pre><code>public class City: MyClass1
{
[MaxLength(255)]
public required string Name { get; set; }
}
</code></pre>
<p>And I want to have property Name as unique (there cannot be more than one city with the same name)</p>
<p>How do I do that?</p>
| [
{
"answer_id": 74387017,
"author": "Max Play",
"author_id": 5593150,
"author_profile": "https://Stackoverflow.com/users/5593150",
"pm_score": 3,
"selected": true,
"text": "public class City: MyClass1\n{\n private static HashSet<string> names;\n private string name;\n\n [MaxLength(255)]\n public required string Name { get => name; set => TrySetName(value); }\n\n void TrySetName(string newName)\n {\n if (!names.Contains(newName))\n {\n names.Add(newName);\n names.Remove(name);\n name = newName;\n }\n else\n {\n // Handle the failure of setting the name somehow\n }\n }\n}\n"
},
{
"answer_id": 74387361,
"author": "Code Name Jack",
"author_id": 3613702,
"author_profile": "https://Stackoverflow.com/users/3613702",
"pm_score": -1,
"selected": false,
"text": "public class Cities : IEnumerable<City>\n{\n private readonly HashSet<City> _cities = new HashSet<City>();\n public void Add(City city)\n {\n _cities.Add(city);\n }\n\n public IEnumerator<City> GetEnumerator()\n {\n return _cities.GetEnumerator();\n }\n IEnumerator IEnumerable.GetEnumerator()\n {\n return GetEnumerator();\n }\n}\n"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74386838",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19799746/"
] |
74,386,866 | <p>Try to create a Windows .bat file to achieve the below function:</p>
<pre><code>cd C:\repo\demo
venv\Scripts\activate
python test.py
</code></pre>
<p>In Visual Studio Code terminal window, I can run the above lines without issue.</p>
<p>Created a .bat file as below:</p>
<pre><code>cd C:\repo\demo
"C:\Users\jw\AppData\Local\Programs\Python\Python310\python.exe" "venv\Scripts\activate"
"C:\Users\jw\AppData\Local\Programs\Python\Python310\python.exe" "python test.py"
pause
</code></pre>
<p>When double click the above .bat file to run it, end with error:</p>
<blockquote>
<p>if [ "${BASH_SOURCE-}" = "$0" ]; then</p>
<p>SyntaxError: cannot assign to literal here. Maybe you meant '==' instead of '='?</p>
</blockquote>
<p>Also tried the below .bat code, not working either:</p>
<pre><code>cd C:\repo\demo
venv\Scripts\activate
python test.py
pause
</code></pre>
<p>How to correct the .bat file to make it work?</p>
<p>======================================</p>
<p>Based on @Compo's comment, tried the below version and it successfully executed <code>python test.py</code>:</p>
<pre><code>cd C:\repo\demo
call "venv\Scripts\activate.bat"
python test.py
pause
</code></pre>
<p>but seems it didn't finish <code>call "venv\Scripts\activate.bat"</code>, the command line window shows as below:</p>
<p><a href="https://i.stack.imgur.com/xmY1F.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/xmY1F.png" alt="enter image description here" /></a></p>
<p>When manually run the code, it will prefix the path with (venv) as below which shows the proper result:</p>
<p><a href="https://i.stack.imgur.com/bDqpv.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/bDqpv.png" alt="enter image description here" /></a></p>
<p>============================================</p>
<p>UPDATE:</p>
<p>The below .bat version works now, an answer from <a href="https://stackoverflow.com/questions/47425520">this question</a></p>
<pre><code>cd C:\repo\demo && call "venv\Scripts\activate.bat" && python test.py && pause
</code></pre>
| [
{
"answer_id": 74387017,
"author": "Max Play",
"author_id": 5593150,
"author_profile": "https://Stackoverflow.com/users/5593150",
"pm_score": 3,
"selected": true,
"text": "public class City: MyClass1\n{\n private static HashSet<string> names;\n private string name;\n\n [MaxLength(255)]\n public required string Name { get => name; set => TrySetName(value); }\n\n void TrySetName(string newName)\n {\n if (!names.Contains(newName))\n {\n names.Add(newName);\n names.Remove(name);\n name = newName;\n }\n else\n {\n // Handle the failure of setting the name somehow\n }\n }\n}\n"
},
{
"answer_id": 74387361,
"author": "Code Name Jack",
"author_id": 3613702,
"author_profile": "https://Stackoverflow.com/users/3613702",
"pm_score": -1,
"selected": false,
"text": "public class Cities : IEnumerable<City>\n{\n private readonly HashSet<City> _cities = new HashSet<City>();\n public void Add(City city)\n {\n _cities.Add(city);\n }\n\n public IEnumerator<City> GetEnumerator()\n {\n return _cities.GetEnumerator();\n }\n IEnumerator IEnumerable.GetEnumerator()\n {\n return GetEnumerator();\n }\n}\n"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74386866",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6179813/"
] |
74,386,885 | <p>I want to get latest record for each group in a table of rows. ex, i want <strong>column c</strong> like getting latest record by count</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Column A</th>
<th>Column B</th>
<th>Column C</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>09-11-2022 15:46:33</td>
<td>2</td>
</tr>
<tr>
<td>1</td>
<td>09-11-2022 21:16:33</td>
<td>4</td>
</tr>
<tr>
<td>1</td>
<td>09-11-2022 15:09:40</td>
<td>1</td>
</tr>
<tr>
<td>1</td>
<td>09-11-2022 20:39:40</td>
<td>3</td>
</tr>
<tr>
<td>2</td>
<td>09-11-2022 15:46:33</td>
<td>1</td>
</tr>
<tr>
<td>2</td>
<td>09-11-2022 21:16:33</td>
<td>2</td>
</tr>
</tbody>
</table>
</div>
<p>OR</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Column A</th>
<th>Column B</th>
<th>Column C</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>09-11-2022 15:46:33</td>
<td></td>
</tr>
<tr>
<td>1</td>
<td>09-11-2022 21:16:33</td>
<td>True</td>
</tr>
<tr>
<td>1</td>
<td>09-11-2022 15:09:40</td>
<td></td>
</tr>
<tr>
<td>1</td>
<td>09-11-2022 20:39:40</td>
<td></td>
</tr>
<tr>
<td>2</td>
<td>09-11-2022 15:46:33</td>
<td></td>
</tr>
<tr>
<td>2</td>
<td>09-11-2022 21:16:33</td>
<td>True</td>
</tr>
</tbody>
</table>
</div>
<p>I want to get flag for latest record in Column C. above mentioned result set i want any of it</p>
<p>thanks in advance</p>
<p>I have tried like this</p>
<pre><code>LastById =
Var modifiedon = 'Table' Column C
Return
COUNTROWS(
FILTER(
ALL( 'Table' ),
'Table' Column C < modifiedon
)
)
</code></pre>
| [
{
"answer_id": 74387017,
"author": "Max Play",
"author_id": 5593150,
"author_profile": "https://Stackoverflow.com/users/5593150",
"pm_score": 3,
"selected": true,
"text": "public class City: MyClass1\n{\n private static HashSet<string> names;\n private string name;\n\n [MaxLength(255)]\n public required string Name { get => name; set => TrySetName(value); }\n\n void TrySetName(string newName)\n {\n if (!names.Contains(newName))\n {\n names.Add(newName);\n names.Remove(name);\n name = newName;\n }\n else\n {\n // Handle the failure of setting the name somehow\n }\n }\n}\n"
},
{
"answer_id": 74387361,
"author": "Code Name Jack",
"author_id": 3613702,
"author_profile": "https://Stackoverflow.com/users/3613702",
"pm_score": -1,
"selected": false,
"text": "public class Cities : IEnumerable<City>\n{\n private readonly HashSet<City> _cities = new HashSet<City>();\n public void Add(City city)\n {\n _cities.Add(city);\n }\n\n public IEnumerator<City> GetEnumerator()\n {\n return _cities.GetEnumerator();\n }\n IEnumerator IEnumerable.GetEnumerator()\n {\n return GetEnumerator();\n }\n}\n"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74386885",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20260385/"
] |
74,386,901 | <p>In my project with PHP Inside the JSON is the data I keep. And each of these data has sequence numbers
1.1,
1.1.1,
1.1.2,
1.1.3,
...,
1.1.10.</p>
<p>When I sorted, I noticed that 1.1.10 came after 1.1.1, whereas 1.1.9 wasn't there yet.</p>
<p>Because it sorts alphabetically.
And I don't know how to deal with it!</p>
<p>Edit: Added sample JSON data.</p>
<pre><code>{
"2": {
"sirano": "1",
"personal": "4",
"tarihler": {
"baslangic": "2022-11-10",
"bitis": "2022-11-17"
},
"ilerleme": "0"
},
"124": {
"sirano": "1.1.1",
"personal": "4",
"tarihler": {
"baslangic": "2022-11-10",
"bitis": "2022-11-17"
},
"ilerleme": "0"
},
"125": {
"sirano": "1.1.2",
"personal": "4",
"tarihler": {
"baslangic": "2022-11-10",
"bitis": "2022-11-17"
},
"ilerleme": "0"
},
"126": {
"sirano": "1.1.3",
"personal": "4",
"tarihler": {
"baslangic": "2022-11-10",
"bitis": "2022-11-17"
},
"ilerleme": "0"
},
"127": {
"sirano": "1.1.4",
"personal": "4",
"tarihler": {
"baslangic": "2022-11-10",
"bitis": "2022-11-17"
},
"ilerleme": "0"
},
"128": {
"sirano": "1.1.5",
"personal": "4",
"tarihler": {
"baslangic": "2022-11-10",
"bitis": "2022-11-17"
},
"ilerleme": "0"
},
"129": {
"sirano": "1.1.6",
"personal": "4",
"tarihler": {
"baslangic": "2022-11-10",
"bitis": "2022-11-17"
},
"ilerleme": "0"
},
"130": {
"sirano": "1.1.7",
"personal": "4",
"tarihler": {
"baslangic": "2022-11-10",
"bitis": "2022-11-17"
},
"ilerleme": "0"
},
"131": {
"sirano": "1.1.8",
"personal": "4",
"tarihler": {
"baslangic": "2022-11-10",
"bitis": "2022-11-17"
},
"ilerleme": "0"
},
"132": {
"sirano": "1.1.9",
"personal": "4",
"tarihler": {
"baslangic": "2022-11-10",
"bitis": "2022-11-17"
},
"ilerleme": "0"
},
"133": {
"sirano": "1.1.10",
"personal": "4",
"tarihler": {
"baslangic": "2022-11-10",
"bitis": "2022-11-17"
},
"ilerleme": "0"
},
"134": {
"sirano": "1.2",
"personal": "4",
"tarihler": {
"baslangic": "2022-11-10",
"bitis": "2022-11-17"
},
"ilerleme": "0"
},
"135": {
"sirano": "1.3.1",
"personal": "4",
"tarihler": {
"baslangic": "2022-11-10",
"bitis": "2022-11-17"
},
"ilerleme": "0"
},
"136": {
"sirano": "1.3.2",
"personal": "4",
"tarihler": {
"baslangic": "2022-11-10",
"bitis": "2022-11-17"
},
"ilerleme": "0"
},
"137": {
"sirano": "1.4.1",
"personal": "4",
"tarihler": {
"baslangic": "2022-11-10",
"bitis": "2022-11-17"
},
"ilerleme": "0"
}
}
</code></pre>
<p><a href="https://i.stack.imgur.com/ghRsd.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ghRsd.png" alt="The ordering looks like this:" /></a></p>
<pre><code>$data = json_decode($proje->JSONData, true);
function order($a, $b)
{
return $a['sirano'] - $b['sirano'];
}
uasort($data, 'order');
</code></pre>
<p>I tried like this, but the result is clear!
Please help me, I'm going crazy!</p>
| [
{
"answer_id": 74387017,
"author": "Max Play",
"author_id": 5593150,
"author_profile": "https://Stackoverflow.com/users/5593150",
"pm_score": 3,
"selected": true,
"text": "public class City: MyClass1\n{\n private static HashSet<string> names;\n private string name;\n\n [MaxLength(255)]\n public required string Name { get => name; set => TrySetName(value); }\n\n void TrySetName(string newName)\n {\n if (!names.Contains(newName))\n {\n names.Add(newName);\n names.Remove(name);\n name = newName;\n }\n else\n {\n // Handle the failure of setting the name somehow\n }\n }\n}\n"
},
{
"answer_id": 74387361,
"author": "Code Name Jack",
"author_id": 3613702,
"author_profile": "https://Stackoverflow.com/users/3613702",
"pm_score": -1,
"selected": false,
"text": "public class Cities : IEnumerable<City>\n{\n private readonly HashSet<City> _cities = new HashSet<City>();\n public void Add(City city)\n {\n _cities.Add(city);\n }\n\n public IEnumerator<City> GetEnumerator()\n {\n return _cities.GetEnumerator();\n }\n IEnumerator IEnumerable.GetEnumerator()\n {\n return GetEnumerator();\n }\n}\n"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74386901",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17701615/"
] |
74,386,948 | <p>How can I recreate GitHub's repositories language list using CSS only? Something like this, for example:</p>
<p><a href="https://i.stack.imgur.com/Kd4iC.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Kd4iC.png" alt="enter image description here" /></a></p>
<p>I started with a list of <code>div</code>s but I cannot figure out how to draw the dots using CSS...</p>
<pre><code><div>
<div>C 90%</div>
<div>Assembly 5.8%</div>
<div>Makefile 2.9%</div>
<div>C++ 0.5%</div>
</div>
</code></pre>
| [
{
"answer_id": 74387141,
"author": "Armin Ayari",
"author_id": 8863489,
"author_profile": "https://Stackoverflow.com/users/8863489",
"pm_score": 1,
"selected": false,
"text": "::before"
},
{
"answer_id": 74387886,
"author": "beep",
"author_id": 9931829,
"author_profile": "https://Stackoverflow.com/users/9931829",
"pm_score": 0,
"selected": false,
"text": "<div class=\"rows\">\n <div class=\"dot\" style=\"color: #555555;\"></div>\n <div class=\"child\">C 90%</div>\n</div>\n<div class=\"rows\">\n <div class=\"dot\" style=\"color: #6E4C13;\"></div>\n <div class=\"child\">Assembly 5.8%</div>\n</div>\n<div class=\"rows\">\n <div class=\"dot\" style=\"color: #427819;\"></div>\n <div class=\"child\">Makefile 2.9%</div>\n</div>\n"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74386948",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9931829/"
] |
74,386,951 | <p>I am trying to generate APK but i run into an Obstacle, I am getting this As error :</p>
<pre><code>> Task :react-native-gesture-handler:generateReleaseRFile FAILED
FAILURE: Build completed with 2 failures.
1: Task failed with an exception.
-----------
* What went wrong:
Execution failed for task ':react-native-gesture-handler:generateReleaseRFile'.
> Could not resolve all files for configuration ':react-native-gesture-handler:releaseCompileClasspath'.
> Failed to transform react-native-0.71.0-rc.0-release.aar (com.facebook.react:react-native:0.71.0-rc.0) to match attributes {artifactType=android-symbol-with-package-name, com.android.build.api.attributes.BuildTypeAttr=release, org.gradle.category=library, org.gradle.dependency.bundling=external, org.gradle.libraryelements=aar, org.gradle.status=release, org.gradle.usage=java-api}.
> Could not find react-native-0.71.0-rc.0-release.aar (com.facebook.react:react-native:0.71.0-rc.0).
Searched in the following locations:
https://repo.maven.apache.org/maven2/com/facebook/react/react-native/0.71.0-rc.0/react-native-0.71.0-rc.0-release.aar
* Try:
> Run with --stacktrace option to get the stack trace.
> Run with --info or --debug option to get more log output.
> Run with --scan to get full insights.
==============================================================================
2: Task failed with an exception.
-----------
* What went wrong:
java.lang.StackOverflowError (no error message)
* Try:
> Run with --stacktrace option to get the stack trace.
> Run with --info or --debug option to get more log output.
> Run with --scan to get full insights.
==============================================================================
* Get more help at https://help.gradle.org
Deprecated Gradle features were used in this build, making it incompatible with Gradle 8.0.
You can use '--warning-mode all' to show the individual deprecation warnings and determine if they come from your own scripts or plugins.
See https://docs.gradle.org/7.5.1/userguide/command_line_interface.html#sec:command_line_warnings
Execution optimizations have been disabled for 1 invalid unit(s) of work during this build to ensure correctness.
Please consult deprecation warnings for more details.
BUILD FAILED in 2m 8s
62 actionable tasks: 4 executed, 58 up-to-date
</code></pre>
<p>What would I not be doing rightly?</p>
<p>Other errors include</p>
<pre><code>info Writing bundle output to:, D:\react-native\******\android\app\build\generated\assets\react\release\index.android.bundle
info Writing sourcemap output to:, D:\react-native\******\android\app\build\intermediates\sourcemaps\react\release\index.android.bundle.packager.map
info Done writing bundle output
info Done writing sourcemap output
info Copying 13 asset files
info Done copying assets
D:\react-native\******\android\app\build\generated\assets\react\release\index.android.bundle:1769:18: warning: the variable "DebuggerInternal" was not declared in function "__shouldPauseOnThrow"
typeof DebuggerInternal !== 'undefined' && DebuggerInternal.shouldPauseOnThrow === true
^~~~~~~~~~~~~~~~
D:\react-native\******\android\app\build\generated\assets\react\release\index.android.bundle:4994:7: warning: the variable "setTimeout" was not declared in function "logCapturedError"
setTimeout(function () {
^~~~~~~~~~
D:\react-native\******\android\app\build\generated\assets\react\release\index.android.bundle:3592:21: warning: the variable "clearTimeout" was not declared in anonymous function " 90#"
cancelTimeout = clearTimeout;
^~~~~~~~~~~~
D:\react-native\******\android\app\build\generated\assets\react\release\index.android.bundle:7492:30: warning: the variable "__REACT_DEVTOOLS_GLOBAL_HOOK__" was not declared in anonymous function " 90#"
if ("undefined" !== typeof __REACT_DEVTOOLS_GLOBAL_HOOK__) {
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
D:\react-native\******\android\app\build\generated\assets\react\release\index.android.bundle:7507:146: warning: the variable "nativeFabricUIManager" was not declared in anonymous function " 119#"
null != handle._nativeTag && (null != handle._internalInstanceHandle ? (handle = handle._internalInstanceHandle.stateNode, null != handle && nativeFabricUIManager.dispatchCommand(handle.node, command, args)) : _$$_REQUIRE(_dependencyMap[2]).UIManager.dispatchViewManagerCommand(handle._nativeTag, command, args));
^~~~~~~~~~~~~~~~~~~~~
D:\react-native\******\android\app\build\generated\assets\react\release\index.android.bundle:8324:5: warning: the variable "setImmediate" was not declared in function "handleResolved"
setImmediate(function () {
^~~~~~~~~~~~
D:\react-native\******\android\app\build\generated\assets\react\release\index.android.bundle:8540:16: warning: the variable "AggregateError" was not declared in function "getAggregateError"
if (typeof AggregateError === 'function') {
^~~~~~~~~~~~~~
D:\react-native\******\android\app\build\generated\assets\react\release\index.android.bundle:11456:12: warning: the variable "fetch" was not declared in anonymous function " 294#"
fetch: fetch,
^~~~~
D:\react-native\******\android\app\build\generated\assets\react\release\index.android.bundle:11457:14: warning: the variable "Headers" was not declared in anonymous function " 294#"
Headers: Headers,
^~~~~~~
D:\react-native\******\android\app\build\generated\assets\react\release\index.android.bundle:11458:14: warning: the variable "Request" was not declared in anonymous function " 294#"
Request: Request,
^~~~~~~
D:\react-native\******\android\app\build\generated\assets\react\release\index.android.bundle:11459:15: warning: the variable "Response" was not declared in anonymous function " 294#"
Response: Response
^~~~~~~~
D:\react-native\******\android\app\build\generated\assets\react\release\index.android.bundle:11608:24: warning: the variable "FileReader" was not declared in function "readBlobAsArrayBuffer"
var reader = new FileReader();
^~~~~~~~~~
D:\react-native\******\android\app\build\generated\assets\react\release\index.android.bundle:11645:36: warning: the variable "Blob" was not declared in anonymous function " 305#"
} else if (support.blob && Blob.prototype.isPrototypeOf(body)) {
^~~~
D:\react-native\******\android\app\build\generated\assets\react\release\index.android.bundle:11647:40: warning: the variable "FormData" was not declared in anonymous function " 305#"
} else if (support.formData && FormData.prototype.isPrototypeOf(body)) {
^~~~~~~~
D:\react-native\******\android\app\build\generated\assets\react\release\index.android.bundle:11649:44: warning: the variable "URLSearchParams" was not declared in anonymous function " 305#"
} else if (support.searchParams && URLSearchParams.prototype.isPrototypeOf(body)) {
^~~~~~~~~~~~~~~
D:\react-native\******\android\app\build\generated\assets\react\release\index.android.bundle:11877:23: warning: the variable "XMLHttpRequest" was not declared in anonymous function " 314#"
var xhr = new XMLHttpRequest();
^~~~~~~~~~~~~~
D:\react-native\******\android\app\build\generated\assets\react\release\index.android.bundle:11468:76: warning: the variable "self" was not declared in anonymous function " 297#"
var global = typeof globalThis !== 'undefined' && globalThis || typeof self !== 'undefined' && self || typeof global !== 'undefined' && global;
^~~~
D:\react-native\******\android\app\build\generated\assets\react\release\index.android.bundle:19082:27: warning: the variable "performance" was not declared in anonymous function " 498#"
if ("object" === typeof performance && "function" === typeof performance.now) {
^~~~~~~~~~~
D:\react-native\******\android\app\build\generated\assets\react\release\index.android.bundle:19105:26: warning: the variable "navigator" was not declared in anonymous function " 498#"
"undefined" !== typeof navigator && undefined !== navigator.scheduling && undefined !== navigator.scheduling.isInputPending && navigator.scheduling.isInputPending.bind(navigator.scheduling);
^~~~~~~~~
D:\react-native\******\android\app\build\generated\assets\react\release\index.android.bundle:19172:37: warning: the variable "MessageChannel" was not declared in anonymous function " 498#"
};else if ("undefined" !== typeof MessageChannel) {
^~~~~~~~~~~~~~
D:\react-native\******\android\app\build\generated\assets\react\release\index.android.bundle:26733:32: warning: the variable "requestAnimationFrame" was not declared in function "onUpdate"
this._animationFrame = requestAnimationFrame(this.onUpdate.bind(this));
^~~~~~~~~~~~~~~~~~~~~
D:\react-native\******\android\app\build\generated\assets\react\release\index.android.bundle:65200:7: warning: the property "alignItems" was set multiple times in the object definition.
alignItems: 'center',
^~~~~~~~~~~~~~~~~~~~
D:\react-native\******\android\app\build\generated\assets\react\release\index.android.bundle:65199:7: note: The first definition was here.
alignItems: 'flex-start',
^~~~~~~~~~~~~~~~~~~~~~~~
D:\react-native\******\android\app\build\generated\assets\react\release\index.android.bundle:65242:7: warning: the property "alignItems" was set multiple times in the object definition.
alignItems: 'center',
^~~~~~~~~~~~~~~~~~~~
D:\react-native\******\android\app\build\generated\assets\react\release\index.android.bundle:65241:7: note: The first definition was here.
alignItems: 'flex-end',
^~~~~~~~~~~~~~~~~~~~~~
</code></pre>
<p>Been searching out different things on the Internet, could not find anything that solves the issue. Seems React native has changed some things i do not seem to see why its giving this As an error.</p>
| [
{
"answer_id": 74387141,
"author": "Armin Ayari",
"author_id": 8863489,
"author_profile": "https://Stackoverflow.com/users/8863489",
"pm_score": 1,
"selected": false,
"text": "::before"
},
{
"answer_id": 74387886,
"author": "beep",
"author_id": 9931829,
"author_profile": "https://Stackoverflow.com/users/9931829",
"pm_score": 0,
"selected": false,
"text": "<div class=\"rows\">\n <div class=\"dot\" style=\"color: #555555;\"></div>\n <div class=\"child\">C 90%</div>\n</div>\n<div class=\"rows\">\n <div class=\"dot\" style=\"color: #6E4C13;\"></div>\n <div class=\"child\">Assembly 5.8%</div>\n</div>\n<div class=\"rows\">\n <div class=\"dot\" style=\"color: #427819;\"></div>\n <div class=\"child\">Makefile 2.9%</div>\n</div>\n"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74386951",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19813264/"
] |
74,386,969 | <p>I have multiple @State var that will be changed in the TextField, but I want to keep the old values to be used after the state values are changed on the TextFields</p>
<pre><code>@State var name: String
var oldName = ???
</code></pre>
<p>What is the best approach for this?</p>
| [
{
"answer_id": 74387231,
"author": "vadian",
"author_id": 5044042,
"author_profile": "https://Stackoverflow.com/users/5044042",
"pm_score": 0,
"selected": false,
"text": ".onSubmit"
},
{
"answer_id": 74387489,
"author": "Cheezzhead",
"author_id": 2542661,
"author_profile": "https://Stackoverflow.com/users/2542661",
"pm_score": 1,
"selected": false,
"text": "TextField"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74386969",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20462449/"
] |
74,386,972 | <p>I have a linestring and a polygon and I am using turf.booleanIntersect() to determine if the line goes through the polygon. The example that i have tested and works is:</p>
<pre><code>var poly1 = turf.polygon([
[
[148.535693, -29.6],
[154.553967, -29.64038],
[154.526554, -33.820031],
[148.535693, -33.6],
[148.535693, -29.6]
]
]);
//const p1 = L.geoJSON(poly1).addTo(mymap);
console.log("TEST: " + turf.booleanIntersects(line, poly1));
</code></pre>
<p>In my real code I read the polygon values from a file and need to insert them into an array which needs to be converted into a "GeoJSON Feature or Geometry" (from webpage).</p>
<p>I am having trouble getting the array to json convert correct.</p>
<pre><code>var polygonlines = [];
var start = [long,lat];
polygonlines.push([start]); //add multiple of these points to the to polygonlines array
//create my json
var geojsonPolygon =
{
"type": "Feature",
"properties": {},
"geometry": {
"type": "Polygon",
"coordinates": polygonlines
}
}
var turfpolygon = turf.polygon(geojsonPolygon.data.geometry.coordinates); //ERROR HERE
const p2 = L.geoJSON(turfpolygon).addTo(mymap);
var result = turf.booleanIntersects(line, turfpolygon)
</code></pre>
<p>The error I get is "Uncaught Error Error: Each LinearRing of a Polygon must have 4 or more Positions."</p>
<p>I can't quite get the structure of the geojsonPolygon correct. I think that it is look at geojsonPolygon Array(1) in attached picture instead of Array(10), but I can't work out how to fix it.</p>
<p>Would love some help getting this structure fixed. Thank you :)</p>
<p>p.s. please ignore values of lat/longs, just examples.</p>
<p>I have seen this question but it hasn't helped <a href="https://stackoverflow.com/questions/50054010/how-to-feed-json-data-of-coordinates-to-turf-polygon">How to feed JSON data of coordinates to turf.polygon?</a></p>
<p><a href="https://i.stack.imgur.com/LGaVX.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/LGaVX.png" alt="enter image description here" /></a></p>
| [
{
"answer_id": 74387231,
"author": "vadian",
"author_id": 5044042,
"author_profile": "https://Stackoverflow.com/users/5044042",
"pm_score": 0,
"selected": false,
"text": ".onSubmit"
},
{
"answer_id": 74387489,
"author": "Cheezzhead",
"author_id": 2542661,
"author_profile": "https://Stackoverflow.com/users/2542661",
"pm_score": 1,
"selected": false,
"text": "TextField"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74386972",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15502957/"
] |
74,386,975 | <pre class="lang-py prettyprint-override"><code>cursor.execute('''CREATE TABLE PEDIDO(
CPEDIDO INT GENERATED AS IDENTITY PRIMARY KEY,
CCLIENTE INT NOT NULL,
FECHA DATE NOT NULL
)''')
valores=[]
for i in range(10):
print(i)
x=datetime.date(year=2022,month=11,day=i+1)
valores.append((i,x))
cursor.executemany("INSERT INTO PEDIDO VALUES(?,?);", valores) #doesn't work writing [valores] instead of valores
</code></pre>
<p>That results in:</p>
<blockquote>
<p>pyodbc.Error: ('HY000', '[HY000] [Devart][ODBC][Oracle]ORA-00947: not enough values\n (0) (SQLExecDirectW)') #when inserting the instances</p>
</blockquote>
<p>I have tried to save data in two different tuples:<code> cclients = (...) and dates=(...)</code> and then write:</p>
<pre class="lang-py prettyprint-override"><code>cursor.executemany("INSERT INTO PEDIDO VALUES(?,?);", [cclients, dates]).
</code></pre>
<p>But doesn't work</p>
| [
{
"answer_id": 74387231,
"author": "vadian",
"author_id": 5044042,
"author_profile": "https://Stackoverflow.com/users/5044042",
"pm_score": 0,
"selected": false,
"text": ".onSubmit"
},
{
"answer_id": 74387489,
"author": "Cheezzhead",
"author_id": 2542661,
"author_profile": "https://Stackoverflow.com/users/2542661",
"pm_score": 1,
"selected": false,
"text": "TextField"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74386975",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20457068/"
] |
74,386,982 | <p>How do I solve this while using <code>include()</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-js lang-js prettyprint-override"><code>const allowedIds = [1, 3]
const allBoats = [{
id: 1,
name: 'titanic'
}, {
id: 2,
name: 'anna'
}, {
id: 3,
name: 'boaty McBoatface'
}, ]
const expectedResult = ['boaty McBoatface', 'titanic']</code></pre>
</div>
</div>
</p>
| [
{
"answer_id": 74387026,
"author": "dangarfield",
"author_id": 3265253,
"author_profile": "https://Stackoverflow.com/users/3265253",
"pm_score": 2,
"selected": false,
"text": "const allowedIds = [1, 3]\n\nconst allBoats = [{\n id: 1,\n name: 'titanic'\n}, {\n id: 2,\n name: 'anna'\n}, {\n id: 3,\n name: 'boaty McBoatface'\n}, ]\n\nconst result = allBoats\n .filter(b => allowedIds.includes(b.id))\n .map(b => b.name)\n .sort((a, b) => a.localeCompare(b))\nconsole.log('result', result)"
},
{
"answer_id": 74387044,
"author": "Sash Sinha",
"author_id": 6328256,
"author_profile": "https://Stackoverflow.com/users/6328256",
"pm_score": 2,
"selected": false,
"text": "allowedIds"
},
{
"answer_id": 74387082,
"author": "Abhishek",
"author_id": 14982115,
"author_profile": "https://Stackoverflow.com/users/14982115",
"pm_score": 0,
"selected": false,
"text": "const selections = allBoats.filter((val)=>{return val.id === 1 || val.id ===3});\nconst result = selections.map((val,key)=>{ val.name}).sort()\nconsole.log(result) //gives [\"boaty McBoatface\", \"titanic\"]\n"
},
{
"answer_id": 74387113,
"author": "Shyam Tayal",
"author_id": 8220144,
"author_profile": "https://Stackoverflow.com/users/8220144",
"pm_score": 0,
"selected": false,
"text": "allBoats.filter(entry => allowedIds.includes(entry.id)).map(item => item.name).sort()\n"
},
{
"answer_id": 74387154,
"author": "Layhout",
"author_id": 17308201,
"author_profile": "https://Stackoverflow.com/users/17308201",
"pm_score": 0,
"selected": false,
"text": "const allowedIds = [1, 3]\n\nconst allBoats = [\n {\n id: 1,\n name: 'titanic'\n },\n {\n id: 2,\n name: 'anna'\n },\n {\n id: 3,\n name: 'boaty McBoatface'\n }\n]\n\nconst expectedResult = allBoats.reduce((p, c) => allowedIds.includes(c.id) ? p.concat(c.name) : p, []).sort((a, b) => a.localeCompare(b));\n\nconsole.log(expectedResult);"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74386982",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
74,387,032 | <p>I want to create an simple XSS. Below is my code</p>
<pre><code><body>
<script>
function update(){
const message = document.getElementById("message").value;
document.getElementById("show_message").innerHTML = message
}
</script>
<h1 class="title">Cross-Site Scripting</h1>
<div class="input">
<input type="text" id="message"/><br/>
<button type="button" onclick="update()">submit</button>
</div>
<hr/>
<div id="root">
You typed :
<span id="show_message">
</span>
</div>
</body>
</code></pre>
<p>Then I tried to type in <code><script>alert(1);</script></code>.But it didn't work. <br/> Where's the problem?</p>
| [
{
"answer_id": 74387180,
"author": "Tushar Shahi",
"author_id": 10140124,
"author_profile": "https://Stackoverflow.com/users/10140124",
"pm_score": 3,
"selected": true,
"text": "script"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74387032",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19870073/"
] |
74,387,089 | <p>I tried to lead from the home page to <code>"/allUsers"</code> page. The homepage has a link that directs to the all Users page. But when I click from the home page to all User page it does not show any content. The link to all Users is <code>"http://localhost:3000/allUsers"</code></p>
<p>App.js:</p>
<pre><code>import './App.css';
import { Routes, Route } from "react-router-dom";
import { BrowserRouter } from 'react-router-dom';
import React, { useState, useEffect } from "react";
import { useDispatch } from "react-redux";
import Home from './components/Home';
import allUsers from './pages/allUsers/allUsers';
import airportEmployee from './pages/AirportEmployee/airportEmployee';
import airlineEmployee from './pages/AirlineEmployee/airlineEmployee';
function App() {
return (
<div className="App">
<Routes>
<Route path="/" element={<Home />} />
<Route path="/allUsers" element={<allUsers />} />
<Route path="/airline-employee" element={<airlineEmployee />} />
<Route path="/airport-employee" element={<airportEmployee />} />
</Routes>
</div>
);
}
export default App;
</code></pre>
<p>Here is the <strong>Home.js</strong> file</p>
<pre><code>const Home = () => {
return (
<Breadcrumbs aria-label="breadcrumb">
<Link
underline="hover"
color="inherit"
href="/allUsers"
fontSize="large"
>
All Users
</Link>
<Link
underline="hover"
color="inherit"
href="/airport-employee"
fontSize="large"
>
Airport Employee
</Link>
<Link
underline="hover"
color="inherit"
href="/airline-employee"
fontSize="large"
>
Airline Employee
</Link>
</Breadcrumbs>
);
};
export default Home;
</code></pre>
| [
{
"answer_id": 74387281,
"author": "Miquel Strippoli",
"author_id": 19890485,
"author_profile": "https://Stackoverflow.com/users/19890485",
"pm_score": -1,
"selected": false,
"text": "<Route path=\"/allUsers\" exact element={<allUsers/>} />\n"
},
{
"answer_id": 74387393,
"author": "Abhishek",
"author_id": 14982115,
"author_profile": "https://Stackoverflow.com/users/14982115",
"pm_score": 0,
"selected": false,
"text": "import { BrowserRouter as Router, Route, Routes, Link } from 'react-router-dom'\nfunction App() {\n return (\n <div className=\"App\">\n<Router>\n <Routes>\n <Route path=\"/\" element={<Home />} />\n <Route path=\"/allUsers\" element={<allUsers />} />\n <Route path=\"/airline-employee\" element={<airlineEmployee />} />\n <Route path=\"/airport-employee\" element={<airportEmployee />} />\n </Routes>\n</Router>\n </div>\n );\n}\n"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74387089",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15363812/"
] |
74,387,128 | <p>I have this dataframe df and the vector z</p>
<pre><code>df = data.frame(x =c(letters[1:3],NA,NA,'part1',letters[4:5],NA,NA,'part2',
letters[6:7]),
y = c('p1','p2','p3',NA,NA,'---','p4',
'p5',NA,NA,'---','p6','p7') )
z = 5:6
</code></pre>
<p>and I want to create a column the is called <code>score</code> with part1 has the score 5 and part2 has the score 6. the condition is that the row before each <strong>part</strong> is composed of NAs. The other values in the score column would be NAs. Appreciate the help.</p>
<p>the expected output</p>
<pre><code> x y score
1 a p1 NA
2 b p2 NA
3 c p3 NA
4 <NA> <NA> NA
5 <NA> <NA> NA
6 part1 --- 5
7 d p4 NA
8 e p5 NA
9 <NA> <NA> NA
10 <NA> <NA> NA
11 part2 --- 6
12 f p6 NA
13 g p7 NA
</code></pre>
| [
{
"answer_id": 74387528,
"author": "shaun_m",
"author_id": 18289387,
"author_profile": "https://Stackoverflow.com/users/18289387",
"pm_score": 3,
"selected": true,
"text": "z"
},
{
"answer_id": 74387610,
"author": "sindri_baldur",
"author_id": 4552295,
"author_profile": "https://Stackoverflow.com/users/4552295",
"pm_score": 1,
"selected": false,
"text": "z"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74387128",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19720935/"
] |
74,387,208 | <p>I have a list that I extract it into sublists and then I splitted it into sublists of 20 items.
Now I want to take juste 200 items of this list and then split it But .take didn't work for me.</p>
<pre><code> static Future<List> localPath() async {
File textAsset = File('/storage/emulated/0/RPSApp/assets/bluetooth.txt');
final text = await textAsset.readAsString();
final bytes = text
.split(',')
.map((s) => s.trim())
.map((s) => int.parse(s))
.toList();
int chunkSize = 20;
final dd = bytes.take(200);
print("BYTES : $dd");
List<int> padTo(List<int> input, int count) {
return [...input, ...List.filled(count - input.length, 255)];
}
List<int> padToChunksize(List<int> input) =>
padTo(input.toList(), chunkSize);
final items =
bytes.slices(chunkSize).map(padToChunksize).take(200).toList();
return items;
//return items;
}
</code></pre>
<p>even when I tried the code below I didn't get the expected output</p>
<pre><code>return items.take(200).toList();
</code></pre>
<p>this is how I use the function:</p>
<pre><code> final chunks = await Utils.localPath();
await Future.forEach(chunks, (chunk) async {
final d = chunk as List<int>;
await c.write(d, withoutResponse: true);
await c.read();
await Future.delayed(const Duration(seconds: 4));
});
</code></pre>
| [
{
"answer_id": 74387528,
"author": "shaun_m",
"author_id": 18289387,
"author_profile": "https://Stackoverflow.com/users/18289387",
"pm_score": 3,
"selected": true,
"text": "z"
},
{
"answer_id": 74387610,
"author": "sindri_baldur",
"author_id": 4552295,
"author_profile": "https://Stackoverflow.com/users/4552295",
"pm_score": 1,
"selected": false,
"text": "z"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74387208",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20285309/"
] |
74,387,223 | <p>EDITED: I am trying to CASE a query from my table when a result meets 2 sets of criteria (Flight Time & Tail Number), but I am receiving the wrong result. I only started SQL a few weeks ago for an upcoming school assignment, but am having trouble with this query.</p>
<pre><code>SELECT FlightNumber AS 'Flight Number', Date, Aircraft, Aircraft_Manufacturer AS 'Aircraft Manufacturer', Tail_Number AS 'Tail Number', Departure, Arrival, FlightTime AS 'Flight Time', Instructor, Passengers,
CASE
WHEN SUM(FlightTime) >= 20 AND Tail_Number LIKE '24-%' THEN "RAAus Recreational Pilots Certificate (RPC)"
WHEN SUM(FlightTime) >= 25 AND Tail_Number LIKE '24-%' THEN "RAAus RPC Passenger Endorsment"
WHEN SUM(FlightTime) >= 32 AND Tail_Number LIKE '24-%' THEN "RAAus RPC Cross Country Endorsment"
WHEN SUM(FlightTime) >= 7 AND Tail_Number LIKE 'VH-%' THEN "RPC Conversion to CASA Recreational Pilot License (RPL)"
ELSE 'Not Eligible For License'
END AS "License Eligibility"
FROM Flight_Log
GROUP BY FlightNumber
ORDER BY FlightNumber
</code></pre>
<p>My results are:
<a href="https://i.stack.imgur.com/id38b.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/id38b.png" alt="Results" /></a></p>
<p>Expected Results:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Flight Number</th>
<th>Flight Time</th>
<th>Licence Eligibility</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>7</td>
<td>Not Eligible for License</td>
</tr>
<tr>
<td>2</td>
<td>6</td>
<td>Not Eligible for License</td>
</tr>
<tr>
<td>3</td>
<td>8</td>
<td>Not Eligible for License</td>
</tr>
<tr>
<td>4</td>
<td>5</td>
<td>RAAus Recreational Pilots Certificate (RPC)</td>
</tr>
</tbody>
</table>
</div>
<p>Once the cumulative hours reaches 20 or more to show the WHEN statements.</p>
<p>My Table Creation with the INSERT INTO looks like this for anyone wondering (I have removed a few rows from the end):</p>
<pre><code>CREATE TABLE IF NOT EXISTS Flight_Log (
`FlightNumber` INTEGER PRIMARY KEY AUTO_INCREMENT,
`Date` DATE,
`Aircraft` VARCHAR(50),
`Aircraft_Manufacturer` VARCHAR(50),
`Tail_Number` VARCHAR(50),
`MTOW` INTEGER,
`Manufacture_Year` YEAR,
`Aircraft_Type` VARCHAR(50),
`Departure` CHAR(4),
`Arrival` CHAR(4),
`FlightTime` INTEGER,
`Instructor` BOOLEAN,
`Passengers` INTEGER
);
INSERT INTO Flight_Log VALUES (1,'2022-10-08','Tecnam P-92 Eaglet','Tecnam','24-5955',600,1992,'Recreational','YCDR','YCDR',1,'1',0);
INSERT INTO Flight_Log VALUES (2,'2022-12-03','Tecnam P-92 Eaglet','Tecnam','24-5955',600,1992,'Recreational','YCDR','YCDR',3,'1',0);
INSERT INTO Flight_Log VALUES (3,'2022-12-05','Tecnam P-92 Eaglet','Tecnam','24-5955',600,1992,'Recreational','YCDR','YCDR',3,'1',0);
INSERT INTO Flight_Log VALUES (4,'2022-12-08','Tecnam Sierra','Tecnam','24-7155',600,2002,'Recreational','YCDR','YCDR',3,'1',0);
INSERT INTO Flight_Log VALUES (5,'2022-12-17','Tecnam Sierra','Tecnam','24-7155',600,2002,'Recreational','YCDR','YCDR',3,'1',0);
INSERT INTO Flight_Log VALUES (6,'2022-12-27','Fly Synthesis Texan','Fly Synthesis','24-5285',600,1998,'Recreational','YCDR','YCDR',1,'1',0);
INSERT INTO Flight_Log VALUES (7,'2022-12-31','Tecnam Sierra','Tecnam','24-7155',600,2002,'Recreational','YCDR','YCDR',2,'0',0);
INSERT INTO Flight_Log VALUES (8,'2023-01-01','Tecnam P-92 Eaglet','Tecnam','24-5955',600,1992,'Recreational','YCDR','YCDR',2,'0',0);
INSERT INTO Flight_Log VALUES (9,'2023-01-12','Tecnam Sierra','Tecnam','24-7155',600,2002,'Recreational','YCDR','YCDR',1,'0',0);
INSERT INTO Flight_Log VALUES (10,'2023-01-18','Tecnam Sierra','Tecnam','24-7155',600,2002,'Recreational','YCDR','YCDR',4,'0',0);
INSERT INTO Flight_Log VALUES (11,'2023-01-27','Tecnam Sierra','Tecnam','24-7155',600,2002,'Recreational','YCDR','YCDR',3,'0',0);
INSERT INTO Flight_Log VALUES (12,'2023-02-03','Tecnam Sierra','Tecnam','24-7155',600,2002,'Recreational','YCDR','YCDR',3,'0',0);
INSERT INTO Flight_Log VALUES (13,'2023-02-14','Tecnam P-92 Eaglet','Tecnam','24-5955',600,1992,'Recreational','YCDR','YCDR',1,'0',1);
INSERT INTO Flight_Log VALUES (14,'2023-02-14','Tecnam P-92 Eaglet','Tecnam','24-5955',600,1992,'Recreational','YCDR','YCDR',1,'0',1);
INSERT INTO Flight_Log VALUES (15,'2023-03-14','Tecnam P-92 Eaglet','Tecnam','24-5955',600,1992,'Recreational','YCDR','YCDR',1,'0',1);
INSERT INTO Flight_Log VALUES (16,'2023-03-14','Tecnam P-92 Eaglet','Tecnam','24-5955',600,1992,'Recreational','YCDR','YCDR',1,'0',1);
INSERT INTO Flight_Log VALUES (17,'2023-03-28','Cessna 172R','Cessna','VH-CFG',1111,1997,'Recreational','YCDR','YCDR',3,'1',0);
INSERT INTO Flight_Log VALUES (18,'2023-04-06','Cessna 172 G1000','Cessna','VH-IVW',1156,2013,'Recreational','YRED','YRED',3,'1',0);
INSERT INTO Flight_Log VALUES (19,'2023-04-19','Cessna 172 G1000','Cessna','VH-IVW',1156,2013,'Recreational','YRED','YCDR',2,'1',0);
INSERT INTO Flight_Log VALUES (20,'2023-04-23','Cirrus SR22','Cirrus','VH-EDH',1633,2014,'Recreational','YBAF','YBAF',2,'1',0);
INSERT INTO Flight_Log VALUES (21,'2023-05-02','Cirrus SR22','Cirrus','VH-EDH',1633,2014,'Recreational','YBAF','YBAF',2,'1',0);
</code></pre>
<p>What am I doing wrong? (I am using the newest version of MySQL (8.0.31))</p>
| [
{
"answer_id": 74387528,
"author": "shaun_m",
"author_id": 18289387,
"author_profile": "https://Stackoverflow.com/users/18289387",
"pm_score": 3,
"selected": true,
"text": "z"
},
{
"answer_id": 74387610,
"author": "sindri_baldur",
"author_id": 4552295,
"author_profile": "https://Stackoverflow.com/users/4552295",
"pm_score": 1,
"selected": false,
"text": "z"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74387223",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16736411/"
] |
74,387,244 | <p>I'm setting up my integration testing rig. I'm using the <code>beforeEach</code> and <code>afterEach</code> hooks to wrap every single test in a transaction that rollsback so that the tests don't affect each other. A simplified example might be this:</p>
<pre class="lang-js prettyprint-override"><code>const { repository } = require("library")
describe("Suite", function () {
beforeEach(async function () {
await knex.raw("BEGIN");
});
afterEach(async function () {
await knex.raw("ROLLBACK");
});
it("A test", async function () {
const user = await repository.createUser()
user.id.should.equal(1)
});
});
</code></pre>
<p>This worked fine because I configured knex to use a single DB connection for tests. Hence calling <code>knex.raw("BEGIN");</code> created a <em>global</em> transaction.</p>
<p>Now however, the library's repository which I can't control started using transactions internally. I.e. <code>createUser()</code> begins and then <em>commits</em> the created user. This broke my tests as now my <code>afterEach</code> hook doesn't rollback the changes because they were already committed.</p>
<p>Is there a way in Postgres to rollback a transaction that have (already committed) nested transactions?</p>
<p>Or maybe a way to use knex to prevent the repository from starting transactions in the first place? It uses <code>knex.transaction()</code> to create them.</p>
<p>Thanks!</p>
| [
{
"answer_id": 74387528,
"author": "shaun_m",
"author_id": 18289387,
"author_profile": "https://Stackoverflow.com/users/18289387",
"pm_score": 3,
"selected": true,
"text": "z"
},
{
"answer_id": 74387610,
"author": "sindri_baldur",
"author_id": 4552295,
"author_profile": "https://Stackoverflow.com/users/4552295",
"pm_score": 1,
"selected": false,
"text": "z"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74387244",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5698865/"
] |
74,387,257 | <p>I have the following dataset:</p>
<pre><code> Col_A Amounts
0 A 100
1 B 200
2 C 500
3 D 100
4 E 500
5 F 300
</code></pre>
<p>The output I am trying to achieve is to basically remove all values based on the "Amounts" column which have a duplicate value and to keep only the rows where there is <strong>one unique instance</strong> of a value.</p>
<p>Desired Output:</p>
<pre><code> Col_A Amounts
1 B 200
5 F 300
</code></pre>
<p>I have tried to use the following with no luck:</p>
<pre><code>df_1.drop_duplicates(subset=['Amounts'])
</code></pre>
<p>This removes the duplicates, however, it still keeps the values which have occurred more than once.</p>
<p>Using the pandas <code>.unique</code> function also provides a similiar undesired output.</p>
| [
{
"answer_id": 74387305,
"author": "jezrael",
"author_id": 2901002,
"author_profile": "https://Stackoverflow.com/users/2901002",
"pm_score": 2,
"selected": true,
"text": "keep=False"
},
{
"answer_id": 74387423,
"author": "Mat.B",
"author_id": 14649447,
"author_profile": "https://Stackoverflow.com/users/14649447",
"pm_score": 0,
"selected": false,
"text": "value_counts()"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74387257",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9395266/"
] |
74,387,347 | <p>i have been trying to implement a context api solution since i want to use children states(data) in my app.js without lifting up the states. anyways i have tried to implement it a context api soloution to by doing the following :</p>
<ol>
<li>i created a folder names context and then created Context.js</li>
</ol>
<p>the code is as follows:</p>
<pre><code>mport { createContext,useState } from "react";
export const Mycontext = createContext()
const Context = ({children}) =>{
const [post, setPost] = useState([])
return(
<Mycontext.Provider value={[post,setPost]}>
{children}
</Mycontext.Provider>
)
}
export default Context
</code></pre>
<ol start="2">
<li>i wrapped the index.js file with the Provider wrapper as follows:</li>
</ol>
<pre><code>import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import Context from './context/Context';
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<Context>
<App />
</Context>
);
</code></pre>
<ol start="3">
<li>my main goal for now is to use useState hook data or states so i can use them in higher up comonents , in this case i want my post.js file to change usestate data in context so i can then use that data to post something in App.js using a container component that takes value as a props</li>
</ol>
<p>i will post the both post.js and container.js and app.js below</p>
<pre><code>import React,{useContext,useState,useEffect,useRef} from 'react'
import '../HomeMainStyling/HomeStyling.css'
import Tweets from './Tweets'
import Context from '../../context/Context'
function Tweet() {
const tw = useRef('')
const {post,setPost} = useContext(Context);
useEffect(() => {
if (post.length) console.log(post);
}, [post]);
function PostNow(event){
event.preventDefault();
setPost((oldpost) => [tw.current.value,...oldpost]);
}
return (
<div className="tweetcontainer">
<textarea ref={tw} className="tweetinfo"></textarea>
<button className="postIt" onClick={PostNow}>tweet</button>
</div>
)
}
export default Tweet
//
</code></pre>
<p>the container is the following:</p>
<pre><code>import React from 'react'
import '../HomeMainStyling/HomeStyling.css'
function Tweets({value}) {
return (
<h2>{value}</h2>
)
}
export default Tweets
</code></pre>
<p>App.js:</p>
<pre><code>import Tweet from './Center/HomeMain/Tweet';
import Tweets from './Center/HomeMain/Tweets';
import { useContext,useState } from 'react';
import Context from './context/Context';
function App() {
const {post,setPost} = useContext(Context);
return (
<div className="App">
<Tweet/>
<Tweets value={post}/>
</div>
);
}
export default App;
</code></pre>
<p>the app should in principle post 1 h1 element for every click in Tweet components</p>
| [
{
"answer_id": 74387480,
"author": "Enve",
"author_id": 1354378,
"author_profile": "https://Stackoverflow.com/users/1354378",
"pm_score": 2,
"selected": false,
"text": "useContext"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74387347",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20181776/"
] |
74,387,351 | <p>The problem give an array of integers 'nums' and an integer 'target', return indices of the two numbers such that they add up to target.</p>
<p>Example:</p>
<pre><code>Input: nums = [2,7,11,15], target = 9
Output: [0,1]
Explanation: Because nums[0] + nums[1] == 9, we return [0, 1].
</code></pre>
<pre><code>class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
y=0
x=0
solutions = []
for x in nums:
for y in nums:
if (nums[x] + nums [y]) == target:
solutions[0] = x
solutions[1] = y
print(solutions)
break
y+=1
x+=1
</code></pre>
<p>Why this solution doesn't work?
The problem is "Index out of range" in line 8</p>
| [
{
"answer_id": 74387480,
"author": "Enve",
"author_id": 1354378,
"author_profile": "https://Stackoverflow.com/users/1354378",
"pm_score": 2,
"selected": false,
"text": "useContext"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74387351",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20264067/"
] |
74,387,353 | <p>I need help with passing the variable I have initialized using <code>__construct()</code> to view in Laravel.</p>
<p>Here is my controller code</p>
<pre><code>protected $profileInfo;
public function __construct(){
$this->profileInfo = Profile::with('address')->where('id', '=', '1')->get();
}
public function index(){
$this->profileInfo;
return view('admin_pages.profile', compact('profileInfo'));
}
</code></pre>
<p>I get an error <code>undefined variable profileInfo</code></p>
| [
{
"answer_id": 74387408,
"author": "Gert B.",
"author_id": 2911020,
"author_profile": "https://Stackoverflow.com/users/2911020",
"pm_score": 3,
"selected": true,
"text": "compact()"
},
{
"answer_id": 74387410,
"author": "stefket",
"author_id": 2499739,
"author_profile": "https://Stackoverflow.com/users/2499739",
"pm_score": 1,
"selected": false,
"text": "compact()"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74387353",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9999993/"
] |
74,387,360 | <p>I would like to read a csv file in streaming Dataflow job and map each row into dict <code>{"column1": "value"1}</code> and upload it into BQ.
As an entry point I am using <code>ReadAllFromText</code> so it returns just row by row, where first row is a header.
How can I map row[0] (header) to all next rows?</p>
<p>I seems like a very basic task but I cannot find any answer for it.</p>
| [
{
"answer_id": 74387408,
"author": "Gert B.",
"author_id": 2911020,
"author_profile": "https://Stackoverflow.com/users/2911020",
"pm_score": 3,
"selected": true,
"text": "compact()"
},
{
"answer_id": 74387410,
"author": "stefket",
"author_id": 2499739,
"author_profile": "https://Stackoverflow.com/users/2499739",
"pm_score": 1,
"selected": false,
"text": "compact()"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74387360",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12135668/"
] |
74,387,368 | <p>There's the following trait:</p>
<pre><code>Trait Example{
val foo : String
}
</code></pre>
<p>Then from another class that uses Example I set foo = "bar". Is there an easy way to for example do print(foo) or execute some other function when this value is set? Without having to touch the assignation preferably, just code within the trait class.</p>
<p>The options I tried would require making foo a function and then it would be called differently, so I'm not sure what's the best way to proceed.</p>
| [
{
"answer_id": 74387408,
"author": "Gert B.",
"author_id": 2911020,
"author_profile": "https://Stackoverflow.com/users/2911020",
"pm_score": 3,
"selected": true,
"text": "compact()"
},
{
"answer_id": 74387410,
"author": "stefket",
"author_id": 2499739,
"author_profile": "https://Stackoverflow.com/users/2499739",
"pm_score": 1,
"selected": false,
"text": "compact()"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74387368",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15107211/"
] |
74,387,376 | <p>I'm not at ease with comprehension dictionaries
I would like to transform this loop into a dictionary comprehension.</p>
<p>Thanks for your help</p>
<pre><code>dico={}
for key in ['good','very good','bad','very bad','not good not bad']:
if key in['good','very good']:
dico[key]='green'
else:
dico[key]='red'
print(dico)
</code></pre>
<p>Here is what's expected</p>
<pre><code>{'good': 'green',
'very good': 'green',
'bad': 'red',
'very bad': 'red',
'not good not bad': 'red'}
</code></pre>
| [
{
"answer_id": 74387408,
"author": "Gert B.",
"author_id": 2911020,
"author_profile": "https://Stackoverflow.com/users/2911020",
"pm_score": 3,
"selected": true,
"text": "compact()"
},
{
"answer_id": 74387410,
"author": "stefket",
"author_id": 2499739,
"author_profile": "https://Stackoverflow.com/users/2499739",
"pm_score": 1,
"selected": false,
"text": "compact()"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74387376",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20467264/"
] |
74,387,389 | <p>I created an event listener to catch when a physical button is pressed, and it works well.
But I would want to update a <code>list</code> used in a <code>LazyColumn</code></p>
<pre><code>class MainActivity : ComponentActivity() {
@OptIn(ExperimentalComposeUiApi::class)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
Theme {
Surface(
modifier = Modifier .fillMaxSize(),
color = MaterialTheme.colors.background
) {
Column(modifier = Modifier.fillMaxSize()) {
Greeting("Android")
}
}
}
}
}
@SuppressLint("RestrictedApi")
override fun dispatchKeyEvent(event: KeyEvent?): Boolean {
// Handling event to get a text (type String)
// ......
//then updating my list
myList+=newValue
}
var myList: List<String> = mutableListOf()
@OptIn(ExperimentalFoundationApi::class, ExperimentalComposeUiApi::class)
@Composable
fun Greeting(name: String, paramBarcode: String) {
var mutableList by remember {mutableStateOf(myList)}
Button(onClick = {
myList+= "new item"
mutableList = myList
}) {
Text(text = "Add")
}
LazyColumn(Modifier.fillMaxSize() .padding(16.dp)
) {
stickyHeader {Row(Modifier.fillMaxSize() .background(Color.Green)
) {
TableCell(text = "Code", width = 264)
}
}
itemsIndexed(items = mutableList, itemContent = {
index, item ->
Row(Modifier.fillMaxSize(),
) {
TableCell(text = item, width = 256)
}
})
}
}
</code></pre>
<p>If I try to <code>add</code> or <code>remove</code> an element of the <code>list</code> from my composable, everything is fine, but I can't get the same behaviour from my event.</p>
<p>I also tried to pass the <code>list</code> as a parameter to my composable, but it didn't help at all.</p>
| [
{
"answer_id": 74387645,
"author": "z.y",
"author_id": 19023745,
"author_profile": "https://Stackoverflow.com/users/19023745",
"pm_score": 3,
"selected": true,
"text": "SnapshotStateList"
},
{
"answer_id": 74391410,
"author": "Joe Mama Jr.",
"author_id": 19014213,
"author_profile": "https://Stackoverflow.com/users/19014213",
"pm_score": 0,
"selected": false,
"text": "\nvar MainList: SnapshotStateList<String> = SnapshotStateList()\n\nclass MainActivity : ComponentActivity() {\n var myList: SnapshotStateList<String> = MainList\n\n @OptIn(ExperimentalComposeUiApi::class)\n override fun onCreate(savedInstanceState: Bundle?) {\n super.onCreate(savedInstanceState)\n setContent {\n Theme {\n Surface(\n modifier = Modifier.fillMaxSize(),\n color = MaterialTheme.colors.background\n ) {\n Column(modifier = Modifier.fillMaxSize()) {\n Greeting(\"Android\", myList)\n }\n }\n }\n }\n }\n}\n\n @SuppressLint(\"RestrictedApi\")\n override fun dispatchKeyEvent(event: KeyEvent?): Boolean {\n MainList.add(\"$barcode\")\n }\n}\n\n@OptIn(ExperimentalFoundationApi::class, ExperimentalComposeUiApi::class)\n@Composable\nfun Greeting(name: String, paramBarcode: String, theList: SnapshotStateList<ScanItem>) {\n var mutableList by remember { mutableStateOf(theList) }\n\n Column() {\n Button(onClick = {\n MainList.add(\"ABC0000000000001\")\n }) {\n Text(text = \"Add item\")\n }\n Row() {\n Button(onClick = { \n MainList.add(\"add00001\")\n }) { \n Text(text = \"Add\")\n }\n Button(\n onClick = { MainList.clear() }\n ) {\n Text(\"Empty list\")\n }\n }\n }\n}\n"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74387389",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19014213/"
] |
74,387,391 | <p>It is possible to configure functions as strings to parse them to functions during runtime.</p>
<p>The following example <code>functionAsString</code> expects input and deals with it, I only know that it MUST return a boolean ( I'm expecting that )</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 x = {
fields: {
age: 0
}
};
const y = {
fields: {
age: 1
}
};
const functionAsString = "(left, right) => left.fields.age < right.fields.age";
const compareFunction = new Function(functionAsString);
const isXLessThanY = compareFunction(x, y);
if (isXLessThanY === undefined) {
console.error("it should not be undefined...");
} else {
console.log({
isXLessThanY
});
}</code></pre>
</div>
</div>
</p>
<p><code>isXLessThanY</code> is <code>undefined</code>. Do you know how to setup a valid function based on a string?</p>
| [
{
"answer_id": 74387645,
"author": "z.y",
"author_id": 19023745,
"author_profile": "https://Stackoverflow.com/users/19023745",
"pm_score": 3,
"selected": true,
"text": "SnapshotStateList"
},
{
"answer_id": 74391410,
"author": "Joe Mama Jr.",
"author_id": 19014213,
"author_profile": "https://Stackoverflow.com/users/19014213",
"pm_score": 0,
"selected": false,
"text": "\nvar MainList: SnapshotStateList<String> = SnapshotStateList()\n\nclass MainActivity : ComponentActivity() {\n var myList: SnapshotStateList<String> = MainList\n\n @OptIn(ExperimentalComposeUiApi::class)\n override fun onCreate(savedInstanceState: Bundle?) {\n super.onCreate(savedInstanceState)\n setContent {\n Theme {\n Surface(\n modifier = Modifier.fillMaxSize(),\n color = MaterialTheme.colors.background\n ) {\n Column(modifier = Modifier.fillMaxSize()) {\n Greeting(\"Android\", myList)\n }\n }\n }\n }\n }\n}\n\n @SuppressLint(\"RestrictedApi\")\n override fun dispatchKeyEvent(event: KeyEvent?): Boolean {\n MainList.add(\"$barcode\")\n }\n}\n\n@OptIn(ExperimentalFoundationApi::class, ExperimentalComposeUiApi::class)\n@Composable\nfun Greeting(name: String, paramBarcode: String, theList: SnapshotStateList<ScanItem>) {\n var mutableList by remember { mutableStateOf(theList) }\n\n Column() {\n Button(onClick = {\n MainList.add(\"ABC0000000000001\")\n }) {\n Text(text = \"Add item\")\n }\n Row() {\n Button(onClick = { \n MainList.add(\"add00001\")\n }) { \n Text(text = \"Add\")\n }\n Button(\n onClick = { MainList.clear() }\n ) {\n Text(\"Empty list\")\n }\n }\n }\n}\n"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74387391",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19698303/"
] |
74,387,443 | <p>I have multiple components with different paths (routes) and would like to export those to a single Main router component.</p>
<p>For example:</p>
<p>routeComponent1.js</p>
<pre><code>export default function childRoutes() {
return (
<div>
<Route path="/foo" component={foo} />
<Route path="/bar" component={bar} />
</div>
);
}
</code></pre>
<p>routeComponent2.js</p>
<pre><code>export default function childRoutes2() {
return (
<div>
<Route path="/foo2" component={foo2} />
<Route path="/bar2" component={bar2} />
</div>
);
}
</code></pre>
<p>I would like to use it in</p>
<p>root.js</p>
<pre><code>import routeComponent1 from 'routeComponent1.js';
import routeComponent2 from 'routeComponent2.js';
class Root extends Component {
constructor(props) {
super(props);
}
render() {
return <Router>{routeComponent1}</Router>;
}
}
</code></pre>
<p>It is giving an error - Invariant Violation: <code><Route></code> elements are for router configuration only and should not be rendered.</p>
<p>Expecting the</p>
<pre><code><Router>
<div>
<Route path="/foo" component={foo} />
<Route path="/bar" component={bar} />
</div>
</Router>
</code></pre>
| [
{
"answer_id": 74387645,
"author": "z.y",
"author_id": 19023745,
"author_profile": "https://Stackoverflow.com/users/19023745",
"pm_score": 3,
"selected": true,
"text": "SnapshotStateList"
},
{
"answer_id": 74391410,
"author": "Joe Mama Jr.",
"author_id": 19014213,
"author_profile": "https://Stackoverflow.com/users/19014213",
"pm_score": 0,
"selected": false,
"text": "\nvar MainList: SnapshotStateList<String> = SnapshotStateList()\n\nclass MainActivity : ComponentActivity() {\n var myList: SnapshotStateList<String> = MainList\n\n @OptIn(ExperimentalComposeUiApi::class)\n override fun onCreate(savedInstanceState: Bundle?) {\n super.onCreate(savedInstanceState)\n setContent {\n Theme {\n Surface(\n modifier = Modifier.fillMaxSize(),\n color = MaterialTheme.colors.background\n ) {\n Column(modifier = Modifier.fillMaxSize()) {\n Greeting(\"Android\", myList)\n }\n }\n }\n }\n }\n}\n\n @SuppressLint(\"RestrictedApi\")\n override fun dispatchKeyEvent(event: KeyEvent?): Boolean {\n MainList.add(\"$barcode\")\n }\n}\n\n@OptIn(ExperimentalFoundationApi::class, ExperimentalComposeUiApi::class)\n@Composable\nfun Greeting(name: String, paramBarcode: String, theList: SnapshotStateList<ScanItem>) {\n var mutableList by remember { mutableStateOf(theList) }\n\n Column() {\n Button(onClick = {\n MainList.add(\"ABC0000000000001\")\n }) {\n Text(text = \"Add item\")\n }\n Row() {\n Button(onClick = { \n MainList.add(\"add00001\")\n }) { \n Text(text = \"Add\")\n }\n Button(\n onClick = { MainList.clear() }\n ) {\n Text(\"Empty list\")\n }\n }\n }\n}\n"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74387443",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8568484/"
] |
74,387,445 | <p>I have a</p>
<pre><code>Map<String,List<User>>map = new HashMap<>();
map.put("projectA",Arrays.asList(new User(1,"Bob"),new User(2,"John"),new User(3,"Mo")));
map.put("projectB",Arrays.asList(new User(2,"John"),new User(3,"Mo")));
map.put("projectC",Arrays.asList(new User(3,"Mo")));
</code></pre>
<p>Can use String instead of User.</p>
<p>String is a project Name but the same users can relate to different projects.</p>
<p>I would like to get sth like <code>Map<User, List<String>></code> where
the key will represent a distinct user and a value as a list of projects' names to which he/she relates.</p>
<pre><code>Bob = [projectA]
John = [projectA, projectB]
Mo = [projectA, projectB, projectC]
</code></pre>
<p>TQ in advance for any piece of advice.</p>
| [
{
"answer_id": 74387617,
"author": "f1sh",
"author_id": 214525,
"author_profile": "https://Stackoverflow.com/users/214525",
"pm_score": 1,
"selected": false,
"text": "public static void main(String[] args) {\n Map<String, List<User>> map = new HashMap<>();\n map.put(\"projectA\", Arrays.asList(new User(1,\"Bob\"),new User(2,\"John\"),new User(3,\"Mo\")));\n map.put(\"projectB\",Arrays.asList(new User(2,\"John\"),new User(3,\"Mo\")));\n map.put(\"projectC\",Arrays.asList(new User(3,\"Mo\")));\n\n Map<User, List<String>> result = new HashMap<>();\n for(Map.Entry<String, List<User>> e:map.entrySet()) {\n for(User u:e.getValue()) {\n result.putIfAbsent(u, new ArrayList<>());\n result.get(u).add(e.getKey());\n }\n }\n System.out.println(result);\n}\npublic static record User(int id, String name) {}\n"
},
{
"answer_id": 74390772,
"author": "Alexander Ivanchenko",
"author_id": 17949945,
"author_profile": "https://Stackoverflow.com/users/17949945",
"pm_score": 0,
"selected": false,
"text": "Map.computeIfAbsent()"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74387445",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12648740/"
] |
74,387,450 | <p>I have checked all the existing questions on Stackoverflow but I couldn't find the perfect answer to it and need your help.</p>
<p>So basically I have multiple Strings containing different formats of URL in different ways, for eg:-</p>
<p>1:</p>
<p><code><p><a href='https://abcd.com/sites/WG-ProductManagementTeam/FunctionalSpecs/Forms/AllItems.aspx?id=/sites/WG-ProductManagementTeam/FunctionalSpecs/DevDOC/Enhancements to PA Peer Checklist/PA Peer Checklist (V2.3) -v10.0.pdf&amp;parent=/sites/WG-ProductManagementTeam/FunctionalSpecs/DevDOC/Enhancements to PA Peer Checklist&amp;p=true&amp;ga=1'>WG-Product Management Team - PA Peer Checklist (V2.3) -v10.0.pdf - All Documents (sharepoint.com)</a></p></code></p>
<p>2:</p>
<p><code>https://abcd.com/sites/WG-ProductManagementTeam/FunctionalSpecs/Forms/AllItems.aspx?id=%2Fsites%2FWG%2DProductManagementTeam%2FFunctionalSpecs%2FDevDOC%2FEnhancements%20to%20PA%20Peer%20Checklist%2FPA%20Peer%20Checklist%20%28V2%2E3%29%20%2Dv10%2E0%2Epdf&parent=%2Fsites%2FWG%2DProductManagementTeam%2FFunctionalSpecs%2FDevDOC%2FEnhancements%20to%20PA%20Peer%20Checklist&p=true&ga=1</code></p>
<p>3:</p>
<p><code>https://abcd.com/:b:/r/sites/WG-ProductManagementTeam/FunctionalSpecs/DevDOC/Enhancements%20to%20PA%20Peer%20Checklist/PA%20Peer%20Checklist%20(v2.0)%20-%20v3.0.pdf?csf=1&web=1&e=txs2Yq</code></p>
<p>I want to extract a part of URL like this:-
/DevDOC/....../.pdf</p>
<p>as you can see above shared 3 URL strings are all different but I am not able to find the most efficient way to resolve this.</p>
<p>I need to do it in such a way that it works for every type of URL string even though formats are different it should extract it from any and every String in same way.</p>
<p>Right now I am using regex: ".<em>/FunctionalSpecs(?!.</em>\1)(.*?)(.pdf)" and it is working for URL 2 and 3 shared above but in case of URL 1 it is returning:</p>
<p>/DevDOC/Enhancements to PA Peer Checklist&p=true&ga=1'>WG-Product Management Team - PA Peer Checklist (V2.3) -v10.0.pdf</p>
<p>which is incorrect, I wanted this:</p>
<p>/DevDOC/Enhancements to PA Peer Checklist/PA Peer Checklist (V2.3) -v10.0.pdf</p>
<p>Please help me resolve this as soon as possible as It seems so easy but I am not able to do it in an efficient way.</p>
<p>Also, I am trying to do it in Java.</p>
<p>Any help is highly appreciated. Thank you.</p>
| [
{
"answer_id": 74387617,
"author": "f1sh",
"author_id": 214525,
"author_profile": "https://Stackoverflow.com/users/214525",
"pm_score": 1,
"selected": false,
"text": "public static void main(String[] args) {\n Map<String, List<User>> map = new HashMap<>();\n map.put(\"projectA\", Arrays.asList(new User(1,\"Bob\"),new User(2,\"John\"),new User(3,\"Mo\")));\n map.put(\"projectB\",Arrays.asList(new User(2,\"John\"),new User(3,\"Mo\")));\n map.put(\"projectC\",Arrays.asList(new User(3,\"Mo\")));\n\n Map<User, List<String>> result = new HashMap<>();\n for(Map.Entry<String, List<User>> e:map.entrySet()) {\n for(User u:e.getValue()) {\n result.putIfAbsent(u, new ArrayList<>());\n result.get(u).add(e.getKey());\n }\n }\n System.out.println(result);\n}\npublic static record User(int id, String name) {}\n"
},
{
"answer_id": 74390772,
"author": "Alexander Ivanchenko",
"author_id": 17949945,
"author_profile": "https://Stackoverflow.com/users/17949945",
"pm_score": 0,
"selected": false,
"text": "Map.computeIfAbsent()"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74387450",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13341552/"
] |
74,387,548 | <p>In a custom class I have the following code:</p>
<pre><code>class CustomClass():
triggerQueue: multiprocessing.Queue
def __init__(self):
self.triggerQueue = multiprocessing.Queue()
def poolFunc(queueString):
print(queueString)
def listenerFunc(self):
pool = multiprocessing.Pool(5)
while True:
try:
queueString = self.triggerQueue.get_nowait()
pool.apply_async(func=self.poolFunc, args=(queueString,))
except queue.Empty:
break
</code></pre>
<p>What I intend to do is:</p>
<ul>
<li>add a trigger to the queue (not implemented in this snippet) -> works as intended</li>
<li>run an endless loop within the listenerFunc that reads all triggers from the queue (if any are found) -> works as intended</li>
<li>pass trigger to poolFunc which is to be executed asynchronosly -> not working</li>
</ul>
<p>It works as soon as I source my poolFun() outside of the class like</p>
<pre><code>def poolFunc(queueString):
print(queueString)
class CustomClass():
[...]
</code></pre>
<p>But why is that so? Do I have to pass the self argument somehow? Is it impossible to perform it this way in general?</p>
<p>Thank you for any hint!</p>
| [
{
"answer_id": 74388656,
"author": "Viktor Katzy",
"author_id": 11067145,
"author_profile": "https://Stackoverflow.com/users/11067145",
"pm_score": 0,
"selected": false,
"text": "@staticmethod\ndef poolFunc(queueString):\n \n print(queueString)\n"
},
{
"answer_id": 74388935,
"author": "larsks",
"author_id": 147356,
"author_profile": "https://Stackoverflow.com/users/147356",
"pm_score": 2,
"selected": true,
"text": "poolFunc"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74387548",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11067145/"
] |
74,387,566 | <p>Lets take this for Example:</p>
<pre><code>public class Vehicle {
public enum Car {
CAR1,
CAR2,
CAR3,
CAR4,
}
public enum BIKE {
BIKE1,
BIKE2,
BIKE3
}
}
public class Main {
public static void main(String args[]) {
Vehicle.Car value1 = Vehicle.Car.CAR1;
Vehicle.Bike value2 = Vehicle.Bike.BIKE1;
print(evaluateType(value1));
// Expected Output: Car
print(evaluateType(value2));
// Expected Output: Bike
}
}
</code></pre>
<p>Now the use case here is, We have to write the function <code>evaluateType</code>. I was wondering if there is a way to know the type of Enum we are using, if it is of type <code>Bike</code> or <code>Car</code>.</p>
<p>Given the fact the enums are stored as Int in memory, this doesn't seems like it can be done. But looking forward to any suggestion on how this type of situations could be handled.</p>
<p>Thank you.</p>
| [
{
"answer_id": 74388656,
"author": "Viktor Katzy",
"author_id": 11067145,
"author_profile": "https://Stackoverflow.com/users/11067145",
"pm_score": 0,
"selected": false,
"text": "@staticmethod\ndef poolFunc(queueString):\n \n print(queueString)\n"
},
{
"answer_id": 74388935,
"author": "larsks",
"author_id": 147356,
"author_profile": "https://Stackoverflow.com/users/147356",
"pm_score": 2,
"selected": true,
"text": "poolFunc"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74387566",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10885530/"
] |
74,387,625 | <p>I'm trying to write a notification system between a server and multiple clients using gRPC server streaming in protobuf-net.grpc (.NET Framework 4.8).</p>
<p>I based my service off of <a href="https://github.com/protobuf-net/protobuf-net.Grpc/blob/main/examples/wcf-port/SimpleStockTicker/src/TraderSys.SimpleStockTickerServer/Services/StockTickerService.cs" rel="nofollow noreferrer">this example</a>. However, if I understand the example correctly, it is only able to handle a single subscriber (as <code>_subscriber</code> is a member variable of the <code>StockTickerService</code> class).</p>
<p>My test service looks like this:</p>
<pre><code>private readonly INotificationService _notificationService;
private readonly Channel<Notification> _channel;
public ClientNotificationService(INotificationService notificationService)
{
_notificationService = notificationService;
_notificationService.OnNotification += OnNotification;
_channel = Channel.CreateUnbounded<Notification>();
}
private async void OnNotification(object sender, Notification notification)
{
await _channel.Writer.WriteAsync(notification);
}
public IAsyncEnumerable<Notification> SubscribeAsync(CallContext context = default)
{
return _channel.AsAsyncEnumerable(context.CancellationToken);
}
</code></pre>
<p><code>INotificationService</code> just has an event <code>OnNotification</code>, which is fired when calling its <code>Notify</code> method.</p>
<p>I then realized that System.Threading.Channels implements the Producer/Consumer pattern, but I need the Publisher/Subscriber pattern. When trying it out, indeed only one of the clients gets notified, instead of all of them.
It would also be nice if the server knew when a client disconnects, which seems impossible when returning <code>_channel.AsAsyncEnumerable</code>.</p>
<p>So how can I modify this in order to</p>
<ul>
<li>serve multiple clients, with all of them being notified when <code>OnNotification</code> is called</li>
<li>and log when a client disconnects?</li>
</ul>
| [
{
"answer_id": 74391602,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 2,
"selected": true,
"text": "SubscribeAsync"
},
{
"answer_id": 74418660,
"author": "4b0",
"author_id": 965146,
"author_profile": "https://Stackoverflow.com/users/965146",
"pm_score": 0,
"selected": false,
"text": "public class NotificationService<T>\n{\n private readonly Subject<T> _stream = new Subject<T>();\n\n public void Publish(T notification)\n {\n _stream.OnNext(notification);\n }\n\n public IDisposable Subscribe(Action<T> onNext)\n return _stream.Subscribe(onNext);\n }\n}\n"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74387625",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2727133/"
] |
74,387,643 | <p>I have a string <code>s:4:"Test";</code> from my <a href="https://stackoverflow.com/questions/74386133/how-to-decrypt-from-bash-string-that-was-encrypted-by-laravel">previous question</a>.
How I can unserialize it and get just a <code>Test</code> string?</p>
| [
{
"answer_id": 74387836,
"author": "sinica",
"author_id": 8063455,
"author_profile": "https://Stackoverflow.com/users/8063455",
"pm_score": 0,
"selected": false,
"text": "echo 's:4:\"Test\";' | sed -e 's/.*\"\\(.*\\)\".*/\\1/'\n"
},
{
"answer_id": 74388494,
"author": "user1934428",
"author_id": 1934428,
"author_profile": "https://Stackoverflow.com/users/1934428",
"pm_score": 2,
"selected": false,
"text": "str='s:4:\"Test\";' # Initial string\ns=${str//[:0-9\\\";]/} # Remove digits, quote, colon, semicolon\necho ${s:1} # Drop the first character\n"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74387643",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8063455/"
] |
74,387,658 | <p>Before switching on angular I worked in <code>javascript</code>. I want to change value of <code>css </code>properties of certain elements in typescript. But I found that you can not change it like in <code>javascript</code>: <code>name.style.color='red'</code>.</p>
<p>With <code>javascript </code>I would write:
HTML:</p>
<pre><code><div id="blue" style="background-color:red;">
Hello
</div>
<button id="it">Press</button>
</code></pre>
<p>JS:</p>
<pre><code>let blue=document.getElementById("blue");
let it=document.getElementById("it");
it.onclick= ()=> blue.style.backgroundColor="blue";
</code></pre>
<p>But in typescript it doesn't work:
HTML:</p>
<pre><code><div id="blue" style="background-color:red;">
Hello
</div>
<button (click)="switch()">Press</button>
</code></pre>
<p>TS:</p>
<pre><code>import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'my_app_2';
blue=document.getElementById("blue");
switch() {
this.blue.style.backgroundColor="blue";
}
}
</code></pre>
<p>I found one soultion, but I would like to know is there any more 'natural' way to do it like in javascript. Here code of that solution:
HTML:</p>
<pre><code><div id="blue" [ngStyle]="this.clicked==true?{'background-color':'blue'}:{'background-color':'red'}">
Hello
</div>
<button (click)="switch()">Press</button>
</code></pre>
<p>TS:</p>
<pre><code>import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'my_app_2';
clicked=false;
switch() {
this.clicked=!this.clicked;
}
}
</code></pre>
| [
{
"answer_id": 74387836,
"author": "sinica",
"author_id": 8063455,
"author_profile": "https://Stackoverflow.com/users/8063455",
"pm_score": 0,
"selected": false,
"text": "echo 's:4:\"Test\";' | sed -e 's/.*\"\\(.*\\)\".*/\\1/'\n"
},
{
"answer_id": 74388494,
"author": "user1934428",
"author_id": 1934428,
"author_profile": "https://Stackoverflow.com/users/1934428",
"pm_score": 2,
"selected": false,
"text": "str='s:4:\"Test\";' # Initial string\ns=${str//[:0-9\\\";]/} # Remove digits, quote, colon, semicolon\necho ${s:1} # Drop the first character\n"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74387658",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20453677/"
] |
74,387,662 | <p>Hi stackoverflow community,</p>
<p>I need some help pls,</p>
<p>I have a GraphQL data source, I'm using apollo client to pull those data.
I am currently working on my login function; I am using next-auth credential provider:
[Edited code below with the fetch call to graphql ]</p>
<pre><code>import NextAuth from "next-auth";
import CredentialsProvider from "next-auth/providers/credentials";
export default NextAuth({
session: {
strategy: 'jwt',
},
callbacks: {
async jwt({ token, user}: any) {
if(user?._id) token._id = user._id;
return token;
},
async session({ session, token}: any) {
if(token?._id) session.user._id = token._id;
return session;
},
},
providers: [
CredentialsProvider({
async authorize(credentials: any) {
const query = `query User($email: String!) { user(email: $email) { id, username, email, password, }}`;
const response: any = await fetch('http://localhost:4000/graphql', {
method: "POST",
headers: {"Content-Type": "application/json","Accept": "application/json", },
body: JSON.stringify({query, variables: { email: credentials.email }})
});
const {data}: any = await response.json();
if(data) {
return {
_id: data.user.id,
name: data.user.username,
email: data.user.email,
};
}
throw new Error("Invalid email or password");
},
}),
],
});
</code></pre>
<p>Here's my getUser hook
[ Commenting this out since this is no longer relevant</p>
<pre><code>// import { useQuery, gql } from '@apollo/client';
// const Get_User = gql`
// query User($email: String!) {
// user(email: $email) {
// id
// username
// email
// password
// }
// }
// `;
// export default function getUser(email: any) {
// const { error, data } = useQuery(Get_User, {variables: {email}});
// return {
// error,
// data,
// }
// }
</code></pre>
<p>I've verified that my next-auth endpoint is working by commenting out the GraphQL getUser and changing the if statement comparing to itself (credential.password === credential.password) and returning a statically written data back.</p>
<p>data inside credentials object is passing and accessing the values correctly.</p>
<p>[YES I WAS :( ] I think I am violating some react hooks law here, but I can't quite figure out how to address this, any enlightenment would be greatly appreciated. Thanks in advance! ^-^</p>
<p>So now it seems like theres something wrong with my fetch timings as it won't return my user details as expected even though my fetch request is working if tested on another page.</p>
| [
{
"answer_id": 74393130,
"author": "Michel Floyd",
"author_id": 2805154,
"author_profile": "https://Stackoverflow.com/users/2805154",
"pm_score": 1,
"selected": false,
"text": "GetUser"
},
{
"answer_id": 74415649,
"author": "Carl Nierves",
"author_id": 7986254,
"author_profile": "https://Stackoverflow.com/users/7986254",
"pm_score": 1,
"selected": true,
"text": "useQuery"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74387662",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7986254/"
] |
74,387,689 | <pre><code>id city
1 London
2 Rome
3 London
4 Rome
</code></pre>
<p>Expected output like this:</p>
<pre><code>London Rome
2 2
</code></pre>
<p>Using case expression...</p>
<p>How can I solve this query?</p>
| [
{
"answer_id": 74387999,
"author": "Littlefoot",
"author_id": 9097906,
"author_profile": "https://Stackoverflow.com/users/9097906",
"pm_score": 2,
"selected": false,
"text": "group by"
},
{
"answer_id": 74388169,
"author": "MT0",
"author_id": 1509264,
"author_profile": "https://Stackoverflow.com/users/1509264",
"pm_score": 1,
"selected": false,
"text": "SELECT COUNT(CASE city WHEN 'London' THEN 1 END) AS London,\n COUNT(CASE city WHEN 'Rome' THEN 1 END) AS Rome\nFROM table_name\nWHERE city IN ('London', 'Rome')\n"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74387689",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20407795/"
] |
74,387,690 | <p>I have an antd Form on which i checked if entered date is past date then i show the Popup with antd PopConfirm and if user press 'Yes' in PopConfirm, i want to submit the form, how can i achieve this?</p>
<p>Below is my code :</p>
<pre><code><PopConfirm
onConfirm={() => {
}}
cancelText={'No'}
okText={'Yes'}
disabled={!isPastDate}
title={'Do you wish to continue with past date?'}
>
<Button type="primary" label="Save" htmlType="submit" />
</PopConfirm>
</code></pre>
| [
{
"answer_id": 74387999,
"author": "Littlefoot",
"author_id": 9097906,
"author_profile": "https://Stackoverflow.com/users/9097906",
"pm_score": 2,
"selected": false,
"text": "group by"
},
{
"answer_id": 74388169,
"author": "MT0",
"author_id": 1509264,
"author_profile": "https://Stackoverflow.com/users/1509264",
"pm_score": 1,
"selected": false,
"text": "SELECT COUNT(CASE city WHEN 'London' THEN 1 END) AS London,\n COUNT(CASE city WHEN 'Rome' THEN 1 END) AS Rome\nFROM table_name\nWHERE city IN ('London', 'Rome')\n"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74387690",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18306625/"
] |
74,387,691 | <pre><code>df1 = pd.DataFrame({'Region': ['E', 'E', 'U', 'E'], 'Id': [1,None,None,None], 'Ids': [1,2,3,4]})
df2 = pd.DataFrame({'Region': ['E', 'U', 'U', 'E'], 'Id': [1,2,3,4], 'Ids': [1,2,3,4]})
x = df1.groupby(['Region']).count()
y = df2.groupby(['Region']).count()
c = pd.concat([x['Id'], y['Id']], axis=1, keys=['Here', 'There'])
</code></pre>
<p>I have the table with two rows (like indices, 'E' and 'U') which count the number of E and U for each data frame and concatenate them with different keys: Here and There.
Now I want to add another index, let's call it 'Total' and next to it I want get the total number of values under 'Here' and 'There'.</p>
<p>Now:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Region</th>
<th>Here</th>
<th>There</th>
</tr>
</thead>
<tbody>
<tr>
<td>E</td>
<td>1</td>
<td>2</td>
</tr>
<tr>
<td>U</td>
<td>0</td>
<td>2</td>
</tr>
</tbody>
</table>
</div>
<p>Now I want to add another index, let's call it 'Total' and next to it I want get the total number of values under 'Here' and 'There'.</p>
<p>I want to achieve:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Region</th>
<th>Here</th>
<th>There</th>
</tr>
</thead>
<tbody>
<tr>
<td>E</td>
<td>1</td>
<td>2</td>
</tr>
<tr>
<td>U</td>
<td>0</td>
<td>2</td>
</tr>
<tr>
<td>Total</td>
<td>1</td>
<td>4</td>
</tr>
</tbody>
</table>
</div>
<p>Thank you.</p>
| [
{
"answer_id": 74387999,
"author": "Littlefoot",
"author_id": 9097906,
"author_profile": "https://Stackoverflow.com/users/9097906",
"pm_score": 2,
"selected": false,
"text": "group by"
},
{
"answer_id": 74388169,
"author": "MT0",
"author_id": 1509264,
"author_profile": "https://Stackoverflow.com/users/1509264",
"pm_score": 1,
"selected": false,
"text": "SELECT COUNT(CASE city WHEN 'London' THEN 1 END) AS London,\n COUNT(CASE city WHEN 'Rome' THEN 1 END) AS Rome\nFROM table_name\nWHERE city IN ('London', 'Rome')\n"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74387691",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20467492/"
] |
74,387,711 | <p>I have some components that I create using createComponent. While some components work correctly some don't have proper css classes. I'm using a function and [ngClass] to set the classes but they just aren't there when I inspect the component in dom.</p>
<pre><code>constructor (private injector: EnvironmentInjector) {};
const compRef = createComponent(RadioButtonComponent, { environmentInjector: this.injector});
document.body.appendChild(compRef.location.nativeElement);
</code></pre>
<p>Radio button has code
radio.component.html</p>
<pre class="lang-html prettyprint-override"><code><div [ngClass]="classes">
...
</div>
</code></pre>
<p>radio.component.ts</p>
<pre><code>public get classes(): string[] {
let cls: string[] = [];
cls.push('some-class-name');
return cls;
}
</code></pre>
| [
{
"answer_id": 74387999,
"author": "Littlefoot",
"author_id": 9097906,
"author_profile": "https://Stackoverflow.com/users/9097906",
"pm_score": 2,
"selected": false,
"text": "group by"
},
{
"answer_id": 74388169,
"author": "MT0",
"author_id": 1509264,
"author_profile": "https://Stackoverflow.com/users/1509264",
"pm_score": 1,
"selected": false,
"text": "SELECT COUNT(CASE city WHEN 'London' THEN 1 END) AS London,\n COUNT(CASE city WHEN 'Rome' THEN 1 END) AS Rome\nFROM table_name\nWHERE city IN ('London', 'Rome')\n"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74387711",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20173895/"
] |
74,387,766 | <p>I'm new with Hololens 2 programming. I'm developing an UWP app with Unity for Holo2 that use an XML configuration file to receive informations about the placing of 3D objects in relative position with the marker. It works fine when I try to read and process the file from Resources folder (Unity and Hololens) and from PC AppData (Unity), but I've some problems when I try to read it from an Hololens AppData folder (also when I try to read file from the special folders KnownFolders).
I used the 'ApplicationData.Current.RoamingFolder.Path' as internal UWP folder (accessible from DevicePortal), and StorageFolder & StorageFile for await Get async method in a new Task.
I also modified the code of package.appxmanifest with right FileTypeAssociation for .xml
I hope that the Microsoft Account Email (user@mail.com) used as Username in the path of ApplicationData.Current.RoamingFolder.Path is not the problem for async methods.</p>
<pre><code>//...
using System.Xml.Linq;
using System.Threading.Tasks;
//...
#if WINDOWS_UWP
using Windows.Storage;
#endif
</code></pre>
<p>Here the loading of stream</p>
<pre><code>#if WINDOWS_UWP
try
{
folderPathName = ApplicationData.Current.RoamingFolder.Path;
using (Stream s = openFileUWP(folderPathName, filenameWithExtension))
{
document = XDocument.Load(s);
}
}
catch (Exception e)
{
document = XDocument.Parse(targetFile.text); //the XML file in Resources folder
}
#else
//...
#endif
</code></pre>
<p>Here the openFileUWP function</p>
<pre><code>#if WINDOWS_UWP
private Stream openFileUWP(string folderName, string fileName)
{
Stream stream = null;
Task task = new Task(
async () =>
{
StorageFolder folder = await StorageFolder.GetFolderFromPathAsync(folderName);
StorageFile file = await folder.GetFileAsync(fileName);
stream = await file.OpenStreamForReadAsync();
});
task.Start();
task.Wait();
return stream;
}
#endif
</code></pre>
| [
{
"answer_id": 74394293,
"author": "Paulo Morgado",
"author_id": 402366,
"author_profile": "https://Stackoverflow.com/users/402366",
"pm_score": 1,
"selected": false,
"text": "Task"
},
{
"answer_id": 74558193,
"author": "Zuocheng Wang - MSFT",
"author_id": 19772221,
"author_profile": "https://Stackoverflow.com/users/19772221",
"pm_score": 0,
"selected": false,
"text": "#if ENABLE_WINMD_SUPPORT\nusing Windows.Storage;\nusing Windows.Storage.Streams;\n#endif\n\n#if ENABLE_WINMD_SUPPORT\n private async void ReadFile()\n {\n Windows.Storage.StorageFolder storageFolder = Windows.Storage.ApplicationData.Current.RoamingFolder;\n Windows.Storage.StorageFile sampleFile = await storageFolder.GetFileAsync(\"sample.txt\");\n var stream = await sampleFile.OpenAsync(Windows.Storage.FileAccessMode.Read); \n //You can return the stream here. Note that the type of this stream is Windows.Storage.Streams.IRandomAccessStream.\n\n ulong size = stream.Size;\n using (var inputStream = stream.GetInputStreamAt(0))\n {\n using (var dataReader = new Windows.Storage.Streams.DataReader(inputStream))\n {\n uint numBytesLoaded = await dataReader.LoadAsync((uint)size);\n string text = dataReader.ReadString(numBytesLoaded);\n }\n }\n }\n#endif\n"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74387766",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20467378/"
] |
74,387,802 | <p>I have two global variables. the first variable is assigned inside the second variable.When I update the first variable the second one is not getting updated.</p>
<pre><code> String value = "abcd";
String value1 = "$value efgh";
void main() {
print(value);
print(value1);
value = "Zxy";
print(value);
print(value1);
}
Result:
abcd
abcd efgh
Zxy
abcd efgh
</code></pre>
<p>To my understanding when I reassigned the first variable with different value.But the second variable don't know about this.That why it is printing the previous value. Its something similar to <code>final</code>.you can only change the value once after initialization.</p>
<p>If my understanding of this function is wrong please explain what is exactly happening and also tell me if there is anyway to change the global variable without the <code>setState</code> or <code>statemanagement</code>.</p>
| [
{
"answer_id": 74390017,
"author": "TheHumanItSelf",
"author_id": 11938374,
"author_profile": "https://Stackoverflow.com/users/11938374",
"pm_score": 2,
"selected": false,
"text": "value1"
},
{
"answer_id": 74390167,
"author": "Afridi Kayal",
"author_id": 12636223,
"author_profile": "https://Stackoverflow.com/users/12636223",
"pm_score": 2,
"selected": true,
"text": "value1 = \"$value efgh\";\n"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74387802",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18906883/"
] |
74,387,809 | <p>I have an issue with the error handling in VBA.
The code has previously worked, but now suddenly errors are not handled by <code>On Error GoTo</code> statements and instead the code is crashing and giving a pop up with the error message as if <code>On Error GoTo 0</code> would be active.</p>
<p>Here is an example of how the code structure is:</p>
<pre><code>On Error GoTo logError
For d = 0 To Doclist.Count -1
On Error GoTo DownloadFailed
session.findById("wnd[0]/tbar[1]/btn[30]").press
session.findById("wnd[1]/usr/sub:SAPLSPO4:0300/ctxtSVALD-VALUE[0,21]").Text = filepath
On Error GoTo logError
...
DownloadFailed:
Err.Clear
On Error GoTo logError
Next d
logError:
ws1.Cells(1, 7).Value = Err.Description
Workbooks("Main.xlsm").Save
</code></pre>
<p>In the first iteration the <code>On Error GoTo DownloadFailed</code> is working as expected, but after this the code is crashing.
The error that I am getting is Run-time error '619'.
I saw on some similar post to clear the error with <code>Err.Clear</code> but this did nothing to my code.</p>
<p>In another part of the code I am using <code>On Error Resume Next</code> which at the same time stopped working.
As mentioned the code has worked previously so I have no idea what could be wrong.</p>
<p>Does anybody have experience with similar issues and any possible solutions for this?</p>
| [
{
"answer_id": 74389023,
"author": "GWD",
"author_id": 12287457,
"author_profile": "https://Stackoverflow.com/users/12287457",
"pm_score": 0,
"selected": false,
"text": "Err.Clear"
},
{
"answer_id": 74389142,
"author": "VBasic2008",
"author_id": 9814069,
"author_profile": "https://Stackoverflow.com/users/9814069",
"pm_score": 2,
"selected": false,
"text": "GoTo"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74387809",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15752997/"
] |
74,387,831 | <p>I am getting this error while running the code in React Native expo with Tailwind</p>
<p><code>Android Bundling failed 25ms</code>
<code>error:</code> <code>node_modules\expo\AppEntry.js: [BABEL]: Cannot find module 'node:path'</code>
<code>Require stack:</code>
<code>C:\Users\HPX\ipx\node_modules\nativewind\dist\babel\index.js</code>
<code>C:\Users\HPX\ipx\node_modules\nativewind\babel.js</code>
<code>C:\Users\HPX\ipx\node_modules@babel\core\lib\config\files\module-types.js</code>
<code>C:\Users\HPX\ipx\node_modules@babel\core\lib\config\files\configuration.js</code>
<code>C:\Users\HPX\ipx\node_modules@babel\core\lib\config\files\index.js</code>
<code>C:\Users\HPX\ipx\node_modules@babel\core\lib\index.js</code>
<code>C:\Users\HPX\ipx\node_modules\metro-transform-worker\src\index.js</code>
<code>C:\Users\HPX\ipx\node_modules\metro\src\DeltaBundler\Worker.flow.js</code>
<code>C:\Users\HPX\ipx\node_modules\metro\src\DeltaBundler\Worker.js</code>
<code>C:\Users\HPX\ipx\node_modules\jest-worker\build\workers\processChild.js (While processing: C:\Users\HPX\ipx\node_modules\nativewind\babel.js</code>)</p>
<p><a href="https://i.stack.imgur.com/EWuuo.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/EWuuo.png" alt="enter image description here" /></a></p>
<hr />
<p>This is my <strong>AppEntry.js</strong> file :</p>
<pre><code>import registerRootComponent from 'expo/build/launch/registerRootComponent';
import App from '../../App';
registerRootComponent(App);
</code></pre>
<p>This is my <strong>package.json</strong> file :</p>
<pre><code>{
"name": "ipx",
"version": "1.0.0",
"main": "node_modules/expo/AppEntry.js",
"scripts": {
"start": "expo start",
"android": "expo start --android",
"ios": "expo start --ios",
"web": "expo start --web"
},
"dependencies": {
"expo": "~47.0.3",
"expo-status-bar": "~1.4.2",
"nativewind": "^2.0.11",
"react": "18.1.0",
"react-native": "0.70.5",
"tailwindcss": "^3.2.3"
},
"devDependencies": {
"@babel/core": "^7.12.9"
},
"private": true
}
</code></pre>
<p>Please replay if you have a solution for this</p>
| [
{
"answer_id": 74389023,
"author": "GWD",
"author_id": 12287457,
"author_profile": "https://Stackoverflow.com/users/12287457",
"pm_score": 0,
"selected": false,
"text": "Err.Clear"
},
{
"answer_id": 74389142,
"author": "VBasic2008",
"author_id": 9814069,
"author_profile": "https://Stackoverflow.com/users/9814069",
"pm_score": 2,
"selected": false,
"text": "GoTo"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74387831",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19146029/"
] |
74,387,861 | <p>I have a <strong>dataframe</strong>. I want it to filter it and reduce certain values to a string. The dataframe looks like this</p>
<p><a href="https://i.stack.imgur.com/slHX6.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/slHX6.png" alt="Dataframeimage" /></a></p>
<p><strong>Code:</strong></p>
<pre><code>data = [['42.0', 'A'], ['41.0', 'A'], ['43.0', 'B'],['43.0', 'C'], ['41.0', 'B'], ['42.0', 'B']]
df = pd.DataFrame(data, columns=['Number', 'Level'])
</code></pre>
<p><strong>I tried this</strong></p>
<pre><code>df.groupby(['Number', 'Level']).size()
</code></pre>
<p><strong>Got this output:</strong></p>
<p><a href="https://i.stack.imgur.com/wg2l9.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/wg2l9.png" alt="output" /></a></p>
<p>But I am looking to convert that output to a string like this</p>
<pre><code>42.0(1A,1B,0C)
41.0(1A,1B,0C)
43.0(0A,1B,1C)
</code></pre>
| [
{
"answer_id": 74387956,
"author": "jezrael",
"author_id": 2901002,
"author_profile": "https://Stackoverflow.com/users/2901002",
"pm_score": 3,
"selected": true,
"text": "crosstab"
},
{
"answer_id": 74387960,
"author": "flyakite",
"author_id": 17326889,
"author_profile": "https://Stackoverflow.com/users/17326889",
"pm_score": 1,
"selected": false,
"text": "df['res'] = df.index.astype(str) + df['Level']\nprint( df.groupby(['Number', 'res']).size() )\n\n###Number res\n###41.0 1A 1\n### 4B 1\n###42.0 0A 1\n### 5B 1\n###43.0 2B 1\n### 3C 1\n###dtype: int64\n"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74387861",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20089685/"
] |
74,387,879 | <p>I hope this question is simple enough to not warrant a reproducible example.</p>
<p>I have the following syntax:</p>
<pre><code>library(data.table)
setDT(table_selection)[, (vars_of_interest) := lapply(.SD, sqrt, na.rm=TRUE), by = year, .SDcols=sds_of_interest]
</code></pre>
<p>I would like to square a sequence of columns instead of taking the square root, but I cannot find a similar function.</p>
<p>How should I do this?</p>
| [
{
"answer_id": 74387956,
"author": "jezrael",
"author_id": 2901002,
"author_profile": "https://Stackoverflow.com/users/2901002",
"pm_score": 3,
"selected": true,
"text": "crosstab"
},
{
"answer_id": 74387960,
"author": "flyakite",
"author_id": 17326889,
"author_profile": "https://Stackoverflow.com/users/17326889",
"pm_score": 1,
"selected": false,
"text": "df['res'] = df.index.astype(str) + df['Level']\nprint( df.groupby(['Number', 'res']).size() )\n\n###Number res\n###41.0 1A 1\n### 4B 1\n###42.0 0A 1\n### 5B 1\n###43.0 2B 1\n### 3C 1\n###dtype: int64\n"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74387879",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8071608/"
] |
74,387,963 | <p>I want to insert multiple tuples into a set which each tuple contains a <code>list</code> and a <code>string</code>.<br />
Each tuple looks like:</p>
<pre><code>sample_tuple = (['list of elements'], 'one_string')
</code></pre>
<p>If we check the type of <code>sample_tuple</code>, we can be sure that it is a <code>tuple</code> with 2 elements (one list and one string).<br />
But when I use the "add" method to insert this tuple to my set, I get the error:</p>
<pre><code> TypeError Traceback (most recent call last)
c:\run.ipynb Cell 47 in <cell line: 15>()
11 sample_tuple = (['list of elements'], 'one_string')
12 sample_set.add(sample_tuple)
TypeError: unhashable type: 'list'
</code></pre>
<p>But this is the way that I insert a <code>tuple</code> into a <code>set</code> in python.<br />
Is there a way I can keep the form of my <code>tuple</code> (ie my <code>tuple</code> still consists of a <code>list</code> and a <code>string</code>) and then be able to insert this tuple into a <code>set</code> in Python?</p>
| [
{
"answer_id": 74387956,
"author": "jezrael",
"author_id": 2901002,
"author_profile": "https://Stackoverflow.com/users/2901002",
"pm_score": 3,
"selected": true,
"text": "crosstab"
},
{
"answer_id": 74387960,
"author": "flyakite",
"author_id": 17326889,
"author_profile": "https://Stackoverflow.com/users/17326889",
"pm_score": 1,
"selected": false,
"text": "df['res'] = df.index.astype(str) + df['Level']\nprint( df.groupby(['Number', 'res']).size() )\n\n###Number res\n###41.0 1A 1\n### 4B 1\n###42.0 0A 1\n### 5B 1\n###43.0 2B 1\n### 3C 1\n###dtype: int64\n"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74387963",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8496414/"
] |
74,388,015 | <p>The code below initializes a list of random integers, and iterates over it. Given a <code>subset_size</code>, at every iteration <code>i</code>, a sublist of <code>i: i + subset_size</code> is accessed. The time to access the sublist grows with <code>subset_size</code>. For <code>n = 100000</code> and <code>subset_size = 50000</code>, it takes 15+ seconds on my i5 mbp. I thought sublists are retrieved using 2 pointers and lazy evaluation but it looks like there's some <code>c</code> loop behind the scenes that populates a new list and returns it as a result. Is this a proper description to what actually happens or is there another explanation?</p>
<pre><code>import random
from datetime import timedelta
from time import perf_counter
def example(n, subset_size):
x = [random.randint(0, 10000) for _ in range(n)]
t = perf_counter()
for i in range(n - subset_size):
_ = x[i : i + subset_size]
print(timedelta(seconds=perf_counter() - t))
if __name__ == '__main__':
example(100000, 50000)
</code></pre>
<hr />
<pre><code>0:00:15.131059
</code></pre>
| [
{
"answer_id": 74388151,
"author": "hgrey",
"author_id": 1327386,
"author_profile": "https://Stackoverflow.com/users/1327386",
"pm_score": -1,
"selected": false,
"text": "itertools.islice"
},
{
"answer_id": 74388247,
"author": "Abdul Niyas P M",
"author_id": 6699447,
"author_profile": "https://Stackoverflow.com/users/6699447",
"pm_score": 3,
"selected": true,
"text": "static PyObject *\nlist_slice(PyListObject *a, Py_ssize_t ilow, Py_ssize_t ihigh)\n{\n PyListObject *np;\n PyObject **src, **dest;\n Py_ssize_t i, len;\n len = ihigh - ilow;\n if (len <= 0) {\n return PyList_New(0);\n }\n # create new list which is long enough to hold the slice length elements.\n np = (PyListObject *) list_new_prealloc(len);\n if (np == NULL)\n return NULL;\n # Adjust the pointer offset, because list internally uses an array of pointers.\n src = a->ob_item + ilow;\n dest = np->ob_item;\n # Copy the elements back.\n for (i = 0; i < len; i++) {\n PyObject *v = src[i];\n Py_INCREF(v);\n dest[i] = v;\n }\n Py_SET_SIZE(np, len);\n return (PyObject *)np;\n}\n"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74388015",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20280771/"
] |
74,388,032 | <p>I'd like to merge two DataFrams that contains two common columns. They have the same number of row and I know the order in both columns is the same, so they are already aligned.
My problem is that, after they've merged I'm left with more rows than I originally had.</p>
<p>Is there a way to merge these two DataFrames and keep the original number if rows?</p>
<pre><code>df1 = pd.DataFrame(
[
{"col1": 1, "col2": 1, "unique_df1_val": "value1"},
{"col1": 2, "col2": 2, "unique_df1_val": "value2"},
{"col1": 2, "col2": 2, "unique_df1_val": "value3"},
]
)
df2 = pd.DataFrame(
[
{"col1": 1, "col2": 1, "unique_df2_val": "value4"},
{"col1": 2, "col2": 2, "unique_df2_val": "value5"},
{"col1": 2, "col2": 2, "unique_df2_val": "value6"},
]
)
### Do some merge of the two ###
# Expected DataFrame
col1 col2 unique_df1_val unique_df2_val
0 1 1 value1 value4
1 2 2 value2 value5
2 2 2 value3 value6
</code></pre>
<p>I've tried using the df1.merge(df2, how="outer"), but this doesn't give me the correct output.</p>
<pre><code>df1.merge(df2, how="outer")
# Returns
col1 col2 unique_df1_val unique_df2_val
0 1 1 value1 value4
1 2 2 value2 value5
2 2 2 value2 value6
3 2 2 value3 value5
4 2 2 value3 value6
</code></pre>
| [
{
"answer_id": 74388068,
"author": "Carmoreno",
"author_id": 4508767,
"author_profile": "https://Stackoverflow.com/users/4508767",
"pm_score": 2,
"selected": false,
"text": "pd.concat"
},
{
"answer_id": 74388179,
"author": "Celius Stingher",
"author_id": 11897007,
"author_profile": "https://Stackoverflow.com/users/11897007",
"pm_score": 3,
"selected": true,
"text": "df1.join(df2,lsuffix='drop').drop(columns=[x+'drop' for x in df1.columns if x in df2.columns])\n"
},
{
"answer_id": 74388225,
"author": "mozway",
"author_id": 16343464,
"author_profile": "https://Stackoverflow.com/users/16343464",
"pm_score": 2,
"selected": false,
"text": "merge"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74388032",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19887308/"
] |
74,388,038 | <p>I used sticky as the navbar's position. it worked all the way until it hit the end of the about section.</p>
<p>I want the navbar to move with the scroll all the way until it reaches the top where it then becomes fixed throughout the remainder of the website.</p>
<p>I have an up-to-date version of chrome (107.0.5304.87) and according to
<a href="https://caniuse.com/?search=sticky" rel="nofollow noreferrer">https://caniuse.com/?search=sticky</a> the browser is compatible with 'sticky'.</p>
<p>I wondered whether display:flex and justify-content could be interfering (read that display:flex and position:absolute are not a good match) and took those away. Nothing changed.</p>
<p>current code:</p>
<pre><code><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="stylesheet" href="style.css">
<title id="title">Fantasy Book Covers</title>
</head>
<body>
<div class="black_background">
<div class="fadein_1">
<p id="beginning_quote">"Each touch...</p>
</div>
<div class="fadein_2">
<p id="ending_quote">brings the magic to life"</p>
</div>
<div class="intro_images">
<img src="https://www.dropbox.com/s/d5pcaukzdu8drjx/Pasted%20Graphic%2018.png?dl=1"/>
<img src="https://www.dropbox.com/s/1fdnhyueimm3xhu/Pasted%20Graphic%2016.png?dl=1"/>
<img src="https://www.dropbox.com/s/496kpiry8x30xzn/Pasted%20Graphic%2017.png?dl=1"/>
</div>
<section id="header">
<div id="nav_bar">
<p id="about">About</p>
<p id="service">Service</p>
<div id="home_button"></div>
<p id="faqs">FAQs</p>
<p id="contact">Contact</p>
</div>
</section>
<div class="about_section">
<p>We believe as fantasy-book enthusiasts that to truly experience the magic of a book, one must “feel” its essence. Our job is to transport you to magical worlds with our</p>
<p> <i>handmade, leather book covers.</i></p>
<p>Choose any book, from any author, and we will bring their story to life.</p>
</div>
<div class="traditional_section">
<div id="traditional_image"></div>
<div id="traditional_p">
<p id="traditional_title">Traditional</p>
<p id="lorem_1">Lorem ipsum dolor sit<br>amet,consectetur adipiscing <br>elit, sed do eiusmod tempor<br>incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.Duis aute irure dolor in reprehenderit in voluptate velit esse cillum</p>
</div>
</body>
</html>
</code></pre>
<pre><code>.black_background{
position: absolute;
margin-left:-2%;
margin-top:-2%;
width: 1461px;
height: 365px;
background: #000000;
}
.intro_images{
position: absolute;
display:flex;
max-width:5%;
height:25%;
left: 39%;
margin-top: 15%;
}
#beginning_quote{
margin-left: 20%;
margin-top: 8%;
font-family: Baskerville;
font-size: 48px;
color: #995DBE;
animation: animate;
}
#beginning_quote::first-letter{
font-size: 70px;
}
#ending_quote{
margin-left: 50%;
margin-top: -3%;
font-family: Baskerville;
font-size: 48px;
color: #DDA5FE;
}
.fadein_1{
animation: fadeIn 3s;
}
@keyframes fadeIn{
0%{opacity:0;}
100%{opacity:1;}
}
.fadein_2{
animation: fadeIn 3s;
}
@keyframes fadeIn{
0%{opacity:0;}
100%{opacity:1;}
}
#nav_bar{
margin-top: 33%;
display: flex;
justify-content: space-evenly;
font-family: Baskerville;
font-size: 20px;
background-color:white;
height:13%;
position: sticky;
top:0;
position: -webkit-sticky;
position: -moz-sticky;
position: -ms-sticky;
position: -o-sticky;
}
#about, #service, #faqs, #contact{
position: relative;
margin-top:0.9%;
}
.about_section{
color:black;
margin-top: 10%;
margin-left: 10%;
font-family:Baskerville;
font-size: 30px;
}
i{
font-size: 50px;
margin-left:20%;
}
.traditional_section{
background-color:rgba(36, 2, 56, 0.45);
width: 848px;
height: 524px;
margin-left: 21%;
margin-top: 20%;
}
</code></pre>
<p>I also tried JS version:</p>
<pre><code>const header = document.getElementById("header");
const navbar = document.getElementById("nav_bar");
window.onscroll = function(){
if(window.pageYOffset >= navbar.offsetTop){
navbar.classList.add("sticky");
}
else {
navbar.classList.remove("sticky");
}
};
</code></pre>
<pre><code>#nav_bar{
margin-top: 33%;
display: flex;
justify-content: space-evenly;
font-family: Baskerville;
font-size: 20px;
background-color:white;
height:13%;
}
.sticky{
position: sticky;
top:0;
left:0;
}
</code></pre>
<p>Again it worked until it hit the the end of the about section where it stopped working.</p>
<p>I am not familiar with jquery if that is what I have to use to make it work.
I would prefer not to use fixed position if there is a way to get it working.</p>
<p>Thanks!</p>
| [
{
"answer_id": 74388612,
"author": "Zeynep Evecen",
"author_id": 13856050,
"author_profile": "https://Stackoverflow.com/users/13856050",
"pm_score": 0,
"selected": false,
"text": "class=\"black_background\""
},
{
"answer_id": 74400903,
"author": "Julia",
"author_id": 20002701,
"author_profile": "https://Stackoverflow.com/users/20002701",
"pm_score": 1,
"selected": false,
"text": ".black_background{\nposition:relative;\nmargin-left:-2%;\nmargin-top:-1%;\nwidth: 1461px;\nheight: 365px;\nbackground: #000000;\n}\n\n#quote{\n position:absolute;\n margin-top: 1%;\n width:100%;\n}\n\n#beginning_quote{\nmargin-left: 20%;\nmargin-top: 8%;\nfont-family: Baskerville;\nfont-size: 48px;\ncolor: #995DBE;\nanimation: animate;\n}\n\n#beginning_quote::first-letter{\n font-size: 70px;\n}\n\n#ending_quote{\nmargin-left: 50%;\nmargin-top: -3%;\nfont-family: Baskerville;\nfont-size: 48px;\ncolor: #DDA5FE;\n}\n\n.fadein_1{\n animation: fadeIn 3s;\n}\n\n@keyframes fadeIn{\n0%{opacity:0;}\n100%{opacity:1;}\n}\n\n.fadein_2{\n animation: fadeIn 3s;\n}\n\n@keyframes fadeIn{\n0%{opacity:0;}\n100%{opacity:1;}\n}\n\n#nav_bar{\n position: relative;\n margin-top: 25%;\n display: flex;\n justify-content: space-evenly;\n font-family: Baskerville;\n font-size: 20px;\n background-color:white;\n height:13%;\n position:sticky;\n top:0;\n z-index:1;\n}\n\n#about, #service, #faqs, #contact{\n position: relative;\n margin-top:0.9%;\n}\n.about_section{\n position:relative;\n color:black;\n margin-top: 10%;\n margin-left: 10%;\n font-family:Baskerville;\n font-size: 30px;\n}\n\ni{\n font-size: 50px;\n margin-left:20%;\n}\n\n.traditional_section{\n background-color:rgba(36, 2, 56, 0.45);\n width: 848px;\n height: 524px;\n margin-left: 21%;\n margin-top:35%;\n}"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74388038",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20002701/"
] |
74,388,040 | <pre><code>I have such an issue running TwinCat3 with 2 PLCs - it starts time to time in CONFIG mode.
The OS is Win7 SP1
TC3 is in version 3.1.4022.16 but we also I've that with the same result on 3.1.4024.35 on 3 different machines.
In logs I have errors as below :
Port_852
11/10/2022 10:01:59 AM 816 ms
PLC: Timeout while checking file Plc\Port_852.autostart.
Init44\IO: Set State TComObj PREOP OP: Check for autostart >> AdsError: 1817 (0x719, ADS ERROR: device has a timeout)
Init44\IO: Set State TComObj PREOP OP: Check for autostart >> AdsError: 1804 (0x70c, ADS ERROR: not found (files, ...)) << failed%!
PLCs size is :
PLC1: Size of generated code: 500392 bytes
PLC2: Size of generated code: 1428418 bytes
</code></pre>
<p>Can this be related e.g. to PLS size ? 2nd one that fails to boot is 3rd time bigger.
Also i did the test and added 2 same PLCs with size 500392 bytes, and again 2nd one failed to load.</p>
<p>Did someone had same issue ?
Is the size can be the issue ?
Maybe I can tweak the timeouts somehow ?</p>
| [
{
"answer_id": 74388612,
"author": "Zeynep Evecen",
"author_id": 13856050,
"author_profile": "https://Stackoverflow.com/users/13856050",
"pm_score": 0,
"selected": false,
"text": "class=\"black_background\""
},
{
"answer_id": 74400903,
"author": "Julia",
"author_id": 20002701,
"author_profile": "https://Stackoverflow.com/users/20002701",
"pm_score": 1,
"selected": false,
"text": ".black_background{\nposition:relative;\nmargin-left:-2%;\nmargin-top:-1%;\nwidth: 1461px;\nheight: 365px;\nbackground: #000000;\n}\n\n#quote{\n position:absolute;\n margin-top: 1%;\n width:100%;\n}\n\n#beginning_quote{\nmargin-left: 20%;\nmargin-top: 8%;\nfont-family: Baskerville;\nfont-size: 48px;\ncolor: #995DBE;\nanimation: animate;\n}\n\n#beginning_quote::first-letter{\n font-size: 70px;\n}\n\n#ending_quote{\nmargin-left: 50%;\nmargin-top: -3%;\nfont-family: Baskerville;\nfont-size: 48px;\ncolor: #DDA5FE;\n}\n\n.fadein_1{\n animation: fadeIn 3s;\n}\n\n@keyframes fadeIn{\n0%{opacity:0;}\n100%{opacity:1;}\n}\n\n.fadein_2{\n animation: fadeIn 3s;\n}\n\n@keyframes fadeIn{\n0%{opacity:0;}\n100%{opacity:1;}\n}\n\n#nav_bar{\n position: relative;\n margin-top: 25%;\n display: flex;\n justify-content: space-evenly;\n font-family: Baskerville;\n font-size: 20px;\n background-color:white;\n height:13%;\n position:sticky;\n top:0;\n z-index:1;\n}\n\n#about, #service, #faqs, #contact{\n position: relative;\n margin-top:0.9%;\n}\n.about_section{\n position:relative;\n color:black;\n margin-top: 10%;\n margin-left: 10%;\n font-family:Baskerville;\n font-size: 30px;\n}\n\ni{\n font-size: 50px;\n margin-left:20%;\n}\n\n.traditional_section{\n background-color:rgba(36, 2, 56, 0.45);\n width: 848px;\n height: 524px;\n margin-left: 21%;\n margin-top:35%;\n}"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74388040",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20467650/"
] |
74,388,072 | <p>I'm try to sum columns(F2:F) in multiple sheets.</p>
<p>Here's my current formula.</p>
<p><code>=ARRAYFORMULA(IF(ISBLANK($A$2:$A), ,QUERY({PROPER(FLATTEN(Romar!$B$2:$B, Angelo!$B$2:$B, Ayyan!$B$2:$B, Edwin!$B$2:$B)), FLATTEN(Romar!$F$2:$F, Angelo!$F$2:$F, Ayyan!$F$2:$F, Edwin!$F$2:$F)}, "SELECT SUM(Col2) WHERE Col1 = '" & $A$2:$A & "' LABEL SUM(Col2) ''")))</code></p>
<p>But it gives me the same result in the entire column.</p>
<p><a href="https://i.stack.imgur.com/ucNrv.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ucNrv.png" alt="enter image description here" /></a></p>
<p>I want the result to be the sum of the person in column(A2:A) each row.</p>
<p><a href="https://i.stack.imgur.com/dl9Or.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/dl9Or.png" alt="enter image description here" /></a></p>
<p>Thank you!</p>
<p>Here's the sample sheet. The desired result should be the total amount released for the customer at A2:A.</p>
<p><a href="https://docs.google.com/spreadsheets/d/1b3bFQzaOk2z3GAUh7mDEjBCmyRgDhbf8tpNDYX60QN8/edit?usp=sharing" rel="nofollow noreferrer">https://docs.google.com/spreadsheets/d/1b3bFQzaOk2z3GAUh7mDEjBCmyRgDhbf8tpNDYX60QN8/edit?usp=sharing</a></p>
| [
{
"answer_id": 74396821,
"author": "player0",
"author_id": 5632629,
"author_profile": "https://Stackoverflow.com/users/5632629",
"pm_score": 3,
"selected": true,
"text": "=BYROW(A2:A, LAMBDA(x, IF(ISBLANK(x),, IFERROR(\n SUM(FILTER({Romar!F:F; Angelo!F:F; Ayyan!F:F; Edwin!F:F}, \n {Romar!B:B; Angelo!B:B; Ayyan!B:B; Edwin!B:B}=x)), 0))))\n"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74388072",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19664060/"
] |
74,388,085 | <p>I've this:</p>
<pre><code>"example: myresult"
</code></pre>
<p>And I need a method that looks for this from ": "</p>
<pre><code>"myresult"
</code></pre>
<p>I tried with String.search()</p>
| [
{
"answer_id": 74388135,
"author": "Naveen",
"author_id": 16260451,
"author_profile": "https://Stackoverflow.com/users/16260451",
"pm_score": 1,
"selected": true,
"text": "function getSecondPart(str) {\n return str.split(':')[1];\n}\n"
},
{
"answer_id": 74388142,
"author": "BugsNRoses",
"author_id": 18306645,
"author_profile": "https://Stackoverflow.com/users/18306645",
"pm_score": -1,
"selected": false,
"text": "'string'.includes(':')\n"
},
{
"answer_id": 74388180,
"author": "Evgeni Dikerman",
"author_id": 1761692,
"author_profile": "https://Stackoverflow.com/users/1761692",
"pm_score": 1,
"selected": false,
"text": "string.includes(searchString, position)"
},
{
"answer_id": 74388191,
"author": "Diego D",
"author_id": 1221208,
"author_profile": "https://Stackoverflow.com/users/1221208",
"pm_score": 0,
"selected": false,
"text": "const subject = \"example: myresult\";\nconst re = /^.+?\\: (.+)$/im;\nconst match = re.exec(subject);\nlet result = \"\";\nif (match !== null) {\n result = match[1]; \n}\n\nconsole.log(result);"
},
{
"answer_id": 74388267,
"author": "solarroi",
"author_id": 4244234,
"author_profile": "https://Stackoverflow.com/users/4244234",
"pm_score": 0,
"selected": false,
"text": "var myresult = \"example: myresult\";\nconsole.log(myresult.split(': ')[1]);"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74388085",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20439814/"
] |
74,388,091 | <p>I wrote a class like which has 3 hidden attributres:</p>
<pre><code>class Car():
def __init__(self, name, model, brand):
self.__name = name
self.__model = model
self.__brand = brand
</code></pre>
<p>Is that possible to create a method for this class to set a new attribute (publisher)?
I wrote this one, but I didn't get result:</p>
<pre><code> def set_publisher(self, publisher):
self.__publisher = publisher
b1 = Car(name="X", model="Y", brand="Z")
publisher="D"
b1.set_publisher(publisher)
</code></pre>
<p>Error:</p>
<pre><code>AttributeError: 'Car' object has no attribute 'set_publisher'
</code></pre>
| [
{
"answer_id": 74388164,
"author": "Cuartero",
"author_id": 17901307,
"author_profile": "https://Stackoverflow.com/users/17901307",
"pm_score": -1,
"selected": false,
"text": "setattr"
},
{
"answer_id": 74388936,
"author": "chepner",
"author_id": 1126841,
"author_profile": "https://Stackoverflow.com/users/1126841",
"pm_score": 0,
"selected": false,
"text": "set_publisher"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74388091",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16356219/"
] |
74,388,107 | <p>currently the logs in the folder “/engine-rocksdb/journals” are running full (WAL logs).</p>
<p>When does ArangoDB do a cleaning run of these logs and delete them automatically and how to trigger this cleaning run earlier? My ArangoDB 3.10 runs in single mode and in a virtual environment (cloud with a network storage).</p>
<p>The logfile are increasing very fast for me because there are many writes to the DB. What is the best way, any idea?</p>
<p>What I have done so far:</p>
<p>If I set the value “rocksdb.wal-archive-size-limit” it does delete the logs when the set limit is reached, but it shows errors in the logfile:</p>
<p><code>2022-09-27T17:53:04Z [898948] WARNING [d9793] {engines} forcing removal of RocksDB WAL file '/archive/813371.log' with start sequence 5387062892 because of overflowing archive. configured maximum archive size is 1073741824, actual archive size is: 75401520</code></p>
<p>However, I still don't understand the meaning of the logfile output: "configured maximum archive size is 1073741824, actual archive size is: 75401520`". The "actual archive size" is smaller?</p>
<p>But what are the consequences of lowering the "wal-archive-size-limit" value? Is it possible to switch off the wal-archive completely. What exactly is it for? As I understand it, ArangoDb need it for transaction security (i.e. in case of power loss), right?</p>
<p>In general, yes, this is a good thing, but how can I get ArangoDb to a) limit this WAL-archive (without error massages) and b) do a cleaning run faster?</p>
<p>thx :-)</p>
| [
{
"answer_id": 74482688,
"author": "stj",
"author_id": 3042070,
"author_profile": "https://Stackoverflow.com/users/3042070",
"pm_score": 2,
"selected": false,
"text": "--rocksdb.wal-file-timeout-initial"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74388107",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13737521/"
] |
74,388,162 | <p>I have created this views but I can't get it to work in my database. Does this look alright?
I have to provide this views see below.
All flight reservations made by John Smith including, for those flights that have flown, the duration of the flight.</p>
<pre><code>CREATE VIEW ViewA AS
SELECT F.FlightID, (F.ArrivalTime-F.DepartTime) As FlightDuration
FROM FLIGHT as F
INNER JOIN RESERVATION as R
ON A.FlightID = R.FlightID
INNER JOIN CUSTOMER as C
ON C.CustomerID = R.CustomerID
WHERE F.DepartTime < Convert(Time, GetDate())
AND C.FirstName = ‘John’
AND C.LastName = ‘Smith’;
</code></pre>
<p>If I run this is says SQL command not properly ended! What am I doing wrong please help?</p>
| [
{
"answer_id": 74388281,
"author": "Littlefoot",
"author_id": 9097906,
"author_profile": "https://Stackoverflow.com/users/9097906",
"pm_score": 2,
"selected": false,
"text": "CREATE OR REPLACE VIEW viewa\nAS\n SELECT f.flightid, (f.arrivaltime - f.departtime) AS flightduration\n FROM flight f\n INNER JOIN reservation r ON a.flightid = r.flightid\n INNER JOIN customer c ON c.customerid = r.customerid\n WHERE f.departtime < SYSDATE\n AND c.firstname = 'John'\n AND c.lastname = 'Smith';\n"
},
{
"answer_id": 74388306,
"author": "Jack D",
"author_id": 19159150,
"author_profile": "https://Stackoverflow.com/users/19159150",
"pm_score": 0,
"selected": false,
"text": "'GetDate()) AND C.FirstName = ‘ John ’ AND C.LastName = ‘ Smith ’'\n"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74388162",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20462352/"
] |
74,388,203 | <p>I have been writing a <code>is_palindrome(int num)</code> function which takes an integer and return true or false. I got the idea of reversing the integer and then check it with the original. To do that I need an extra <code>reverse()</code> function. But I want to know if there is a way of checking the palindrome using only one recursive function.</p>
| [
{
"answer_id": 74388408,
"author": "BambooleanLogic",
"author_id": 1701776,
"author_profile": "https://Stackoverflow.com/users/1701776",
"pm_score": 2,
"selected": true,
"text": "function is_palindrome(i) {\n if (i is a single-digit number) return true\n x = first digit of i\n y = last digit of i\n if (x != y) return false\n if (i is a two-digit number) return true\n j = i without the first and last digit\n return is_palindrome(j)\n}\n"
},
{
"answer_id": 74388659,
"author": "Laurent LA RIZZA",
"author_id": 2071258,
"author_profile": "https://Stackoverflow.com/users/2071258",
"pm_score": 0,
"selected": false,
"text": "bool is_palindrome_impl(int number, int radix, int highest_digit_divider) {\n // First check if the number has 1 digit, in which case\n // it is a palindrome.\n if(highest_digit_divider < radix) { return true; }\n\n // Then check if the highest digit is different from the lowest digit,\n // in which case it is NOT a palindrome.\n const int highest_digit = number / highest_digit_divider;\n const int lowest_digit = number % radix;\n if(highest_digit != lowest_digit) { return false; }\n\n // Then check whether the inner part is a palindrome\n const int inner_part = (number % highest_digit_divider) / radix;\n return is_palindrome_impl(inner_part, radix, highest_digit_divider / radix / radix);\n}\n"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74388203",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12741290/"
] |
74,388,224 | <p>I do not want the modal to be closed when reset is clicked.
It should just reset the inner form.
But my code is closing the modal.</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><!doctype html>
<html lang="en">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-Zenh87qX5JnK2Jl0vWa8Ck2rdkQ2Bzep5IDxbcnCeuOxjzrPF/et3URy9Bv1WTRi" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-OERcA2EqjJCMA+/3y+gxIOqMEjwtxJY7qPCqsdltbNJuaOe923+mo//f6V8Qbsw3" crossorigin="anonymous"></script>
</head>
<body>
<div class="modal fade" id="messagemodal" tabindex="-1">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Modal title</h5>
<button type="button" class="btn-close" aria-label="Close"></button>
</div>
<div class="modal-body">
<p>Modal body text goes here.
<form action="/action_page.php">
<label for="fname">First name:</label><br>
<input type="text" id="fname" name="fname" value="John"><br>
<label for="lname">Last name:</label><br>
<input type="text" id="lname" name="lname" value="Doe"><br>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal" onclick="$('form').trigger('reset');return false;">Reset</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
<script>
var modal = new bootstrap.Modal(document.getElementById('messagemodal'), {
keyboard: false
});
modal.show();
</script>
</body></code></pre>
</div>
</div>
</p>
| [
{
"answer_id": 74388408,
"author": "BambooleanLogic",
"author_id": 1701776,
"author_profile": "https://Stackoverflow.com/users/1701776",
"pm_score": 2,
"selected": true,
"text": "function is_palindrome(i) {\n if (i is a single-digit number) return true\n x = first digit of i\n y = last digit of i\n if (x != y) return false\n if (i is a two-digit number) return true\n j = i without the first and last digit\n return is_palindrome(j)\n}\n"
},
{
"answer_id": 74388659,
"author": "Laurent LA RIZZA",
"author_id": 2071258,
"author_profile": "https://Stackoverflow.com/users/2071258",
"pm_score": 0,
"selected": false,
"text": "bool is_palindrome_impl(int number, int radix, int highest_digit_divider) {\n // First check if the number has 1 digit, in which case\n // it is a palindrome.\n if(highest_digit_divider < radix) { return true; }\n\n // Then check if the highest digit is different from the lowest digit,\n // in which case it is NOT a palindrome.\n const int highest_digit = number / highest_digit_divider;\n const int lowest_digit = number % radix;\n if(highest_digit != lowest_digit) { return false; }\n\n // Then check whether the inner part is a palindrome\n const int inner_part = (number % highest_digit_divider) / radix;\n return is_palindrome_impl(inner_part, radix, highest_digit_divider / radix / radix);\n}\n"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74388224",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5549354/"
] |
74,388,347 | <p>I have a dropdown list with values and i am getting this error message when trying to select the values (cannot share the link because it is hidden):</p>
<pre><code>Element: [[[[ChromeDriver: chrome on WINDOWS (4aeb1bf64ec7a13956b6b0b2cf24d9ca)] -> xpath: //*[@id="Datatable_ReceiptListModel"]/tbody/tr[3]/td[10]/select]] -> xpath: .//option[normalize-space(.) = "Option 1"]]
</code></pre>
<p>The HTML for that dropdown is:</p>
<pre><code><select class="select-submotive inputs-table hide-in-partial" style="visibility: visible;">
<option value="">Seleccione...</option>
<option value="5">Option 1</option>
<option value="6">Option 2</option>
</select>
</code></pre>
<p>The XPATH is:</p>
<pre><code>//*[@id="Datatable_ReceiptListModel"]/tbody/tr[1]/td[10]/select
</code></pre>
<p>I did this:</p>
<pre><code> Select dropdown736 = new Select(driver.findElement(By.xpath("//*[@id=\"Datatable_ReceiptListModel\"]/tbody/tr[3]/td[10]/select")));
dropdown736.selectByVisibleText("Option 1");
</code></pre>
<p>Am i doing anything wrong?</p>
| [
{
"answer_id": 74388408,
"author": "BambooleanLogic",
"author_id": 1701776,
"author_profile": "https://Stackoverflow.com/users/1701776",
"pm_score": 2,
"selected": true,
"text": "function is_palindrome(i) {\n if (i is a single-digit number) return true\n x = first digit of i\n y = last digit of i\n if (x != y) return false\n if (i is a two-digit number) return true\n j = i without the first and last digit\n return is_palindrome(j)\n}\n"
},
{
"answer_id": 74388659,
"author": "Laurent LA RIZZA",
"author_id": 2071258,
"author_profile": "https://Stackoverflow.com/users/2071258",
"pm_score": 0,
"selected": false,
"text": "bool is_palindrome_impl(int number, int radix, int highest_digit_divider) {\n // First check if the number has 1 digit, in which case\n // it is a palindrome.\n if(highest_digit_divider < radix) { return true; }\n\n // Then check if the highest digit is different from the lowest digit,\n // in which case it is NOT a palindrome.\n const int highest_digit = number / highest_digit_divider;\n const int lowest_digit = number % radix;\n if(highest_digit != lowest_digit) { return false; }\n\n // Then check whether the inner part is a palindrome\n const int inner_part = (number % highest_digit_divider) / radix;\n return is_palindrome_impl(inner_part, radix, highest_digit_divider / radix / radix);\n}\n"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74388347",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14012751/"
] |
74,388,350 | <p>I am trying to count the number of populated rows in Excel, but excluding the first row as this is used as a header. ie. I want to start counting from the second row.</p>
<p>The following works to count populated rows, including the first row:</p>
<pre><code>=COUNTIF(Books!A:A, "<>")
</code></pre>
<p>Logically, this is what I want, but it doesn't work in Excel:</p>
<pre><code>=COUNTIF(Books!A2:A, "<>")
</code></pre>
<p>Seems like this should be simple? Am I missing something obvious? Thanks in advance!</p>
| [
{
"answer_id": 74388496,
"author": "Toby_Stoe",
"author_id": 19735003,
"author_profile": "https://Stackoverflow.com/users/19735003",
"pm_score": 2,
"selected": true,
"text": "=COUNTIF(Books!A2:A1048576;\"<>\")\n"
},
{
"answer_id": 74388543,
"author": "Foxfire And Burns And Burns",
"author_id": 9199828,
"author_profile": "https://Stackoverflow.com/users/9199828",
"pm_score": -1,
"selected": false,
"text": "=COUNTIF(Books!A2:A20, \"<>\")\n"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74388350",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2862135/"
] |
74,388,353 | <p>I've deleted CRA and configured webpack/babel on my own. Now I have problems with dynamic imports.</p>
<p><a href="https://i.stack.imgur.com/CRAWr.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/CRAWr.png" alt="error" /></a></p>
<p>This works fine:</p>
<pre><code>import("./" + "CloudIcon" + ".svg")
.then(file => {
console.log(file);
})
</code></pre>
<p>This doesn't work:</p>
<pre><code>const name = 'CloudIcon';
import("./" + name + ".svg")
.then(file => {
console.log(file);
})
</code></pre>
<p>I've tried to export files with different types. It didn't work.
Have tried to use Webpack Magic Comments, but didn't help either.</p>
<p>I suppose, that something is wrong with my webpack/babel settings, but what?</p>
<p>babel.config.js:</p>
<pre><code>const plugins = [
"@babel/syntax-dynamic-import",
["@babel/plugin-transform-runtime"],
"@babel/transform-async-to-generator",
"@babel/plugin-proposal-class-properties"
];
if (process.env.NODE_ENV === 'development') {
plugins.push('react-refresh/babel');
}
module.exports = {
presets: [[
"@babel/preset-env", {
"debug": false,
"modules": false,
"useBuiltIns": false
}],
['@babel/preset-react', {throwIfNamespace: false}],
'@babel/preset-typescript'
],
plugins,
};
</code></pre>
<p>webpack.config.js:</p>
<pre><code>require('dotenv').config();
const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const ReactRefreshWebpackPlugin = require('@pmmmwh/react-refresh-webpack-plugin');
const webpack = require('webpack');
const reactAppVars = (() => {
const obj = {};
for (let key in process.env) {
if (key.startsWith('REACT_APP_')) obj[key] = process.env[key];
}
return obj;
})();
const target = process.env['NODE_ENV'] === 'production' ? 'browserslist' : 'web';
const plugins = [
new webpack.EnvironmentPlugin({'NODE_ENV': process.env['NODE_ENV'], 'PUBLIC_URL': '', ...reactAppVars}),
new HtmlWebpackPlugin({template: path.resolve(__dirname, '../public/index.html')}),
new MiniCssExtractPlugin({filename: '[name].[contenthash].css'}),
new webpack.ProvidePlugin({process: 'process/browser'}),
new webpack.ProvidePlugin({"React": "react"}),
];
if (process.env['SERVE']) plugins.push(new ReactRefreshWebpackPlugin());
const proxy = {
//Proxy settings
}
module.exports = {
entry: "./src/index.js",
output: {
filename: "main.js",
path: path.resolve(__dirname, "../build"),
assetModuleFilename: '[path][name].[ext]'
},
plugins,
devtool: 'source-map',
devServer: {
static: {
directory: path.resolve(__dirname, "../public"),
},
proxy,
port: 9999,
hot: true,
},
module: {
rules: [
{ test: /\.(html)$/, use: ['html-loader'] },
{
test: /\.(s[ac]|c)ss$/i,
use: [
MiniCssExtractPlugin.loader,
'css-loader',
'postcss-loader',
'sass-loader'
]
},
{
test: /\.less$/i,
use: [
MiniCssExtractPlugin.loader,
'css-loader',
'postcss-loader',
{
loader: 'less-loader',
options: {
lessOptions: {
javascriptEnabled: true
}
}
}
]
},
{
test: /\.(png|jpe?g|gif|webp|ico)$/i,
type: process.env['NODE_ENV'] === 'production' ? 'asset' : 'asset/resource'
},
{
test: /\.svg$/i,
issuer: /\.[jt]sx?$/,
use: ['@svgr/webpack', {
loader: 'file-loader',
options: {
name: '[path][name].[ext]'
}
}],
},
{
test: /\.(woff2?|eot|ttf|otf)$/i,
type: process.env['NODE_ENV'] === 'production' ? 'asset' : 'asset/resource'
},
{
test: /\.jsx?$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
cacheDirectory: true,
}
}
},
{
test: /\.([cm]?ts|tsx)$/,
use: {
loader: "babel-loader",
options: {
presets: [
"@babel/preset-env",
"@babel/preset-react",
"@babel/preset-typescript",
]
}
}
},
{
test: /\.md$/,
loader: "raw-loader"
},
],
},
resolve: {
'roots': [path.resolve('./src')],
'extensions': ['', '.js', '.jsx', '.ts', '.tsx'],
extensionAlias: {
".js": [".js", ".ts"],
".cjs": [".cjs", ".cts"],
".mjs": [".mjs", ".mts"]
},
fallback: {
'process/browser': require.resolve('process/browser')
}
},
mode: process.env['NODE_ENV'],
target
}
</code></pre>
| [
{
"answer_id": 74388496,
"author": "Toby_Stoe",
"author_id": 19735003,
"author_profile": "https://Stackoverflow.com/users/19735003",
"pm_score": 2,
"selected": true,
"text": "=COUNTIF(Books!A2:A1048576;\"<>\")\n"
},
{
"answer_id": 74388543,
"author": "Foxfire And Burns And Burns",
"author_id": 9199828,
"author_profile": "https://Stackoverflow.com/users/9199828",
"pm_score": -1,
"selected": false,
"text": "=COUNTIF(Books!A2:A20, \"<>\")\n"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74388353",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14313523/"
] |
74,388,382 | <p>I am running several calculations and ML algorithms in R and store their results in four distinctive tables.
For each calculation, I obtain four tables, which I store in a single list.
According to R, all of my lists are labelled as "Large List (4 elements, 971.2 kB)" in the upper right quadrant in RStudio where all my objects, functions, etc. are displayed.
I have five of these lists and save them for later use with the save() function.</p>
<p>I use the function:</p>
<p><code>save(list1, list2, list3, list4, list5, file="mypath/mylists.RData")</code></p>
<p>For some reason, which I do not understand, R takes more than 24 hours to save these four lists with only 971.2 kB each.
Maybe, I should add that apparently more than 10GB of my RAM are used by R at the time. However, the lists are as small as I indicated above.</p>
<p>Does anyone have an idea why it takes so long to save the lists to my harddrive and what I could do about it?</p>
<p>Thank you</p>
| [
{
"answer_id": 74391627,
"author": "user2554330",
"author_id": 2554330,
"author_profile": "https://Stackoverflow.com/users/2554330",
"pm_score": 2,
"selected": false,
"text": "F <- function () {\n X <- rnorm(1000000)\n Y ~ z\n}\n"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74388382",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10695249/"
] |
74,388,423 | <p>I feel like I have a super easy question but for the life of me I can't find it when googling or searching here (or I don't know the correct terms to find a solution) so here goes.</p>
<p>I have a large amount of text in R in which I want to identify all numbers/digits, and add a specific number to them, for example 5.</p>
<p>So just as a small example, if this were my text:</p>
<pre><code>text <- c("Hi. It is 6am. I want to leave at 7am")
</code></pre>
<p>I want the output to be:</p>
<pre><code>> text
[1] "Hi. It is 11am. I want to leave at 12am"
</code></pre>
<p>But also I need the addition for each individual digit, so if this is the text:</p>
<pre><code>text <- c("Hi. It is 2017. I am 35 years old.")
</code></pre>
<p>...I want the output to be:</p>
<pre><code>> text
[1] "Hi. It is 75612. I am 810 years old."
</code></pre>
<p>I have tried 'grabbing' the numbers from the string and adding 5, but I don't know how to then get them back into the original string so I can get the full text back.</p>
<p>How should I go about this? Thanks in advance!</p>
| [
{
"answer_id": 74388736,
"author": "AndS.",
"author_id": 9778513,
"author_profile": "https://Stackoverflow.com/users/9778513",
"pm_score": 1,
"selected": false,
"text": "gsubfn"
},
{
"answer_id": 74401200,
"author": "teambigfoot",
"author_id": 20467805,
"author_profile": "https://Stackoverflow.com/users/20467805",
"pm_score": 0,
"selected": false,
"text": "text1 <- c(\"Hi. It is 2017. I am 35 years old.\")\ntext2 <- c(\"Hi. It is 6am. I want to leave at 7am\")\n\nchange_number <- function(text, change, sign){ \n string_change <- glue::glue(\"`(\\\\1{sign}{change})`\")\n gsub(\"(\\\\d)\", string_change, text, perl = TRUE) %>%\n gsubfn::fn$c() }\n\nchange_number(text = text1, change = 5, sign = \"+\")\n#>[1] \"Hi. It is 75612. I am 810 years old.\"\n\nchange_number(text = text2, change = 5, sign = \"+\")\n#>[1] \"Hi. It is 11am. I want to leave at 12am\"\n"
},
{
"answer_id": 74401394,
"author": "sindri_baldur",
"author_id": 4552295,
"author_profile": "https://Stackoverflow.com/users/4552295",
"pm_score": 0,
"selected": false,
"text": "add_n = \\(x, n, by_digit = FALSE) {\n if (by_digit) ptrn = \"[0-9]\" else ptrn = \"[0-9]+\"\n tmp = gregexpr(ptrn, x)\n raw = regmatches(x, gregexpr(ptrn, x))\n raw_plusn = lapply(raw, \\(x) as.integer(x) + n)\n for (i in seq_along(x)) regmatches(x[i], tmp[i]) = raw_plusn[i]\n x\n}\n\ntext = c(\n \"Hi. It is 6am. I want to leave at 7am\", \n \"wow it's 505 dollars and 19 cents\",\n \"Hi. It is 2017. I am 35 years old.\"\n)\n\n> add_n(text, 5)\n# [1] \"Hi. It is 11am. I want to leave at 12am\"\n# [2] \"wow it's 510 dollars and 24 cents\" \n# [3] \"Hi. It is 2022. I am 40 years old.\" \n\n> add_n(text, -2)\n# [1] \"Hi. It is 4am. I want to leave at 5am\" \"wow it's 503 dollars and 17 cents\" \n# [3] \"Hi. It is 2015. I am 33 years old.\" \n\n> add_n(text, 5, by_digit = TRUE)\n# [1] \"Hi. It is 11am. I want to leave at 12am\"\n# [2] \"wow it's 10510 dollars and 614 cents\" \n# [3] \"Hi. It is 75612. I am 810 years old.\" \n"
},
{
"answer_id": 74429031,
"author": "Chris Ruehlemann",
"author_id": 8039978,
"author_profile": "https://Stackoverflow.com/users/8039978",
"pm_score": 0,
"selected": false,
"text": "tidyverse"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74388423",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20467805/"
] |
74,388,436 | <p>I have got a object called curNode like this</p>
<pre><code>{
"name": "CAMPAIGN",
"attributes": {},
"children": []
}
</code></pre>
<p>I am trying to push to the object as shown below</p>
<pre><code>curNode!.children!.push({
name: newNodeName,
children: [],
});
</code></pre>
<p>I get the below error</p>
<pre><code>TypeError: Cannot add property 0, object is not extensible
at Array.push (<anonymous>)
</code></pre>
| [
{
"answer_id": 74388736,
"author": "AndS.",
"author_id": 9778513,
"author_profile": "https://Stackoverflow.com/users/9778513",
"pm_score": 1,
"selected": false,
"text": "gsubfn"
},
{
"answer_id": 74401200,
"author": "teambigfoot",
"author_id": 20467805,
"author_profile": "https://Stackoverflow.com/users/20467805",
"pm_score": 0,
"selected": false,
"text": "text1 <- c(\"Hi. It is 2017. I am 35 years old.\")\ntext2 <- c(\"Hi. It is 6am. I want to leave at 7am\")\n\nchange_number <- function(text, change, sign){ \n string_change <- glue::glue(\"`(\\\\1{sign}{change})`\")\n gsub(\"(\\\\d)\", string_change, text, perl = TRUE) %>%\n gsubfn::fn$c() }\n\nchange_number(text = text1, change = 5, sign = \"+\")\n#>[1] \"Hi. It is 75612. I am 810 years old.\"\n\nchange_number(text = text2, change = 5, sign = \"+\")\n#>[1] \"Hi. It is 11am. I want to leave at 12am\"\n"
},
{
"answer_id": 74401394,
"author": "sindri_baldur",
"author_id": 4552295,
"author_profile": "https://Stackoverflow.com/users/4552295",
"pm_score": 0,
"selected": false,
"text": "add_n = \\(x, n, by_digit = FALSE) {\n if (by_digit) ptrn = \"[0-9]\" else ptrn = \"[0-9]+\"\n tmp = gregexpr(ptrn, x)\n raw = regmatches(x, gregexpr(ptrn, x))\n raw_plusn = lapply(raw, \\(x) as.integer(x) + n)\n for (i in seq_along(x)) regmatches(x[i], tmp[i]) = raw_plusn[i]\n x\n}\n\ntext = c(\n \"Hi. It is 6am. I want to leave at 7am\", \n \"wow it's 505 dollars and 19 cents\",\n \"Hi. It is 2017. I am 35 years old.\"\n)\n\n> add_n(text, 5)\n# [1] \"Hi. It is 11am. I want to leave at 12am\"\n# [2] \"wow it's 510 dollars and 24 cents\" \n# [3] \"Hi. It is 2022. I am 40 years old.\" \n\n> add_n(text, -2)\n# [1] \"Hi. It is 4am. I want to leave at 5am\" \"wow it's 503 dollars and 17 cents\" \n# [3] \"Hi. It is 2015. I am 33 years old.\" \n\n> add_n(text, 5, by_digit = TRUE)\n# [1] \"Hi. It is 11am. I want to leave at 12am\"\n# [2] \"wow it's 10510 dollars and 614 cents\" \n# [3] \"Hi. It is 75612. I am 810 years old.\" \n"
},
{
"answer_id": 74429031,
"author": "Chris Ruehlemann",
"author_id": 8039978,
"author_profile": "https://Stackoverflow.com/users/8039978",
"pm_score": 0,
"selected": false,
"text": "tidyverse"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74388436",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9932078/"
] |
74,388,445 | <p>I am using Zivid.NET, Halcon.NET and ML.NET together. Zivid provides me with a 3D byte array (row, column, channel), Halcon uses <code>HImages</code>/<code>HObjects</code>, ML.NET functionality expects a 1D byte array (same as <code>File.ReadAllBytes()</code>)</p>
<p>So far I used a workaround where:</p>
<ol>
<li>I <code>save()</code>'d Zivid's <code>imageRGBA</code> as a PNG,</li>
<li>which I read with Halcon's <code>read_image()</code> that gives me a <code>HObject</code>.</li>
<li>After some graphical work I saved the <code>HObject</code> again as a PNG using <code>write_image()</code>.</li>
<li>Using <code>File.ReadAllBytes()</code> to read that PNG I get the <code>byte[]</code> that my ML.NET functionalities expect.</li>
</ol>
<p>But this is far from ideal with larger amounts of data.</p>
<p>What I need is:</p>
<ol>
<li>a way to convert <code>byte[r,c,c]</code> images to <code>HObject</code>/<code>HImage</code>.</li>
<li>a way to convert <code>HObject</code>/<code>HImage</code> images to <code>byte[]</code>.</li>
</ol>
<p>Halcon's <a href="https://www.mvtec.com/doc/halcon/13/en/read_image.html" rel="nofollow noreferrer"><code>read_image()</code></a> and <a href="https://www.mvtec.com/doc/halcon/13/en/write_image.html" rel="nofollow noreferrer"><code>write_image()</code></a> don't seem to have any options for this and I haven't found anything helpful so far.</p>
| [
{
"answer_id": 74390827,
"author": "Vladimir Perković",
"author_id": 482036,
"author_profile": "https://Stackoverflow.com/users/482036",
"pm_score": 1,
"selected": false,
"text": "public HImage(string type, int width, int height, IntPtr pixelPointer)\n"
},
{
"answer_id": 74446400,
"author": "Malinko",
"author_id": 15335754,
"author_profile": "https://Stackoverflow.com/users/15335754",
"pm_score": 0,
"selected": false,
"text": "var byteArr = imgRGBA.ToByteArray();\n\nbyte[,] redByteArray = new byte[1200, 1920];\nbyte[,] greenByteArray = new byte[1200, 1920];\nbyte[,] blueByteArray = new byte[1200, 1920];\n\nfor (int row = 0; row < 1200; row++)\n for (int col = 0; col < 1920; col++)\n {\n redByteArray[row, col] = byteArr[row, col, 0];\n greenByteArray[row, col] = byteArr[row, col, 1];\n blueByteArray[row, col] = byteArr[row, col, 2];\n }\n\nGCHandle pinnedArray_red = GCHandle.Alloc(redByteArray, GCHandleType.Pinned);\nIntPtr pointer_red = pinnedArray_red.AddrOfPinnedObject();\n\nGCHandle pinnedArray_green = GCHandle.Alloc(greenByteArray, GCHandleType.Pinned);\nIntPtr pointer_green = pinnedArray_green.AddrOfPinnedObject();\n\nGCHandle pinnedArray_blue = GCHandle.Alloc(blueByteArray, GCHandleType.Pinned);\nIntPtr pointer_blue = pinnedArray_blue.AddrOfPinnedObject();\n\nGenImage3(out HObject imgHImage, \"byte\", 1920, 1200, pointer_red, pointer_green, pointer_blue);\n\npinnedArray_red.Free();\npinnedArray_green.Free();\npinnedArray_blue.Free();\n"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74388445",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15335754/"
] |
74,388,462 | <p>I am binding to an appsettings config section in my host build using the following:-</p>
<pre><code>services.Configure<MySettings1>(hostContext.Configuration.GetSection("TheSection"));
</code></pre>
<p>I only want to bind one section, but the actual type I want to bind to is dependent on a string variable myTypeName and it could be one of 3 types - MySettings1, MySettings2 or MySettings3.</p>
<p>So what i want to do is (which i know is not possible):-</p>
<pre><code>var myTypeName = Environment.GetEnvironmentVariable("MY_TYPE_NAME");
services.Configure<myTypeName>(hostContext.Configuration.GetSection("TheSection"));
</code></pre>
<p>The section can have different structures for each of the three types and it can be called TheSection or something different for each type (that bit is ok as it is already a string).</p>
<p>I couldn't see any overloads for the Configure method in the ms docs that don't require a type, but i am no expert in generics so was hoping someone could point me in the right direction (or alternatively, tell me i shouldn't do this coz of xyz :).</p>
| [
{
"answer_id": 74390827,
"author": "Vladimir Perković",
"author_id": 482036,
"author_profile": "https://Stackoverflow.com/users/482036",
"pm_score": 1,
"selected": false,
"text": "public HImage(string type, int width, int height, IntPtr pixelPointer)\n"
},
{
"answer_id": 74446400,
"author": "Malinko",
"author_id": 15335754,
"author_profile": "https://Stackoverflow.com/users/15335754",
"pm_score": 0,
"selected": false,
"text": "var byteArr = imgRGBA.ToByteArray();\n\nbyte[,] redByteArray = new byte[1200, 1920];\nbyte[,] greenByteArray = new byte[1200, 1920];\nbyte[,] blueByteArray = new byte[1200, 1920];\n\nfor (int row = 0; row < 1200; row++)\n for (int col = 0; col < 1920; col++)\n {\n redByteArray[row, col] = byteArr[row, col, 0];\n greenByteArray[row, col] = byteArr[row, col, 1];\n blueByteArray[row, col] = byteArr[row, col, 2];\n }\n\nGCHandle pinnedArray_red = GCHandle.Alloc(redByteArray, GCHandleType.Pinned);\nIntPtr pointer_red = pinnedArray_red.AddrOfPinnedObject();\n\nGCHandle pinnedArray_green = GCHandle.Alloc(greenByteArray, GCHandleType.Pinned);\nIntPtr pointer_green = pinnedArray_green.AddrOfPinnedObject();\n\nGCHandle pinnedArray_blue = GCHandle.Alloc(blueByteArray, GCHandleType.Pinned);\nIntPtr pointer_blue = pinnedArray_blue.AddrOfPinnedObject();\n\nGenImage3(out HObject imgHImage, \"byte\", 1920, 1200, pointer_red, pointer_green, pointer_blue);\n\npinnedArray_red.Free();\npinnedArray_green.Free();\npinnedArray_blue.Free();\n"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74388462",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11786379/"
] |
74,388,493 | <p>I'm very new to React and web development as a whole, and I know the code is styled terribly but bear with me please.</p>
<p>I'm attempting to get weather data with openweathermap API, which I have to use latitude and longitude for my desired location, which I am supposed to get from their separate geocoding API when I feed it the capital and country code of a country I'm interested in.</p>
<p>I'm kind of unsure how to "stack" these requests so that the first coordinate request goes through and gives the coordinates to the second, weather request. My problem, is that the coordinates (which I otherwise get successfully) are given as undefined to my next request, and I can't figure out why, and I've tried a lot.</p>
<pre><code>const Content = ({result}) => {
const languages = [result['languages']]
const [weather, setWeather] = useState([])
const [coordinate, setCoordinates] = useState([])
const api_key = process.env.REACT_APP_API_KEY
useEffect(() => {
axios
.get(`http://api.openweathermap.org/geo/1.0/direct?q=${result['capital']},${result['cca2']}&limit=1&appid=${api_key}`)
.then(response => {
setCoordinates(response.data)
})
.then(() =>
axios
.get(`https://api.openweathermap.org/data/3.0/onecall?lat=${coordinate['lat']}&lon=${coordinate['lon']}&exclude=1&appid=${api_key}`)
.then(response => {
setWeather(response.data)
}))
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [])
</code></pre>
| [
{
"answer_id": 74390827,
"author": "Vladimir Perković",
"author_id": 482036,
"author_profile": "https://Stackoverflow.com/users/482036",
"pm_score": 1,
"selected": false,
"text": "public HImage(string type, int width, int height, IntPtr pixelPointer)\n"
},
{
"answer_id": 74446400,
"author": "Malinko",
"author_id": 15335754,
"author_profile": "https://Stackoverflow.com/users/15335754",
"pm_score": 0,
"selected": false,
"text": "var byteArr = imgRGBA.ToByteArray();\n\nbyte[,] redByteArray = new byte[1200, 1920];\nbyte[,] greenByteArray = new byte[1200, 1920];\nbyte[,] blueByteArray = new byte[1200, 1920];\n\nfor (int row = 0; row < 1200; row++)\n for (int col = 0; col < 1920; col++)\n {\n redByteArray[row, col] = byteArr[row, col, 0];\n greenByteArray[row, col] = byteArr[row, col, 1];\n blueByteArray[row, col] = byteArr[row, col, 2];\n }\n\nGCHandle pinnedArray_red = GCHandle.Alloc(redByteArray, GCHandleType.Pinned);\nIntPtr pointer_red = pinnedArray_red.AddrOfPinnedObject();\n\nGCHandle pinnedArray_green = GCHandle.Alloc(greenByteArray, GCHandleType.Pinned);\nIntPtr pointer_green = pinnedArray_green.AddrOfPinnedObject();\n\nGCHandle pinnedArray_blue = GCHandle.Alloc(blueByteArray, GCHandleType.Pinned);\nIntPtr pointer_blue = pinnedArray_blue.AddrOfPinnedObject();\n\nGenImage3(out HObject imgHImage, \"byte\", 1920, 1200, pointer_red, pointer_green, pointer_blue);\n\npinnedArray_red.Free();\npinnedArray_green.Free();\npinnedArray_blue.Free();\n"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74388493",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19243784/"
] |
74,388,503 | <p>I am making an ajax get request to my laravel backend, the response (json response) includes array of products, in the ajax success function I am looping over the products array to render them in my html elements.</p>
<p>here is my controller response from laravel backend :</p>
<pre><code>return response()->json(['products'=>$products]);
</code></pre>
<p>and here in my ajax success function (front end) I am looping over the products:</p>
<pre><code>$.each(res.products, function(index, product){
rest += `{!! Theme::partial('product-item', compact('product')) !!}`;
});
</code></pre>
<p>I just need to put the product variable (loop parameters) in my compact function (loop body)</p>
<p>how can I parse the 'product' from the response to the 'product' in the compact function?</p>
<p>thanks in advance.</p>
<p>I made some researches about this problem but I was unfortunate</p>
| [
{
"answer_id": 74388660,
"author": "AdBess",
"author_id": 16554748,
"author_profile": "https://Stackoverflow.com/users/16554748",
"pm_score": 0,
"selected": false,
"text": "var products = await request.json();\nindex=0;\nfor(product in products)\n{\n // depends on your json response\n console.log(product[index])\n // pay attention to the index you're trying to get\n}\n"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74388503",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15446553/"
] |
74,388,522 | <p>I was trying to compare c and cython runtime and decide on which one should I choose for my project. So I tested a simple calculation with both. but I couldn't find any good answer to how to measure cython execute time to compare with c:</p>
<p>C :</p>
<pre><code>#include <stdio.h>
#include <time.h>
int main() {
int a[3] = {2, 3, 4};
long long int n = 0;
clock_t start, end;
double cpu_time_used;
start = clock();
for(long long int i=0; i<1000000000; i++)
n += a[0] + a[2];
end = clock();
cpu_time_used = ((double) (end - start)) / CLOCKS_PER_SEC;
printf("time : %f", cpu_time_used);
return 0;
}
</code></pre>
<p>Cython :</p>
<pre><code>cpdef func():
cdef int arr[3]
arr[:] = [2, 3, 4]
cdef unsigned long long a = 0, i
for i in range(1000000000):
a += arr[0] + arr[2]
return a
</code></pre>
<p>I want to know how to compare execute time of cython?</p>
| [
{
"answer_id": 74388632,
"author": "amirhm",
"author_id": 4529589,
"author_profile": "https://Stackoverflow.com/users/4529589",
"pm_score": 2,
"selected": true,
"text": "loopcount * (arr[0] + arr[2])"
},
{
"answer_id": 74388688,
"author": "0___________",
"author_id": 6110094,
"author_profile": "https://Stackoverflow.com/users/6110094",
"pm_score": 0,
"selected": false,
"text": "timeit"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74388522",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3901715/"
] |
74,388,549 | <p>I wanted to delete all records except the one with the highest value so I did</p>
<pre><code>CREATE TABLE code (
id SERIAL,
name VARCHAR(255) NOT NULL ,
value int NOT NULL
);
INSERT INTO code (name,value) VALUES ('name',1);
INSERT INTO code (name,value) VALUES ('name',2);
INSERT INTO code (name,value) VALUES ('name',3);
INSERT INTO code (name,value) VALUES ('name1',3);
INSERT INTO code (name,value) VALUES ('name2',1);
INSERT INTO code (name,value) VALUES ('name2',3);
</code></pre>
<p>Example I want to delete all records except the one with the highest value on value column</p>
<p>I am expecting to get result as:</p>
<pre><code>name 3
name1 3
name2 3
</code></pre>
<p>I tried doing</p>
<pre><code>DELETE FROM code where value != (select MAX(value) value from code where count(code) > 1)
</code></pre>
<p>But I'm getting an error like:</p>
<blockquote>
<p>ERROR: aggregate functions are not allowed in WHERE<br />
LINE 1: ...value != (select MAX(value) value from code where count(code...</p>
</blockquote>
<p>With everyone's idea and combine with this</p>
<pre><code>SELECT dept, SUM(expense) FROM records
WHERE ROW(year, dept) IN (SELECT x, y FROM otherTable)
GROUP BY dept;
</code></pre>
<p><a href="https://stackoverflow.com/questions/46407030/postgres-where-clause-over-two-columns-from-subquery">link</a></p>
<p>I was able to make the query I want</p>
<p><a href="https://dbfiddle.uk/BIToOQAE" rel="nofollow noreferrer">Demo</a></p>
| [
{
"answer_id": 74388632,
"author": "amirhm",
"author_id": 4529589,
"author_profile": "https://Stackoverflow.com/users/4529589",
"pm_score": 2,
"selected": true,
"text": "loopcount * (arr[0] + arr[2])"
},
{
"answer_id": 74388688,
"author": "0___________",
"author_id": 6110094,
"author_profile": "https://Stackoverflow.com/users/6110094",
"pm_score": 0,
"selected": false,
"text": "timeit"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74388549",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4452553/"
] |
74,388,579 | <p>I have a <code>test</code> collection with these two documents:</p>
<pre><code>{ _id: ObjectId("636ce11889a00c51cac27779"), sku: 'kw-lids-0009' }
{ _id: ObjectId("636ce14b89a00c51cac2777a"), sku: 'kw-fs66-gre' }
</code></pre>
<p>I've created a search index with this definition:</p>
<pre><code>{
"analyzer": "lucene.standard",
"searchAnalyzer": "lucene.standard",
"mappings": {
"dynamic": false,
"fields": {
"sku": {
"type": "string"
}
}
}
}
</code></pre>
<p>If I run this aggregation:</p>
<pre><code>[{
$search: {
index: 'test',
text: {
query: 'kw-fs',
path: 'sku'
}
}
}]
</code></pre>
<p>Why do I get 2 results? I only expected the one with <code>sku: 'kw-fs66-gre'</code> </p>
| [
{
"answer_id": 74388632,
"author": "amirhm",
"author_id": 4529589,
"author_profile": "https://Stackoverflow.com/users/4529589",
"pm_score": 2,
"selected": true,
"text": "loopcount * (arr[0] + arr[2])"
},
{
"answer_id": 74388688,
"author": "0___________",
"author_id": 6110094,
"author_profile": "https://Stackoverflow.com/users/6110094",
"pm_score": 0,
"selected": false,
"text": "timeit"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74388579",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1098626/"
] |
74,388,586 | <p>everyone! First of all, thanks in advance.</p>
<p>I've searched everywhere for a solution for my problem. Even when copying from the source code, it doesn't solve it.</p>
<p>I'm doing the <a href="https://www.odoo.com/documentation/16.0/developer/howtos/rdtraining/B_acl_irrules.html#advanced-b-acl-and-record-rules" rel="nofollow noreferrer">Advanced B: ACL and Record Rules tutorial</a></p>
<p>When completing the <a href="https://www.odoo.com/documentation/16.0/developer/howtos/rdtraining/B_acl_irrules.html#multi-company-security" rel="nofollow noreferrer">sub-chapter on multi-company security</a>, I can't do it.</p>
<p>My user can't get access to my new company</p>
<p>The problems I've encountered so far are:</p>
<ol>
<li>The new company isn't in company_ids</li>
<li>When changing the Default Company and allowed companies, if:
<ul>
<li><p>The company is the new company</p>
</li>
<li><p>The only allowed company is the new company</p>
<p>Then, I get the error: <code>Access Error: Access to unauthorized or invalid companies.</code></p>
</li>
</ul>
</li>
</ol>
<p>I don't know why my new company is invalid</p>
<p>I'm trying to access another company's records</p>
<p>This is my rule:</p>
<pre><code><record id="estate_private_companies_properties" model="ir.rule">
<field name="name">Privacy Plan Multi-Company</field>
<field name="model_id" ref="model_estate_property"/>
<field name="global" eval="True"/>
<field name="domain_force">[
('company_id', 'in', company_ids)
]</field>
</record>
</code></pre>
<p>EDIT:</p>
<p>Sorry for the confusion. I know the xml is not the problem</p>
<p>The problem is that my company is unauthorized or invalid and it doesn't show up in my <code>company_ids</code></p>
| [
{
"answer_id": 74388632,
"author": "amirhm",
"author_id": 4529589,
"author_profile": "https://Stackoverflow.com/users/4529589",
"pm_score": 2,
"selected": true,
"text": "loopcount * (arr[0] + arr[2])"
},
{
"answer_id": 74388688,
"author": "0___________",
"author_id": 6110094,
"author_profile": "https://Stackoverflow.com/users/6110094",
"pm_score": 0,
"selected": false,
"text": "timeit"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74388586",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7137219/"
] |
74,388,588 | <p>Let’s say I had two lists like this:</p>
<pre><code>l1 = [‘a’,’b’,’c’,’d’,’e’,’f’,’g’,’h’]
l2 = [True, True, True, False, False, True, False, True]
</code></pre>
<p>With Python, how could I iterate through these elements in order and group them in groups of 3 or 4 based on l2. So that the output would look like this:</p>
<pre><code>groups = [[‘a’,’b’,’c’],[‘d’,’e’],[‘f’,’g’,’h’]]
</code></pre>
<p>Basically the rules are as follows:</p>
<ol>
<li>Each ”True” is worth 1 point and each “False” is worth 2 points.</li>
<li>No group can have more than 4 points.</li>
<li>Iterate through the lists in order and group them accordingly.</li>
</ol>
<p>Here's what I've tried:</p>
<pre><code>l1 = ["a","b","c","d","e","f","g","h"]
l2 = [True, True, True, False, False, True, False, True]
groups = []
count = 1
index = 0
while index <= len(l1):
group = []
for e,b in zip(l1,l2):
if len(group) <= 3:
if b is True:
group.append(e)
index += 1
else:
group.append(e)
group.append("False")
index += 1
else:
groups.append(group)
group = []
index -= 1
</code></pre>
| [
{
"answer_id": 74388632,
"author": "amirhm",
"author_id": 4529589,
"author_profile": "https://Stackoverflow.com/users/4529589",
"pm_score": 2,
"selected": true,
"text": "loopcount * (arr[0] + arr[2])"
},
{
"answer_id": 74388688,
"author": "0___________",
"author_id": 6110094,
"author_profile": "https://Stackoverflow.com/users/6110094",
"pm_score": 0,
"selected": false,
"text": "timeit"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74388588",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7612063/"
] |
74,388,601 | <p>I have data like this:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Customer ID</th>
<th>Name</th>
<th>Type</th>
<th>Last Submit</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>Patricio</td>
<td>C</td>
<td>January 2022</td>
</tr>
<tr>
<td>2</td>
<td>Dale</td>
<td>A</td>
<td>June 2022</td>
</tr>
<tr>
<td>3</td>
<td>Yvonne</td>
<td>C</td>
<td>July 2022</td>
</tr>
<tr>
<td>4</td>
<td>Pawe</td>
<td>C</td>
<td>JUne 2022</td>
</tr>
<tr>
<td>5</td>
<td>Sergio</td>
<td>B</td>
<td>August 2022</td>
</tr>
<tr>
<td>6</td>
<td>Roland</td>
<td>C</td>
<td>August 2022</td>
</tr>
<tr>
<td>7</td>
<td>Georg</td>
<td>D</td>
<td>November 2022</td>
</tr>
<tr>
<td>8</td>
<td>Catherine</td>
<td>D</td>
<td>October 2022</td>
</tr>
<tr>
<td>9</td>
<td>Pascale</td>
<td>E</td>
<td>October 2022</td>
</tr>
<tr>
<td>10</td>
<td>Irene</td>
<td>A</td>
<td>November 2022</td>
</tr>
</tbody>
</table>
</div>
<p>How to sort type A out of the queue first like A,B,C,D,E,F, then the last submit is at the top.</p>
<p>The example output:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Customer ID</th>
<th>Name</th>
<th>Type</th>
<th>Last Submit</th>
</tr>
</thead>
<tbody>
<tr>
<td>10</td>
<td>Irene</td>
<td>A</td>
<td>November 202[![enter image description here][1]][1]2</td>
</tr>
<tr>
<td>1</td>
<td>Dale</td>
<td>A</td>
<td>June 2022</td>
</tr>
<tr>
<td>5</td>
<td>Sergio</td>
<td>B</td>
<td>August 2022</td>
</tr>
<tr>
<td>6</td>
<td>Roland</td>
<td>C</td>
<td>August 2022</td>
</tr>
<tr>
<td>3</td>
<td>Yvonne</td>
<td>C</td>
<td>July 2022</td>
</tr>
<tr>
<td>4</td>
<td>Pawe</td>
<td>C</td>
<td>June 2022</td>
</tr>
<tr>
<td>1</td>
<td>Patricio</td>
<td>C</td>
<td>January 2022</td>
</tr>
<tr>
<td>7</td>
<td>Georg</td>
<td>D</td>
<td>November 2022</td>
</tr>
<tr>
<td>8</td>
<td>Catherine</td>
<td>D</td>
<td>October 2022</td>
</tr>
<tr>
<td>9</td>
<td>Pascale</td>
<td>E</td>
<td>October 2022</td>
</tr>
</tbody>
</table>
</div> | [
{
"answer_id": 74388632,
"author": "amirhm",
"author_id": 4529589,
"author_profile": "https://Stackoverflow.com/users/4529589",
"pm_score": 2,
"selected": true,
"text": "loopcount * (arr[0] + arr[2])"
},
{
"answer_id": 74388688,
"author": "0___________",
"author_id": 6110094,
"author_profile": "https://Stackoverflow.com/users/6110094",
"pm_score": 0,
"selected": false,
"text": "timeit"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74388601",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19305198/"
] |
74,388,611 | <p>I am using a static variables to get access between threads, but is taking so long to get their values.</p>
<p>Context: I have a static class <code>Results.cs</code>, where I store the result variables of two running <code>Process.cs</code> instances.</p>
<pre><code>public static int ResultsStation0 { get; set; }
public static int ResultsStation1 { get; set; }
</code></pre>
<p>Then, a function of the two process instances is called at the same time, with initial value of ResultsStation0/1 = -1.</p>
<p>Because the result will be provided not at the same time, the function is checking that both results are available. The fast instance will set the result and await for the result of the slower instance.</p>
<pre><code> void StationResult(){
Stopwatch sw = new Stopwatch();
sw.Restart();
switch (stationIndex) //Set the result of the station thread
{
case 0: Results.ResultsStation0 = 1; break;
case 1: Results.ResultsStation1 = 1; break;
}
//Waits to get the results of both threads
while (true)
{
if (Results.ResultsStation0 != -1 && Results.ResultsStation1 != -1)
{
break;
}
}
Trace_Info("GOT RESULTS " + stationIndex + "Time: " + sw.ElapsedMilliseconds.ToString() + "ms");
if (Results.ResultsStation0 == 1 && Results.ResultsStation1 == 1)
{
//set OK if both results are OK
Device.profinet.WritePorts(new Enum[] { NOK, OK },
new int[] { 0, 1 });
}
}
</code></pre>
<p>It works, but the problem is that the value of sw of the thread that awaits, should be 1ms more or less. I am getting 1ms sometimes, but most of the times I have values up to 80ms.
My question is: why it takes that much if they are sharing the same memory (I guess)?</p>
<p>Is this the right way to access to a variable between threads?</p>
| [
{
"answer_id": 74388910,
"author": "JonasH",
"author_id": 12342238,
"author_profile": "https://Stackoverflow.com/users/12342238",
"pm_score": 4,
"selected": true,
"text": "var result1 = Task.Run(MyMethod1);\nvar result2 = Task.Run(MyMethod2);\nawait Task.WhenAll(new []{result1, result2});\n"
},
{
"answer_id": 74388986,
"author": "SimplyCode",
"author_id": 10895224,
"author_profile": "https://Stackoverflow.com/users/10895224",
"pm_score": 1,
"selected": false,
"text": "AutoResetEvent"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74388611",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1238934/"
] |
74,388,617 | <p>Assuming I have the following text file:</p>
<pre><code>a b c d 1 2 3
e f g h 1 2 3
i j k l 1 2 3
m n o p 1 2 3
</code></pre>
<p>How do I replace '1 2 3' with '4 5 6' in the line that contains the letter (e) <strong>and</strong> move it after the line that contains the letter (k)?</p>
<p>N.B. the line that contains the letter (k) may come in <em>any location</em> in the file, the lines are not assumed to be in any order</p>
<p>My approach is</p>
<ol>
<li>Remove the line I want to replace</li>
<li>Find the lines <strong>before</strong> the line I want to move it after</li>
<li>Find the lines <strong>after</strong> the line I want to move it after</li>
<li>append the output to a file</li>
</ol>
<pre><code>grep -v 'e' $original > $file
grep -B999 'k' $file > $output
grep 'e' $original | sed 's/1 2 3/4 5 6/' >> $output
grep -A999 'k' $file | tail -n+2 >> $output
rm $file
mv $output $original
</code></pre>
<p>but there is a lot of issues in this solution:</p>
<ol>
<li>a lot of <code>grep</code> commands that seems unnecessary</li>
<li>the argument <code>-A999</code> and <code>-B999</code> are assuming the file would not contain lines more than 999, it would be better to have another way to get lines before and after the matched line</li>
</ol>
<p>I am looking for a more efficient way to achieve that</p>
| [
{
"answer_id": 74388694,
"author": "anubhava",
"author_id": 548225,
"author_profile": "https://Stackoverflow.com/users/548225",
"pm_score": 0,
"selected": false,
"text": "awk"
},
{
"answer_id": 74388807,
"author": "HatLess",
"author_id": 16372109,
"author_profile": "https://Stackoverflow.com/users/16372109",
"pm_score": 2,
"selected": false,
"text": "sed"
},
{
"answer_id": 74389756,
"author": "dawg",
"author_id": 298607,
"author_profile": "https://Stackoverflow.com/users/298607",
"pm_score": 1,
"selected": false,
"text": "awk '\n/\\<e\\>/{\n s=$0\n sub(\"1 2 3\", \"4 5 6\", s)\n next\n}\n/\\<k\\>/ && s {\n printf(\"%s\\n%s\\n\",$0,s)\n next\n} 1\n' file\n"
},
{
"answer_id": 74396931,
"author": "potong",
"author_id": 967492,
"author_profile": "https://Stackoverflow.com/users/967492",
"pm_score": 0,
"selected": false,
"text": "sed -n '/e/{s/1 2 3/4 5 6/;s#.*#/e/d;/k/s/.*/\\&\\\\n&/#p};' file | sed -f - file\n"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74388617",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10347663/"
] |
74,388,661 | <p>how can i sort 2D mutable list of array by the first element of array?</p>
<pre><code>val books = mutableListOf<Any>(
listof("abc","b",1),
listof("abb","y",2),
listof("abcl"."i",3)
)
</code></pre>
<p>i want to get sort this mutablelist by alphabetical order of the first element of each list.</p>
<p>output should be</p>
<pre><code>[listof("abb","y",2), listof("abc","b",1), listof("abcl"."i",3) ]
</code></pre>
| [
{
"answer_id": 74388694,
"author": "anubhava",
"author_id": 548225,
"author_profile": "https://Stackoverflow.com/users/548225",
"pm_score": 0,
"selected": false,
"text": "awk"
},
{
"answer_id": 74388807,
"author": "HatLess",
"author_id": 16372109,
"author_profile": "https://Stackoverflow.com/users/16372109",
"pm_score": 2,
"selected": false,
"text": "sed"
},
{
"answer_id": 74389756,
"author": "dawg",
"author_id": 298607,
"author_profile": "https://Stackoverflow.com/users/298607",
"pm_score": 1,
"selected": false,
"text": "awk '\n/\\<e\\>/{\n s=$0\n sub(\"1 2 3\", \"4 5 6\", s)\n next\n}\n/\\<k\\>/ && s {\n printf(\"%s\\n%s\\n\",$0,s)\n next\n} 1\n' file\n"
},
{
"answer_id": 74396931,
"author": "potong",
"author_id": 967492,
"author_profile": "https://Stackoverflow.com/users/967492",
"pm_score": 0,
"selected": false,
"text": "sed -n '/e/{s/1 2 3/4 5 6/;s#.*#/e/d;/k/s/.*/\\&\\\\n&/#p};' file | sed -f - file\n"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74388661",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20463529/"
] |
74,388,681 | <p>I have this array that has <code>length = 3</code>:</p>
<pre class="lang-js prettyprint-override"><code> state = ["q0", "q1", "q2,q3"]
</code></pre>
<p>And I want to modify that, and I want it to look something like this:</p>
<pre class="lang-js prettyprint-override"><code> state = ["q0", "q1", "q2", "q3"] // length = 4.
</code></pre>
<p>I want to cut the <code>string = "q2,q3"</code> in a way that I will get <code>"q2"</code> and <code>"q3"</code> so that I can replace the <code>state[2]</code> value with <code>"q2"</code> and automatically add to the array like <code>state[3] = "q3"</code>.</p>
<p>Does anyone know how can I do it?</p>
<p>I tried the <code>split</code> method but it didn't work as I wanted.</p>
| [
{
"answer_id": 74388784,
"author": "David Thomas",
"author_id": 82548,
"author_profile": "https://Stackoverflow.com/users/82548",
"pm_score": 0,
"selected": false,
"text": "// initial state, chained immediately to\n// Array.prototype.map() to create a new Array\n// based on the initial state ([\"q0\", \"q1\", \"q2, q3\"]):\nlet state = [\"q0\", \"q1\", \"q2, q3\"].map(\n // str is a reference to the current String of the Array\n // (the variable name is free to be changed to anything\n // of your preference):\n (str) => {\n // here we create a new Array using String.prototype.split(','),\n // which splits the string on each ',' character:\n let subunits = str.split(',');\n \n // if subunits exists, and has a length greater than 1,\n // we return a new Array which is formed by calling\n // Array.prototype.map() - again - and iterating over\n // each Array-element to remove leading/trailing white-\n // space with String.prototype.trim(); otherwise\n // if the str is either not an Array, or the length is\n // not greater than 1, we return str:\n return subunits && subunits.length > 1 ? subunits.map((el) => el.trim()) : str;\n // we then call Array.prototype.map():\n }).flat();\n\n// and log the output:\nconsole.log(state);"
},
{
"answer_id": 74388794,
"author": "Lukáš Gibo Vaic",
"author_id": 4449862,
"author_profile": "https://Stackoverflow.com/users/4449862",
"pm_score": 0,
"selected": false,
"text": "state"
},
{
"answer_id": 74388799,
"author": "Benjie Alaan",
"author_id": 4010747,
"author_profile": "https://Stackoverflow.com/users/4010747",
"pm_score": 0,
"selected": false,
"text": "forEach()"
},
{
"answer_id": 74388818,
"author": "Vivekanand Vishvkarma",
"author_id": 19443694,
"author_profile": "https://Stackoverflow.com/users/19443694",
"pm_score": 0,
"selected": false,
"text": "let state = [\"q0\", \"q1\", \"q2,q3\"];\nstate=state.join(',');\nstate=state.split(',');\nconsole.log(state);\n"
},
{
"answer_id": 74388820,
"author": "Can Ozdemir",
"author_id": 18617885,
"author_profile": "https://Stackoverflow.com/users/18617885",
"pm_score": 0,
"selected": false,
"text": "let deneme = [\"first\",\"second\",\"third fourth\"];\n\n\nlet index = deneme[2].indexOf(\" \"); // Gets the first index where a space occours\nlet firstPart = deneme[2].slice(0, index); // Gets the first part\nlet secondPart = deneme[2].slice(index + 1);\n\nconsole.log(\"first try\" ,deneme);\ndeneme[2] = firstPart;\ndeneme.push(secondPart);\nconsole.log(\"second look\",deneme);"
},
{
"answer_id": 74388833,
"author": "Trevor Dixon",
"author_id": 711902,
"author_profile": "https://Stackoverflow.com/users/711902",
"pm_score": 2,
"selected": false,
"text": "[\"q0\", \"q1\", \"q2,q3\"].flatMap(v => v.split(','))\n"
},
{
"answer_id": 74389829,
"author": "PeterKA",
"author_id": 3558931,
"author_profile": "https://Stackoverflow.com/users/3558931",
"pm_score": 0,
"selected": false,
"text": "Array#flatMap"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74388681",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20183430/"
] |
74,388,684 | <p>I have an array with the following objects:</p>
<p><code>const arrayData = [</code>
<code>{name: 'John', car:'BMW', value1: 500, value2: 350},</code>
<code>{name: 'Paul', car: 'AUDI', value1: 290, value2: 200},</code>
<code>{name: 'John', car:'BMW', value1: 600, value2: 360},</code>
<code>{name: 'John', car:'BMW', value1: 500, value2: 350},</code>
<code>{name: 'Paul', car: 'AUDI', value1: 120, value2: 50},</code>
<code>{name: 'John', car:'BMW', value1: 100, value2: 100},</code>
<code>];</code></p>
<p>I would like to join them passing the common name as a reference and do the sum of value1 and value2 according to the result below. I tried to reduce but I didn't get the expected result.</p>
<p><code>[</code>
<code>{name: 'John', car:'BMW', value1: 1700, value2: 1160},</code>
<code>{name: 'Paul', car: 'AUDI', value1: 410, value2: 250}</code>
<code>]</code></p>
<p>I tried to reduce it but I didn't get the expected result.</p>
| [
{
"answer_id": 74388784,
"author": "David Thomas",
"author_id": 82548,
"author_profile": "https://Stackoverflow.com/users/82548",
"pm_score": 0,
"selected": false,
"text": "// initial state, chained immediately to\n// Array.prototype.map() to create a new Array\n// based on the initial state ([\"q0\", \"q1\", \"q2, q3\"]):\nlet state = [\"q0\", \"q1\", \"q2, q3\"].map(\n // str is a reference to the current String of the Array\n // (the variable name is free to be changed to anything\n // of your preference):\n (str) => {\n // here we create a new Array using String.prototype.split(','),\n // which splits the string on each ',' character:\n let subunits = str.split(',');\n \n // if subunits exists, and has a length greater than 1,\n // we return a new Array which is formed by calling\n // Array.prototype.map() - again - and iterating over\n // each Array-element to remove leading/trailing white-\n // space with String.prototype.trim(); otherwise\n // if the str is either not an Array, or the length is\n // not greater than 1, we return str:\n return subunits && subunits.length > 1 ? subunits.map((el) => el.trim()) : str;\n // we then call Array.prototype.map():\n }).flat();\n\n// and log the output:\nconsole.log(state);"
},
{
"answer_id": 74388794,
"author": "Lukáš Gibo Vaic",
"author_id": 4449862,
"author_profile": "https://Stackoverflow.com/users/4449862",
"pm_score": 0,
"selected": false,
"text": "state"
},
{
"answer_id": 74388799,
"author": "Benjie Alaan",
"author_id": 4010747,
"author_profile": "https://Stackoverflow.com/users/4010747",
"pm_score": 0,
"selected": false,
"text": "forEach()"
},
{
"answer_id": 74388818,
"author": "Vivekanand Vishvkarma",
"author_id": 19443694,
"author_profile": "https://Stackoverflow.com/users/19443694",
"pm_score": 0,
"selected": false,
"text": "let state = [\"q0\", \"q1\", \"q2,q3\"];\nstate=state.join(',');\nstate=state.split(',');\nconsole.log(state);\n"
},
{
"answer_id": 74388820,
"author": "Can Ozdemir",
"author_id": 18617885,
"author_profile": "https://Stackoverflow.com/users/18617885",
"pm_score": 0,
"selected": false,
"text": "let deneme = [\"first\",\"second\",\"third fourth\"];\n\n\nlet index = deneme[2].indexOf(\" \"); // Gets the first index where a space occours\nlet firstPart = deneme[2].slice(0, index); // Gets the first part\nlet secondPart = deneme[2].slice(index + 1);\n\nconsole.log(\"first try\" ,deneme);\ndeneme[2] = firstPart;\ndeneme.push(secondPart);\nconsole.log(\"second look\",deneme);"
},
{
"answer_id": 74388833,
"author": "Trevor Dixon",
"author_id": 711902,
"author_profile": "https://Stackoverflow.com/users/711902",
"pm_score": 2,
"selected": false,
"text": "[\"q0\", \"q1\", \"q2,q3\"].flatMap(v => v.split(','))\n"
},
{
"answer_id": 74389829,
"author": "PeterKA",
"author_id": 3558931,
"author_profile": "https://Stackoverflow.com/users/3558931",
"pm_score": 0,
"selected": false,
"text": "Array#flatMap"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74388684",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20468121/"
] |
74,388,687 | <p>I want to iterate through a vector, and get a mutable reference to each item, and a mutable slice to the rest of the vector, so I can use both every iteration. Something like:</p>
<p>e.g:</p>
<pre><code>for index in 0..model.len() {
let (item, rest): (&mut Item, &mut [Item]) = model.split_rest_mut(index);
item.do_something(rest);
}
</code></pre>
<p>e.g <code>[1,2,3,4,5,6].split_rest_mut(2)</code> would be <code>3, [1,2,4,5,6]</code>.</p>
<p>I would like this to be as performant as possible.</p>
<p>It seems to be similar behaviour to <code>split_at_mut</code>, so I imagine this should be possible.</p>
<p>How would I go about doing this?</p>
| [
{
"answer_id": 74388791,
"author": "Thomas",
"author_id": 14637,
"author_profile": "https://Stackoverflow.com/users/14637",
"pm_score": 1,
"selected": false,
"text": "Vec::split_at_mut"
},
{
"answer_id": 74388792,
"author": "Masklinn",
"author_id": 8182118,
"author_profile": "https://Stackoverflow.com/users/8182118",
"pm_score": 0,
"selected": false,
"text": "split_at_mut"
},
{
"answer_id": 74389004,
"author": "E_net4 the comment flagger",
"author_id": 1233251,
"author_profile": "https://Stackoverflow.com/users/1233251",
"pm_score": 2,
"selected": true,
"text": "split_rest_mut(usize) -> (&mut T, &[T])"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74388687",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3052832/"
] |
74,388,706 | <p>I'm using Laravel 8, but don't seem to know which controller controls the layout master blade file. I have been able to pass variables to the sub-view (Profile page) file successfully but don't know how to achieve that with the layout view master blade.</p>
<p>I am trying to pass variables from a controller called <code>ProfileController</code> in <code>app\Http\Controllers</code> to the master blade layout. In the profile controller, I have a code that retrieves user profile data from the database.</p>
<pre><code>$profileInfo = Profile::with('address')->where('id', '=', '1')->get();
return view('admin_pages.profile', compact('profileInfo'));
</code></pre>
<p>In the profiles table, I have names and image fields <code>first_name, last_name, photo</code> which I can access with a foreach loop from the data <code>$profileInfo</code> passed to the sub-view using</p>
<pre><code>@foreach($profileInfo as $data)
{{ $data->first_name}}
@endforeach
</code></pre>
<p>and so on.</p>
<p>My master blade file is located at <code>resources\views\layout\admin.blade.php</code>. I want to be able to display the <code>names</code> and <code>photo</code> from the <code>admin.blade.php</code> so the logged in user can see their profile image when logged in even when they don't visit their profile page (sub-view) which is located at <code>resources\views\admin_pages\profile.blade.php</code>, extending the master blade (<code>admin.blade.php</code>).</p>
<p>Please kindly help out.</p>
| [
{
"answer_id": 74388791,
"author": "Thomas",
"author_id": 14637,
"author_profile": "https://Stackoverflow.com/users/14637",
"pm_score": 1,
"selected": false,
"text": "Vec::split_at_mut"
},
{
"answer_id": 74388792,
"author": "Masklinn",
"author_id": 8182118,
"author_profile": "https://Stackoverflow.com/users/8182118",
"pm_score": 0,
"selected": false,
"text": "split_at_mut"
},
{
"answer_id": 74389004,
"author": "E_net4 the comment flagger",
"author_id": 1233251,
"author_profile": "https://Stackoverflow.com/users/1233251",
"pm_score": 2,
"selected": true,
"text": "split_rest_mut(usize) -> (&mut T, &[T])"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74388706",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9999993/"
] |
74,388,723 | <p>I want to merge two datasets on 'key1' and 'key2' columns so that in case of missing value, for example, in the 'key2' column, it would take all combinations of the second key that belong to the first key. Here is an example:</p>
<pre><code> def merge_nan_as_any(mask, data, on, how)
...
mask = pd.DataFrame({'key1': [1,1,2,2],
'key2': [None,3,1,2],
'value2': [1,2,3,4]})
data = pd.DataFrame({'key1': [1,1,1,2,2,2],
'key2': [1,2,3,1,2,3],
'value1': [1,2,3,4,5,6]})
result = merge_nan_as_any(mask, data, on=['key1', 'key2'], how='left')
result = pd.DataFrame({'key1': [1,1,1,1,2,2],
'key2': [1,2,3,3,1,2],
'value2': [1,1,1,2,3,4],
'value1': [1,2,3,3,4,5]})
</code></pre>
<p>There is a missed value of the second key, so it takes all rows from the second dataset that satisfy the condition: key1 must equal to 1, key2 is any the second key value from the second dataset. How to do that?</p>
<p>The first obvious solution that came to my mind is to iterate over the first dataset and filter out combinations that satisfy the condition and the second one is to split the first dataset into several ones so that they have NaNs in the same columns and merge each of them on columns that have values.</p>
<p>But I don't like these solutions and guess there is more elegant way to do what I want.</p>
<p>I will appreciate for any help!</p>
| [
{
"answer_id": 74388946,
"author": "Celius Stingher",
"author_id": 11897007,
"author_profile": "https://Stackoverflow.com/users/11897007",
"pm_score": 1,
"selected": false,
"text": "mask['key2'] = mask['key2'].fillna(' '.join([str(x) for x in data['key2'].unique()])).astype(str).str.split(' ')\nmask = mask.explode('key2')\nmask['key2'] = pd.to_numeric(mask['key2'])\npd.merge(mask,data,on=['key1','key2'],how='left')\n"
},
{
"answer_id": 74389043,
"author": "mozway",
"author_id": 16343464,
"author_profile": "https://Stackoverflow.com/users/16343464",
"pm_score": 2,
"selected": false,
"text": "concat"
}
] | 2022/11/10 | [
"https://Stackoverflow.com/questions/74388723",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16895442/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.