qid int64 4 22.2M | question stringlengths 18 48.3k | answers list | date stringlengths 10 10 | metadata list |
|---|---|---|---|---|
74,350,412 | <p>Can anyone help I am a beginner? I want the variable choice to be displayed after the menu is but I need the variable to be on top so the name inserted can be shown beside add player name.</p>
<pre class="lang-py prettyprint-override"><code>choice = input("Input your menu choice: ")
choice = False
if choice == "1":
name = input("What is your name? ")
print(" Menu ")
print("------------------------------------------")
print(f"[1] Add player name: {name} ")
print("[2] Play guess the capital city")
print("[3] End game")
print("------------------------------------------")
choice True
</code></pre>
<p>I tried to use a Boolean but it didn't so any help would be great.</p>
| [
{
"answer_id": 74350614,
"author": "Johnny John Boy",
"author_id": 7553746,
"author_profile": "https://Stackoverflow.com/users/7553746",
"pm_score": 1,
"selected": false,
"text": "import random\n\nname = 'Anonomous'\n\nplaying = True\n\nwhile playing == True:\n print(\" Menu \")\n print(\"------------------------------------------\")\n print(f\"[1] Add player name: {name} \")\n print(\"[2] Play guess the capital city\")\n print(\"[3] End game\")\n print(\"------------------------------------------\")\n\n choice = input(\"Input your menu choice: \")\n\n if choice == \"1\":\n name = input(\"What is your name? \")\n\n if choice == \"2\":\n winner = False\n capital_city = random.choice(['London', 'Paris', 'Rome'])\n while not winner:\n guess = input(\"What capital city am I thinking of? \").title()\n if guess == capital_city:\n print(f'You won!!! I was thinking of {guess}..')\n winner = True\n else:\n print(f'No, it was not {guess}, guess again..')\n \n if choice == \"3\":\n playing = False\n"
},
{
"answer_id": 74350737,
"author": "bwilk315",
"author_id": 20438342,
"author_profile": "https://Stackoverflow.com/users/20438342",
"pm_score": 0,
"selected": false,
"text": "choice = input(\"Input your menu choice: \")\nchoice = False\n"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74350412",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20442394/"
] |
74,350,413 | <p>This is my dataframe:</p>
<pre><code>df <- structure(list(month_date = structure(c(19117, 19149, 19180,
19212, 19244, 19275), class = "Date"), Values = c(9693, 10227,
10742, 11672, 10565, 10080)), row.names = c(NA, -6L), class = c("tbl_df",
"tbl", "data.frame"))
</code></pre>
<p>I need to increse the column month_date until "2023-12-01" with "NA" values.</p>
<p>The output should be a datframe with months until "2023-12-01" and on the Values column filled by "NA" values starting on "2022-11-01".</p>
<p>How can I do this?</p>
| [
{
"answer_id": 74350614,
"author": "Johnny John Boy",
"author_id": 7553746,
"author_profile": "https://Stackoverflow.com/users/7553746",
"pm_score": 1,
"selected": false,
"text": "import random\n\nname = 'Anonomous'\n\nplaying = True\n\nwhile playing == True:\n print(\" Menu \")\n print(\"------------------------------------------\")\n print(f\"[1] Add player name: {name} \")\n print(\"[2] Play guess the capital city\")\n print(\"[3] End game\")\n print(\"------------------------------------------\")\n\n choice = input(\"Input your menu choice: \")\n\n if choice == \"1\":\n name = input(\"What is your name? \")\n\n if choice == \"2\":\n winner = False\n capital_city = random.choice(['London', 'Paris', 'Rome'])\n while not winner:\n guess = input(\"What capital city am I thinking of? \").title()\n if guess == capital_city:\n print(f'You won!!! I was thinking of {guess}..')\n winner = True\n else:\n print(f'No, it was not {guess}, guess again..')\n \n if choice == \"3\":\n playing = False\n"
},
{
"answer_id": 74350737,
"author": "bwilk315",
"author_id": 20438342,
"author_profile": "https://Stackoverflow.com/users/20438342",
"pm_score": 0,
"selected": false,
"text": "choice = input(\"Input your menu choice: \")\nchoice = False\n"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74350413",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20359538/"
] |
74,350,443 | <p>In Azure Devops, let's say you have three self-hosted agents that run on three different Windows Servers and they are all part of the Default agent pool. When you create a build you're only able to specify what agent pool to pull from. If your wanting to create the build to run a specific agent (windows server) where do you specify this or how does it know to grab the right agent?? If you could please provide and explanation on how this works.</p>
<p>Thank you</p>
| [
{
"answer_id": 74350614,
"author": "Johnny John Boy",
"author_id": 7553746,
"author_profile": "https://Stackoverflow.com/users/7553746",
"pm_score": 1,
"selected": false,
"text": "import random\n\nname = 'Anonomous'\n\nplaying = True\n\nwhile playing == True:\n print(\" Menu \")\n print(\"------------------------------------------\")\n print(f\"[1] Add player name: {name} \")\n print(\"[2] Play guess the capital city\")\n print(\"[3] End game\")\n print(\"------------------------------------------\")\n\n choice = input(\"Input your menu choice: \")\n\n if choice == \"1\":\n name = input(\"What is your name? \")\n\n if choice == \"2\":\n winner = False\n capital_city = random.choice(['London', 'Paris', 'Rome'])\n while not winner:\n guess = input(\"What capital city am I thinking of? \").title()\n if guess == capital_city:\n print(f'You won!!! I was thinking of {guess}..')\n winner = True\n else:\n print(f'No, it was not {guess}, guess again..')\n \n if choice == \"3\":\n playing = False\n"
},
{
"answer_id": 74350737,
"author": "bwilk315",
"author_id": 20438342,
"author_profile": "https://Stackoverflow.com/users/20438342",
"pm_score": 0,
"selected": false,
"text": "choice = input(\"Input your menu choice: \")\nchoice = False\n"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74350443",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8481408/"
] |
74,350,449 | <p>I have a List.
Employee, for example:</p>
<pre><code>@Data
@AllArgConstructor
public class Employee {
private string firstName;
private string last name;
private domestic salary;
private LocalDataTime getSalary;
}
</code></pre>
<p>The sheet can contain data with the same last name, first name, but different date and salary.
Or maybe not. For example.</p>
<pre><code>List<Employee> employee = new ArrayList<>();
Employee one = new Employee("John", "Smith", 10, 2022-09-01);
Employee two = new Employee("John", "Smith", 20, 2022-10-01);
Employee three = new Employee("John", "Smith", 5, 2022-11-01);
Employee four = new Employee("Kelly", "Jones", 12, 2022-03-01);
Employee five = new Employee("Sara", "Kim", 21, 2022-03-01);
Employee six = new Employee("Sara", "Kim", 7, 2022-07-01);
employee.add(one);
employee.add(two);
employee.add(three);
employee.add(four);
employee.add(five);
employee.add(six);
</code></pre>
<p>Need for each unique combination of last name and first name, get a data for the last date.</p>
<p>In Out:</p>
<p>"John", "Smith", 5, 2022-11-01</p>
<p>"Kelly", "Jones", 12, 2022-03-01</p>
<p>"Sara", "Kim", 7, 2022-07-01</p>
<p>I'm just starting to learn stream API and dont understand how to filter by a field inside an object for 2 unique other fields.</p>
<p>Is it possible to do so?</p>
| [
{
"answer_id": 74350726,
"author": "YCF_L",
"author_id": 5558072,
"author_profile": "https://Stackoverflow.com/users/5558072",
"pm_score": 1,
"selected": false,
"text": "BinaryOperator"
},
{
"answer_id": 74351189,
"author": "Ashish Patil",
"author_id": 5014221,
"author_profile": "https://Stackoverflow.com/users/5014221",
"pm_score": 0,
"selected": false,
"text": "HashMap<List<String>>,Employee>"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74350449",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17089505/"
] |
74,350,501 | <p>I have a dataset containing information of some purchases starting on <code>03/01/2018 03:00</code> and ending on <code>25/04/2022 15:00</code>. There's no pattern between dates and times of purchase occurrences. For instance, there's no purchase happening on <code>04/01/2018 05:00</code> or <code>04/01/2018 15:00</code>, etc. For each day, I am trying to find the latest time in which a purchase has happened.</p>
<p>For example, based on the following dataset, is it possible to have a dictionary that as a key stores dates and as a value the latest price of the purchase?</p>
<pre><code>"03/01/2018" => 9.3
"04/01/2018" => 5.4
"03/01/2019" => 7.6
.... all the way to 25/04/2022 15:00
</code></pre>
<p><a href="https://i.stack.imgur.com/e4pMc.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/e4pMc.png" alt="enter image description here" /></a></p>
| [
{
"answer_id": 74351450,
"author": "Dan Getz",
"author_id": 3580870,
"author_profile": "https://Stackoverflow.com/users/3580870",
"pm_score": 3,
"selected": true,
"text": "DataFrames"
},
{
"answer_id": 74355239,
"author": "giantmoa",
"author_id": 20258205,
"author_profile": "https://Stackoverflow.com/users/20258205",
"pm_score": 2,
"selected": false,
"text": "InMemoryDatasets"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74350501",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13099604/"
] |
74,350,517 | <p>I'm using a database within my Titanium app to pull data, and in turn loop through display the section headers, then content within each section.</p>
<p>All works great, with the exception of when I tap on any of the first 7 sections, they all return the last section details when I tap the listitem.</p>
<p>Pretty sure this is a simple fix where I'm passing the args across, but I'm struggling to get this working correctly!</p>
<p>Here is my Controller</p>
<pre><code>var args = $.args;
// Here we need to get the courseID and then return the correct sessions for that course
var courseID = args.courseID;
$.courseDetailWindow.title = args.courseTitle.text.toUpperCase();
// open the DB
var db = Ti.Database.open('myDB');
// set the ListSections outside of the loop
var sections = [];
// do the loop of sessions for this course
var sessionRS = db.execute('SELECT session_id, session_name, session_intro, session_course_id FROM sessions WHERE session_course_id = ' + courseID);
while (sessionRS.isValidRow()) {
var sessionName = sessionRS.fieldByName('session_name');
var sessionID = sessionRS.fieldByName('session_id');
// create the List Section
var listSection = Ti.UI.createListSection({ headerTitle: sessionName});
// create the data set of drills
var drillDataSet = [];
// do the loop of drills for this session
var drillRS = db.execute('SELECT drill_id, drill_name, drill_intro, drill_instructions, drill_video, drill_duration FROM drills WHERE session_id = ' + sessionID);
while (drillRS.isValidRow()) {
var drillName = drillRS.fieldByName('drill_name');
var drillDuration = drillRS.fieldByName('drill_duration');
var drillVideo = drillRS.fieldByName('drill_video');
var drillIntro = drillRS.fieldByName('drill_intro');
var drillInstructions = drillRS.fieldByName('drill_instructions');
// push the drill data into the array
drillDataSet.push({
template : "drillTemplate",
drillName : { text : drillName },
drillDuration : { text : "Drill - " + drillDuration },
drillInstructions : { text : drillInstructions },
drillIntro : { text : drillIntro },
drillIcon : { image : "images/control-cat-icon.png" },
drillVideo : { url : drillVideo}
});
// assign those drills to the session
listSection.setItems(drillDataSet);
// move onto the next drill
drillRS.next();
}
// close the drill DB connection
drillRS.close();
// add the session name and drills to the section
sections.push(listSection);
// move onto the next session
sessionRS.next();
}
// close the session DB connection
sessionRS.close();
// Push all of the content to the main ListView
$.courseDetailView.sections = sections;
// Handle the List Row Tap
function openDrillDetail(e) {
var drillDetailWindow = Alloy.createController('/drillDetail', drillDataSet[e.itemIndex]).getView();
if (OS_IOS) {
Alloy.Globals.tabGroup.activeTab.open(drillDetailWindow);
}
if (OS_ANDROID) {
drillDetailWindow.open();
}
}
</code></pre>
<p>The issue would be within the drillDataSet, and it's index. I'm assuming it's returning the last section as I'm essentially overwriting it within each loop. But I'm stuck!</p>
<p>I need the OpenDrillDetail() function to send the correct args across to the next screen.</p>
<p>Here is my XML.</p>
<pre><code><Alloy>
<Window id="courseDetailWindow">
<ScrollView id="courseDetailScrollView">
<ListView id="courseDetailView" defaultItemTemplate="drillTemplate" onItemclick="openDrillDetail" height="Ti.UI.SIZE">
<Templates>
<ItemTemplate name="drillTemplate" id="drillTemplate">
<View id="drillOuterView">
<View id="greenBlock">
<ImageView bindId="drillIcon" id="drillIcon" />
</View>
<Label bindId="drillName" id="drillName" />
<Label bindId="drillDuration" id="drillDuration" />
</View>
</ItemTemplate>
</Templates>
<!--<HeaderView id="sessionView">
<View height="Ti.UI.SIZE" layout="vertical">
<Label id="sessionTitle" text="Session 1"></Label>
</View>>
</HeaderView>-->
<ListSection id="drillSection">
<ListItem template="drillTemplate" id="drillView"/>
</ListSection>
</ListView>
</ScrollView>
</Window>
</Alloy>
</code></pre>
| [
{
"answer_id": 74351450,
"author": "Dan Getz",
"author_id": 3580870,
"author_profile": "https://Stackoverflow.com/users/3580870",
"pm_score": 3,
"selected": true,
"text": "DataFrames"
},
{
"answer_id": 74355239,
"author": "giantmoa",
"author_id": 20258205,
"author_profile": "https://Stackoverflow.com/users/20258205",
"pm_score": 2,
"selected": false,
"text": "InMemoryDatasets"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74350517",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/228674/"
] |
74,350,530 | <p>I have a dictionary of lists, whose values are connections to other keys in that same dictionary. I need a summarized list of the connections between all of the keys regardless of how many levels the keys are away from each other.</p>
<p>I can make this work with a bunch of for loops that keep searching back through the same dictionary, but I can't get this to work as a recursive function that combines all of the lists.</p>
<p>input:</p>
<pre><code> sampleDict = {'1': ['2', '3'],
'2': ['1', '4'] ,
'3': ['1'],
'4': ['2'],
'5': ['6'],
'6': ['5', '7'],
'7': ['6', '8', '9'],
'8': ['7', '10'],
'9': ['7', '11'],
'10': ['8'],
'11': ['9'],
'12': [],
'13': ['14'],
'14': ['13']
}
</code></pre>
<p>Expected output:</p>
<pre><code>outputDict = {1: ['1', '2', '3', '4'],
2: ['5', '6', '7', '8', '9', '10', '11'],
3: ['12'],
4: ['13', '14']
}
</code></pre>
<p>Things I have tried:</p>
<p>If I run this code block enough times, I get the answer I want and then de-duplicate the dictionary. But I would prefer something more dynamic that adjusts to different situations and the number of connections between keys.</p>
<pre><code>for i in sampleDict.keys():
linked = sampleDict[i]
for j in linked:
sampleDict[i] = list(set(sampleDict[i] + sampleDict[j]))
</code></pre>
<p>If I stick that code above in a recursive function, it runs forever because I cannot find a dynamic exit condition that applies once every connection has been made.</p>
<pre><code>def clusters(dictionary):
for i in dictionary.keys():
linked = dictionary[i]
for j in linked:
dictionary[i] = list(set(dictionary[i] + dictionary[j]))
return clusters(dictionary)
</code></pre>
| [
{
"answer_id": 74350787,
"author": "Ben Grossmann",
"author_id": 2476977,
"author_profile": "https://Stackoverflow.com/users/2476977",
"pm_score": 2,
"selected": true,
"text": "def dfs(v,component,unseen,adj):\n for w in adj[v]:\n if w in unseen:\n component.append(w)\n unseen.remove(w)\n dfs(w,component,unseen,adj)\n\nunseen = set(sampleDict)\ncomponents = []\nwhile unseen:\n v = unseen.pop()\n components.append([v])\n dfs(v,components[-1],unseen,sampleDict)\n\ncomponents.sort()\noutputDict = dict(enumerate(components))\n"
},
{
"answer_id": 74350876,
"author": "Andrej Kesely",
"author_id": 10035985,
"author_profile": "https://Stackoverflow.com/users/10035985",
"pm_score": 0,
"selected": false,
"text": "sampleDict = {\n \"1\": [\"2\", \"3\"],\n \"2\": [\"1\", \"4\"],\n \"3\": [\"1\"],\n \"4\": [\"2\"],\n \"5\": [\"6\"],\n \"6\": [\"5\", \"7\"],\n \"7\": [\"6\", \"8\", \"9\"],\n \"8\": [\"7\", \"10\"],\n \"9\": [\"7\", \"11\"],\n \"10\": [\"8\"],\n \"11\": [\"9\"],\n \"12\": [],\n \"13\": [\"14\"],\n \"14\": [\"13\"],\n}\n\ntmp = {}\nfor k, v in sampleDict.items():\n tmp.setdefault(k, set())\n tmp[k].add(k)\n for vv in v:\n tmp.setdefault(vv, tmp[k])\n tmp[k].add(vv)\n\nprint(dict(enumerate({id(v): v for v in tmp.values()}.values(), 1)))\n"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74350530",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8161361/"
] |
74,350,552 | <p>I followed all the docs recomendation and still not working</p>
<pre><code>const express = require('express')
const app = express()
const test = require('./middleware/test')
app.use(express.json())
app.use(test)
app.get('/home', (req,res) => {
console.log('home')
res.send("home")
})
</code></pre>
<p>THE MIDDLEWAER FUNCTION IS IN THE MIDDLEWARE FOLDER</p>
<pre><code>const test = ( err, req, res, next) => {
console.log("error mddleware is working")
next()
}
</code></pre>
| [
{
"answer_id": 74352160,
"author": "BISHAL GOON",
"author_id": 20345598,
"author_profile": "https://Stackoverflow.com/users/20345598",
"pm_score": -1,
"selected": false,
"text": "const express = require(\"express\")\nconst app = express()\nconst errorHandler = require(\"./middleware/errorHandler\")\n\napp.use(express.json())\n\napp.get(\"/home\", (req, res) => {\n console.log(\"home\")\n throw new Error(\"error\")\n res.send(\"home\")\n})\n\napp.use(errorHandler)\napp.listen(3000, () => console.log(\"server running on port 3000\"))\n"
},
{
"answer_id": 74357480,
"author": "Sou",
"author_id": 8799005,
"author_profile": "https://Stackoverflow.com/users/8799005",
"pm_score": 0,
"selected": false,
"text": "module.exports = errorHandler"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74350552",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16616472/"
] |
74,350,575 | <p>I created a html login box and designed it, the problem is the login box is stuck on the left side of the screen. I've tried to shift it to the right but my methods have failed. Wondering if there's a simple solution to the issue or if maybe I added too many elements that are affecting it?</p>
<p>Example:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code> .loginbox {
width: 320px;
background: #000;
color: #fff;
padding: 5px;
}
h2 {
margin: 0;
padding: 0 0 20px;
text-align: center;
font-size: 22px;
}
.avatar {
width: 5px;
height: 5px;
border-radius: 50%;
top: -50%;
left: calc(50% - 50px);
}
.loginbox p {
margin: 0;
padding: 0;
font-weight: bold;
}
.loginbox input {
width: 100%;
margin-bottom: 20px;
}
.loginbox input[type="text"],
input[type="password"] {
border: none;
border-bottom: 1px solid #fff;
background: transparent;
outline: none;
height: 40px;
color: #fff;
font-size: 16px;
}
.loginbox input[type="submit"] {
border: none;
outline: none;
height: 40px;
background: #fb2525;
color: #fff;
font-size: 18px;
border-radius: 20px;
}
.loginbox input[type="submit"]:hover {
cursor: pointed;
background: #ffc107;
color: #000;
}
.loginbox a {
text-decoration: none;
font-size: 12px;
line-height: 20px;
color: darkgrey;
}
.loginbox a:hover {
color: #ffc107;
}
.responsive {
width: 100%;
max-width: 400px;
height: auto;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><!-- Login Form Starts -->
<div class="loginbox">
<img src="https://cdn.houseplansservices.com/product/scne5s9p1kk12soorouhkn56dt/w800x533.jpg?v=18" alt="avatar" class="responsive">
<h2>Login Here</h2>
<form>
<p>Username</p>
<input type="text" name="Username" placeholder="Enter Username">
<p>Password</p>
<input type="password" name="Password" placeholder="Enter Password">
<input action="RoyalReaderHomePageL.php" type="submit" name="login_button" value="Login">
<a href="#">Forgot your password?</a><br>
<a href="signup.php">Not a member? Sign up Now</a>
</form>
</div>
<!-- Login Form Ends --></code></pre>
</div>
</div>
</p>
<p>I tried to shift it to the left via changing the margin and adding padding but that method failed.</p>
| [
{
"answer_id": 74350678,
"author": "John",
"author_id": 11111119,
"author_profile": "https://Stackoverflow.com/users/11111119",
"pm_score": 1,
"selected": false,
"text": "float: right;"
},
{
"answer_id": 74350689,
"author": "Maik Lowrey",
"author_id": 14807111,
"author_profile": "https://Stackoverflow.com/users/14807111",
"pm_score": 1,
"selected": false,
"text": ".wrapper {\n display: flex;\n justify-content: end;\n}\n"
},
{
"answer_id": 74350811,
"author": "Mark Schultheiss",
"author_id": 125981,
"author_profile": "https://Stackoverflow.com/users/125981",
"pm_score": 0,
"selected": false,
"text": ".loginbox {\n display: grid;\n grid-template-columns: minmax(400px, auto) / 1fr;\n width: 320px;\n background: #000;\n color: #fff;\n padding: 5px;\n}\n\nh2 {\n grid-column: 2 / 2;\n margin: 0;\n padding: 0 0 20px;\n text-align: center;\n font-size: 22px;\n}\n\nform {\n grid-column: 2 / 2;\n}\n\n.avatar {\n width: 5px;\n height: 5px;\n border-radius: 50%;\n top: -50%;\n left: calc(50% - 50px);\n}\n\n.loginbox p {\n margin: 0;\n padding: 0;\n font-weight: bold;\n}\n\n.loginbox input {\n width: 100%;\n margin-bottom: 20px;\n}\n\n.loginbox input[type=\"text\"],\ninput[type=\"password\"] {\n border: none;\n border-bottom: 1px solid #fff;\n background: transparent;\n outline: none;\n height: 40px;\n color: #fff;\n font-size: 16px;\n}\n\n.loginbox input[type=\"submit\"] {\n border: none;\n outline: none;\n height: 40px;\n background: #fb2525;\n color: #fff;\n font-size: 18px;\n border-radius: 20px;\n}\n\n.loginbox input[type=\"submit\"]:hover {\n cursor: pointed;\n background: #ffc107;\n color: #000;\n}\n\n.loginbox a {\n text-decoration: none;\n font-size: 12px;\n line-height: 20px;\n color: darkgrey;\n}\n\n.loginbox a:hover {\n color: #ffc107;\n}\n\n.responsive {\n grid: 1 / 1;\n width: 100%;\n max-width: 400px;\n height: auto;\n}"
},
{
"answer_id": 74350972,
"author": "Rocky Barua",
"author_id": 16801529,
"author_profile": "https://Stackoverflow.com/users/16801529",
"pm_score": 1,
"selected": false,
"text": "margin-left: auto;"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74350575",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16941396/"
] |
74,350,577 | <p>As the title mentioned, I have to remove adjacent duplicates in doubly linked list such that if input is 'google', the adjacent duplicates removal is google-->ggle-->le and hence output should be 'le'. I'm supposed to code it in C. I tried to perform delete operation as shown in this image-<a href="https://i.stack.imgur.com/erW7A.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/erW7A.png" alt="image" /></a>, except that I don't know how to continuously loop till all adjacent duplicates are removed (I don't know how to use recursion). I'm removing adjacent duplicates in remove_adjacent_duplicates() function, and since I don't know how to put terminating condition in loop, I've merely used while loop. I also don't know how to assign modified doubly linked list to original linked list named 'head', and so <code>head=current;</code> in while loop (line 63 of code) is a wrong assignment as it finally prints empty(?) list. Please rectify my mistakes and give correct solution. Here's my code-</p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct node {
char data;
struct node *next;
struct node *prev;
};
struct node *head, *tail = NULL; //Represent the head and tail of the doubly linked list
int len;
void addNode(char data) {
struct node *newNode = (struct node*)malloc(sizeof(struct node)); //Create new node
newNode->data = data;
if(head == NULL) { //If dll is empty
head = tail = newNode; //Both head and tail will point to newNode
head->prev = NULL; //head's previous will point to NULL
tail->next = NULL; //tail's next will point to NULL, as it is the last node of the list
}
else {
tail->next = newNode; //newNode will be added after tail such that tail's next points to newNode
newNode->prev = tail; //newNode's previous will point to tail
tail = newNode; //newNode will become new tail
tail->next = NULL; //As it is last node, tail's next will point to NULL
}
}
void remove_adjacent_duplicates() {
struct node *current, *index, *temp;
if(head == NULL) {
return;
}
else
{
current=head;
while(current != NULL)
{
if(current->data == current->next->data)
{
index = current->prev; //noting data previous to duplicate data
//printf("%c\n",index->data);
while(current->data == current->next->data && current!=NULL)
{
current=current->next; //iterating till all adjacent duplicates are found
//printf("*%c\n",current->data);
}
temp=current->next; //temp points to character next to latest adjacent duplicate
//printf("!%c\n",temp->data);
index->next=temp; //the 'next' pointer of struct node of data before duplicate points to node after all adjacent duplicates found currently
//printf("@%c\n",index->data);
temp->prev=index; //data's 'prev' pointer (right after adjacent duplicates) points to data present just before adjacent duplicates
//printf("#%c\n",temp->data);
head=current; //logical error
//printf("$%c\n",head->data);
free(current);
free(index);
free(temp);
break;
}
else
{
current=current->next;
}
}
}
}
void display() {
struct node *current = head; //head the global one
while(current != NULL) {
printf("%c<->", current->data); //Prints each node by incrementing pointer.
current = current->next;
}
printf("NULL\n");
}
int main()
{
char s[100];
int i;
printf("Enter string: ");
scanf("%s",s);
len=strlen(s);
for(i=0;i<len;i++){
addNode(s[i]);
}
printf("Doubly linked list: \n");
display();
remove_adjacent_duplicates()
printf("Doubly linked list after removing adjacent duplicates: \n");
display();
return 0;
}
</code></pre>
| [
{
"answer_id": 74351215,
"author": "AR7CORE",
"author_id": 12945333,
"author_profile": "https://Stackoverflow.com/users/12945333",
"pm_score": 0,
"selected": false,
"text": "current node = list\n\nwhile (current node != second last node)\n{\n if (current node == next node) \n {\n remove(next node) \n current node = list\n } \n} \n"
},
{
"answer_id": 74352017,
"author": "Vlad from Moscow",
"author_id": 2877241,
"author_profile": "https://Stackoverflow.com/users/2877241",
"pm_score": 1,
"selected": false,
"text": "struct node *head, *tail = NULL; //Represent the head and tail of the doubly linked list \n"
},
{
"answer_id": 74352291,
"author": "Ian Abbott",
"author_id": 5264491,
"author_profile": "https://Stackoverflow.com/users/5264491",
"pm_score": 2,
"selected": true,
"text": "void remove_adjacent_duplicates(void) { \n struct node *current = head;\n struct node *next;\n struct node *prev;\n int remove = 0;\n\n while (current != NULL)\n {\n next = current->next;\n if (next != NULL && next->data == current->data)\n {\n // Need to remove the current node and the next node.\n remove = 2;\n }\n if (remove != 0)\n {\n // Remove the current node.\n prev = current->prev;\n if (prev == NULL)\n {\n head = next;\n }\n else\n {\n prev->next = next;\n }\n if (next == NULL)\n {\n tail = prev;\n }\n else\n {\n next->prev = prev;\n }\n free(current);\n remove -= 1; // Reduce running count of adjacent nodes to be removed.\n if (remove != 0)\n {\n // Next node will also be removed.\n // Step forward to next node.\n current = next;\n }\n else if (prev == NULL)\n {\n // No current plan to also remove the next node.\n // No previous node to step back to,\n // so step forwards to the next node.\n current = next;\n }\n else\n {\n // No current plan to also remove the next node.\n // Step backwards to the previous node.\n current = prev;\n }\n }\n else\n {\n // Not removing current node. Step forwards to the next node.\n current = next;\n }\n }\n}\n"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74350577",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19611563/"
] |
74,350,583 | <p>If I have an offset abbreviation like <code>EDT</code>, then how can I find the zone it belongs to?</p>
<pre><code>irb(main):001:0> Time.find_zone("EDT")
=> nil
irb(main):002:0> ActiveSupport::TimeZone["EDT"]
=> nil
</code></pre>
<p>(These work for <code>EST</code>)</p>
<p>Looking at the <a href="https://github.com/tzinfo/tzinfo" rel="nofollow noreferrer">TZInfo documentation</a>, I found</p>
<blockquote>
<p>A list of the unique offsets used by a time zone can be obtained with the offsets_up_to method. The result is returned as an <code>Array</code> of <code>TZInfo::TimezoneOffset</code> objects</p>
</blockquote>
<p>So I tried</p>
<pre><code>irb(main):013:0> TZInfo::Timezone.all.find { |tz| tz.offsets_up_to(Time.now).map(&:abbreviation).include?("EDT") }
=> #<TZInfo::TimezoneProxy: America/Cancun>
</code></pre>
<p>which is a wrong answer for me as Cancun <em>used</em> to have daylight savings time and so use EDT but doesn't any more.</p>
<p>Please note I am not asking about a time zone which is necessarily <em>currently</em> EDT, but which has EDT this year, at least.</p>
| [
{
"answer_id": 74350796,
"author": "Alexey Romanov",
"author_id": 9204,
"author_profile": "https://Stackoverflow.com/users/9204",
"pm_score": 0,
"selected": false,
"text": "def tz_by_offset_abbr(abbr)\n year = Time.now.year\n dates = [Date.new(year, 1, 1), Date.new(year, 7, 1)]\n ActiveSupport::TimeZone.all.find do |tz|\n dates.any? { |date| date.in_time_zone(tz).zone == abbr }\n end\nend\n"
},
{
"answer_id": 74353058,
"author": "Matt Johnson-Pint",
"author_id": 634824,
"author_profile": "https://Stackoverflow.com/users/634824",
"pm_score": 3,
"selected": true,
"text": "CST"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74350583",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9204/"
] |
74,350,610 | <p>In my script setup SFC I want to dynamically call another function from the same component by it's name in string variable, right now I'm doing it that way:</p>
<pre><code>let functionName = "myFunction(param)";
eval(functionName);
</code></pre>
<p>I read on MDN docs that using eval is dangerous, I tried to use return Function but it gives me "Uncaught ReferenceError: myFunction is not defined" or "TypeError: [...] is not a function"</p>
<p>is there a better way or do I have to use eval?</p>
| [
{
"answer_id": 74350796,
"author": "Alexey Romanov",
"author_id": 9204,
"author_profile": "https://Stackoverflow.com/users/9204",
"pm_score": 0,
"selected": false,
"text": "def tz_by_offset_abbr(abbr)\n year = Time.now.year\n dates = [Date.new(year, 1, 1), Date.new(year, 7, 1)]\n ActiveSupport::TimeZone.all.find do |tz|\n dates.any? { |date| date.in_time_zone(tz).zone == abbr }\n end\nend\n"
},
{
"answer_id": 74353058,
"author": "Matt Johnson-Pint",
"author_id": 634824,
"author_profile": "https://Stackoverflow.com/users/634824",
"pm_score": 3,
"selected": true,
"text": "CST"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74350610",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9436295/"
] |
74,350,616 | <p>I'm aware that Python has a very nice function sorted() for this but I'd like to implement my own function to understand the logic.
<strong>I have a list of strings and I'd like to sort them first by length, then alphabetically.</strong>
For example,</p>
<h4>Input:</h4>
<pre><code>['daring','adequate','bold','bait','cold','beautiful']
</code></pre>
<h4>Output:</h4>
<pre><code>['bait','bold','cold','daring','adequate','beautiful']
</code></pre>
<p>How do I build a function that does this?</p>
<p>I started with building a simple quicksort function for sorting only alphabetically, but now I can't think of a efficient way of progressing from it to include 2 keys at once.
Here is the code: (assumes strings are all in one case)</p>
<pre><code>def quick_sort(sequence):
length = len(sequence)
if length <=1:
return sequence
else:
pivot = sequence.pop()
items_greater = []
items_lower = []
for item in sequence:
if item >pivot:
items_greater.append(item)
else:
items_lower.append(item)
return quick_sort(items_lower) + [pivot] + quick_sort(items_greater)
print(quick_sort(['daring','adequate','bold','bait','cold','beautiful']))
</code></pre>
<p>TLDR: How to turn this into a Length/Alphebetical sort?
Thanks</p>
| [
{
"answer_id": 74350796,
"author": "Alexey Romanov",
"author_id": 9204,
"author_profile": "https://Stackoverflow.com/users/9204",
"pm_score": 0,
"selected": false,
"text": "def tz_by_offset_abbr(abbr)\n year = Time.now.year\n dates = [Date.new(year, 1, 1), Date.new(year, 7, 1)]\n ActiveSupport::TimeZone.all.find do |tz|\n dates.any? { |date| date.in_time_zone(tz).zone == abbr }\n end\nend\n"
},
{
"answer_id": 74353058,
"author": "Matt Johnson-Pint",
"author_id": 634824,
"author_profile": "https://Stackoverflow.com/users/634824",
"pm_score": 3,
"selected": true,
"text": "CST"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74350616",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17739476/"
] |
74,350,626 | <p>When running the code with <code>await asyncio.sleep(1)</code> below:</p>
<pre class="lang-py prettyprint-override"><code>import asyncio
async def test1():
for _ in range(0, 3):
print("Test1")
await asyncio.sleep(1) # Here
async def test2():
for _ in range(0, 3):
print("Test2")
await asyncio.sleep(1) # Here
async def test3():
for _ in range(0, 3):
print("Test3")
await asyncio.sleep(1) # Here
async def call_tests():
await asyncio.gather(test1(), test2(), test3())
asyncio.run(call_tests())
</code></pre>
<p><code>test1()</code>, <code>test2()</code> and <code>test3()</code> are run alternately sleeping 1 second each time as shown below:</p>
<pre class="lang-none prettyprint-override"><code>Test1
Test2
Test3
Test1
Test2
Test3
Test1
Test2
Test3
</code></pre>
<p>Now, I want to run them alternately without sleeping but if I remove <code>await asyncio.sleep(1)</code> from them:</p>
<pre class="lang-py prettyprint-override"><code># ...
async def test1():
for _ in range(0, 3):
print("Test1")
# await asyncio.sleep(1)
async def test2():
for _ in range(0, 3):
print("Test2")
# await asyncio.sleep(1)
async def test3():
for _ in range(0, 3):
print("Test3")
# await asyncio.sleep(1)
# ...
</code></pre>
<p>They are run serially as shown below:</p>
<pre class="lang-none prettyprint-override"><code>Test1
Test1
Test1
Test2
Test2
Test2
Test3
Test3
Test3
</code></pre>
<p>So, how can I run them alternately without sleeping?</p>
| [
{
"answer_id": 74350627,
"author": "Kai - Kazuya Ito",
"author_id": 8172439,
"author_profile": "https://Stackoverflow.com/users/8172439",
"pm_score": 1,
"selected": false,
"text": "await asyncio.sleep(0)"
},
{
"answer_id": 74351527,
"author": "jsbueno",
"author_id": 108205,
"author_profile": "https://Stackoverflow.com/users/108205",
"pm_score": 2,
"selected": false,
"text": "await asyncio.sleep(0)"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74350626",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8172439/"
] |
74,350,633 | <p>In this piece of code:</p>
<pre><code>void func(size_t dim, double **ptr){
(*ptr) = malloc(dim * sizeof **ptr);
/* Perform Calculations...*/
}
</code></pre>
<p>What is the difference between using <code>sizeof **ptr</code> and <code>sizeof *ptr</code>? This is confusing me. It seems to have no difference when I'm dealing with <code>int*</code> and <code>double*</code> types, but when I'm dealing with <code>chars*</code>, using <code>sizeof **ptr</code> results in a segmentation fault. Could you help me with that?</p>
<p>Thanks in advance!</p>
| [
{
"answer_id": 74350840,
"author": "AR7CORE",
"author_id": 12945333,
"author_profile": "https://Stackoverflow.com/users/12945333",
"pm_score": 0,
"selected": false,
"text": "int * pointer = malloc(sizeof(* pointer));\n"
},
{
"answer_id": 74350863,
"author": "Vlad from Moscow",
"author_id": 2877241,
"author_profile": "https://Stackoverflow.com/users/2877241",
"pm_score": 0,
"selected": false,
"text": "ptr"
},
{
"answer_id": 74351158,
"author": "Eric Postpischil",
"author_id": 298225,
"author_profile": "https://Stackoverflow.com/users/298225",
"pm_score": 2,
"selected": true,
"text": "sizeof **ptr"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74350633",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14523469/"
] |
74,350,634 | <p>I have a file (file.txt) that looks like this with 6 columns:</p>
<pre><code>CHROM ID REF ALT ALT_FREQS OBS_CT
1 rs376342519:10616:CC:C CC C 0.995708 3862
1 1:54712:T:TTTTC T TTTTC 0.595903 3862
1 rs368808541:603010:C:A C A 0.00194132 3862
1 1:625248:CA:C CA C 0.00326171 3862
1 1:746828:AGG:A AGGATTGCTGAC A 0.00364759 3862
1 1:774926:GAC:G GAC G 0.000900845 3862
1 1:775682:G:A G A 0.00183606 3862
1 rs149821290:781367:A:C A C 0.00493168 3862
1 rs139691522:800053:A:G A G 0.69276305 3862
</code></pre>
<p>If the 5th column is above 0.5 above I need to do 1 - (the value in column 5). E.g.
Output would look like this with the new value in a new column called new_MAF. If the value is 0.5 or less it can just be printed as it is.</p>
<pre><code>CHROM ID REF ALT ALT_FREQS OBS_CT new_MAF
1 rs376342519:10616:CC:C CC C 0.995708 3862 0.004292
1 1:54712:T:TTTTC T TTTTC 0.595903 3862 0.404097
1 rs368808541:603010:C:A C A 0.00194132 3862 0.00194132
1 1:625248:CA:C CA C 0.00326171 3862 0.00326171
1 1:746828:AGG:A AGGATTGCTGAC A 0.00364759 3862 0.00364759
1 1:774926:GAC:G GAC G 0.000900845 3862 0.000900845
1 1:775682:G:A G A 0.00183606 3862 0.00183606
1 rs149821290:781367:A:C A C 0.00493168 3862 0.00493168
1 rs139691522:800053:A:G A G 0.69276305 3862 0.30723695
</code></pre>
<p>I have used the following awk script below:</p>
<pre><code>awk '{
if ($5 > 0.5)
print 1 - $5
else
print $5
}' file.txt > newfile.txt
</code></pre>
<p>It provides the right output</p>
<pre><code>0.004292
0.404097
0.00194132
0.00326171
0.00364759
0.000900845
0.00183606
0.00493168
0.30723695
</code></pre>
<p>But I need it in the same <code>file1</code> in a new column called <code>new_MAF</code> at the end.</p>
| [
{
"answer_id": 74350840,
"author": "AR7CORE",
"author_id": 12945333,
"author_profile": "https://Stackoverflow.com/users/12945333",
"pm_score": 0,
"selected": false,
"text": "int * pointer = malloc(sizeof(* pointer));\n"
},
{
"answer_id": 74350863,
"author": "Vlad from Moscow",
"author_id": 2877241,
"author_profile": "https://Stackoverflow.com/users/2877241",
"pm_score": 0,
"selected": false,
"text": "ptr"
},
{
"answer_id": 74351158,
"author": "Eric Postpischil",
"author_id": 298225,
"author_profile": "https://Stackoverflow.com/users/298225",
"pm_score": 2,
"selected": true,
"text": "sizeof **ptr"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74350634",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14614150/"
] |
74,350,637 | <p>I am trying to redo the following (simplified) python example in Haskell</p>
<pre class="lang-py prettyprint-override"><code>zerosList = [0,0,0,0,0,0,0,0,0,0]
for number in range(1,10):
if (number & 1) == 0:
for index in range(number,9,2):
zerosList[index] = zerosList[index]+1
</code></pre>
<p>where we change some values in the list from <code>[0,0,0,0,0,0,0,0,0,0]</code> to <code>[0,0,1,0,2,0,3,0,4,0]</code>.</p>
<p>I suppose I have to use some <code>filter</code>s to capture even numbers and then probably use a <code>map</code> or a <code>foldl</code> somewhere... but can't figure out how to assemble the whole thing. Something like that?</p>
<pre class="lang-hs prettyprint-override"><code>zeros = take 10 $ cycle [0]
numbers = [1..10]
foldl (+) zeros $ filter even numbers
</code></pre>
<p>or that?</p>
<pre class="lang-hs prettyprint-override"><code>zeros = take 10 $ cycle [0]
numbers = [1..10]
map (+ $ filter even numbers) zeros
</code></pre>
<p>Well, none of that works so I am clearly on the wrong path. Maybe I should write a replaceAt function?</p>
| [
{
"answer_id": 74351339,
"author": "Chris",
"author_id": 15261315,
"author_profile": "https://Stackoverflow.com/users/15261315",
"pm_score": 1,
"selected": false,
"text": "replace :: Int -> [Int] -> [Int]\nreplace _ [] = []\nreplace i [x] = [i]\nreplace i (x:y:xs) = i : y : replace (i+1) xs\n"
},
{
"answer_id": 74351383,
"author": "amalloy",
"author_id": 625403,
"author_profile": "https://Stackoverflow.com/users/625403",
"pm_score": 3,
"selected": true,
"text": "[0..4]"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74350637",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15005121/"
] |
74,350,663 | <p>I am quite new to Android, and I don't know how to inherit from the class 'HereMapClass', in my case, into an activity 'HereMap' that extends AppCompatActivity?</p>
<p>I think there is code in double, the goal is to have the main class that inherit all the functions of the HereMapClass. I would like to get the class HereMapClass to manage the download of map etc... and the main class just to manage the map visually on the phone in a fragment. I did it that way because I need to use the class separate as I use it in multiple place in the code but without needing to display the map visually.</p>
<p>Here is the code of the Main class :</p>
<p><strong>HereMap Class activity:</strong></p>
<pre><code>import androidx.appcompat.app.AppCompatActivity;
public class HereMap extends AppCompatActivity {
private MapView view;
private AndroidXMapFragment mapFragment = null;
private MapRoute m_mapRoute;
JSONArray jsonPoints;
JSONArray jsArray;
ArrayList<String> poiArr;
String gpsFolder;
String poiFolder;
String loopName = "";
String loopLang = "";
String loopEvent = "";
Context mContext;
Intent intent;
Bundle bundle2;
private final static String TAG = HereMap.class.getSimpleName();
private MapView mapView;
private Map map;
private static Image m_marker_image;
//MapScreenMarker m_tap_marker;
MapMarker m_tap_marker2;
private ArrayList<MapPackage> currentInstalledMaps;
private String currentInstalledMapsString;
private ProgressBar downloadProgressBar;
private PositioningManager positioningManager = null;
private PositioningManager.OnPositionChangedListener positionListener;
private GeoCoordinate currentPosition;
// listener for MapLoader
private MapLoader.Listener mapLoaderHandler = new MapLoader.Listener() {
@Override
public void onProgress(int progress) {
Log.i(TAG, "Progress " + progress + "%");
downloadProgressBar.setProgress(progress);
}
@Override
public void onInstallationSize(long diskSize, long networkSize) {
Log.i(TAG, "Map data require " + diskSize);
}
@Override
public void onGetMapPackagesComplete(MapPackage rootMapPackage,
MapLoader.ResultCode resultCode) {
if (resultCode == MapLoader.ResultCode.OPERATION_SUCCESSFUL) {
Log.i(TAG, "Map packages received successful: " + rootMapPackage.getTitle());
currentInstalledMaps = new ArrayList<>(1);
populateInstalledMaps(rootMapPackage);
} else {
Log.e(TAG, "Can't retrieve map packages: " + resultCode.name());
Toast.makeText(HereMap.this,
"Error: " + resultCode.name(), Toast.LENGTH_SHORT).show();
return;
}
StringBuilder sb = new StringBuilder();
for (MapPackage pac : currentInstalledMaps) {
sb.append(pac.getTitle());
sb.append("\n");
}
currentInstalledMapsString = sb.toString();
}
private void populateInstalledMaps(MapPackage pac) {
// only take installed root package, so if e.g. Germany is installed,
// don't check for children states
if (pac.getInstallationState() == MapPackage.InstallationState.INSTALLED) {
Log.i(TAG, "Installed package found: " + pac.getTitle() + " id " + pac.getId());
currentInstalledMaps.add(pac);
} else if (pac.getChildren() != null && pac.getChildren().size() > 0) {
for (MapPackage p : pac.getChildren()) {
populateInstalledMaps(p);
}
}
}
...
</code></pre>
<p>Here is the class to inherit into the main one:</p>
<p><strong>HereMapClass:</strong></p>
<pre><code>public class HereMapClass {
private MapView view;
private AndroidXMapFragment mapFragment = null;
private MapRoute m_mapRoute;
private MapEngine mapEngine;
private MapLoader mapLoader;
JSONArray jsonPoints;
JSONArray jsArray;
ArrayList<String> poiArr;
String gpsFolder;
String poiFolder;
String loopName = "";
String loopLang = "";
String loopEvent = "";
Context mContext;
Intent intent;
Bundle bundle2;
private final static String TAG = HereMap.class.getSimpleName();
private MapView mapView;
private Map map;
private static Image m_marker_image;
//MapScreenMarker m_tap_marker;
MapMarker m_tap_marker2;
private ArrayList<MapPackage> currentInstalledMaps;
private String currentInstalledMapsString;
private ProgressBar downloadProgressBar;
private PositioningManager positioningManager = null;
private PositioningManager.OnPositionChangedListener positionListener;
private GeoCoordinate currentPosition;
private Context context;
public HereMapClass(Context context){
this.context=context;
}
// listener for MapLoader
private MapLoader.Listener mapLoaderHandler = new MapLoader.Listener() {
@Override
public void onProgress(int progress) {
Log.i(TAG, "Progress " + progress + "%");
downloadProgressBar.setProgress(progress);
}
@Override
public void onInstallationSize(long diskSize, long networkSize) {
Log.i(TAG, "Map data require " + diskSize);
}
@Override
public void onGetMapPackagesComplete(MapPackage rootMapPackage,
MapLoader.ResultCode resultCode) {
if (resultCode == MapLoader.ResultCode.OPERATION_SUCCESSFUL) {
Log.i(TAG, "Map packages received successful: " + rootMapPackage.getTitle());
currentInstalledMaps = new ArrayList<>(1);
populateInstalledMaps(rootMapPackage);
} else {
Log.e(TAG, "Can't retrieve map packages: " + resultCode.name());
Toast.makeText(context,
"Error: " + resultCode.name(), Toast.LENGTH_SHORT).show();
return;
}
StringBuilder sb = new StringBuilder();
for (MapPackage pac : currentInstalledMaps) {
sb.append(pac.getTitle());
sb.append("\n");
}
currentInstalledMapsString = sb.toString();
}
private void populateInstalledMaps(MapPackage pac) {
// only take installed root package, so if e.g. Germany is installed,
// don't check for children states
if (pac.getInstallationState() == MapPackage.InstallationState.INSTALLED) {
Log.i(TAG, "Installed package found: " + pac.getTitle() + " id " + pac.getId());
currentInstalledMaps.add(pac);
} else if (pac.getChildren() != null && pac.getChildren().size() > 0) {
for (MapPackage p : pac.getChildren()) {
populateInstalledMaps(p);
}
}
//continuez à installer
//lancer notification pour login
}
...
</code></pre>
<p>Best regards</p>
| [
{
"answer_id": 74351339,
"author": "Chris",
"author_id": 15261315,
"author_profile": "https://Stackoverflow.com/users/15261315",
"pm_score": 1,
"selected": false,
"text": "replace :: Int -> [Int] -> [Int]\nreplace _ [] = []\nreplace i [x] = [i]\nreplace i (x:y:xs) = i : y : replace (i+1) xs\n"
},
{
"answer_id": 74351383,
"author": "amalloy",
"author_id": 625403,
"author_profile": "https://Stackoverflow.com/users/625403",
"pm_score": 3,
"selected": true,
"text": "[0..4]"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74350663",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3581620/"
] |
74,350,677 | <p>So I want to change the color of the text on <code>hover</code> <strong>or</strong> <code>focus</code></p>
<pre><code><div class="hover:text-green-500 focus:text-green-500">foo bar</div>
</code></pre>
<p>But I was wondering if is possible to compress all in one statement, so I would not need to repeat the <code>text-green-500</code> for both. I tried the code below, but it becomes an <strong>and</strong> statement instead of <strong>or</strong>.</p>
<pre><code><div class="hover:focus:text-green-500">foo bar</div>
</code></pre>
<p>In pure css, what I'm looking for to do would be something like this:</p>
<pre><code>div:hover, div:focus {
color: green
}
</code></pre>
<p>Is that possible in TailwindCSS?</p>
| [
{
"answer_id": 74351339,
"author": "Chris",
"author_id": 15261315,
"author_profile": "https://Stackoverflow.com/users/15261315",
"pm_score": 1,
"selected": false,
"text": "replace :: Int -> [Int] -> [Int]\nreplace _ [] = []\nreplace i [x] = [i]\nreplace i (x:y:xs) = i : y : replace (i+1) xs\n"
},
{
"answer_id": 74351383,
"author": "amalloy",
"author_id": 625403,
"author_profile": "https://Stackoverflow.com/users/625403",
"pm_score": 3,
"selected": true,
"text": "[0..4]"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74350677",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10342557/"
] |
74,350,679 | <p>In the following example I show some mixins that may or may not use <code>*args</code> or <code>**kwargs</code>:</p>
<pre><code>class AMixin():
def __init__(self, **kwargs):
print("AMixin")
self.a = 'a' + str(kwargs.get('a', ''))
class BMixin():
def __init__(self, **kwargs):
print("BMixin")
self.b = 'b' + str(kwargs.get('b', ''))
class ABMixin(AMixin, BMixin):
def __init__(self, **kwargs):
print("ABMixin")
super().__init__(**kwargs)
class A(AMixin):
def __init__(self, **kwargs):
super().__init__(**kwargs)
class B(BMixin):
def __init__(self, **kwargs):
super().__init__(**kwargs)
class AB(ABMixin):
def __init__(self, **kwargs):
print("AB")
super().__init__(**kwargs)
AB(a='a', b='b')
</code></pre>
<p>Here I encounter an issue because the last mixin is calling its parent which doesn't exist:</p>
<pre><code>Cell In [4], line 9, in BMixin.__init__(self, *args, **kwargs)
8 def __init__(self, *args, **kwargs):
----> 9 super().__init__(*args, **kwargs)
10 print("BMixin")
11 self.b = 'b' + str(kwargs.get('b', ''))
TypeError: object.__init__() takes exactly one argument
(the instance to initialize)
</code></pre>
<p>How should I modify this example to allow any combination of mixins, and inherit mixins in any order?</p>
<p>One possible UGLY solution is to add a dummy end mixin:</p>
<pre><code>class EndMixin:
def __init__(self, **kwargs):
...
class AMixin(EndMixin):
def __init__(self, **kwargs):
print("AMixin")
self.a = 'a' + str(kwargs.get('a', ''))
class BMixin(EndMixin):
def __init__(self, **kwargs):
print("BMixin")
self.b = 'b' + str(kwargs.get('b', ''))
</code></pre>
| [
{
"answer_id": 74351339,
"author": "Chris",
"author_id": 15261315,
"author_profile": "https://Stackoverflow.com/users/15261315",
"pm_score": 1,
"selected": false,
"text": "replace :: Int -> [Int] -> [Int]\nreplace _ [] = []\nreplace i [x] = [i]\nreplace i (x:y:xs) = i : y : replace (i+1) xs\n"
},
{
"answer_id": 74351383,
"author": "amalloy",
"author_id": 625403,
"author_profile": "https://Stackoverflow.com/users/625403",
"pm_score": 3,
"selected": true,
"text": "[0..4]"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74350679",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2612235/"
] |
74,350,680 | <p>i'm creating a simple rpg game and i need to get information from one file and store it in my variables to be able to make the user save/modify items in the game easily, i can read my files but i do not know how to get the name and the numbers inside this lables:</p>
<pre><code>itemName:("Steel Sword"),itemStats(2,0,0);
</code></pre>
<p>i need to get "Steel Sword" in a String and the numbers to the other variables...</p>
<p>maybe you could tell me also how to connect the name to the stats, i don't have really a good way to do it.</p>
<p>i tried to use indexOf to get the start and end of the string but i need to figure out the separators on the stats and maybe there's a more reliable way to do this...</p>
| [
{
"answer_id": 74351087,
"author": "hopperelec",
"author_id": 17168710,
"author_profile": "https://Stackoverflow.com/users/17168710",
"pm_score": -1,
"selected": false,
"text": "{\"itemName\": \"Steel Sword\", \"itemStats\": [2,0,0]}\n"
},
{
"answer_id": 74354384,
"author": "DevilsHnd",
"author_id": 4725875,
"author_profile": "https://Stackoverflow.com/users/4725875",
"pm_score": 2,
"selected": true,
"text": "List<Item>"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74350680",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20442581/"
] |
74,350,720 | <p>Often i have a method where i want to return the error if something goes wrong, and instead of returning null, I want something less prone to errors at runtime and more easy to consume. Is there anything already done in .Net or maybe a nuget package?
Maybe have a constructor with optional parameters or object initializer would be enough?</p>
<p>This would have been the first approach but then every new Dto has to either have these Error property or inherit from a base class.</p>
<pre><code> if (condition)
{
return new MyDto(null, error);
}
return new MyDto(someVariable, null);
</code></pre>
<p>So I've made this class to use a return type:</p>
<pre><code>public class Optional<TObject> where TObject : class
{
public Optional(TObject? value)
{
Value = value;
}
public Optional(String error)
{
Error = error;
}
public TObject? Value { get; }
public String Error { get;} = String.Empty;
public Boolean IsError => !String.IsNullOrEmpty(Error);
}
</code></pre>
<p>I return it in the method:</p>
<pre><code> if (condition)
{
return new Optional(error);
}
return new Optional(new MyDto(someVariable));
</code></pre>
<p>And then consume it like this:</p>
<pre><code>var result = await myService.GetSomethingAsync();
if(result.IsError)
{
await DisplayAlert("error", result.Error, "Ok");
}
else
{
await DoSomethingElse(result.Value);
}
</code></pre>
| [
{
"answer_id": 74351171,
"author": "Olivier Jacot-Descombes",
"author_id": 880990,
"author_profile": "https://Stackoverflow.com/users/880990",
"pm_score": 1,
"selected": false,
"text": "Value"
},
{
"answer_id": 74351242,
"author": "José Ramírez",
"author_id": 13886104,
"author_profile": "https://Stackoverflow.com/users/13886104",
"pm_score": 0,
"selected": false,
"text": "public class SvcResult\n{\n public List<Error> Errors { get; } // Error is a class of my own. Add set; if deserialization is needed.\n public bool Success { get; } // Add set; if deserialization is needed.\n\n // Then parameterless constructor for a successful result.\n // Then parameterized constructor to receive errors for a failed result.\n}\n"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74350720",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14892820/"
] |
74,350,730 | <p>I am trying to overwrite an object given specific changes to that object. The problem is that there are other nested objects that get overwritten as well. How would I prevent this?</p>
<pre><code> const deviceChanges = {
"a": 5,
"card": {
"back": [
{
"key": "iphoneText",
"label": "IPHONE",
"value": "UPDATED VALUE FOR IPHONE"
},
]
}
};
let newBody = {
"a": 3,
"card": {
"back": [
{
"key": "androidText",
"label": "ANDROID",
"value": "androidOS"
},
{
"key": "samsungText",
"label": "SAMSUNG",
"value": "samsungOS"
},
{
"key": "iphoneText",
"label": "IPHONE",
"value": "iphone"
},
{
"key": "macbookText",
"label": "MACBOOK",
"value": "macbookOS"
}
]
},
"c": 8
};
const expected = {
"object": {
"a": 5,
"card": {
"back": [
{
"key": "androidText",
"label": "ANDROID",
"value": "androidOS"
},
{
"key": "samsungText",
"label": "SAMSUNG",
"value": "samsungOS"
},
{
"key": "iphoneText",
"label": "IPHONE",
"value": "UPDATED VALUE FOR IPHONE"
},
{
"key": "macbookText",
"label": "MACBOOK",
"value": "macbookOS"
}
]
},
"c": 8
}
};
</code></pre>
<p>Here is a Unit Test example of what I am trying to do. I want to take the changes object, and basically replace b.x in newBody, but I also want to preserve the other fields like b.y, a, and C. I want to make it as dynamic as possible, so if there is another object for newBody.b.x or another value for A, I want the code to be able to notice that and adequately change that. Does anyone have an idea on what to do here?</p>
<pre><code>for (let [key, value] of Object.entries(changes)) {
for(let [key1, value1] of Object.entries(value)) {
newBody[key][key1] = value1;
}
}
</code></pre>
<p>This is what I have so far in terms of Code. But it only takes into account the fact that it only needs to traverse through two objects to replace. If I had something like:</p>
<pre><code>const changes = {
"b": {
"x": "new",
"y": {
"n": "iphone"
}
}
};
</code></pre>
<p>The code would not work. How do I make it as dynamic as possible to realize how many objects it needs to replace?</p>
| [
{
"answer_id": 74351155,
"author": "danh",
"author_id": 294949,
"author_profile": "https://Stackoverflow.com/users/294949",
"pm_score": 2,
"selected": true,
"text": "const changes = {\n \"b\": {\n \"x\": \"changed\",\n \"Z\": \"new key/value pair\"\n }\n};\n\nlet newBody = {\n \"a\": 3,\n \"b\": {\n \"x\": \"old\",\n \"y\": \"fields\"\n },\n \"c\": 8\n};\n\n// overwrite values in target with matching keys in source \n// side-effects target, also returns it\nfunction merge(target, source) {\n for (const [key, value] of Object.entries(source)) {\n if (key in target) {\n if (typeof value === 'object' && typeof target[key] === 'object') {\n merge(target[key], value);\n } else {\n target[key] = value;\n }\n } else {\n // the key in source isn't in the target. add it\n target[key] = value;\n }\n }\n return target;\n}\n\nconst r = merge(newBody, changes)\nconsole.log(r)"
},
{
"answer_id": 74353174,
"author": "Lord-JulianXLII",
"author_id": 19529102,
"author_profile": "https://Stackoverflow.com/users/19529102",
"pm_score": 0,
"selected": false,
"text": "{x: \"new\"}"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74350730",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20442697/"
] |
74,350,748 | <p>I have a dataset like below -</p>
<p><code>List((X,Set(" 1", " 7")), (Z,Set(" 5")), (D,Set(" 2")), (E,Set(" 8")), ("F ",Set(" 5", " 9", " 108")), (G,Set(" 2", " 11")), (A,Set(" 7", " 5")), (M,Set(108)))</code></p>
<p>Here X is related to A as 7 is common between them</p>
<p>Z is related to A as 5 is common between them</p>
<p>F is related to A as 5 is common between them</p>
<p>M is related to F as 108 is common between them</p>
<p>So, X, Z, A, F and M are related</p>
<p>D and G are related as 2 is common between them</p>
<p>E is not related to anybody</p>
<p>So, the output would be ((X, Z, A, F, M), (D,G), (E))</p>
<p>Order doesn't matter here.</p>
<p>I have used Scala here, but solution in Scala/Python or a pseudocode would work for me.</p>
| [
{
"answer_id": 74350894,
"author": "ravenspoint",
"author_id": 16582,
"author_profile": "https://Stackoverflow.com/users/16582",
"pm_score": -1,
"selected": false,
"text": "X 1\nX 7\nZ 5\n...\n"
},
{
"answer_id": 74352762,
"author": "Andrey Tyukin",
"author_id": 2707792,
"author_profile": "https://Stackoverflow.com/users/2707792",
"pm_score": 2,
"selected": true,
"text": "(A, { 1, 2 })"
},
{
"answer_id": 74353305,
"author": "Philluminati",
"author_id": 25466,
"author_profile": "https://Stackoverflow.com/users/25466",
"pm_score": -1,
"selected": false,
"text": "val initialData :List[(String, Set[String])] = List(\n (\"X\",Set(\" 1\", \" 7\")),\n (\"Z\",Set(\" 5\")),\n (\"D\",Set(\" 2\")),\n (\"E\",Set(\" 8\")),\n (\"F \",Set(\" 5\", \" 9\", \" 108\")),\n (\"G\",Set(\" 2\", \" 11\")),\n (\"A\",Set(\" 7\", \" 5\")),\n (\"M\",Set(\"108\"))\n)\n"
},
{
"answer_id": 74371436,
"author": "soumya-kole",
"author_id": 2122502,
"author_profile": "https://Stackoverflow.com/users/2122502",
"pm_score": 0,
"selected": false,
"text": "data=[\n[\"X\",{\"1\", \"7\"}],\n[\"Z\",{\"5\",}],\n[\"D\",{\"2\",}],\n[\"E\",{\"8\",}],\n[\"F\",{\"5\", \"9\", \"108\"}],\n[\"G\",{\"2\", \"11\"}],\n[\"A\",{\"7\", \"5\"}],\n[\"M\",{\"108\"}]\n]\n\nfor i in range(len(data)):\n for j in range(len(data)):\n if(data[i][1].intersection(data[j][1])):\n if(data[i][0]!=data[j][0] ):\n data[i][1] = data[j][1] = (data[i][1]).union(data[j][1])\nfor k, g in groupby(sorted([[sorted(tuple(d[1])),d[0]] for d in data]), key=lambda x: x[0]):\n print(list(l[1] for l in g))\n"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74350748",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2122502/"
] |
74,350,788 | <p>I want to change the property <code>amount</code> in a state object using buttons (increment and decrement). I checked using <code>console.log</code> and the property's value is changing when the buttons are clicked, but the displayed number is not changing. why is that? what am I doing wrong?</p>
<p>here's my code: (<a href="https://codesandbox.io/s/little-hill-yvbcn7?file=/src/App.js:0-864" rel="nofollow noreferrer">codesandbox</a>)</p>
<pre><code>import React, { useState, useEffect } from "react";
import { Button } from "react-bootstrap";
export default function App() {
const [data, setData] = useState({});
useEffect(() => {
const temp = {
id: 1,
name: "apple",
amount: 10
};
setData(temp);
}, []);
const handleInc = () => {
let temp = data;
temp.amount++;
console.log("increment", temp.amount);
setData(temp);
};
const handleDec = () => {
let temp = data;
temp.amount--;
console.log("decrement", temp.amount);
setData(temp);
};
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<label>name: {data.name}</label>
<br />
<label>amount: {data.amount}</label>
<br />
<Button onClick={handleDec}>Reduce</Button>
<Button onClick={handleInc}>Increase</Button>
</div>
);
}
</code></pre>
| [
{
"answer_id": 74350954,
"author": "Nice Books",
"author_id": 994006,
"author_profile": "https://Stackoverflow.com/users/994006",
"pm_score": 1,
"selected": false,
"text": "let temp = data;\ntemp.amount++;\nsetData(temp);\n"
},
{
"answer_id": 74350956,
"author": "Nikita Chayka",
"author_id": 7064030,
"author_profile": "https://Stackoverflow.com/users/7064030",
"pm_score": 1,
"selected": false,
"text": "let temp = data"
},
{
"answer_id": 74351455,
"author": "Anh Le Hoang",
"author_id": 16315750,
"author_profile": "https://Stackoverflow.com/users/16315750",
"pm_score": 0,
"selected": false,
"text": "Callback"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74350788",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1235167/"
] |
74,350,813 | <p>Current issue: Taking input to select a dictionary key, and add in a <code>quantity</code> key:value pair to that nested dictionary.</p>
<p>This is my attempt</p>
<pre class="lang-py prettyprint-override"><code>menu = {
1: {"item": "Green Beret Omelette", "price": "$12.99"},
2: {"item": "Get to the Chopped Salad", "price": "$14.99"},
3: {"item": "Pump You Up Protein Shake", "price": "$9.99"},
4: {"item": "I'll Be Baby Back Ribs", "price": "$22.99"},
5: {"item": "Let Off Some Steamed Vegetables", "price": "$4.99"},
6: {"item": "The Ice Cream Cometh", "price": "$15.99"}
}
selection = int(input("Please select your item:\n"))
if int(selection) < 1 or int(selection) > 6:
print("Invalid selection. Please try again. \n")
count = int(input("Enter quantity: \n"))
# This is the line I'd like help with
menu[selection].update["quantity": count]
</code></pre>
<p>How do I structure the line <code>menu[selection].update["quantity": count]</code> so that menu would be updated to:</p>
<pre class="lang-py prettyprint-override"><code>menu = {
1: {"item": "Green Beret Omelette", "price": "$12.99", "quantity": 2}, # Note the new k:v here
2: {"item": "Get to the Chopped Salad", "price": "$14.99"},
3: {"item": "Pump You Up Protein Shake", "price": "$9.99"},
4: {"item": "I'll Be Baby Back Ribs", "price": "$22.99"},
5: {"item": "Let Off Some Steamed Vegetables", "price": "$4.99"},
6: {"item": "The Ice Cream Cometh", "price": "$15.99"}
}
</code></pre>
| [
{
"answer_id": 74350954,
"author": "Nice Books",
"author_id": 994006,
"author_profile": "https://Stackoverflow.com/users/994006",
"pm_score": 1,
"selected": false,
"text": "let temp = data;\ntemp.amount++;\nsetData(temp);\n"
},
{
"answer_id": 74350956,
"author": "Nikita Chayka",
"author_id": 7064030,
"author_profile": "https://Stackoverflow.com/users/7064030",
"pm_score": 1,
"selected": false,
"text": "let temp = data"
},
{
"answer_id": 74351455,
"author": "Anh Le Hoang",
"author_id": 16315750,
"author_profile": "https://Stackoverflow.com/users/16315750",
"pm_score": 0,
"selected": false,
"text": "Callback"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74350813",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11550733/"
] |
74,350,818 | <p>For the below code, specifically the <code>{}</code> that don't seem connected to anything, what is the syntax called and what is it doing?</p>
<p>And when/why can I omit the <code>()</code> when using this syntax?</p>
<pre><code>var a = new OpenApiSecurityRequirement() // Can I omit () and when/why?
{
{ // What is this doing?
new OpenApiSecurityScheme
{
Reference = new OpenApiReference
{
Type = ReferenceType.SecurityScheme,
Id="Bearer"
}
},
new string[]{}
} // What is this doing?
};
</code></pre>
| [
{
"answer_id": 74350954,
"author": "Nice Books",
"author_id": 994006,
"author_profile": "https://Stackoverflow.com/users/994006",
"pm_score": 1,
"selected": false,
"text": "let temp = data;\ntemp.amount++;\nsetData(temp);\n"
},
{
"answer_id": 74350956,
"author": "Nikita Chayka",
"author_id": 7064030,
"author_profile": "https://Stackoverflow.com/users/7064030",
"pm_score": 1,
"selected": false,
"text": "let temp = data"
},
{
"answer_id": 74351455,
"author": "Anh Le Hoang",
"author_id": 16315750,
"author_profile": "https://Stackoverflow.com/users/16315750",
"pm_score": 0,
"selected": false,
"text": "Callback"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74350818",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3700261/"
] |
74,350,829 | <p>I have a problem with updating the state of parent component with a props from child component. It seems the following code is not working, however it looks fine</p>
<pre><code>setUsersList(prevState => {
return [...prevState, data];
});
</code></pre>
<p>My parent component receives an object. Console.log(data) outputs the object received from child component. However, when console logging updated state (console.log(usersList)) it returns an empty array</p>
<p>Parent component:</p>
<pre><code>import React, { useState } from "react";
import AddUser from "./components/Users/AddUser";
import UsersList from "./components/Users/UsersList";
function App() {
const [usersList, setUsersList] = useState([]);
const addUserHandler = data => {
console.log(data);
setUsersList(prevState => {
return [...prevState, data];
});
console.log(usersList);
};
return (
<div>
<AddUser onAddUser={addUserHandler}></AddUser>
<UsersList users={usersList}></UsersList>
</div>
);
}
export default App;
</code></pre>
<p>Child component:</p>
<pre><code>import React, { useState } from "react";
import Button from "../UI/Button";
import Card from "../UI/Card";
import styles from "./AddUser.module.css";
const AddUser = props => {
const [inputData, setInputData] = useState({ name: "", age: "" });
const addUserHandler = event => {
event.preventDefault();
if (
inputData.age.trim().length === 0 ||
inputData.name.trim().length === 0
) {
return;
}
if (+inputData.age < 1) {
return;
}
props.onAddUser(inputData);
console.log(inputData.name, inputData.age);
setInputData({ name: "", age: "" });
};
const usernameChangeHandler = event => {
setInputData({ ...inputData, name: event.target.value });
};
const ageChangeHandler = event => {
setInputData({ ...inputData, age: event.target.value });
};
return (
<Card className={styles.input}>
<form onSubmit={addUserHandler}>
<label htmlFor="username">Username</label>
<input
id="username"
type="text"
onChange={usernameChangeHandler}
value={inputData.name}
></input>
<label htmlFor="age">Age (Years)</label>
<input
id="age"
type="number"
onChange={ageChangeHandler}
value={inputData.age}
></input>
<Button type="submit">Add User</Button>
</form>
</Card>
);
};
export default AddUser;
</code></pre>
| [
{
"answer_id": 74350954,
"author": "Nice Books",
"author_id": 994006,
"author_profile": "https://Stackoverflow.com/users/994006",
"pm_score": 1,
"selected": false,
"text": "let temp = data;\ntemp.amount++;\nsetData(temp);\n"
},
{
"answer_id": 74350956,
"author": "Nikita Chayka",
"author_id": 7064030,
"author_profile": "https://Stackoverflow.com/users/7064030",
"pm_score": 1,
"selected": false,
"text": "let temp = data"
},
{
"answer_id": 74351455,
"author": "Anh Le Hoang",
"author_id": 16315750,
"author_profile": "https://Stackoverflow.com/users/16315750",
"pm_score": 0,
"selected": false,
"text": "Callback"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74350829",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11395158/"
] |
74,350,835 | <p>I am trying to save an excel file generated by another application that is open. i.e the excel application is in the foreground. This file has some data and it needs to be saved i.e written into the disk.</p>
<p>In other words, I need to do an operation like File->SaveAs.</p>
<p>Steps to reproduce:</p>
<ol>
<li>Open an Excel Application. This will be shown as Book1 - Excel in the title by default</li>
<li>Write this code and run</li>
</ol>
<pre><code>import win32com.client as win32
app = win32.gencache.EnsureDispatch('Excel.Application')
app.Workbooks(1).SaveAs(r"C:\Users\test\Desktop\test.xlsx")
app.Application.Quit()
</code></pre>
<p>Error -</p>
<pre><code>Traceback (most recent call last):
File "c:/Users/test/Downloads/automate_excel.py", line 6, in <module>
ti = disp._oleobj_.GetTypeInfo()
pywintypes.com_error: (-2147418111, 'Call was rejected by callee.', None, None)
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "c:/Users/test/Downloads/automate_excel.py", line 6, in <module>
app = win32.gencache.EnsureDispatch('Excel.Application')
File "C:\Users\test\AppData\Local\Programs\Python\Python38\lib\site-packages\win32com\client\gencache.py", line 633, in EnsureDispatch
raise TypeError(
TypeError: This COM object can not automate the makepy process - please run makepy manually for this object
</code></pre>
| [
{
"answer_id": 74350954,
"author": "Nice Books",
"author_id": 994006,
"author_profile": "https://Stackoverflow.com/users/994006",
"pm_score": 1,
"selected": false,
"text": "let temp = data;\ntemp.amount++;\nsetData(temp);\n"
},
{
"answer_id": 74350956,
"author": "Nikita Chayka",
"author_id": 7064030,
"author_profile": "https://Stackoverflow.com/users/7064030",
"pm_score": 1,
"selected": false,
"text": "let temp = data"
},
{
"answer_id": 74351455,
"author": "Anh Le Hoang",
"author_id": 16315750,
"author_profile": "https://Stackoverflow.com/users/16315750",
"pm_score": 0,
"selected": false,
"text": "Callback"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74350835",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7067851/"
] |
74,350,878 | <p>I have an example of how the value of the Input element will change but the browser won't show the current value, you can check in the DevTools of the browser that the value is changed.</p>
<p>I'm wondering why it's not showing the actual value of the Input element.</p>
<pre><code>import { useState } from "react"
export default()=>{
const [input,setinput]=useState(<></>)
const AddInput=(name)=>{
setinput(<input type='text' defaultValue={name} />)
}
return <>
{input}
<button onClick={()=>{AddInput('name1')}}>Add input with Name1</button>
<button onClick={()=>{AddInput('name2')}}>Add input with Name2</button>
</>
}
</code></pre>
| [
{
"answer_id": 74350954,
"author": "Nice Books",
"author_id": 994006,
"author_profile": "https://Stackoverflow.com/users/994006",
"pm_score": 1,
"selected": false,
"text": "let temp = data;\ntemp.amount++;\nsetData(temp);\n"
},
{
"answer_id": 74350956,
"author": "Nikita Chayka",
"author_id": 7064030,
"author_profile": "https://Stackoverflow.com/users/7064030",
"pm_score": 1,
"selected": false,
"text": "let temp = data"
},
{
"answer_id": 74351455,
"author": "Anh Le Hoang",
"author_id": 16315750,
"author_profile": "https://Stackoverflow.com/users/16315750",
"pm_score": 0,
"selected": false,
"text": "Callback"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74350878",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11346798/"
] |
74,350,895 | <p>So im trying to make a if statement with a ui button in Uinty and i need to get the name of the button for the if state ment but it tells me that it is not convertabel even thou it is bouth a string or is it not?</p>
<p>I tried it like this and was expecting it to work but it didn´t</p>
<pre><code>public class UIGetClick : MonoBehaviour
{
public bool clicked = false;
public string ButtonName = EventSystem.current.currentSelectedGameObject.name;
</code></pre>
<pre><code>public void Back()
{
string ClickedButtonName = EventSystem.current.currentSelectedGameObject.name;
}
public void Freez()
{
if (ButtonName = "Back")
{
clicked = true;
}
else
{
clicked = false;
}
Debug.Log(clicked);
}
}
</code></pre>
<blockquote>
<p>Assets\UIGetClick.cs(18,13): error CS0029: Cannot implicitly convert type 'string' to 'bool'</p>
</blockquote>
<p>I also tried <code>bool.</code> and <code>string.</code> but that didn´t work either.</p>
<pre><code>public class UIGetClick : MonoBehaviour
{
public bool clicked = false;
public string ButtonName = EventSystem.current.currentSelectedGameObject.name;
</code></pre>
<pre><code>public void Back()
{
string ClickedButtonName = EventSystem.current.currentSelectedGameObject.name;
}
public void Freez()
{
if (ButtonName == "Back")
{
clicked = true;
}
else
{
clicked = false;
}
Debug.Log(clicked);
}
</code></pre>
<blockquote>
<p>NullReferenceException: Object reference not set to an instance of an object
UIGetClick..ctor () (at Assets/UIGetClick.cs:9)</p>
</blockquote>
<p>any thoughs and help?</p>
| [
{
"answer_id": 74350954,
"author": "Nice Books",
"author_id": 994006,
"author_profile": "https://Stackoverflow.com/users/994006",
"pm_score": 1,
"selected": false,
"text": "let temp = data;\ntemp.amount++;\nsetData(temp);\n"
},
{
"answer_id": 74350956,
"author": "Nikita Chayka",
"author_id": 7064030,
"author_profile": "https://Stackoverflow.com/users/7064030",
"pm_score": 1,
"selected": false,
"text": "let temp = data"
},
{
"answer_id": 74351455,
"author": "Anh Le Hoang",
"author_id": 16315750,
"author_profile": "https://Stackoverflow.com/users/16315750",
"pm_score": 0,
"selected": false,
"text": "Callback"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74350895",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20442602/"
] |
74,350,958 | <p>I already know that we can get outerHTML if the element can access direly like</p>
<pre><code> var htmlString = $('#mySelectBox').outerHTML;
</code></pre>
<p>What if the element can't access directly because it is generated from a framework like ASP Entity Framework and we do not have direct access to that element but to one of its grand parents, like</p>
<pre><code> $('#table-body:first-child').closest('select').children;
</code></pre>
<p>This <strong>children</strong> property returns an HTMLCollection and is there a way to get outerHTML of each child of that HTMLCollection.</p>
<pre><code> var optionsHTMLCollection = $('#table-body:first-child').closest('select').children;
</code></pre>
<p>I tried this, but failed.</p>
<pre><code> var optionsAsHTMLString = '';
for (var i=0; i<optionsHTMLCollection.length; I++) {
optionsAsHTMLString
}
</code></pre>
<p><strong>Update 1</strong>(Because @Twisty is asking for more HTML in the comments below. I'm pasting as it is. Later I will minimize more)</p>
<pre><code><table class="table table-dark table-hover">
<thead class="align-middle">
<tr>
<th scope="col">Seq No</th>
<th scope="col">Item Category</th>
<th scope="col">Percentage (%)</th>
<th scope="col">Item Name</th>
<th class="text-center" scope="col">Actions</th>
</tr>
</thead>
<tbody id="table-body">
<tr>
<th scope="row">1</th>
<td>
<select class="form-select"
data-val="true" data-val-required="The ItemCatId field is required."
id="PolyCombItemCatBridgeList_0__ItemCatId" name="PolyCombItemCatBridgeList[0].ItemCatId">
<option selected>-- select product finishing type --</option>
<option value="1">HIGH DENSITY POLYETHYLENE</option>
<option value="2">LINEAR LOW DENSITY POLYETHYLENE</option>
</select>
<b><span class="text-danger" for=""></span></b>
</td>
<td>
<input type="text" class="form-control" placeholder="Percentage" data-val="true"
data-val-number="The field Percentage must be a number."
data-val-range="Percentage is between 0% and 100%" data-val-range-max="100" data-val-range-min="0"
data-val-required="The Percentage field is required." id="PolyCombItemCatBridgeList_0__Percentage"
name="PolyCombItemCatBridgeList[0].Percentage" value="">
<b><span class="text-danger" for="BagType.Isactive"></span></b>
</td>
<td class="align-bottom">
<div>
<button type="button" class="btn btn-danger rounded del-this-row"><i
class="fa-regular fa-trash-can"></i> Delete</button>
</div>
</td>
</tr>
<tr>
<th scope="row">1</th>
<td>
<select class="form-select"
data-val="true" data-val-required="The ItemCatId field is required."
id="PolyCombItemCatBridgeList_1__ItemCatId" name="PolyCombItemCatBridgeList[1].ItemCatId">
<option selected>-- select product finishing type --</option>
<option value="1">HIGH DENSITY POLYETHYLENE</option>
<option value="2">LINEAR LOW DENSITY POLYETHYLENE</option>
</select>
<b><span class="text-danger" for=""></span></b>
</td>
<td>
<input type="text" class="form-control" placeholder="Percentage" data-val="true"
data-val-number="The field Percentage must be a number."
data-val-range="Percentage is between 0% and 100%" data-val-range-max="100" data-val-range-min="0"
data-val-required="The Percentage field is required." id="PolyCombItemCatBridgeList_1__Percentage"
name="PolyCombItemCatBridgeList[1].Percentage" value="">
<b><span class="text-danger" for="BagType.Isactive"></span></b>
</td>
<td class="align-bottom">
<div>
<button type="button" class="btn btn-danger rounded del-this-row"><i
class="fa-regular fa-trash-can"></i> Delete</button>
</div>
</td>
</tr>
</tbody>
<tfoot>
<tr>
<td class="border-0" colspan="4" style="text-align: right;">
Need To Add New Row?
</td>
<td class="border-0">
<div class="d-flex justify-content-end">
<button id="add-row" type="button" class="btn btn-primary rounded-circle">+</button>
</div>
</td>
</tr>
</tfoot>
</table>
</code></pre>
<p>I want to target the first select box which is in the first row and to get its all option childrens to a string variable with all the markup to concatenate into a html template mentioned below. All the Ids, name=, ... are generated by ASP MVC. That is why is looks complex.</p>
<p>HTML TEMPLATE</p>
<pre><code> `<tr>
<th scope="row">1</th>
<td>
<select class="form-select" data-val="true" data-val-required="The ItemCatId field is required." id="PolyCombItemCatBridgeList_`+ row_count +`__ItemCatId" name="PolyCombItemCatBridgeList[` + row_count + `].ItemCatId">
`
+ select_items_list +
`
</select>
<b><span class="text-danger" for=""></span></b>
</td>
<td>
<input type="text" class="form-control" placeholder="Percentage" data-val="true" data-val-number="The field Percentage must be a number." data-val-range="Percentage is between 0% and 100%" data-val-range-max="100" data-val-range-min="0" data-val-required="The Percentage field is required." id="PolyCombItemCatBridgeList_`+ row_count + `__Percentage" name="PolyCombItemCatBridgeList[` + row_count + `].Percentage" value="">
<b><span class="text-danger" for="BagType.Isactive"></span></b>
</td>
<td class="align-bottom">
<div>
<button type="button" class="btn btn-danger rounded del-this-row"><i class="fa-regular fa-trash-can"></i> Delete</button>
</div>
</td>
</tr>`
</code></pre>
<p>Here row_count, select_items_list are string variables</p>
| [
{
"answer_id": 74350954,
"author": "Nice Books",
"author_id": 994006,
"author_profile": "https://Stackoverflow.com/users/994006",
"pm_score": 1,
"selected": false,
"text": "let temp = data;\ntemp.amount++;\nsetData(temp);\n"
},
{
"answer_id": 74350956,
"author": "Nikita Chayka",
"author_id": 7064030,
"author_profile": "https://Stackoverflow.com/users/7064030",
"pm_score": 1,
"selected": false,
"text": "let temp = data"
},
{
"answer_id": 74351455,
"author": "Anh Le Hoang",
"author_id": 16315750,
"author_profile": "https://Stackoverflow.com/users/16315750",
"pm_score": 0,
"selected": false,
"text": "Callback"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74350958",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6696702/"
] |
74,350,962 | <p>In Xamarin, I frequently used <code><NavigationPage.TitleView></code> to customize the navigation title bar in my views. Now that I am working in MAUI, this tag seems to have no effect on a ShellItem view.</p>
<p>Here is <code>AppShell.xaml</code>:</p>
<pre><code><?xml version="1.0" encoding="UTF-8" ?>
<Shell
x:Class="MyApp.AppShell"
xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:localize="clr-namespace:FleetHDMobile.Resources.Strings"
xmlns:local="clr-namespace:FleetHDMobile.Views"
Shell.FlyoutBehavior="Disabled">
<ShellItem Route="MainPage">
<ShellContent
Title="MainPage"
ContentTemplate="{DataTemplate local:MainPage}"
/>
</ShellItem> . . .
</code></pre>
<p>Here is <code>MainPage.xaml</code>:</p>
<pre><code><?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:localize="clr-namespace:FleetHDMobile.Resources.Strings"
Shell.FlyoutBehavior="Flyout"
x:Class="FleetHDMobile.Views.MainPage">
<NavigationPage.TitleView>
<Label
Text="XXX"
HeightRequest="44"
WidthRequest="300" />
</NavigationPage.TitleView>
<ScrollView>
</code></pre>
<p>I have tried making MainPage a tab in the tabbar, but that didn't customize the title view either.</p>
<p>The <code><NavigationPage.TitleView></code> tag has no effect on the rendered view. I would like to put small logo icons in the title bar, but cannot figure out how to do so.</p>
| [
{
"answer_id": 74351530,
"author": "Jimmy",
"author_id": 13445783,
"author_profile": "https://Stackoverflow.com/users/13445783",
"pm_score": 0,
"selected": false,
"text": "MainPage.xaml.cs"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74350962",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1256015/"
] |
74,350,991 | <p>I've installed intellij CE with jpabuddy but jpa buddy not appears to be working in my current project.</p>
<p>This is my current pom.xml dependencies section</p>
<pre><code><dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.12.0</version>
</dependency>
<dependency>
<groupId>de.flapdoodle.embed</groupId>
<artifactId>de.flapdoodle.embed.mongo</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.jeasy</groupId>
<artifactId>easy-random-core</artifactId>
<version>4.0.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
</code></pre>
<p>This is my current IDE right panel... as you can see JPA Palette is missing.</p>
<p>I'm running IntelliJ in a Kubuntu 22.04</p>
<p><a href="https://i.stack.imgur.com/ajRI8.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ajRI8.png" alt="enter image description here" /></a></p>
<p><a href="https://i.stack.imgur.com/LUJXr.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/LUJXr.png" alt="Installed Plugin" /></a></p>
| [
{
"answer_id": 74351031,
"author": "duffymo",
"author_id": 37213,
"author_profile": "https://Stackoverflow.com/users/37213",
"pm_score": 0,
"selected": false,
"text": "Preferences->Plugins"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74350991",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5481641/"
] |
74,351,005 | <p>Update: I have already accepted the answer. However, if anyone could explain about why I got error message "keyerror:1 " in my method 2 in the question, I will be very happy with that. Thank you!</p>
<p>----------------original question ----------------</p>
<p>I 'm completing one exercise, but whatever I have tried, nothing was correct. I went through all those available answers, still I could not figure it out. The expected answer is described hereinbelow:</p>
<p>The exercise template contains a class named Car which represents the features of a car through two attributes: make (str) and top_speed (int).</p>
<p>Please write a function named fastest_car(cars: list) which takes a list of Car objects as its argument.</p>
<p>The function should return the make of the fastest car. You may assume there will always be a single car with the highest top speed. Do not change the list given as an argument, or make any changes to the Car class definition.</p>
<p>You may use the following code to test your function:</p>
<pre><code>if __name__ == "__main__":
car1 = Car("Saab", 195)
car2 = Car("Lada", 110)
car3 = Car("Ferrari", 280)
car4 = Car("Trabant", 85)
cars = [car1, car2, car3, car4]
print(fastest_car(cars))
# Ferrari
</code></pre>
<p>I have tried like this:</p>
<pre><code>
class Car:
def __init__(self,make:str,top_speed:int):
self.make=make
self.top_speed=top_speed
def fastest_car(self,list):
list.sort(key = lambda x : x.top_speed)
print("Sort by speed")
print(list)
if __name__ == "__main__":
car1 = Car("Saab", 195)
car2 = Car("Lada", 110)
car3 = Car("Ferrari", 280)
car4 = Car("Trabant", 85)
cars = [car1, car2, car3, car4]
Car.fastest_car(cars[-1])
#error message: TypeError: fastest_car() missing 1 required positional argument: 'list'
</code></pre>
<p>I also tried normal method:</p>
<pre><code>#method 2
cars=[{'Saab':195},{'Lada':110},{'Ferrari':280},{'Trabant':85}]
a=sorted(cars,key = lambda x : x[1])
print(a)#just print the sorted list
error message:
----> 3 a=sorted(cars,key = lambda x : x[1])
4 print(a)
KeyError: 1
</code></pre>
<p>If you could kindly pointed out what I did wrong, I will highly appreciated. Thank You!</p>
<p>point out mistakes and gain the knowledge</p>
| [
{
"answer_id": 74351031,
"author": "duffymo",
"author_id": 37213,
"author_profile": "https://Stackoverflow.com/users/37213",
"pm_score": 0,
"selected": false,
"text": "Preferences->Plugins"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74351005",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20442786/"
] |
74,351,008 | <p>I use MAUI.NET with MVVM architecture. Because of this I do not want to manage things through an events.</p>
<p>I want to visualize two moments:</p>
<ul>
<li>when the user hover over the button</li>
<li>when the user click on the button</li>
</ul>
<p>After these moments I want to button looks normal as nothing happened.</p>
<p>I just found a way to manage second moment (after the button is pressed).</p>
<p>What I managed to do is to set VisualState in a global ResourceDirectory for a buttons, like this:</p>
<pre><code> <Style TargetType="Button" x:Key="HideButtonStyle">
<Setter Property="VisualStateManager.VisualStateGroups">
<VisualStateGroupList>
<VisualStateGroup x:Name="CommonStates">
<VisualState x:Name="Normal">
<VisualState.Setters>
<Setter Property="BackgroundColor" Value="{StaticResource MediumDarkColor}" />
<Setter Property="Scale" Value="1" />
</VisualState.Setters>
</VisualState>
<VisualState x:Name="Pressed">
<VisualState.Setters>
<Setter Property="BackgroundColor" Value="{StaticResource HideColor}" />
<Setter Property="Scale" Value="1.07" />
</VisualState.Setters>
</VisualState>
</VisualStateGroup>
</VisualStateGroupList>
</Setter>
</Style>
</code></pre>
<p>I tried other state like "Focused".</p>
<p>And the buttons seems to be normal button:</p>
<pre><code> <Button Grid.Row="2" Style="{StaticResource HideButtonStyle}" Text="123" Command="{Binding GetSourceFilePathCommand}"/>
</code></pre>
<p>The problem is that some buttons backs to the "normal state" immediately and some not.
When the user click on something else it backs to normal, finally.</p>
<p>I have investigated if this is not due to async in Command, but is not.
It seems that the buttons that come back to normal state (proper in my opinion) are the buttons that fires the dialog.</p>
<p>I would like to that after user press the button, it got a colour etc. for a 2-3 seconds and backs automatically to normal state.</p>
<p>It would be fantastic if I could signalize that user hover over the button with let's say scaling it, and signalize when the user press the button with a colouring it for a moment.</p>
| [
{
"answer_id": 74351031,
"author": "duffymo",
"author_id": 37213,
"author_profile": "https://Stackoverflow.com/users/37213",
"pm_score": 0,
"selected": false,
"text": "Preferences->Plugins"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74351008",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12698833/"
] |
74,351,011 | <p>I have unbalanced panel data (repeated observations per ID at different points in time). I need to identify for a change in variable per person over time.</p>
<p>Here is the code to generate the data frame:</p>
<pre><code>df = pd.DataFrame(
{
"region": ["C1", "C1", "C2", "C2", "C2"],
"id": [1, 1, 2, 2, 2],
"date": ["01/01/2021", "01/02/2021", "01/01/2021", "01/02/2021", "01/03/2021"],
"job": ["A", "A", "A", "B", "B"],
}
)
df
</code></pre>
<p>I am trying to create a column ("change") that indicates when individual 2 changes job status from A to B on that date (01/02/2021).</p>
<p>I have tried the following, but it is giving me an error:</p>
<pre><code>df['change']=df.groupby(['id'])['job'].diff().fillna(0)
</code></pre>
| [
{
"answer_id": 74352517,
"author": "ali ardakani",
"author_id": 14883419,
"author_profile": "https://Stackoverflow.com/users/14883419",
"pm_score": 2,
"selected": true,
"text": "df[\"change\"] = df.groupby(\n[\"id\"])[\"job\"].transform(lambda x: x.ne(x.shift().bfill())).astype(int)\n"
},
{
"answer_id": 74354808,
"author": "Suryadipta",
"author_id": 11611258,
"author_profile": "https://Stackoverflow.com/users/11611258",
"pm_score": 0,
"selected": false,
"text": "df = pd.DataFrame(\n {\n \"region\": [\"C1\", \"C1\", \"C2\", \"C2\", \"C2\"],\n \"id\": [1, 1, 2, 2, 2],\n \"date\": [0, 1, 0, 1, 2],\n \"job\": [\"A\", \"A\", \"A\", \"B\", \"B\"],\n }\n)\n\ndf1 = df.set_index(['id', 'date']).sort_index()\ndf1['job_lag'] = df1.groupby(level='id')['job'].shift()\ndf1.job_lag.fillna(df1.job, inplace=True)\ndef change(x):\n if x['job'] != x['job_lag'] :\n return 1\n else:\n return 0\ndf1['dummy'] = df1.apply(change, axis=1)\ndf1\n"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74351011",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11611258/"
] |
74,351,014 | <p>I have a regular expression like the following: (Running on Oracle's <code>regexp_like()</code>, despite the question isn't Oracle-specific)</p>
<pre><code>abc|bcd|def|xyz
</code></pre>
<p>This basically matches a <code>tags</code> field on database to see if <code>tags</code> field contains <code>abc</code> <strong>OR</strong> <code>bcd</code> <strong>OR</strong> <code>def</code> <strong>OR</strong> <code>xyz</code> when user has input for the search query "<code>abc bcd def xyz</code>".
The <code>tags</code> field on the database holds keywords separated by spaces, e.g. "cdefg abcd xyz"</p>
<p>On Oracle, this would be something like:</p>
<pre><code>select ... from ... where
regexp_like(tags, 'abc|bcd|def|xyz');
</code></pre>
<p>It works fine as it is, but I want to add an extra option for users to search for results that match all keywords. How should I change the regular expression so that it matches <code>abc</code> <strong>AND</strong> <code>bcd</code> <strong>AND</strong> <code>def</code> <strong>AND</strong> <code>xyz</code> ?</p>
<p>Note: Because I won't know what exact keywords the user will enter, I can't pre-structure the query in the PL/SQL like this:</p>
<pre><code>select ... from ... where
tags like '%abc%' AND
tags like '%bcd%' AND
tags like '%def%' AND
tags like '%xyz%';
</code></pre>
| [
{
"answer_id": 74351790,
"author": "p3consulting",
"author_id": 4956336,
"author_profile": "https://Stackoverflow.com/users/4956336",
"pm_score": 0,
"selected": false,
"text": "with data(val) AS (\n select 'cdefg abcd xyz' from dual union all\n select 'cba lmnop xyz' from dual\n),\ntargets(s) as (\n select regexp_substr('abc bcd def xyz', '[^ ]+', 1, LEVEL) from dual\n connect by regexp_substr('abc bcd def xyz', '[^ ]+', 1, LEVEL) is not null\n)\nselect val from data d\njoin targets t on \n regexp_like(val,s)\ngroup by val having(count(*) = (select count(*) from targets))\n;\n"
},
{
"answer_id": 74351821,
"author": "MT0",
"author_id": 1509264,
"author_profile": "https://Stackoverflow.com/users/1509264",
"pm_score": 1,
"selected": false,
"text": "SELECT t.*\nFROM table_name t\n CROSS APPLY(\n WITH input (match) AS (\n SELECT 'abc bcd def xyz' FROM DUAL\n )\n SELECT 1\n FROM input\n CONNECT BY LEVEL <= REGEXP_COUNT(match, '\\S+')\n HAVING COUNT(\n REGEXP_SUBSTR(\n t.tags,\n REGEXP_SUBSTR(match, '\\S+', 1, LEVEL)\n )\n ) = REGEXP_COUNT(match, '\\S+')\n )\n"
},
{
"answer_id": 74353406,
"author": "Jason Seek Well",
"author_id": 20324967,
"author_profile": "https://Stackoverflow.com/users/20324967",
"pm_score": 0,
"selected": false,
"text": "DECLARE\n\n -- match string should be just the values to match with spaces in between\n p_match_string VARCHAR2(200) := 'abc bcd def xyz';\n -- need logic to determine match one (OR) versus match all (AND)\n p_match_type VARCHAR2(3) := 'OR';\n l_sql_statement VARCHAR2(4000);\n -- create type if bulk collect is needed\n TYPE t_email_address_tab IS TABLE OF customers.EMAIL_ADDRESS%TYPE INDEX BY PLS_INTEGER;\n l_email_address_tab t_email_address_tab;\n\nBEGIN\n\n WITH sql_clauses(row_idx,sql_text) AS\n (SELECT 0 row_idx -- build select plus beginning of where clause\n ,'SELECT email_address '\n || 'FROM customers '\n || 'WHERE 1 = '\n || DECODE(p_match_type, 'AND', '1', '0') sql_text\n FROM DUAL\n UNION\n SELECT LEVEL row_idx -- build joins for each keyword\n ,DECODE(p_match_type, 'AND', ' AND ', ' OR ') \n || 'email_address'\n || ' LIKE ''%' \n || REGEXP_SUBSTR( p_match_string,'[^ ]+',1,level) \n || '%''' sql_text\n FROM DUAL\n CONNECT BY LEVEL <= LENGTH(p_match_string) - LENGTH(REPLACE( p_match_string, ' ' )) + 1\n )\n -- put it all together by row_idx\n SELECT LISTAGG(sql_text, '') WITHIN GROUP (ORDER BY row_idx)\n INTO l_sql_statement\n FROM sql_clauses;\n\n dbms_output.put_line(l_sql_statement);\n\n -- can use execute immediate (or ref cursor) for dynamic sql\n EXECUTE IMMEDIATE l_sql_statement\n BULK COLLECT\n INTO l_email_address_tab;\n\nEND;\n"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74351014",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2526586/"
] |
74,351,063 | <p>I am building a MySQL image using <code>buildah bud -f .podman/MySQL.conf -t localhost/mysql:mushroom</code> and the following dockerfile (located at .podman/MYSQL.conf)<br></p>
<pre><code> FROM mysql:8.0
ENV MYSQL_ROOT_PASSWORD='password'
EXPOSE 3306
</code></pre>
<p>I start the container using: <br>
<code>podman run --rm -v mysql_data:/var/lib/mysql localhost/mysql:mushroom</code> <br>
<br>
After starting the container I <code>podman exe -it [ID] /bin/bash</code> into the container cli.<br>
running <code>mysql -p</code> and entering the correct password returns <code>access denied for user 'root'@'localhost' (using password: YES)</code><br><br></p>
<p>I have confirmed that the env var MYSQL_ROOT_PASSWORD is correctly set.
I have tried entering the password in the podman run command (using <code>-e MYSQL_ROOT_PASSWORD=password</code>) I have confirmed that the volume <code>mysql_data</code> doesn't exist when I start the container.</p>
<p>Any suggestions for other things to try?</p>
| [
{
"answer_id": 74365952,
"author": "Richard Huxton",
"author_id": 1029453,
"author_profile": "https://Stackoverflow.com/users/1029453",
"pm_score": 1,
"selected": false,
"text": "Dockerfile"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74351063",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4374801/"
] |
74,351,076 | <p>I would like to find an elegant way of initializing C++ array elements with their indices. I have a lot of code that looks like this:</p>
<pre><code>static constexpr size_t ELEMENT_COUNT = 8;
MyObject x[ELEMENT_COUNT] = {{0}, {1}, {2}, {3}, {4}, {5}, {6}, {7}};
</code></pre>
<p>Where <code>MyObject</code> is effectively,</p>
<pre><code>struct MyObject {
size_t mMyIndex;
MyObject(size_t myIndex) : mMyIndex(myIndex) {}
};
</code></pre>
<p>The problems should be already clear: when <code>ELEMENT_COUNT</code> changes, I have to adapt the initializer list, which feels very un-C++. And if <code>ELEMENT_COUNT</code> is, say, <code>1000</code>, this becomes impractical.</p>
<p>Is something like the following possible in C++?:</p>
<pre><code>MyObject mObjects[ELEMENT_COUNT] = initialize_array_with_indices<ELEMENT_COUNT>();
</code></pre>
<p>Does such a function like <code>initialize_array_with_indices<N>()</code> exist in the std library? Is it possible? Using <code>std::array<></code> is an option, if that gets me further.</p>
| [
{
"answer_id": 74351185,
"author": "user17732522",
"author_id": 17732522,
"author_profile": "https://Stackoverflow.com/users/17732522",
"pm_score": 4,
"selected": true,
"text": "std::iota"
},
{
"answer_id": 74357605,
"author": "tenfour",
"author_id": 402169,
"author_profile": "https://Stackoverflow.com/users/402169",
"pm_score": 0,
"selected": false,
"text": "template<typename T, std::size_t N, std::size_t... Is>\nstd::array<T, N> initialize_array_with_indices_helper(std::index_sequence<Is...>) {\n return std::array<T, N>{Is...};\n}\n\ntemplate<typename T, std::size_t N>\nconstexpr std::array<T,N> initialize_array_with_indices() {\n return initialize_array_with_indices_helper<T, N>(std::make_index_sequence<N>());\n}\n"
},
{
"answer_id": 74360822,
"author": "Jason Liam",
"author_id": 12002570,
"author_profile": "https://Stackoverflow.com/users/12002570",
"pm_score": 1,
"selected": false,
"text": "constexpr"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74351076",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/402169/"
] |
74,351,090 | <p>I've got to create a 4 meal option, of which 3 meals also have sauce options.
No loop and/or functions are allowed.</p>
<p>So I got 4 meals; 1) Steak, 2) Mussels, 3) Scampi, 4) Quinoa
The user get's asked what meals he wants, by inserting the corresponding number.
Any other number should result in a; "We do not serve this".</p>
<p>The first 3 meals, also get another user prompt of different sauces.
The output should reflect the meal + sauce.</p>
<p>I've been trying this assignment for many more hours than I dare to admit.
I'm a beginner (started in September, combining studies with full-time work) and all other assignments went pretty good so far, this one not so much...
I also tried to line up my sauces better with '\n', but this gave me a error.
Currently my code has no error, but I kinda wish it did...</p>
<p>I've gotten completely lost in the cycle of 'if' and 'elif'. I hope someone can shine some light.</p>
<pre><code>import sys
maaltijd_1 = "Biefstuk"
maaltijd_2 = "Mosselen"
maaltijd_3 = "Scampis"
maaltijd_4 = "Quinoa met wintergroenten"
#Biefstuk saus
maaltijd_1_saus_1 = "Geen saus"
maaltijd_1_saus_2 = "Béarnaise"
maaltijd_1_saus_3 = "Pepersaus"
maaltijd_1_saus_4 = "Champignonroomsaus"
#Mosselen saus
maaltijd_2_saus_1 = "Natuur"
maaltijd_2_saus_2 = "Look"
maaltijd_2_saus_3 = "Pikant"
#Scampis saus
maaltijd_3_saus_1 = "Natuur"
maaltijd_3_saus_2 = "Look"
maaltijd_3_saus_3 = "Pikant"
print("Welkom, U kan kiezen uit:\n 1)Biefstuk\n 2)Mosselen\n 3)Scampis\n 4)Quinoa met wintergroeten")
klant = int(input("Geef het nummer in van uw gewenste maaltijd: "))
#biefstuk
if (klant == maaltijd_1):
print("Prima, bij biefstuk kan U kiezen uit de volgende sausen: ", maaltijd_1_saus_1, maaltijd_1_saus_2, maaltijd_1_saus_3, maaltijd_1_saus_4)
elif (klant == 0 and klant >= 5):
print("Dit gerecht hebben hebben we niet.")
klant = int(input("Geef het nummer in van uw gewenste saus: "))
if (klant == 0 and klant >= 5):
print("Deze saus hebben hebben we niet.")
elif (klant == maaltijd_1_saus_1):
print("Uw maaltijd: Biefstuk zonder saus komt er zo aan. Smakelijk!")
sys.exit()
elif (klant == maaltijd_1_saus_2):
print("Uw maaltijd: Biefstuk met Béarnaise saus komt er zo aan. Smakelijk!")
sys.exit()
elif (klant == maaltijd_1_saus_3):
print("Uw maaltijd: Biefstuk met pepersaus komt er zo aan. Smakelijk!")
sys.exit()
elif (klant == maaltijd_1_saus_4):
print("Uw maaltijd: Biefstuk met champignonroomsaus komt er zo aan. Smalelijk!")
sys.exit()
#Mosselen
elif (klant == maaltijd_2):
print("Prima, bij mosselen kan U kiezen uit de volgende sausen: ", maaltijd_2_saus_1, maaltijd_2_saus_2, maaltijd_2_saus_3)
elif (klant == 0 and klant >= 5):
print("Dit gerecht hebben hebben we niet.")
klant = int(input("Geef het nummer in van uw gewenste saus: "))
if (klant == 0 and klant >= 5):
print("Deze saus hebben we niet.")
if (klant == maaltijd_2_saus_1):
print("Uw maaltijd: Mosselen Natuur, komt er zo aan. Smakelijk!")
elif (klant == maaltijd_2_saus_2):
print("Uw maaltijd: Mosselen Look, komt er zo aan. Smakelijk!")
elif (klant == maaltijd_2_saus_3):
print("Uw maaltijd: Mosselen Pikant, komt er zo aan. Smalelijk!")
sys.exit()
#Scampis
elif (klant == maaltijd_3):
print("Prima, bij scampis kan U kiezen uit de volgende sausen: ", maaltijd_3_saus_1, maaltijd_3_saus_2, maaltijd_3_saus_3)
elif (klant == 0 and klant >= 5):
print("Deze saus hebben hebben we niet.")
klant = int(input("Geef het nummer in van uw gewenste saus: "))
if (klant == 0 and klant >= 5):
print("Deze saus hebben we niet.")
if (klant == maaltijd_3_saus_1):
print("Uw maaltijd: Scampis Natuur, komt er zo aan. Smakelijk!")
elif (klant == maaltijd_3_saus_2):
print("Uw maaltijd: Scampis Look, komt er zo aan. Smakelijk!")
elif (klant == maaltijd_3_saus_3):
print("Uw maaltijd: Scampis Pikant, komt er zo aan. Smalelijk!")
sys.exit()
#Quinoa
elif (klant == maaltijd_4):
print("Prima, uw gerecht; Quinoa met wintergroenten, komt er zo aan. Smakelijk!")
sys.exit()
</code></pre>
| [
{
"answer_id": 74351185,
"author": "user17732522",
"author_id": 17732522,
"author_profile": "https://Stackoverflow.com/users/17732522",
"pm_score": 4,
"selected": true,
"text": "std::iota"
},
{
"answer_id": 74357605,
"author": "tenfour",
"author_id": 402169,
"author_profile": "https://Stackoverflow.com/users/402169",
"pm_score": 0,
"selected": false,
"text": "template<typename T, std::size_t N, std::size_t... Is>\nstd::array<T, N> initialize_array_with_indices_helper(std::index_sequence<Is...>) {\n return std::array<T, N>{Is...};\n}\n\ntemplate<typename T, std::size_t N>\nconstexpr std::array<T,N> initialize_array_with_indices() {\n return initialize_array_with_indices_helper<T, N>(std::make_index_sequence<N>());\n}\n"
},
{
"answer_id": 74360822,
"author": "Jason Liam",
"author_id": 12002570,
"author_profile": "https://Stackoverflow.com/users/12002570",
"pm_score": 1,
"selected": false,
"text": "constexpr"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74351090",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20442768/"
] |
74,351,091 | <p>I'm using Azure Cosmos DB for NoSQL. I made a container with a partitionkey called 'pricedate' but not really. It's really called '/pricedate' because it's required to have the slash. How do I query it in python with <code>azure.cosmos</code> version 4.3.0 library?</p>
<p>I've tried:</p>
<pre><code>x=container.query_items("select * from container c where c.pricedate='2018-04-01'", enable_cross_partition_query=True)
x.next()
</code></pre>
<p>Got a <code>StopIteration</code> error</p>
<pre><code>x=container.query_items("select * from container c where c./pricedate='2018-04-01'", enable_cross_partition_query=True)
x.next()
</code></pre>
<p>Got a <code>CosmosHttpResponseError</code> for incorrect syntax around the <code>/</code></p>
<pre><code>x=container.query_items("select * from container c where c.\"/pricedate\"='2018-04-01'", enable_cross_partition_query=True)
x.next()
</code></pre>
<p>Got a <code>CosmosHttpResponseError</code> for incorrect syntax again.</p>
<p>For extra info...</p>
<pre><code>x=container.read_all_items()
x.next()
</code></pre>
<p>returns:</p>
<pre><code>{'id': '2018-04-01T04:00:00+00:00',
'da': 'full',
'rt': 'full',
'/pricedate': '2018-04-01',
'_rid': 'mu0HAOqArvIBAAAAAAAAAA==',
'_self': 'dbs/mu0HAA==/colls/mu0HAOqArvI=/docs/mu0HAOqArvIBAAAAAAAAAA==/',
'_etag': '"0600755a-0000-0100-0000-63692d300000"',
'_attachments': 'attachments/',
'_ts': 1667837232}
</code></pre>
<p>so there is definitely data that matches the query and it is all lower case.</p>
| [
{
"answer_id": 74351185,
"author": "user17732522",
"author_id": 17732522,
"author_profile": "https://Stackoverflow.com/users/17732522",
"pm_score": 4,
"selected": true,
"text": "std::iota"
},
{
"answer_id": 74357605,
"author": "tenfour",
"author_id": 402169,
"author_profile": "https://Stackoverflow.com/users/402169",
"pm_score": 0,
"selected": false,
"text": "template<typename T, std::size_t N, std::size_t... Is>\nstd::array<T, N> initialize_array_with_indices_helper(std::index_sequence<Is...>) {\n return std::array<T, N>{Is...};\n}\n\ntemplate<typename T, std::size_t N>\nconstexpr std::array<T,N> initialize_array_with_indices() {\n return initialize_array_with_indices_helper<T, N>(std::make_index_sequence<N>());\n}\n"
},
{
"answer_id": 74360822,
"author": "Jason Liam",
"author_id": 12002570,
"author_profile": "https://Stackoverflow.com/users/12002570",
"pm_score": 1,
"selected": false,
"text": "constexpr"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74351091",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1818713/"
] |
74,351,093 | <p>I need some help with RegEx. I have a URL:</p>
<p><code>article/life/food/woman-who-called-911-over-pink-bbq-tells-her-side-of-the-story/275-88a8538f-4c62-4204-aed8-4381d618208d</code></p>
<p>This URL is not fixed and this changes every time. I only need to extract <code>woman-who-called-911-over-pink-bbq-tells-her-side-of-the-story</code> and store it in table.</p>
<p>Here's my attempt:</p>
<pre><code>select parse_url(c1:uri):path as PATH,
count(1) as CNT
from "OPE_RAW_DATA"."TAGGER_DEFAULT"."INTERACTION_20221107"
where c1:uri like'%www.kens5.com%'
group by PATH
order by CNT desc
</code></pre>
| [
{
"answer_id": 74351185,
"author": "user17732522",
"author_id": 17732522,
"author_profile": "https://Stackoverflow.com/users/17732522",
"pm_score": 4,
"selected": true,
"text": "std::iota"
},
{
"answer_id": 74357605,
"author": "tenfour",
"author_id": 402169,
"author_profile": "https://Stackoverflow.com/users/402169",
"pm_score": 0,
"selected": false,
"text": "template<typename T, std::size_t N, std::size_t... Is>\nstd::array<T, N> initialize_array_with_indices_helper(std::index_sequence<Is...>) {\n return std::array<T, N>{Is...};\n}\n\ntemplate<typename T, std::size_t N>\nconstexpr std::array<T,N> initialize_array_with_indices() {\n return initialize_array_with_indices_helper<T, N>(std::make_index_sequence<N>());\n}\n"
},
{
"answer_id": 74360822,
"author": "Jason Liam",
"author_id": 12002570,
"author_profile": "https://Stackoverflow.com/users/12002570",
"pm_score": 1,
"selected": false,
"text": "constexpr"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74351093",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10422686/"
] |
74,351,118 | <p>I am trying to write a generic wrapper function, and thought that this would work, but it is not:</p>
<pre><code>function wrapFunctionWithLogging<T extends Function>(f: (...args: Parameters<T>) => ReturnType<T>): ReturnType<T> {
return function (...args: Parameters<T>) {
console.log('before ');
try {
return f(...args);
} catch (error) {
console.error(error);
throw error;
} finally {
console.log('done');
}
};
}
</code></pre>
<p>I got another version with two types like</p>
<pre><code>wrapFunctionWithLogging<TArgs extends any[], TReturn>
</code></pre>
<p>and it is working fine, I am curious why this version would not work.</p>
| [
{
"answer_id": 74351185,
"author": "user17732522",
"author_id": 17732522,
"author_profile": "https://Stackoverflow.com/users/17732522",
"pm_score": 4,
"selected": true,
"text": "std::iota"
},
{
"answer_id": 74357605,
"author": "tenfour",
"author_id": 402169,
"author_profile": "https://Stackoverflow.com/users/402169",
"pm_score": 0,
"selected": false,
"text": "template<typename T, std::size_t N, std::size_t... Is>\nstd::array<T, N> initialize_array_with_indices_helper(std::index_sequence<Is...>) {\n return std::array<T, N>{Is...};\n}\n\ntemplate<typename T, std::size_t N>\nconstexpr std::array<T,N> initialize_array_with_indices() {\n return initialize_array_with_indices_helper<T, N>(std::make_index_sequence<N>());\n}\n"
},
{
"answer_id": 74360822,
"author": "Jason Liam",
"author_id": 12002570,
"author_profile": "https://Stackoverflow.com/users/12002570",
"pm_score": 1,
"selected": false,
"text": "constexpr"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74351118",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/125032/"
] |
74,351,127 | <p>I have an example df:</p>
<pre><code>df <- data.frame(
group = c("a", "a", "a", "a", "b", "b", "c", "c", "c", "c", "d", "d", "d", "e", "e", "e", "e"),
col1 = c(-36,10,-5,1, 0, 5,10, 5, 20, 2, -1, 1, 2, -10, -5, -1, 10 )
)
group col1
1 a -36
2 a 10
3 a -5
4 a 1
5 b 0
6 b 5
7 c 10
8 c 5
9 c 20
10 c 2
11 d -1
12 d 1
13 d 2
14 e -10
15 e -5
16 e -1
17 e 10
</code></pre>
<p>and I want to mutate a flag such that if grouped by 'group, if there is a value of 1 in col1, set that to "Y" and all other records in that group to blank. If there is a value of less than or equal to one, set the record with the highest col1 to "Y" and all other records in that group to blank (but col1 cannot be greater than 1 - these records must have blank flag). Otherwise, set every record to blank. Every record above value of 1 should have blank flag.</p>
<p>This is what I've tried:</p>
<pre><code>df3 <- df %>% mutate(flag = case_when(
any(col1 == 1) ~ ifelse(col1 == 1, "Y", ""),
any(col1 < 1) & !any(col1 == 1) ~ ifelse(col1 < 1 & col1 == max(col1), "Y", ""),
TRUE ~ ""))
</code></pre>
<p>This is the expected outcome:</p>
<pre><code> group col1 flag
1 a -36
2 a 10
3 a -5
4 a 1 Y
5 b 0 Y
6 b 5
7 c 10
8 c 5
9 c 20
10 c 2
11 d -1
12 d 1 Y
13 d 2
14 e -10
15 e -5
16 e -1 Y
17 e 10
</code></pre>
| [
{
"answer_id": 74351327,
"author": "akrun",
"author_id": 3732271,
"author_profile": "https://Stackoverflow.com/users/3732271",
"pm_score": 3,
"selected": true,
"text": "if/else"
},
{
"answer_id": 74351398,
"author": "AndS.",
"author_id": 9778513,
"author_profile": "https://Stackoverflow.com/users/9778513",
"pm_score": 2,
"selected": false,
"text": "case_when"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74351127",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8864308/"
] |
74,351,257 | <p>How do I generate <code>5</code> random <code>rasters</code> with values within defined bounds (different for each raster), and with pixel values summing up to <code>1</code>?</p>
<p>Here are the bounds</p>
<pre><code>xmin <- c(0, 0, 0, 0, 0)
xmax <- c(26.0, 78.6, 14.4, 39.4, 70.8)
</code></pre>
<p>Can I also follow the distribution of values from a second <code>raster</code> for each of the random <code>rasters</code>?</p>
| [
{
"answer_id": 74351327,
"author": "akrun",
"author_id": 3732271,
"author_profile": "https://Stackoverflow.com/users/3732271",
"pm_score": 3,
"selected": true,
"text": "if/else"
},
{
"answer_id": 74351398,
"author": "AndS.",
"author_id": 9778513,
"author_profile": "https://Stackoverflow.com/users/9778513",
"pm_score": 2,
"selected": false,
"text": "case_when"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74351257",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1280548/"
] |
74,351,275 | <p>I tried to change a display color from Blue to Orange when the temperature > 30'C or > 86'F by using a toggle switch and a range slider. the toggle switch is working ok, but the range slider doesn't work correctly.</p>
<p>For example,</p>
<p>When move the range slider to 87'F, sometimes the display is Blue (it's supposed to be Orange), and sometimes when move the range slider back to 86'F, the display = Orange (it's supposed to be Blue).</p>
<p>I wonder why sometimes it works, sometimes it doesn't work.
<a href="https://codepen.io/nttirevs/pen/ExRyJMg" rel="nofollow noreferrer">Code URL</a></p>
<pre><code>const App = () => {
const [value, setValue] = React.useState(0);
const [toggle, setToggle] = React.useState(false);
const [displayColor, setDisplayColor] = React.useState('cold');
const convertTemp = () => {
if(toggle){
setValue(value*9/5+32);
if ( value > 30){
setDisplayColor('hot');
}
else {
setDisplayColor('cold');
}
}
else if (!toggle){
setValue((value-32)*5/9);
if ( value > 86){
setDisplayColor('hot');
}
else {
setDisplayColor('cold');
}
}
}
const changeTemp = (e) => {
setValue(e.target.value);
if(toggle){
if ( value > 30){
setDisplayColor('hot');
}
else {
setDisplayColor('cold');
}
}
else if (!toggle) {
if ( value > 86){
setDisplayColor('hot');
}
else {
setDisplayColor('cold');
}
}
}
return (
<div className="container">
<div className={`display ${displayColor}`}>
{Math.round(value)}
</div>
<h1>{toggle ? "Celsius" : 'Fahrenheit'}</h1>
<label className='switch'>
<input onClick={convertTemp} onChange={(e) => setToggle(e.target.checked)} className='toggle' type='checkbox'></input>
<span className='slider'></span>
</label>
<input onChange={changeTemp} type="range" min="-100" max="100"></input>
</div>
)
}
ReactDOM.render(<App />, document.getElementById("root"));
</code></pre>
<p>Here is CSS</p>
<pre><code>body {
margin: 0;
min-height: 100vh;
display: flex;
align-items: center;
justify-content: center;
}
.container {
background-color: rgba(198, 208, 211, 0.922);
box-shadow: 2px 2px 5px rgba(0, 0, 0, 0.3);
width: 250px;
height: 400px;
display: grid;
align-items: center;
justify-content: center;
border-radius: 50px;
}
.display {
border-radius: 50px;
font-size: 60px;
height: 100px;
width: 200px;
display: flex;
align-items: center;
justify-content: center;
margin: 10px 0;
}
.switch {
position: relative;
display: inline;
width: 60px;
height: 34px;
margin-left: 70px;
}
.switch input {
opacity: 0;
width: 0;
height: 0;
}
.slider {
position: absolute;
cursor: pointer;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: rgb(91, 104, 150);
transition: 0.4s;
}
.slider:before {
position: absolute;
content: '';
height: 26px;
width: 26px;
left: 4px;
bottom: 4px;
background-color: aliceblue;
transition: 0.4s;
}
input:checked + .slider {
background-color: rgb(221, 92, 92);
}
input:checked + .slider:before {
transform: translateX(26px);
}
h1 {
display: flex;
align-items: center;
justify-content: center;
}
input[type=range] {
height: 30px;
margin: 10px 0;
cursor: pointer;
}
.cold {
background-color: rgb(95, 161, 201);
}
.hot {
background-color: rgb(242, 153, 101);
}
</code></pre>
| [
{
"answer_id": 74351435,
"author": "John Li",
"author_id": 20436957,
"author_profile": "https://Stackoverflow.com/users/20436957",
"pm_score": 2,
"selected": false,
"text": "const bgColor = (toggle && value > 30) || (!toggle && value > 86) ? 'hot' : 'cold'\n"
},
{
"answer_id": 74351680,
"author": "MalwareMoon",
"author_id": 20241005,
"author_profile": "https://Stackoverflow.com/users/20241005",
"pm_score": 1,
"selected": false,
"text": "const App = () => {\n const [value, setValue] = React.useState(0);\n const [isCelsius, setIsCelsius] = React.useState(false);\n const bgColor = (isCelsius && value > 30) || (!isCelsius && value > 86) ? 'hot' : 'cold'\n return (\n <div className=\"container\">\n <div className={`display ${bgColor}`}>\n {Math.round(value)}\n </div>\n <h1>{isCelsius ? \"Celsius\" : 'Fahrenheit'}</h1>\n <label className='switch'>\n <input onChange={(e) => {\n setIsCelsius(e.target.checked)\n }}\n className='toggle'\n type='checkbox'\n />\n <span className='slider'></span>\n </label>\n <input \n onChange={(e) => setValue(e.target.value)}\n type=\"range\"\n min=\"-100\"\n max=\"100\"\n />\n </div>\n )\n}\n\n\nReactDOM.render(<App />, document.getElementById(\"root\"));\n"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74351275",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20441670/"
] |
74,351,288 | <p>Having a problem with my mocked return response from my controller.</p>
<p>The async response is returning as the actual POJO not the serialized json.</p>
<p>Running the application and using Postman, the returned response is indeed a JSON Object... but testing it returns the actual mock POJO I've created...
here is my test case.</p>
<pre><code>@WebMvcTest(CustomerController.class)
class CustomerControllerTest {
@Autowired
MockMvc mvc;
@MockBean
private CustomerService customerService;
private Mono<OtcBalanceResponse> responseMono;
private OtcBalanceResponse otcResponseMock;
@BeforeEach
void setupMocks() {
OtcBalanceResponse otcResponseMock = new OtcBalanceResponse();
otcResponseMock.setOtcBalance(new BigDecimal("1.30"));
otcResponseMock.setUserId("testID");
responseMono = Mono.just(otcResponseMock);
}
@Test
void testGetCustomerOTCBalance() throws Exception {
when(customerService.getCustomerOTCBalance((OtcBalanceRequest) any()))
.thenReturn(responseMono);
MockHttpServletRequestBuilder requestBuilder = MockMvcRequestBuilders.get("/customer/otc-balance").accept(MediaType.APPLICATION_JSON);
mvc.perform(requestBuilder).andExpect(MockMvcResultMatchers.jsonPath("$.otcBalance").value(1.30));
}
</code></pre>
<p>}</p>
<p>here is my Controller class</p>
<pre><code> @GetMapping("/otc-balance")
public Mono<OtcBalanceResponse> getCustomerOTCBalance(OtcBalanceRequest otcBalanceRequest){
return customerService.getCustomerOTCBalance(otcBalanceRequest);
}
</code></pre>
<p>Here is my service</p>
<pre><code> public Mono<OtcBalanceResponse> getCustomerOTCBalance(OtcBalanceRequest request) {
return webClientBuilder
.baseUrl(customerBase)
.build()
.post()
.uri(otcBalancePath)
.body(BodyInserters.fromValue(request))
.retrieve()
.bodyToMono(OtcBalanceResponse.class);
}
</code></pre>
<p>this is my logged result</p>
<pre><code>Async:
Async started = true
Async result = OtcBalanceResponse(otcBalance=1.30, otcRolloverFlag=false, isIncommMember=false, otcStartDate=null, otcEndDate=null)
</code></pre>
| [
{
"answer_id": 74351950,
"author": "Lesiak",
"author_id": 1570854,
"author_profile": "https://Stackoverflow.com/users/1570854",
"pm_score": 2,
"selected": true,
"text": "@WebFluxTest(CustomerController.class)\nclass CustomerControllerTest {\n @Autowired\n private WebTestClient webClient;\n\n // ...\n\n @Test\n void testGetCustomerOTCBalance() throws Exception {\n\n when(customerService.getCustomerOTCBalance(any()))\n .thenReturn(responseMono);\n\n webClient.get().uri(\"/customer/otc-balance\")\n .exchange()\n .expectStatus().isOk()\n .expectBody()\n .jsonPath(\"$.otcBalance\").isEqualTo(1.30);\n\n }\n\n}\n"
},
{
"answer_id": 74352062,
"author": "M. Deinum",
"author_id": 2696260,
"author_profile": "https://Stackoverflow.com/users/2696260",
"pm_score": 2,
"selected": false,
"text": "MockMvc"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74351288",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8759986/"
] |
74,351,315 | <p>I want to call my HTTP callable functions in my front-end but cannot import firebase properly. I tried reading the <a href="https://firebase.google.com/docs/functions/callable#set_up_your_client_development_environment" rel="nofollow noreferrer">firebase documentation</a> but am still confused.</p>
<p>My questions:</p>
<ol>
<li>Do I need to import the firebase SDK in my front-end to gain access to my deployed firebase functions?</li>
</ol>
<p>Front-end code:</p>
<pre><code>import "../App.css";
import React, { useState } from "react";
import { getFunctions, httpsCallable } from
"firebase/functions";
const functions = require("firebase/functions");
export default function Navbar() {
const getViewCount =
firebase.functions().httpsCallable("getViewCount");
getViewCount().then((result) => {
console.log(result.data);
});
</code></pre>
<ol start="2">
<li>If so, how do I do that? (The site is already hosted on firebase). If not, what am I missing here?</li>
</ol>
<p>Here is my Firebase functions code from the backend:</p>
<pre><code> exports.getViewCount = functions
.runWith({ secrets: ["YOUTUBE_API"] })
.https.onCall(async (data, context) => {
const youtube = google.youtube({
version: "v3",
auth: process.env.YOUTUBE_API,});
const { count } = await youtube.channels.list({
id: process.env.YOUTUBE_CHANNEL_ID,
part: "statistics",});
const viewCount = count.items[0].statistics.viewCount;
return {
count: viewCount,};
});
</code></pre>
| [
{
"answer_id": 74351950,
"author": "Lesiak",
"author_id": 1570854,
"author_profile": "https://Stackoverflow.com/users/1570854",
"pm_score": 2,
"selected": true,
"text": "@WebFluxTest(CustomerController.class)\nclass CustomerControllerTest {\n @Autowired\n private WebTestClient webClient;\n\n // ...\n\n @Test\n void testGetCustomerOTCBalance() throws Exception {\n\n when(customerService.getCustomerOTCBalance(any()))\n .thenReturn(responseMono);\n\n webClient.get().uri(\"/customer/otc-balance\")\n .exchange()\n .expectStatus().isOk()\n .expectBody()\n .jsonPath(\"$.otcBalance\").isEqualTo(1.30);\n\n }\n\n}\n"
},
{
"answer_id": 74352062,
"author": "M. Deinum",
"author_id": 2696260,
"author_profile": "https://Stackoverflow.com/users/2696260",
"pm_score": 2,
"selected": false,
"text": "MockMvc"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74351315",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19797781/"
] |
74,351,323 | <p>I would like to print out total amount for each date so that my new dataframe will have date and and total amount columns.
My data frame looks like this</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>permitnum</th>
<th>amount</th>
</tr>
</thead>
<tbody>
<tr>
<td>6/1/2022</td>
<td>na</td>
</tr>
<tr>
<td>ascas</td>
<td>30.00</td>
</tr>
<tr>
<td>olic</td>
<td>40.41</td>
</tr>
<tr>
<td>6/2/2022</td>
<td>na</td>
</tr>
<tr>
<td>avrey</td>
<td>17.32</td>
</tr>
<tr>
<td>fev</td>
<td>32.18</td>
</tr>
<tr>
<td>grey</td>
<td>12.20</td>
</tr>
</tbody>
</table>
</div>
<p>any advice on how to go about this will be appreciated</p>
| [
{
"answer_id": 74351950,
"author": "Lesiak",
"author_id": 1570854,
"author_profile": "https://Stackoverflow.com/users/1570854",
"pm_score": 2,
"selected": true,
"text": "@WebFluxTest(CustomerController.class)\nclass CustomerControllerTest {\n @Autowired\n private WebTestClient webClient;\n\n // ...\n\n @Test\n void testGetCustomerOTCBalance() throws Exception {\n\n when(customerService.getCustomerOTCBalance(any()))\n .thenReturn(responseMono);\n\n webClient.get().uri(\"/customer/otc-balance\")\n .exchange()\n .expectStatus().isOk()\n .expectBody()\n .jsonPath(\"$.otcBalance\").isEqualTo(1.30);\n\n }\n\n}\n"
},
{
"answer_id": 74352062,
"author": "M. Deinum",
"author_id": 2696260,
"author_profile": "https://Stackoverflow.com/users/2696260",
"pm_score": 2,
"selected": false,
"text": "MockMvc"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74351323",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20412105/"
] |
74,351,335 | <p>Well I am a beginner with android and kotlin so I have been trying to send a variable <strong>semesterSelected</strong> from the fragment <strong>ViewCourses</strong> to my viewmodel <strong>UserViewModel</strong> is the codes are down below.</p>
<pre><code>`class ViewCourses(path: String) : ReplaceFragment() {
private var semesterSelected= path
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
container?.removeAllViews()
return inflater.inflate(R.layout.fragment_view_courses, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
userRecyclerView = view.findViewById(R.id.recyclerView)
userRecyclerView.layoutManager = LinearLayoutManager(context)
userRecyclerView.setHasFixedSize(true)
adapter = MyAdapter()
userRecyclerView.adapter = adapter
makeToast(semesterSelected)
// The variable I am trying to send to UserViewModel is -->> semesterSelected
var viewModel: UserViewModel = ViewModelProvider(this)[UserViewModel::class.java]
viewModel.allUsers.observe(viewLifecycleOwner) {
adapter.updateUserList(it)
}
}
}
</code></pre>
<pre><code>class UserViewModel : ViewModel() {
private val repository: UserRepository = UserRepository("CSE/year3semester1").getInstance()
private val _allUsers = MutableLiveData<List<CourseData>>()
val allUsers: LiveData<List<CourseData>> = _allUsers
init {
repository.loadUsers(_allUsers)
}
}
</code></pre>
<p>The reason I am doing this is I am wanting a to send a variable to my repository <strong>UserRepository</strong> all the way from <strong>ViewCourses</strong> and thought sending this via <strong>UserViewModel</strong> might be a way .</p>
<pre><code>class UserRepository(semesterSelected: String) {
// The variable I am expecting to get from UserViewModel
private var semesterSelected = semesterSelected
private val databaseReference: DatabaseReference =
FirebaseDatabase.getInstance().getReference("course-list/$semesterSelected")
@Volatile
private var INSTANCE: UserRepository? = null
fun getInstance(): UserRepository {
return INSTANCE ?: synchronized(this) {
val instance = UserRepository(semesterSelected)
INSTANCE = instance
instance
}
}
fun loadUsers(userList: MutableLiveData<List<CourseData>>) {
databaseReference.addValueEventListener(object : ValueEventListener {
override fun onDataChange(snapshot: DataSnapshot) {
try {
val courseList: List<CourseData> = snapshot.children.map { dataSnapshot ->
dataSnapshot.getValue(CourseData::class.java)!!
}
userList.postValue(courseList)
} catch (e: Exception) {
}
}
override fun onCancelled(error: DatabaseError) {
}
})
}
}
</code></pre>
<p>I tried something like below</p>
<pre><code>class ViewCourses(path: String) : ReplaceFragment() {
private var semesterSelected= path
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
container?.removeAllViews()
return inflater.inflate(R.layout.fragment_view_courses, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
userRecyclerView = view.findViewById(R.id.recyclerView)
userRecyclerView.layoutManager = LinearLayoutManager(context)
userRecyclerView.setHasFixedSize(true)
adapter = MyAdapter()
userRecyclerView.adapter = adapter
makeToast(semesterSelected)
**// Sending the variable as parameter**
var viewModel: UserViewModel = ViewModelProvider(this)[UserViewModel(semesterSelected)::class.java]
viewModel.allUsers.observe(viewLifecycleOwner) {
adapter.updateUserList(it)
}
}
}
</code></pre>
<pre><code>class UserViewModel(semesterSelected: String) : ViewModel() {
private val repository: UserRepository = UserRepository("CSE/year3semester1").getInstance()
private val _allUsers = MutableLiveData<List<CourseData>>()
val allUsers: LiveData<List<CourseData>> = _allUsers
init {
repository.loadUsers(_allUsers)
}
}
</code></pre>
<p>but doing this my app crashes . how can this be done ?
Thanks in Advance.</p>
| [
{
"answer_id": 74351950,
"author": "Lesiak",
"author_id": 1570854,
"author_profile": "https://Stackoverflow.com/users/1570854",
"pm_score": 2,
"selected": true,
"text": "@WebFluxTest(CustomerController.class)\nclass CustomerControllerTest {\n @Autowired\n private WebTestClient webClient;\n\n // ...\n\n @Test\n void testGetCustomerOTCBalance() throws Exception {\n\n when(customerService.getCustomerOTCBalance(any()))\n .thenReturn(responseMono);\n\n webClient.get().uri(\"/customer/otc-balance\")\n .exchange()\n .expectStatus().isOk()\n .expectBody()\n .jsonPath(\"$.otcBalance\").isEqualTo(1.30);\n\n }\n\n}\n"
},
{
"answer_id": 74352062,
"author": "M. Deinum",
"author_id": 2696260,
"author_profile": "https://Stackoverflow.com/users/2696260",
"pm_score": 2,
"selected": false,
"text": "MockMvc"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74351335",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13925224/"
] |
74,351,352 | <p>I am trying to input an array and then print it in reverse order using for loop. Firstly, I tried to print out the array elements in original order as follows:</p>
<pre><code>#include <stdio.h>
int main()
{
int a[100];
int n,i;
int *p=a;
printf("Enter size of array:");
scanf("%d",&n);
printf("Enter array elements:");
for(i=0;i<n;i++){
printf("Enter array element [%d]:",i);
scanf("%d",p+i);
}
printf("Array elements in reverse order: ");
for (i=0;i<n;i++){
printf("%d\n",*(p+i));
}
</code></pre>
<p>The above code worked and desired output was achieved. And then I tried to output array elements in reverse order using following changes in the last for loop:</p>
<pre><code>for (i=n;i>0;i--){
printf("%d\n",*(p+i));
</code></pre>
<p>But doing this the output appears as below:
<a href="https://i.stack.imgur.com/PhvV5.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/PhvV5.png" alt="enter image description here" /></a></p>
<p>while the desired output is:</p>
<pre><code>3
2
1
</code></pre>
<p>What am I missing?</p>
| [
{
"answer_id": 74351387,
"author": "dbush",
"author_id": 1687119,
"author_profile": "https://Stackoverflow.com/users/1687119",
"pm_score": 3,
"selected": true,
"text": "for (i=n-1;i>=0;i--){\n"
},
{
"answer_id": 74351452,
"author": "AR7CORE",
"author_id": 12945333,
"author_profile": "https://Stackoverflow.com/users/12945333",
"pm_score": 1,
"selected": false,
"text": "for (i = n - 1; i >= 0; i--) {\n //... \n}\n"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74351352",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10838122/"
] |
74,351,404 | <p>By using <code>TextEditingController</code> in Flutter, I'm trying to force the user to enter a number that starts with zero and then the number 4 or 8, then enter whatever he wants. Like this:</p>
<pre><code>04****** or 08******
</code></pre>
<p>What should I do?</p>
<p>My code:</p>
<pre><code>
TextFormField(
maxLength: 10,
controller: _inputdat,
inputFormatters: [ FilteringTextInputFormatter.digitsOnly,],
keyboardType: TextInputType.number),
ElevatedButton(
......
onPressed: () async {
if (_inputdat.text.length < 10
|| !RegExp(r'^[0][8/4/2]{1}[0-9]{8}$').hasMatch(value))
{
ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
backgroundColor: Color(0xff446d74),
content: Text(
"Error",
)));
</code></pre>
<p>What's wrong with my code? I got the error: Undefined name 'value'.</p>
| [
{
"answer_id": 74351387,
"author": "dbush",
"author_id": 1687119,
"author_profile": "https://Stackoverflow.com/users/1687119",
"pm_score": 3,
"selected": true,
"text": "for (i=n-1;i>=0;i--){\n"
},
{
"answer_id": 74351452,
"author": "AR7CORE",
"author_id": 12945333,
"author_profile": "https://Stackoverflow.com/users/12945333",
"pm_score": 1,
"selected": false,
"text": "for (i = n - 1; i >= 0; i--) {\n //... \n}\n"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74351404",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20114679/"
] |
74,351,425 | <p>I Try To Pass Parameter To With() Function For Model:</p>
<pre><code>Model::with(['functionA($parameters)', 'functionB'])
</code></pre>
| [
{
"answer_id": 74351968,
"author": "Mahmoud",
"author_id": 10094324,
"author_profile": "https://Stackoverflow.com/users/10094324",
"pm_score": -1,
"selected": false,
"text": "$model = new Model(); // or $model = Model::where(anyConditionYouWant)->first();\n$model->functionA($parameters);\n"
},
{
"answer_id": 74357239,
"author": "Khayam Khan",
"author_id": 10739750,
"author_profile": "https://Stackoverflow.com/users/10739750",
"pm_score": 2,
"selected": true,
"text": "Model::with(['functionA' => function($query) use ($parameters) {\n $query->where('some_column', $parameters);\n }, 'functionB'])->get(); \n"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74351425",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11064578/"
] |
74,351,428 | <p>I need a function to count the total number of days in the 'days' column between a start date of 1st Jan 1995 and an end date of 31st Dec 2019 in a dataframe taking Leapyears into account as well</p>
<p>For example:</p>
<ul>
<li>1st Jan 1995 - Day 1</li>
<li>1st Feb 1995 - Day 32</li>
<li>2nd Feb 1995 - Day 33...</li>
</ul>
<p>And so on all the way to 31st Dec 2019.</p>
<p><a href="https://i.stack.imgur.com/F0Gjn.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/F0Gjn.png" alt="Screenshot of the 1st ten rows of the dataset" /></a></p>
<p>This is the function I created initially but it doesn't work.
<code>prices</code> is the name of the data frame and <code>'days'</code> is the column where the number of days is to reflect.</p>
<pre><code>def date_difference(self):
for i in range(prices.shape[0] - 1):
prices['days'][i+1] = (prices['days'][i+1] - prices['days'][i])
</code></pre>
| [
{
"answer_id": 74351559,
"author": "Mateusz Dorobek",
"author_id": 8081835,
"author_profile": "https://Stackoverflow.com/users/8081835",
"pm_score": 1,
"selected": false,
"text": "days"
},
{
"answer_id": 74352420,
"author": "Chisom Anene",
"author_id": 20442029,
"author_profile": "https://Stackoverflow.com/users/20442029",
"pm_score": -1,
"selected": false,
"text": "def date_difference(last_day):\n last_day = pd.to_datetime(last_day, dayfirst = True)\n first_day = pd.to_datetime(\"01/01/1995\", dayfirst = True)\n diff = last_day - first_day\n\nprices['days'] = prices['days'].apply(date_difference)\n"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74351428",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20442029/"
] |
74,351,434 | <p>I'm struggling to understand why is the <code>__gc</code> metamethod is not being called here. I immediately removed the reference to <code>x</code> and triggered a GC, so why?</p>
<pre class="lang-lua prettyprint-override"><code>local obj = {}
obj.__index = obj
function obj:__gc()
print("gc")
end
function new()
return setmetatable({}, obj)
end
local x = new()
x = nil
collectgarbage()
</code></pre>
<p>I expect that the GC would collect that <code>x</code> and so it would trigger the <code>__gc</code> metamethod associated with it.</p>
<p>This is just a minimal reproducible example but to make my goals clear I want to wrap a C data in LuaJIT's ffi to deallocate its memory upon garbage collection.</p>
| [
{
"answer_id": 74351619,
"author": "Optimum",
"author_id": 12135804,
"author_profile": "https://Stackoverflow.com/users/12135804",
"pm_score": 0,
"selected": false,
"text": "__gc"
},
{
"answer_id": 74351734,
"author": "Ravener",
"author_id": 17027299,
"author_profile": "https://Stackoverflow.com/users/17027299",
"pm_score": 2,
"selected": true,
"text": "ffi.metatype"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74351434",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17027299/"
] |
74,351,436 | <p>I have two GitHub accounts setup with ssh keys, one personal and one enterprise.</p>
<p>I have an ssh config file as such:</p>
<pre><code># * GitHub CKO SSH Key
Host github-enterprise
HostName github.com
AddKeysToAgent yes
UseKeychain yes
User git
IdentityFile ~/.ssh/id_ed25519_github
# * GitHub Personal SSH Key
Host github-personal
HostName github.com
AddKeysToAgent yes
UseKeychain yes
User git
IdentityFile ~/.ssh/gh_mervinhemaraju_ed25519
</code></pre>
<p>Both keys were created seperately and attached to the respective account.</p>
<p>The weird issue is that I was using this for like a month, and it was working. Today, when i logged in, i committed some work on my personal repo and when i tried to do a remote push (which was working for this repo previously), i got and user permission denied.</p>
<p>I then performed an ssh test on both ssh keys and the results was as such:</p>
<pre><code>ssh -T ssh -T git@github-personal
Hi mervin-hemaraju-enterprise! You've successfully authenticated, but GitHub does not provide shell access.
ssh -T git@github-enterprise
Hi mervin-hemaraju-cko! You've successfully authenticated, but GitHub does not provide shell access.
</code></pre>
<p>The personal key test is wrong. It should've been <code>Hi mervinhemaraju! You've successfully authenticated, but GitHub does not provide shell access.</code> since mervinhemaraju is my personal account, but is instead referring to the enterprise one.</p>
<p>I am on MacOs. Can someone please help ?</p>
| [
{
"answer_id": 74351500,
"author": "m0j0",
"author_id": 31319,
"author_profile": "https://Stackoverflow.com/users/31319",
"pm_score": 0,
"selected": false,
"text": "~/.ssh/config"
},
{
"answer_id": 74486321,
"author": "Jimmy Bernljung",
"author_id": 490223,
"author_profile": "https://Stackoverflow.com/users/490223",
"pm_score": 2,
"selected": true,
"text": "IdentitiesOnly yes"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74351436",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6884119/"
] |
74,351,486 | <p>The script makes an ajax call to a PHP file on input change, but the JSON isn't parsing and I don't know why
Here's the Javascript</p>
<pre><code> input.addEventListener("input", (event) => {output.innerHTML = "Cerca " + document.getElementById("tophead-searchbar").value + " su Nevent";
var searchqueryajax = new XMLHttpRequest;
ajaxquerylink = "suggerimenti_query.php?query=" + document.getElementById("tophead-searchbar").value;
searchqueryajax.addEventListener("load", innerhtmlqueries());
searchqueryajax.open("GET", ajaxquerylink);
searchqueryajax.send();
function innerhtmlqueries() {
queriesarray = JSON.parse(searchqueryajax.responseText);
}
});
</code></pre>
<p>The input is document.getElementById("tophead-searchbar") and the output is the Result1, it says the value of the input
Here is the PHP Script:</p>
<pre><code>$query = $_REQUEST["query"];
$queryresults = mysqli_query($name, "SELECT * FROM search_queries WHERE MATCH(ID, QUERY) AGAINST('$query') LIMIT 7");
if ($queryresults->num_rows > 0) {
$autocompleteresults = array();
while($row = mysqli_fetch_array($queryresults)) {
$results["ID"] = $row["ID"];
$results["value"] = $row["QUERY"];
$results["type"] = $row["TIPO"];
array_push($autocompleteresults, $results);
}
}
echo json_encode($autocompleteresults);
</code></pre>
<p>There are no PHP errors on the log and i don't see the PHP File on Network Tab of the browser F12 editor</p>
<p>I tried to do some things on Javascript code but i still don't notice the request on Network Tab</p>
<p>Edit: I also have another ajax call like this in the same file and it works</p>
<pre><code> var checkajaxiflogged = new XMLHttpRequest();
checkajaxiflogged.addEventListener("load", checkajaxiflogged_function);
checkajaxiflogged.open("GET", "topbarprofileinformation.php");
checkajaxiflogged.send();
function checkajaxiflogged_function() {
topheadjsonresponse = JSON.parse(checkajaxiflogged.responseText);
document.getElementById("tophead-account-img").style.backgroundImage = "url('../beta/immagini_profilo/" + topheadjsonresponse.profiloimg + "')";
if (topheadjsonresponse.isloggedin == "yes") {
document.getElementById("tophead-accedi-btn").style.display = "none";
document.getElementById("tophead-account-img").style.display = "block";
document.getElementById("Immagine-Profilo-Menu-Principale").style.backgroundImage = "url('../beta/immagini_profilo/" + topheadjsonresponse.profiloimg + "')";
document.getElementById("Nome-Profilo-Menu-Principale").innerHTML = topheadjsonresponse.displayname;
document.getElementById("Username-Profilo-Menu-Principale").innerHTML = "@" + topheadjsonresponse.username;
}
}
</code></pre>
| [
{
"answer_id": 74351500,
"author": "m0j0",
"author_id": 31319,
"author_profile": "https://Stackoverflow.com/users/31319",
"pm_score": 0,
"selected": false,
"text": "~/.ssh/config"
},
{
"answer_id": 74486321,
"author": "Jimmy Bernljung",
"author_id": 490223,
"author_profile": "https://Stackoverflow.com/users/490223",
"pm_score": 2,
"selected": true,
"text": "IdentitiesOnly yes"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74351486",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19436223/"
] |
74,351,494 | <p>I want to take two fields from my model, one is a float, and the other is a ManyToMany and do an arithmetic operation on them and add them in a field with annotate</p>
<p>At one point it worked for me and then it didn't.</p>
<p>I don't know what would be the correct way I show some things from my files.</p>
<p>models.py</p>
<pre><code>from django.db.models import F, DecimalField
class Tax(models.Model):
name = models.CharField(max_length=50)
porcent = models.IntegerField()
def __str__(self):
return self.name
class Product(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
title = models.CharField(max_length=200)
code_number = models.IntegerField(verbose_name='Bar Code')
image = models.ImageField(upload_to='products/')
purchase_price = models.DecimalField(max_digits=10, decimal_places=2)
sale_price= models.DecimalField(max_digits=10, decimal_places=2)
tax = models.ManyToManyField(Tax, blank=True, related_name="tax")
description = models.TextField()
created_date = models.DateTimeField(
default=timezone.now)
published_date = models.DateTimeField(
blank=True, null=True)
def publish(self):
self.published_date = timezone.now()
self.save()
def __str__(self):
return self.title
</code></pre>
<p>views.py</p>
<pre><code>from django.shortcuts import render
from .models import Tax, Product, Invoice
from django.db.models import F, DecimalField
class InvoiceDashboard(View):
def get(self, request, *args, **kwargs):
products=Product.objects.all().annotate(amount_tax = ((F('sale_price') / 100) * F('tax__porcent'))).annotate(
price_total=(F('sale_price') + F('amount_tax'))
)
context = {
'products': products,
}
return render(request, 'pos/cashier.html', context)
</code></pre>
<p>pos/cashier.html</p>
<pre><code>{% extends 'pos/base.html' %}
{% block content %}
<tbody id="table_p">
{% for product in products %}
<tr class="productO" id="{{ product.id }}" data-id="{{ product.id }}" data-saleprice="{{ product.sale_price }}" data-codenumber="{{ product.code_number }}" data-amounttax="{{ product.amount_tax|floatformat:2 }}">
<th scope="row">{{ product.code_number }}</th>
<td><img src="/media/{{ product.image }}" width="60" height="60"/>{{ product.title }}</td>
<td><input class="spinner" id="{{ product.id }}" type="number" value="1" placeholder="1" min="1" max="100" disabled></td>
<td class="sub-total-p" id="{{ product.sale_price }}">{{ product.sale_price }}</td>
<td>{% for tax in product.tax.all %}{{ tax }} {% endfor %} | {{ product.amount_tax|floatformat:2 }}</td>
<td class="total-p" id="{{ product.price_total }}">{{ product.price_total|floatformat:2 }}</td>
<td class="sub-select">
<div class="form-check form-switch">
<input class="form-check-input" type="checkbox" id="{{ product.id }}">
</div>
</td>
</tr>
{% endfor %}
</tbody>
{% endblock %}
</code></pre>
<p>How can I get the percentage of each of the Taxes in a Product Object?</p>
| [
{
"answer_id": 74351500,
"author": "m0j0",
"author_id": 31319,
"author_profile": "https://Stackoverflow.com/users/31319",
"pm_score": 0,
"selected": false,
"text": "~/.ssh/config"
},
{
"answer_id": 74486321,
"author": "Jimmy Bernljung",
"author_id": 490223,
"author_profile": "https://Stackoverflow.com/users/490223",
"pm_score": 2,
"selected": true,
"text": "IdentitiesOnly yes"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74351494",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1005875/"
] |
74,351,496 | <p>I've a file as follows:</p>
<pre><code>[para1]
abc-1-10 interpreter=/bin/sed
abc-1-11 interpreter=/bin/sed
[para2]
abc-2-100 interpreter=/bin/sed
abc-2-205 interpreter=/bin/sed
abc-2-206 interpreter=/bin/sed
[para3]
abc-3-15 interpreter=/bin/sed
abc-3-18 interpreter=/bin/sed
</code></pre>
<p>I need each para written to a separate file i.e. the line [para1] and the two entries i.e. abc-1-10 and abc-1-11</p>
<p>I tried</p>
<pre><code>awk -v Var="\[para" '$1~Var{p=1}/^$/{p=0}p /tmp/filename
</code></pre>
<p>which gives an error as: <code>awk:warning: escape sequence '\[' treated as plain '[' </code></p>
<p>I also tried <code>awk -v Var="para" '$1~Var{p=1}/^$/{p=0}p /tmp/filename</code> and it prints the whole file!!. Any help is much appreciated.</p>
| [
{
"answer_id": 74351693,
"author": "HatLess",
"author_id": 16372109,
"author_profile": "https://Stackoverflow.com/users/16372109",
"pm_score": 2,
"selected": true,
"text": "awk"
},
{
"answer_id": 74354388,
"author": "potong",
"author_id": 967492,
"author_profile": "https://Stackoverflow.com/users/967492",
"pm_score": 0,
"selected": false,
"text": "csplit -q -f file -b %d.txt inputFile '/^\\[/' '{*}' && rm file0.txt\n"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74351496",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4204237/"
] |
74,351,515 | <p>I have a future call that I want to get 2 list Strings</p>
<p>But I get the return value it's a Future<List< dynamic >></p>
<pre><code>var datasource = const FutureInformation();
getSliderDetailsEvents() async {
SliderDetails futureEvents = await datasource.getSliderDetails();
List<String> images = futureEvents.image; //List<String>
List<String> titles = futureEvents.title; // List<String>
List information = [images,titles]; //return an array
return information;
}
</code></pre>
<p>How can I access the two List in this async call? I know as it's async I have to return a future, Would I have to create a FutureBuilder to create the List's.</p>
<p>Thanks</p>
| [
{
"answer_id": 74351693,
"author": "HatLess",
"author_id": 16372109,
"author_profile": "https://Stackoverflow.com/users/16372109",
"pm_score": 2,
"selected": true,
"text": "awk"
},
{
"answer_id": 74354388,
"author": "potong",
"author_id": 967492,
"author_profile": "https://Stackoverflow.com/users/967492",
"pm_score": 0,
"selected": false,
"text": "csplit -q -f file -b %d.txt inputFile '/^\\[/' '{*}' && rm file0.txt\n"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74351515",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1348731/"
] |
74,351,550 | <p>I see gobs of posts about passing column names as strings to function but none of them consider this use case. All the methods I see don't work. Here is one. Please compare the <code>what_I_want</code> column to the <code>what_I_get</code> column below. I want the value of items in the column, not the column name, of course. Thanks.</p>
<pre><code>library(dplyr)
Fun <- function(df,column) {
df %>%
mutate(what_I_want = cyl) %>%
# current best practice? Doen't work in this case.
mutate(what_I_get := {{column}})
}
mtcars[1:2,1:3] %>% Fun("cyl")
#> mpg cyl disp what_I_want what_I_get
#> Mazda RX4 21 6 160 6 cyl
#> Mazda RX4 Wag 21 6 160 6 cyl
</code></pre>
<p>Created on 2022-11-07 with reprex v2.0.2</p>
| [
{
"answer_id": 74351585,
"author": "akrun",
"author_id": 3732271,
"author_profile": "https://Stackoverflow.com/users/3732271",
"pm_score": 0,
"selected": false,
"text": "ensym"
},
{
"answer_id": 74351590,
"author": "Jilber Urbina",
"author_id": 1315767,
"author_profile": "https://Stackoverflow.com/users/1315767",
"pm_score": 2,
"selected": true,
"text": "get"
},
{
"answer_id": 74351593,
"author": "stefan",
"author_id": 12993861,
"author_profile": "https://Stackoverflow.com/users/12993861",
"pm_score": 0,
"selected": false,
"text": ".data"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74351550",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4634335/"
] |
74,351,551 | <p>I set up a small vba macro that loops through a selected user range and changes the font of the cell.
However, when I accidentally press Ctrl+A and change the font with my code the whole sheet crashes (I believe because it's too many cells to loop through).</p>
<p>Is there a way to speed up the loop or make it more efficient?</p>
<pre><code>Public Sub Font_OnAction( _
ByRef Control As Office.IRibbonControl, _
ByRef galleryID As String, _
ByRef selectedIndex As Integer)
Dim myRange As Range
Set myRange = Selection
Dim myCell As Range
For Each myCell In myRange
Select Case selectedIndex
Case 0
With myCell.Font
.Color = RGB(3, 3, 3)
End With
Case 1
With myCell.Font
.Color = RGB(5, 5, 5)
End With
Case 2
With myCell.Font
.Color = RGB(10, 10, 10)
End With
Case 3
With myCell.Font
.Color = RGB(50, 254, 225)
End With
Case 4
With myCell.Font
.Color = RGB(57, 69, 251)
End With
Case 5
With myCell.Font
.Color = RGB(154, 154, 154)
End With
Case 6
With myCell.Font
.Color = RGB(228, 228, 228)
End With
Case 7
With myCell.Font
.Color = RGB(62, 0, 175)
End With
Case 8
With myCell.Font
.Color = RGB(73, 252, 156)
End With
End Select
Next myCell
End Sub
</code></pre>
| [
{
"answer_id": 74351634,
"author": "BigBen",
"author_id": 9245853,
"author_profile": "https://Stackoverflow.com/users/9245853",
"pm_score": 3,
"selected": true,
"text": "If TypeOf Selection Is Range Then\n Select Case selectedIndex\n Case 0\n Selection.Font.Color = RGB(3, 3, 3)\n Case 1\n Selection.Font.Color = RGB(5, 5, 5) \n Case 2\n Selection.Font.Color = RGB(10, 10, 10)\n Case 3\n Selection.Font.Color = RGB(50, 254, 225) \n Case 4\n Selection.Font.Color = RGB(57, 69, 251)\n Case 5\n Selection.Font.Color = RGB(154, 154, 154)\n Case 6\n Selection.Font.Color = RGB(228, 228, 228)\n Case 7\n Selection.Font.Color = RGB(62, 0, 175)\n Case 8\n Selection.Font.Color = RGB(73, 252, 156)\n End Select\nEnd If\n"
},
{
"answer_id": 74351683,
"author": "Péter Forgó",
"author_id": 13406526,
"author_profile": "https://Stackoverflow.com/users/13406526",
"pm_score": 0,
"selected": false,
"text": "Public Sub Font_OnAction( _\n ByRef Control As Office.IRibbonControl, _\n ByRef galleryID As String, _\n ByRef selectedIndex As Integer)\n\nDim myRange As Range\nDim vColor As Variant\n\n Application.ScreenUpdating = False\n Set myRange = Selection\n Select Case selectedIndex\n Case 0: vColor = RGB(3, 3, 3)\n Case 1: vColor = RGB(5, 5, 5)\n Case 2: vColor = RGB(10, 10, 10)\n Case 3: vColor = RGB(50, 254, 225)\n ' OTHER CASES...\n End Select\n myRange.Font.Color = vColor\n Application.ScreenUpdating = True\nEnd Sub\n"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74351551",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20214787/"
] |
74,351,552 | <p>I have abstracted some logic for fetching data into its own service.</p>
<pre><code>
import type { Todo } from './Todo';
class TodoService {
private async secretFetch() {
const todos = await fetch('https://jsonplaceholder.typicode.com/todos/');
return (await todos.json()) as Todo[];
}
async fetchTodos() {
const todos = await this.secretFetch();
return todos;
}
}
const todoService = new TodoService();
export default todoService;
</code></pre>
<p>I would like to use this method as a parameter for <code>useQuery</code>, but I noticed that the query fails when the method calls another method inside my class.</p>
<pre><code>export default function App() {
const { data: todos, isLoading } = useQuery('todos', todoService.fetchTodos);
if (isLoading) {
return <p> Loading </p>;
}
if (todos.length === 0) {
return <p> There are no todos </p>;
}
return (
<ul>
{todos.map((todo) => (
<li> {todo.title} </li>
))}
</ul>
);
}
</code></pre>
<p>Here's an example in Stack blitz: <a href="https://stackblitz.com/edit/react-ts-5uxsz5?file=App.tsx" rel="nofollow noreferrer">https://stackblitz.com/edit/react-ts-5uxsz5?file=App.tsx</a></p>
| [
{
"answer_id": 74351634,
"author": "BigBen",
"author_id": 9245853,
"author_profile": "https://Stackoverflow.com/users/9245853",
"pm_score": 3,
"selected": true,
"text": "If TypeOf Selection Is Range Then\n Select Case selectedIndex\n Case 0\n Selection.Font.Color = RGB(3, 3, 3)\n Case 1\n Selection.Font.Color = RGB(5, 5, 5) \n Case 2\n Selection.Font.Color = RGB(10, 10, 10)\n Case 3\n Selection.Font.Color = RGB(50, 254, 225) \n Case 4\n Selection.Font.Color = RGB(57, 69, 251)\n Case 5\n Selection.Font.Color = RGB(154, 154, 154)\n Case 6\n Selection.Font.Color = RGB(228, 228, 228)\n Case 7\n Selection.Font.Color = RGB(62, 0, 175)\n Case 8\n Selection.Font.Color = RGB(73, 252, 156)\n End Select\nEnd If\n"
},
{
"answer_id": 74351683,
"author": "Péter Forgó",
"author_id": 13406526,
"author_profile": "https://Stackoverflow.com/users/13406526",
"pm_score": 0,
"selected": false,
"text": "Public Sub Font_OnAction( _\n ByRef Control As Office.IRibbonControl, _\n ByRef galleryID As String, _\n ByRef selectedIndex As Integer)\n\nDim myRange As Range\nDim vColor As Variant\n\n Application.ScreenUpdating = False\n Set myRange = Selection\n Select Case selectedIndex\n Case 0: vColor = RGB(3, 3, 3)\n Case 1: vColor = RGB(5, 5, 5)\n Case 2: vColor = RGB(10, 10, 10)\n Case 3: vColor = RGB(50, 254, 225)\n ' OTHER CASES...\n End Select\n myRange.Font.Color = vColor\n Application.ScreenUpdating = True\nEnd Sub\n"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74351552",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8897307/"
] |
74,351,554 | <p>I have a class <code>SqlGetGroupCutRates</code> which has a</p>
<pre><code>public bool UpdateDefaultTarget(string param1)
</code></pre>
<p>method. In this method, I am using the <code>SqlClient.SqlCommand</code> class.</p>
<pre><code>public bool UpdateDefaultTarget(string g1)
{
string myworkCenterCode = Form1.globalWorkCenter;
try
{
string connString = @"Data Source =" + server + "; Initial Catalog =" + redGreenDB + ";Integrated Security=SSPI";
// WHERE CUT_RATE_GROUP = @CUT_RATE_GROUP... WHAT IS @CUT_RATE_GROUP????
string myCommandString = "SELECT TOP 1 Default_Cut_Rate_Per_Hour FROM " + groupCutRateTable + " WHERE " +
"Cut_Rate_Group= @Cut_Rate_Group ORDER BY Record_Date DESC";
// SQL connection using the connString taking us to the redGreenDB
using (SqlConnection conn = new SqlConnection(connString))
{
conn.Open();
// Get the specific default cut rate from groupCutRateTable ("dbo.ABR_Tape_Cvt_Group_Cut_Rates") where Cut_Rate_Group (column)
using (SqlCommand cmd = new SqlCommand(myCommandString, conn))
{
cmd.Parameters.AddWithValue("Cut_Rate_Group", g1);
using (SqlDataReader reader = cmd.ExecuteReader())
{
if (reader.HasRows)
{
defaultFoundInQuery = true;
while (reader.Read())
{
int ordTarget = reader.GetOrdinal("Default_Cut_Rate_Per_Hour");
// Handle potential null database values:
if (!reader.IsDBNull(ordTarget))
{
int ord1 = reader.GetOrdinal("Default_Cut_Rate_Per_Hour");
default_Cut_Rate_Per_Hour = reader.GetDouble(ord1);
}
else
{
default_Cut_Rate_Per_Hour = 0;
}
}
}
// else if no data rows found.
else
{
default_Cut_Rate_Per_Hour = 0;
}
conn.Close();
}
}
}
}
catch (Exception ex)
{
MessageBox.Show("Problem getting Group Cut Rates from database: \n" + ex);
}
return defaultFoundInQuery;
}
</code></pre>
<p>In my <code>myCommandString</code> variable, you will notice it is set to the value</p>
<pre><code>string myCommandString = "SELECT TOP 1 Default_Cut_Rate_Per_Hour FROM " + groupCutRateTable + " WHERE " +
"Cut_Rate_Group= @Cut_Rate_Group ORDER BY Record_Date DESC";
</code></pre>
<p>I am querying the top 1/first Default_Cut_Rate_Per_Hour column value from the groupCutRateTable WHERE the Cut_Rate_Group column value is @Cut_Rate_Group.</p>
<p>My question is... in this query... what is meant by the @Cut_Rate_Group part of the query? Is this just going to return the first Cut_Rate_Group column value? Essentially making this a "static" query that will always return the same value? Or is the syntax of @Cut_Rate_Group seen as dynamic? Meaning @Cut_Rate_Group is assigned a value somewhere in my code?</p>
<p>Apologies, I am very new to this. If you have any docs I could read further into this, I would also appreciate that so I can better understand any answer I may get. Thanks for taking the time to read this.</p>
<p>I am expecting that this syntax would make @Cut_Rate_Group dynamic in the sense that it is almost viewed as a variable that is assigned a value.</p>
| [
{
"answer_id": 74351634,
"author": "BigBen",
"author_id": 9245853,
"author_profile": "https://Stackoverflow.com/users/9245853",
"pm_score": 3,
"selected": true,
"text": "If TypeOf Selection Is Range Then\n Select Case selectedIndex\n Case 0\n Selection.Font.Color = RGB(3, 3, 3)\n Case 1\n Selection.Font.Color = RGB(5, 5, 5) \n Case 2\n Selection.Font.Color = RGB(10, 10, 10)\n Case 3\n Selection.Font.Color = RGB(50, 254, 225) \n Case 4\n Selection.Font.Color = RGB(57, 69, 251)\n Case 5\n Selection.Font.Color = RGB(154, 154, 154)\n Case 6\n Selection.Font.Color = RGB(228, 228, 228)\n Case 7\n Selection.Font.Color = RGB(62, 0, 175)\n Case 8\n Selection.Font.Color = RGB(73, 252, 156)\n End Select\nEnd If\n"
},
{
"answer_id": 74351683,
"author": "Péter Forgó",
"author_id": 13406526,
"author_profile": "https://Stackoverflow.com/users/13406526",
"pm_score": 0,
"selected": false,
"text": "Public Sub Font_OnAction( _\n ByRef Control As Office.IRibbonControl, _\n ByRef galleryID As String, _\n ByRef selectedIndex As Integer)\n\nDim myRange As Range\nDim vColor As Variant\n\n Application.ScreenUpdating = False\n Set myRange = Selection\n Select Case selectedIndex\n Case 0: vColor = RGB(3, 3, 3)\n Case 1: vColor = RGB(5, 5, 5)\n Case 2: vColor = RGB(10, 10, 10)\n Case 3: vColor = RGB(50, 254, 225)\n ' OTHER CASES...\n End Select\n myRange.Font.Color = vColor\n Application.ScreenUpdating = True\nEnd Sub\n"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74351554",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11943666/"
] |
74,351,555 | <p>I am building a cross platform app using Xamarin forms on a mac using Visual code for mac.</p>
<p>I need to be able to change the status bar text and background colors on both the iOS and Android version of the APP.</p>
<p>I tried James Montemagno's solution from his video.
<a href="https://www.youtube.com/watch?v=GKJRR8_DSSs" rel="nofollow noreferrer">https://www.youtube.com/watch?v=GKJRR8_DSSs</a></p>
<p>So every thing was good till we needed to use this code <code>window.DecorView.SystemUiVisibility</code>
This code is deprecated and Visual Studio does not offert any hint to what I can use instead. I have tried to find but all I get is Android native related information <a href="https://stackoverflow.com/questions/62577645/android-view-view-systemuivisibility-deprecated-what-is-the-replacement">1</a>.</p>
<p>I really wish I would not have to use "native" code for some thing so basic in mobile App development. I understand that using the Shell class will allow me do use the minimal amount of "native" code possible, really wish to avoid coding any native code if possibly.</p>
<p>Context: I need to set the Android version of the app so that is has a white status bar and black text. Also I have 1 page with a black background image taking the full view, so on this page I need the status bar to be transparent and use a white foreground color.</p>
<p>So what does replace <code>window.DecorView.SystemUiVisibility = darkStatusBarTint ? flag : 0;</code> ??</p>
<p>The app is targeting Android API 30.</p>
<p>This is the code that is in the video</p>
<pre><code>From main project stub
using System;
using System.Drawing;
namespace MyApp.Helpers
{
public interface IEnvironment
{
void SetStatusBarColor(Color color, bool darkStatusBarTint);
}
}
From android stub
using System;
using System.Drawing;
using System.Runtime.CompilerServices;
using Android.OS;
using EGrid18.Helpers;
using Xamarin.Essentials;
using Xamarin.Forms;
using Color = System.Drawing.Color;
using DependencyAttribute = Xamarin.Forms.DependencyAttribute;
[assembly: Dependency(typeof(MyApp.Droid.Environment))]
namespace MyApp.Droid
{
public class Environment: IEnvironment
{
public void SetStatusBarColor(Color color, bool darkStatusBarTint)
{
if (Build.VERSION.SdkInt < Android.OS.BuildVersionCodes.Lollipop)
return;
var activity = Platform.CurrentActivity;
var window = activity.Window;
window.AddFlags(Android.Views.WindowManagerFlags.DrawsSystemBarBackgrounds);
window.ClearFlags(Android.Views.WindowManagerFlags.TranslucentStatus);
window.SetStatusBarColor(color.ToPlatformColor());
if(Build.VERSION.SdkInt >= Android.OS.BuildVersionCodes.M)
{
var flag = (Android.Views.StatusBarVisibility)Android.Views.SystemUiFlags.LightStatusBar;
#pragma warning disable CS0618 // Le type ou le membre est obsolète
//problen is here
window.DecorView.SystemUiVisibility = darkStatusBarTint ? flag : 0;
#pragma warning restore CS0618 // Le type ou le membre est obsolète
}
}
}
}
</code></pre>
| [
{
"answer_id": 74351634,
"author": "BigBen",
"author_id": 9245853,
"author_profile": "https://Stackoverflow.com/users/9245853",
"pm_score": 3,
"selected": true,
"text": "If TypeOf Selection Is Range Then\n Select Case selectedIndex\n Case 0\n Selection.Font.Color = RGB(3, 3, 3)\n Case 1\n Selection.Font.Color = RGB(5, 5, 5) \n Case 2\n Selection.Font.Color = RGB(10, 10, 10)\n Case 3\n Selection.Font.Color = RGB(50, 254, 225) \n Case 4\n Selection.Font.Color = RGB(57, 69, 251)\n Case 5\n Selection.Font.Color = RGB(154, 154, 154)\n Case 6\n Selection.Font.Color = RGB(228, 228, 228)\n Case 7\n Selection.Font.Color = RGB(62, 0, 175)\n Case 8\n Selection.Font.Color = RGB(73, 252, 156)\n End Select\nEnd If\n"
},
{
"answer_id": 74351683,
"author": "Péter Forgó",
"author_id": 13406526,
"author_profile": "https://Stackoverflow.com/users/13406526",
"pm_score": 0,
"selected": false,
"text": "Public Sub Font_OnAction( _\n ByRef Control As Office.IRibbonControl, _\n ByRef galleryID As String, _\n ByRef selectedIndex As Integer)\n\nDim myRange As Range\nDim vColor As Variant\n\n Application.ScreenUpdating = False\n Set myRange = Selection\n Select Case selectedIndex\n Case 0: vColor = RGB(3, 3, 3)\n Case 1: vColor = RGB(5, 5, 5)\n Case 2: vColor = RGB(10, 10, 10)\n Case 3: vColor = RGB(50, 254, 225)\n ' OTHER CASES...\n End Select\n myRange.Font.Color = vColor\n Application.ScreenUpdating = True\nEnd Sub\n"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74351555",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/796060/"
] |
74,351,568 | <p>Consider data frame below</p>
<pre><code>df <- data.frame(a=c("Y", "Y","N", "Y", "N", "N"),
b = c(200, 1,1.4,1.3,2,1.6),
c = c(200,-200,10,12,14,15),
d = c("f","f","m", "m","m","m"))
a b c d
1 Y 200.0 200 f
2 Y 1.0 -200 f
3 N 1.4 10 m
4 Y 1.3 12 m
5 N 2.0 14 m
6 N 1.6 15 m
</code></pre>
<p>I want to trim data frame such that rows with values less than 1 percentile and greater than 99 percentile from the numeric columns are removed.</p>
<pre><code> a b c d
1 N 1.4 10 m
2 Y 1.3 12 m
3 N 2.0 14 m
4 N 1.6 15 m
</code></pre>
<p>I can remove top and bottom undesired values, when categorical variables are not present.</p>
<pre><code>df %>% dplyr::select(is.numeric) %>%
filter_all(all_vars(between(., quantile(., .01), quantile(., .99))))
</code></pre>
<p>but I do not know how to do the job while keeping categorical columns. any help or hint with is appreciated.</p>
| [
{
"answer_id": 74351653,
"author": "akrun",
"author_id": 3732271,
"author_profile": "https://Stackoverflow.com/users/3732271",
"pm_score": 2,
"selected": true,
"text": "if_all"
},
{
"answer_id": 74351920,
"author": "Ric Villalba",
"author_id": 6912817,
"author_profile": "https://Stackoverflow.com/users/6912817",
"pm_score": 0,
"selected": false,
"text": "df[findInterval(1:nrow(df), quantile(1:nrow(df),c(.01, 0.99)))==1,]\n"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74351568",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16354132/"
] |
74,351,588 | <p>I'm using a transaction to see how long a device is RFM mode and the duration field increases with each table row. How I think it should work is that while the field is 'yes' it would calculate the duration that all events equal 'yes', but I have a lot of superfluous data that shouldn't be there IMO.
I only want to keep the largest duration event so I want to compare the current events duration to the next events duration and if its smaller than the current event, keep the current event.</p>
<pre><code>index=crowdstrike sourcetype=crowdstrike:device:json
| transaction falcon_device.hostname startswith="falcon_device.reduced_functionality_mode=yes" endswith="falcon_device.reduced_functionality_mode=no"
| table _time duration
</code></pre>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>_time</th>
<th>duration</th>
</tr>
</thead>
<tbody>
<tr>
<td>2022-10-28 06:07:45</td>
<td>888198</td>
</tr>
<tr>
<td>2022-10-28 05:33:44</td>
<td>892400</td>
</tr>
<tr>
<td>2022-10-28 04:57:44</td>
<td>896360</td>
</tr>
<tr>
<td>2022-08-22 18:25:53</td>
<td>3862</td>
</tr>
<tr>
<td>2022-08-22 18:01:53</td>
<td>7703</td>
</tr>
<tr>
<td>2022-08-22 17:35:53</td>
<td>11543</td>
</tr>
</tbody>
</table>
</div>
<p>In the data above the duration goes from 896360 to 3862, and can happen on any date, and the duration runs in cycles like that where it increases until it starts over. So in the comparison I would keep the event at the 10-28 inflection point and so on at all other inflection points throughout the dataset.
How would I construct that multi event comparison?</p>
| [
{
"answer_id": 74351653,
"author": "akrun",
"author_id": 3732271,
"author_profile": "https://Stackoverflow.com/users/3732271",
"pm_score": 2,
"selected": true,
"text": "if_all"
},
{
"answer_id": 74351920,
"author": "Ric Villalba",
"author_id": 6912817,
"author_profile": "https://Stackoverflow.com/users/6912817",
"pm_score": 0,
"selected": false,
"text": "df[findInterval(1:nrow(df), quantile(1:nrow(df),c(.01, 0.99)))==1,]\n"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74351588",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3567091/"
] |
74,351,624 | <p>I would like to have a chart that connects missing points by a line, but not show a symbol at the missing point. Here is some code that creates some test data and produces a chart, but I would like a (id=B) green line joining points 4 and 6 with a straight line, but no green triangle at time 5. I did try <code>geom_path</code> instead of <code>geom_line</code>, but nothing much changed. Thanks</p>
<pre><code>library(ggplot2)
set.seed(1)
x <- rep(seq(1:10), 3)
y <- c(runif(10), runif(10) + 1, runif(10) + 2)
group <- c(rep("A", 10), rep("B", 10), rep("C", 10))
df <- data.frame(cbind(group, x, y))
df$x <- as.numeric(df$x)
df$y <- as.numeric(df$y)
df[15,]$y <- NA
ggplot(data=df, aes(x=x, y=y, group=group)) +
geom_line(aes(colour=group))+
geom_point(aes(colour=group, shape=group))+
scale_shape_manual(values = c(1:3)) +
theme(legend.position="bottom")
</code></pre>
| [
{
"answer_id": 74351704,
"author": "zephryl",
"author_id": 17303805,
"author_profile": "https://Stackoverflow.com/users/17303805",
"pm_score": 3,
"selected": true,
"text": "NA"
},
{
"answer_id": 74351719,
"author": "Curt F.",
"author_id": 4480692,
"author_profile": "https://Stackoverflow.com/users/4480692",
"pm_score": 1,
"selected": false,
"text": "library(tidyverse)\n\n# form some data\nset.seed(1)\nx <- rep(seq(1:10), 3)\ny <- c(runif(10), runif(10) + 1, runif(10) + 2)\ngroup <- c(rep(\"A\", 10), rep(\"B\", 10), rep(\"C\", 10))\n\ndf <- tibble(group=group, x = x, y = y)\n\n# add an NA\ndf[15,]$y <- NA\n\n# plot with a gap where the NA is\np1 <- # p1 fails because of NA \n ggplot(data=df, aes(x=x, y=y, group=group)) +\n geom_line(aes(colour=group))+\n geom_point(aes(colour=group, shape=group))+\n scale_shape_manual(values = c(1:3)) +\n theme(legend.position=\"bottom\")\n\n# plot with no gap\np2 <- p1 %+% {df %>% na.omit()} # p2 does what you want\n\np1\n\np2\n"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74351624",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5770273/"
] |
74,351,625 | <p>Ideally, for populate to work during queries in mongoose, both the schemas of that which is been populated and the calling schema needs to be imported in same file under same repo.</p>
<p>Now, I have a scenario where a schema called <code>AuthorSchema</code> was created by another internal micro-service in another repo which is pointing to the same database as my own service and I wish to populate it during my queries.</p>
<p>Is there a way to automatically decode the <code>AuthorSchema</code> from the <code>author</code> collection name after I've connected to the database?</p>
<p>E.g</p>
<pre><code>let posts = await Post.find({})
.populate("author", 'first_name last_name _id').limit(10)
</code></pre>
<p>Where I have created <code>postSchema</code> in my own service but <code>authorSchema</code> was created by another micro-service in another repo called <code>author-management-microservice</code> and as such I have no access to that schema.</p>
<p>What I would want is something like:</p>
<pre><code>let AuthorSchema = mongoose.connection.decodeSchemaFromCollectionName('author');
</code></pre>
<p>Such that I can modify my query to something like</p>
<pre><code>let posts = await Post.find({})
.populate({path:"author", model:AuthorSchema, select:'first_name last_name _id'}).limit(10)
</code></pre>
<p>The reason I want something like this is because I have been battling with <code>MissingSchemaError: Schema hasn't been registered for model "Author".</code> whenever I try to populate <code>author</code> and I don't want to copy around duplicate schema files across different micro-services.</p>
| [
{
"answer_id": 74351704,
"author": "zephryl",
"author_id": 17303805,
"author_profile": "https://Stackoverflow.com/users/17303805",
"pm_score": 3,
"selected": true,
"text": "NA"
},
{
"answer_id": 74351719,
"author": "Curt F.",
"author_id": 4480692,
"author_profile": "https://Stackoverflow.com/users/4480692",
"pm_score": 1,
"selected": false,
"text": "library(tidyverse)\n\n# form some data\nset.seed(1)\nx <- rep(seq(1:10), 3)\ny <- c(runif(10), runif(10) + 1, runif(10) + 2)\ngroup <- c(rep(\"A\", 10), rep(\"B\", 10), rep(\"C\", 10))\n\ndf <- tibble(group=group, x = x, y = y)\n\n# add an NA\ndf[15,]$y <- NA\n\n# plot with a gap where the NA is\np1 <- # p1 fails because of NA \n ggplot(data=df, aes(x=x, y=y, group=group)) +\n geom_line(aes(colour=group))+\n geom_point(aes(colour=group, shape=group))+\n scale_shape_manual(values = c(1:3)) +\n theme(legend.position=\"bottom\")\n\n# plot with no gap\np2 <- p1 %+% {df %>% na.omit()} # p2 does what you want\n\np1\n\np2\n"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74351625",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15155716/"
] |
74,351,639 | <p>I have some buttons with data-attibutes that are passing to html when they are clicked.
I'm not beeing able to hide the div of .discounts when the value inserted on the data-attibute is equal to 0. Here is my code:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var discounters = document.querySelectorAll(".discount__Topics");
discounters.forEach((index) => {
var buttons = index.querySelectorAll(".form-button");
buttons.forEach(function (item) {
item.addEventListener('click', function(){
var discount = getDiscount(this);
let span = index.querySelector('.discount-amount')
span.innerHTML = '<strong>' + discount+ '</strong>'
});
});
function getDiscount(clicked_element) {
var val = clicked_element.getAttribute("data-discount");
return val;
}
});</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>.discount__Topics {
margin-bottom:20px;
}
.discounts {
background-color: red;
color: white;
display: inline-flex;
margin-bottom:5px;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="discount__Topics">
<div class="discounts"><strong class="discount-amount">38</strong>%</div>
<div class="offers">
<button class="form-button" data-discount="38">Offer 1</button>
<button class="form-button" data-discount="0">Offer 2</button>
<button class="form-button" data-discount="22">Offer 3</button>
<button class="form-button" data-discount="88">Offer 4</button>
</div>
</div>
<div class="discount__Topics">
<div class="discounts"><strong class="discount-amount">12</strong>%</div>
<div class="offers">
<button class="form-button" data-discount="12">Offer 1</button>
<button class="form-button" data-discount="32">Offer 2</button>
<button class="form-button" data-discount="0">Offer 3</button>
<button class="form-button" data-discount="55">Offer 4</button>
</div>
</div></code></pre>
</div>
</div>
</p>
<p>Hope someone can help me.
Many thanks</p>
| [
{
"answer_id": 74351709,
"author": "Alexis",
"author_id": 13986485,
"author_profile": "https://Stackoverflow.com/users/13986485",
"pm_score": 0,
"selected": false,
"text": "element.style.display = \"none\""
},
{
"answer_id": 74351751,
"author": "Amirhossein Sefati",
"author_id": 11856099,
"author_profile": "https://Stackoverflow.com/users/11856099",
"pm_score": 0,
"selected": false,
"text": "var discounters = document.querySelectorAll(\".discount__Topics\");\n\ndiscounters.forEach((index) => {\n\n var buttons = index.querySelectorAll(\".form-button\");\n\n buttons.forEach(function (item) {\n item.addEventListener('click', function(){ \n var discount = getDiscount(this);\n let span = index.querySelector('.discount-amount')\n if (discount!=0){ \n document.getElementById(\"firstDiscount\").style.display = \"inline-flex\"\n span.innerHTML = '<strong>' + discount+ '</strong>'\n }else{\n \n document.getElementById(\"firstDiscount\").style.display = \"none\"\n }\n });\n });\n\n function getDiscount(clicked_element) {\n var val = clicked_element.getAttribute(\"data-discount\"); \n return val;\n }\n\n});"
},
{
"answer_id": 74351842,
"author": "Sean",
"author_id": 5351721,
"author_profile": "https://Stackoverflow.com/users/5351721",
"pm_score": 1,
"selected": false,
"text": "[data-discount='0'] {\n display: none;\n}\n"
},
{
"answer_id": 74352161,
"author": "kyllaz",
"author_id": 14185251,
"author_profile": "https://Stackoverflow.com/users/14185251",
"pm_score": 0,
"selected": false,
"text": "var discounters = document.querySelectorAll(\".discount__Topics\");\n\ndiscounters.forEach((index) => {\n\n var buttons = index.querySelectorAll(\".form-button\");\n\n buttons.forEach(function (item) {\n item.addEventListener('click', function(){ \n var discount = getDiscount(this);\n let span = index.querySelector('.discount-amount')\n span.innerHTML = '<strong>' + discount+ '</strong>'\n if (discount !=0){ \n index.querySelector(\".discounts\").style.display = \"inline-flex\"\n } else {\n index.querySelector(\".discounts\").style.display = \"none\"\n }\n });\n });\n\n function getDiscount(clicked_element) {\n var val = clicked_element.getAttribute(\"data-discount\"); \n return val;\n }\n\n});"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74351639",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14185251/"
] |
74,351,647 | <p>I've run into an issue with our current mobile project where our click wont interact with a save button on our device page. This is currently the only scenario we have run into this with so far. I've tried various xpaths/locators including placing coordinates into the xpath itself with no luck. Additionally I noticed that clickable is set to false so I also tried the attribute above the save text, which was set to clickable true and didn't have any luck there either. Any ideas would be welcome! For perspective, I need to be able to click the save button. When it runs, it it says it clicks and attempts our validation, but nothing actually happens on the emulator.</p>
<p>Pom:</p>
<pre><code><project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId></groupId>
<artifactId>framework</artifactId>
<version>0.0.1-SNAPSHOT</version>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<testng.files.location>src/TestSuites/</testng.files.location>
<testng.file>testng.xml</testng.file>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<gridUrl>http://selenium-hub-1.qa.automation.vpc:4444/wd/hub</gridUrl>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.0.0-M3</version>
<configuration>
<suiteXmlFiles>
<suiteXmlFile>${SuiteXmlFile}</suiteXmlFile>
</suiteXmlFiles>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<!-- https://mvnrepository.com/artifact/org.testng/testng -->
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>7.4.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/log4j/log4j -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/commons-io/commons-io -->
<!-- https://mvnrepository.com/artifact/commons-io/commons-io -->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.11.0</version>
</dependency>
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>4.5.0</version>
</dependency>
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-remote-driver</artifactId>
<version>3.6.0</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>5.2.3</version>
</dependency>
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-chrome-driver</artifactId>
<version>4.5.0</version>
</dependency>
<dependency>
<groupId>io.github.bonigarcia</groupId>
<artifactId>webdrivermanager</artifactId>
<version>5.3.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.31</version>
</dependency>
<dependency>
<groupId>io.appium</groupId>
<artifactId>java-client</artifactId>
<version>8.2.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.logging.log4j/log4j-to-slf4j -->
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-to-slf4j</artifactId>
<version>2.19.0</version>
</dependency>
</dependencies>
</project>
</code></pre>
<p>Method:</p>
<pre><code>/**
* Registers a real lock from locations screen
*
* @throws InterruptedException
*/
public void addLock(String serialNumber, String model, String lockName) throws InterruptedException{
logg.info("Adding a device");
withAction.mobileClick(btnAddLock);
logg.info("Add Lock button is clicked");
logg.info("Clicking Scan QR Code button");
withAction.mobileClick(btnScanQRCode);
logg.info("Sending a serial number into the enter serial number manually field");
logg.info("Clicking Enter Serial Number Manually button");
withAction.mobileClick(btnEnterSNManually);
logg.info("Validating Enter serial number is displayed");
withAssert.mobileStringExists(txtEnterSN, "Enter serial number");
withAction.sendText(btnEnterSN, serialNumber);
logg.info("Clicking a model tile");
WebElement element = appiumDriver.findElement(By.xpath("//*[@text='" + model + "']"));
withAction.mobileClick(element);
logg.info("Clicking continue button");
withAction.mobileClick(btnContinue);
logg.info("Validating the next screen that is showing You are almost done! text");
withAssert.mobileStringExists(txtAlmostDone, "You are almost done!");
logg.info("Sending a name to a lock");
withAction.sendText(btnLockName, lockName);
withAction.mobileBack();
logg.info("Validating save button");
withAssert.mobileStringExists(txtSave, "Save");
Thread.sleep(3000);
logg.info("Clicking save lock button");
withAction.mobileClick(btnSaveLock); //this is where it needs to click
logg.info("Validating success message");
withAssert.mobileStringExists(txtSuccess, "Success!");
logg.info("Clicking next button");
withAction.mobileClick(btnNext);
logg.info("Clicking done button");
withAction.mobileClick(btnDone);
logg.info("Validating Lock Setup Not Finished message");
withAssert.mobileStringExists(txtSuccess, "Lock Setup Not Finished");
logg.info("Clicking I'll connect my lock later button");
withAction.mobileClick(btnConnectLater);
}
</code></pre>
<p>MobileClick Method</p>
<pre><code>/**
* clicks an element
*
* @param element
*/
public void mobileClick(WebElement element) {
logg.info("Clicking an element by xpath");
WebDriverWait wait = new WebDriverWait(appiumDriver, Duration.ofSeconds(30));
wait.until(ExpectedConditions.elementToBeClickable(element)).click();
}
</code></pre>
<p><a href="https://i.stack.imgur.com/aquTG.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/aquTG.png" alt="App View" /></a></p>
<p><a href="https://i.stack.imgur.com/bU09C.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/bU09C.png" alt="Appium Inspector" /></a></p>
| [
{
"answer_id": 74351709,
"author": "Alexis",
"author_id": 13986485,
"author_profile": "https://Stackoverflow.com/users/13986485",
"pm_score": 0,
"selected": false,
"text": "element.style.display = \"none\""
},
{
"answer_id": 74351751,
"author": "Amirhossein Sefati",
"author_id": 11856099,
"author_profile": "https://Stackoverflow.com/users/11856099",
"pm_score": 0,
"selected": false,
"text": "var discounters = document.querySelectorAll(\".discount__Topics\");\n\ndiscounters.forEach((index) => {\n\n var buttons = index.querySelectorAll(\".form-button\");\n\n buttons.forEach(function (item) {\n item.addEventListener('click', function(){ \n var discount = getDiscount(this);\n let span = index.querySelector('.discount-amount')\n if (discount!=0){ \n document.getElementById(\"firstDiscount\").style.display = \"inline-flex\"\n span.innerHTML = '<strong>' + discount+ '</strong>'\n }else{\n \n document.getElementById(\"firstDiscount\").style.display = \"none\"\n }\n });\n });\n\n function getDiscount(clicked_element) {\n var val = clicked_element.getAttribute(\"data-discount\"); \n return val;\n }\n\n});"
},
{
"answer_id": 74351842,
"author": "Sean",
"author_id": 5351721,
"author_profile": "https://Stackoverflow.com/users/5351721",
"pm_score": 1,
"selected": false,
"text": "[data-discount='0'] {\n display: none;\n}\n"
},
{
"answer_id": 74352161,
"author": "kyllaz",
"author_id": 14185251,
"author_profile": "https://Stackoverflow.com/users/14185251",
"pm_score": 0,
"selected": false,
"text": "var discounters = document.querySelectorAll(\".discount__Topics\");\n\ndiscounters.forEach((index) => {\n\n var buttons = index.querySelectorAll(\".form-button\");\n\n buttons.forEach(function (item) {\n item.addEventListener('click', function(){ \n var discount = getDiscount(this);\n let span = index.querySelector('.discount-amount')\n span.innerHTML = '<strong>' + discount+ '</strong>'\n if (discount !=0){ \n index.querySelector(\".discounts\").style.display = \"inline-flex\"\n } else {\n index.querySelector(\".discounts\").style.display = \"none\"\n }\n });\n });\n\n function getDiscount(clicked_element) {\n var val = clicked_element.getAttribute(\"data-discount\"); \n return val;\n }\n\n});"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74351647",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9553478/"
] |
74,351,687 | <p>I've got a ViewModel which conforms the <code>ObservableObject</code> protocol.</p>
<p>This ViewModel holds a enum variable.</p>
<pre><code>class DeviceViewModel:ObservableObject {
enum ConnectionState: Equatable, CaseIterable {
case NoConnected
case Connected
}
@Published var connectionState: ConnectionState = .NoConnected
}
</code></pre>
<p>I also got a simple view that it will change the text depending of that enum:</p>
<pre><code>struct ContentView: View {
let viewModel: DeviceViewModel
var body: some View {
if viewModel.connectionState != .NoConnected {
Text("connected")
} else {
Text("No connected")
}
}
}
</code></pre>
<p>I've noticed that if the enum <code>connectionState</code> changes it won't trigger the view to refresh.</p>
<p>To test this I've added a init method in the ViewModel with the following <code>asyncAfter</code>:</p>
<pre><code> init() {
DispatchQueue.main.asyncAfter(deadline: .now() + 5) { [weak self] in
guard let self = self else {
return
}
self.connectionState = .Connected
print("self.connectionState: \(self.connectionState)")
}
}
</code></pre>
<p>Any idea what I'm missing?</p>
<p>Thanks</p>
| [
{
"answer_id": 74351709,
"author": "Alexis",
"author_id": 13986485,
"author_profile": "https://Stackoverflow.com/users/13986485",
"pm_score": 0,
"selected": false,
"text": "element.style.display = \"none\""
},
{
"answer_id": 74351751,
"author": "Amirhossein Sefati",
"author_id": 11856099,
"author_profile": "https://Stackoverflow.com/users/11856099",
"pm_score": 0,
"selected": false,
"text": "var discounters = document.querySelectorAll(\".discount__Topics\");\n\ndiscounters.forEach((index) => {\n\n var buttons = index.querySelectorAll(\".form-button\");\n\n buttons.forEach(function (item) {\n item.addEventListener('click', function(){ \n var discount = getDiscount(this);\n let span = index.querySelector('.discount-amount')\n if (discount!=0){ \n document.getElementById(\"firstDiscount\").style.display = \"inline-flex\"\n span.innerHTML = '<strong>' + discount+ '</strong>'\n }else{\n \n document.getElementById(\"firstDiscount\").style.display = \"none\"\n }\n });\n });\n\n function getDiscount(clicked_element) {\n var val = clicked_element.getAttribute(\"data-discount\"); \n return val;\n }\n\n});"
},
{
"answer_id": 74351842,
"author": "Sean",
"author_id": 5351721,
"author_profile": "https://Stackoverflow.com/users/5351721",
"pm_score": 1,
"selected": false,
"text": "[data-discount='0'] {\n display: none;\n}\n"
},
{
"answer_id": 74352161,
"author": "kyllaz",
"author_id": 14185251,
"author_profile": "https://Stackoverflow.com/users/14185251",
"pm_score": 0,
"selected": false,
"text": "var discounters = document.querySelectorAll(\".discount__Topics\");\n\ndiscounters.forEach((index) => {\n\n var buttons = index.querySelectorAll(\".form-button\");\n\n buttons.forEach(function (item) {\n item.addEventListener('click', function(){ \n var discount = getDiscount(this);\n let span = index.querySelector('.discount-amount')\n span.innerHTML = '<strong>' + discount+ '</strong>'\n if (discount !=0){ \n index.querySelector(\".discounts\").style.display = \"inline-flex\"\n } else {\n index.querySelector(\".discounts\").style.display = \"none\"\n }\n });\n });\n\n function getDiscount(clicked_element) {\n var val = clicked_element.getAttribute(\"data-discount\"); \n return val;\n }\n\n});"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74351687",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/426180/"
] |
74,351,690 | <p>I'm trying to use Nivo charts with typescript and I'm not sure how to define the type of data Nivo expects for their Bar Chart. (<a href="https://nivo.rocks" rel="nofollow noreferrer">https://Nivo.Rocks</a>)</p>
<p>I've been trying to use</p>
<ol>
<li>Object Index Signature ... <code>{[Key: string]: string;}</code></li>
<li>Record utility type ... <code>Record<string, string></code></li>
</ol>
<p>A snippet of example data from Nivo is as folllows:</p>
<pre><code>data = [
{
country: 'AD',
'hot dog': 111,
'hot dogColor': 'hsl(168, 70%, 50%)',
burger: 19,
burgerColor: 'hsl(123, 70%, 50%)',
sandwich: 161,
sandwichColor: 'hsl(91, 70%, 50%)',
kebab: 199,
kebabColor: 'hsl(347, 70%, 50%)',
fries: 153,
friesColor: 'hsl(346, 70%, 50%)',
donut: 41,
donutColor: 'hsl(96, 70%, 50%)',
}
];
</code></pre>
<p>I attempted things similar to this...</p>
<pre><code>export type NivoBarData = {
[Key: string]: string;
[Key: string]: number;
nodeKeyValue?: NivoBarNodeValue;
nodeColor?: NivoBarNodeColor;
};
export type NivoBarTitle = Record<string, string>;
export type NivoBarNodeColor = { [Key: string]: string };
export type NivoBarNodeValue = { [Key: string]: number };
</code></pre>
| [
{
"answer_id": 74351781,
"author": "GatesKennedy",
"author_id": 9380773,
"author_profile": "https://Stackoverflow.com/users/9380773",
"pm_score": 0,
"selected": false,
"text": "BarDatum"
},
{
"answer_id": 74352061,
"author": "caTS",
"author_id": 18244921,
"author_profile": "https://Stackoverflow.com/users/18244921",
"pm_score": 2,
"selected": true,
"text": "Color"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74351690",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9380773/"
] |
74,351,697 | <p>my output file has random data when I write something on it,I checked multiple sources of writing object on a file and this seems correct still can't enter the right data</p>
<p><a href="https://i.stack.imgur.com/SOiyH.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/SOiyH.png" alt="enter image description here" /></a></p>
<pre><code>
#include<bits/stdc++.h>
using namespace std;
namespace fs = std::filesystem;
class Events{
char eventName[90];
public:
void setEventName(){
cout<<"set event name ";
cin>>eventName;
}
};
class EventFunctions:public Events{
public:
void WriteEvent(){
Events obj;
obj.setEventName();
ofstream outf;
outf.open("hello.txt");
outf.write((char *)&obj,sizeof(obj));
outf.close();
}
};
int main(){
EventFunctions ee;
ee.WriteEvent();
}
</code></pre>
<p>using devc++
<br>
MinGW GCC 11.2.0</p>
| [
{
"answer_id": 74351828,
"author": "Mark Ransom",
"author_id": 5987,
"author_profile": "https://Stackoverflow.com/users/5987",
"pm_score": 2,
"selected": false,
"text": "outf.write(&obj.eventName, strlen(obj.eventName));\n"
},
{
"answer_id": 74351873,
"author": "Silvio Mayolo",
"author_id": 2288659,
"author_profile": "https://Stackoverflow.com/users/2288659",
"pm_score": 2,
"selected": false,
"text": "write"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74351697",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11199128/"
] |
74,351,715 | <p>I'm coding ( Slice ) from Redux, but I need the ( initialState ) to be NULL, what's the best way to do this? I tried inserting the comma but it didn't work.</p>
<p><strong>My Code:</strong></p>
<pre><code>import { createSlice } from '@reduxjs/toolkit';
export const slice = createSlice({
name: 'initial',
initialState,
reducers: {
ADDS(state, actions) {
return {
...state,
product: actions.payload,
}
}
}
});
export const { ADDS } = slice.actions;
export default slice.reducer;
</code></pre>
<p><strong>My Error:</strong></p>
<pre><code>Uncaught ReferenceError: initialState is not defined
at ./src/redux/slice.js (slice.js:6:1)
at options.factory (react refresh:6:1)
at __webpack_require__ (bootstrap:24:1)
at fn (hot module replacement:62:1)
at ./src/App.js (bundle.js:21:70)
at options.factory (react refresh:6:1)
at __webpack_require__ (bootstrap:24:1)
at fn (hot module replacement:62:1)
at ./src/index.js (UI.jsx:3:1)
at options.factory (react refresh:6:1)
</code></pre>
<p>Thanks</p>
| [
{
"answer_id": 74351828,
"author": "Mark Ransom",
"author_id": 5987,
"author_profile": "https://Stackoverflow.com/users/5987",
"pm_score": 2,
"selected": false,
"text": "outf.write(&obj.eventName, strlen(obj.eventName));\n"
},
{
"answer_id": 74351873,
"author": "Silvio Mayolo",
"author_id": 2288659,
"author_profile": "https://Stackoverflow.com/users/2288659",
"pm_score": 2,
"selected": false,
"text": "write"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74351715",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17016241/"
] |
74,351,720 | <p>When I hover the SVG, both SVG and text of link change color. But when I hover the text, only the text changes color. Is there a way to combine both as a kind of one link area?</p>
<p>I would like to get a kind of field, where both SVG and text change color, when I hover over one of them. So the user sees that it belongs together. I experimented with <span> or <div>, but don't really have an idea where to start. I'm pretty much a beginner and appreciate your help.</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>.svg-social-menu li {
display: inline-block;
list-style-type: none;
}
.svg-social-menu li::before {
display: none;
}
.svg-social-menu svg {
fill: #6d9dbd;
}
.svg-social-menu svg:hover {
fill: #4c4c4c;
}
.svg-social-menu a {
color: #6d9dbd;
text-decoration: none;
}
.svg-social-menu li {
background: none;
border: none;
box-shadow: none;
}
.svg-social-menu a:hover {
color: #4c4c4c;
}
.svg-social-menu a:visited {
fill: #6d9dbd;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul class="svg-social-menu">
<li>
<a href="https://www.newsletter.de" class="svg-social-menu" alt="Newsletter-Logo">
<svg version="1.1" id="Newsletter" xmlns="http://www.w3.org/2000/svg" class="svg-social-menu" alt="Newsletter-Logo" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" viewBox="0 0 491.84 491.84" style="enable-background:new 0 0 491.84 491.84;"
xml:space="preserve" width="35" height="35">
<title>Newsletter</title>
<desc>Link zum Newsletter</desc>
<g>
<g>
<path d="M481.64,205.12l-123-90.7c-8.3-6.3-21.9-5.2-28.1,4.2c-6.3,8.3-5.2,21.9,4.2,28.1l103.1,76l-192.9,148.2l-191.8-148.3
l100.9-75.9c9.4-6.3,10.4-18.8,4.2-28.1c-6.3-9.4-18.8-10.4-28.1-4.2l-122,91.7c-5.9,3.9-8.5,10.3-8.1,16.8c0,0.4,0,0.8,0,1.1
v245.9c0,14.3,10.4,20.8,20.8,20.8h448.1c18.4,0,22.9-8.6,22.9-20.8v-245.9C491.84,215.22,483.94,206.62,481.64,205.12z
M41.74,266.52l107.3,82.6l-107.3,80.5C41.74,429.62,41.74,266.52,41.74,266.52z M81.74,450.12l101.7-75l49,37.5
c7.3,5.2,17.7,5.2,25,0l49-38.6l101.4,76.1H81.74z M449.14,430.32l-108.4-81.3l108.4-83.4V430.32z"></path> <path d="M167.84,209.42l63.6,56.3c11.5,9.3,23.3,4.2,27.1,1l63.6-57.3c8.3-8.3,9.4-20.8,2.1-29.2s-20.8-9.4-29.2-2.1l-29.2,25.5
V21.92c0-11.5-9.4-20.8-20.8-20.8s-20.8,9.4-20.8,20.8v181.8l-29.2-25.5c-8.3-7.3-21.9-6.3-29.2,2.1S159.44,202.12,167.84,209.42z">
</path>
</g>
</g>
</svg>
<b>Newsletter</b>
</a>
</li>
</ul></code></pre>
</div>
</div>
</p>
| [
{
"answer_id": 74351909,
"author": "j08691",
"author_id": 616443,
"author_profile": "https://Stackoverflow.com/users/616443",
"pm_score": 3,
"selected": true,
"text": ".svg-social-menu svg:hover "
},
{
"answer_id": 74352524,
"author": "herrstrietzel",
"author_id": 15015675,
"author_profile": "https://Stackoverflow.com/users/15015675",
"pm_score": 0,
"selected": false,
"text": "currentColor"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74351720",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20442845/"
] |
74,351,726 | <p>I'm trying to calculate paths for a pip install from a internal devpi server. I'm running a self-hosted runner on a Windows server virtual machine. I'm trying to install the latest PIP package to the tool directory by calculating the path as follows;</p>
<pre><code> - name: pip install xmlcli
env:
MYTOOLS: ${{ runner.tool_cache }}\mytools
run: |
echo "${{ runner.tool_cache }}"
$env:MYTOOLS
pip install --no-cache-dir --upgrade mytools.xmlcli --target=$env:MYTOOLS -i ${{secrets.PIP_INDEX_URL}}
echo "XMLCLI={$env:MYTOOLS}\mytools\xmlcli" >> $GITHUB_ENV`
- name: test xmlcli
run: echo "${{ env.XMLCLI }}"
</code></pre>
<p>As you can see; I've had some noob issues trying to output the env variable in windows. I came to the conclusion that under windows; the "run" command is being sent via powershell. Hence the "$env:MYTOOLS" usage.</p>
<p>The problem is the echo "XMLCLI=..." back to the git_env doesn't seem to be working properly as the test xmlcli step returns empty string.</p>
<p>I'm pretty sure I tried several different iterations of the echo command; but, haven't been successful.
Is there a video/docs/something that will clearly lays out the usage of "path arithmetic" from within the github action environment?</p>
| [
{
"answer_id": 74351909,
"author": "j08691",
"author_id": 616443,
"author_profile": "https://Stackoverflow.com/users/616443",
"pm_score": 3,
"selected": true,
"text": ".svg-social-menu svg:hover "
},
{
"answer_id": 74352524,
"author": "herrstrietzel",
"author_id": 15015675,
"author_profile": "https://Stackoverflow.com/users/15015675",
"pm_score": 0,
"selected": false,
"text": "currentColor"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74351726",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12345332/"
] |
74,351,742 | <p>I'm trying to do this:</p>
<pre><code>services.AddDbContext<AppDbContext>(
opt => opt.UseSqlServer(
configuration.GetConnectionString("AppConnectionString"),
x => x.UseNetTopologySuite(),
options => options.EnableRetryOnFailure())); // Here's where it fails
</code></pre>
<p>But I'm getting this:
<code>No overload for method UseSqlServer takes 3 arguments</code></p>
<p>I understand that however I don't know how to do it any other way besides going down a path I don't know.</p>
| [
{
"answer_id": 74351909,
"author": "j08691",
"author_id": 616443,
"author_profile": "https://Stackoverflow.com/users/616443",
"pm_score": 3,
"selected": true,
"text": ".svg-social-menu svg:hover "
},
{
"answer_id": 74352524,
"author": "herrstrietzel",
"author_id": 15015675,
"author_profile": "https://Stackoverflow.com/users/15015675",
"pm_score": 0,
"selected": false,
"text": "currentColor"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74351742",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13445783/"
] |
74,351,766 | <p>What's the wrong in my code?</p>
<p>I used 'cors' package to pass cors policy, but it doesn't work.</p>
<p>My server code is:</p>
<pre><code>const express = require("express");
const app = express();
require("dotenv").config();
const bodyParser = require("body-parser");
const cors = require("cors");
const { routes } = require("./routes/auth.routes");
const stripe = require("./routes/stripe");
const ObjectId = require("mongodb").ObjectId;
require('./db/db')();
app.use("/auth", routes)
const port = 5000;
app.use(cors());
app.use(bodyParser.urlencoded({ extended: true }));
</code></pre>
<p><a href="https://i.stack.imgur.com/uPTSu.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/uPTSu.png" alt="Cors error" /></a></p>
| [
{
"answer_id": 74351897,
"author": "ruriko123",
"author_id": 16617908,
"author_profile": "https://Stackoverflow.com/users/16617908",
"pm_score": 0,
"selected": false,
"text": " \"proxy\": \"http://localhost:5000\"\n"
},
{
"answer_id": 74351940,
"author": "BISHAL GOON",
"author_id": 20345598,
"author_profile": "https://Stackoverflow.com/users/20345598",
"pm_score": 1,
"selected": false,
"text": "const express = require(\"express\");\nconst app = express();\nrequire(\"dotenv\").config();\n\nconst bodyParser = require(\"body-parser\");\nconst cors = require(\"cors\");\nconst { routes } = require(\"./routes/auth.routes\");\nconst stripe = require(\"./routes/stripe\");\nconst ObjectId = require(\"mongodb\").ObjectId;\n\nrequire('./db/db')();\n\napp.use(cors());\napp.use(bodyParser.urlencoded({ extended: true }));\n\napp.use(\"/auth\", routes)\n\nconst port = 5000;\n"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74351766",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16815849/"
] |
74,351,830 | <p>I have a sales database and I want to display the least used payment method. From the query that displays the times each payment method is used, I want to display the name of the method and how many times it was used only.</p>
<p>To display the payment methods and counts I used
SELECT Payment, COUNT(Payment) AS Occ
FROM SALES
GROUP BY Payment
ORDER BY Payment</p>
<p>This resulted in the following output:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Payment</th>
<th>Occ</th>
</tr>
</thead>
<tbody>
<tr>
<td>Paypal</td>
<td>123</td>
</tr>
<tr>
<td>Credit</td>
<td>352</td>
</tr>
</tbody>
</table>
</div>
<p>I wanted to display Paypal only so I used the following:</p>
<p>SELECT Payment, MIN(Occ) AS Frequency
FROM (SELECT Payment, COUNT(Payment) AS Occ
FROM SALES
GROUP BY Payment
ORDER BY Payment)</p>
<p>But that gave an error</p>
<p>The desired result is</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Payment</th>
<th>Frequency</th>
</tr>
</thead>
<tbody>
<tr>
<td>Paypal</td>
<td>123</td>
</tr>
</tbody>
</table>
</div> | [
{
"answer_id": 74351897,
"author": "ruriko123",
"author_id": 16617908,
"author_profile": "https://Stackoverflow.com/users/16617908",
"pm_score": 0,
"selected": false,
"text": " \"proxy\": \"http://localhost:5000\"\n"
},
{
"answer_id": 74351940,
"author": "BISHAL GOON",
"author_id": 20345598,
"author_profile": "https://Stackoverflow.com/users/20345598",
"pm_score": 1,
"selected": false,
"text": "const express = require(\"express\");\nconst app = express();\nrequire(\"dotenv\").config();\n\nconst bodyParser = require(\"body-parser\");\nconst cors = require(\"cors\");\nconst { routes } = require(\"./routes/auth.routes\");\nconst stripe = require(\"./routes/stripe\");\nconst ObjectId = require(\"mongodb\").ObjectId;\n\nrequire('./db/db')();\n\napp.use(cors());\napp.use(bodyParser.urlencoded({ extended: true }));\n\napp.use(\"/auth\", routes)\n\nconst port = 5000;\n"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74351830",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20443347/"
] |
74,351,833 | <p>I have a class Person with the attributes name and level</p>
<pre><code>class Person:
def __init__(self, name, level):
self.name = name
self.level = level
</code></pre>
<p>let's say i have a bunch of objects from that class with different attributes</p>
<pre><code>p1 = Person("person1", "5")
p2 = Person("person2", "10")
p3 = Person("person2", "15")
</code></pre>
<p>And a list containing the name of all those objects</p>
<pre><code>people_list = ["p1","p2","p3"]
</code></pre>
<p>i want to make a function on the Person class, that finds and prints all the levels
This is what i made so far.</p>
<pre><code>def lvlFinder(self, people_list):
for x, item in enumerate(people_list):
y = getattr(p1, "level")
print(y)
</code></pre>
<p>Is there a way so instead of p1 in getattr(p1,"level") i could have a variable that changes to p2 and so on as it loops.
I tried many different ways, but honestly i don't even know if anything is right.
Is there a better way of doing this?</p>
| [
{
"answer_id": 74351984,
"author": "quamrana",
"author_id": 4834,
"author_profile": "https://Stackoverflow.com/users/4834",
"pm_score": 2,
"selected": true,
"text": "people_list = [p1, p2, p3]\n"
},
{
"answer_id": 74352024,
"author": "user99999",
"author_id": 20070120,
"author_profile": "https://Stackoverflow.com/users/20070120",
"pm_score": 0,
"selected": false,
"text": "people_list"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74351833",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20443179/"
] |
74,351,838 | <p>Im trying to just capture the following string: <code>u00</code> because i need to replace it to <code>\u00</code>.</p>
<p>Sometimes this characters appear with a <code>\</code> before, in that case, i don't want to capture it.
At other times, the simbol is <code>"</code>, i want to capture it, but just the <code>u00</code>, not <code>"u00</code></p>
<p>Im trying this:</p>
<pre><code>file_modified = re.sub(r'[^\\|^\s](u00)', r'\\u00', original_file)
</code></pre>
<p>Im capturing the <code>"</code> and i don't know how to skip it, i just want to capture <code>u00</code></p>
| [
{
"answer_id": 74351987,
"author": "craigb",
"author_id": 20236884,
"author_profile": "https://Stackoverflow.com/users/20236884",
"pm_score": 0,
"selected": false,
"text": "r'(?<!\\\\)(u00)'"
},
{
"answer_id": 74352147,
"author": "Wiktor Stribiżew",
"author_id": 3832970,
"author_profile": "https://Stackoverflow.com/users/3832970",
"pm_score": 2,
"selected": true,
"text": "file_modified = re.sub(r'\\\\?u00', r'\\\\u00', original_file)\n"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74351838",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12725687/"
] |
74,351,855 | <p>I have a data model with two tables sharing the same columns.
I have merged the tables using the prefixes "Old." and "New."
I'd like to add a calculated column for each column that shows if the values are different with the name like "Column_IsDifferent" and a boolean value of true or false.</p>
<p>I have already found out that you can add multiple columns by using List.Accumulate. But for some reason my code seems not to work as expected:</p>
<pre><code>= List.Accumulate(List.Select(Table.ColumnNames(#"Extend joined table"), each Text.StartsWith(_, "New")), #"Extend joined table", (state, current) => Table.AddColumn(state, Text.RemoveRange(current, 0, 4) & "_IsDifferent", each Table.Column(state, current) <> Table.Column(state, "Old." & Text.RemoveRange(current, 0, 4)), type logical))
</code></pre>
<p>Basically, it takes forever to load data and I don't get an error message...</p>
<p>I suspect there is something wrong with this part:</p>
<pre><code>Table.Column(state, current) <> Table.Column(state, "Old." & Text.RemoveRange(current, 0, 4))
</code></pre>
| [
{
"answer_id": 74353367,
"author": "horseyride",
"author_id": 9264230,
"author_profile": "https://Stackoverflow.com/users/9264230",
"pm_score": 0,
"selected": false,
"text": "let Source = Excel.CurrentWorkbook(){[Name=\"Table1\"]}[Content],\n#\"Added Index\" = Table.AddIndexColumn(Source, \"Index\", 0, 1, Int64.Type),\n#\"Unpivoted Other Columns\" = Table.UnpivotOtherColumns(#\"Added Index\", {\"Index\"}, \"Attribute\", \"Value\"),\n#\"Duplicated Column\" = Table.DuplicateColumn(#\"Unpivoted Other Columns\", \"Attribute\", \"Attribute - Copy\"),\n#\"Split Column by Delimiter\" = Table.SplitColumn(#\"Duplicated Column\", \"Attribute - Copy\", Splitter.SplitTextByDelimiter(\".\", QuoteStyle.Csv), {\"A1\", \"A2\"}),\n#\"Grouped Rows\" = Table.Group(#\"Split Column by Delimiter\", {\"Index\", \"A2\"}, {{\"data\", each \n let compare = if _{0}[Value] = _{1}[Value] then \"match\" else \"nomatch\"\n in Table.InsertRows( _,1,{[Index = _{0}[Index], Attribute = \"Delta.\"&_{0}[A2], Value=compare, A1=\"Delta\", A2=_{0}[A2]]})\n, type table }}),\n#\"Expanded data\" = Table.ExpandTableColumn(#\"Grouped Rows\", \"data\", {\"Attribute\", \"Value\" }, {\"Attribute\", \"Value\"}),\n#\"Removed Columns\" = Table.RemoveColumns(#\"Expanded data\",{\"A2\"}),\n#\"Pivoted Column\" = Table.Pivot(#\"Removed Columns\", List.Distinct(#\"Removed Columns\"[Attribute]), \"Attribute\", \"Value\"),\n#\"Removed Columns1\" = Table.RemoveColumns(#\"Pivoted Column\",{\"Index\"})\nin #\"Removed Columns1\"\n"
},
{
"answer_id": 74353763,
"author": "kami",
"author_id": 5986209,
"author_profile": "https://Stackoverflow.com/users/5986209",
"pm_score": -1,
"selected": false,
"text": "each Table.Column(state, current) <> Table.Column(state, \"Old.\" & Text.RemoveRange(current, 0, 4))\n"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74351855",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5986209/"
] |
74,351,882 | <p>I am struggling with getting SSRS to have a domain name without naming the virtual directory. To give an example.</p>
<p>I currently have reporting.domain.com/reports working fine. It's great. However, I want to eliminate the /reports, and I want to use reports.domain.com.</p>
<p>I have tried to google this, but I haven't found any instructions on getting this done.</p>
<p>Does anyone have any idea what I can do? This is for INTERNAL purposes and not public web purposes.</p>
<p>Reiteration:</p>
<p>reporting.domain.com/reports (currently works fine)
to
reports.domain.com (I want end users to use this)</p>
| [
{
"answer_id": 74353367,
"author": "horseyride",
"author_id": 9264230,
"author_profile": "https://Stackoverflow.com/users/9264230",
"pm_score": 0,
"selected": false,
"text": "let Source = Excel.CurrentWorkbook(){[Name=\"Table1\"]}[Content],\n#\"Added Index\" = Table.AddIndexColumn(Source, \"Index\", 0, 1, Int64.Type),\n#\"Unpivoted Other Columns\" = Table.UnpivotOtherColumns(#\"Added Index\", {\"Index\"}, \"Attribute\", \"Value\"),\n#\"Duplicated Column\" = Table.DuplicateColumn(#\"Unpivoted Other Columns\", \"Attribute\", \"Attribute - Copy\"),\n#\"Split Column by Delimiter\" = Table.SplitColumn(#\"Duplicated Column\", \"Attribute - Copy\", Splitter.SplitTextByDelimiter(\".\", QuoteStyle.Csv), {\"A1\", \"A2\"}),\n#\"Grouped Rows\" = Table.Group(#\"Split Column by Delimiter\", {\"Index\", \"A2\"}, {{\"data\", each \n let compare = if _{0}[Value] = _{1}[Value] then \"match\" else \"nomatch\"\n in Table.InsertRows( _,1,{[Index = _{0}[Index], Attribute = \"Delta.\"&_{0}[A2], Value=compare, A1=\"Delta\", A2=_{0}[A2]]})\n, type table }}),\n#\"Expanded data\" = Table.ExpandTableColumn(#\"Grouped Rows\", \"data\", {\"Attribute\", \"Value\" }, {\"Attribute\", \"Value\"}),\n#\"Removed Columns\" = Table.RemoveColumns(#\"Expanded data\",{\"A2\"}),\n#\"Pivoted Column\" = Table.Pivot(#\"Removed Columns\", List.Distinct(#\"Removed Columns\"[Attribute]), \"Attribute\", \"Value\"),\n#\"Removed Columns1\" = Table.RemoveColumns(#\"Pivoted Column\",{\"Index\"})\nin #\"Removed Columns1\"\n"
},
{
"answer_id": 74353763,
"author": "kami",
"author_id": 5986209,
"author_profile": "https://Stackoverflow.com/users/5986209",
"pm_score": -1,
"selected": false,
"text": "each Table.Column(state, current) <> Table.Column(state, \"Old.\" & Text.RemoveRange(current, 0, 4))\n"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74351882",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11396082/"
] |
74,351,933 | <p>I know there's a way to configure a Spark Application based in your cluster resources ("Executor memory" and "number of Executor" and "executor cores") I'm wondering if exist a way to do it considering the data input size?</p>
<p>What would happen if data input size does not fit into all partitions?</p>
<p>Example:</p>
<ul>
<li><p>Data input size = 200GB</p>
</li>
<li><p>Number of partitions in cluster = 100</p>
</li>
<li><p>Size of partitions = 128MB</p>
</li>
<li><p>Total size that partitions could handle = 100 * 128MB = 128GB</p>
</li>
</ul>
<p>What about the rest of the data (72GB)?</p>
<p>I guess Spark will wait to have free the resources free due to is designed to process batches of data Is this a correct assumption?</p>
<p>Thank in advance</p>
| [
{
"answer_id": 74352987,
"author": "Zafar",
"author_id": 4373061,
"author_profile": "https://Stackoverflow.com/users/4373061",
"pm_score": 1,
"selected": false,
"text": "spark.executor.cores"
},
{
"answer_id": 74411054,
"author": "ankush1377",
"author_id": 12600300,
"author_profile": "https://Stackoverflow.com/users/12600300",
"pm_score": 0,
"selected": false,
"text": "Size of partitions = 128MB"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74351933",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18931096/"
] |
74,351,969 | <p>I have the following program that prints even numbers in a provided range. However, I'd like to make it so that if the second number is smaller than the 1st number, e.g. end < start, then print the even numbers but in reverse order.</p>
<p>I'm thinking we would need two separate loops for each condition based on what I have here, but is there a much more simplistic way to accomplish this?</p>
<pre><code>start = int (input("1st number: "))
end = int (input("2nd number: "))
for num in range(start, end + 1):
if num % 2 == 0 and start < end:
print (num, end = " ")
#elif num % 2 == 0 and end > start:
#print (num, end = " ")
</code></pre>
| [
{
"answer_id": 74352040,
"author": "Jean-François Fabre",
"author_id": 6451573,
"author_profile": "https://Stackoverflow.com/users/6451573",
"pm_score": 1,
"selected": true,
"text": "start = 20\nend = 30\n\n# uncomment to swap start & end\n#start,end = end,start\n\n# compute direction. 2 or -2\ndirection = 2 if (end-start)>0 else -2\n\n# add direction to end works in both directions\nfor num in range(start, end + direction,direction):\n print(num,end=\" \")\n"
},
{
"answer_id": 74352058,
"author": "Alberto Garcia",
"author_id": 15647384,
"author_profile": "https://Stackoverflow.com/users/15647384",
"pm_score": 2,
"selected": false,
"text": "start = int (input(\"1st number: \")) \nend = int (input(\"2nd number: \"))\n\nrng = range(start, end + 1) if start < end else range(start, end -1, -1)\nfor num in rng:\n if num % 2 == 0:\n print (num, end = \" \")\n"
},
{
"answer_id": 74352399,
"author": "Arifa Chan",
"author_id": 19574157,
"author_profile": "https://Stackoverflow.com/users/19574157",
"pm_score": 1,
"selected": false,
"text": "print(*[n for n in (range(start,end+1), range(start,end-1,-1))[start>end] if not n % 2])\n"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74351969",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8397835/"
] |
74,352,005 | <p>My web method:</p>
<pre><code> [HttpPost]
public async Task<IActionResult> UploadFile2(IFormFile file, int idPackage)
{
string output = $"{file.FileName} - {file.Length} - {idPackage}";
return Ok(output);
}
</code></pre>
<p>My Postman request:</p>
<pre><code>POST https://localhost:7006/api/upload/UploadFile2 HTTP/1.1
User-Agent: PostmanRuntime/7.29.2
Accept: */*
Postman-Token: fc51918c-f03f-4e29-9726-6a5159dcb035
Host: localhost:7006
Accept-Encoding: gzip, deflate, br
Connection: keep-alive
Content-Type: multipart/form-data; boundary=--------------------------368567246425722572627984
Content-Length: 363
----------------------------368567246425722572627984
Content-Disposition: form-data; name="idPackage"
1247
----------------------------368567246425722572627984
Content-Disposition: form-data; name="file"; filename="dummy.dat"
Content-Type: application/octet-stream
dummy data from the dummy file
----------------------------368567246425722572627984--
</code></pre>
<p>The file parameter correctly receives the uploaded file as input.</p>
<p>The idPackage parameter remains the default value of 0, even though I am sending along 1247 for this value.</p>
<p>What could possibly be causing this?</p>
<p><strong>Update 1</strong></p>
<p>This very same web request does work in another project of mine, I just found out.</p>
<p>It has to be some sort of server side setting, related to how requests are handled, although I currently have no idea which one.</p>
<p><strong>Update 2</strong></p>
<p>I figured it had to be the Newtonsoft JSON resolver configuration that I have in my other project.</p>
<p>Turns out that wasn't it. Still no idea what it <strong>could</strong> be, then.</p>
<p>Is there any way of debugging how C# processes a web request under the hood?</p>
| [
{
"answer_id": 74352668,
"author": "K. A.",
"author_id": 11696753,
"author_profile": "https://Stackoverflow.com/users/11696753",
"pm_score": 1,
"selected": false,
"text": "public class UploadFileDTO \n{\n public IFormFile File { get; set; } \n public int IdPackage { get; set; }\n}\n"
},
{
"answer_id": 74352889,
"author": "Jay",
"author_id": 1018165,
"author_profile": "https://Stackoverflow.com/users/1018165",
"pm_score": 1,
"selected": true,
"text": "[HttpPost]\npublic async Task<IActionResult> UploadFile2(IFormFile file, [FromForm]int idPackage)\n{\n string output = $\"{file.FileName} - {file.Length} - {idPackage}\";\n return Ok(output);\n}\n"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74352005",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1018165/"
] |
74,352,053 | <p>Based on the data below how can I average the columns <code>InIndividuals</code>, <code>OutIndividuals</code>, <code>InAGI</code> and <code>OutAGI</code> by <code>FIPS</code>? I am using <code>FIPS</code> because there are several counties with the same name. So the column <code>Key</code> is no longer needed as it's a concatenate of <code>FIPS</code> and <code>Year</code>.</p>
<p>Desired output schema/columns:</p>
<pre><code> FIPS County State AvgInIndividuals AvgOutIndividuals AvgNetMigration AvgInAGI AvgOutAGI
1 8001 Adams County CO 36.0 40.0 -4 388.5 351.0
2 12001 Alachua County FL 407.0 404.0 3 277.5 346.5
3 16001 Ada County ID 18.5 18.5 0 499.5 462.0
</code></pre>
<p>Sample data:</p>
<pre><code>df = structure(list(FIPS = c(12001L, 8001L, 16001L, 12001L,
8001L, 16001L), State = c("FL", "CO", "ID", "FL",
"CO", "ID"), County = c("Alachua County", "Adams County",
"Ada County", "Alachua County", "Adams County", "Ada County"),
InIndividuals = c(433L, 30L, 16L, 381L, 42L, 21L), OutIndividuals = c(426L, 33L, 12L, 382L, 47L, 25L), InAGI = c(111L, 222L, 333L, 444L, 555L, 666L), NetMigration = c(7L, -3L, 4L, -1L, -5L, -4L), OutAGI = c(570L, 246L, 135L, 123L, 456L, 789L), FiscalYear = c("2011 - 2012",
"2011 - 2012", "2011 - 2012", "2011 - 2012", "2010 - 2011",
"2010 - 2011"), Year = c(2012L, 2012L, 2012L, 2011L, 2011L,
2011L), Key = c(120012012L, 80012012L, 160012012L, 120012011L,
80012011L, 160012011L)), class = "data.frame", row.names = c(NA,
-6L))
</code></pre>
| [
{
"answer_id": 74352668,
"author": "K. A.",
"author_id": 11696753,
"author_profile": "https://Stackoverflow.com/users/11696753",
"pm_score": 1,
"selected": false,
"text": "public class UploadFileDTO \n{\n public IFormFile File { get; set; } \n public int IdPackage { get; set; }\n}\n"
},
{
"answer_id": 74352889,
"author": "Jay",
"author_id": 1018165,
"author_profile": "https://Stackoverflow.com/users/1018165",
"pm_score": 1,
"selected": true,
"text": "[HttpPost]\npublic async Task<IActionResult> UploadFile2(IFormFile file, [FromForm]int idPackage)\n{\n string output = $\"{file.FileName} - {file.Length} - {idPackage}\";\n return Ok(output);\n}\n"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74352053",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12547996/"
] |
74,352,076 | <p>The problem is that the database does not have time to be processed and there is a call on the second circle.
How to make the database processing happen and the cycle goes on. asynchronously</p>
<pre><code>async def send_mes_to_users(client):
async with client:
user = 'userrrrrrrrr'
try:
if db.check_invited(name_table=table, user_name=user) != "TRUE":
await client.send_message(entity=user, message=message)
db.add_invited(name_table=table, user=user) #??????????
print(f'Sent: @{user}')
except errors.BadRequestError as e:
print(f'Error: {e}')
async def main():
await asyncio.gather(
send_mes_to_users(TelegramClient('user1', api_id, api_hash)),
send_mes_to_users(TelegramClient('user2', api_id, api_hash)),
)
asyncio.run(main())
</code></pre>
| [
{
"answer_id": 74352668,
"author": "K. A.",
"author_id": 11696753,
"author_profile": "https://Stackoverflow.com/users/11696753",
"pm_score": 1,
"selected": false,
"text": "public class UploadFileDTO \n{\n public IFormFile File { get; set; } \n public int IdPackage { get; set; }\n}\n"
},
{
"answer_id": 74352889,
"author": "Jay",
"author_id": 1018165,
"author_profile": "https://Stackoverflow.com/users/1018165",
"pm_score": 1,
"selected": true,
"text": "[HttpPost]\npublic async Task<IActionResult> UploadFile2(IFormFile file, [FromForm]int idPackage)\n{\n string output = $\"{file.FileName} - {file.Length} - {idPackage}\";\n return Ok(output);\n}\n"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74352076",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17103932/"
] |
74,352,097 | <p>I know this question has been asked many times but it just doesnt work for me and i dont know why.
I need to see a graph without zero values, but it only shows a graph with them no matter what i try</p>
<p>These are the first 5 rows from .csv file. I need this kind of values</p>
<pre><code>0 2022-10-24T12:12:35Z 44.61
1 2022-10-24T12:12:40Z 17.33
2 2022-10-24T12:12:45Z 41.20
3 2022-10-24T12:12:51Z 33.49
4 2022-10-24T12:12:56Z 55.68
29944 2022-11-03T09:51:58Z 0.0
29945 2022-11-03T09:52:28Z 0.0
29946 2022-11-03T09:52:58Z 0.0
29947 2022-11-03T09:53:28Z 0.0
29948 2022-11-03T09:53:58Z 0.0
</code></pre>
<p>these are the last 5 rows from .cvs file. I need these type of rows deleted</p>
<p>This is my code now:</p>
<pre><code># libraries
import matplotlib.pyplot as plt
import pandas as pd
from sklearn.metrics import mean_absolute_error
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeRegressor
import seaborn as sns
from datetime import datetime
import plotly.express as px
from sklearn.ensemble import IsolationForest
import plotly.graph_objects as go
headers = ['time', 'value']
# Read data
#dataset = pd.read_csv("raw_input_filtered.csv", parse_dates=[0])
dataset2 = pd.read_csv("coffe-2col.csv", sep=';', skiprows=1, names=headers) #, dtype=dtypes)
# Printing head of the DataFrame
print(dataset2.head())
# remove empty lines
#groups = dataset2.groupby((dataset2.drop('value', axis= 1) == 0).all(axis=1))
#all_zero = groups.get_group(True)
#non_all_zero = groups.get_group(False)
new_dataset2 = dataset2.dropna()
#dataset2 = dataset2.drop(dataset2[dataset2.value == 0].index)
#dataset2.drop(dataset2[dataset2.value == 0].index, inplace=True)
non of these worked
</code></pre>
| [
{
"answer_id": 74352129,
"author": "Naveed",
"author_id": 3494754,
"author_profile": "https://Stackoverflow.com/users/3494754",
"pm_score": 2,
"selected": true,
"text": "# select rows that has value 0\n# then take negation of it and return the DF using LOC\n\ndf=df.loc[~df['value'].eq(0)]\n\n"
},
{
"answer_id": 74352164,
"author": "Dizzy",
"author_id": 20215078,
"author_profile": "https://Stackoverflow.com/users/20215078",
"pm_score": 0,
"selected": false,
"text": "dataset2.loc[~(dataset2==0).all(axis=1)]\n"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74352097",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20350038/"
] |
74,352,116 | <p>I am trying to match partials from a list with a complete match in the other list.</p>
<pre><code>match_list = ['abc', 'bcc'] # etc
files = os.listdir()
files = ['hello-abc', 'bye-abc', 'byebyebcc', 'byehelloxyz']
# List comprehension to match partial 'hello-abc'(example) in files with element 'abc' in files.
# this wont work
files = [i for i in files if i in match_list]
# results in files = []
</code></pre>
<p>Expected output:</p>
<pre><code>files = ['hello-abc', 'bye-abc', 'byebyebcc']
</code></pre>
| [
{
"answer_id": 74352146,
"author": "I'mahdi",
"author_id": 1740577,
"author_profile": "https://Stackoverflow.com/users/1740577",
"pm_score": 2,
"selected": false,
"text": "any()"
},
{
"answer_id": 74352180,
"author": "Alberto Garcia",
"author_id": 15647384,
"author_profile": "https://Stackoverflow.com/users/15647384",
"pm_score": 1,
"selected": false,
"text": "any"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74352116",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6387095/"
] |
74,352,124 | <p>I have this clunky code here and hope there is any way to shorten this.
By the way, "req.query" is my query object from an nodejs express server.</p>
<pre><code> const q = req.query
User.insertOne({
firstName: q.firstName,
lastName: q.lastName,
bestFriend: q.bestFriend,
hobbies: q.hobbies,
address: {
street: q.address.street,
number: q.address.number,
plz: q.address.plz,
city: q.address.city,
country: q.address.country,
},
contact: {
telephone: q.contact.telephone,
email: q.contact.email,
},
})
</code></pre>
<p>My first solution was - as you can see - to replace req.query with q, but this does not seem to be enough.</p>
<p>Maybe you could do this with the "with" statement, but i haven't used it before and I've heard that you shouldn't implement it (don't know why....).</p>
| [
{
"answer_id": 74352523,
"author": "jessica-98",
"author_id": 20261328,
"author_profile": "https://Stackoverflow.com/users/20261328",
"pm_score": 0,
"selected": false,
"text": "const _ = require(\"lodash\"); \nUser.insertOne(_.pick(req.query, [\n \"firstName\",\n \"lastName\",\n \"bestFriend\",\n \"hobbies\",\n \"address.street\",\n \"address.number\",\n \"address.plz\",\n \"address.city\",\n \"address.country\",\n \"contact.telephone\",\n \"contact.email\"\n]))\n"
},
{
"answer_id": 74352589,
"author": "Aleksandar",
"author_id": 12737879,
"author_profile": "https://Stackoverflow.com/users/12737879",
"pm_score": 2,
"selected": true,
"text": "//Object destructuring:\nconst { firstName, lastName, bestFriend, hobbies } = req.query;\nconst { street, number, plz, city, country } = req.query.address;\nconst { telephone, email } = req.query.contact;\n\n//Using the ES6 object property shorthand:\n User.insertOne({\n firstName,\n lastName,\n bestFriend,\n hobbies,\n address: {\n street,\n number,\n plz,\n city,\n country,\n },\n contact: {\n telephone,\n email,\n },\n })\n"
},
{
"answer_id": 74352644,
"author": "Abiranjan",
"author_id": 6655088,
"author_profile": "https://Stackoverflow.com/users/6655088",
"pm_score": 1,
"selected": false,
"text": "const q = req.query\nUser.insertOne(q);\n"
},
{
"answer_id": 74352854,
"author": "Peter Seliger",
"author_id": 2627243,
"author_profile": "https://Stackoverflow.com/users/2627243",
"pm_score": 0,
"selected": false,
"text": "const req = {\n query: {\n foo: 'Foo',\n bar: 'Bar',\n\n firstName: 'Anni',\n lastName: 'Smith',\n bestFriend: 'Jane Doe',\n hobbies: '',\n address: {\n street: 'Any Lane',\n number: 42,\n plz: '1-234-456',\n city: 'Some City',\n country: 'Motherland',\n },\n contact: {\n telephone: '9-87-654-321',\n email: 'anni.smith@provider.com',\n },\n more_not_needed_data: {\n baz: 'Baz',\n biz: 'Biz',\n },\n },\n};\n\nconst userDataFromRest =\n (({ foo, bar, more_not_needed_data, ...data }) => data)(req.query);\n\nconst explicitUserData = (\n ({\n firstName, lastName, bestFriend, hobbies, address, contact,\n }) => ({\n firstName, lastName, bestFriend, hobbies, address, contact,\n })\n)(req.query);\n\n/*\nUser\n .insertOne((({ foo, bar, 'more not needed data', ...data }) => data)(req.query));\n\nUser\n .insertOne((\n ({\n firstName, lastName, bestFriend, hobbies, address, contact,\n }) => ({\n firstName, lastName, bestFriend, hobbies, address, contact,\n })\n )(req.query));\n*/\n\nconsole.log({\n query: req.query,\n userDataFromRest,\n explicitUserData, \n});"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74352124",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19762828/"
] |
74,352,125 | <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function storage(data) {
let object = {};
data.forEach(line => {
let [product, quantity] = line.split(' ');
if (!object[product]) {
object[product] = quantity;
} else {
let currentQuantity = Object.assign(object[product] = quantity); < -- - problem comes from here
let newQuantity = Number(currentQuantity) + Number(quantity);
Object.assign(product, newQuantity);
}
});
}
storage(['tomatoes 10', 'coffee 5', 'olives 100', 'coffee 40']);</code></pre>
</div>
</div>
</p>
<p>Hello , I am new in the OOP and I want to combine different values from a key with same name.</p>
<p>output wanted <code>['tomatoes 10', 'coffee 45', 'olives 100']</code></p>
| [
{
"answer_id": 74352523,
"author": "jessica-98",
"author_id": 20261328,
"author_profile": "https://Stackoverflow.com/users/20261328",
"pm_score": 0,
"selected": false,
"text": "const _ = require(\"lodash\"); \nUser.insertOne(_.pick(req.query, [\n \"firstName\",\n \"lastName\",\n \"bestFriend\",\n \"hobbies\",\n \"address.street\",\n \"address.number\",\n \"address.plz\",\n \"address.city\",\n \"address.country\",\n \"contact.telephone\",\n \"contact.email\"\n]))\n"
},
{
"answer_id": 74352589,
"author": "Aleksandar",
"author_id": 12737879,
"author_profile": "https://Stackoverflow.com/users/12737879",
"pm_score": 2,
"selected": true,
"text": "//Object destructuring:\nconst { firstName, lastName, bestFriend, hobbies } = req.query;\nconst { street, number, plz, city, country } = req.query.address;\nconst { telephone, email } = req.query.contact;\n\n//Using the ES6 object property shorthand:\n User.insertOne({\n firstName,\n lastName,\n bestFriend,\n hobbies,\n address: {\n street,\n number,\n plz,\n city,\n country,\n },\n contact: {\n telephone,\n email,\n },\n })\n"
},
{
"answer_id": 74352644,
"author": "Abiranjan",
"author_id": 6655088,
"author_profile": "https://Stackoverflow.com/users/6655088",
"pm_score": 1,
"selected": false,
"text": "const q = req.query\nUser.insertOne(q);\n"
},
{
"answer_id": 74352854,
"author": "Peter Seliger",
"author_id": 2627243,
"author_profile": "https://Stackoverflow.com/users/2627243",
"pm_score": 0,
"selected": false,
"text": "const req = {\n query: {\n foo: 'Foo',\n bar: 'Bar',\n\n firstName: 'Anni',\n lastName: 'Smith',\n bestFriend: 'Jane Doe',\n hobbies: '',\n address: {\n street: 'Any Lane',\n number: 42,\n plz: '1-234-456',\n city: 'Some City',\n country: 'Motherland',\n },\n contact: {\n telephone: '9-87-654-321',\n email: 'anni.smith@provider.com',\n },\n more_not_needed_data: {\n baz: 'Baz',\n biz: 'Biz',\n },\n },\n};\n\nconst userDataFromRest =\n (({ foo, bar, more_not_needed_data, ...data }) => data)(req.query);\n\nconst explicitUserData = (\n ({\n firstName, lastName, bestFriend, hobbies, address, contact,\n }) => ({\n firstName, lastName, bestFriend, hobbies, address, contact,\n })\n)(req.query);\n\n/*\nUser\n .insertOne((({ foo, bar, 'more not needed data', ...data }) => data)(req.query));\n\nUser\n .insertOne((\n ({\n firstName, lastName, bestFriend, hobbies, address, contact,\n }) => ({\n firstName, lastName, bestFriend, hobbies, address, contact,\n })\n )(req.query));\n*/\n\nconsole.log({\n query: req.query,\n userDataFromRest,\n explicitUserData, \n});"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74352125",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12153732/"
] |
74,352,126 | <p>I am trying to get the result of games where records are not in team_id array.</p>
<p>from front end, sending array of team_id [ 23, 24 ], the result should not consider 23, 24 id from game_teams table</p>
<p><strong>games table</strong></p>
<pre><code>| id | name |
| 42 | game 1 |
| 43 | game 2 |
</code></pre>
<p><strong>teams table</strong></p>
<pre><code>| id | name |
| 22 | team 1 |
| 23 | team 2 |
| 24 | team 3 |
| 25 | team 4 |
| 26 | team 5 |
</code></pre>
<p><strong>game_teams table</strong></p>
<pre><code>| id | game_id | team_id |
| 1 | 42 | 22 |
| 2 | 42 | 23 |
| 3 | 43 | 23 |
| 4 | 43 | 24 |
| 5 | 43 | 25 |
| 6 | 43 | 26 |
</code></pre>
<p><code>$results = Game::with(['gameTeams.teams'])->whereNotIn("team_id", $request->arr_team_ids)->get()->toArray();</code></p>
<p>with above code the result is not as "Expected result".</p>
<p><strong>Expected result below, here you can see the record 23, 24 are not expected result which are in game_teams table :</strong></p>
<pre><code>[
{
"id": 42,
"name": "game 1",
"game_teams": [
{
"id": 1,
"game_id": 42,
"team_id": 22,
"teams": {
"id": 22,
"name": "team 1",
}
}
]
},
{
"id": 43,
"name": "game 2",
"game_teams": [
{
"id": 5,
"game_id": 43,
"team_id": 25,
"teams": {
"id": 25,
"name": "team 4"
}
},
{
"id": 6,
"game_id": 43,
"team_id": 26,
"teams": {
"id": 26,
"name": "team 5",
}
}
]
},
]
</code></pre>
| [
{
"answer_id": 74352523,
"author": "jessica-98",
"author_id": 20261328,
"author_profile": "https://Stackoverflow.com/users/20261328",
"pm_score": 0,
"selected": false,
"text": "const _ = require(\"lodash\"); \nUser.insertOne(_.pick(req.query, [\n \"firstName\",\n \"lastName\",\n \"bestFriend\",\n \"hobbies\",\n \"address.street\",\n \"address.number\",\n \"address.plz\",\n \"address.city\",\n \"address.country\",\n \"contact.telephone\",\n \"contact.email\"\n]))\n"
},
{
"answer_id": 74352589,
"author": "Aleksandar",
"author_id": 12737879,
"author_profile": "https://Stackoverflow.com/users/12737879",
"pm_score": 2,
"selected": true,
"text": "//Object destructuring:\nconst { firstName, lastName, bestFriend, hobbies } = req.query;\nconst { street, number, plz, city, country } = req.query.address;\nconst { telephone, email } = req.query.contact;\n\n//Using the ES6 object property shorthand:\n User.insertOne({\n firstName,\n lastName,\n bestFriend,\n hobbies,\n address: {\n street,\n number,\n plz,\n city,\n country,\n },\n contact: {\n telephone,\n email,\n },\n })\n"
},
{
"answer_id": 74352644,
"author": "Abiranjan",
"author_id": 6655088,
"author_profile": "https://Stackoverflow.com/users/6655088",
"pm_score": 1,
"selected": false,
"text": "const q = req.query\nUser.insertOne(q);\n"
},
{
"answer_id": 74352854,
"author": "Peter Seliger",
"author_id": 2627243,
"author_profile": "https://Stackoverflow.com/users/2627243",
"pm_score": 0,
"selected": false,
"text": "const req = {\n query: {\n foo: 'Foo',\n bar: 'Bar',\n\n firstName: 'Anni',\n lastName: 'Smith',\n bestFriend: 'Jane Doe',\n hobbies: '',\n address: {\n street: 'Any Lane',\n number: 42,\n plz: '1-234-456',\n city: 'Some City',\n country: 'Motherland',\n },\n contact: {\n telephone: '9-87-654-321',\n email: 'anni.smith@provider.com',\n },\n more_not_needed_data: {\n baz: 'Baz',\n biz: 'Biz',\n },\n },\n};\n\nconst userDataFromRest =\n (({ foo, bar, more_not_needed_data, ...data }) => data)(req.query);\n\nconst explicitUserData = (\n ({\n firstName, lastName, bestFriend, hobbies, address, contact,\n }) => ({\n firstName, lastName, bestFriend, hobbies, address, contact,\n })\n)(req.query);\n\n/*\nUser\n .insertOne((({ foo, bar, 'more not needed data', ...data }) => data)(req.query));\n\nUser\n .insertOne((\n ({\n firstName, lastName, bestFriend, hobbies, address, contact,\n }) => ({\n firstName, lastName, bestFriend, hobbies, address, contact,\n })\n )(req.query));\n*/\n\nconsole.log({\n query: req.query,\n userDataFromRest,\n explicitUserData, \n});"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74352126",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15593322/"
] |
74,352,148 | <p>There's a table with three columns: start date, end date and task duration in hours. For example, something like that:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Id</th>
<th>StartDate</th>
<th>EndDate</th>
<th>Duration</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>07-11-2022</td>
<td>15-11-2022</td>
<td>40</td>
</tr>
<tr>
<td>2</td>
<td>02-09-2022</td>
<td>02-11-2022</td>
<td>122</td>
</tr>
<tr>
<td>3</td>
<td>10-10-2022</td>
<td>05-11-2022</td>
<td>52</td>
</tr>
</tbody>
</table>
</div>
<p>And I want to get a table like that:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th style="text-align: left;">Id</th>
<th style="text-align: center;">Month</th>
<th style="text-align: right;">HoursPerMonth</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align: left;">1</td>
<td style="text-align: center;">11</td>
<td style="text-align: right;">40</td>
</tr>
<tr>
<td style="text-align: left;">2</td>
<td style="text-align: center;">09</td>
<td style="text-align: right;">56</td>
</tr>
<tr>
<td style="text-align: left;">2</td>
<td style="text-align: center;">10</td>
<td style="text-align: right;">62</td>
</tr>
<tr>
<td style="text-align: left;">2</td>
<td style="text-align: center;">11</td>
<td style="text-align: right;">4</td>
</tr>
<tr>
<td style="text-align: left;">3</td>
<td style="text-align: center;">10</td>
<td style="text-align: right;">42</td>
</tr>
<tr>
<td style="text-align: left;">3</td>
<td style="text-align: center;">11</td>
<td style="text-align: right;">10</td>
</tr>
</tbody>
</table>
</div>
<p>Briefly, I wanted to know, how many working hours is in each month between start and end dates. Proportionally. How can I achieve that by MS SQL Query? Data is quite big so the query speed is important enough. Thanks in advance!</p>
<p>I've tried <code>DATEDIFF</code> and <code>EOMONTH</code>, but that solution doesn't work with tasks > 2 months. And I'm sure that this solution is bad decision. I hope, that it can be done more elegant way.</p>
| [
{
"answer_id": 74352481,
"author": "John Cappelletti",
"author_id": 1570000,
"author_profile": "https://Stackoverflow.com/users/1570000",
"pm_score": 2,
"selected": false,
"text": "Select ID\n ,Month = month(D)\n ,HoursPerMonth = (sum(1.0) / (1+max(datediff(DAY,StartDate,EndDate)))) * max(Duration)\n From YourTable A\n Join (\n Select Top 75000 D=dateadd(day,Row_Number() Over (Order By (Select NULL)),0) \n From master..spt_values n1, master..spt_values n2\n ) B on D between StartDate and EndDate\n Group By ID,month(D)\n Order by ID,Month\n"
},
{
"answer_id": 74352908,
"author": "StoneGiant",
"author_id": 5572384,
"author_profile": "https://Stackoverflow.com/users/5572384",
"pm_score": 0,
"selected": false,
"text": "DECLARE @source\n TABLE (\n SOURCE_ID INT\n ,STARTDATE DATE\n ,ENDDATE DATE\n ,DURATION INT\n )\n;\n\nINSERT\n INTO\n @source\nVALUES\n (1, '20221107', '20221115', 40 )\n ,(2, '20220902', '20221102', 122 )\n ,(3, '20221010', '20221105', 52 )\n;\n"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74352148",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20443475/"
] |
74,352,251 | <p>I wrote some code to solve project Eulers #8. I have seen a few other solutions to this problem on line, but I do not understand how they create the nested loop, or it is a different method.</p>
<p>Problem OVERVIEW: Find the thirteen adjacent digits in the 1000-digit number(string with no delimitator) that have the greatest product. What is the value of this product?</p>
<p>I got it to work, but I could not find a way to simplify my product of 13 numbers from a string of numbers.</p>
<p>Here is what I had in mind:</p>
<pre><code>num_string = '73167176531330624919225119674426574742355349...'
length = 13
products_of_13 = []
largest_product_of_13 =0
for i in range(0,(len(num_string) - 12)):
product_13=0
for j in range (i,i+12):
product_13 *= int(num_string[j])
products_of_13.append(product_13)
for num in products_of_13:
if num > largest_product_of_13:
# print(product_13)
largest_product_of_13 = num
print(largest_product_of_13)
</code></pre>
<p>This only resulted in an answer of 0 every time. I added</p>
<pre><code>print(int(num_string[j]))
</code></pre>
<p>into the above code to check that I am getting the correct numbers, but it looks as though a zero is being put between each iteration of the loop. Making everything zero.</p>
<p>QUESTION: How do I make a loop to calculate the product_13 , to avoid typing out each string index and turning it in to an integer?</p>
<p>I tried so many things that did not work I used the below code that is horrible to read:</p>
<pre><code>num_string='''7316717653133062491922511967442657474235534919493496983520312774506326239578318016984801869478851843858615607891129494954595017379583319528532088055111254069874715852386305071569329096329522744304355766896648950445244523161731856403098711121722383113622298934233803081353362766142828064444866452387493035890729629049156044077239071381051585930796086670172427121883998797908792274921901699720888093776657273330010533678812202354218097512545405947522435258490771167055601360483958644670632441572215539753697817977846174064955149290862569321978468622482839722413756570560574902614079729686524145351004748216637048440319989000889524345065854122758866688116427171479924442928230863465674813919123162824586178664583591245665294765456828489128831426076900422421902267105562632111110937054421750694165896040807198403850962455444362981230987879927244284909188845801561660979191338754992005240636899125607176060588611646710940507754100225698315520005593572972571636269561882670428252483600823257530420752963450'''
products_of_13 = []
largest_product_of_13 =0
for i in range(0,(len(num_string) - 12)):
product_13= int(num_string[i])*int(num_string[i+1])*int(num_string[i+2])*int(num_string[i+3])*int(num_string[i+4])*int(num_string[i+5])*int(num_string[i+6])*int(num_string[i+7])*int(num_string[i+8])*int(num_string[i+9])*int(num_string[i+10])*int(num_string[i+11])*int(num_string[i+12])
products_of_13.append(product_13)
for num in products_of_13:
if num > largest_product_of_13:
# print(product_13)
largest_product_of_13 = num
print(largest_product_of_13)
</code></pre>
<p>UPTDATE: solution is 23514624000</p>
| [
{
"answer_id": 74352406,
"author": "assume_irrational_is_rational",
"author_id": 11622508,
"author_profile": "https://Stackoverflow.com/users/11622508",
"pm_score": 0,
"selected": false,
"text": "reduce(lambda x,y: x*y, map(int, your_string))"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74352251",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20303754/"
] |
74,352,270 | <p>I am new to pygame (and coding) and can't figure out how to move my player from one side of the screen to the other, like the side gates in pacman, here's my code i hope someone can help me cuz it's seems like it's something easy but i just can't think of a solution yet</p>
<pre><code>import pygame
white=(255,255,255)
yellow=(255,255,102)
black=(0,0,0)
red=(213,50,80)
green=(0,255,0)
blue=(50,153,213)
dis_witdh,dis_height=1920,1080
dis=pygame.display.set_mode((dis_witdh,dis_height))
pygame.display.set_caption("")
fps=60
velocity=6
border=pygame.Rect((0,0), (dis_witdh, dis_height))
player_witdh=10
player_height=10
def draw_widow(player):
dis.fill(black)
pygame.draw.rect(dis, white, [player.x ,player.y ,player_witdh,player_height])
pygame.display.update()
def movement(keys_pressed,player):
if keys_pressed[pygame.K_a] and player.x-velocity>-1:
player.x-=velocity
if keys_pressed[pygame.K_d] and player.x+velocity<dis_witdh-9:
player.x+=velocity
if keys_pressed[pygame.K_w] and player.y+velocity>9:
player.y-=velocity
if keys_pressed[pygame.K_s] and player.y+velocity<dis_height-9:
player.y+=velocity
if keys_pressed[pygame.K_ESCAPE]:
pygame.quit()
def world_generation():
def main():
player=pygame.Rect(dis_witdh/2,dis_height/2,player_witdh,player_height)
clock=pygame.time.Clock()
run=True
while run:
clock.tick(fps)
for event in pygame.event.get():
if event.type==pygame.QUIT:
run=False
keys_pressed=pygame.key.get_pressed()
movement(keys_pressed,player)
draw_widow(player)
pygame.quit()
if __name__=="__main__":
main()
</code></pre>
| [
{
"answer_id": 74352406,
"author": "assume_irrational_is_rational",
"author_id": 11622508,
"author_profile": "https://Stackoverflow.com/users/11622508",
"pm_score": 0,
"selected": false,
"text": "reduce(lambda x,y: x*y, map(int, your_string))"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74352270",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20441186/"
] |
74,352,273 | <p>Hello I Have problem with getting signal in my second program.
I have code like this:</p>
<p>Program1:</p>
<pre><code>int main() {
int id = fork();
if (id == 0) {
execl("program2", "program2", NULL);
kill(id, SIGUSR1);
}
return 0;
}
</code></pre>
<p>Program 2:</p>
<pre><code>void signal_handler1(int sig) {
printf("test\n");
}
int main(int argc, char* argv[]) {
signal(SIGUSR1, signal_handler1);
printf("Hello world\n");
return 0;
}
</code></pre>
<p>And why I get</p>
<pre><code>Hello World
</code></pre>
<p>Instend of</p>
<pre><code>test
Hello World
</code></pre>
| [
{
"answer_id": 74352406,
"author": "assume_irrational_is_rational",
"author_id": 11622508,
"author_profile": "https://Stackoverflow.com/users/11622508",
"pm_score": 0,
"selected": false,
"text": "reduce(lambda x,y: x*y, map(int, your_string))"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74352273",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15403065/"
] |
74,352,280 | <p>I have two dataframes that I'd like to join if one column's value is contained in the other column. The dataframes look like this:</p>
<pre><code>df1 = pl.DataFrame({"col1": [1, 2, 3], "col2": ["x1, x2, x3", "x2, x3", "x3"]})
df2 = pl.DataFrame({"col3": [4, 5, 6], "col4": ["x1", "x2", "x3"]})
</code></pre>
<p>I tried to do:</p>
<pre><code>model_data = df1.join(df2, on="col2")
</code></pre>
<p>Which does not produce the desired result. What I'd like to see is something like this:</p>
<pre><code>col1 col2 col3 col4
1 "x1, x2, x3" 4 "x1"
1 "x1, x2, x3" 5 "x2"
1 "x1, x2, x3" 6 "x3"
2 "x2, x3" 5 "x2"
2 "x2, x3" 6 "x3"
3 "x3" 6 "x3"
</code></pre>
<p>It's a question of how you do the join when one value is contained by another value. I could not find good examples of this in the docs.</p>
| [
{
"answer_id": 74368943,
"author": "jqurious",
"author_id": 20454927,
"author_profile": "https://Stackoverflow.com/users/20454927",
"pm_score": 2,
"selected": false,
"text": "col2"
},
{
"answer_id": 74392766,
"author": "Dean MacGregor",
"author_id": 1818713,
"author_profile": "https://Stackoverflow.com/users/1818713",
"pm_score": 1,
"selected": false,
"text": "col4"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74352280",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2690677/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.