qid int64 4 22.2M | question stringlengths 18 48.3k | answers list | date stringlengths 10 10 | metadata list |
|---|---|---|---|---|
74,232,582 | <p>I have the following object that contains two arrays inside:</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 response = {
"layers": [{
"layer": "test5",
"perms": {
"group_id": 1,
"layer_id": 60
}
},
{
"layer": "test6",
"perms": {
"group_id": 1,
"layer_id": 61
}
},
{
"layer": "test7",
"perms": {
"group_id": 1,
"layer_id": 71
}
},
{
"layer": "test8",
"perms": {
"group_id": 1,
"layer_id": 76
}
}
],
"perms": [{
"layer": "test6",
"perms": {
"group_id": 2,
"layer_id": 61
}
},
{
"layer": "test7",
"perms": {
"group_id": 2,
"layer_id": 71
}
},
{
"layer": "test8",
"perms": {
"group_id": 2,
"layer_id": 76
}
}
],
"status": "open"
}</code></pre>
</div>
</div>
</p>
<p>I want to compare both <code>layers</code> and <code>perms</code> and if their <code>layer</code> key is the same then add a new key called <code>check = true</code> otherwise <code>check = false</code></p>
<p>Here is how I did:</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 layers = response.layers
const perms = response.perms
layers.map(layer => {
perms.filter(perm => {
if (layer.layer === perm.layer) {
layer.check = true
} else {
layer.check = false
}
})
})
return layers</code></pre>
</div>
</div>
</p>
<p>I want to get the following:</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>"layers": [{
"layer": "test5",
"perms": {
"group_id": 1,
"layer_id": 60
},
"check": false
},
{
"layer": "test6",
"perms": {
"group_id": 1,
"layer_id": 61
},
"check": true
},
{
"layer": "test7",
"perms": {
"group_id": 1,
"layer_id": 71
},
"check": true
},
{
"layer": "test8",
"perms": {
"group_id": 1,
"layer_id": 76
},
"check": true
}
]</code></pre>
</div>
</div>
</p>
| [
{
"answer_id": 74232654,
"author": "jitender",
"author_id": 5621827,
"author_profile": "https://Stackoverflow.com/users/5621827",
"pm_score": 3,
"selected": true,
"text": "const response = {\n \"layers\": [{\n \"layer\": \"test5\",\n \"perms\": {\n \"group_id\": 1,\n ... | 2022/10/28 | [
"https://Stackoverflow.com/questions/74232582",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11311898/"
] |
74,232,597 | <p>I am looking for a way to merge a <code>Dataset</code> with another, but by drawing samples from it only occasionally.</p>
<p>For example, given these two <code>Dataset</code>s</p>
<pre class="lang-py prettyprint-override"><code>ds1 = tf.data.Dataset.range(1, 10).repeat()
ds10 = tf.data.Dataset.range(10, 100, 10).repeat()
</code></pre>
<p>I would like to add samples from <code>ds10</code> to those of <code>ds1</code> but only for every two samples, so that the result would be</p>
<pre class="lang-py prettyprint-override"><code>ds = my_merge(ds1, ds10)
list(ds)
# 11, 2, 23, 4, 35, 6, 47...
</code></pre>
<p>Is this possible? I would like to avoid solutions discarding samples from <code>ds10</code> as this would be inefficient in my case.</p>
<p>EDIT The resulting <code>ds</code> needs to be a <code>Dataset</code> so that further input pipeline operations (e.g. batching) can be applied.</p>
| [
{
"answer_id": 74232654,
"author": "jitender",
"author_id": 5621827,
"author_profile": "https://Stackoverflow.com/users/5621827",
"pm_score": 3,
"selected": true,
"text": "const response = {\n \"layers\": [{\n \"layer\": \"test5\",\n \"perms\": {\n \"group_id\": 1,\n ... | 2022/10/28 | [
"https://Stackoverflow.com/questions/74232597",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9973879/"
] |
74,232,601 | <p>Using pySimpleGUI I simply want to change the mouse cursor while the code is processing a query, but the cursor does only change <em>after</em> the code is executed... it does work when I put a window.read() after the set_cursor() call, but then the proceeding code is not executed immediately. What am I doing wrong? Unfortunately, the documentation does not provide an example.</p>
<pre><code>import PySimpleGUI as sg
#... more code
window = sg.Window(f"Report Generator v{APP_VERSION}", layout)
while True:
event, values = window.read()
# close button was clicked
if event == "Close" or event == sg.WIN_CLOSED:
break
# Generate button was clicked
elif event == "Generate":
window.set_cursor("coffee_mug")
window.refresh()
# more code where the cursor should be changed but isn't
</code></pre>
| [
{
"answer_id": 74234211,
"author": "Jason Yang",
"author_id": 11936135,
"author_profile": "https://Stackoverflow.com/users/11936135",
"pm_score": 0,
"selected": false,
"text": "import PySimpleGUI as sg\n\nlayout = [\n [sg.Text(\"Hello World\")],\n [sg.Button('Submit'), sg.Button('C... | 2022/10/28 | [
"https://Stackoverflow.com/questions/74232601",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10258072/"
] |
74,232,604 | <p>What i'm trying to achieve is that, depending on the content of the <code>TabBarView</code> component, expand it to take as much space as it needs ( height ) and make the whole screen scrollable, not only the <code>Container</code> of the <code>TabBarView</code>.</p>
<p>In the attached example I have a <code>Container</code> which wraps the <code>TabBar</code> component. It has a fixed height at the moment because it throws errors if not. Actually that's the problem i want to fix. Get rid of that fix height, and have it somehow dinamically set.</p>
<p>Here is my code with comments:</p>
<pre><code>import 'package:flutter/material.dart';
import 'package:livescore/models/leaguesModel/leagues_model.dart';
import 'package:livescore/models/livescores/livescore_data_model.dart';
import 'package:livescore/pages/matchDetailsPage/components/matchDetailsHeaderWidgets/match_details_header.dart';
import 'package:livescore/pages/matchDetailsPage/components/matchDetailsStatsWidgets/match_details_stats_component.dart';
// ignore: must_be_immutable
class MatchDetailsPage extends StatefulWidget {
LeaguesModelData leaguesModelData;
LivescoreDataModel matchDetails;
MatchDetailsPage(this.leaguesModelData, this.matchDetails, {super.key});
@override
State<MatchDetailsPage> createState() => _MatchDetailsPageState();
}
class _MatchDetailsPageState extends State<MatchDetailsPage>
with SingleTickerProviderStateMixin {
late TabController _tabController;
@override
void initState() {
_tabController = TabController(length: 10, vsync: this);
super.initState();
}
@override
void dispose() {
super.dispose();
_tabController.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: SingleChildScrollView(
child: Container(
// whole screen background and border
height: MediaQuery.of(context).size.height,
decoration: BoxDecoration(
border: Border.all(
color: Theme.of(context).colorScheme.primary, width: 5),
),
child: Column(
children: <Widget>[
MatchDetailsHeader(
widget.leaguesModelData,
widget
.matchDetails), // upper side of the screen, above the TabBar component
Padding(
padding: const EdgeInsets.only(top: 30, right: 20, left: 20),
child: Container(
// the container representing the TabBar zone
height: 400,
width: MediaQuery.of(context).size.width,
decoration: BoxDecoration(
border: Border.all(color: Colors.white),
color: Colors.white,
borderRadius: const BorderRadius.all(Radius.circular(10)),
),
child: Padding(
padding: const EdgeInsets.only(left: 10, right: 10),
child: Column(
children: [
Padding(
padding: const EdgeInsets.only(top: 15, bottom: 20),
child: SizedBox(
child: TabBar(
labelPadding:
const EdgeInsets.symmetric(horizontal: 10),
isScrollable: true,
indicatorWeight: 0,
labelStyle: const TextStyle(fontSize: 13),
unselectedLabelColor: Colors.grey.shade700,
labelColor: Colors.white,
indicator: const ShapeDecoration(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.all(
Radius.circular(15))),
color: Colors.pink),
tabs: const [
Tab(
text: "Stats",
),
Tab(
text: "Info",
),
Tab(
text: "Line-up",
),
Tab(
text: "H2H",
),
Tab(
text: "Table",
),
Tab(
text: "News",
),
Tab(
text: "Info",
),
Tab(
text: "Info",
),
Tab(
text: "Info",
),
Tab(
text: "Info",
),
],
controller: _tabController,
indicatorSize: TabBarIndicatorSize.tab,
),
),
),
Expanded(
flex: 1,
child: TabBarView(
physics: const NeverScrollableScrollPhysics(),
controller: _tabController,
children: [
(widget.matchDetails.stats != null &&
widget
.matchDetails.stats!.data.isNotEmpty)
? MatchDetailsStatsComponent(
widget.matchDetails.localTeam.data.id,
widget.matchDetails.visitorTeam.data.id,
widget.matchDetails.stats)
: Column(
children: const [
Text("stats not available yet"),
Text("stats not available yet"),
Text("stats not available yet"),
Text("stats not available yet"),
Text("stats not available yet"),
Text("stats not available yet"),
Text("stats not available yet"),
Text("stats not available yet"),
Text("stats not available yet"),
Text("stats not available yet"),
Text("stats not available yet"),
Text("stats not available yet"),
Text("stats not available yet"),
Text("stats not available yet"),
Text("stats not available yet"),
Text("stats not available yet"),
Text("stats not available yet"),
Text("stats not available yet"),
Text("stats not available yet"),
Text("stats not available yet"),
Text("stats not available yet"),
Text("stats not available yet"),
],
),
const Text("abcd"),
const Text("abcd"),
const Text("abcd"),
const Text("abcd"),
const Text("abcd"),
const Text("abcd"),
const Text("abcd"),
const Text("abcd"),
const Text("abcd"),
],
),
),
],
),
),
),
),
],
),
),
),
);
}
}
</code></pre>
<p>I tried getting it work with <code>NestedScrollView</code>, <code>ListView</code>, have <code>ScrollPhysics</code> on the parent <code>SingleChildScrollView</code> and <code>NeverScrollableScrollPhysics</code> on the <code>TabBarView</code> component, but didn't get it to work.</p>
<p><a href="https://i.stack.imgur.com/mISif.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/mISif.png" alt="This image represents the screen at the moment, when the content doens't exceeds it's limits." /></a></p>
<p><a href="https://i.stack.imgur.com/KEMws.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/KEMws.png" alt="This image shows the boundry error that is thrown when the content exceeds it's limits. When this is the case, i would the TabBarView container to expand and make the whole screen scrollable" /></a></p>
| [
{
"answer_id": 74234211,
"author": "Jason Yang",
"author_id": 11936135,
"author_profile": "https://Stackoverflow.com/users/11936135",
"pm_score": 0,
"selected": false,
"text": "import PySimpleGUI as sg\n\nlayout = [\n [sg.Text(\"Hello World\")],\n [sg.Button('Submit'), sg.Button('C... | 2022/10/28 | [
"https://Stackoverflow.com/questions/74232604",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14493851/"
] |
74,232,616 | <p>I am trying to predict the y values using LogisticRegression.
<a href="https://i.stack.imgur.com/UGnmD.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/UGnmD.png" alt="enter image description here" /></a></p>
<p>Here is a sample of the that is train.</p>
<pre class="lang-py prettyprint-override"><code>x = data[["A1", "A2", "A3","A4", "A5", "A6", "A7", "A8", "A9", "A10", "A11"]]
y = data["y"]
x_train, x_test, y_train, y_test = train_test_split(df, y, test_size=0.4, random_state=42)
log_model = LogisticRegression(solver='lbfgs', max_iter=1000)
log_model.fit(x_train,y_train)
predictions = log_model.predict(x_test)
accuracy_score(y_test,predictions)
</code></pre>
<p>However my accuracy score is only 0.712.
Is there any feature engineering or anything that I can do to increase the score?</p>
| [
{
"answer_id": 74234211,
"author": "Jason Yang",
"author_id": 11936135,
"author_profile": "https://Stackoverflow.com/users/11936135",
"pm_score": 0,
"selected": false,
"text": "import PySimpleGUI as sg\n\nlayout = [\n [sg.Text(\"Hello World\")],\n [sg.Button('Submit'), sg.Button('C... | 2022/10/28 | [
"https://Stackoverflow.com/questions/74232616",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19513635/"
] |
74,232,688 | <p>Why does this codelab at android developers passes a "onNextButtonClicked: () -> Unit," instead of just passing the "navController: NavController,"... it seems simpler.. is there a reason for this?</p>
<p><a href="https://i.stack.imgur.com/ovliT.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ovliT.png" alt="enter image description here" /></a>
<a href="https://i.stack.imgur.com/hQmh4.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/hQmh4.png" alt="enter image description here" /></a></p>
<p><a href="https://github.com/google-developer-training/basic-android-kotlin-compose-training-lunch-tray/tree/main" rel="nofollow noreferrer">Codelab in github</a></p>
| [
{
"answer_id": 74234211,
"author": "Jason Yang",
"author_id": 11936135,
"author_profile": "https://Stackoverflow.com/users/11936135",
"pm_score": 0,
"selected": false,
"text": "import PySimpleGUI as sg\n\nlayout = [\n [sg.Text(\"Hello World\")],\n [sg.Button('Submit'), sg.Button('C... | 2022/10/28 | [
"https://Stackoverflow.com/questions/74232688",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7005465/"
] |
74,232,707 | <p>I have a project and within this project I use TypeScript and React, but I encountered a problem that I want to store the response coming from the backend and put it in "setDataTraining" but the problem is that nothing is stored within this variable "dataTraining"</p>
<p>How can i solve this problem?</p>
<p>this is Response that comes from backend.</p>
<p><a href="https://i.stack.imgur.com/7z1nK.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/7z1nK.png" alt="enter image description here" /></a></p>
<p>I tried using the following instruction:</p>
<pre><code>committeeData?.items
</code></pre>
<p>And store it in the variable "dataTraining", but it didn't recognize the value of items even though it came from the backend.</p>
<p>index.tsx:</p>
<pre><code>import _ from 'lodash';
import { FunctionComponent, useContext, useEffect, useState } from 'react';
import { Check } from 'react-feather';
import { useMutation, useQuery } from 'react-query';
import { useNavigate } from 'react-router-dom';
import caseServeice from '../../../api/nuclearMedicineApi/services/Case';
import {
AuthContext,
IAuthContext,
} from '../../../contexts/auth-context';
import Scaffold from '../../common/scaffold';
import { committeeRequestColumns } from './data';
import { committeeRequestFilters } from './filters';
import committeeRequest from '../../../api/nuclearMedicineApi/services/CommitteeRequests';
import { notify } from '../../common/notification';
interface CommitteeRequestPageProps { }
const CommitteeRequestPage: FunctionComponent<CommitteeRequestPageProps> = () => {
const auth = useContext<IAuthContext>(AuthContext);
let committeeColumns = committeeRequestColumns;
committeeColumns = auth.userData?.roleNames?.some(
(role) => role === 'DOCTOR',
)
? committeeColumns.filter(
(item) => item.dataSelector !== 'supervisoryDoctor',
)
: committeeColumns;
const approveCommitteeRequestNotification = () => {
// onSuccess: (data) => {
notify('success', 'ok', 'approveCommitteeRequest');
// },
};
const [dataTraining, setDataTraining] = useState({})
const getDataFromBackend = async(waitingListId: any) =>{
console.log('number: ', waitingListId, typeof(waitingListId));
let dataPat = await committeeRequest.approveCommitteeRequest(waitingListId);
console.log('data training: ', dataTraining)
console.log('getDataApprove: ', dataPat);
return dataPat;
}
const getAllCommitteeData = async() => {
let committeeData = await committeeRequest.comitteeRequestGetAll();
setDataTraining(committeeData);
console.log('committee Data Response: ', committeeData);
console.log('data training: ', dataTraining);
return committeeData;
}
useEffect(() => {
getAllCommitteeData();
setDataTraining((v) => v)
console.log('data training outside: ', dataTraining)}, [dataTraining])
// console.log('data training outside: ', dataTraining);
// useEffect(() => {
// committeeRequest.comitteeRequestGetAll()
// }, []);
return (
<>
<Scaffold
getAllFunc={getAllCommitteeData}
tableColumns={committeeColumns}
filterColumns={committeeRequestFilters}
getAllParams={{ MaxResultCount: 1000 }}
create={false}
fullWidthFrom
dataName='committeeRequest'
formType='full'
update={false}
restrictedActions={{ update: false }}
// documentaionId={1}
customCreateAction={() => {
// navigate('/auth/patient/create');
} }
customActions={[
{
Icon: <Check className='icon-button-table' />,
cb: (id) => {
console.log('iddddd: ', id)
let waitingListId = +id;
console.log('idfgdg: ', waitingListId, typeof(waitingListId));
// setWaitingNumberId(waitingListId)
getDataFromBackend(waitingListId)
// committeeRequest.comitteeRequestGetAll()
// committeeRequest.approveCommitteeRequest(waitingListId)
// console.log('const a: ', a);
approveCommitteeRequestNotification()
},
tooltip: 'Approve',
},
]}
customOnRowClick={(row) => { } }
FormSubmitMapper={(data) => data}
mainPermissionName='Patient'
tableDataMapper={(data) => {
return data?.map((row: any) => {
return {
...row,
patient: row.patient?.label,
supervisoryDoctor: row.supervisoryDoctor?.label,
topographyIndex: row.topographyIndex?.label,
machine: row.machine?.label,
};
});
} } createFunc={function (data: any): Promise<any> {
throw new Error('Function not implemented.');
} } updateFunc={function (data: any): Promise<any> {
throw new Error('Function not implemented.');
} } getFunc={function (data: any): Promise<any> {
throw new Error('Function not implemented.');
} } deleteFunc={function (data: any): Promise<any> {
throw new Error('Function not implemented.');
} } />
</>
);
};
export default CommitteeRequestPage;
</code></pre>
| [
{
"answer_id": 74234211,
"author": "Jason Yang",
"author_id": 11936135,
"author_profile": "https://Stackoverflow.com/users/11936135",
"pm_score": 0,
"selected": false,
"text": "import PySimpleGUI as sg\n\nlayout = [\n [sg.Text(\"Hello World\")],\n [sg.Button('Submit'), sg.Button('C... | 2022/10/28 | [
"https://Stackoverflow.com/questions/74232707",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16377085/"
] |
74,232,723 | <p>I have multiple variables in my data frame with negative and positive values. Thus I'd like to normalize/scale the variables between -1, 1. I didnt find a working solution. Any suggestions? Thanks a lot!</p>
<p>I scaled other variables with the sklearn MinMaxScaler 0, 1. Didn't find an additional -1, 1 solution there.</p>
| [
{
"answer_id": 74234211,
"author": "Jason Yang",
"author_id": 11936135,
"author_profile": "https://Stackoverflow.com/users/11936135",
"pm_score": 0,
"selected": false,
"text": "import PySimpleGUI as sg\n\nlayout = [\n [sg.Text(\"Hello World\")],\n [sg.Button('Submit'), sg.Button('C... | 2022/10/28 | [
"https://Stackoverflow.com/questions/74232723",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14451760/"
] |
74,232,728 | <p>this is my model 'Order' and the 'Order_item' model has association with it</p>
<pre><code>class Order < ApplicationRecord
has_many :order_items
belongs_to :user
before_save :set_subtotal
def subtotal
order_items.collect { |order_item| order_item.valid? ? order_item.unit_price * order_item.quantity : 0 }.sum
end
private
def set_subtotal
self[:subtotal] = subtotal
end
end
</code></pre>
<p>2nd model:</p>
<pre><code>class OrderItem < ApplicationRecord
belongs_to :product
belongs_to :order
before_save :set_unit_price
before_save :set_total
def unit_price
# If there is a record
if persisted?
self[:unit_price]
else
product.price
end
end
def total
return unit_price * quantity
end
private
def set_unit_price
self[:unit_price] = unit_price
end
def set_total
self[:total] = total * quantity
end
end
</code></pre>
<p>i am trying to check the test case of RSPEC for the 'SUbtotal' function but i can't seem to find the logic</p>
<p>Rspec model file: Order</p>
<pre><code># frozen_string_literal: true
require 'rails_helper'
RSpec.describe Order, type: :model do
let(:user) { FactoryBot.create(:user) }
let(:subtotal) { FactoryBot.create(:order, subtotal: 1000) }
let(:items) { FactoryBot.create(:order_item) }
describe 'callbacks' do
it { is_expected.to callback(:set_subtotal).before(:save) }
end
describe 'associations' do
it { is_expected.to belong_to(:user) }
it { is_expected.to have_many(:order_items) }
end
#Gives Error i dont know how to get this
# describe 'subtotal' do
# it 'it should calculate the subtotal' do
# expect(Order.subtotal).to eq(1000)
# end
# end
end
</code></pre>
<p><a href="https://i.stack.imgur.com/izVxY.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/izVxY.png" alt="enter image description here" /></a></p>
| [
{
"answer_id": 74234211,
"author": "Jason Yang",
"author_id": 11936135,
"author_profile": "https://Stackoverflow.com/users/11936135",
"pm_score": 0,
"selected": false,
"text": "import PySimpleGUI as sg\n\nlayout = [\n [sg.Text(\"Hello World\")],\n [sg.Button('Submit'), sg.Button('C... | 2022/10/28 | [
"https://Stackoverflow.com/questions/74232728",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19697647/"
] |
74,232,742 | <p>The following code described bellow cannot connect to my Event Hub using Managed Identity and a separate VNet sub-net (please look into my Function and Event Hub settings)</p>
<p>PS: It`s possible to connect the Event Hub in case I temporary switch off the 'Selected networks' and turn on the 'Public access' and return it back for my Event Hub settings.</p>
<p>Additional Info: My Azure Function code is run as a Linux docker container and exposes the following ports: 80, 443, and for AMQP connection 5671, 5672</p>
<pre><code>const string ServiceBusNamespacePostfix = ".servicebus.windows.net"
var fullyQualifiedNamespace = eventHubSettings.Value.NameSpace.Contains(ServiceBusNamespacePostfix)
? eventHubSettings.Value.NameSpace
: $"{eventHubSettings.Value.NameSpace}{ServiceBusNamespacePostfix}";
_producerClient = new Azure.Messaging.EventHubs.Producer.EventHubProducerClient(fullyQualifiedNamespace, eventHubSettings.Value.Name, credential,
new EventHubProducerClientOptions
{
ConnectionOptions = new EventHubConnectionOptions
{
TransportType = EventHubsTransportType.AmqpTcp,
}
}
);
</code></pre>
<p>Azure Function settings:
<a href="https://i.stack.imgur.com/SWOW3.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/SWOW3.png" alt="enter image description here" /></a></p>
<p>Event Hub settings:
<a href="https://i.stack.imgur.com/jzDmi.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/jzDmi.png" alt="enter image description here" /></a></p>
<p>Please could anyone suggest what should I correct into the code and if my settings are wrong or I don<code>t understand VNet</code>s usage correctly?</p>
| [
{
"answer_id": 74234211,
"author": "Jason Yang",
"author_id": 11936135,
"author_profile": "https://Stackoverflow.com/users/11936135",
"pm_score": 0,
"selected": false,
"text": "import PySimpleGUI as sg\n\nlayout = [\n [sg.Text(\"Hello World\")],\n [sg.Button('Submit'), sg.Button('C... | 2022/10/28 | [
"https://Stackoverflow.com/questions/74232742",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20356320/"
] |
74,232,771 | <p>I have this list of dictionary and I would like to get those with the same exact value of 'name' and 'school' into a new list and also getting their 'age' merged into a list as well and the rest of the dictionary that is not identical to just add into the list as per usual..</p>
<p>Here is an example of the list of dictionary</p>
<pre><code>[{'name': 'Jane', 'age':12, 'school': 'SIT'}, {'name': 'John', 'age':13, 'school': 'SMU'},{'name': 'Jane', 'age':14, 'school': 'SIT'}, {'name': 'Jane', 'age':16, 'school': 'SIT'}, {'name': 'John', 'age':13, 'school': 'NUS'}]
</code></pre>
<p>and I would like it to make it into something like this..</p>
<pre><code>[{'name': 'Jane', 'age': [12,14,16], 'school': 'SIT'}, {'name': 'John', 'age': 13, 'school': 'SMU'}, {'name': 'John', 'age':13, 'school': 'NUS'}]
</code></pre>
<p>using Python.. please help!</p>
<p>tried using counter, loops but still can't get it to work..</p>
| [
{
"answer_id": 74233130,
"author": "Ashutosh Kulkarni",
"author_id": 18660435,
"author_profile": "https://Stackoverflow.com/users/18660435",
"pm_score": 0,
"selected": false,
"text": "x = [{'name': 'Jane', 'age':12, 'school': 'SIT'}, {'name': 'John', 'age':13, 'school': 'SMU'},{'name': ... | 2022/10/28 | [
"https://Stackoverflow.com/questions/74232771",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20356461/"
] |
74,232,795 | <p>i am newly startup react native framework here, i am using useState and useEffect to fetch data from api and store in useStete.
when i render or try to fetch data from api, at the first log/render is giving me undefined and the it's giving me data for the API.
The first undefined is making problem for me, so i want to avoid the first render for fetching data.
it's okay for me to give <strong>direct second render</strong> for the <strong>fetch data</strong> for API.</p>
<p>so either how can i overcome undefined here wait until <strong>give me fetch data or directly provide me second render</strong> avoid first render of undefined.</p>
<p>i am really appriciate your helping,</p>
<p>thanks in advance!</p>
<p><strong>Note: i don't want to initialize State to avoid undefined.</strong></p>
<pre><code>const [data, setData] = useState();
useEffect(() => {
fetch("https://jsonplaceholder.typicode.com/posts/5")
.then((response) => response.json())
.then((data) => setData(data))
.catch((error) => console.error(error))
}, []);
console.log(data);
</code></pre>
<p>output:
<a href="https://i.stack.imgur.com/5pRn7.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/5pRn7.png" alt="enter image description here" /></a></p>
| [
{
"answer_id": 74232883,
"author": "Guillaume Piedigrossi",
"author_id": 9488088,
"author_profile": "https://Stackoverflow.com/users/9488088",
"pm_score": 1,
"selected": false,
"text": "useEffect(…)\nif(!data) return null;\nreturn (<YourComponent />)\n"
},
{
"answer_id": 74232943... | 2022/10/28 | [
"https://Stackoverflow.com/questions/74232795",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19983659/"
] |
74,232,809 | <p>I created this component. file name: InputTextComponent.razor</p>
<pre><code><div class="form-group">
<label for="Name">Name</label>
<InputText @bind-Value="@Value"/>
</div>
@code {
[Parameter]
public string Value{ get; set; }
}
</code></pre>
<p>in the page index.razor</p>
<pre><code>@page "/"
<EditForm model="@data" OnValidSubmit="()=>OnClickBtn()">
<DataAnnotationsValidator></DataAnnotationsValidator>
<ValidationSummary></ValidationSummary>
<div class="modal-body">
<InputTextComponent Value="data.Name"/>
</div>
<div class="modal-footer justify-content-between">
<button type="button" >Cancel</button>
<button type="submit" class="btn btn-primary">OK</button>
</div>
</EditForm>
@code{
public class Item
{
public string Name { get; set; } = string.Empty;
}
private Item data { get; set; } = new Item(){ Name="John"};
private void OnClickBtn()
{
string k = "";
}
}
</code></pre>
<p>When I run, it show :</p>
<p>then i edit the name field. and press "ok" button.</p>
<p><a href="https://i.stack.imgur.com/0PG1M.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/0PG1M.png" alt="enter image description here" /></a></p>
<p>How to pass @bind-value into component. (the same InputText on blazor component).<br />
Thanks all!!</p>
| [
{
"answer_id": 74232883,
"author": "Guillaume Piedigrossi",
"author_id": 9488088,
"author_profile": "https://Stackoverflow.com/users/9488088",
"pm_score": 1,
"selected": false,
"text": "useEffect(…)\nif(!data) return null;\nreturn (<YourComponent />)\n"
},
{
"answer_id": 74232943... | 2022/10/28 | [
"https://Stackoverflow.com/questions/74232809",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14466616/"
] |
74,232,854 | <p>How can I use guard let like:</p>
<pre><code>guard let value = vm.value1 || let value = vm.value2 else { return }
</code></pre>
<p>I need to check value1, If it has value, continue to work with it, else check value2, and work with it, else: quit. Only one can have value.</p>
| [
{
"answer_id": 74232975,
"author": "Sweeper",
"author_id": 5133585,
"author_profile": "https://Stackoverflow.com/users/5133585",
"pm_score": 3,
"selected": true,
"text": "guard let value = vm.value1 ?? vm.value2 else { return }\n"
},
{
"answer_id": 74233808,
"author": "Ahsan ... | 2022/10/28 | [
"https://Stackoverflow.com/questions/74232854",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19793331/"
] |
74,232,870 | <p>I have two tables. One is ACTUAL_FLIGHTS and other is SCHEDULED_FLIGHTS.</p>
<p><strong>ACTUAL_FLIGHTS:</strong></p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th style="text-align: center;">Aircraft</th>
<th style="text-align: center;">Type</th>
<th style="text-align: center;">FLIGHT_DATE</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align: center;">BBQ</td>
<td style="text-align: center;">A320</td>
<td style="text-align: center;">26-OCT-2022</td>
</tr>
<tr>
<td style="text-align: center;">AFC</td>
<td style="text-align: center;">A321</td>
<td style="text-align: center;">27-OCT-2022</td>
</tr>
<tr>
<td style="text-align: center;">JFK</td>
<td style="text-align: center;">A321</td>
<td style="text-align: center;">25-OCT-2022</td>
</tr>
<tr>
<td style="text-align: center;">AFC</td>
<td style="text-align: center;">A321</td>
<td style="text-align: center;">22-OCT-2022</td>
</tr>
</tbody>
</table>
</div>
<p><strong>SCHEDULED_FLIGHTS</strong></p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th style="text-align: center;">Aircraft</th>
<th style="text-align: center;">Type</th>
<th style="text-align: center;">SCHEDULE_DATE</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align: center;">BBQ</td>
<td style="text-align: center;">A320</td>
<td style="text-align: center;">28-OCT-2022</td>
</tr>
<tr>
<td style="text-align: center;">AFC</td>
<td style="text-align: center;">A321</td>
<td style="text-align: center;">27-OCT-2022</td>
</tr>
<tr>
<td style="text-align: center;">JFK</td>
<td style="text-align: center;">A321</td>
<td style="text-align: center;">29-OCT-2022</td>
</tr>
<tr>
<td style="text-align: center;">AFC</td>
<td style="text-align: center;">A321</td>
<td style="text-align: center;">30-OCT-2022</td>
</tr>
</tbody>
</table>
</div>
<p>Now I need to count number of days between last flight and the next scheduled flight for each Aircraft. Resulting table should look like this:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th style="text-align: center;">Aircraft</th>
<th style="text-align: center;">DIFF_DAYS</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align: center;">BBQ</td>
<td style="text-align: center;">2</td>
</tr>
<tr>
<td style="text-align: center;">AFC</td>
<td style="text-align: center;">0</td>
</tr>
<tr>
<td style="text-align: center;">JFK</td>
<td style="text-align: center;">4</td>
</tr>
</tbody>
</table>
</div>
<p>I've tried this query, but didn't get intended result, even it frezees while generating result:</p>
<pre><code>SELECT s.AC,
MIN(s.SCHEDULE_DATE) - MAX(f.FLIGHT_DATE)
FROM SCHEDULE_FLIGHT s
INNER JOIN FLIGHT_DATE f ON f.AC = s.AC
HAVING MIN(s.SCHEDULE_DATE) >= MAX(f.FLIGHT_DATE)
GROUP BY s.AC;
</code></pre>
| [
{
"answer_id": 74232975,
"author": "Sweeper",
"author_id": 5133585,
"author_profile": "https://Stackoverflow.com/users/5133585",
"pm_score": 3,
"selected": true,
"text": "guard let value = vm.value1 ?? vm.value2 else { return }\n"
},
{
"answer_id": 74233808,
"author": "Ahsan ... | 2022/10/28 | [
"https://Stackoverflow.com/questions/74232870",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16561042/"
] |
74,232,958 | <p>I have the following input data:</p>
<p><a href="https://i.stack.imgur.com/S7ZFj.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/S7ZFj.png" alt="enter image description here" /></a></p>
<p>I want to get a formula that can sort out descending order values for the factors across the three treatments.</p>
<p>For a particular factor, the formula should return A for six (6) consecutive descending ordered values within the treatment, B for four (4) consecutive descended order values, C for three (3) consecutive descended ordered values, and blank otherwise.</p>
<p>Here is the expected output from the input data sample:</p>
<p><a href="https://i.stack.imgur.com/6jNXY.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/6jNXY.png" alt="enter image description here" /></a></p>
<p><strong>Notes</strong>:</p>
<ol>
<li>I'm using office 365, please consider that in your answer</li>
<li>I need a formula with drag and drop than doing it manually because in some cases, the factors are up to 100 and more than 70 treatments...</li>
</ol>
| [
{
"answer_id": 74232975,
"author": "Sweeper",
"author_id": 5133585,
"author_profile": "https://Stackoverflow.com/users/5133585",
"pm_score": 3,
"selected": true,
"text": "guard let value = vm.value1 ?? vm.value2 else { return }\n"
},
{
"answer_id": 74233808,
"author": "Ahsan ... | 2022/10/28 | [
"https://Stackoverflow.com/questions/74232958",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20322472/"
] |
74,232,966 | <p>We have a scenario where we need to replace the TargetOriginID of CacheBehaviour in the distribution of a json file. We need to replace the Existing TargetOriginID with New Values. I have tried with below jq command but not getting any closer</p>
<pre><code>for targetoriginID in $(jq '(.CacheBehaviors.Items[].TargetOriginId)' distconfig.json);
do
echo "#######fetch the new value from change behaviour json file"#######
NewValue=$(jq -r "map(select(.targetoriginid == ""$targetoriginID""))[].targetorigindr" changebehaviour.json)
echo "#########replace value in dist config json file with new value from change behaviour###########"
jq -r '(.CacheBehaviors.Items[].TargetOriginId | select(. == "$targetoriginID")) = "$NewValue"' distconfig.json > "tmp" && mv "tmp" distconfig.json
</code></pre>
<pre class="lang-json prettyprint-override"><code>{
"CachedMethods": {
"Quantity": 3,
"Items": [
"HEAD",
"GET",
"OPTIONS"
]
}
},
"SmoothStreaming": false,
"Compress": false,
"LambdaFunctionAssociations": {
"Quantity": 0
},
"FunctionAssociations": {
"Quantity": 0
},
"FieldLevelEncryptionId": "",
"ForwardedValues": {
"QueryString": true,
"Cookies": {
"Forward": "none"
},
"Headers": {
"Quantity": 9,
"Items": [
"Authorization",
"Origin",
"access-control-allow-credentials",
"expires",
"access-control-max-age",
"access-control-allow-headers",
"cache-control",
"access-control-allow-methods",
"pragma"
]
},
"QueryStringCacheKeys": {
"Quantity": 1,
"Items": [
"*"
]
}
},
"MinTTL": 0,
"DefaultTTL": 86400,
"MaxTTL": 31536000
},
"CacheBehaviors": {
"Quantity": 2,
"Items": [
{
"PathPattern": "jkl/*",
"TargetOriginId": "nkl/Prod",
"TrustedSigners": {
"Enabled": false,
"Quantity": 0
},
"TrustedKeyGroups": {
"Enabled": false,
"Quantity": 0
},
"ViewerProtocolPolicy": "redirect-to-https",
"AllowedMethods": {
"Quantity": 7,
"Items": [
"HEAD",
"DELETE",
"POST",
"GET",
"OPTIONS",
"PUT",
"PATCH"
],
"CachedMethods": {
"Quantity": 3,
"Items": [
"HEAD",
"GET",
"OPTIONS"
]
}
},
"SmoothStreaming": false,
"Compress": false,
"LambdaFunctionAssociations": {
"Quantity": 0
},
"FunctionAssociations": {
"Quantity": 0
},
"FieldLevelEncryptionId": "",
"ForwardedValues": {
"QueryString": true,
"Cookies": {
"Forward": "all"
},
"Headers": {
"Quantity": 9,
"Items": [
"Authorization",
"Origin",
"access-control-allow-credentials",
"access-control-max-age",
"access-control-allow-headers",
"cache-control",
"access-control-allow-methods",
"expirers",
"pragma"
]
},
"QueryStringCacheKeys": {
"Quantity": 1,
"Items": [
"*"
]
}
},
"MinTTL": 0,
"DefaultTTL": 86400,
"MaxTTL": 31536000
},
{
"PathPattern": "fgh/*",
"TargetOriginId":"xyz/Prod",
"TrustedSigners": {
"Enabled": false,
"Quantity": 0
},
"TrustedKeyGroups": {
"Enabled": false,
"Quantity": 0
},
"ViewerProtocolPolicy": "redirect-to-https",
"AllowedMethods": {
"Quantity": 7,
"Items": [
"HEAD",
"DELETE",
"POST",
"GET",
"OPTIONS",
"PUT",
"PATCH"
],
"CachedMethods": {
"Quantity": 3,
"Items": [
"HEAD",
"GET",
"OPTIONS"
]
}
},
"SmoothStreaming": false,
"Compress": false,
"LambdaFunctionAssociations": {
"Quantity": 0
},
"FunctionAssociations": {
"Quantity": 0
},
"FieldLevelEncryptionId": "",
"ForwardedValues": {
"QueryString": true,
"Cookies": {
"Forward": "none"
},
"Headers": {
"Quantity": 10,
"Items": [
"access-control-allow-origin",
"authorization",
"Origin",
"access-control-allow-credentials",
"access-control-max-age",
"access-control-allow-headers",
"cache-control",
"access-control-allow-methods",
"expirers",
"pragma"
]
},
"QueryStringCacheKeys": {
"Quantity": 1,
"Items": [
"*"
]
}
},
"MinTTL": 0,
"DefaultTTL": 0,
"MaxTTL": 0
}
]
}
</code></pre>
<p>Looking for a solution to make bulk change in CacheBehaviour for all TargetOriginID's</p>
| [
{
"answer_id": 74233123,
"author": "peak",
"author_id": 997358,
"author_profile": "https://Stackoverflow.com/users/997358",
"pm_score": 0,
"selected": false,
"text": "jq --arg newvalue xyz '\n (.. | objects | select(has(\"TargetOriginId\")) | .TargetOriginId) |= $newvalue\n'\n"
},
{... | 2022/10/28 | [
"https://Stackoverflow.com/questions/74232966",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20356611/"
] |
74,232,979 | <p>I have 20 input fields in my app. What is the best way to define <code>TextFormField</code> widgets?</p>
<p>For example:</p>
<pre><code>Column(
children: [
_buildCariUnvanTextField(unvanController),
_buildCariUnvanTextField(unvanController),
_buildCariUnvanTextField(unvanController),
_buildCariUnvanTextField(unvanController),
_buildCariUnvanTextField(unvanController),
_buildCariUnvanTextField(unvanController),
_buildCariUnvanTextField(unvanController),
_buildCariUnvanTextField(unvanController),
_buildCariUnvanTextField(unvanController),
_buildCariUnvanTextField(unvanController),
],
),
</code></pre>
<p>Should I have 20 separate methods? Is it the correct way to define? Or what should I do? Can anyone explain?</p>
| [
{
"answer_id": 74233256,
"author": "My Car",
"author_id": 16124033,
"author_profile": "https://Stackoverflow.com/users/16124033",
"pm_score": 0,
"selected": false,
"text": "ListView.builder"
}
] | 2022/10/28 | [
"https://Stackoverflow.com/questions/74232979",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11764250/"
] |
74,232,992 | <p>I am kind of stuck. I have thought of the idea to use the .insertBefore() but I am not sure where to place the syntax. I also need to add checkboxes instead of the bullets that automaticly apear when using , I have no clue have to do this.
My code is as follows.
HTML</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 n = [];
function changeText() {
inputText = document.getElementById('inputText').value;
n.push(inputText);
document.querySelector('#list ul').innerHTML += "<li>" + inputText
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><html lang="en">
<head>
<title>To-Do list</title>
<mmeta charset="UTF-8">
<link rel="stylesheet" href="todoStyle.css">
</head>
<body>
<div id="form">
<h1>New Task</h1>
<div id="button">
<button onclick="changeText()">Add to list</button>
</div>
<div id="input">
<input type="text" id="inputText" name="addNewList">
</div>
</div>
<div class="list1" id="list">
<h1>My to-do list</h1>
<ul>
</ul>
</div>
<script src="todo.js"></script>
</body>
</html></code></pre>
</div>
</div>
</p>
<p>I tried inserting the .insertBefore() in a new document.getElementById. But I was not sure where to insert this line of code.</p>
| [
{
"answer_id": 74233256,
"author": "My Car",
"author_id": 16124033,
"author_profile": "https://Stackoverflow.com/users/16124033",
"pm_score": 0,
"selected": false,
"text": "ListView.builder"
}
] | 2022/10/28 | [
"https://Stackoverflow.com/questions/74232992",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20229542/"
] |
74,233,002 | <p>I want to have a SystemVerilog function that can accept any number of string arguments, this function is essentially a wrapper around the in-built <code>$display</code> as such I want users to be able to call the function in the same way, passing any number of strings into <code>myfunc()</code> as follows:</p>
<pre><code>myfunc(stringVar1, "literalString", stringVar2, stringVarN, intVarToConvertToString);
</code></pre>
<p>My current implementation is to just have a single string arg and use the SystemVerilog concatenation operator to concatenate all the strings I wish to pass; e.g.</p>
<pre><code>myfunc({stringVar1, "literalString", stringVar2, stringVarN, intVarToConvertToString});
</code></pre>
<p>however when I try to pass in a numeric type like <code>int</code> as a concatenated string, it isn't being converted into a string representation of its value correctly, and the <code>�</code> character is printed in its place. I have also tried to perform an explicit string cast on the non-string types being concatenated but to no avail.</p>
<p>I know that if I got all of the arguments to my function separately I can then just pass them directly to <code>$display</code> which does correctly convert the number types to their string representation to display them. Does anyone know how I would do this in System Verilog?</p>
| [
{
"answer_id": 74236163,
"author": "Serge",
"author_id": 1143850,
"author_profile": "https://Stackoverflow.com/users/1143850",
"pm_score": 0,
"selected": false,
"text": "{}"
},
{
"answer_id": 74236321,
"author": "Mikef",
"author_id": 899862,
"author_profile": "https:/... | 2022/10/28 | [
"https://Stackoverflow.com/questions/74233002",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11127623/"
] |
74,233,022 | <p>I need to search a string for a substring, if the substring is found print the string upto the end of the substring.i.e</p>
<pre><code>str="this is a long string"
substring="long"
expected="this is a long"
</code></pre>
<p>I have tried bash string manipulation and failed. Tried to use an <strong>awk</strong> command, but I can't get it right.
This works if substring is not in a variable, but I require it in a variable since the input varies.</p>
<p><code>awk -F'long' '{print $1}' <<<$str</code></p>
<pre><code>awk -v myvar="$substring" -F'myvar' '{print $1}' <<<$str
</code></pre>
<p>prints the whole string.
Any help will be appreciated.</p>
| [
{
"answer_id": 74236163,
"author": "Serge",
"author_id": 1143850,
"author_profile": "https://Stackoverflow.com/users/1143850",
"pm_score": 0,
"selected": false,
"text": "{}"
},
{
"answer_id": 74236321,
"author": "Mikef",
"author_id": 899862,
"author_profile": "https:/... | 2022/10/28 | [
"https://Stackoverflow.com/questions/74233022",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2562052/"
] |
74,233,047 | <p>Say I want to make a function more flexible, by allowing as parameters either:</p>
<ul>
<li>an element of type number</li>
<li>any generic element + a converter function that converts it into a number</li>
</ul>
<pre><code>type ElementConvertor<T> = T extends number ? never : (element: T) => number
function isNumber(x: any): x is number {
return typeof x === "number"
}
function evaluate<T>(element: T, toNumber: ElementConvertor<T>) {
if (isNumber(element)) return element
else return toNumber(element)
}
const main = () => {
const array1 = [1, 2, 3];
const array1Value = array1.map(x => evaluate(x));
// -> TS compiler complains here
//input.tsx(7, 34): An argument for 'toNumber' was not provided.
const array2 = [{ value: 1 }, { value: 2 }, { value: 3 }]
const array2Value = array2.map((x => evaluate(x, ({ value }) => value)))
console.log(array1Value, array2Value)
}
</code></pre>
<p><a href="https://www.typescriptlang.org/play?#code/C4TwDgpgBAogNhAthAdsAwgexQNwgJ2E3wB4AVAPigF4oyoIAPYVAEwGcoUBXRAIwJQA-Fwh58UAFxQAFBATI00sgEoaVHvwIAobQDNuKAMbAAltiin2AOV4D8MxtICGKECumNLnTfagBvbShgqHwIYG58FChQSEw9KC9qZKgAIl8CVO0AX10DYzMLMWc4bmcWcgo5BVRgZQAaGMxbLXxpeCRarFwCIlJKNUCQywSZKxb7as60FTUwiKiGGrQgkPl2aHnI6KIJginFYBUc3W0jbHZgKERnU2jaGTVqKiGQ85RLqGd8fGcQAEYaFAANr-RoAJkaAGYALoAblWwXen2+vwBADUStxoLRUX9-gA6G5gRzqBg4LHlCCOWYIxFQZFXPEgcFA4H+KAU0oQaSA7KNDlc7HSVn8gKcrE8qBQqDZGH0xlfH5-cGY7lA5ngonOEmk57kyksRyNGSCyWyp5UIUQWbHXTDZGYBAEuCYADmMmZ-zV2Mamp9NpOQA" rel="nofollow noreferrer">Link to TS playground</a></p>
<p>What am I missing? Thanks</p>
| [
{
"answer_id": 74233279,
"author": "Svetoslav Petkov",
"author_id": 11612861,
"author_profile": "https://Stackoverflow.com/users/11612861",
"pm_score": 3,
"selected": true,
"text": "//delcare overload signatures\nfunction evaluate(element: number): number;\nfunction evaluate<T>(element: ... | 2022/10/28 | [
"https://Stackoverflow.com/questions/74233047",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5201562/"
] |
74,233,063 | <p>I'm using Moq for mocking a method call and I want to mock a null response. The <code>Login</code> method returns a <code>LoginResult</code> type.</p>
<p>My Login interface:</p>
<pre><code>public async Task<LoginResult> Login(string userPin)
</code></pre>
<p>My unit test mock:</p>
<pre><code>var credentialsService = new Mock<ICredentialsService>();
credentialsService.Setup(x => x.Login("1234")).ReturnsAsync((LoginResult)null);
</code></pre>
<p>With the above mock, I receive the following warnings:</p>
<p>warning 1:</p>
<blockquote>
<p>Warning CS8600 Converting null literal or possible null value to non-nullable type</p>
</blockquote>
<p>warning 2:</p>
<blockquote>
<p>Argument of type 'ISetup<ICredentialsService, Task>' cannot be used for parameter 'mock' of type 'IReturns<ICredentialsService, Task<LoginResult?>>' in 'IReturnsResult ReturnsExtensions.ReturnsAsync<ICredentialsService, LoginResult?>(IReturns<ICredentialsService, Task<LoginResult?>> mock, LoginResult? value)' due to differences in the nullability of reference types.</p>
</blockquote>
<p>How can I resolve these two warnings?</p>
| [
{
"answer_id": 74233279,
"author": "Svetoslav Petkov",
"author_id": 11612861,
"author_profile": "https://Stackoverflow.com/users/11612861",
"pm_score": 3,
"selected": true,
"text": "//delcare overload signatures\nfunction evaluate(element: number): number;\nfunction evaluate<T>(element: ... | 2022/10/28 | [
"https://Stackoverflow.com/questions/74233063",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2903635/"
] |
74,233,107 | <p>I have (builtin) <code>settings sync</code> on in VSCode. For various workspaces I use the the workspace settings to give titleBar of each workspace a different color for easy recognition. However everytime I re-open a workspace (for which I set workspace settings for titleBar colorCustomizations) VSCode tries to overwrite the values in workspace <code>settings.json</code> into the ones used in user <code>settings.json</code>.</p>
<p>Example the workspace <code>settings.json</code> I set for the workspace:</p>
<pre><code>{
"workbench.colorCustomizations": {
"titleBar.activeBackground": "#f558be",
"titleBar.activeForeground": "#ffffff",
"titleBar.inactiveBackground": "#f424ac",
"titleBar.inactiveForeground": "#cccccc",
"editorGhostText.border": "#d94e4e",
"editorGhostText.foreground": "#b95454",
},
}
</code></pre>
<p>Which at re-opening are overwritten and thus changed into:</p>
<pre><code>{
"workbench.colorCustomizations": {
"editorGhostText.border": "#d94e4e",
"editorGhostText.foreground": "#b95454"
},
}
</code></pre>
<p>I tried setting:</p>
<pre><code> "settingsSync.ignoredSettings": [
"workbench.colorCustomizations"
],
</code></pre>
<p>in <code>User</code> settings, but that seems only works on user settings, as it does not solve my issue. The <code>settingsSync.ignoredSettings</code>, which might solve my issue, can not be set on <code>Workspace</code> settings.</p>
<p>I tried adding <code>vscode/</code> or <code>vscode/settings.json</code> to the <code>.gitignore</code> file of my project, but issue remains.</p>
<p>How can I avoid VSCode trying to overwrite my workspace settings?</p>
| [
{
"answer_id": 74233279,
"author": "Svetoslav Petkov",
"author_id": 11612861,
"author_profile": "https://Stackoverflow.com/users/11612861",
"pm_score": 3,
"selected": true,
"text": "//delcare overload signatures\nfunction evaluate(element: number): number;\nfunction evaluate<T>(element: ... | 2022/10/28 | [
"https://Stackoverflow.com/questions/74233107",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3294412/"
] |
74,233,117 | <p>I'm trying to filter the <code>array</code> by the <code>numbers</code>. Basically, car with id <code>48</code> should be deleted because it does not exist on <code>numbers</code></p>
<p>What am I missing here??
<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 numbers = [49, 482, 49, 49, 49, 1135, 49, 1709, 1044, 1016, 30];
const array = [{
cars: [{
id: 48
}, {
id: 49
}]
}];
array.forEach(elem => elem.cars.filter(car => !numbers.includes(car.id)));
console.log(array);</code></pre>
</div>
</div>
</p>
<p>I want to keep the same structure, I just want tot delete the car with id <code>48</code></p>
| [
{
"answer_id": 74233185,
"author": "naveen",
"author_id": 17447,
"author_profile": "https://Stackoverflow.com/users/17447",
"pm_score": 2,
"selected": true,
"text": "forEach"
},
{
"answer_id": 74233325,
"author": "Phani",
"author_id": 16149885,
"author_profile": "http... | 2022/10/28 | [
"https://Stackoverflow.com/questions/74233117",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12046376/"
] |
74,233,128 | <p>I got a server running on <strong>0.0.0.0:18830</strong>.
On <strong>windows</strong> when I trying to connect to this server with python socket</p>
<pre><code>socket.connect_ex('0.0.0.0', 18830)
</code></pre>
<p>it returns <strong>10049</strong></p>
<p>with the following code</p>
<pre><code>socket.connect_ex('127.0.0.1', 18830)
</code></pre>
<p>it returns <strong>0</strong> which means ok</p>
<p>However when I run the server and the two codes above on <strong>WSL Debian</strong>
Both commands will return <strong>0</strong></p>
<p>Any explains on why it happens like this?</p>
| [
{
"answer_id": 74233185,
"author": "naveen",
"author_id": 17447,
"author_profile": "https://Stackoverflow.com/users/17447",
"pm_score": 2,
"selected": true,
"text": "forEach"
},
{
"answer_id": 74233325,
"author": "Phani",
"author_id": 16149885,
"author_profile": "http... | 2022/10/28 | [
"https://Stackoverflow.com/questions/74233128",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4935801/"
] |
74,233,144 | <p>I have added a Video to visualize my problem better: <a href="https://streamable.com/wdhna2" rel="nofollow noreferrer">https://streamable.com/wdhna2</a></p>
<p>The problem is that my images load slowly, even I added a precache method and a splash screen. On first boot, the problem isn't that big, maybe because of the precache.
here I'm implementing the precache method:</p>
<pre><code>class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
loadImage(context); <--- Method call
SystemChrome.setPreferredOrientations([
DeviceOrientation.portraitUp,
DeviceOrientation.portraitDown,
]);
</code></pre>
<p>and here is my precache method (just a snipped, not for all pictures):</p>
<pre><code>import 'package:flutter/material.dart';
void loadImage(context){
precacheImage(const AssetImage("assets/widgetsImages/bmi.jpg"), context);
precacheImage(const AssetImage("assets/widgetsImages/calc.webp"), context);
precacheImage(const AssetImage("assets/widgetsImages/chat.webp"), context);
}
</code></pre>
<p>I also tried to add a splash screen with the flutter_native_splash package, but this wouldn't fix the problem that the images load slowly after I close and reopen the app, without clearing my RAM. Anyway, here is the code for that:</p>
<pre><code>Future<void> main() async {
WidgetsBinding widgetsBinding = WidgetsFlutterBinding.ensureInitialized();
FlutterNativeSplash.preserve(widgetsBinding: widgetsBinding);
</code></pre>
<p>and the end of the splashscreen when the first window opens:</p>
<pre><code>class _NutriWidgetState extends State<NutriWidget> {
@override
void initState() {
super.initState();
FlutterNativeSplash.remove();
}
</code></pre>
<p>Do you have an idea how I could load the images faster? Do I do something wrong?</p>
| [
{
"answer_id": 74233185,
"author": "naveen",
"author_id": 17447,
"author_profile": "https://Stackoverflow.com/users/17447",
"pm_score": 2,
"selected": true,
"text": "forEach"
},
{
"answer_id": 74233325,
"author": "Phani",
"author_id": 16149885,
"author_profile": "http... | 2022/10/28 | [
"https://Stackoverflow.com/questions/74233144",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19913052/"
] |
74,233,146 | <p>if you have a function that returns a struct, is it then possible to access on of the internal values in struct that is returned, without having to handling the whole struct.</p>
<p>The code could look something like this;</p>
<pre><code>struct myStruct
{
int value1;
int value2;
};
myStruct functionReturningStruct(void);
....
value2 = functionReturningStruct().value2
</code></pre>
<p>if it's possible in anyway, how?</p>
| [
{
"answer_id": 74233372,
"author": "CGi03",
"author_id": 18646208,
"author_profile": "https://Stackoverflow.com/users/18646208",
"pm_score": 1,
"selected": false,
"text": "#include <stdio.h>\n\nstruct myStruct\n{\n int value1;\n int value2;\n};\n\nstruct myStruct functionReturningS... | 2022/10/28 | [
"https://Stackoverflow.com/questions/74233146",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14649629/"
] |
74,233,148 | <p>I'm trying to understand the concept of pointers. So I wrote a code (from a book I have) but It doesn't complile. Can't understand what is wrong, again I wrote exactly how it is in the book, and I checked if there are some mistakes, but I can't find any...</p>
<p>Here is the code:</p>
<pre><code>#include <stdio.h>
int var = 1;
int *ptr;
int main(void)
{
ptr = &var;
printf("Var = %d", var);
printf("Var = %d", *ptr);
printf("The adress of the variable = %d", &var);
printf("The adress = %d", ptr);
return 0;
}
</code></pre>
<p>Here are the errors I got:</p>
<pre class="lang-none prettyprint-override"><code>ø.c:13:47: error: format specifies type 'int' but the argument has
type 'int *' [-Werror,-Wformat]
printf("The adress of the variable = %d", &var);
~~ ^~~~ ø.c:14:31: error: format specifies type 'int' but the argument has type 'int *'
[-Werror,-Wformat]
printf("The adress = %d", ptr);
~~ ^~~
</code></pre>
| [
{
"answer_id": 74233240,
"author": "Lakshana. S",
"author_id": 20356790,
"author_profile": "https://Stackoverflow.com/users/20356790",
"pm_score": -1,
"selected": false,
"text": " #include <stdio.h>\n\n int main(void)\n {\n int var = 1;\n int *ptr;\n ptr = &var; \n \n p... | 2022/10/28 | [
"https://Stackoverflow.com/questions/74233148",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20228582/"
] |
74,233,163 | <p>I'm looping through an array of items to check the corresponding element in order to display them in the correct order.</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 array1 = ["one", "two", "three", "four"]
const array2 = ["two", "three", "one", "four"]
for (i = 0; i < array1.length; i++) {
console.log(array1);
console.log(array1.filter((element) => array2.includes(element)));
// here I'm trying to iterate through each element of array1 and find the corresponding element in array2.
}</code></pre>
</div>
</div>
</p>
<p>The expected output should be something like :</p>
<pre><code>the corresponding array of array1[0] is array2[2],
the corresponding array of array1[1] is array2[1],
and so on.
</code></pre>
| [
{
"answer_id": 74233253,
"author": "fusion",
"author_id": 12531598,
"author_profile": "https://Stackoverflow.com/users/12531598",
"pm_score": 1,
"selected": false,
"text": "const array1 = [\"one\", \"two\", \"three\", \"four\"]\nconst array2 = [\"two\", \"three\", \"one\", \"four\"]\n\nf... | 2022/10/28 | [
"https://Stackoverflow.com/questions/74233163",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9011747/"
] |
74,233,170 | <p>I have this sample situation</p>
<pre><code><div class="main-class"></div>
</code></pre>
<p>in the css</p>
<pre><code>.main-class {
maring-top:1px
}
</code></pre>
<p>so sometimes in my div I add at run time some other class so it could be</p>
<pre><code><div class="main-class a"></div>
</code></pre>
<p>or</p>
<pre><code><div class="main-class b"></div>
</code></pre>
<p>or</p>
<pre><code><div class="main-class c"></div>
</code></pre>
<p>so in my css</p>
<pre><code>.main-class.c{
margin-top: 5px;
}
.main-class.a{
margin-top: 5px;
}
.main-class.b{
margin-top: 5px;
}
</code></pre>
<p>or simply</p>
<pre><code>.main-class.c,
.main-class.a,
.main-class.b{
margin-top: 5px;
}
</code></pre>
<p><strong>this is too long</strong>, is there any other ways to do this
<strong>if .main-class has any other (a , b , c) so the margin will be 5px?</strong></p>
<p>I tried this</p>
<pre><code>.main-class:has(.a, .b, .c)
{
margin-top :5xp;
}
</code></pre>
<p>and this does not work</p>
| [
{
"answer_id": 74233316,
"author": "connexo",
"author_id": 3744304,
"author_profile": "https://Stackoverflow.com/users/3744304",
"pm_score": 3,
"selected": true,
"text": "maring-top"
},
{
"answer_id": 74233447,
"author": "Cédric",
"author_id": 17684809,
"author_profil... | 2022/10/28 | [
"https://Stackoverflow.com/questions/74233170",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/287964/"
] |
74,233,181 | <p>I am trying to show two nested circles in my ggplot object using <code>ggforce::geom_circle</code> that look like this:</p>
<p><a href="https://i.stack.imgur.com/oN8R2.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/oN8R2.png" alt="enter image description here" /></a></p>
<p>It definitely works when I am plotting two circles:</p>
<p><a href="https://i.stack.imgur.com/b9yaw.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/b9yaw.png" alt="enter image description here" /></a></p>
<p>but if I try to limit the x and y axis using <code>scale_x</code> or <code>coord_cartesian</code> either my polygons are weirdly cut, or not shown:</p>
<p><a href="https://i.stack.imgur.com/5UnMQ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/5UnMQ.png" alt="enter image description here" /></a></p>
<p>What can be the issue?</p>
<p>Here is a dummy example:</p>
<pre><code>library(ggforce)
set.seed(4242)
dd <- data.frame(x = runif(20, min=0, max=2),
y = runif(20, min=0, max=2))
# There's presumably a way to do this within the above mutate function using case_when()
ggplot(dd) +
geom_circle(aes(x0 = 0, y0 = 0, r = 2),
inherit.aes = FALSE, fill = 'grey90',
lty = 'dotted', color = 'grey70', alpha = 0.5) +
geom_circle(aes(x0 = 0, y0 = 0, r = 0.5),
inherit.aes = FALSE, fill = 'grey70',
lty = 'dotted', color = 'grey50', alpha = 0.5) +
geom_point(aes(x = x, y = y), size=1)+
geom_abline(intercept = 0, slope=0.5, col='red') +
geom_abline(intercept = 0, slope=1.8, col='blue') +
#scale_x_continuous(expand = c(0, 0), limits = c(0, 2)) +
#scale_y_continuous(expand = c(0, 0), limits = c(0, 2)) +
coord_cartesian(xlim = c(0,2.5), # try to limit the xy axis in two ways
ylim = c(0,2.5)) +
theme_bw() +
theme_update(legend.position = 'bottom') +
theme_update(aspect.ratio=1)
</code></pre>
<p>Session info:</p>
<pre><code> R version 4.1.1 (2021-08-10)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 10 x64 (build 17763)
Matrix products: default
locale:
[1] LC_COLLATE=English_United States.1252
[2] LC_CTYPE=English_United States.1252
[3] LC_MONETARY=English_United States.1252
[4] LC_NUMERIC=C
[5] LC_TIME=English_United States.1252
attached base packages:
[1] stats graphics grDevices utils datasets methods base
other attached packages:
[1] ggforce_0.4.1 ggplot2_3.3.6
loaded via a namespace (and not attached):
[1] Rcpp_1.0.7 magrittr_2.0.2 MASS_7.3-54 tidyselect_1.1.2
[5] munsell_0.5.0 colorspace_2.0-2 R6_2.5.1 rlang_1.0.2
[9] fansi_1.0.2 dplyr_1.0.8 tools_4.1.1 grid_4.1.1
[13] gtable_0.3.0 utf8_1.2.2 cli_3.2.0 DBI_1.1.2
[17] withr_2.5.0 ellipsis_0.3.2 digest_0.6.28 assertthat_0.2.1
[21] tibble_3.1.6 lifecycle_1.0.1 crayon_1.5.0 farver_2.1.0
[25] tweenr_1.0.2 purrr_0.3.4 vctrs_0.3.8 glue_1.6.2
[29] labeling_0.4.2 polyclip_1.10-4 compiler_4.1.1 pillar_1.7.0
[33] generics_0.1.2 scales_1.1.1 pkgconfig_2.0.3
</code></pre>
| [
{
"answer_id": 74233232,
"author": "Quinten",
"author_id": 14282714,
"author_profile": "https://Stackoverflow.com/users/14282714",
"pm_score": 1,
"selected": false,
"text": "expand"
},
{
"answer_id": 74261225,
"author": "maycca",
"author_id": 2742140,
"author_profile"... | 2022/10/28 | [
"https://Stackoverflow.com/questions/74233181",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2742140/"
] |
74,233,183 | <p>There is a Template restriction,
the 5th step must be NavigationTemplate, PaneTemplate or MessageTemplate.</p>
<p>I'd like to know How to get the current total number of steps.</p>
| [
{
"answer_id": 74233232,
"author": "Quinten",
"author_id": 14282714,
"author_profile": "https://Stackoverflow.com/users/14282714",
"pm_score": 1,
"selected": false,
"text": "expand"
},
{
"answer_id": 74261225,
"author": "maycca",
"author_id": 2742140,
"author_profile"... | 2022/10/28 | [
"https://Stackoverflow.com/questions/74233183",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13753575/"
] |
74,233,203 | <p>What is the event that a function will be triggered when the user is clicking on the red close button.
I need to create a little lets name it log item when thiss happens in a txt file.</p>
<p>I searched but didn't find any solution</p>
<pre><code>private void Window_Closing1(object sender, System.Windows.Forms.FormClosingEventArgs e)
{
}
private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
}
</code></pre>
| [
{
"answer_id": 74233271,
"author": "jmcilhinney",
"author_id": 584183,
"author_profile": "https://Stackoverflow.com/users/584183",
"pm_score": 1,
"selected": false,
"text": "Closing"
},
{
"answer_id": 74237057,
"author": "jtxkopt",
"author_id": 7141410,
"author_profil... | 2022/10/28 | [
"https://Stackoverflow.com/questions/74233203",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20356767/"
] |
74,233,204 | <p>I am writing a python program to calculate the chi-square value for a set of observed and expected frequencies. The program that I have constructed is written like so</p>
<pre><code># Author: Evan Gertis
# Date : 10/25
# program : quantile decile calculator
import csv
import pandas as pd
import numpy as np
from scipy.stats import chi2_contingency
import seaborn as sns
import matplotlib.pyplot as plt
import logging
logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s')
# Step 1: read csv
dicerollsCSV = open('dice_rolls.csv')
df = pd.read_csv(dicerollsCSV)
logging.debug(df['Observed'])
logging.debug(df['Expected'])
# Step 2: Convert the data into a contingency table
logging.debug('Step 2: Convert the data into a contingency tables')
# Compute a simple cross tabulation of two (or more) factors. By default computes a frequency table of the factors unless an array of values and an aggregation function are passed.
# Implement steps from: https://predictivehacks.com/how-to-run-chi-square-test-in-python/
contingency = pd.crosstab(df['Observed'], df['Expected'])
logging.debug(f'contingency:{contingency}')
# Step 3; calculate the percentages by Observed(row)
logging.debug('Step 3; calculate the percentages by Observed(row)')
# add normalize='index'
contingency_pct = pd.crosstab(df['Observed'],df['Expected'],normalize='index')
logging.debug(f'contingency_pct:{contingency_pct}')
# Step 4; calculate the chi-square test
logging.debug('Step 4: calculate the chi-square test')
c, p, dof, expected = chi2_contingency(contingency)
# c: The test statistic
# p: The p-value of the test
# dof: Degrees of freedom
# expected: The expected frequencies, based on the marginal sums of the table
logging.debug(f'c: The statistic test {c}')
logging.debug(f'p: The p-value of the test {p}')
logging.debug(f'dof: Degrees of freedom {dof}')
logging.debug(f'expected: The expected frequencies, based on the marginal sums of the table {expected}')
</code></pre>
<p>I am using <a href="https://predictivehacks.com/how-to-run-chi-square-test-in-python/" rel="nofollow noreferrer">https://predictivehacks.com/how-to-run-chi-square-test-in-python/</a> as a guide for completing this task. The specific dataset that I am using is</p>
<pre><code>Observed, Expected
15, 13.9
35, 27.8
49, 41.7
58, 55.6
65, 69.5
76, 83.4
72, 69.5
60, 55.6
35, 41.7
29, 27.8
6, 13.9
</code></pre>
<p>Expected:
chi-square value from the observed and expected frequencies. The p-value should be 0.411.</p>
<p>Actual</p>
<pre><code>2022-10-31 06:57:07,338 - DEBUG - c: The statistic test 49.499999999999986
2022-10-31 06:57:07,338 - DEBUG - p: The p-value of the test 0.2983423936107591
2022-10-31 06:57:07,338 - DEBUG - dof: Degrees of freedom 45
2022-10-31 06:57:07,339 - DEBUG - expected: The expected frequencies, based on the marginal sums of the table [[0.18181818 0.18181818 0.18181818 0.18181818 0.18181818 0.09090909]
</code></pre>
<p>What can I try next?</p>
| [
{
"answer_id": 74233271,
"author": "jmcilhinney",
"author_id": 584183,
"author_profile": "https://Stackoverflow.com/users/584183",
"pm_score": 1,
"selected": false,
"text": "Closing"
},
{
"answer_id": 74237057,
"author": "jtxkopt",
"author_id": 7141410,
"author_profil... | 2022/10/28 | [
"https://Stackoverflow.com/questions/74233204",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3937811/"
] |
74,233,210 | <p>I am able to configure usage of ODM and Mongodb with api-platform using <a href="https://api-platform.com/docs/core/mongodb/" rel="nofollow noreferrer">official doc</a>. But you still need to define service for postgress (and have orm dependencies installed), otherwise on startup app waits for db and fails on timeout:</p>
<pre class="lang-bash prettyprint-override"><code>php_1 | Waiting for database to be ready...
php_1 | Still waiting for database to be ready... Or maybe the database is not reachable. 59 attempts left.
php_1 | Still waiting for database to be ready... Or maybe the database is not reachable. 58 attempts left.
</code></pre>
<p>Here is databases part of <code>docker-compose</code>:</p>
<pre class="lang-yaml prettyprint-override"><code> database:
image: postgres:13-alpine
environment:
- POSTGRES_DB=api
- POSTGRES_PASSWORD=!ChangeMe!
- POSTGRES_USER=api-platform
volumes:
- db_data:/var/lib/postgresql/data:rw
# you may use a bind-mounted host directory instead, so that it is harder to accidentally remove the volume and lose all your data!
# - ./api/docker/db/data:/var/lib/postgresql/data:rw
expose:
- 5433
db-mongodb:
# In production, you may want to use a managed database service
image: mongo
environment:
- MONGO_INITDB_DATABASE=api
- MONGO_INITDB_ROOT_USERNAME=api-platform
# You should definitely change the password in production
- MONGO_INITDB_ROOT_PASSWORD=!ChangeMe!
volumes:
- db_data:/var/lib/mongodb/data:rw
# You may use a bind-mounted host directory instead, so that it is harder to accidentally remove the volume and lose all your data!
# - ./docker/db/data:/var/lib/mongodb/data:rw
ports:
- 27017
</code></pre>
<p>Any hints what should I change in my configuration to be able to delete <code>database</code> service? I want to keep my setup clean.</p>
| [
{
"answer_id": 74233271,
"author": "jmcilhinney",
"author_id": 584183,
"author_profile": "https://Stackoverflow.com/users/584183",
"pm_score": 1,
"selected": false,
"text": "Closing"
},
{
"answer_id": 74237057,
"author": "jtxkopt",
"author_id": 7141410,
"author_profil... | 2022/10/28 | [
"https://Stackoverflow.com/questions/74233210",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2265241/"
] |
74,233,237 | <p>I have two data frames. The first one which is the reference df and looks like this :</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>var1</th>
<th>var2</th>
</tr>
</thead>
<tbody>
<tr>
<td>a</td>
<td>e</td>
</tr>
<tr>
<td>b</td>
<td>z</td>
</tr>
<tr>
<td>c</td>
<td>f</td>
</tr>
<tr>
<td>d</td>
<td>h</td>
</tr>
</tbody>
</table>
</div>
<p>and the second one that is my universe:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>sym1</th>
<th>sym2</th>
</tr>
</thead>
<tbody>
<tr>
<td>e</td>
<td>a</td>
</tr>
<tr>
<td>b</td>
<td>f</td>
</tr>
<tr>
<td>b</td>
<td>z</td>
</tr>
<tr>
<td>f</td>
<td>c</td>
</tr>
<tr>
<td>n</td>
<td>s</td>
</tr>
<tr>
<td>n</td>
<td>k</td>
</tr>
<tr>
<td>k</td>
<td>l</td>
</tr>
</tbody>
</table>
</div>
<p>I want to merge them and take only the unique combinations that exist in reference dataframe from all the possible pair in the universe.</p>
<p>Ideally I want the reported data frame to look like this :</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>var1</th>
<th>var2</th>
</tr>
</thead>
<tbody>
<tr>
<td>a</td>
<td>e</td>
</tr>
<tr>
<td>b</td>
<td>z</td>
</tr>
<tr>
<td>c</td>
<td>f</td>
</tr>
<tr>
<td>NA</td>
<td>NA</td>
</tr>
</tbody>
</table>
</div>
<pre><code>library(tidyverse)
var1 = c("a","b","c","d")
var2 = c("e","z","f","h")
ref = tibble(var1,var2);ref
sym1 = c("e","b","b","f","n","n","k")
sym2 = c("a","f","z","c","s","k","l")
univ = tibble(sym1,sym2);univ
</code></pre>
<p>How can I do this in R using dplyr ?</p>
| [
{
"answer_id": 74233271,
"author": "jmcilhinney",
"author_id": 584183,
"author_profile": "https://Stackoverflow.com/users/584183",
"pm_score": 1,
"selected": false,
"text": "Closing"
},
{
"answer_id": 74237057,
"author": "jtxkopt",
"author_id": 7141410,
"author_profil... | 2022/10/28 | [
"https://Stackoverflow.com/questions/74233237",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16346449/"
] |
74,233,239 | <p>I have</p>
<pre><code>df = structure(list(`Q4-21` = c(0L, 1L, 0L, 1L, 0L, 1L, 0L, 1L, 0L,
1L, 0L, 1L, 0L, 1L, 0L, 1L), `Q1-22` = c(0L, 0L, 1L, 1L, 0L,
0L, 1L, 1L, 0L, 0L, 1L, 1L, 0L, 0L, 1L, 1L), `Q2-22` = c(0L,
0L, 0L, 0L, 1L, 1L, 1L, 1L, 0L, 0L, 0L, 0L, 1L, 1L, 1L, 1L),
`Q3-22` = c(0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L), Name = c("A", "B", "C", "D", "E", "F", "G",
"H", "I", "J", "K", "L", "M", "N", "O", "P")), row.names = c(NA,
-16L), class = "data.frame")
</code></pre>
<p><a href="https://i.stack.imgur.com/SbAR5.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/SbAR5.png" alt="enter image description here" /></a></p>
<p>I want</p>
<ul>
<li>to filter where columns 3,4, and 5 are not simultaneously 0</li>
<li>to refer to each column by position, as column names will change repeatedly</li>
</ul>
<p>I have tried:</p>
<pre><code>cols_of_interest = colnames(df)[2:4]
df %>%
filter_at(which(colnames(df) %in% cols_of_interest), all_vars(. !=0))
</code></pre>
<p>but this filters on each column separately not being 0</p>
<p>I need to filter out rows <code>A</code> and <code>B</code></p>
<p>Am aware of <code>df[df[,2] !=0 | df[,3] !=0 | df[,4]!= 0,]</code>, but would prefer tidyverse method</p>
<p>Any suggestions?</p>
| [
{
"answer_id": 74233449,
"author": "Maël",
"author_id": 13460602,
"author_profile": "https://Stackoverflow.com/users/13460602",
"pm_score": 2,
"selected": true,
"text": "if_all"
},
{
"answer_id": 74233478,
"author": "jay.sf",
"author_id": 6574038,
"author_profile": "h... | 2022/10/28 | [
"https://Stackoverflow.com/questions/74233239",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2123706/"
] |
74,233,259 | <p>I think I'm missing a core concept of Jetpack Compose here. I'm running into an issue when I'm trying to change a <code>non-constructor</code> <code>data class</code> <code>property</code> inside of a composable when this composable is part of an observed list.</p>
<p>Does not work: (<code>sadProperty</code> is not declared in the constructor)</p>
<pre><code>data class IntWrapper(val actualInt: Int = 0) {
var sadProperty: Int = 0
}
@Preview
@Composable
fun test() {
var state by remember { mutableStateOf(listOf(IntWrapper(1), IntWrapper(2), IntWrapper(3),IntWrapper(4)))}
fun onClick(item: IntWrapper) {
val indexOf = state.indexOf(item)
val newState = state.minus(item).toMutableList()
val copy = item.copy()
copy.sadProperty = Random.nextInt()
newState.add(indexOf, copy)
state = newState
}
Column() {
for (item in state) {
Text("ac: ${item.actualInt} sad: ${item.sadProperty}", modifier = Modifier.clickable { onClick(item)})
}
}
}
</code></pre>
<p>Works: (<code>actualInt</code> is declared in the constructor)</p>
<pre><code>data class IntWrapper(var actualInt: Int = 0) {
var sadProperty: Int = 0
}
@Preview
@Composable
fun test() {
var state by remember { mutableStateOf(listOf(IntWrapper(1), IntWrapper(2), IntWrapper(3),IntWrapper(4)))}
fun onClick(item: IntWrapper) {
val indexOf = state.indexOf(item)
val newState = state.minus(item).toMutableList()
val copy = item.copy()
copy.actualInt = Random.nextInt()
newState.add(indexOf, copy)
state = newState
}
Column() {
for (item in state) {
Text("ac: ${item.actualInt} sad: ${item.sadProperty}", modifier = Modifier.clickable { onClick(item)})
}
}
}
</code></pre>
<p>Could somebody explain why this happens?</p>
| [
{
"answer_id": 74233399,
"author": "z.y",
"author_id": 19023745,
"author_profile": "https://Stackoverflow.com/users/19023745",
"pm_score": 3,
"selected": true,
"text": "Jetpack Compose"
}
] | 2022/10/28 | [
"https://Stackoverflow.com/questions/74233259",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5056966/"
] |
74,233,301 | <p>I've run the google-pagespeed-insight tool, on which one link has been marked as not being https.
Further investigations lead to a lot of links in wp_posts having http://localhost/(...) as links.</p>
<p>It may be due to me moving of the site from a localhost installation to the live webspace.</p>
<p>So I'm wondering, if i could delete those links, as they won't really point anywhere.
Is there anything else i'd have to check, like other tables?</p>
<p>Thanks folks!</p>
<p>Investigated links via wp_posts and found lots of localhost ones.</p>
| [
{
"answer_id": 74233399,
"author": "z.y",
"author_id": 19023745,
"author_profile": "https://Stackoverflow.com/users/19023745",
"pm_score": 3,
"selected": true,
"text": "Jetpack Compose"
}
] | 2022/10/28 | [
"https://Stackoverflow.com/questions/74233301",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11318587/"
] |
74,233,308 | <p>I was working on a project on <a href="https://www.theodinproject.com/lessons/ruby-stock-picker" rel="nofollow noreferrer">theodinproject </a>ruby curriculum. I am to implement a method that takes in an array of stock prices and return the best day to buy and the best day to sell. The index of each price (array element) is its day.
The way I want to approach the problem was to first copy the array to a new binding, then map over the original array and inside it maps into the copied array and deleting the first element after the loop finished i.e., to make for the case whereby a person cannot buy in day 10 and sell in day 1.</p>
<p>This is the code I've written:</p>
<pre><code>def stock_picker(stock_price)
#copying the array into a new binding
stock_array = []
stock_array.replace(stock_price)
stock_price.map do |buy|
stock_array.map do |sell|
sell - buy
end
#deleting the first element
stock_array.shift
end
end
array = stock_picker([17,3,6,9,15,8,6,1,10])
</code></pre>
<p>This was result I received:</p>
<pre><code>[17, 3, 6, 9, 15, 8, 6, 1, 10]
</code></pre>
<p>and this is what I'm expecting to get:</p>
<pre><code>[[0, -14, -11, -8, -2, -9, -11, -16, -7], [0, 3, 6, 12, 5, 3, -2, 7], [0, 3, 9, 2, 0, -5, 4], [0, 6, -1, -3, -8, 1], [0, -7, -9, -14, -5], [0, -2, -7, 2], [0, -5, 4], [0, 9], [0]]
</code></pre>
| [
{
"answer_id": 74234000,
"author": "Roman Van Loo",
"author_id": 9090414,
"author_profile": "https://Stackoverflow.com/users/9090414",
"pm_score": 1,
"selected": false,
"text": ".map"
},
{
"answer_id": 74234051,
"author": "ajay_speed",
"author_id": 19611403,
"author_p... | 2022/10/28 | [
"https://Stackoverflow.com/questions/74233308",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19632940/"
] |
74,233,309 | <p>I have a list which looks like this:</p>
<pre><code>10.0139_ssrn.3771318
10.1001_archdermatol.2012.418
10.1001_archinte.165.15.1737
10.1001_archinte.165.15.1743
10.1001_archinte.165.18.2142
10.1001_archinternmed.2012.127
</code></pre>
<p>I have a second list which looks like this:</p>
<pre><code>123 10.0139_ssrn.3771318
356 10.1001_archdermatol.2012.418
357 10.1001_archinte.165.15.1737
6 10.1001_archinternmed.2012.127
379 10.1001_archopht.123.1.25
12 10.1001_archoto.2010.121
97 10.1001_archotol.127.1.25
</code></pre>
<p>The second list does not contain all items in the first list and vice versa.</p>
<p>I would like to create a file that contains only the matches and would look like this:</p>
<pre><code>123 10.0139_ssrn.3771318
356 10.1001_archdermatol.2012.418
357 10.1001_archinte.165.15.1737
6 10.1001_archinternmed.2012.127
</code></pre>
<p>I can extract individual lines the way I want with the following command in Powershell:</p>
<pre><code>Get-Content 'Y:\folder\second_list.csv' | foreach {
$_ -match "10.0139_ssrn.3771318"}| Out-File 'Y:\folder\10.0139_ssrn.3771318'
</code></pre>
<p>I do not manage to write a loop that draws the entries from the first file. I tried something like this:</p>
<pre><code>Get-Content 'Y:\folder\second_list.csv' | foreach {
$line -contains (Get-Content "Y:\folder\first_list.csv")| Out-file "Y:\folder\output.csv" -append}
</code></pre>
<p>There are two problems: first, no match is identified (although there should be some matches) and, second, the entry in the output file is always “FALSE” (rather than the matching line of the second_list or no entry at all if no match is found).</p>
| [
{
"answer_id": 74234000,
"author": "Roman Van Loo",
"author_id": 9090414,
"author_profile": "https://Stackoverflow.com/users/9090414",
"pm_score": 1,
"selected": false,
"text": ".map"
},
{
"answer_id": 74234051,
"author": "ajay_speed",
"author_id": 19611403,
"author_p... | 2022/10/28 | [
"https://Stackoverflow.com/questions/74233309",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13818643/"
] |
74,233,319 | <p>I've seen plenty of examples and I can't make them work on my table. I have this table:</p>
<pre><code>data = {'ID': ['Tom', 'Tom','Tom','Joseph','Joseph','Ben','Ben','Eden','Tim','Adam'], 'Tranche': ['Red', 'Red', 'Red', 'Blue','Blue','Blue','Blue','Red','Red','Blue'],'Totals':[100,100,100,50,50,90,90,70,60,70],'Sent':['2022-01-18','2022-02-19','2022-03-14','2021-04-14','2021-04-22','2022-03-03','2022-02-07','2022-01-04','2022-01-10','2022-01-15'],'Amount':[20,10,14,34,15,60,25,10,10,40],'Opened':['2021-12-29','2021-12-29','2021-12-29','2021-03-23','2021-03-23','2021-12-19','2021-12-19','2021-12-29','2021-12-29','2021-12-29']}
df = pd.DataFrame(data)
df["Opened"] = df["Opened"].astype('datetime64[ns]')
df["Sent"] = df["Sent"].astype('datetime64[ns]')
df['SentMonth'] = pd.to_datetime(df['Sent']).dt.to_period('M')
</code></pre>
<p><a href="https://i.stack.imgur.com/FtBDi.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/FtBDi.png" alt="enter image description here" /></a></p>
<p>I want every ID to have every SentMonth, with amount zero if there is no amount (fillna will do if I can get to that point). I need this to make a later .cumsum() give correct results.</p>
<p>e.g. for Tom, the output should be something like this, but just more rows with more SentMonths. The day in the Sent column does not matter - but there must be one row for every month:
<a href="https://i.stack.imgur.com/XpEQB.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/XpEQB.png" alt="enter image description here" /></a></p>
<p>First solution that is always given is reindexing. I can't do this as every SentMonth is duplicated, and Sent will also always have duplicates in my full table.</p>
<p><code>df.resample('M').sum() </code> gives the error: Only valid with DatetimeIndex, TimedeltaIndex or PeriodIndex, but got an instance of 'RangeIndex'.
Which I tried to fix by doing</p>
<pre><code>df1 = df.set_index('SentMonth').groupby('ID').resample('1D')['Amount'].ffill()
</code></pre>
<p>But this brings me back to the unique index error.</p>
<p>Is there any other approach that can get around this? Thanks! :)</p>
| [
{
"answer_id": 74234000,
"author": "Roman Van Loo",
"author_id": 9090414,
"author_profile": "https://Stackoverflow.com/users/9090414",
"pm_score": 1,
"selected": false,
"text": ".map"
},
{
"answer_id": 74234051,
"author": "ajay_speed",
"author_id": 19611403,
"author_p... | 2022/10/28 | [
"https://Stackoverflow.com/questions/74233319",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5574107/"
] |
74,233,327 | <p>I did not find the correct place to use the require method in any documentation. I understand that it is desirable to use the require method at the very beginning of the script, but is it possible and how correct is it to use the require method in the initializer class constructor?</p>
<p>Usually i make like this
<code>require 'my_file'</code></p>
<p>how good is it to do the option below</p>
<p><code> class MyClass</code><br />
<code> def initialize</code><br />
<code>require 'my_file'</code><br />
<code>end</code><br />
<code>end</code></p>
<p>Read require method documentation</p>
| [
{
"answer_id": 74233433,
"author": "Oliver Kristen",
"author_id": 15451402,
"author_profile": "https://Stackoverflow.com/users/15451402",
"pm_score": 1,
"selected": false,
"text": "require 'my_file'\n\nclass MyClass\n def initialize\n end\nend\n\n"
},
{
"answer_id": 74233711,
... | 2022/10/28 | [
"https://Stackoverflow.com/questions/74233327",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15289990/"
] |
74,233,332 | <p>I want my dataclass to have a field that can either be provided manually, or if it isn't, it is inferred at initialization from the other fields. MWE:</p>
<pre class="lang-py prettyprint-override"><code>from collections.abc import Sized
from dataclasses import dataclass
from typing import Optional
@dataclass
class Foo:
data: Sized
index: Optional[list[int]] = None
def __post_init__(self):
if self.index is None:
self.index = list(range(len(self.data)))
reveal_type(Foo.index) # Union[None, list[int]]
reveal_type(Foo([1,2,3]).index) # Union[None, list[int]]
</code></pre>
<p>How can this be implemented in a way such that:</p>
<ol>
<li>It complies with <code>mypy</code> type checking</li>
<li><code>index</code> is guaranteed to be of type <code>list[int]</code></li>
</ol>
<p>I considered using <code>default_factory(list)</code>, however, then how does one distinguish the User passing <code>index=[]</code> from the sentinel value? Is there a proper solution besides doing</p>
<pre class="lang-py prettyprint-override"><code>index: list[int] = None # type: ignore[assignment]
</code></pre>
| [
{
"answer_id": 74233756,
"author": "Paweł Rubin",
"author_id": 8091093,
"author_profile": "https://Stackoverflow.com/users/8091093",
"pm_score": 2,
"selected": true,
"text": "NotImplemented"
},
{
"answer_id": 74233959,
"author": "Daniil Fajnberg",
"author_id": 19770795,
... | 2022/10/28 | [
"https://Stackoverflow.com/questions/74233332",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9318372/"
] |
74,233,343 | <p>I'm trying to display the data from the database, but whenever I connect it the whole page gets repeated - from the head title to a row and then it shows the head title again as if I had split the page, and another row from the database.</p>
<p>I want to show the data like the products page next to each other but it only shows one and then repeats the whole page.</p>
<p>This is my code that I tried - the page gets repeated from the main-container and shows one row, then repeats the main container again.</p>
<pre><code>
<?php
require_once 'opp_data.php';
$sql ="SELECT * FROM college_opp";
$allopp =$conn->query($sql);
?>
//i dont know if i have to show the whole code but this is only the code part where everything gets repeated
<?php
while ($row = mysqli_fetch_assoc($allopp)) {
?>
<div class="main-container">
<h2>تصفح الفرص التطوعية </h2>
<div class="post-collect">
<div class="post-main-container">
<div class="all sports">
<div class="post-img">
<img src="imgs/<?php echo $row["images"]; ?>">
<span class="category-name" data-name="sporty">كلية علوم الرياضة </span>
</div>
<div class="post-content">
<div class="post-content-top">
<span>
<i class="fa-solid fa-users-line"></i><?php echo $row["volunteer_num"]; ?>
</span>
<span><i class="fa-regular fa-calendar-days"></i><?php echo $row["Date"]; ?></span>
</div>
<h2>"<?php echo $row["Title"]; ?>"</h2>
<p>"<?php echo $row["Description"]; ?>"</p>
</div>
<div class="button-btn">
<a href="#">التفاصيل والتسجيل</a>
</div>
</div>
</div>
</div>
</div>
<?php
}
?>
</body>
</code></pre>
<p>for the style.css\\</p>
<pre><code>
.main-container{
width: 90vw;
margin: 0 auto;
padding: 40px 0;
}
.main-container h2{
text-align: center;
padding: 90px 0;
font-size: 32px;
color: #fff;
}
.main-container p{
font-weight: 300;
padding: 10px 0;
opacity: 0.7;
text-align: center;
}
.post-main-container{
display: grid;
grid-template-columns: repeat(4, 1fr);
grid-gap: 60px;
}
.post-main-container div{
box-shadow: 0px 8px 27px -12px rgba(0, 0, 0, 0.64);
}
.post-img{
position: relative;
width: 2vw;
height: 19vw;
}
.post-img img{
position: absolute;
left: 20px;
width: 17vw;
height: 19vw;
}
.post-content{
padding: 25px;
}
.post-content-top{
background: #2b1055;
color: #fff;
opacity: 0,9;
padding: 5px 0 5px 15px;
}
.post-content-top span{
padding-right: 20px;
}
.post-content h2{
font-size: 22px;
padding: 12px 0;
font-weight: 400;
}
.post-content p{
opacity: 0.7;
font-size: 15px;
line-height: 1.8;
color: ghostwhite;
}
.button-btn a {
padding: 8px 15px;
display: block;
font-family:'Almarai', sans-serif ;
font-size: 15px;
cursor: pointer;
background: transparent;
border-radius: 20px;
width: 50%;
border: 2px solid #fff;
color: #fff;
margin: 5px auto;
padding: 0.4rem;
text-decoration: none;
font-weight: 600;
transition: all 0.2s ease-in-out;
}
.button-btn a:hover{
background:#2b1055;
}
</code></pre>
| [
{
"answer_id": 74233418,
"author": "FUZIION",
"author_id": 13050564,
"author_profile": "https://Stackoverflow.com/users/13050564",
"pm_score": 1,
"selected": false,
"text": "<?php\n require_once 'opp_data.php';\n $sql =\"SELECT * FROM college_opp\";\n $allopp =$conn->query($sql)... | 2022/10/28 | [
"https://Stackoverflow.com/questions/74233343",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20258400/"
] |
74,233,353 | <p>I want dynamic return type from parameters.</p>
<pre><code>type TestType = {
value1: string,
value2: number
}
function testFn1<T extend TestType>(...pick:(keyof T)[]): ??? { }
//testFn<TestType>("value1") expect {value1: string}
//testFn<TestType>("value1","value2") expect {value1: string, value2:number}
</code></pre>
<p>Plz</p>
<p>How can i define function return type?</p>
<p>I try below.</p>
<pre><code>function test3<T, K extends keyof T>(...vars: K[]): Record<K, string | number>
</code></pre>
<p>but this return Just T</p>
| [
{
"answer_id": 74233418,
"author": "FUZIION",
"author_id": 13050564,
"author_profile": "https://Stackoverflow.com/users/13050564",
"pm_score": 1,
"selected": false,
"text": "<?php\n require_once 'opp_data.php';\n $sql =\"SELECT * FROM college_opp\";\n $allopp =$conn->query($sql)... | 2022/10/28 | [
"https://Stackoverflow.com/questions/74233353",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8629656/"
] |
74,233,375 | <p>Similar question but with javascript <a href="https://stackoverflow.com/questions/15125920/how-to-get-distinct-values-from-an-array-of-objects-in-javascript">here</a>. Accepted answer</p>
<pre><code>const data = [
{ group: 'A', name: 'SD' },
{ group: 'B', name: 'FI' },
{ group: 'A', name: 'MM' },
{ group: 'B', name: 'CO'}
];
const unique = [...new Set(data.map(item => item.group))]; // [ 'A', 'B']
</code></pre>
<p>However if you try the same thing with typescript you get an error <em>ts2802</em> <strong>Type 'Set' can only be iterated through when using the '--downlevelIteration' flag or with a '--target' of 'es2015' or higher</strong></p>
<p>How can you achieve the same results with typescript?</p>
<p><strong>Question two</strong>
How about you want to get unique objects rather than strings . For eample if you want to get</p>
<pre><code>[
{ group: 'A', name: 'SD' },
{ group: 'B', name: 'FI' },
]
</code></pre>
| [
{
"answer_id": 74233421,
"author": "Ali Zgheib",
"author_id": 10693772,
"author_profile": "https://Stackoverflow.com/users/10693772",
"pm_score": 3,
"selected": true,
"text": "const array = Array.from(new Set(data.map(item => item.group)));\n"
},
{
"answer_id": 74235023,
"aut... | 2022/10/28 | [
"https://Stackoverflow.com/questions/74233375",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19124826/"
] |
74,233,398 | <p>The GameObject in my Unity project should deactivate and then reactivate after a set time. It does deactivate but never reactivates. The object does not deactivate itself so it cant be because of that.</p>
<p>neither</p>
<pre><code>public class PickupController : MonoBehaviour
{
public IEnumerator Reactivate(float seconds, GameObject target)
{
target.SetActive(false);
while (!target.gameObject.active)
{
yield return new WaitForSeconds(seconds);
}
target.SetActive(true);
}
}
</code></pre>
<p>or</p>
<pre><code>public class PickupController : MonoBehaviour
{
public IEnumerator Reactivate(float seconds, GameObject target)
{
target.SetActive(false);
yield return new WaitForSeconds(seconds);
target.SetActive(true);
}
}
</code></pre>
<p>works.</p>
<p>Thanks for the help. :)</p>
| [
{
"answer_id": 74233421,
"author": "Ali Zgheib",
"author_id": 10693772,
"author_profile": "https://Stackoverflow.com/users/10693772",
"pm_score": 3,
"selected": true,
"text": "const array = Array.from(new Set(data.map(item => item.group)));\n"
},
{
"answer_id": 74235023,
"aut... | 2022/10/28 | [
"https://Stackoverflow.com/questions/74233398",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16607054/"
] |
74,233,436 | <p>I am trying to ignore the character <code>@</code> with random numbers combined using RegEx.</p>
<p>This is what I don't want to detect:<br />
<code>@1235</code></p>
<p>This is what I want to detect:<br />
<code>12345</code></p>
<p>This what I did so far:</p>
<pre><code>(?!@[0-9])([0-9])
</code></pre>
| [
{
"answer_id": 74233626,
"author": "Wiktor Stribiżew",
"author_id": 3832970,
"author_profile": "https://Stackoverflow.com/users/3832970",
"pm_score": 3,
"selected": true,
"text": "(?<![@\\d])\\d+\n"
},
{
"answer_id": 74233652,
"author": "The fourth bird",
"author_id": 542... | 2022/10/28 | [
"https://Stackoverflow.com/questions/74233436",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20224716/"
] |
74,233,462 | <p>I am trying to record JS page using jmeter but nothing is recorded. Please help me</p>
<p>Can Jmeter able to record JavaScript web page</p>
| [
{
"answer_id": 74233626,
"author": "Wiktor Stribiżew",
"author_id": 3832970,
"author_profile": "https://Stackoverflow.com/users/3832970",
"pm_score": 3,
"selected": true,
"text": "(?<![@\\d])\\d+\n"
},
{
"answer_id": 74233652,
"author": "The fourth bird",
"author_id": 542... | 2022/10/28 | [
"https://Stackoverflow.com/questions/74233462",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20356999/"
] |
74,233,472 | <p>i have query like this, but displays wrong last_message.</p>
<pre><code> $users = Message::join('users', function ($join) {
$join->on('messages.from_id', '=', 'users.id')
->orOn('messages.to_id', '=', 'users.id');
})
->where(function ($q) {
$q->where('messages.from_id', auth()->user()->id)
->orWhere('messages.to_id', auth()->user()->id);
})
->where('users.id','!=',auth()->user()->id)
->select([
'users.id',
'users.name',
'users.avatar',
DB::raw('MAX(messages.created_at) max_created_at'),
DB::raw('MAX(messages.body) last_message'),
DB::raw('CASE WHEN(COUNT(messages.is_read) FILTER (WHERE is_read = false
AND messages.from_id != '.auth()->user()->id.') = 0) THEN true ELSE false END is_read'),
DB::raw('COUNT(messages.is_read) FILTER (WHERE is_read = false
AND messages.from_id != '.auth()->user()->id.') count_unread')
])
->orderBy('max_created_at', 'desc')
->groupBy('users.id')
->paginate($request->per_page ?? 20)
->withQueryString();
</code></pre>
<p>when i change</p>
<pre><code> DB::raw('MAX(messages.body) last_message'),
</code></pre>
<p>to</p>
<pre><code> DB::raw('messages.body ORDER BY messages.created_at DESC LIMIT 1 last_message'),
</code></pre>
<p>display error messages like this, syntax error at or near "last_message". How to fix this?</p>
| [
{
"answer_id": 74233626,
"author": "Wiktor Stribiżew",
"author_id": 3832970,
"author_profile": "https://Stackoverflow.com/users/3832970",
"pm_score": 3,
"selected": true,
"text": "(?<![@\\d])\\d+\n"
},
{
"answer_id": 74233652,
"author": "The fourth bird",
"author_id": 542... | 2022/10/28 | [
"https://Stackoverflow.com/questions/74233472",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16848125/"
] |
74,233,503 | <p>I want to write a code for this question:
write a code which creates a new number 'n2' which consists reverse order of digits of a number 'n' which divides it without any remainder for example if input is 122
it will print 221 because 1,2,2 can divide 122 without any remainder another example is 172336 here 1,2,3,3,6 can divide it without any remainder so the output should be 63321(reverse order).
my code is:</p>
<pre><code>n = str(input())
x = ""
z = 0
for z in range(len(n)):
if int(n)%int(n[z])==0:
x = n[z] + ""
else:
n.replace(n[z],"")
z = z+1
print(x[::-2])
</code></pre>
<p>if I input the number 122 here i get the output 2 but i should be getiing output of 221 why.</p>
| [
{
"answer_id": 74233626,
"author": "Wiktor Stribiżew",
"author_id": 3832970,
"author_profile": "https://Stackoverflow.com/users/3832970",
"pm_score": 3,
"selected": true,
"text": "(?<![@\\d])\\d+\n"
},
{
"answer_id": 74233652,
"author": "The fourth bird",
"author_id": 542... | 2022/10/28 | [
"https://Stackoverflow.com/questions/74233503",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19843081/"
] |
74,233,536 | <p>I have a JSON file like this:</p>
<pre><code>{
"Location":true,
"adddress":[
{
"street1":" 1 58 4 16"
},
{
"street2":" 3 76 57 12"
}
{
"street3:":....
}
...
{
"streetn":...
}
]
}
</code></pre>
<p>I want to add 10 to the last data of street1, street2 ....so the output looks like this how to achieve this:</p>
<p>Expected output:</p>
<pre><code>{
"Location":true,
"adddress":[
{
"street1":" 1 58 4 26"
},
{
"sttreet2":" 3 76 57 22"
}
]
}
</code></pre>
| [
{
"answer_id": 74233600,
"author": "Gonçalo Peres",
"author_id": 7109869,
"author_profile": "https://Stackoverflow.com/users/7109869",
"pm_score": 2,
"selected": true,
"text": "json"
},
{
"answer_id": 74233614,
"author": "Riccardo Bucco",
"author_id": 5296106,
"author... | 2022/10/28 | [
"https://Stackoverflow.com/questions/74233536",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20356951/"
] |
74,233,537 | <p>I don't understand how this code works. Could anyone please enlighten me a bit. I was pretty much sure "the parameter pack should be the last argument"</p>
<pre><code>void foo(auto&&...args1, auto&&... args2, auto&&... args3) {
std::cout << "args1:\n", ((std::cout << args1 << " "), ...);
std::cout << "args2:\n", ((std::cout << args2 << " "), ...);
std::cout << "args3:\n", ((std::cout << args3 << " "), ...);
}
int main(int argc, char** argv)
{
foo(1,2,3,4,5,6);
}
</code></pre>
<p>If it's allowed how can I split arg1, args2 and args3?</p>
<p>The compiler (g++-11) assumes all parameters pack except args3 are empty, so the output is</p>
<pre><code>args1:
args2:
args3:
1 2 3 4 5 6
</code></pre>
| [
{
"answer_id": 74233823,
"author": "Caleth",
"author_id": 2610810,
"author_profile": "https://Stackoverflow.com/users/2610810",
"pm_score": 1,
"selected": false,
"text": "std::tuple"
},
{
"answer_id": 74236137,
"author": "Jason Liam",
"author_id": 12002570,
"author_pr... | 2022/10/28 | [
"https://Stackoverflow.com/questions/74233537",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3029238/"
] |
74,233,603 | <p>I would like to create a "view" table where I would like to rename 2 rows (2 different names).
Unfortunately, when I type this command, it doesn't work:</p>
<pre><code>SELECT torch_cooling AS MASTER,
REPLACE (REPLACE(torch_cooling, 'gas', 'Gasgekühlt')'water', 'Wassergekühlt') AS TEXT
FROM to_torches
</code></pre>
<p>I would like "gas" to be "Gasgekühlt" and "Water" to be "Wassergekühlt".</p>
<p><a href="https://i.stack.imgur.com/UVAnD.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/UVAnD.png" alt="enter image description here" /></a></p>
<pre><code>SELECT torch_cooling AS MASTER,
REPLACE (REPLACE(torch_cooling, 'gas', 'Gasgekühlt') 'water', 'Wassergekühlt') AS TEXT
FROM to_torches`
</code></pre>
| [
{
"answer_id": 74233823,
"author": "Caleth",
"author_id": 2610810,
"author_profile": "https://Stackoverflow.com/users/2610810",
"pm_score": 1,
"selected": false,
"text": "std::tuple"
},
{
"answer_id": 74236137,
"author": "Jason Liam",
"author_id": 12002570,
"author_pr... | 2022/10/28 | [
"https://Stackoverflow.com/questions/74233603",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17821799/"
] |
74,233,639 | <p>I got this code going on, and my only question is this:</p>
<p>when the compiler gets to the delete pa2 part of the program, what happens to the allocated vector which I made using the constructor? Does the deconstructor get called and the array will be deleted from memry too, or it's just the pointer that's going to lose the link to the address of that newly allocated X and the object X remains in memory? Thank you for your time!</p>
<pre><code>#include <iostream>
using namespace std;
class X {
public:
float* vector;
X() {
this->vector = new float[10];
for (int i = 0; i < 10; i++) {
vector[i] = 1;
}
}
X(float* v) {
this->vector = new float[3];
for (int i = 0; i < 3; i++) {
this->vector[i] = v[i];
}
delete[]v;
}
~X() {
delete[]this->vector;
}
};
int main() {
X a1;
X a2(new float[3]{ 100, 100.5, 200 });
X* pa2 = new X(new float[3]{ 100, 100.5, 200 });
cout << pa2 << endl;
cout << pa2->vector[0];
delete pa2;
}
</code></pre>
<p>I tried deleting the pa2, as seen in the code, but I am not sure whether the dynamically allocated vector (the one passed for the constructor of X on X* pa2) will also be deleted from Heap Memory or not.</p>
| [
{
"answer_id": 74233741,
"author": "Ted Lyngmo",
"author_id": 7582247,
"author_profile": "https://Stackoverflow.com/users/7582247",
"pm_score": 0,
"selected": false,
"text": "delete[]"
},
{
"answer_id": 74233780,
"author": "Thomas",
"author_id": 14637,
"author_profile... | 2022/10/28 | [
"https://Stackoverflow.com/questions/74233639",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16670844/"
] |
74,233,759 | <p>I'm beginning to learn the object-oriented programming in order to make a project : while I have some files that have been given to help me by my internship tutor, I can't manage to work with it. So I struggle to make a basic insertion for registration.</p>
<p>Here is the model class Player :</p>
<pre><code><?php
declare(strict_types=1);
namespace RpgForum;
require_once(__DIR__ . '/../utils.php');
use \Ank\Config;
use \Ank\Repository;
use \Ank\Entity;
use \Ank\Db;
class Player extends Entity{
protected function setPlayer(string $username, string $mail, string $password){
$db = getInstance();
var_dump($db);
$sql = $db->prepare('INSERT INTO player SET username = :username, mail = :mail, password = :password');
$sql->bindValue(':username', $username);
$sql->bindValue(':mail', $mail);
$sql->bindValue(':password', crypt($password, gen_salt("md5")));
$res = $sql->execute();
}
}
</code></pre>
<p>And so here is the error :</p>
<blockquote>
<p>Fatal error: Uncaught Error: Call to undefined function
RpgForum\getInstance() in /app/src/RpgForum/Player.php:68 Stack trace:
#0 /app/src/controller/connectionController.php(18): RpgForum\Player->setPlayer() #1
/app/src/controller/connectionController.php(25):
RpgForum\Register->register() #2 {main} thrown in
/app/src/RpgForum/Player.php on line 68</p>
</blockquote>
<p>Here is the thing : I have a class Player that uses a class Db and extends a class called Entity. <code>getInstance()</code> function is a public static function that I found in the <code>Db</code> class.</p>
<p>And so, I have an error telling that some of my attributes or methods are not defined, as if the link between classes could not be done...</p>
<p>So I tried to change what should be used or extended in term of classes. I tried to understand what my tutor gave me but it only disrupted some of my neurons. I took some online free courses to upgrade my knowledge and so I gave it a try with my new skills as I declared classes, new objects, some parameters and tried make a link with the database and view via the controller. But in the end I can't see in the database the new player, showing me that something failed (see the error thrown).</p>
| [
{
"answer_id": 74233741,
"author": "Ted Lyngmo",
"author_id": 7582247,
"author_profile": "https://Stackoverflow.com/users/7582247",
"pm_score": 0,
"selected": false,
"text": "delete[]"
},
{
"answer_id": 74233780,
"author": "Thomas",
"author_id": 14637,
"author_profile... | 2022/10/28 | [
"https://Stackoverflow.com/questions/74233759",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20356794/"
] |
74,233,774 | <p>I need help with this Python program.</p>
<p>With the input below:</p>
<pre><code>Enter number: 1
Enter number: 2
Enter number: 3
Enter number: 4
Enter number: 5
</code></pre>
<p>the program must output:</p>
<pre><code>Output: 54321
</code></pre>
<p>My code is:</p>
<pre><code>n = 0
t = 1
rev = 0
while(t <= 5):
n = int(input("Enter a number:"))
t+=1
a = n % 10
rev = rev * 10 + a
n = n // 10
print(rev)
</code></pre>
<p>Its output is "12345" instead of "54321".<br />
What should I change?</p>
| [
{
"answer_id": 74233826,
"author": "Omar",
"author_id": 9289463,
"author_profile": "https://Stackoverflow.com/users/9289463",
"pm_score": 0,
"selected": false,
"text": "my_list = []\nwhile(t <= 5):\n n = int(input(\"Enter a number:\"))\n t+=1\n my_list.append(n)\nmy_list.reverse... | 2022/10/28 | [
"https://Stackoverflow.com/questions/74233774",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20356754/"
] |
74,233,801 | <p>I'm moving some tests to newer Mockito versions and I'm running into a wall when it comes to <code>@ParameterizedTest</code> tests and Mockito's <code>UnnecessaryStubbingsException</code>.</p>
<p>The issue is that the test in question sometimes needs to have a service mocked, depending on the parameters of the test. For some parameters, the code will not execute to the line where the mocked service is called, while for other parameters it will.</p>
<p>This results in Mockito throwing the <code>UnnecessaryStubbingsException</code> for the cases where the mock is unused. I can't remove the stub because then the test will fail for parameters where the code actually executes to the point where the service needs to be mocked.</p>
<p>To illustrate, let's say I have this dummy method I'm testing:</p>
<pre><code>public boolean process(String flag) {
if (Objects.equals(flag, "flag1")) {
throw new IllegalArgumentException("Oh no, exception!");
}
boolean result = someService.execute(flag);
if (result) {
throw new IllegalArgumentException("Oh no, exception!");
}
return result;
}
</code></pre>
<p>And then the parameterised test to check multiple flags:</p>
<pre><code>@ParameterizedTest
@MethodSource("getFlags")
void shouldTestIfFlagWorks(String someFlag) {
// Given
Mockito.doReturn(true).when(someService).execute(someFlag);
// When
Throwable thrown = Assertions.catchThrowable(() -> serviceUnderTest.process(someFlag));
// Then
Assertions.assertThat(thrown).hasMessage("Oh no, exception!");
}
private static Stream<Arguments> getFlags() {
return Stream.of(
Arguments.of("flag1"),
Arguments.of("flag2")
);
}
</code></pre>
<p>The example is a bit contrived, but this will fail with <code>UnnecessaryStubbingsException</code> because the first parameter the test runs with doesn't need the mock. If I remove the stub, the test with the first parameter will work, while it will fail once it runs for the second time with the next parameter.</p>
<p>Is there any way to circumvent this? One option I know would solve this is to use <code>Mockito.lenient()</code>. The other option is to refactor and move the parameters that need the mock to a separate test.</p>
<p>I'm curious if there's any different / better approach, or something else that I'm missing here.</p>
| [
{
"answer_id": 74233826,
"author": "Omar",
"author_id": 9289463,
"author_profile": "https://Stackoverflow.com/users/9289463",
"pm_score": 0,
"selected": false,
"text": "my_list = []\nwhile(t <= 5):\n n = int(input(\"Enter a number:\"))\n t+=1\n my_list.append(n)\nmy_list.reverse... | 2022/10/28 | [
"https://Stackoverflow.com/questions/74233801",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10580773/"
] |
74,233,827 | <p>In Safari but not in Chrome applying svg mask on svg icon renders blurry edges. I've created minimal reproducible example... at least I hope that it's reproducible. Because this effect is not constant:</p>
<ul>
<li>some random changes in unrelated parts of a page can "fix" the bug.</li>
<li>after these changes if I refresh the page - the bug disappears or reappears at random. Sometimes the switch happens when I duplicate a tab, or open the page in a new tab manually entering the url in the address bar, or when I open a new private window . Probably some cache magic.</li>
</ul>
<p>I've tried it on desktop in 15.6.1 and 16.4 and in webviews on an assortment of Apple mobile devices.</p>
<p>The actual result:</p>
<p><a href="https://i.stack.imgur.com/AJVsJ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/AJVsJ.png" alt="enter image description here" /></a></p>
<p>The expected result:</p>
<p><a href="https://i.stack.imgur.com/vzabB.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/vzabB.png" alt="enter image description here" /></a></p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><html>
<head>
<style>
.logo {
width: 96px;
height: 96px;
-webkit-mask-size: contain;
mask-size: contain;
-webkit-mask-image:
url(data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNDgiIGhlaWdodD0iNDgiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+PG1hc2sgaWQ9ImEiIHN0eWxlPSJtYXNrLXR5cGU6YWxwaGEiIG1hc2tVbml0cz0idXNlclNwYWNlT25Vc2UiIHg9IjAiIHk9IjAiIHdpZHRoPSI0OCIgaGVpZ2h0PSI0OCI+PHBhdGggZD0iTTQ4IDI0YzAgMTkuMjA1LTQuNzk1IDI0LTI0IDI0UzAgNDMuMjA1IDAgMjQgNC43OTUgMCAyNCAwczI0IDQuNzk1IDI0IDI0eiIgZmlsbD0iI2ZmZiIvPjwvbWFzaz48ZyBtYXNrPSJ1cmwoI2EpIj48cGF0aCBmaWxsPSIjMDAwIiBkPSJNMCAwaDQ4djQ4SDB6Ii8+PC9nPjwvc3ZnPg==);
mask-image:
url(data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNDgiIGhlaWdodD0iNDgiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+PG1hc2sgaWQ9ImEiIHN0eWxlPSJtYXNrLXR5cGU6YWxwaGEiIG1hc2tVbml0cz0idXNlclNwYWNlT25Vc2UiIHg9IjAiIHk9IjAiIHdpZHRoPSI0OCIgaGVpZ2h0PSI0OCI+PHBhdGggZD0iTTQ4IDI0YzAgMTkuMjA1LTQuNzk1IDI0LTI0IDI0UzAgNDMuMjA1IDAgMjQgNC43OTUgMCAyNCAwczI0IDQuNzk1IDI0IDI0eiIgZmlsbD0iI2ZmZiIvPjwvbWFzaz48ZyBtYXNrPSJ1cmwoI2EpIj48cGF0aCBmaWxsPSIjMDAwIiBkPSJNMCAwaDQ4djQ4SDB6Ii8+PC9nPjwvc3ZnPg==);
background-image:
url(data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMjAiIGhlaWdodD0iMjAiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+PHBhdGggZmlsbD0iIzAwMCIgZD0iTTAgMGgyMHYyMEgweiIvPjwvc3ZnPg==);
background-size: cover;
}
</style>
</head>
<body>
<div class="logo"/>
</body>
</html></code></pre>
</div>
</div>
</p>
<p><strong>SVGs</strong></p>
<ol>
<li>The mask:</li>
</ol>
<pre class="lang-html prettyprint-override"><code><svg width="48" height="48" viewBox="0 0 48 48" fill="none" xmlns="http://www.w3.org/2000/svg">
<mask id="mask0_16513_8424" style="mask-type:alpha" maskUnits="userSpaceOnUse" x="0" y="0" width="48" height="48">
<path d="M48 24C48 43.2052 43.2052 48 24 48C4.79475 48 0 43.2052 0 24C0 4.79475 4.79475 0 24 0C43.2052 0 48 4.79475 48 24Z" fill="white"/>
</mask>
<g mask="url(#mask0_16513_8424)">
<rect width="48" height="48" fill="black"/>
</g>
<defs>
</defs>
</svg>
</code></pre>
<ol start="2">
<li>The icon:</li>
</ol>
<pre class="lang-html prettyprint-override"><code><svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">
<rect width="20" height="20" fill="#000000"/>
</svg>
</code></pre>
| [
{
"answer_id": 74234189,
"author": "Hoargarth",
"author_id": 9184970,
"author_profile": "https://Stackoverflow.com/users/9184970",
"pm_score": 0,
"selected": false,
"text": "viewBox"
},
{
"answer_id": 74238169,
"author": "herrstrietzel",
"author_id": 15015675,
"author... | 2022/10/28 | [
"https://Stackoverflow.com/questions/74233827",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12610347/"
] |
74,233,837 | <p>Let's say I have a template that displays a certain quantity of items like so:</p>
<pre class="lang-html prettyprint-override"><code><template>
<div>
<div v-for="item in items.slice(0, 10)" :key="item" />
</div>
</template>
</code></pre>
<p>How can I show less items on mobile viewport, modifying my slice function ?</p>
<p>I would like to avoid duplicating code and having two lists, one with <code>items.slice(0, 10)</code> and one with <code>items.slice(0, 5)</code>, and show one or the other according to a media query because that's not scalable.</p>
<p>I thought about checking user's viewport width on <code>mounted</code> and on page-resize and update the quantity of items that are displayed according to this but I don't find it very clean.</p>
<p>I feel like it's a very common use-case though, is there a good way of doing this ?</p>
| [
{
"answer_id": 74234391,
"author": "kissu",
"author_id": 8816585,
"author_profile": "https://Stackoverflow.com/users/8816585",
"pm_score": 2,
"selected": true,
"text": "<div v-for=\"item in items.slice(0, this.$currentViewport.label === 'mobile' ? 5 : 10)\"\n :key=\"item\"\n/>\n"
},
... | 2022/10/28 | [
"https://Stackoverflow.com/questions/74233837",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9947189/"
] |
74,233,840 | <p>I have created a Validation Error to show up when the submit button is clicked and the condition of the field is empty. But when I try to test it when the field is filled, the validation error still showing up. What's wrong with my code ?</p>
<pre><code>def action_approved(self):
for rec in self:
expense_account = self.env['account.pettycash.voucher.wizard.line'].search([('expense_account','=',False)])
if expense_account :
raise ValidationError('Fill the expense account!')
else :
rec.state = 'approved'
</code></pre>
<p>I expect validation error to show up when field is empty and approve when filled</p>
| [
{
"answer_id": 74234391,
"author": "kissu",
"author_id": 8816585,
"author_profile": "https://Stackoverflow.com/users/8816585",
"pm_score": 2,
"selected": true,
"text": "<div v-for=\"item in items.slice(0, this.$currentViewport.label === 'mobile' ? 5 : 10)\"\n :key=\"item\"\n/>\n"
},
... | 2022/10/28 | [
"https://Stackoverflow.com/questions/74233840",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7769113/"
] |
74,233,872 | <p>I'm using <code>pragma solidity >=0.4.0 <0.9.0;</code></p>
<p>Line <code>34</code> with below code:</p>
<p><code>event studentAdded(string memory full_name, uint256 memory st_id);</code></p>
<p>I'm facing this error. Can anyone help?</p>
<p><code>ParserError: Expected ',' but got 'memory' --> contracts/Scorecard.sol:34:31: | 34 | event studentAdded(string memory full_name, uint256 memory st_id); | ^^^^^^</code></p>
<p>While removing the <code>memory</code> keyword from all arguments of event definitions. I was able to compile successfully but I still can't understand the reasoning behind this. The data location should be either <code>memory</code> or <code>storage</code> for all the variables right?</p>
| [
{
"answer_id": 74236145,
"author": "Dushyanth Kumar Reddy",
"author_id": 10845790,
"author_profile": "https://Stackoverflow.com/users/10845790",
"pm_score": 2,
"selected": false,
"text": "memory"
}
] | 2022/10/28 | [
"https://Stackoverflow.com/questions/74233872",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14795286/"
] |
74,233,878 | <p>Something recently hyped my curiosity while coding : is it possible to intricate pointers in C ?
I explain: I would like to link two pointers, let's say two int * p1 and p2. The idea is, whenever I edit the value of p1, the value of p2 is also edited. Example :</p>
<ul>
<li><code>*p1 = 2</code>
and I want for instance that <code>*p2 = *p1-1</code>;</li>
<li><code>*p1=3;</code>.
But here <code>*p2</code> still amounts to 1... Is there a way to make <code>*p2</code> equals to <code>*p1 - 1</code> every time, without having to edit the value of <code>*p2</code> after every modification of <code>*p1</code> ?</li>
</ul>
<p>Not having to edit intricated pointers every time.</p>
| [
{
"answer_id": 74233968,
"author": "chrslg",
"author_id": 20037042,
"author_profile": "https://Stackoverflow.com/users/20037042",
"pm_score": 2,
"selected": false,
"text": "int x=12;\nint *y=&x;\n\n*y=15; // Wow, value of x has changed\n"
},
{
"answer_id": 74233972,
"author":... | 2022/10/28 | [
"https://Stackoverflow.com/questions/74233878",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19535875/"
] |
74,233,880 | <p>I need to upload the attachment which is received outlook email to amazon s3 bucket.</p>
<ul>
<li>The email with attachment is received once per day</li>
<li>Is there any process which can automate this process of uploading it to specific s3 bucket?</li>
</ul>
<p>I have tried to search for any available add-ins in outlook.</p>
| [
{
"answer_id": 74233968,
"author": "chrslg",
"author_id": 20037042,
"author_profile": "https://Stackoverflow.com/users/20037042",
"pm_score": 2,
"selected": false,
"text": "int x=12;\nint *y=&x;\n\n*y=15; // Wow, value of x has changed\n"
},
{
"answer_id": 74233972,
"author":... | 2022/10/28 | [
"https://Stackoverflow.com/questions/74233880",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14092279/"
] |
74,233,934 | <p>I have the following lists and would like to get the maximum values for each person and create a new list using exclusively the for loop and max function. How can I do it?</p>
<pre class="lang-py prettyprint-override"><code>persons = ['John', 'James', 'Robert']
values = [
(101, 97, 79),
(67, 85, 103),
(48, 201, 105),
]
</code></pre>
<p>I'm looking for this ouput:</p>
<pre><code>Output 1 = [('John', 101), ('James', 103), ('Robert', 201]
Output 2 = [101, 103, 201]
</code></pre>
<p>Can anyone help?</p>
<p>I just do not manage to get this result at all.</p>
| [
{
"answer_id": 74233979,
"author": "Rodrigo Guzman",
"author_id": 13315525,
"author_profile": "https://Stackoverflow.com/users/13315525",
"pm_score": 2,
"selected": false,
"text": "for i, j in zip(persons, values):\n print(i,max(j))\n"
},
{
"answer_id": 74234031,
"author":... | 2022/10/28 | [
"https://Stackoverflow.com/questions/74233934",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20357222/"
] |
74,233,936 | <p>I have followed doc guidance on how to setup java azure functions project with InteliJ: <a href="https://learn.microsoft.com/en-us/azure/azure-functions/functions-create-maven-intellij" rel="nofollow noreferrer">https://learn.microsoft.com/en-us/azure/azure-functions/functions-create-maven-intellij</a></p>
<p>Nevertheless when trying to use local.settings.json file to inject application settings when running Functions locally, values are not injected and the file is ignored by the runtime.
Is there a way how to make use of local.settings.json as with C# functions? For time being I used workaround of adding values into run configuration.</p>
<p>I am using Java 8, Azure Functions Core tools 4.x</p>
| [
{
"answer_id": 74263213,
"author": "Pravallika Kothaveerannagari",
"author_id": 19991670,
"author_profile": "https://Stackoverflow.com/users/19991670",
"pm_score": 0,
"selected": false,
"text": "local.settings.json"
},
{
"answer_id": 74288379,
"author": "Paizo",
"author_i... | 2022/10/28 | [
"https://Stackoverflow.com/questions/74233936",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1696691/"
] |
74,233,940 | <p>I'm trying to write a function that should delete Amazon S3 objects within a designated bucket, when I delete a Woocommerce product(s). But I keep getting an fatal error.</p>
<p><strong>Here's how I'm trying to accomplish this:</strong></p>
<ul>
<li>The S3 objects (images) are used as Woocommerce downloadable product variations.</li>
<li>Using Woocommerce's <code>before_delete_post</code> I loop through a products variations and trigger <code>$s3->deleteObject</code>.</li>
<li>I have a custom field on each variation called <code>s3path</code>. This stores the path of the S3 object eg <code>path/object.jpg</code>.</li>
</ul>
<p>Here's my function so far. This is saved in <code>functions.php</code>:</p>
<pre><code>function delete_s3_product_images() {
global $product;
require ABSPATH . 'vendor/autoload.php';
$s3 = new Aws\S3\S3Client([
'region' => 'ap-southeast-2',
'version' => 'latest',
'credentials' => [
'key' => "--Amazon S3 Key--",
'secret' => "--Amazon S3 Secret--",
]
]);
$variations = $product->get_available_variations();
foreach ( $variations as $key => $value ) {
$result = $s3->deleteObject([
'Bucket' => '--Bucket Name--',
'Key' => $value['s3path'] //value outputs as "path/object.jpg"
]);
}
}
add_action( 'before_delete_post', 'delete_s3_product_images', 10, 1 );
</code></pre>
<p>Here's the error:</p>
<pre><code>Fatal error: Uncaught Error: Call to a member function get_available_variations() on null
</code></pre>
<p>I'm assuming it's throwing the error because it thinks the <code>$product</code> is empty. How can I retrieve the <code>$product</code> correctly?</p>
<p><strong>Edit</strong>: Have changed up my original code to use <code>$postid</code> and am not getting any errors any more. However, the image objects within S3 aren't being deleted. Here's my updated code:</p>
<pre><code>function delete_s3_product_images($postid) {
require ABSPATH . 'vendor/autoload.php';
$s3 = new Aws\S3\S3Client([
'region' => 'ap-southeast-2',
'version' => 'latest',
'credentials' => [
'key' => "--Amazon S3 Key--",
'secret' => "--Amazon S3 Secret--",
]
]);
$args = array(
'post_type' => 'product_variation',
'post_status' => 'publish',
'posts_per_page' => -1,
'post_parent' => $postid,
'meta_query' => array(
array(
'key' => 's3path',
)
),
);
$query = new WP_Query( $args );
while( $query->have_posts() ) {
$query->the_post();
$s3path = get_post_meta( get_the_id(), 's3path', true );
$result = $s3->deleteObject([
'Bucket' => '--Bucket Name--',
'Key' => $s3path
]);
}
wp_reset_postdata();
}
add_action( 'before_delete_post', 'delete_s3_product_images', 10, 1);
</code></pre>
<p>I can confirm that the code works brilliantly when used as a shortcode either within or outside of a Woocommerce page. I'm now assuming it must to do with how <code>before_delete_post</code> handles the <code>while</code> loop?</p>
| [
{
"answer_id": 74263213,
"author": "Pravallika Kothaveerannagari",
"author_id": 19991670,
"author_profile": "https://Stackoverflow.com/users/19991670",
"pm_score": 0,
"selected": false,
"text": "local.settings.json"
},
{
"answer_id": 74288379,
"author": "Paizo",
"author_i... | 2022/10/28 | [
"https://Stackoverflow.com/questions/74233940",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3741890/"
] |
74,233,947 | <p>I need to loop thought data and need to check if value. First check my code:</p>
<p>What i need. inside map above i need to set one if and just prop to NewComponent data where if is true? What i try:</p>
<p>but this no work.</p>
| [
{
"answer_id": 74263213,
"author": "Pravallika Kothaveerannagari",
"author_id": 19991670,
"author_profile": "https://Stackoverflow.com/users/19991670",
"pm_score": 0,
"selected": false,
"text": "local.settings.json"
},
{
"answer_id": 74288379,
"author": "Paizo",
"author_i... | 2022/10/28 | [
"https://Stackoverflow.com/questions/74233947",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20294615/"
] |
74,233,975 | <p>I am facing problems while using <code>nltk.tokenize.words_tokenize</code> in my code.</p>
<p>My code is as follows:</p>
<pre><code>def clean_str_and_tokenise(line):
'''
STEP 1:
Remove punctuation marks from the input string and convert the entire string to lowercase
chars_to_remove = [',', '.', '"', "'", '/', '*', ',', '?', '!', '-', '\n', '“', '”', '_', '&', '\ufeff', '&', ';', ":"]
STEP 2:
Tokenize (convert the clean string into a list with each word being a separate element)
Arguments:
line: The raw text string
Returns:
list of words in lowercase without punctuations
'''
# YOUR CODE HERE
chars_to_remove = [',', '.', '"', "'", '/', '*', ',', '?', '!', '-', '\n', '“', '”', '_', '&', '\ufeff', '&', ';', ":"]
text_clean = "".join([i.lower() for i in line if i not in chars_to_remove])
print(text_clean)
return nltk.tokenize.word_tokenize(text_clean)
</code></pre>
<p>Using test string 1</p>
<pre><code>test_str1 = 'Never, GOING* tO give. you- up?'
clean_str_and_tokenise(test_str1)
</code></pre>
<p>I get output as:</p>
<pre><code>never going to give you up
['never', 'going', 'to', 'give', 'you', 'up']
</code></pre>
<p>But when I use test string 2</p>
<pre><code>test_str2 = 'Never, GONNA* give. you- up?'
clean_str_and_tokenise(test_str2)
</code></pre>
<p>I get the following output:</p>
<pre><code>never gonna give you up
['never', 'gon', 'na', 'give', 'you', 'up']
</code></pre>
<p>I word 'gonna' gets split around 'n'. I tried changing the strings and the error stays there. I have figured out that the error is in tokenisation because the cleaning and converting to lower case is working properly. Can someone please help explain this?</p>
<p>I expect that the word 'gonna' in test string 2 should not split and tokenise as a single word i.e. the output should look like</p>
<pre><code>['never', 'gonna', 'give', 'you', 'up']
</code></pre>
| [
{
"answer_id": 74263213,
"author": "Pravallika Kothaveerannagari",
"author_id": 19991670,
"author_profile": "https://Stackoverflow.com/users/19991670",
"pm_score": 0,
"selected": false,
"text": "local.settings.json"
},
{
"answer_id": 74288379,
"author": "Paizo",
"author_i... | 2022/10/28 | [
"https://Stackoverflow.com/questions/74233975",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20357247/"
] |
74,233,985 | <p>I have an issue with my code, i have a search input and a list of countries</p>
<p>When i type some words i have an error which cause to my app collapse</p>
<p>I've been trying for about two days to find the problem but can't find it.</p>
<p>This is the error message : Uncaught TypeError: Cannot read properties of undefined (reading 'filter')</p>
<pre><code>const Country = ({name, num}) =>{
//console.log(name)
return (
<div>
<p>{name}</p>
</div>
)} // Component
const Input = ({onSearch, search}) =>{
return (
<div>
Find countries: <input onChange={onSearch} value={search} />
</div>
)} // Component
import { useState, useEffect } from "react";
import axios from "axios";
import Input from "./components/Input";
import Country from "./components/Country";
const App = () => {
const [countryList, setCountryList] = useState();
const [search, setSearch] = useState("");
const [filter, setFilter] = useState(false);
useEffect(() => {
axios
.get("https://restcountries.com/v3.1/all")
.then((res) => setCountryList(res.data));
}, []);
const onSearch = (event) => {
if (event.target.value === " ") setFilter(false);
else {
setFilter(true);
setSearch(event.target.value);
}
};
const countriesList = filter
? countryList.filter((country) => {
return country.name.common.includes(search);
})
: null ;
return (
<div>
<Input onSearch={onSearch} search={search} />
{filter ? (
countriesList.length === 0 ? (
<h3>No match</h3>
) : countriesList.length > 10 ? (
<h3>Too many matches, specify another filter...</h3>
) : countriesList.length < 10 && countriesList.length > 1 ? (
countriesList.map((country, i) => (
<Country name={country.name.common} key={i} num={false} />
))
) : (
<Country name={countriesList[0].name.common} num={true} /> &&
console.log("common", countriesList)
)
) : (
<h3>Search for any country</h3>
)}
</div>
);
};
</code></pre>
| [
{
"answer_id": 74263213,
"author": "Pravallika Kothaveerannagari",
"author_id": 19991670,
"author_profile": "https://Stackoverflow.com/users/19991670",
"pm_score": 0,
"selected": false,
"text": "local.settings.json"
},
{
"answer_id": 74288379,
"author": "Paizo",
"author_i... | 2022/10/28 | [
"https://Stackoverflow.com/questions/74233985",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18954608/"
] |
74,233,990 | <p>I have a Kubernetes cluster with 3 nodes. On this cluster, there is one Kubernetes StatefulSet that is responsible for receiving messages, persisting the messages, and scheduling the received messages and an application processor of type Deployment that has 3 instances (replicas), Here the App Processor POD is receiving multiple kinds of messages from Message Processor POD using REST calls. <br/>
So finally I have</p>
<pre><code>message-processor-0
</code></pre>
<p>and</p>
<pre><code>app-processor-12345
app-processor-23456
app-processor-45567
</code></pre>
<p>Here my requirement is, I want to send particular types of messages to only one dedicated instance of the App Processor.</p>
| [
{
"answer_id": 74234442,
"author": "Rick",
"author_id": 5260090,
"author_profile": "https://Stackoverflow.com/users/5260090",
"pm_score": 0,
"selected": false,
"text": "app-processor"
},
{
"answer_id": 74235559,
"author": "Raj",
"author_id": 6212039,
"author_profile":... | 2022/10/28 | [
"https://Stackoverflow.com/questions/74233990",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17031361/"
] |
74,234,040 | <p>I'm facing this problem while trying to move input value to component state hook using the onChange attribute.
i'll be happy with your help.</p>
<pre><code>import React from 'react'
import { useState } from 'react';
import './userInterface.css';
function UserInterface() {
const [userInfo, setUserInfo] = useState({
isLoggedIn : '',
userName : '',
email : '',
password : ''
})
let usenamePattern = /[A-Za-z0-9]{3,16}./ ;
let emailPattern = /[A-Za-z0-9@.]{7,}/ ;
const getInputToState = (e,inputField) => {
switch(inputField){
case 'username' : {
setUserInfo(userInfo.userName = e.target.value)
console.log(userInfo)
break
}
case 'email' : {
setUserInfo(userInfo.email = e.target.value)
console.log(userInfo)
break
}
case 'password' : {
setUserInfo(userInfo.password = e.target.value)
console.log(userInfo)
break
}
default:
return null
}
console.log(userInfo)
}
const alertForm = () => {
if(userInfo.userName == '' && userInfo.email == '' && userInfo.password == ''){
return{
msg : '',
color : 'green'
}
}
else if(userInfo.userName.match(usenamePattern)){
return {
msg : 'You are allright !',
color : 'limegreen'
}
}else if(!userInfo.userName.match(usenamePattern)){
return {
msg : 'Username should be more than 3 characters and less than 16, and contains only alphabets and numbers',
color : 'red'
}
}
}
return (
<div id='user-div'>
<form id='user-form'>
<h2 id="form-title">Tell us who you are :)</h2>
<ul id="form-inputs">
<li className="form-input">
<input type="text" className="user-input" placeholder='Enter a username' maxLength={16} onChange={getInputToState()}/>
</li>
<li className="form-input">
<input type="text" className="user-input" placeholder='Enter your e-mail' onChange={getInputToState()}/>
</li>
<li className="form-input">
<input type="text" className="user-input" placeholder='Create a password' onChange={(e) => {getInputToState()}}/>
</li>
<li className="form-input">
<a><button className='action-form' id='submit-button' disabled>Submit</button></a>
</li>
</ul>
<h4 id='alert-msg' style={{color : alertForm()?.color}}>{alertForm()?.msg}</h4>
<h3 id='login-sign'>Already have an account ? <a href="/" id='login-form'>Log In</a></h3>
</form>
</div>
)
}
export default UserInterface ;
</code></pre>
<p>here is the entire component code, it has no relation with props or exports.
When i write in inputs the console returns nothing which means that the function do not work</p>
| [
{
"answer_id": 74234442,
"author": "Rick",
"author_id": 5260090,
"author_profile": "https://Stackoverflow.com/users/5260090",
"pm_score": 0,
"selected": false,
"text": "app-processor"
},
{
"answer_id": 74235559,
"author": "Raj",
"author_id": 6212039,
"author_profile":... | 2022/10/28 | [
"https://Stackoverflow.com/questions/74234040",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17862094/"
] |
74,234,054 | <p>I have added new attribute "Pan"(pancard number) on registration form. Validations are also working fine. but if I hits register tab, I am getting error like</p>
<p>[/grocerymatestorefront] threw exception [Request processing failed; nested exception is de.hybris.platform.servicelayer.exceptions.ModelSavingException: [de.hybris.platform.servicelayer.interceptor.impl.MandatoryAttributesValidator@246420ba]:missing values for [pan] in model CustomerModel () to create a new Customer] with root cause de.hybris.platform.servicelayer.interceptor.impl.MandatoryAttributesValidator$MissingMandatoryAttributesException: [de.hybris.platform.servicelayer.interceptor.impl.MandatoryAttributesValidator@246420ba]:missing values for [pan] in model CustomerModel () to create a new Customer</p>
<p>To resolve this error I tried modifier optional = "true" in items.xml doing that above error got resolved but I am not able to store the value for pan.
So please help me to solve both issues customermodel error and storing value in database.</p>
| [
{
"answer_id": 74234442,
"author": "Rick",
"author_id": 5260090,
"author_profile": "https://Stackoverflow.com/users/5260090",
"pm_score": 0,
"selected": false,
"text": "app-processor"
},
{
"answer_id": 74235559,
"author": "Raj",
"author_id": 6212039,
"author_profile":... | 2022/10/28 | [
"https://Stackoverflow.com/questions/74234054",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20345940/"
] |
74,234,076 | <p>what happens if after guard let I return from init? I know that if it's a failable init(like init?) it returns nil.</p>
<pre><code> init(_ quoteRequest: QuoteRequest?, buy: Bool = true) {
super.init(nibName: nil, bundle: nil)
guard let quoteRequest = quoteRequest else { return }
self.quoteRequest = quoteRequest
self.buy = buy
}
</code></pre>
<p>does object initializes? or partly? don't get it</p>
<p>I did't get any errors, but I don't understand what happend.</p>
| [
{
"answer_id": 74234726,
"author": "Pierre",
"author_id": 12931221,
"author_profile": "https://Stackoverflow.com/users/12931221",
"pm_score": 1,
"selected": false,
"text": "self.buy"
},
{
"answer_id": 74235081,
"author": "matt",
"author_id": 341994,
"author_profile": ... | 2022/10/28 | [
"https://Stackoverflow.com/questions/74234076",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19793331/"
] |
74,234,135 | <p>I am loading global CSS styles but I need them to <strong>not</strong> affect one part of the page and all of its subcomponents. There are some old information but is there a solution now when :not() is a <a href="https://www.w3.org/TR/selectors-4/#negation" rel="nofollow noreferrer">Level 4 selector</a>?</p>
<p>Codepen example that is not working: <a href="https://codepen.io/LaCertosus/pen/PoaYeRj" rel="nofollow noreferrer">https://codepen.io/LaCertosus/pen/PoaYeRj</a></p>
<p>I have a HTML structure that is not predefined, I do not know how many and what elements are around and inside the "red" element.</p>
<p>Visual example</p>
<p><a href="https://i.stack.imgur.com/rugV7.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/rugV7.png" alt="Visual example" /></a></p>
<pre class="lang-html prettyprint-override"><code><div class="parent">
<div class="_filler">
<div class="_filler">
<div class="block">
Should be red
</div>
</div>
</div>
<div>
<div class="child-lime">
<div class="block">
Should be lime
</div>
<div class="_filler">
<div class="block">
Should be lime
</div>
</div>
</div>
</div>
</div>
</code></pre>
<pre class="lang-scss prettyprint-override"><code>.parent:not(.child-lime) {
.block {
background: red;
}
}
/* Block is an example, in reality we don't know the class name */
.block {
height: 100px;
width: 100px;
background: lime;
border: 1px solid #000;
display: flex;
align-items: center;
justify-content: center;
padding: 1rem;
}
</code></pre>
<p>I have tried different combinations with :not() selector but with no luck. It works when I don't need to include all children.</p>
| [
{
"answer_id": 74234726,
"author": "Pierre",
"author_id": 12931221,
"author_profile": "https://Stackoverflow.com/users/12931221",
"pm_score": 1,
"selected": false,
"text": "self.buy"
},
{
"answer_id": 74235081,
"author": "matt",
"author_id": 341994,
"author_profile": ... | 2022/10/28 | [
"https://Stackoverflow.com/questions/74234135",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4183424/"
] |
74,234,187 | <p>I want to do a story problem on the following math.</p>
<p>A merchant sells an item at a price $210.00 and profit 5% of the price buy. Determine the purchase price the item.</p>
<p>The answer is like the following <a href="https://i.stack.imgur.com/IcoTZ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/IcoTZ.png" alt="picture" /></a>.</p>
<p>Then, I solved it with the code below.</p>
<pre><code> from fractions import Fraction
def purchase_price(pp, profit):
x = pp + profit
return x
pp = 100
profit = 5
a = pp + profit
a = 210 * Fraction(100, 105)
print('${:,.2f}'.format(a))
</code></pre>
<p>the result is like this.</p>
<pre><code>TypeError: unsupported format string passed to Fraction.__format__
</code></pre>
<p>And I, who is still a beginner, want to ask... does my code look neat and clean?</p>
<p>My study materials are <a href="https://www.geeksforgeeks.org/find-cost-price-from-given-selling-price-and-profit-or-loss-percentage/" rel="nofollow noreferrer">here</a> and <a href="https://stackoverflow.com/questions/30926840/how-to-check-change-between-two-values-in-percent">here</a>.</p>
<p>Thank you, any help will be highly appreciated.</p>
| [
{
"answer_id": 74234222,
"author": "Rodrigo Guzman",
"author_id": 13315525,
"author_profile": "https://Stackoverflow.com/users/13315525",
"pm_score": 1,
"selected": false,
"text": "100/105"
},
{
"answer_id": 74234415,
"author": "MartinsM",
"author_id": 4658852,
"autho... | 2022/10/28 | [
"https://Stackoverflow.com/questions/74234187",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15120094/"
] |
74,234,191 | <p>I'm trying to make a dynamic (number of columns/rows might change) grid of images that always gets resized to a percentage of the viewport's size.</p>
<p>The width limit works fine, but the grid goes over the height limit. How can I fix this?
I'd also like the images to have no spaces or gaps between them (both on the y and x axis) no matter their size.</p>
<p><a href="https://jsfiddle.net/od3tyepr/" rel="nofollow noreferrer">https://jsfiddle.net/od3tyepr/</a></p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>* {
margin: 0;
border: 0;
padding-right: 0;
padding-left: 0;
padding: 0;
}
#_parent {
display: flex;
height: 100vh;
width: 50vw;
align-content: center;
align-items: center;
margin: auto;
}
#_grid {
position: relative;
display: flex;
align-items: flex-start;
height: 80%;
width: 100%;
}
#_row {
display: flex;
flex-direction: row;
flex-wrap: wrap;
}
._img {
max-width: 100%;
max-height: 100%;
width: calc(100% / 3);
object-fit: contain;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="root">
<div id="_parent">
<div id="_grid">
<div id="_row">
<img id="" src="//placeimg.com/600/400?text=1" class="_img">
<img id="" src="//placeimg.com/600/400?text=2" class="_img">
<img id="" src="//placeimg.com/600/400?text=3" class="_img">
<img id="" src="//placeimg.com/600/400?text=4" class="_img">
<img id="" src="//placeimg.com/600/400?text=5" class="_img">
<img id="" src="//placeimg.com/600/400?text=6" class="_img">
<img id="" src="//placeimg.com/600/400?text=7" class="_img">
<img id="" src="//placeimg.com/600/400?text=8" class="_img">
<img id="" src="//placeimg.com/600/400?text=9" class="_img">
<img id="" src="//placeimg.com/600/400?text=10" class="_img">
<img id="" src="//placeimg.com/600/400?text=11" class="_img">
<img id="" src="//placeimg.com/600/400?text=12" class="_img">
<img id="" src="//placeimg.com/600/400?text=13" class="_img">
<img id="" src="//placeimg.com/600/400?text=14" class="_img">
<img id="" src="//placeimg.com/600/400?text=15" class="_img">
</div>
</div>
</div>
</div></code></pre>
</div>
</div>
</p>
<p>As you can see, the image doesn't get resized to fit the height and instead there is a lot of scrolling.</p>
| [
{
"answer_id": 74234313,
"author": "foze aboelhija",
"author_id": 10121702,
"author_profile": "https://Stackoverflow.com/users/10121702",
"pm_score": -1,
"selected": false,
"text": "overflow: auto;"
},
{
"answer_id": 74234353,
"author": "Temani Afif",
"author_id": 8620333... | 2022/10/28 | [
"https://Stackoverflow.com/questions/74234191",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18618451/"
] |
74,234,199 | <p>I have an app which loads data from a json. That data could be a video, in which case it's rendered the next component:</p>
<pre><code>export default function Video({ video }) {
return (
<>
<video controls width="100%">
<source src={require(video)} type="video/mp4" />
</video>
</>
);
}
</code></pre>
<p>The param <strong>video</strong> has the path to the video, it's supossed to be located in a local folder on my app. When I try to render the component <strong>Video</strong> with a valid param, I obtain the next error:</p>
<p><code>Uncaught Error: Cannot find module 'static/content/sample_video.mp4'</code></p>
<p>Meanwhile, when I try to get the video directly from a string like this:
`</p>
<pre><code> <source src={require("static/content/sample_video.mp4")} type="video/mp4" />
</code></pre>
<p><br />
The video is rendered correctly. The parameter <strong>video</strong> has exactly the same string that I'm hardcoding in the require.</p>
<p>What should I do to render my video using the parameter?</p>
| [
{
"answer_id": 74234873,
"author": "Samy Rahmani",
"author_id": 19003871,
"author_profile": "https://Stackoverflow.com/users/19003871",
"pm_score": 1,
"selected": false,
"text": "useEffect"
}
] | 2022/10/28 | [
"https://Stackoverflow.com/questions/74234199",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17915434/"
] |
74,234,236 | <p>I am trying to send simple email through mailgun and laravel, but getting a weird error.
I am not using queue just sending a simple welcome email on run time.</p>
<p>following is error:</p>
<blockquote>
<p>Serialization of 'Closure' is not allowed</p>
</blockquote>
<p>Following is mail send code:</p>
<pre><code>$details = array(
'email' => $request->email,
'password' => $request->password,
);
Mail::send('emails.welcome', $details, function ($message) use ($user) {
$message->from('admin@mywebsite.tv', 'Admin');
$message->to($user->email);
});
</code></pre>
<p>When I comment above code, everything works fine.</p>
| [
{
"answer_id": 74234744,
"author": "Douwe de Haan",
"author_id": 1336174,
"author_profile": "https://Stackoverflow.com/users/1336174",
"pm_score": 0,
"selected": false,
"text": "Mail::from('admin@mywebsite.tv', 'Admin')->to($user->email)->send('emails.welcome', $details)\n"
},
{
... | 2022/10/28 | [
"https://Stackoverflow.com/questions/74234236",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1794208/"
] |
74,234,237 | <p><a href="https://i.stack.imgur.com/irjFP.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/irjFP.png" alt="enter image description here" /></a></p>
<p>im trying to do a v-for loop but its showing this error on vue3 + typescript project</p>
<p>this is a component and im passing props like this</p>
<pre class="lang-html prettyprint-override"><code><script setup lang="ts">
import { ref } from "vue"
defineProps({
margin: {
type: Number,
default: 1
},
futurecashflow: {
type: Array,
default: [1,2]
},
});
</script>
</code></pre>
<p>i tried everything, this error wasnt present before like a week ago this is apperaing out of no where</p>
| [
{
"answer_id": 74234744,
"author": "Douwe de Haan",
"author_id": 1336174,
"author_profile": "https://Stackoverflow.com/users/1336174",
"pm_score": 0,
"selected": false,
"text": "Mail::from('admin@mywebsite.tv', 'Admin')->to($user->email)->send('emails.welcome', $details)\n"
},
{
... | 2022/10/28 | [
"https://Stackoverflow.com/questions/74234237",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19342179/"
] |
74,234,246 | <p>I want to make the sum of the first 3 columns with <code>pmap</code>.</p>
<pre class="lang-r prettyprint-override"><code>library(tidyverse)
mtcars %>%
mutate(new = pmap(select(., 1:3), ~ sum(.))) # FAILS
mtcars %>%
mutate(new = pmap(., ~ sum(.[1:3]))) # FAILS
mpg cyl disp hp drat wt qsec vs am gear carb new
Mazda RX4 21.0 6 160.0 110 3.90 2.620 16.46 0 1 4 4 NA
Mazda RX4 Wag 21.0 6 160.0 110 3.90 2.875 17.02 0 1 4 4 NA
Datsun 710 22.8 4 108.0 93 3.85 2.320 18.61 1 1 4 1 NA
</code></pre>
<p>I know how to do it with <code>rowwise</code> or <code>RowSums</code> but I want a solution with <code>pmap</code>.</p>
| [
{
"answer_id": 74234339,
"author": "Maël",
"author_id": 13460602,
"author_profile": "https://Stackoverflow.com/users/13460602",
"pm_score": 3,
"selected": true,
"text": "pmap"
},
{
"answer_id": 74234364,
"author": "deschen",
"author_id": 2725773,
"author_profile": "ht... | 2022/10/28 | [
"https://Stackoverflow.com/questions/74234246",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8806649/"
] |
74,234,267 | <p>As I click on the "Continue" button it's not navigating me to the LogIn Screen.I tried multiple times but its not working and displaying me the above error sometimes.</p>
<p>What should be the correct code here for me to navigate to LogIn Screen.
"Navigator.pushNamed(context,<strong>#What should I write here?</strong>)."
(Also, I can provide the loginPage code as well if its required.)</p>
<pre><code>**Body.dart**
```
import 'package:flutter/material.dart';
import 'package:flutter_catalog/constants.dart';
import 'package:flutter_catalog/default_button.dart';
import 'package:flutter_catalog/pages/login_page.dart';
import 'package:flutter_catalog/size_config.dart';
import '../components/splash_content.dart';
class Body extends StatefulWidget {
@override
_BodyState createState() => _BodyState();
}
class _BodyState extends State<Body> {
int currentPage = 0;
@override
Widget build(BuildContext context) {
return SafeArea(
child: SizedBox(
width: double.infinity,
child: Column(
children: <Widget>[
Expanded(
flex: 5,
child: PageView.builder(
onPageChanged: (value) {
setState(() {
currentPage = value;
});
},
itemCount: splashData.length,
itemBuilder: (context, index) => SplashContent(
image: splashData[index]["image"],
text: splashData[index]['text'],
),
),
),
Expanded(
flex: 2,
child: Padding(
padding: EdgeInsets.symmetric(
horizontal: getProportionateScreenWidth(20)),
child: Column(
children: <Widget>[
Spacer(),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: List.generate(
splashData.length,
(index) => buildDot(index: index),
),
),
Spacer(flex: 3),
DefaultButton(
text: "Continue",
press: () {
Navigator.pushNamed(context,**#What should I write here?**);
},
),
Spacer(),
],
),
),
),
],
),
),
);
}
}
```
**Routes.dart**
```
class MyRoutes{
static String loginRoute = "/login";
static String homeRoute = "/home";
static String HomeDetailRoute = "/detail";
static String cartRoute = "/cart";
static String welcomescreenRoute = "/welcome";
static String SplashScreenRoute = "/splash";
}
**main.dart**
void main() {
setPathUrlStrategy();
runApp(VxState(store: MyStore(), child: MyApp()));
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
var vxNavigator = VxNavigator(routes: {
"/": (_, __) => MaterialPage(child: SplashScreen()),
MyRoutes.homeRoute: (_, __) => MaterialPage(child: HomePage()),
MyRoutes.SplashScreenRoute: (_, __) => MaterialPage(child: SplashScreen()),
MyRoutes.HomeDetailRoute: (uri, _) {
final catalog = (VxState.store as MyStore)
.catalog
.getById(int.parse(uri.queryParameters["id"]!));
return MaterialPage(
child: HomeDetailPage(
catalog: catalog,
),
);
},
MyRoutes.loginRoute: (_, __) => MaterialPage(child: LoginPage()),
MyRoutes.cartRoute: (_, __) => MaterialPage(child: CartPage()),
});
(VxState.store as MyStore).navigator = vxNavigator;
</code></pre>
| [
{
"answer_id": 74234339,
"author": "Maël",
"author_id": 13460602,
"author_profile": "https://Stackoverflow.com/users/13460602",
"pm_score": 3,
"selected": true,
"text": "pmap"
},
{
"answer_id": 74234364,
"author": "deschen",
"author_id": 2725773,
"author_profile": "ht... | 2022/10/28 | [
"https://Stackoverflow.com/questions/74234267",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19017043/"
] |
74,234,275 | <p>I tried to fetch 50 products from a database with the highest price but if i set the LIMIT at 50 it's just fetching the first 50 products order by the price. This is not what i want. How can i setup the mysql query right or should i fetch all and set the limit in the php fetch_assoc()?</p>
<p>SQL Query:</p>
<pre><code>SELECT id, product_name, product_url, product_price, product_delivery_time, product_on_stock, product_language, product_type
FROM product
WHERE is_active = '1' AND not product_price = 'N/A'
AND product_price > (SELECT max(product_price) from product)
</code></pre>
<p>I tried different SQL queries but without success. I'm not familiar with sub-queries and i think somewhere their is the problem.</p>
| [
{
"answer_id": 74234314,
"author": "DenicioCode",
"author_id": 2331735,
"author_profile": "https://Stackoverflow.com/users/2331735",
"pm_score": 3,
"selected": true,
"text": "order by price desc limit 50"
},
{
"answer_id": 74236116,
"author": "rootsen",
"author_id": 20083... | 2022/10/28 | [
"https://Stackoverflow.com/questions/74234275",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20083529/"
] |
74,234,303 | <p>In this playground, I want to implement a method only for const generic parameters for which a certain property holds: <a href="https://play.rust-lang.org/?version=nightly&mode=debug&edition=2021&gist=3e4d5f9f27912d032308a390a56f5f94" rel="nofollow noreferrer">https://play.rust-lang.org/?version=nightly&mode=debug&edition=2021&gist=3e4d5f9f27912d032308a390a56f5f94</a></p>
<p>I am using a zero-sized type and add a method to it:</p>
<pre class="lang-rust prettyprint-override"><code>pub struct Resource<const N: usize> {}
impl<const N: usize> Resource<N> {
const fn shorten<const M: usize>(self) -> Resource<M>
where
[(); N - M]:, // type existence only ensured if N >= M
{
// Runtime checks, though they should not be needed
if M <= N {
Resource {}
} else {
panic!("Resources can only be shortened")
}
}
}
</code></pre>
<p>The idea is that a <code>Resource<N></code> type can be shortened to <code>Resource<M></code> if <code>N >= M</code>.</p>
<p>However, when I use it like this:</p>
<pre class="lang-rust prettyprint-override"><code>pub fn bar<const N: usize>(
resource: Resource<N>,
) -> Result<((), Resource<{ N - 1 }>), Box<dyn std::error::Error>>
where
[(); N - 1]:,
{
Ok(((), resource.shorten::<{ N - 1 }>()))
}
</code></pre>
<p>I get the following compiler error:</p>
<pre><code>error: unconstrained generic constant
--> src/main.rs:43:22
|
43 | Ok(((), resource.shorten::<{ N - 1 }>()))
| ^^^^^^^
|
= help: try adding a `where` bound using this expression: `where [(); N - M]:`
note: required by a bound in `Resource::<N>::shorten`
--> src/main.rs:8:14
|
6 | const fn shorten<const M: usize>(self) -> Resource<M>
| ------- required by a bound in this
7 | where
8 | [(); N - M]:, // type existence only ensured if N >= M
| ^^^^^ required by this bound in `Resource::<N>::shorten`
</code></pre>
<p>I understand (and found in other online resources) that the compiler suggestion with <code>where</code> might be misleading (as it is not a commonly used feature). Ignoring the suggestion, I am not sure why and where this bound is required in the first place.</p>
<p>In <code>bar</code>, the <code>shorten</code> call is executed on <code>Resource<N></code> (clear from parameter) to return <code>Resource<{N - 1}></code> (clear from turbo-fish). What am I missing?</p>
<p>Happy to hear some thoughts from more experienced Rustaceans.</p>
| [
{
"answer_id": 74234418,
"author": "Chayim Friedman",
"author_id": 7884305,
"author_profile": "https://Stackoverflow.com/users/7884305",
"pm_score": 2,
"selected": true,
"text": "N"
}
] | 2022/10/28 | [
"https://Stackoverflow.com/questions/74234303",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2365618/"
] |
74,234,310 | <p>TLDR: How can I make a notebook cell save its own python code to a file so that I can reference it later?</p>
<p>I'm doing tons of small experiments where I make adjustments to Python code to change its behaviour, and then run various algorithms to produce results for my research. I want to save the cell code (the actual python code, not the output) into a new uniquely named file every time I run it so that I can easily keep track of which experiments I have already conducted. I found lots of answers on saving the output of a cell, but this is not what I need. Any ideas how to make a notebook cell save its own code to a file in Google Colab?</p>
<p>For example, I'm looking to save a file that contains the entire below snippet in text:</p>
<pre><code>df['signal adjusted'] = df['signal'].pct_change() + df['baseline']
results = run_experiment(df)
</code></pre>
| [
{
"answer_id": 74234954,
"author": "Tuppitappi",
"author_id": 10129894,
"author_profile": "https://Stackoverflow.com/users/10129894",
"pm_score": 0,
"selected": false,
"text": "cell_str = '''\ndf['signal adjusted'] = df['signal'].pct_change() + df['baseline']\nresults = run_experiment(df... | 2022/10/28 | [
"https://Stackoverflow.com/questions/74234310",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10129894/"
] |
74,234,329 | <p>I have an API data source I am refreshing daily to gather power bi activity. Each day, the data returns a different amount of columns, so it might have 60 one day and 80 (+20) additional another day.</p>
<p>When I try to refresh the dataset in the Power BI Service, it naturally fails and states that the new columns cannot be found in the row set.</p>
<p>I have explored many options such as creating a combine table, however I do not know all the names of the columns that could come in each day so this failed because it was very static. Does anyone know of a way to dynamically handle these daily changes?</p>
<p>Many thanks</p>
| [
{
"answer_id": 74235585,
"author": "JSmart523",
"author_id": 7158380,
"author_profile": "https://Stackoverflow.com/users/7158380",
"pm_score": 0,
"selected": false,
"text": "type any"
}
] | 2022/10/28 | [
"https://Stackoverflow.com/questions/74234329",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16406181/"
] |
74,234,330 | <pre class="lang-py prettyprint-override"><code>ip_address = input().split(".")
if ip_address[0] >= 0 and ip_address[0].isnumeric() and ip_address[0] <=255:
print("Valid first byte")
else:
print("Invalid first byte")
</code></pre>
<p>In this code, when I add my final condition of <code>ip_address[0] <=255</code> I always get my byte as invalid even though it would technically fit those parameters. For example, I've tried inputs 0 and 127 but they come up as invalid, but if I remove the last condition they are valid. Where am I going wrong?</p>
<p>I've tried putting it as <code>ip_address[0] < 256</code> but this hasn't worked either.</p>
| [
{
"answer_id": 74234400,
"author": "quamrana",
"author_id": 4834,
"author_profile": "https://Stackoverflow.com/users/4834",
"pm_score": 2,
"selected": false,
"text": "input()"
},
{
"answer_id": 74234411,
"author": "Kungfu panda",
"author_id": 15349625,
"author_profile... | 2022/10/28 | [
"https://Stackoverflow.com/questions/74234330",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20357515/"
] |
74,234,352 | <p>I'm running a process and I have committed a mistake in the condition so now is executing forever. How can I stop this without closing the R session?</p>
<p>Thanks</p>
| [
{
"answer_id": 74234400,
"author": "quamrana",
"author_id": 4834,
"author_profile": "https://Stackoverflow.com/users/4834",
"pm_score": 2,
"selected": false,
"text": "input()"
},
{
"answer_id": 74234411,
"author": "Kungfu panda",
"author_id": 15349625,
"author_profile... | 2022/10/28 | [
"https://Stackoverflow.com/questions/74234352",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10668119/"
] |
74,234,356 | <p>I have a WordPress site and some of the images on my site are not displayed on mobile.
My site is WordPress and I use the rocket plugin, but there are no problems with the mobile settings
<a href="https://i.stack.imgur.com/FbTNT.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/FbTNT.png" alt="my site" /></a></p>
<p>my site : <a href="https://farazito.ir/" rel="nofollow noreferrer">farazito.ir</a></p>
| [
{
"answer_id": 74234400,
"author": "quamrana",
"author_id": 4834,
"author_profile": "https://Stackoverflow.com/users/4834",
"pm_score": 2,
"selected": false,
"text": "input()"
},
{
"answer_id": 74234411,
"author": "Kungfu panda",
"author_id": 15349625,
"author_profile... | 2022/10/28 | [
"https://Stackoverflow.com/questions/74234356",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14778493/"
] |
74,234,379 | <p>I have job class numbers stored on the database and want to show my data in "DataGridView" by replacing the job class numbers with job class name.</p>
<p>I use Entity Framework and retrieve data from the database to a generic list.</p>
<p>I try to create DataTable and bound the DataGridView to it.</p>
<p>Is this way correct?</p>
<p>In my code below I want to determine the column that is used in DataTable but it does not work properly if I remove column names ("ID", "Nme", "jobClass" ... ) it work and show all columns in DataGridView but with add column names I get reeor.</p>
<p><a href="https://i.stack.imgur.com/1AISQ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/1AISQ.png" alt="enter image description here" /></a></p>
<p>`</p>
<pre><code>IEnumerable<Employee> employeesList = new List<Employee>();
employeesList = db.EmployeeRepository.GetAllEmployees();
DataTable employeesTable = new DataTable();
using (var reader = ObjectReader.Create(employeesList,"ID", "Name", "jobClass", "College", "Department" ))
{
employeesTable.Load(reader);
}
dgvEmployees.DataSource = employeesTable;
</code></pre>
<p>`</p>
| [
{
"answer_id": 74234400,
"author": "quamrana",
"author_id": 4834,
"author_profile": "https://Stackoverflow.com/users/4834",
"pm_score": 2,
"selected": false,
"text": "input()"
},
{
"answer_id": 74234411,
"author": "Kungfu panda",
"author_id": 15349625,
"author_profile... | 2022/10/28 | [
"https://Stackoverflow.com/questions/74234379",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5204828/"
] |
74,234,423 | <p>I have this query</p>
<pre><code>SELECT *
FROM table1 as t1
WHERE (t1.phone != "" OR t1.sms_phone != "")
and t1.docType in (1,2,3)
and not exists (select id from table2 where product_id=1 and doc_id=t1.id);
</code></pre>
<p>And I want to replace the part with "not exists" with JOIN, so I tried this way:</p>
<pre><code>SELECT *
FROM table1 as t1
LEFT OUTER JOIN table2
ON table2.doc_id = t1.id
AND table2.product_id = 1
and table2.id IS NULL
WHERE (t1.phone != "" OR t1.sms_phone != "")
and t1.docType in (1,2,3);
</code></pre>
<p>But second query returns much more records..</p>
| [
{
"answer_id": 74234531,
"author": "Akina",
"author_id": 10138734,
"author_profile": "https://Stackoverflow.com/users/10138734",
"pm_score": 2,
"selected": true,
"text": "SELECT t1.*\nFROM table1 AS t1 \nLEFT JOIN table2 AS t2 ON t2.product_id=1 AND t2.doc_id=t1.id\nWHERE (t1.phone != \"... | 2022/10/28 | [
"https://Stackoverflow.com/questions/74234423",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19515751/"
] |
74,234,431 | <p>I'm working on a bookstore using Django. I'm trying to save each book's cover in each book created by the user using imagefield. I implemented every step in Django documentation about using imagefield but it doesn't work.</p>
<p>settings.py(in main project):</p>
<pre><code>MEDIA_DIR = os.path.join(BASE_DIR,'media')
MEDIA_ROOT = MEDIA_DIR
MEDIA_URL = '/media/'
</code></pre>
<p>in urls.py (main project):</p>
<pre><code>from django.contrib import admin
from django.urls import include, path
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path("admin/", admin.site.urls),
path("", include("book.urls")),
]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
</code></pre>
<p>in models.py(the book app):</p>
<pre><code>class books(models.Model):
cover = models.ImageField(upload_to='cover/co', blank=True)
</code></pre>
<p>When I want go admin I find that the photo is submitted (when I click on the photo url in database nothing is shown to me) but I don't find any created media folders and when I try to request the image in any template It isn't showed to me.
when I try to click on the photo in the database in admin this is shown to me:
<a href="https://i.stack.imgur.com/ZLByu.png" rel="nofollow noreferrer">enter image description here</a>
These are the paths of the app, project and static:
<a href="https://i.stack.imgur.com/WQ4Kg.png" rel="nofollow noreferrer">enter image description here</a></p>
<p>I don't know where is the problem and how to solve it as this is my first time to use imagefiled in django model,,, it might be from the paths, the model or the urls so if there is any help.</p>
| [
{
"answer_id": 74234676,
"author": "Manoj Tolagekar",
"author_id": 17808039,
"author_profile": "https://Stackoverflow.com/users/17808039",
"pm_score": 0,
"selected": false,
"text": "MEDIA_URL='/media/'\nMEDIA_ROOT=os.path.join(BASE_DIR,'media')\n"
},
{
"answer_id": 74235506,
... | 2022/10/28 | [
"https://Stackoverflow.com/questions/74234431",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19704638/"
] |
74,234,450 | <p>I've made myself an API which returns the following values:</p>
<pre><code>[{"id":1,"title":"Illmatic","artist":"Nas","songs":["The Genesis","N.Y. State Of Mind","The World Is Yours"],"offer":25.01,"offer_owner":123456,"due_date":1669593600000,"genre":"hiphop","auction_owner":696969},
{"id":2,"title":"Life After Death","artist":"The Notorious B.I.G.","songs":["Intro","Things Done Changed","Gimme The Loot"],"offer":25,"offer_owner":696969,"due_date":1669593600000,"genre":"hiphop","auction_owner":123456},
{"id":3,"title":"After Hours","artist":"The Weekend","songs":["Alone Again","After Hours","Save Your Tears","Escape From LA","Snowchild"],"offer":25,"offer_owner":123456,"due_date":1369593600000,"genre":"pop","auction_owner":696969}]
</code></pre>
<p>I have the following Svelte code:</p>
<pre><code>import { onMount } from "svelte";
let albums;
onMount(async () => {
fetch("http://localhost:8080/api/albums/").then((response) => response.json().then(
(data) => albums = data
// console.log(data) returns data ));
});
console.log(albums); // returns undefined?
</code></pre>
<p>Note: when I fetch the data from the API I get the data in my data variable. When I console log on it, it returns an array with 3 rows.</p>
<p>But when I want to write my data value to the albums variable it gets undefined when I call the console.log at the last row of the script. What am I doing wrong? I'm kinda stuck because I really don't know where the problem is.</p>
<p><strong>Edit:</strong></p>
<p>Based on the comments I managed to fix the issue.</p>
<pre><code><script>
import { onMount } from "svelte";
let albums;
let hasData;
onMount(async () => {
fetch("http://localhost:8080/api/albums/")
.then((response) => response.json())
.then((data) => {
albums = data;
hasData = true;
});
});
</script>
{#if hasData}
{#each Object.values(albums) as album}
{album.title}
{:else}
<p>Loading...</p>
{/each}
{/if}
</code></pre>
| [
{
"answer_id": 74234676,
"author": "Manoj Tolagekar",
"author_id": 17808039,
"author_profile": "https://Stackoverflow.com/users/17808039",
"pm_score": 0,
"selected": false,
"text": "MEDIA_URL='/media/'\nMEDIA_ROOT=os.path.join(BASE_DIR,'media')\n"
},
{
"answer_id": 74235506,
... | 2022/10/28 | [
"https://Stackoverflow.com/questions/74234450",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10031659/"
] |
74,234,457 | <p>i am a beginner on reactjs.i am trying to make a login and logout system.it is expexted that when i login, the navbar will show a logout buttom.But i found that i have login to the page but the logout buttom on the navbar is not work
here is my layout for navbar:</p>
<pre><code>function Layout(props) {
</code></pre>
<p>const loginStatus=props.loginstatus;</p>
<pre><code>return (
<Navbar style={{"backgroundColor":"rgb(146, 212, 246)"}} variant='dark'expand="lg">
<Container className="container" fluid >
<Navbar.Brand href="/"><strong>STH News</strong></Navbar.Brand>
<Navbar.Toggle aria-controls="navbarScroll" />
<Navbar.Collapse id="navbarScroll">
<Nav
className="me-auto my-2 my-lg-0"
style={{ 'fontSize': '20px' }}
navbarScroll
>
<Nav.Link style={{'color':"white"}} href="/">Home</Nav.Link>
{loginStatus ?
<><form onSubmit={props.handlelogout}><Nav.Link style={{ 'color': "white" }} href='/' type='submit'>Logout</Nav.Link></form><NavDropdown style={{ 'color': "white" }} title="Your account" id="navbarScrollingDropdown">
<NavDropdown.Item href="#action3">Stored News</NavDropdown.Item>
<NavDropdown.Item href="#action4">
History
</NavDropdown.Item>
<NavDropdown.Divider />
<NavDropdown.Item href="#action5">
Personal infomation
</NavDropdown.Item>
</NavDropdown></>:
<Nav.Link style={{'color':"white"}} href="/login">Login</Nav.Link>
}
</Nav>
</code></pre>
<p>i use the index page for handling the function on login and logout.Here is my index.js:</p>
<pre><code>export default function Index(){
const [loginStatus,setLoginStatus]=useState({loginStatus:false});
function handlelogout(){
setLoginStatus({loginStatus:false})
console.log("logouted")
}
return(
<BrowserRouter>
<Layout loginstatus={loginStatus} logout={handlelogout} />
<Routes>
<Route path="/" />
<Route index element={<App />}/>
<Route path="login" element={<Login loginstatus={()=>{setLoginStatus(true);console.log("login")} }/>}/>
</Routes>
</BrowserRouter>
)
}
</code></pre>
<p>my login page:</p>
<pre><code>const Login=(props)=> {
return (
<><form onSubmit={props.loginstatus}><Button type='submit' variant="primary">Primary</Button></form>{/* <Link
to={{pathname:'/layout',state:loginStatus}} /> */}</>);
}
export default Login;
</code></pre>
<p>the loginstatus is used to set the status ,but seems the problem is on handling the loginstatus in between the pages.</p>
| [
{
"answer_id": 74234676,
"author": "Manoj Tolagekar",
"author_id": 17808039,
"author_profile": "https://Stackoverflow.com/users/17808039",
"pm_score": 0,
"selected": false,
"text": "MEDIA_URL='/media/'\nMEDIA_ROOT=os.path.join(BASE_DIR,'media')\n"
},
{
"answer_id": 74235506,
... | 2022/10/28 | [
"https://Stackoverflow.com/questions/74234457",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20112858/"
] |
74,234,467 | <p>I have list of dfs (in the code below named "Input") which can vary in its length (regarding the amount of dfs) and I want to sum specific sections of each column which refers to the year in the first column of each df. In the end I want my code to give me back the exact same list of dfs but with the summed values in each column (in the code below named "output"). So, I want to get from "Input" to "output".</p>
<pre><code>import pandas as pd
# Input
l1 = [2022, 2022, 2022, 2022, 2023, 2023, 2023, 2023]
l2 = [1,2,3,4,5,6,7,8]
l3 = [2,3,4,5,6,7,8,9]
l4 = [1,2,3,4,5,6,7,8]
l5 = [2,3,4,5,6,7,8,9]
l6 = [1,2,3,4,5,6,7,8]
df00_in = pd.concat([pd.DataFrame(l1), pd.DataFrame(l2),
pd.DataFrame(l3), pd.DataFrame(l4), pd.DataFrame(l5), pd.DataFrame(l6)], axis = 1)
df01_in = pd.concat([pd.DataFrame(l1), pd.DataFrame(l2),
pd.DataFrame(l3), pd.DataFrame(l4), pd.DataFrame(l5), pd.DataFrame(l6)], axis = 1)
df02_in = pd.concat([pd.DataFrame(l1), pd.DataFrame(l2),
pd.DataFrame(l3), pd.DataFrame(l4), pd.DataFrame(l5), pd.DataFrame(l6)], axis = 1)
# list of input dfs
Input = [df00_in, df01_in, df02_in]
###################################
# Output
l7 = [2022, 2023]
l8 = [sum(l2[:4]), sum(l2[4:])]
l9 = [sum(l3[:4]), sum(l3[4:])]
l10 = [sum(l4[:4]), sum(l4[4:])]
l11 = [sum(l5[:4]), sum(l5[4:])]
l12 = [sum(l6[:4]), sum(l6[4:])]
df00_out = pd.concat([pd.DataFrame(l7), pd.DataFrame(l8),
pd.DataFrame(l9), pd.DataFrame(l10), pd.DataFrame(l11), pd.DataFrame(l12)], axis = 1)
df01_out = pd.concat([pd.DataFrame(l7), pd.DataFrame(l8),
pd.DataFrame(l9), pd.DataFrame(l10), pd.DataFrame(l11), pd.DataFrame(l12)], axis = 1)
df02_out = pd.concat([pd.DataFrame(l7), pd.DataFrame(l8),
pd.DataFrame(l9), pd.DataFrame(l10), pd.DataFrame(l11), pd.DataFrame(l12)], axis = 1)
# list of output dfs
output = [df00_out, df01_out, df02_out]
</code></pre>
<p>In the example above I added each year only four times (quarterly), but it can happen that every year will appear 12 times (so monthly and the dfs will expand in the same way). So, my idea is some kind of "SumIf: years are the same".
Any ideas on that? THX!</p>
| [
{
"answer_id": 74234622,
"author": "ozacha",
"author_id": 5726768,
"author_profile": "https://Stackoverflow.com/users/5726768",
"pm_score": 2,
"selected": false,
"text": "pd.concat"
},
{
"answer_id": 74234719,
"author": "louis",
"author_id": 18018014,
"author_profile"... | 2022/10/28 | [
"https://Stackoverflow.com/questions/74234467",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19776970/"
] |
74,234,488 | <p>I am not sure, if it's possible, but take this snippet of code:</p>
<pre><code>#include <stdio.h>
struct car {
float speed;
};
struct bike {
float speed;
};
void drive(float* speed)
{
printf("driving at speed %f\n", *speed);
}
template<typename T>
void drive(T driveable)
{
drive(&driveable->speed);
}
int main() {
struct car car = { .speed = 10.f };
struct bike bike = { .speed = 20.f };
drive(&car);
drive(&bike);
}
</code></pre>
<p>The idea is that any object that has a member field of type <code>float</code> and that is named <code>speed</code> can be used transparently with the function <code>drive</code>. Thanks to the template-overload function <code>drive</code>, which passes the member of the template type to the actual <code>drive</code> free-function.</p>
<p>Is it possible, to combine the template - function with the free-function in a single one? Something along the lines:</p>
<pre><code>template<typename T>
void drive(T driveable)
void drive(float *speed = &driveable->speed)
{
printf("driving at speed %f\n", *speed);
}
</code></pre>
<p>Additionally, would there be another, more elegant way to do what I want?</p>
| [
{
"answer_id": 74234622,
"author": "ozacha",
"author_id": 5726768,
"author_profile": "https://Stackoverflow.com/users/5726768",
"pm_score": 2,
"selected": false,
"text": "pd.concat"
},
{
"answer_id": 74234719,
"author": "louis",
"author_id": 18018014,
"author_profile"... | 2022/10/28 | [
"https://Stackoverflow.com/questions/74234488",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6784916/"
] |
74,234,491 | <p>As part of a Frontend Mentor challenge, I am creating a simple email validation for a subscription landing page. It simply checks whether the email field is empty, if so, it throws an error message. Another error message is shown if the user enters an incorrect email address.</p>
<p>I've created a function called <em>checkInputs()</em> which contains a conditional <em>else if</em> statement</p>
<p>When testing on live server, the first condition works fine, when I leave the email field empty, however, the second condition doesn't even run, nor does the third.</p>
<p>I've included the full in case it's anything else throwing the whole function off. I tested the function <em>isEmail()</em> which checks whether the email is valid, and it works fine for me.</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 form = document.getElementById('form');
const email = document.getElementById('email');
form.addEventListener('submit', (e) => {
e.preventDefault();
checkInputs();
})
function checkInputs() {
const emailValue = email.value;
const emptyEmail = emailValue === '';
const invalidEmail = !isEmail(emailValue);
if (emptyEmail) {
setErrorFor(email, 'Oops! Please add your email');
} else if (invalidEmail) {
setErrorFor(email, 'Oops! Please check your email');
} else {
setSuccessFor(emailValue);
}
};
function setErrorFor(input, message) {
const formGroup = input.parentElement;
const small = formGroup.querySelector('small');
formGroup.className = 'form-group error';
small.innerHTML = message;
}
function setSuccessFor(input) {
const formGroup = input.parentElement;
formGroup.className = 'form-group success';
}
// checks if email is valid
function isEmail(email) {
const regx = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return regx.test(email);
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="form-group">
<form id="form" method="POST" name="subscribe">
<input type="email" placeholder="Email address" name="email" id="email" class="email-input error">
<br>
<small></small>
<br>
<button class="form-btn" type="submit">Request Access</button>
</form>
</div></code></pre>
</div>
</div>
</p>
| [
{
"answer_id": 74234524,
"author": "Jamie Burton",
"author_id": 10091841,
"author_profile": "https://Stackoverflow.com/users/10091841",
"pm_score": -1,
"selected": false,
"text": "const emptyEmail = emailValue === '';\n"
},
{
"answer_id": 74234584,
"author": "Aniket Pradhan",... | 2022/10/28 | [
"https://Stackoverflow.com/questions/74234491",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16977174/"
] |
74,234,501 | <p>I am trying to insert hard coded data with QueryBuilder insertGetId() method.</p>
<p>my code is-</p>
<pre><code><?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
class StudentController extends Controller
{
public function addStudent()
{
$foreign_key = DB::table('students')->insertGetId([
'id' => 'stu-000002',
'name' => 'Ahsan',
'email' => 'ahsan@example.net',
]);
echo $foreign_key;
}
}
</code></pre>
<p>My migration file is-</p>
<pre><code><?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('students', function (Blueprint $table) {
$table->string('id', 30)->primary();
$table->string('name', 100);
$table->string('email', 100)->unique();
$table->timestamp('created_at')->useCurrent();
$table->timestamp('updated_at')->useCurrent();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('students');
}
};
</code></pre>
<p>My route is -</p>
<pre><code>Route::post('/add-student', [StudentController::class, 'addStudent']);
</code></pre>
<p>But result is -</p>
<pre><code>Symfony \ Component \ HttpKernel \ Exception \ MethodNotAllowedHttpException
The GET method is not supported for this route. Supported methods: POST.
</code></pre>
<p>But when I try to insert data with get method like-</p>
<pre><code>Route::get('/add-student', [StudentController::class, 'addStudent']);
</code></pre>
<p>Data has been inserted . But primary key has been retrived 0 as primary key is custom string.</p>
<p>How can I solve this problem. Thank you.</p>
| [
{
"answer_id": 74235271,
"author": "Douwe de Haan",
"author_id": 1336174,
"author_profile": "https://Stackoverflow.com/users/1336174",
"pm_score": 0,
"selected": false,
"text": "MethodNotAllowedException"
},
{
"answer_id": 74235917,
"author": "Zaryabro1",
"author_id": 104... | 2022/10/28 | [
"https://Stackoverflow.com/questions/74234501",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15572918/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.