qid
int64 4
19.1M
| question
stringlengths 18
48.3k
| answers
list | date
stringlengths 10
10
| metadata
list |
|---|---|---|---|---|
74,619,638
|
<p>I have a pandas dataframe <code>df</code> which looks as follows:</p>
<pre><code>A B C D E F G H I J
Values
A NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
B NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
C yes NaN NaN NaN NaN NaN NaN NaN NaN NaN
D NaN yes NaN NaN NaN NaN NaN NaN NaN NaN
E NaN ok ok NaN NaN NaN NaN NaN NaN NaN
F NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
G NaN NaN NaN ok NaN NaN NaN NaN NaN NaN
H NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
I yes NaN NaN NaN NaN NaN NaN NaN NaN NaN
J NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
</code></pre>
<p>df.to_dict() is as follows:</p>
<pre><code>{'A': {'A': nan,
'B': nan,
'C': 'yes',
'D': nan,
'E': nan,
'F': nan,
'G': nan,
'H': nan,
'I': 'yes',
'J': nan},
'B': {'A': nan,
'B': nan,
'C': nan,
'D': 'yes',
'E': 'ok',
'F': nan,
'G': nan,
'H': nan,
'I': nan,
'J': nan},
'C': {'A': nan,
'B': nan,
'C': nan,
'D': nan,
'E': 'ok',
'F': nan,
'G': nan,
'H': nan,
'I': nan,
'J': nan},
'D': {'A': nan,
'B': nan,
'C': nan,
'D': nan,
'E': nan,
'F': nan,
'G': 'ok',
'H': nan,
'I': nan,
'J': nan},
'E': {'A': nan,
'B': nan,
'C': nan,
'D': nan,
'E': nan,
'F': nan,
'G': nan,
'H': nan,
'I': nan,
'J': nan},
'F': {'A': nan,
'B': nan,
'C': nan,
'D': nan,
'E': nan,
'F': nan,
'G': nan,
'H': nan,
'I': nan,
'J': nan},
'G': {'A': nan,
'B': nan,
'C': nan,
'D': nan,
'E': nan,
'F': nan,
'G': nan,
'H': nan,
'I': nan,
'J': nan},
'H': {'A': nan,
'B': nan,
'C': nan,
'D': nan,
'E': nan,
'F': nan,
'G': nan,
'H': nan,
'I': nan,
'J': nan},
'I': {'A': nan,
'B': nan,
'C': nan,
'D': nan,
'E': nan,
'F': nan,
'G': nan,
'H': nan,
'I': nan,
'J': nan},
'J': {'A': nan,
'B': nan,
'C': nan,
'D': nan,
'E': nan,
'F': nan,
'G': nan,
'H': nan,
'I': nan,
'J': nan},
'To': {'A': '',
'B': '',
'C': 'A, ',
'D': 'B, ',
'E': 'B, C, ',
'F': '',
'G': 'D, ',
'H': '',
'I': 'A, ',
'J': ''}}
</code></pre>
<p>I'd like to get a new column "To" which corresponding to each row which contains the list of columns having non NaN values such as "yes" or "ok".</p>
<p>I did it using the following code:</p>
<pre><code>df["To"] = ""
for index in df.index:
for column in df.columns[:-1]:
if pd.isnull(df.loc[index, column]) == False:
df.loc[index, "To"] += column + ", "
df
</code></pre>
<p>As shown, I created a new column called "To" and looped through each row and column to fill the "To" column.</p>
<p>The resulting dataframe looks as follows:</p>
<pre><code>A B C D E F G H I J To
Values
A NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
B NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
C yes NaN NaN NaN NaN NaN NaN NaN NaN NaN A,
D NaN yes NaN NaN NaN NaN NaN NaN NaN NaN B,
E NaN ok ok NaN NaN NaN NaN NaN NaN NaN B, C,
F NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
G NaN NaN NaN ok NaN NaN NaN NaN NaN NaN D,
H NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
I yes NaN NaN NaN NaN NaN NaN NaN NaN NaN A,
J NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
</code></pre>
<p>I think this is not an effective process and is time-consuming when the dataset is large.
Is there any shorter and more efficient way of creating this "To" column in pandas dataframe?</p>
|
[
{
"answer_id": 74619756,
"author": "Mustafa Aydın",
"author_id": 9332187,
"author_profile": "https://Stackoverflow.com/users/9332187",
"pm_score": 3,
"selected": true,
"text": "In [242]: df.notna().dot(df.columns + \", \").str[:-2]\nOut[242]:\nA\nB\nC A\nD B\nE B, C\nF\nG D\nH\nI A\nJ\ndtype: object\n df.notna()"
},
{
"answer_id": 74619772,
"author": "mozway",
"author_id": 16343464,
"author_profile": "https://Stackoverflow.com/users/16343464",
"pm_score": 2,
"selected": false,
"text": "stack groupby.agg df['To'] = (df\n .stack()\n .reset_index(-1)['level_1']\n .groupby(level=0).agg(','.join)\n )\n A B C D E F G H I J To\nA NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN\nB NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN\nC yes NaN NaN NaN NaN NaN NaN NaN NaN NaN A\nD NaN yes NaN NaN NaN NaN NaN NaN NaN NaN B\nE NaN ok ok NaN NaN NaN NaN NaN NaN NaN B,C\nF NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN\nG NaN NaN NaN ok NaN NaN NaN NaN NaN NaN D\nH NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN\nI yes NaN NaN NaN NaN NaN NaN NaN NaN NaN A\nJ NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74619638",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12276279/"
] |
74,619,659
|
<p>I think I might have found a bug in the <code>strtotime()</code> function.</p>
<p>My application uses unix timestamps to set events for certain days. I use relative time format string in conjunction with these timestamps.</p>
<p>I made this minimal code to reproduce the bug:</p>
<pre><code><?php
echo "Last day of " . date('M-Y', 1677628800) . " is: " . date('M-d-Y', strtotime('last day this month', 1677628800)) . " expecting march 31! <br>";
echo "Last day of " . date('M-Y', 1677628800) . " is: " . date('M-d-Y', strtotime('last day next month', 1677628800)) . " expecting april 30 in this case!<br>";
echo "Last day of " . date('M-Y', 1677628800) . " is: " . date('M-d-Y', strtotime('first day of next month', 1677628800)) . " expecting first day of april <br>";
echo "Last day of " . date('M-Y', strtotime('first day of this month')) . " is: " . date('M-d-Y', strtotime('last day this month', strtotime('first day of this month'))) . "<br>";
echo "Last day of " . date('M-Y', strtotime('first day of this month')) . " is: " . date('M-d-Y', strtotime('last day this month')) . "<br>";
?>
</code></pre>
<p>Why is PHP displaying this unexpected behaviour? My guess is that my timestamp being right on the edge of two days is the root cause of my problem. Is this some weird timezone issue?. I assume not because <code>strtotime()</code> is coming up with these timestamps in the first place so that should not make any difference!</p>
<p>Anyone got a better solution then just adding a day?</p>
|
[
{
"answer_id": 74619768,
"author": "gaetan-hexadog",
"author_id": 20637850,
"author_profile": "https://Stackoverflow.com/users/20637850",
"pm_score": 2,
"selected": true,
"text": "<?php\necho \"Last day of \".date('M-Y', 1677628800).\" is: \".date('M-d-Y', strtotime('last day of this month', 1677628800)).\" expecting march 31!\" . PHP_EOL; \necho \"Last day of \".date('M-Y', 1677628800).\" is: \".date('M-d-Y', strtotime('last day of next month', 1677628800)).\" expecting april 30 in this case!\" . PHP_EOL; \necho \"Last day of \".date('M-Y', 1677628800).\" is: \".date('M-d-Y', strtotime('first day of next month', 1677628800)).\" expecting first day of april\" . PHP_EOL; \necho \"Last day of \".date('M-Y', strtotime('first day of this month')).\" is: \".date('M-d-Y', strtotime('last day of this month', strtotime('first day of this month'))). PHP_EOL; \necho \"Last day of \".date('M-Y', strtotime('first day of this month')).\" is: \".date('M-d-Y', strtotime('last day of this month')) . PHP_EOL; \n"
},
{
"answer_id": 74620088,
"author": "mickmackusa",
"author_id": 2943403,
"author_profile": "https://Stackoverflow.com/users/2943403",
"pm_score": 0,
"selected": false,
"text": "of 01 t echo date('M-01-Y');\n\necho \"\\n---\\n\";\n\necho date('M-01-Y', strtotime('next month'));\n\necho \"\\n---\\n\";\n\necho date('M-t-Y');\n\necho \"\\n---\\n\";\n\necho date('M-t-Y', strtotime('next month'));\n Nov-01-2022\n---\nDec-01-2022\n---\nNov-30-2022\n---\nDec-31-2022\n first day of"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74619659",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16781639/"
] |
74,619,661
|
<p>In Xamarin.Forms we want to add a new button using</p>
<pre><code> f001content = new Xamarin.Forms.AbsoluteLayout;
f001content.Children.Add(new Button
{
Text = "Button",
AutomationId = "MyButton",
}, new Rectangle(0,0,100,40));
</code></pre>
<p>How can we find the reference to the button just added so that we can modify it in the future?</p>
|
[
{
"answer_id": 74619713,
"author": "Andrew",
"author_id": 8395242,
"author_profile": "https://Stackoverflow.com/users/8395242",
"pm_score": 1,
"selected": false,
"text": "var coolButton = new Button { Text = \"Button\", AutomationId = \"MyButton\" };\nf001content.Children.Add(coolButton, new Rectangle(0,0,100,40));\n"
},
{
"answer_id": 74619734,
"author": "Jason",
"author_id": 1338,
"author_profile": "https://Stackoverflow.com/users/1338",
"pm_score": 2,
"selected": false,
"text": "f001content = new Xamarin.Forms.AbsoluteLayout;\n\nvar btn = new Button\n {\n Text = \"Button\",\n AutomationId = \"MyButton\",\n }, new Rectangle(0,0,100,40));\n\n f001content.Children.Add(btn);\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74619661",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1252790/"
] |
74,619,663
|
<p>I'm trying to redirect to the created page after I've filled out and submitted a form. I have gotten it to work on the update form but not the create form. How do i do this?</p>
<p>Here's what I have so far. Let me know if you need more details and code</p>
<p>views.py</p>
<pre><code>@login_required(login_url='login')
def createRoom(request):
form = RoomForm()
topics = Topic.objects.all()
if request.method == 'POST':
topic_name = request.POST.get('topic')
topic, created = Topic.objects.get_or_create(name=topic_name)
Room.objects.create(
host=request.user,
topic=topic,
name=request.POST.get('name'),
assigned=request.user,
status=request.POST.get('status'),
priority=request.POST.get('priority'),
type=request.POST.get('type'),
description=request.POST.get('description'),
)
return render('room', pk=room.id)
context = {'form': form, 'topics': topics, 'room': room}
return render(request, 'room/room_form.html', context)
</code></pre>
<p>But this throws this error</p>
<p>traceback</p>
<pre><code>Traceback (most recent call last):
File "C:\Users\mikha\issue_env\lib\site-packages\django\core\handlers\exception.py", line 55, in inner
response = get_response(request)
File "C:\Users\mikha\issue_env\lib\site-packages\django\core\handlers\base.py", line 197, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\mikha\issue_env\lib\site-packages\django\contrib\auth\decorators.py", line 23, in _wrapped_view
return view_func(request, *args, **kwargs)
File "C:\Users\mikha\issuetracker\base\views.py", line 68, in createRoom
return render('room', pk=room.id)
Exception Type: AttributeError at /create-room/
Exception Value: 'function' object has no attribute 'id'
</code></pre>
|
[
{
"answer_id": 74620228,
"author": "SamSparx",
"author_id": 18799377,
"author_profile": "https://Stackoverflow.com/users/18799377",
"pm_score": 2,
"selected": true,
"text": "Room room room = Room.objects.create(\n"
},
{
"answer_id": 74620708,
"author": "Olasubomi",
"author_id": 13397363,
"author_profile": "https://Stackoverflow.com/users/13397363",
"pm_score": 0,
"selected": false,
"text": "@login_required(login_url='login')\ndef createRoom(request):\n form = RoomForm()\n topics = Topic.objects.all()\n if request.method == 'POST':\n topic_name = request.POST.get('topic')\n topic, created = Topic.objects.get_or_create(name=topic_name)\n\n room = Room.objects.create(\n host=request.user,\n topic=topic,\n name=request.POST.get('name'),\n assigned=request.user,\n status=request.POST.get('status'),\n priority=request.POST.get('priority'),\n type=request.POST.get('type'),\n description=request.POST.get('description'),\n )\n room.save() \n return redirect(\"created-room-view-function\")\n\n context = {'form': form, 'topics': topics, 'room': room}\n return render(request, 'room/room_form.html', context)\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74619663",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17998744/"
] |
74,619,796
|
<p>I have a webpage with multiple thumbnails all positioned side-by-side. When an image is clicked, a modal window pops up displaying a larger version of the image and a close button. I want the window to change its image src when one of the image "buttons" is clicked. So i have attempted to put an attribute called "imgsrc" inside the span elements which are all under the div whose class="graveyard-dump"</p>
<p>HTML</p>
<pre><code>\\\button that looks like a thumbnail of "image 04"\\\
<button button="click"
class="graveyard-btn graveyard-primary"
data-toggle="modal"
data-target="#exampleModal"
imgsrc="http://example.com/wp-content/uploads/04.png">
<img src= "http://example.com/wp-content/uploads/04.png">
</button>
</code></pre>
<pre><code>\\\Image of modal set to "image 22" as default\\\
<div class="modal-body">
<img class="modal-image"
src="http://example.com/wp-content/uploads/22.png"
alt="Click on button" />
</code></pre>
<p>Non-working jQuery</p>
<pre><code>\\\On Click change the modal image src attribute to the value at imgsrc of the thumbnail element clicked\\\
$('.graveyard-dump span').ready(function click(f) {
$('.graveyard-dump span').click(function click(f) {
$('.modal-image').attr('src', $(this).attr("imgsrc"));
});
});
</code></pre>
<p>I got the idea to reuse code from another program I have which changes a series of css elements and text on click. Here is some code that works which i stole the idea from:
HTML</p>
<pre><code>///Red button with many attribute values for the jQuery to read and place///
<span class="redbtn1"
picChange="url(http://example.com/wp-content/uploads/Resin-Red.png)"
name="Red"
color="#ff0000"
background1="#ff2400"
background2="#ba110c"
background3="#90021F"
background4="none"
name1="Scarlet"
name2="Crimson"
name3="Burgundy"
name4="-"
></span>
</code></pre>
<p>jQuery</p>
<pre><code>///Reads a click, adds the class "active" and removes it from other buttons, changes many attributes around the page. None of these are attribute-attribute changes though.///
$('.changecolor span').ready(function click(f) {
$('.changecolor span').click(function click(f) {
$('.changecolor span').removeClass("active");
$(this).addClass("active");
$('.pic').css('background-image', $(this).attr("picChange"));
$('.name').text($(this).attr("name"));
$('.name').css('color', $(this).attr("color"));
$('.colorbar-1').css('background', $(this).attr('background1'));
$('.colorbar-2').css('background', $(this).attr('background2'));
$('.colorbar-3').css('background', $(this).attr('background3'));
$('.colorbar-4').css('background', $(this).attr('background4'));
$('.colorbar-1').text($(this).attr("name1"));
$('.colorbar-2').text($(this).attr("name2"));
$('.colorbar-3').text($(this).attr("name3"));
$('.colorbar-4').text($(this).attr("name4"));
</code></pre>
|
[
{
"answer_id": 74620228,
"author": "SamSparx",
"author_id": 18799377,
"author_profile": "https://Stackoverflow.com/users/18799377",
"pm_score": 2,
"selected": true,
"text": "Room room room = Room.objects.create(\n"
},
{
"answer_id": 74620708,
"author": "Olasubomi",
"author_id": 13397363,
"author_profile": "https://Stackoverflow.com/users/13397363",
"pm_score": 0,
"selected": false,
"text": "@login_required(login_url='login')\ndef createRoom(request):\n form = RoomForm()\n topics = Topic.objects.all()\n if request.method == 'POST':\n topic_name = request.POST.get('topic')\n topic, created = Topic.objects.get_or_create(name=topic_name)\n\n room = Room.objects.create(\n host=request.user,\n topic=topic,\n name=request.POST.get('name'),\n assigned=request.user,\n status=request.POST.get('status'),\n priority=request.POST.get('priority'),\n type=request.POST.get('type'),\n description=request.POST.get('description'),\n )\n room.save() \n return redirect(\"created-room-view-function\")\n\n context = {'form': form, 'topics': topics, 'room': room}\n return render(request, 'room/room_form.html', context)\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74619796",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17172160/"
] |
74,619,807
|
<p>I have a simple CSV file with 4 columns. I am trying to use the OwnerEmail column and Azure AD (or On-Prem Active Directory) to populate the employee ID column using PowerShell.</p>
<p>Original:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Employee ID</th>
<th>DepartmentNumber</th>
<th>OwnerEmail</th>
<th>Cost</th>
</tr>
</thead>
<tbody>
<tr>
<td></td>
<td>074674</td>
<td>test@conso.com</td>
<td>4353.345</td>
</tr>
<tr>
<td></td>
<td>456246</td>
<td>tester@conso.com</td>
<td>3452.453</td>
</tr>
</tbody>
</table>
</div>
<p>After:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Employee ID</th>
<th>DepartmentNumber</th>
<th>OwnerEmail</th>
<th>Cost</th>
</tr>
</thead>
<tbody>
<tr>
<td>435345</td>
<td>074674</td>
<td>test@conso.com</td>
<td>4353.345</td>
</tr>
<tr>
<td>546345</td>
<td>456246</td>
<td>tester@conso.com</td>
<td>3452.453</td>
</tr>
</tbody>
</table>
</div>
<p>I've only gotten as far as adding the Employee Id column to the Csv file which did not exist before. I have not been able to find anything on this. A little Advice and direction would be really helpful. I am new to PowerShell</p>
<p>How I added Employee ID Column:</p>
<p>$CSVImport | Select-Object "employeeID",*</p>
|
[
{
"answer_id": 74620228,
"author": "SamSparx",
"author_id": 18799377,
"author_profile": "https://Stackoverflow.com/users/18799377",
"pm_score": 2,
"selected": true,
"text": "Room room room = Room.objects.create(\n"
},
{
"answer_id": 74620708,
"author": "Olasubomi",
"author_id": 13397363,
"author_profile": "https://Stackoverflow.com/users/13397363",
"pm_score": 0,
"selected": false,
"text": "@login_required(login_url='login')\ndef createRoom(request):\n form = RoomForm()\n topics = Topic.objects.all()\n if request.method == 'POST':\n topic_name = request.POST.get('topic')\n topic, created = Topic.objects.get_or_create(name=topic_name)\n\n room = Room.objects.create(\n host=request.user,\n topic=topic,\n name=request.POST.get('name'),\n assigned=request.user,\n status=request.POST.get('status'),\n priority=request.POST.get('priority'),\n type=request.POST.get('type'),\n description=request.POST.get('description'),\n )\n room.save() \n return redirect(\"created-room-view-function\")\n\n context = {'form': form, 'topics': topics, 'room': room}\n return render(request, 'room/room_form.html', context)\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74619807",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11110921/"
] |
74,619,812
|
<p>How to make downward triangle from 5 to 1</p>
<pre><code>function segitiga(baris) {
let pola = '';
for (let i = 1; i <= baris; i++) {
for (let j = baris; j >= i; j--) {
pola += i;
}
pola += '\n';
} return pola;
} console.log(segitiga(5));
</code></pre>
<p>Output</p>
<pre><code>11111
2222
333
44
5
</code></pre>
<p>I want the output can be like this</p>
<p>Output:</p>
<pre><code>55555
4444
333
22
1
</code></pre>
|
[
{
"answer_id": 74620228,
"author": "SamSparx",
"author_id": 18799377,
"author_profile": "https://Stackoverflow.com/users/18799377",
"pm_score": 2,
"selected": true,
"text": "Room room room = Room.objects.create(\n"
},
{
"answer_id": 74620708,
"author": "Olasubomi",
"author_id": 13397363,
"author_profile": "https://Stackoverflow.com/users/13397363",
"pm_score": 0,
"selected": false,
"text": "@login_required(login_url='login')\ndef createRoom(request):\n form = RoomForm()\n topics = Topic.objects.all()\n if request.method == 'POST':\n topic_name = request.POST.get('topic')\n topic, created = Topic.objects.get_or_create(name=topic_name)\n\n room = Room.objects.create(\n host=request.user,\n topic=topic,\n name=request.POST.get('name'),\n assigned=request.user,\n status=request.POST.get('status'),\n priority=request.POST.get('priority'),\n type=request.POST.get('type'),\n description=request.POST.get('description'),\n )\n room.save() \n return redirect(\"created-room-view-function\")\n\n context = {'form': form, 'topics': topics, 'room': room}\n return render(request, 'room/room_form.html', context)\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74619812",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9797797/"
] |
74,619,823
|
<p>I have an array of objects with an array that contains other objects. I'm trying to work out how I can filter the first objects based on data inside the array of second objects</p>
<pre><code>[{
object1Name: "test",
secondaryObjects: [
{
second2Name: "test-again"
data: "hello"
},
{
second2Name: "Hello!"
data: "remove based on this"
}
]
},
{
another object...
}]
</code></pre>
<p>I want to filter the first array by checking if any objects contain a secondary object with the data "hello". If they have a secondary object with that data it then filters out the object1</p>
<pre><code>const filteredField = data.filter((entry) => {
return entry.secondaryObjects[0].second2Name.includes('hello')
})
</code></pre>
<p>When I use this, I have it working but it only checks the first index of secondary objects but if it's in index 1 it does not work.</p>
|
[
{
"answer_id": 74620228,
"author": "SamSparx",
"author_id": 18799377,
"author_profile": "https://Stackoverflow.com/users/18799377",
"pm_score": 2,
"selected": true,
"text": "Room room room = Room.objects.create(\n"
},
{
"answer_id": 74620708,
"author": "Olasubomi",
"author_id": 13397363,
"author_profile": "https://Stackoverflow.com/users/13397363",
"pm_score": 0,
"selected": false,
"text": "@login_required(login_url='login')\ndef createRoom(request):\n form = RoomForm()\n topics = Topic.objects.all()\n if request.method == 'POST':\n topic_name = request.POST.get('topic')\n topic, created = Topic.objects.get_or_create(name=topic_name)\n\n room = Room.objects.create(\n host=request.user,\n topic=topic,\n name=request.POST.get('name'),\n assigned=request.user,\n status=request.POST.get('status'),\n priority=request.POST.get('priority'),\n type=request.POST.get('type'),\n description=request.POST.get('description'),\n )\n room.save() \n return redirect(\"created-room-view-function\")\n\n context = {'form': form, 'topics': topics, 'room': room}\n return render(request, 'room/room_form.html', context)\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74619823",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18030965/"
] |
74,619,838
|
<p>I am trying to convert some html files to json.
From the beginning: I downloaded a kind of old dataset called <code>SarcasmAmazonReviewsCorpus</code>. It has several txt files, all with comments, reactions, name of product and so on, as it follows in the image:</p>
<p><a href="https://i.stack.imgur.com/yFEhZ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/yFEhZ.png" alt="enter image description here" /></a></p>
<p>I was able to pick up each txt file and using os module I created a list with every file content. The code was:</p>
<pre><code>files_content = []
for filename in filter(lambda p: p.endswith("txt"), os.listdir(path)):
filepath = os.path.join(path, filename)
with open(filepath, mode='r') as f:
files_content += [f.read()]
</code></pre>
<p>Then, I am trying to use Beatifulsoup:</p>
<pre><code>soup = BeautifulSoup(files_content[2], 'html5lib')
soup
</code></pre>
<p>The output is like:</p>
<p><img src="https://i.stack.imgur.com/zsTzL.png" alt="image" /></p>
<p>Is there a way that I can convert all the itens in the <code>files_content</code> list into a <code>json file</code>?
Tkanks for the help!</p>
|
[
{
"answer_id": 74620228,
"author": "SamSparx",
"author_id": 18799377,
"author_profile": "https://Stackoverflow.com/users/18799377",
"pm_score": 2,
"selected": true,
"text": "Room room room = Room.objects.create(\n"
},
{
"answer_id": 74620708,
"author": "Olasubomi",
"author_id": 13397363,
"author_profile": "https://Stackoverflow.com/users/13397363",
"pm_score": 0,
"selected": false,
"text": "@login_required(login_url='login')\ndef createRoom(request):\n form = RoomForm()\n topics = Topic.objects.all()\n if request.method == 'POST':\n topic_name = request.POST.get('topic')\n topic, created = Topic.objects.get_or_create(name=topic_name)\n\n room = Room.objects.create(\n host=request.user,\n topic=topic,\n name=request.POST.get('name'),\n assigned=request.user,\n status=request.POST.get('status'),\n priority=request.POST.get('priority'),\n type=request.POST.get('type'),\n description=request.POST.get('description'),\n )\n room.save() \n return redirect(\"created-room-view-function\")\n\n context = {'form': form, 'topics': topics, 'room': room}\n return render(request, 'room/room_form.html', context)\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74619838",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19522687/"
] |
74,619,847
|
<p>I have a Cloud SQL instance with hundreds of databases, one for each customer. Each database has the same tables in it, but data only for the specific customer.</p>
<p>What I want to do with it, is transform in various ways so to get an overview table with all of the customers. Unfortunately, I cannot seem to find a tool that can itterate over all the databases a Cloud SQL instance has, execute queries and then write that data to BigQuery.</p>
<p>I was really hoping that Dataflow would be the solution but as far as I have tried and looked online, I cannot find a way to make it work. Since I spent a lot of time already on investigating Dataflow, I thought it might be best to ask here.</p>
<p>Currently I am looking at Data Fusion, Datastream, Apache Airflow.
Any suggestions?</p>
|
[
{
"answer_id": 74620228,
"author": "SamSparx",
"author_id": 18799377,
"author_profile": "https://Stackoverflow.com/users/18799377",
"pm_score": 2,
"selected": true,
"text": "Room room room = Room.objects.create(\n"
},
{
"answer_id": 74620708,
"author": "Olasubomi",
"author_id": 13397363,
"author_profile": "https://Stackoverflow.com/users/13397363",
"pm_score": 0,
"selected": false,
"text": "@login_required(login_url='login')\ndef createRoom(request):\n form = RoomForm()\n topics = Topic.objects.all()\n if request.method == 'POST':\n topic_name = request.POST.get('topic')\n topic, created = Topic.objects.get_or_create(name=topic_name)\n\n room = Room.objects.create(\n host=request.user,\n topic=topic,\n name=request.POST.get('name'),\n assigned=request.user,\n status=request.POST.get('status'),\n priority=request.POST.get('priority'),\n type=request.POST.get('type'),\n description=request.POST.get('description'),\n )\n room.save() \n return redirect(\"created-room-view-function\")\n\n context = {'form': form, 'topics': topics, 'room': room}\n return render(request, 'room/room_form.html', context)\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74619847",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20637442/"
] |
74,619,885
|
<p>I was wondering how to find elements that end in <code>%</code> and remove the <code>%</code> sign from those elements?</p>
<pre><code>data <- read.table(text="
COURSE CLASE GROUP_A GROUP_B
algebra 1 25% 8%
algebra 2 35% 9%
number_theory 3 18% 7%
number_theory 4 14% 11%
math_games 5 12% 5%
math_games 6 19% 4%
",h=TRUE)
</code></pre>
|
[
{
"answer_id": 74619945,
"author": "Vida",
"author_id": 9620304,
"author_profile": "https://Stackoverflow.com/users/9620304",
"pm_score": 1,
"selected": false,
"text": "mydata <- read.table(text=\"\n COURSE CLASE GROUP_A GROUP_B\n algebra 1 25% 8%\n algebra 2 35% 9%\n number_theory 3 18% 7%\n number_theory 4 14% 11%\n math_games 5 12% 5%\n math_games 6 19% 4%\n \",h=TRUE)\nmydata[,c(\"GROUP_A\",\"GROUP_B\")] <- lapply(mydata[,c(\"GROUP_A\",\"GROUP_B\")],\n function(x) as.numeric(gsub(\"%$\",\"\",x)))\n"
},
{
"answer_id": 74619960,
"author": "G. Grothendieck",
"author_id": 516548,
"author_profile": "https://Stackoverflow.com/users/516548",
"pm_score": 2,
"selected": true,
"text": "data |>\n replace(TRUE, lapply(data, sub, pattern = \"%$\", replacement = \"\")) |>\n type.convert(as.is = TRUE)\n COURSE CLASE GROUP_A GROUP_B\n1 algebra 1 25 8\n2 algebra 2 35 9\n3 number_theory 3 18 7\n4 number_theory 4 14 11\n5 math_games 5 12 5\n6 math_games 6 19 4\n library(dplyr)\n\ndata %>%\n mutate(across(everything(), ~ sub(\"%$\", \"\", .x))) %>%\n type.convert(as.is = TRUE)\n"
},
{
"answer_id": 74619988,
"author": "Ruam Pimentel",
"author_id": 13015865,
"author_profile": "https://Stackoverflow.com/users/13015865",
"pm_score": 0,
"selected": false,
"text": "library(dplyr)\nlibrary(stringr)\n data <- read.table(text=\"\nCOURSE CLASE GROUP_A GROUP_B\nalgebra 1 25% 8%\nalgebra 2 35% 9%\nnumber_theory 3 18% 7%\nnumber_theory 4 14% 11%\nmath_games 5 12% 5%\nmath_games 6 19% 4%\n\",h=TRUE) %>% as_tibble()\n\n across() dplyr str_remove() stringr %>% as.numeric() across() c(GROUP_A, GROUP_B) data %>% \n mutate(across(c(GROUP_A, GROUP_B), \n ~str_remove(.x, \"%\") %>% as.numeric())) \n \n#> # A tibble: 6 × 4\n#> COURSE CLASE GROUP_A GROUP_B\n#> <chr> <int> <dbl> <dbl>\n#> 1 algebra 1 25 8\n#> 2 algebra 2 35 9\n#> 3 number_theory 3 18 7\n#> 4 number_theory 4 14 11\n#> 5 math_games 5 12 5\n#> 6 math_games 6 19 4\n"
},
{
"answer_id": 74620086,
"author": "arg0naut91",
"author_id": 8389003,
"author_profile": "https://Stackoverflow.com/users/8389003",
"pm_score": 0,
"selected": false,
"text": "idx <- apply(data, 2, function(x) any(grepl('%$', x)))\ndata[idx] <- lapply(data[idx], function(x) as.numeric(sub('%$', '', x)))\n COURSE CLASE GROUP_A GROUP_B\n1 algebra 1 25 8\n2 algebra 2 35 9\n3 number_theory 3 18 7\n4 number_theory 4 14 11\n5 math_games 5 12 5\n6 math_games 6 19 4\n str(data)\n\n'data.frame': 6 obs. of 4 variables:\n $ COURSE : Factor w/ 3 levels \"algebra\",\"math_games\",..: 1 1 3 3 2 2\n $ CLASE : int 1 2 3 4 5 6\n $ GROUP_A: num 25 35 18 14 12 19\n $ GROUP_B: num 8 9 7 11 5 4\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74619885",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16760971/"
] |
74,619,887
|
<p>Im trying to generate a password in Bash that matches MacOS password requirements and one of them is that it can't have repeated characters (aa, bb, 44, 00, etc).</p>
<p>I know i can use <code>openssl rand -base64</code> or <code>/dev/urandom</code> and use <code>tr -d</code> to manipulate the output string. I use <code>grep -E '(.)\1{1,}'</code> to search for repeated characters but if i use this regex to delete (<code>tr -d (.)\1{1,}'</code>), it deletes the entire string. I even tried <code>tr -s '(.)\1{1,}'</code> to squeeze the characters to just one occurrence but it keep generating repeated characters in some attempts. Is it possible to achieve what i'm trying to?</p>
<p>P.S.: that's a situation where i cant download any "password generator tool" like pwgen and more. It must be "native"</p>
|
[
{
"answer_id": 74619945,
"author": "Vida",
"author_id": 9620304,
"author_profile": "https://Stackoverflow.com/users/9620304",
"pm_score": 1,
"selected": false,
"text": "mydata <- read.table(text=\"\n COURSE CLASE GROUP_A GROUP_B\n algebra 1 25% 8%\n algebra 2 35% 9%\n number_theory 3 18% 7%\n number_theory 4 14% 11%\n math_games 5 12% 5%\n math_games 6 19% 4%\n \",h=TRUE)\nmydata[,c(\"GROUP_A\",\"GROUP_B\")] <- lapply(mydata[,c(\"GROUP_A\",\"GROUP_B\")],\n function(x) as.numeric(gsub(\"%$\",\"\",x)))\n"
},
{
"answer_id": 74619960,
"author": "G. Grothendieck",
"author_id": 516548,
"author_profile": "https://Stackoverflow.com/users/516548",
"pm_score": 2,
"selected": true,
"text": "data |>\n replace(TRUE, lapply(data, sub, pattern = \"%$\", replacement = \"\")) |>\n type.convert(as.is = TRUE)\n COURSE CLASE GROUP_A GROUP_B\n1 algebra 1 25 8\n2 algebra 2 35 9\n3 number_theory 3 18 7\n4 number_theory 4 14 11\n5 math_games 5 12 5\n6 math_games 6 19 4\n library(dplyr)\n\ndata %>%\n mutate(across(everything(), ~ sub(\"%$\", \"\", .x))) %>%\n type.convert(as.is = TRUE)\n"
},
{
"answer_id": 74619988,
"author": "Ruam Pimentel",
"author_id": 13015865,
"author_profile": "https://Stackoverflow.com/users/13015865",
"pm_score": 0,
"selected": false,
"text": "library(dplyr)\nlibrary(stringr)\n data <- read.table(text=\"\nCOURSE CLASE GROUP_A GROUP_B\nalgebra 1 25% 8%\nalgebra 2 35% 9%\nnumber_theory 3 18% 7%\nnumber_theory 4 14% 11%\nmath_games 5 12% 5%\nmath_games 6 19% 4%\n\",h=TRUE) %>% as_tibble()\n\n across() dplyr str_remove() stringr %>% as.numeric() across() c(GROUP_A, GROUP_B) data %>% \n mutate(across(c(GROUP_A, GROUP_B), \n ~str_remove(.x, \"%\") %>% as.numeric())) \n \n#> # A tibble: 6 × 4\n#> COURSE CLASE GROUP_A GROUP_B\n#> <chr> <int> <dbl> <dbl>\n#> 1 algebra 1 25 8\n#> 2 algebra 2 35 9\n#> 3 number_theory 3 18 7\n#> 4 number_theory 4 14 11\n#> 5 math_games 5 12 5\n#> 6 math_games 6 19 4\n"
},
{
"answer_id": 74620086,
"author": "arg0naut91",
"author_id": 8389003,
"author_profile": "https://Stackoverflow.com/users/8389003",
"pm_score": 0,
"selected": false,
"text": "idx <- apply(data, 2, function(x) any(grepl('%$', x)))\ndata[idx] <- lapply(data[idx], function(x) as.numeric(sub('%$', '', x)))\n COURSE CLASE GROUP_A GROUP_B\n1 algebra 1 25 8\n2 algebra 2 35 9\n3 number_theory 3 18 7\n4 number_theory 4 14 11\n5 math_games 5 12 5\n6 math_games 6 19 4\n str(data)\n\n'data.frame': 6 obs. of 4 variables:\n $ COURSE : Factor w/ 3 levels \"algebra\",\"math_games\",..: 1 1 3 3 2 2\n $ CLASE : int 1 2 3 4 5 6\n $ GROUP_A: num 25 35 18 14 12 19\n $ GROUP_B: num 8 9 7 11 5 4\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74619887",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20637970/"
] |
74,619,926
|
<p>I want to fit the video to the screen and scrolling needs to be disabled.</p>
<p><strong>Problem:</strong> <br>
Instead of being full screen it is overflowing from the screen.</p>
<p>What am I doing wrong here?</p>
<pre><code><!DOCTYPE html>
<html>
<head>
<style>
.videosize {
position:absolute;
z-index:-1;
top:0;
left:0;
width:100%;
height:auto;
}
</style>
<script src="https://cdn.jsdelivr.net/npm/indigo-player@1/lib/indigo-player.js"></script>
</head>
<body>
<div id="playerContainer" class="videosize">
<script>
const config = {
sources: [
{
type: 'hls',
src: 'https://test-streams.mux.dev/x36xhzz/x36xhzz.m3u8',
}
],
};
const element = document.getElementById('playerContainer');
const player = IndigoPlayer.init(element, config);
</script>
</div>
</body>
</html>
</code></pre>
|
[
{
"answer_id": 74619945,
"author": "Vida",
"author_id": 9620304,
"author_profile": "https://Stackoverflow.com/users/9620304",
"pm_score": 1,
"selected": false,
"text": "mydata <- read.table(text=\"\n COURSE CLASE GROUP_A GROUP_B\n algebra 1 25% 8%\n algebra 2 35% 9%\n number_theory 3 18% 7%\n number_theory 4 14% 11%\n math_games 5 12% 5%\n math_games 6 19% 4%\n \",h=TRUE)\nmydata[,c(\"GROUP_A\",\"GROUP_B\")] <- lapply(mydata[,c(\"GROUP_A\",\"GROUP_B\")],\n function(x) as.numeric(gsub(\"%$\",\"\",x)))\n"
},
{
"answer_id": 74619960,
"author": "G. Grothendieck",
"author_id": 516548,
"author_profile": "https://Stackoverflow.com/users/516548",
"pm_score": 2,
"selected": true,
"text": "data |>\n replace(TRUE, lapply(data, sub, pattern = \"%$\", replacement = \"\")) |>\n type.convert(as.is = TRUE)\n COURSE CLASE GROUP_A GROUP_B\n1 algebra 1 25 8\n2 algebra 2 35 9\n3 number_theory 3 18 7\n4 number_theory 4 14 11\n5 math_games 5 12 5\n6 math_games 6 19 4\n library(dplyr)\n\ndata %>%\n mutate(across(everything(), ~ sub(\"%$\", \"\", .x))) %>%\n type.convert(as.is = TRUE)\n"
},
{
"answer_id": 74619988,
"author": "Ruam Pimentel",
"author_id": 13015865,
"author_profile": "https://Stackoverflow.com/users/13015865",
"pm_score": 0,
"selected": false,
"text": "library(dplyr)\nlibrary(stringr)\n data <- read.table(text=\"\nCOURSE CLASE GROUP_A GROUP_B\nalgebra 1 25% 8%\nalgebra 2 35% 9%\nnumber_theory 3 18% 7%\nnumber_theory 4 14% 11%\nmath_games 5 12% 5%\nmath_games 6 19% 4%\n\",h=TRUE) %>% as_tibble()\n\n across() dplyr str_remove() stringr %>% as.numeric() across() c(GROUP_A, GROUP_B) data %>% \n mutate(across(c(GROUP_A, GROUP_B), \n ~str_remove(.x, \"%\") %>% as.numeric())) \n \n#> # A tibble: 6 × 4\n#> COURSE CLASE GROUP_A GROUP_B\n#> <chr> <int> <dbl> <dbl>\n#> 1 algebra 1 25 8\n#> 2 algebra 2 35 9\n#> 3 number_theory 3 18 7\n#> 4 number_theory 4 14 11\n#> 5 math_games 5 12 5\n#> 6 math_games 6 19 4\n"
},
{
"answer_id": 74620086,
"author": "arg0naut91",
"author_id": 8389003,
"author_profile": "https://Stackoverflow.com/users/8389003",
"pm_score": 0,
"selected": false,
"text": "idx <- apply(data, 2, function(x) any(grepl('%$', x)))\ndata[idx] <- lapply(data[idx], function(x) as.numeric(sub('%$', '', x)))\n COURSE CLASE GROUP_A GROUP_B\n1 algebra 1 25 8\n2 algebra 2 35 9\n3 number_theory 3 18 7\n4 number_theory 4 14 11\n5 math_games 5 12 5\n6 math_games 6 19 4\n str(data)\n\n'data.frame': 6 obs. of 4 variables:\n $ COURSE : Factor w/ 3 levels \"algebra\",\"math_games\",..: 1 1 3 3 2 2\n $ CLASE : int 1 2 3 4 5 6\n $ GROUP_A: num 25 35 18 14 12 19\n $ GROUP_B: num 8 9 7 11 5 4\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74619926",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20638017/"
] |
74,620,046
|
<p>I have a connect and disconnect table. I need to find out how many people disconnected and reconnected have at least one matching phone number. Both tables have columns Telephone_Number, Primrary_Number and Alternate_phone_number.</p>
<pre><code>FROM CONN_UNIVERSE CU
LEFT JOIN DISC_UNIVERSE DU
ON (
DU.TELEPHONE_NUMBER = CU.TELEPHONE_NUMBER
OR DU.TELEPHONE_NUMBER = CU.PRIMARY_PHONE_NUMBER
OR DU.TELEPHONE_NUMBER = CU.ALTERNATE_PHONE_NUMBER
OR DU.PRIMARY_PHONE_NUMBER = CU.TELEPHONE_NUMBER
OR DU.PRIMARY_PHONE_NUMBER = CU.PRIMARY_PHONE_NUMBER
OR DU.PRIMARY_PHONE_NUMBER = CU.ALTERNATE_PHONE_NUMBER
OR DU.ALTERNATE_PHONE_NUMBER = CU.TELEPHONE_NUMBER
OR DU.ALTERNATE_PHONE_NUMBER = CU.PRIMARY_PHONE_NUMBER
OR DU.ALTERNATE_PHONE_NUMBER = CU.ALTERNATE_PHONE_NUMBER)
</code></pre>
<p>I want to flag the rows where there is any match between different telephone numbers. This code keeps running and never finishes. On checking the query performance/profile it is considering this set of code as Cartesian join (54%).</p>
<p>How can I rewrite this code and get better performance?</p>
|
[
{
"answer_id": 74620363,
"author": "Thorsten Kettner",
"author_id": 2270762,
"author_profile": "https://Stackoverflow.com/users/2270762",
"pm_score": 1,
"selected": false,
"text": "COALESCE SELECT\n cu.some_column,\n COALESCE(du1.colx, du2.colx, du3.colx, du4.colx, du5.colx, du6.colx, du7.colx, du8.colx, du9.colx) AS colx,\n COALESCE(du1.coly, du2.coly, du3.coly, du4.coly, du5.coly, du6.coly, du7.coly, du8.coly, du9.coly) AS coly \nFROM conn_universe cu\nLEFT JOIN disc_universe du1 ON du1.telephone_number = cu.telephone_number\nLEFT JOIN disc_universe du2 ON du2.telephone_number = cu.primary_phone_number\nLEFT JOIN disc_universe du3 ON du3.telephone_number = cu.alternate_phone_number\nLEFT JOIN disc_universe du4 ON du4.primary_phone_number = cu.telephone_number\nLEFT JOIN disc_universe du5 ON du5.primary_phone_number = cu.primary_phone_number\nLEFT JOIN disc_universe du6 ON du6.primary_phone_number = cu.alternate_phone_number\nLEFT JOIN disc_universe du7 ON du7.alternate_phone_number = cu.telephone_number\nLEFT JOIN disc_universe du8 ON du8.alternate_phone_number = cu.primary_phone_number\nLEFT JOIN disc_universe du9 ON du9.alternate_phone_number = cu.alternate_phone_number);\n"
},
{
"answer_id": 74624758,
"author": "JHH",
"author_id": 20127235,
"author_profile": "https://Stackoverflow.com/users/20127235",
"pm_score": 0,
"selected": false,
"text": "conn_info_columns conn_universe disc_info_columns disc_universe phone_type with cte_conn_universe as (\nselect conn_info_columns, 'TELEPHONE' as phone_type, telephone_number as phone_number from conn_universe where telephone_number is not null\nunion all\nselect conn_info_columns, 'PRIMARY_PHONE' as phone_type, primary_phone_number as phone_number from conn_universe where primary_phone_number is not null\nunion all\nselect conn_info_columns, 'ALTERNATE_PHONE' as phone_type, alternate_phone_number as phone_number from conn_universe where alternate_phone_number is not null),\ncte_disc_universe as (\nselect disc_info_columns, 'TELEPHONE' as phone_type, telephone_number as phone_number from disc_universe where telephone_number is not null\nunion all\nselect disc_info_columns, 'PRIMARY_PHONE' as phone_type, primary_phone_number as phone_number from disc_universe where primary_phone_number is not null\nunion all\nselect disc_info_columns, 'ALTERNATE_PHONE' as phone_type, alternate_phone_number as phone_number from disc_universe where alternate_phone_number is not null)\nselect coalesce(c.phone_number, d.phone_number) as phone_number,\n c.phone_type as conn_phone_type,\n d.phone_type as disc_phone_type,\n c.conn_info_columns,\n d.disc_info_columns\n from cte_conn_universe c\n full outer\n join cte_disc_universe d\n on c.phone_number = d.phone_number;\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74620046",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10273357/"
] |
74,620,049
|
<p>I need to invalidate some queries in the <code>onSuccess</code> of an <code>useMutation</code>.</p>
<p>I have a <code>queryKey</code> schema like this:</p>
<pre><code>.....
1-["questions", "by_vendor" , "{vendor_code}" , "by_status", "{status}"]
2-["questions", "by_status", "{status}"]
3-["questions", "by_vendor", "{vendor_code}"]
.....
</code></pre>
<p>I'm using <code>useQueryClient</code> to get the query client.</p>
<p>I need to invalidate the <code>querykeys</code> where the <code>"by_status"</code> is used.</p>
<p>Is there a way of accessing active <code>queryKeys</code>.</p>
<p>There are methods like <code>queryClient.getQueryData()</code> but all require the <code>queryKey</code> in advance.</p>
<p>Thank you!</p>
|
[
{
"answer_id": 74621753,
"author": "Chad S.",
"author_id": 5274205,
"author_profile": "https://Stackoverflow.com/users/5274205",
"pm_score": 2,
"selected": false,
"text": "return useQuery(\n ['questions', { by_vendor: vendor, by_status: status }],\n async ({queryKey}) => {\n // Stuff to use the query key and get api data\n }\n);\n\n queryClient.invalidateQueries({\n queryKey: ['questions', { by_status: status }],\n})\n"
},
{
"answer_id": 74650985,
"author": "Woohaik",
"author_id": 17200950,
"author_profile": "https://Stackoverflow.com/users/17200950",
"pm_score": 1,
"selected": true,
"text": "exact: true useQueryClient const queryClient = useQueryClient()\n getQueryCache() getAll() queryCache Query QueryKey const queryCache = queryClient.getQueryCache()\nconst queryKeys = queryCache.getAll().map(cache => cache.queryKey) // QueryKey[]\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74620049",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17200950/"
] |
74,620,092
|
<p><em>So I'm trying to combine the output of these two statements:</em></p>
<pre><code>SELECT COUNT (CUSTOMER_ID) FROM CUSTOMER WHERE MILES BETWEEN 3 AND 5;
</code></pre>
<p><em>This total gives me 8</em></p>
<pre><code>SELECT COUNT (CUSTOMER_ID) FROM CUSTOMER;
</code></pre>
<p>*This total gives me 20 (total number of rows in my database)</p>
<p>This gives me an answer of who from my database lives within 3 and 5 miles, where miles is its own column.</p>
<p>I would like to output the answer to a percentage of my total database eg. 8/20 * 100 * = 40%</p>
<pre><code>SELECT
(SELECT COUNT (CUSTOMER_ID) FROM CUSTOMER WHERE MILES BETWEEN 3 AND 5) /
(SELECT COUNT (CUSTOMER_ID) FROM CUSTOMER) * 100 FROM CUSTOMER ;
</code></pre>
<p>But this gives me 20 rows of "40" which is the correct answer, I just don't want 20 rows of it.</p>
|
[
{
"answer_id": 74621753,
"author": "Chad S.",
"author_id": 5274205,
"author_profile": "https://Stackoverflow.com/users/5274205",
"pm_score": 2,
"selected": false,
"text": "return useQuery(\n ['questions', { by_vendor: vendor, by_status: status }],\n async ({queryKey}) => {\n // Stuff to use the query key and get api data\n }\n);\n\n queryClient.invalidateQueries({\n queryKey: ['questions', { by_status: status }],\n})\n"
},
{
"answer_id": 74650985,
"author": "Woohaik",
"author_id": 17200950,
"author_profile": "https://Stackoverflow.com/users/17200950",
"pm_score": 1,
"selected": true,
"text": "exact: true useQueryClient const queryClient = useQueryClient()\n getQueryCache() getAll() queryCache Query QueryKey const queryCache = queryClient.getQueryCache()\nconst queryKeys = queryCache.getAll().map(cache => cache.queryKey) // QueryKey[]\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74620092",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20638149/"
] |
74,620,099
|
<p>I need to capture the aggregated number of items in each subcategories and categories. Each category has the same finite set of subcategories.There is a finite set of category as well. I intend to capture the aggregation using this schema:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Timestamp</th>
<th>Count_CatA_Sub1</th>
<th>Count_CatA_Sub2</th>
<th>...</th>
<th>Count_CatD_Sub6</th>
<th>Count_CatD_Sub7</th>
</tr>
</thead>
<tbody>
<tr>
<td>2022-11-29</td>
<td>1</td>
<td>2</td>
<td>...</td>
<td>27</td>
<td>28</td>
</tr>
</tbody>
</table>
</div>
<p>But I need to visualize the number of items in a category as well. With the above sample row, I need the output:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Timestamp</th>
<th>CountA</th>
<th>CountB</th>
<th>CountC</th>
<th>CountD</th>
</tr>
</thead>
<tbody>
<tr>
<td>2022-11-29</td>
<td>28</td>
<td>77</td>
<td>126</td>
<td>175</td>
</tr>
</tbody>
</table>
</div>
<p>I would rather not have to type out <code>CountA=Count_CatA_Sub1 + Count_CatA_Sub2 +... Count_CatA_Sub7</code>. Is it possible to do these with wildcard in Kusto? Or a better schema?</p>
|
[
{
"answer_id": 74620562,
"author": "ChrisWue",
"author_id": 220986,
"author_profile": "https://Stackoverflow.com/users/220986",
"pm_score": 1,
"selected": false,
"text": "narrow() datatable(Timestamp: datetime, CatA_Sub1: int, CatA_Sub2: int, CatB_Sub1: int) [\n datetime(2022-11-28 11:50:00), 1, 2, 3,\n datetime(2022-11-28 11:51:00), 4, 5, 6,\n datetime(2022-11-28 11:52:00), 7, 8, 9,\n datetime(2022-11-28 11:53:00), 10, 11, 12,\n datetime(2022-11-28 11:54:00), 13, 14, 15,\n datetime(2022-11-28 11:55:00), 16, 17, 18\n]\n| evaluate narrow()\n| summarize Timestamp = maxif(todatetime(Value), Column == 'Timestamp'),\n TotalCount = sumif(toint(Value), Column != 'Timestamp') by Row\n| project-away Row\n"
},
{
"answer_id": 74623705,
"author": "David דודו Markovitz",
"author_id": 6336479,
"author_profile": "https://Stackoverflow.com/users/6336479",
"pm_score": 0,
"selected": false,
"text": "// Sample data generation. Not part of the solution.\nlet t = materialize(print Timestamp = range(datetime(2022-11-29), datetime(2022-12-03), 1d), Cat = range(0, 3), Sub = range(1, 7) | mv-expand Timestamp to typeof(datetime) | mv-expand Cat to typeof(int) | mv-expand Sub to typeof(int) | serialize Val = row_number() | extend Col = strcat(\"Count_Cat\", tostring(make_string(to_utf8(\"A\")[0] + Cat)) ,\"_Sub\", Sub) | evaluate pivot(Col, take_any(Val), Timestamp));\n// Solution starts here\nt\n| project Timestamp, Metrics = bag_remove_keys(pack_all(), dynamic([\"Timestamp\"]))\n| mv-apply Metrics on \n (\n extend k = tostring(bag_keys(Metrics)[0])\n | extend v = tolong(Metrics[k])\n | parse k with \"Count_Cat\" Cat \"_Sub\" Sub:int\n | summarize sum(v) by Cat\n | summarize make_bag(bag_pack(strcat(\"Count\", Cat), sum_v))\n )\n| evaluate bag_unpack(bag_)\n"
},
{
"answer_id": 74623728,
"author": "David דודו Markovitz",
"author_id": 6336479,
"author_profile": "https://Stackoverflow.com/users/6336479",
"pm_score": 0,
"selected": false,
"text": "// Sample data generation. Not part of the solution.\nlet t = materialize(print Timestamp = range(datetime(2022-11-29), datetime(2022-12-03), 1d), Cat = range(0, 3), Sub = range(1, 7) | mv-expand Timestamp to typeof(datetime) | mv-expand Cat to typeof(int) | mv-expand Sub to typeof(int) | serialize Val = row_number() | extend Col = strcat(\"Count_Cat\", tostring(make_string(to_utf8(\"A\")[0] + Cat)) ,\"_Sub\", Sub) | evaluate pivot(Col, take_any(Val), Timestamp));\n// Solution starts here\nt\n| project Timestamp, Metrics = bag_remove_keys(pack_all(), dynamic([\"Timestamp\"]))\n| mv-expand kind=array Metrics \n| extend k = tostring(Metrics[0]), v = tolong(Metrics[1])\n| parse k with \"Count_Cat\" Cat \"_Sub\" Sub:int\n| extend Col = strcat(\"Count\", Cat)\n| evaluate pivot(Col, sum(v), Timestamp)\n"
},
{
"answer_id": 74625299,
"author": "David דודו Markovitz",
"author_id": 6336479,
"author_profile": "https://Stackoverflow.com/users/6336479",
"pm_score": 0,
"selected": false,
"text": "// Sample data generation. Not part of the solution.\nlet t = materialize(print Timestamp = range(datetime(2022-11-29), datetime(2022-12-03), 1d), Cat = range(0, 3), Sub = range(1, 7) | mv-expand Timestamp to typeof(datetime) | mv-expand Cat to typeof(int) | mv-expand Sub to typeof(int) | serialize Val = row_number() | extend Col = strcat(\"Count_Cat\", tostring(make_string(to_utf8(\"A\")[0] + Cat)) ,\"_Sub\", Sub) | evaluate pivot(Col, take_any(Val), Timestamp));\n// Solution starts here\nt\n| evaluate narrow()\n| parse Column with \"Count_Cat\" Cat \"_Sub\" Sub:int\n| summarize Count = sumif(tolong(Value), Column != \"Timestamp\")\n ,Timestamp = todatetime(take_anyif(Value, Column == \"Timestamp\")) \n by Row, Cat\n| summarize take_any(Timestamp), make_bag(bag_pack(Cat, Count)) by Row\n| evaluate bag_unpack(bag_, \"Count\")\n| project-away Row\n"
},
{
"answer_id": 74625892,
"author": "David דודו Markovitz",
"author_id": 6336479,
"author_profile": "https://Stackoverflow.com/users/6336479",
"pm_score": 0,
"selected": false,
"text": "// Sample data generation. Not part of the solution.\nlet t = materialize(print Timestamp = range(datetime(2022-11-29), datetime(2022-12-03), 1d), Cat = range(0, 3), Sub = range(1, 7) | mv-expand Timestamp to typeof(datetime) | mv-expand Cat to typeof(int) | mv-expand Sub to typeof(int) | serialize Val = row_number() | extend Col = strcat(\"Count_Cat\", tostring(make_string(to_utf8(\"A\")[0] + Cat)) ,\"_Sub\", Sub) | evaluate pivot(Col, take_any(Val), Timestamp));\n// Solution starts here\nlet cat = 4;\nlet sub = 7;\nlet categories = toscalar\n(\n t\n | getschema\n | parse-where ColumnName with \"Count_Cat\" Cat \"_Sub\" Sub:int\n | summarize make_set(Cat)\n);\nt\n| project Timestamp, Count = array_split(array_slice(pack_array(*), 1, cat*sub), range(sub, sub*(cat-1), sub))\n| mv-expand with_itemindex=i Count\n| extend Cat = strcat(\"Count\", tostring(categories[i]))\n| evaluate pivot(Cat, take_any(tolong(array_sum(Count))), Timestamp)\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74620099",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4092412/"
] |
74,620,121
|
<p>How and where is the head list implemented in task 83 on leetcode? Where is it initialized? Can you please write the code for this in what it would look like in a regular editor?</p>
<p>Here is the solution:</p>
<pre><code>public ListNode deleteDuplicates(ListNode head) {
if(head==null || head.next==null)return head;
ListNode node=head;
while(head!=null && head.next!=null){
if(head.val==head.next.val){
head.next=head.next.next;
}
else head=head.next;
}
return node;`
}
</code></pre>
|
[
{
"answer_id": 74620202,
"author": "Thomas Kläger",
"author_id": 5646962,
"author_profile": "https://Stackoverflow.com/users/5646962",
"pm_score": 0,
"selected": false,
"text": "ListNode source = new ListNode(1, new ListNode(1, new ListNode(2)));\n\nListNode result = new Solution().deleteDuplicates(source);\n\n// code that checks that result is a list of two elements and contains 1 and 2 in that order\n"
},
{
"answer_id": 74620470,
"author": "Alexander Ivanchenko",
"author_id": 17949945,
"author_profile": "https://Stackoverflow.com/users/17949945",
"pm_score": 3,
"selected": true,
"text": "head Node deleteDuplicates() Node deleteDuplicates() node head public ListNode deleteDuplicates(ListNode head) {\n if (head == null || head.next == null) return head;\n ListNode node = head;\n\n while (node != null && node.next != null) {\n if (node.val == node.next.val) {\n node.next = node.next.next;\n } else node = node.next;\n }\n return head;\n}\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74620121",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17274825/"
] |
74,620,123
|
<p>I'm working in BigQuery and I have some URLs, let's say they looks like this:</p>
<pre><code>URL
https://www.newssite.com/news/biden-rail-strike/12345/UTM=company-Library/
https://www.newssite.com/news/news-about-today-exiting/55690/
https://www.nytimes.com/2022/11/29/us/politics/biden-rail-strike.html
https://www.differentnewssite.com/news/news-about-yesterday-exiting/55690/UTM=facebook
https://www.newssite.com/opinion/opinion-about-today-sad-insightful/578932/
</code></pre>
<p>I want to extract the path section of it into a different column so it looks like this:</p>
<pre><code>Path
news/biden-rail-strike/12345/
news/news-about-today-exiting/55690/
2022/11/29/us/politics/biden-rail-strike.html
news/news-about-yesterday-exiting/55690/
opinion/opinion-about-today-sad-insightful/578932
</code></pre>
<p>I've tried options with variations on <code>select url, Regexp_extract(st_destination_url,'regex') as path</code> and have also played with splitting the URL as well, but haven't landed on a solution. Any thoughts?</p>
|
[
{
"answer_id": 74620972,
"author": "Ricco D",
"author_id": 14733669,
"author_profile": "https://Stackoverflow.com/users/14733669",
"pm_score": 0,
"selected": false,
"text": "with sample_data as (\nselect 'https://www.newssite.com/news/biden-rail-strike/12345/UTM=company-Library/' as url\nunion all select 'https://www.newssite.com/news/news-about-today-exiting/55690/' as url\nunion all select 'https://www.nytimes.com/2022/11/29/us/politics/biden-rail-strike.html' as url\nunion all select 'https://www.differentnewssite.com/news/news-about-yesterday-exiting/55690/UTM=facebook' as url\nunion all select 'https://www.newssite.com/opinion/opinion-about-today-sad-insightful/578932/' as url\n),\n\nremove_host as (\n select \n url,\n regexp_replace(right(url,length(url)-length(concat('https://',NET.HOST(url)))),r'(/)$','') as trimmed,\n from sample_data\n),\nwith_split as (\n select \n url,\n trimmed,\n split(trimmed,'/') splitted,\n from remove_host\n)\n\nselect \nurl,\nif(regexp_contains(trimmed,r'=')=true,\n array_to_string(array(\n select * except(offset) \n from with_split.splitted with offset\n where offset < array_length(with_split.splitted) - 1\n ),'/'),trimmed \n) as path\n\nfrom with_split\n"
},
{
"answer_id": 74621460,
"author": "Jaytiger",
"author_id": 19039920,
"author_profile": "https://Stackoverflow.com/users/19039920",
"pm_score": 2,
"selected": false,
"text": "WITH sample_data AS (\n select 'https://www.newssite.com/news/biden-rail-strike/12345/UTM=company-Library/' url union all\n select 'https://www.newssite.com/news/news-about-today-exiting/55690/' url union all\n select 'https://www.nytimes.com/2022/11/29/us/politics/biden-rail-strike.html' url union all\n select 'https://www.differentnewssite.com/news/news-about-yesterday-exiting/55690/UTM=facebook&UTM=company-Library' url union all\n select 'http://www.newssite.com/opinion/opinion-about-today-sad-insightful/578932/' url\n)\nSELECT REPLACE(REGEXP_REPLACE(url, r'(https?:\\/\\/|\\w+=[\\w-]+[\\/\\&]?)', ''), NET.HOST(url) || '/', '') Path\n FROM sample_data;\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74620123",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10778372/"
] |
74,620,126
|
<p>Trying to make a button event onMouseDown, a function should run at the end of the set amount of time. The function runs onMouseDown and clears the interval onMouseUp, but the interval still runs after releasing the button.</p>
<p>This is the code currently. I have the interval global and set it in the planting function. It should unset in the notPlanting function, but it does not.</p>
<pre><code>import React from "react";
function PlantDefuser() {
var interval
function planting() {
interval = setInterval(() => {
console.log("Defuser Planted")
}, 1000)
}
function notPlanting() {
console.log(interval)
clearInterval(interval)
}
return (
<button onMouseDown={planting} onMouseUp={notPlanting}>Press and Hold</button>
)
}
export default PlantDefuser
</code></pre>
|
[
{
"answer_id": 74620188,
"author": "Martinez",
"author_id": 19027584,
"author_profile": "https://Stackoverflow.com/users/19027584",
"pm_score": 3,
"selected": true,
"text": "useRef ref import { useRef } from \"react\";\n\nconst PlantDefuser = () => {\n const interval = useRef();\n\n function planting() {\n interval.current = setInterval(() => {\n console.log(\"Defuser Planted\");\n }, 1000);\n }\n\n function notPlanting() {\n clearInterval(interval.current);\n }\n\n return (\n <button onMouseDown={planting} onMouseUp={notPlanting}>\n Press and Hold\n </button>\n );\n}\n\nexport default PlantDefuser\n"
},
{
"answer_id": 74620189,
"author": "Angel Zlatanov",
"author_id": 14342112,
"author_profile": "https://Stackoverflow.com/users/14342112",
"pm_score": 0,
"selected": false,
"text": "import React, { useState } from \"react\";\n\nconst PlantDefuser = () => {\n const [plantingInterval, setPlantingInterval] = useState(null);\n\n const planting = () => {\n const plantingIntervalId = setInterval(() => {\n console.log(\"Defuser Planted\");\n }, 1000);\n setPlantingInterval(plantingIntervalId);\n };\n\n const notPlanting = () => {\n clearInterval(plantingInterval);\n setPlantingInterval(null);\n };\n\n return (\n <button onMouseDown={planting} onMouseUp={notPlanting}>\n Press and Hold\n </button>\n );\n};\n\nexport default PlantDefuser;\n"
},
{
"answer_id": 74620493,
"author": "monim",
"author_id": 16632344,
"author_profile": "https://Stackoverflow.com/users/16632344",
"pm_score": 0,
"selected": false,
"text": "cleanup function clearInterval function PlantDefuser() {\n const [run, setRun] = useState(false);\n\n useEffect(() => {\n if (run) {\n const countTimer = setInterval(() => {\n console.log(\"Defuser Planted\");\n }, 1000);\n\n return () => {\n console.log(countTimer);\n clearInterval(countTimer);\n };\n }\n }, [run]);\n\n return (\n <button onMouseDown={() => setRun(!run)} onMouseUp={() => setRun(!run)}>\n Press and Hold\n </button>\n );\n}\n\nexport default PlantDefuser;\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74620126",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14030389/"
] |
74,620,166
|
<p>I want to get the information about the people followed by the Twitter account "POTUS" in a dictionary. My code:</p>
<pre><code>import tweepy, json
client = tweepy.Client(bearer_token=x)
id = client.get_user(username="POTUS").data.id
users = client.get_users_following(id=id, user_fields=['created_at','description','entities','id', 'location', 'name', 'pinned_tweet_id', 'profile_image_url','protected','public_metrics','url','username','verified','withheld'], expansions=['pinned_tweet_id'], max_results=13)
</code></pre>
<p>This query returns the type "Response", which in turn stores the type "User":</p>
<p><code>Response(data=[<User id=7563792 name=U.S. Men's National Soccer Team username=USMNT>, <User id=1352064843432472578 name=White House COVID-19 Response Team username=WHCOVIDResponse>, <User id=1351302423273472012 name=Kate Bedingfield username=WHCommsDir>, <User id=1351293685493878786 name=Susan Rice username=AmbRice46>, ..., <User id=1323730225067339784 name=The White House username=WhiteHouse>], includes={}, errors=[], meta={'result_count': 13})</code></p>
<p>I've tried <code>._json</code> and <code>.json()</code> but both didn't work.</p>
<p>Does anyone have any idea how I can convert this response into a dictionary object to work with?
Thanks in advance</p>
|
[
{
"answer_id": 74620188,
"author": "Martinez",
"author_id": 19027584,
"author_profile": "https://Stackoverflow.com/users/19027584",
"pm_score": 3,
"selected": true,
"text": "useRef ref import { useRef } from \"react\";\n\nconst PlantDefuser = () => {\n const interval = useRef();\n\n function planting() {\n interval.current = setInterval(() => {\n console.log(\"Defuser Planted\");\n }, 1000);\n }\n\n function notPlanting() {\n clearInterval(interval.current);\n }\n\n return (\n <button onMouseDown={planting} onMouseUp={notPlanting}>\n Press and Hold\n </button>\n );\n}\n\nexport default PlantDefuser\n"
},
{
"answer_id": 74620189,
"author": "Angel Zlatanov",
"author_id": 14342112,
"author_profile": "https://Stackoverflow.com/users/14342112",
"pm_score": 0,
"selected": false,
"text": "import React, { useState } from \"react\";\n\nconst PlantDefuser = () => {\n const [plantingInterval, setPlantingInterval] = useState(null);\n\n const planting = () => {\n const plantingIntervalId = setInterval(() => {\n console.log(\"Defuser Planted\");\n }, 1000);\n setPlantingInterval(plantingIntervalId);\n };\n\n const notPlanting = () => {\n clearInterval(plantingInterval);\n setPlantingInterval(null);\n };\n\n return (\n <button onMouseDown={planting} onMouseUp={notPlanting}>\n Press and Hold\n </button>\n );\n};\n\nexport default PlantDefuser;\n"
},
{
"answer_id": 74620493,
"author": "monim",
"author_id": 16632344,
"author_profile": "https://Stackoverflow.com/users/16632344",
"pm_score": 0,
"selected": false,
"text": "cleanup function clearInterval function PlantDefuser() {\n const [run, setRun] = useState(false);\n\n useEffect(() => {\n if (run) {\n const countTimer = setInterval(() => {\n console.log(\"Defuser Planted\");\n }, 1000);\n\n return () => {\n console.log(countTimer);\n clearInterval(countTimer);\n };\n }\n }, [run]);\n\n return (\n <button onMouseDown={() => setRun(!run)} onMouseUp={() => setRun(!run)}>\n Press and Hold\n </button>\n );\n}\n\nexport default PlantDefuser;\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74620166",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20638190/"
] |
74,620,173
|
<p>I would like to know if it is the optimal way to set values on a array</p>
<pre><code>fun setParameters(myArray: MutableList<Symbol>, instance: MutationData){
myArray.forEachIndexed { index, valArr ->
myArray[index] = setValues(valArr, members?.settings)
myArray[index] = setValueForByReference(instance, myArray[index])
}
}
</code></pre>
<p>or if exist a better way as create another array and fill into and after return the new array I don't know what do you think?</p>
<p>learn if I did right with this solution or get a optimal way to solve</p>
|
[
{
"answer_id": 74620358,
"author": "Jiya",
"author_id": 12017533,
"author_profile": "https://Stackoverflow.com/users/12017533",
"pm_score": 2,
"selected": false,
"text": "mapIndexed myArray.mapIndexed { index, valArr ->\n setValues(valArr, members?.settings)\n setValueForByReference(instance, myArray[index])\n }\n"
},
{
"answer_id": 74628925,
"author": "Tenfour04",
"author_id": 506796,
"author_profile": "https://Stackoverflow.com/users/506796",
"pm_score": 2,
"selected": true,
"text": "myArray.forEachIndexed { index, valArr ->\n val interimValue = setValues(valArr, members?.settings)\n myArray[index] = setValueForByReference(instance, interimValue)\n}\n map map index val newList = myArray.map { valArr ->\n val interimValue = setValues(valArr, members?.settings)\n setValueForByReference(instance, interimValue)\n}\n forEachIndexed() ?.settings val settings = members?.settings\nmyArray.forEachIndexed { index, valArr ->\n val interimValue = setValues(valArr, settings)\n myArray[index] = setValueForByReference(instance, interimValue)\n}\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74620173",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19898656/"
] |
74,620,193
|
<p>A want to check if input string is in right format</p>
<pre><code>"%d/%d"
</code></pre>
<p>For example, when the input will be</p>
<pre><code>"3/5"
return 1;
</code></pre>
<p>And when the input will be</p>
<pre><code>"3/5f"
return 0;
</code></pre>
<p>I have idea to do this using regex, but I had problem to run regex.h on windows.</p>
|
[
{
"answer_id": 74620358,
"author": "Jiya",
"author_id": 12017533,
"author_profile": "https://Stackoverflow.com/users/12017533",
"pm_score": 2,
"selected": false,
"text": "mapIndexed myArray.mapIndexed { index, valArr ->\n setValues(valArr, members?.settings)\n setValueForByReference(instance, myArray[index])\n }\n"
},
{
"answer_id": 74628925,
"author": "Tenfour04",
"author_id": 506796,
"author_profile": "https://Stackoverflow.com/users/506796",
"pm_score": 2,
"selected": true,
"text": "myArray.forEachIndexed { index, valArr ->\n val interimValue = setValues(valArr, members?.settings)\n myArray[index] = setValueForByReference(instance, interimValue)\n}\n map map index val newList = myArray.map { valArr ->\n val interimValue = setValues(valArr, members?.settings)\n setValueForByReference(instance, interimValue)\n}\n forEachIndexed() ?.settings val settings = members?.settings\nmyArray.forEachIndexed { index, valArr ->\n val interimValue = setValues(valArr, settings)\n myArray[index] = setValueForByReference(instance, interimValue)\n}\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74620193",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18905898/"
] |
74,620,209
|
<p>I have a dictionary with lists (with strings inside) and I need I need to check if a string appears anywhere among those lists.
Here is an example</p>
<pre><code>classes = {
"class_A" : ["Mike","Alice","Peter"],
"class_B" : ["Sam","Robert","Anna"],
"class_C" : ["Tom","Nick","Jack"]
}
students=["Alice","Frodo","Jack"]
for student in students:
if student *in any of the classes*:
print("Is here")
else:
print("Is not here")
</code></pre>
<p>For every student in the list I provided: if that student is in any of the classes, do A, if not do B.
Currently the output is <code>Is here, Is not here, Is here</code></p>
<p>Here is my current code:</p>
<pre><code>studentsInClasses=[]
for studentsInClass in classes.values()
studentsInClasses+=studentsInClass
students=["Alice","Frodo","Jack"]
for student in students:
if student in studentsInClasses:
print("Is here")
else:
print("Is not here")
</code></pre>
<p>But this is happening inside a complex structure of classes, functions and loops so it become a major performance issue as soon as I scale up the inputs.
Here is something that I do like, but is a bit annoying as I have to make sure that whatever function my code is in, has access to this one:</p>
<pre><code>def check(student,classes):
for value in classes.values():
if student in value:
return True
return False
</code></pre>
<p>It is probably as good as it gets, but I would like to know if there is a simple one liner that does the job.</p>
<p><em>Requirements</em>:</p>
<ul>
<li>Does not create a copy of the lists</li>
<li>Does not rely on keys in any way</li>
<li>Preferably nice and simple</li>
<li>Isn't an over-engineered superefficient solution</li>
</ul>
<p>I am new to stack overflow, if I am doing any major mistakes in my way of posting please do tell, I will try to improve my question writing.</p>
<p>Thanks</p>
|
[
{
"answer_id": 74620253,
"author": "trincot",
"author_id": 5459839,
"author_profile": "https://Stackoverflow.com/users/5459839",
"pm_score": 2,
"selected": false,
"text": "def check(student, classes):\n return any(student in value for value in classes.values())\n def checkall(students, classes):\n return [any(student in value for value in classes.values()) \n for student in students]\n"
},
{
"answer_id": 74620260,
"author": "Alexandru DuDu",
"author_id": 12003966,
"author_profile": "https://Stackoverflow.com/users/12003966",
"pm_score": 0,
"selected": false,
"text": "is here is not here classes = {\n \"class_A\" : [\"Mike\",\"Alice\",\"Peter\"],\n \"class_B\" : [\"Sam\",\"Robert\",\"Anna\"],\n \"class_C\" : [\"Tom\",\"Nick\",\"Jack\"]\n}\nfor line in str(classes).split(\",\"):\n if student in line:\n print(\"Student in here\")\n else:\n print(\"Student not here\")\n"
},
{
"answer_id": 74620283,
"author": "C.Nivs",
"author_id": 7867968,
"author_profile": "https://Stackoverflow.com/users/7867968",
"pm_score": 0,
"selected": false,
"text": "set from itertools import chain\n\nvalues = set(chain(*classes.values()))\n\nstudents=[\"Alice\",\"Frodo\",\"Jack\"]\n\nfor student in students:\n if student in values:\n print(\"Is here\")\n else:\n print(\"Is not here\")\n\n set"
},
{
"answer_id": 74620312,
"author": "spacether",
"author_id": 4175822,
"author_profile": "https://Stackoverflow.com/users/4175822",
"pm_score": 0,
"selected": false,
"text": "class_to_students = {\n \"class_A\" : {\"Mike\",\"Alice\",\"Peter\"},\n \"class_B\" : {\"Sam\",\"Robert\",\"Anna\"},\n \"class_C\" : {\"Tom\",\"Nick\",\"Jack\"}\n}\nstudents=[\"Alice\",\"Frodo\",\"Jack\"]\nfor student in students:\n for class_students in class_to_students.values():\n if student in class_students:\n print(f\"{student} Is here\")\n break\n else:\n # loop was not broken out of\n print(f\"{student} Is not here\")\n Alice Is here\nFrodo Is not here\nJack Is here\n"
},
{
"answer_id": 74620326,
"author": "Guillaume BEDOYA",
"author_id": 20522241,
"author_profile": "https://Stackoverflow.com/users/20522241",
"pm_score": 0,
"selected": false,
"text": "classes = {\n \"class_A\": [\"Mike\",\"Alice\",\"Peter\"],\n \"class_B\": [\"Sam\",\"Robert\",\"Anna\"],\n \"class_C\": [\"Tom\",\"Nick\",\"Jack\"]\n}\n\nstudents = [\"Alice\", \"Frodo\", \"Jack\"]\nres = [student in class_ for class_ in classes.values() for student in students ]\nprint(res)\n"
},
{
"answer_id": 74620420,
"author": "Nico",
"author_id": 12797458,
"author_profile": "https://Stackoverflow.com/users/12797458",
"pm_score": 1,
"selected": true,
"text": "studentsInClasses=[]\nfor studentsInClass in classes.values()\n studentsInClasses+=studentsInClass\n\nstudentsInClasses = sorted(studentsInClasses)\nstudents=sorted([\"Alice\",\"Frodo\",\"Jack\"])\n\nlastMatch=0\nfor i in range(len(students)):\n student = students[i]\n try:\n lastMatch = studentsInClasses[lastMatch:].index(student)\n print(f\"{student} in class\")\n except ValueError as e:\n pass\n\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74620209",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20199109/"
] |
74,620,214
|
<p>I have seen names within square brackets in a site's CSS:</p>
<pre class="lang-css prettyprint-override"><code>/* simplified example */
body {
grid-template-columns:
[main-menu]
20%
[content]
40%
[asides]
20%
[ads]
20%
;
}
</code></pre>
<p><a href="https://developer.mozilla.org/en-US/docs/Web/CSS/grid-template-columns#values" rel="nofollow noreferrer">MDN's documentation</a> explains that these are custom identifiers and that one can add many of them within the square brackets.</p>
<p>Yet it does not talk about why one would use them and which effect this has. My first guess was that they are cosmetic and help to structure the code. But deleting these lines, or replacing them with a value like <code>0</code> or <code>auto</code> changes the layout.</p>
<p>Why would one use them? Which effect do they have?</p>
|
[
{
"answer_id": 74620506,
"author": "Temani Afif",
"author_id": 8620333,
"author_profile": "https://Stackoverflow.com/users/8620333",
"pm_score": 2,
"selected": false,
"text": "body {\n display: grid;\n grid-template-columns: \n [main-menu] \n 20%\n [content] \n 40%\n [asides]\n 20%\n [ads] \n 20%\n ;\n}\n\n.ads {\n grid-area: ads; /* I will get placed at the line called \"ads\" in the template */\n height: 100px;\n background: red;\n} <div class=\"ads\"></div> [linename] <custom-ident> <custom-ident> <custom-ident>-start <custom-ident>-end"
},
{
"answer_id": 74620789,
"author": "Nils Lindemann",
"author_id": 1658543,
"author_profile": "https://Stackoverflow.com/users/1658543",
"pm_score": -1,
"selected": true,
"text": "body {\n display: grid;\n grid-template-columns:\n [menu]\n 20%\n [content]\n 60%\n [aside]\n 20%\n ;\n}\n body {\n display: grid;\n grid-template-columns: \n 20%\n 60%\n 20%\n ;\n grid-template-areas: \n \"menu content aside\"\n ;\n}\n body {\n margin:0;\n width: 100vw;\n height:100vh;\n display: grid;\n\n grid-template-columns:\n [left] 20%\n [center] 60%\n [right] 20%\n ;\n grid-template-rows:\n [top] 20%\n [middle] 60%\n [bottom] 20%\n ;\n}\n\n.header {\n grid-area: top / left / top-end / right-end;\n background: yellow;\n}\n\n.menu {\n grid-area: middle / left / middle-end / left-end;\n background: lime;\n}\n\n.content {\n grid-area: middle / center / middle-end / center-end;\n background: skyblue;\n}\n\n.aside {\n grid-area: middle / right / middle-end / right-end;\n background: orange;\n}\n\n.footer {\n grid-area: bottom / left / bottom-end / right-end;\n background: forestgreen;\n} <div class=\"header\"></div>\n<div class=\"menu\"></div>\n<div class=\"content\"></div>\n<div class=\"aside\"></div>\n<div class=\"footer\"></div> grid-template-areas body {\n margin:0;\n width: 100vw;\n height:100vh;\n display: grid;\n\n grid-template-columns:\n 20%\n 60%\n 20%\n ;\n grid-template-rows:\n 20%\n 60%\n 20%\n ;\n grid-template-areas:\n \"header header header\"\n \"menu content aside\"\n \"footer footer footer\"\n ;\n\n}\n\n.header {\n grid-area: header;\n background: yellow;\n}\n\n.menu {\n grid-area: menu;\n background: lime;\n}\n\n.content {\n grid-area: content;\n background: skyblue;\n}\n\n.aside {\n grid-area: aside;\n background: orange;\n}\n\n.footer {\n grid-area: footer;\n background: forestgreen;\n} <div class=\"header\"></div>\n<div class=\"menu\"></div>\n<div class=\"content\"></div>\n<div class=\"aside\"></div>\n<div class=\"footer\"></div> grid-template-areas"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74620214",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1658543/"
] |
74,620,231
|
<p>I'm a university student. and the teacher wants me to pass multiple strings to function. The answer output is correct but I wonder what the warning is why it shows and how to fix it in my case.</p>
<p>I try to figure it out but so many times I search. It just contains the other case and no one this like my case (using sting with pointer). So if you can additionally recommend me the website that has my case or something with passing 2d array to function I will appreciate it so much.</p>
<p>Here's the code</p>
<pre><code>#include <stdio.h>
#include <string.h>
int hydroxide(char (*message)[100], int size);
int main()
{
char message[6][100] = {"KOH", "H2O2", "NaCl", "NaOH", "C9H8O4", "MgOH"};
int size;
printf("Messages ending with OH are: ");
for(int i = 0; i < 6; i++)
{
size = strlen(message[i]);
if(hydroxide(message[i], size) == 1)
{
printf("%s ", message[i]);
}
}
printf("\n");
return 1;
}
int hydroxide(char (*message)[100], int size)
{
if(((*message)[size - 2] == 'O') && ((*message)[size - 1] == 'H'))
{
return 1;
}
else
{
return 0;
}
}
</code></pre>
<p>When I try running it, it shows like this.</p>
<pre><code>HW-4_5_3.c: In function 'main':
HW-4_5_3.c:19:22: warning: passing argument 1 of 'hydroxide' from incompatible pointer type [-Wincompatible-pointer-types]
if(hydroxide(message[i], size) == 1)
^~~~~~~
HW-4_5_3.c:6:5: note: expected 'char (*)[100]' but argument is of type 'char *'
int hydroxide(char (*message)[100], int size);
^~~~~~~~~
Messages ending with OH are: KOH NaOH MgOH
</code></pre>
<p>The part that "Messages ending with OH are: KOH NaOH MgOH" is what I want. So, how can I fix it?</p>
|
[
{
"answer_id": 74620266,
"author": "Ted Lyngmo",
"author_id": 7582247,
"author_profile": "https://Stackoverflow.com/users/7582247",
"pm_score": 0,
"selected": false,
"text": "int hydroxide(char (*message)[100], int size);\n char[100] if(hydroxide(&message[i], size) == 1)\n// ^\n hydroxide int hydroxide(char *message, int size)\n{\n if(size < 2) return 0; // added precaution\n\n if((message[size - 2] == 'O') && (message[size - 1] == 'H'))\n {\n return 1;\n }\n else\n {\n return 0;\n }\n}\n"
},
{
"answer_id": 74620294,
"author": "Vlad from Moscow",
"author_id": 2877241,
"author_profile": "https://Stackoverflow.com/users/2877241",
"pm_score": 3,
"selected": true,
"text": "int hydroxide(char (*message)[100], int size);\n char ( * )[100] if(hydroxide(message[i], size) == 1)\n char * message[i] char[100] char * int hydroxide( const char *message )\n{\n size_t n = strlen( message );\n\n return n > 1 && message[n-2] == 'O' && message[n-1] == 'H';\n}\n if ( hydroxide(message[i] ) )\n const 2 1 0"
},
{
"answer_id": 74620295,
"author": "ChrisSc",
"author_id": 16872665,
"author_profile": "https://Stackoverflow.com/users/16872665",
"pm_score": 1,
"selected": false,
"text": "int hydroxide(char *message, int size);\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74620231",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20079730/"
] |
74,620,239
|
<p>I need to write a report in SSRS</p>
<p>I need the numbers to display as listed below</p>
<p>0.3555 is displayed as 0.35</p>
<p>0 is displayed as 0 Instead I get 0.00</p>
<p>So far I have =FormatNumber(Fields!Day3.Value, 2) to only have two decimal but now I need it to be 0 when there is no decimal How do I do that?</p>
|
[
{
"answer_id": 74620266,
"author": "Ted Lyngmo",
"author_id": 7582247,
"author_profile": "https://Stackoverflow.com/users/7582247",
"pm_score": 0,
"selected": false,
"text": "int hydroxide(char (*message)[100], int size);\n char[100] if(hydroxide(&message[i], size) == 1)\n// ^\n hydroxide int hydroxide(char *message, int size)\n{\n if(size < 2) return 0; // added precaution\n\n if((message[size - 2] == 'O') && (message[size - 1] == 'H'))\n {\n return 1;\n }\n else\n {\n return 0;\n }\n}\n"
},
{
"answer_id": 74620294,
"author": "Vlad from Moscow",
"author_id": 2877241,
"author_profile": "https://Stackoverflow.com/users/2877241",
"pm_score": 3,
"selected": true,
"text": "int hydroxide(char (*message)[100], int size);\n char ( * )[100] if(hydroxide(message[i], size) == 1)\n char * message[i] char[100] char * int hydroxide( const char *message )\n{\n size_t n = strlen( message );\n\n return n > 1 && message[n-2] == 'O' && message[n-1] == 'H';\n}\n if ( hydroxide(message[i] ) )\n const 2 1 0"
},
{
"answer_id": 74620295,
"author": "ChrisSc",
"author_id": 16872665,
"author_profile": "https://Stackoverflow.com/users/16872665",
"pm_score": 1,
"selected": false,
"text": "int hydroxide(char *message, int size);\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74620239",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18356622/"
] |
74,620,273
|
<p>I have application with drawing option using jQuery. On Desktop everything works well but lines are not drawn on mobile devices. On touchmove and touchstart I can trigger console logs but line is not show. Here is my code so far:</p>
<pre><code><script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script>
var mousePressed = false;
var lastX, lastY;
var ctx;
var ctxtwo;
var color;
ctx = document.getElementById('myCanvas').getContext("2d");
ctxtwo = document.getElementById('myCanvasTwo').getContext("2d");
$('#skinModal').click(function () {
$(".spectrum-input").change(function () {
color = $(this).val();
});
})
$("#skin-condition-save").click(function () {
document.getElementById('right_side_face_canvas').value = document.getElementById('myCanvas').toDataURL('image/png');
document.getElementById('left_side_face_canvas').value = document.getElementById('myCanvasTwo').toDataURL('image/png');
});
$('#myCanvas, #myCanvasTwo').mousedown(function (e) {
var second = false;
if (e.target.id == 'myCanvasTwo') {
second = true;
}
mousePressed = true;
Draw(e.pageX - $(this).offset().left, e.pageY - $(this).offset().top, false, second);
});
$('#myCanvas, #myCanvasTwo').on("touchstart", function (e) {
console.log('first');
var second = false;
if (e.target.id == 'myCanvasTwo') {
console.log('second');
second = true;
}
mousePressed = true;
Draw(e.pageX - $(this).offset().left, e.pageY - $(this).offset().top, false, second);
});
$('#myCanvas, #myCanvasTwo').mousemove(function (e) {
var second = false;
if (e.target.id == 'myCanvasTwo') {
second = true;
}
if (mousePressed) {
Draw(e.pageX - $(this).offset().left, e.pageY - $(this).offset().top, true, second);
}
});
$('#myCanvas, #myCanvasTwo').on("touchmove", function (e) {
console.log('111');
var second = false;
if (e.target.id == 'myCanvasTwo') {
console.log('222');
second = true;
}
if (mousePressed) {
Draw(e.pageX - $(this).offset().left, e.pageY - $(this).offset().top, true, second);
}
});
$('#myCanvas, #myCanvasTwo').mouseup(function (e) {
mousePressed = false;
});
$('#myCanvas, #myCanvasTwo').mouseleave(function (e) {
mousePressed = false;
});
function Draw(x, y, isDown, isSecond) {
if (isDown) {
if (isSecond) {
ctxtwo.beginPath();
ctxtwo.strokeStyle = color;
ctxtwo.lineWidth = $('#selWidth').val();
ctxtwo.lineJoin = "round";
ctxtwo.moveTo(lastX, lastY);
ctxtwo.lineTo(x, y);
ctxtwo.closePath();
ctxtwo.stroke();
} else {
ctx.beginPath();
ctx.strokeStyle = color;
ctx.lineWidth = $('#selWidth').val();
ctx.lineJoin = "round";
ctx.moveTo(lastX, lastY);
ctx.lineTo(x, y);
ctx.closePath();
ctx.stroke();
}
}
lastX = x;
lastY = y;
}
function clearArea() {
// Use the identity matrix while clearing the canvas
ctx.setTransform(1, 0, 0, 1, 0, 0);
ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
}
function clearAreaTwo() {
// Use the identity matrix while clearing the canvas
ctxtwo.setTransform(1, 0, 0, 1, 0, 0);
ctxtwo.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
}
</script>
</code></pre>
<p>What code modifications would I need to make to be able to draw on mobile devices?</p>
|
[
{
"answer_id": 74620266,
"author": "Ted Lyngmo",
"author_id": 7582247,
"author_profile": "https://Stackoverflow.com/users/7582247",
"pm_score": 0,
"selected": false,
"text": "int hydroxide(char (*message)[100], int size);\n char[100] if(hydroxide(&message[i], size) == 1)\n// ^\n hydroxide int hydroxide(char *message, int size)\n{\n if(size < 2) return 0; // added precaution\n\n if((message[size - 2] == 'O') && (message[size - 1] == 'H'))\n {\n return 1;\n }\n else\n {\n return 0;\n }\n}\n"
},
{
"answer_id": 74620294,
"author": "Vlad from Moscow",
"author_id": 2877241,
"author_profile": "https://Stackoverflow.com/users/2877241",
"pm_score": 3,
"selected": true,
"text": "int hydroxide(char (*message)[100], int size);\n char ( * )[100] if(hydroxide(message[i], size) == 1)\n char * message[i] char[100] char * int hydroxide( const char *message )\n{\n size_t n = strlen( message );\n\n return n > 1 && message[n-2] == 'O' && message[n-1] == 'H';\n}\n if ( hydroxide(message[i] ) )\n const 2 1 0"
},
{
"answer_id": 74620295,
"author": "ChrisSc",
"author_id": 16872665,
"author_profile": "https://Stackoverflow.com/users/16872665",
"pm_score": 1,
"selected": false,
"text": "int hydroxide(char *message, int size);\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74620273",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7202135/"
] |
74,620,284
|
<p>I faced a problem with com.netflix.eureka:eureka-client:2.0.0-rc.4 <a href="https://i.stack.imgur.com/qqkAC.png" rel="nofollow noreferrer">build</a></p>
<p>(Sorry for pom screenshots, was too much code here)</p>
<p><a href="https://i.stack.imgur.com/ts2SZ.png" rel="nofollow noreferrer">pom1</a></p>
<p><a href="https://i.stack.imgur.com/Q4gvX.png" rel="nofollow noreferrer"><br />
pom2</a></p>
<p><a href="https://i.stack.imgur.com/0q3dG.png" rel="nofollow noreferrer"><br />
pom3</a></p>
<p>How can I resolve this dependency?</p>
<p>I tried to add a <a href="https://i.stack.imgur.com/FYF1v.png" rel="nofollow noreferrer">dependency</a></p>
<p>But it didn't help.</p>
<p>Maven clean install and deleting .m2 repo also didn't help.</p>
|
[
{
"answer_id": 74620266,
"author": "Ted Lyngmo",
"author_id": 7582247,
"author_profile": "https://Stackoverflow.com/users/7582247",
"pm_score": 0,
"selected": false,
"text": "int hydroxide(char (*message)[100], int size);\n char[100] if(hydroxide(&message[i], size) == 1)\n// ^\n hydroxide int hydroxide(char *message, int size)\n{\n if(size < 2) return 0; // added precaution\n\n if((message[size - 2] == 'O') && (message[size - 1] == 'H'))\n {\n return 1;\n }\n else\n {\n return 0;\n }\n}\n"
},
{
"answer_id": 74620294,
"author": "Vlad from Moscow",
"author_id": 2877241,
"author_profile": "https://Stackoverflow.com/users/2877241",
"pm_score": 3,
"selected": true,
"text": "int hydroxide(char (*message)[100], int size);\n char ( * )[100] if(hydroxide(message[i], size) == 1)\n char * message[i] char[100] char * int hydroxide( const char *message )\n{\n size_t n = strlen( message );\n\n return n > 1 && message[n-2] == 'O' && message[n-1] == 'H';\n}\n if ( hydroxide(message[i] ) )\n const 2 1 0"
},
{
"answer_id": 74620295,
"author": "ChrisSc",
"author_id": 16872665,
"author_profile": "https://Stackoverflow.com/users/16872665",
"pm_score": 1,
"selected": false,
"text": "int hydroxide(char *message, int size);\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74620284",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14375179/"
] |
74,620,285
|
<p>I have a dataframe and I need to find the most acess hour from the day. I think i need to do some for loops to store the values and after find the most acess hour.</p>
<p>My code until now is:</p>
<p><code>df['date_time'] = pd.to_datetime(df['date_time']) </code></p>
<p>This me return:</p>
<pre><code>0 2022-11-24 19:18:37
1 2022-11-25 00:45:35
2 2022-11-25 00:48:01
3 2022-11-25 00:59:38
4 2022-11-25 01:01:07
...
890 2022-11-29 20:55:13
891 2022-11-29 20:55:33
892 2022-11-29 20:56:30
893 2022-11-29 20:57:01
894 2022-11-29 21:06:27
Name: date_time, Length: 895, dtype: datetime64[ns]
</code></pre>
<p>This dataframe have 7 days of data, I need find the most acess hour for every day, and of the week. I tried using some for's loop but i dont know much about the Pandas. I will learn more the documentation but if someone knows how to solve this problem....</p>
<p>Thankssss</p>
|
[
{
"answer_id": 74620266,
"author": "Ted Lyngmo",
"author_id": 7582247,
"author_profile": "https://Stackoverflow.com/users/7582247",
"pm_score": 0,
"selected": false,
"text": "int hydroxide(char (*message)[100], int size);\n char[100] if(hydroxide(&message[i], size) == 1)\n// ^\n hydroxide int hydroxide(char *message, int size)\n{\n if(size < 2) return 0; // added precaution\n\n if((message[size - 2] == 'O') && (message[size - 1] == 'H'))\n {\n return 1;\n }\n else\n {\n return 0;\n }\n}\n"
},
{
"answer_id": 74620294,
"author": "Vlad from Moscow",
"author_id": 2877241,
"author_profile": "https://Stackoverflow.com/users/2877241",
"pm_score": 3,
"selected": true,
"text": "int hydroxide(char (*message)[100], int size);\n char ( * )[100] if(hydroxide(message[i], size) == 1)\n char * message[i] char[100] char * int hydroxide( const char *message )\n{\n size_t n = strlen( message );\n\n return n > 1 && message[n-2] == 'O' && message[n-1] == 'H';\n}\n if ( hydroxide(message[i] ) )\n const 2 1 0"
},
{
"answer_id": 74620295,
"author": "ChrisSc",
"author_id": 16872665,
"author_profile": "https://Stackoverflow.com/users/16872665",
"pm_score": 1,
"selected": false,
"text": "int hydroxide(char *message, int size);\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74620285",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18334056/"
] |
74,620,324
|
<p>using <code>Getx</code>, when I have a <code>GetxController</code> and I want to use it inside my view UI, it required removing <code>const</code> on the widget constructor :</p>
<p>Controller :</p>
<pre><code>class TestController extends GetxController {
// ...
}
</code></pre>
<p>View :</p>
<pre><code> class TextWidget extends StatelessWidget {
const TextWidget({super.key}); // throws error
final controller = Get.put(TestController());
@override
Widget build(BuildContext context) {
return Container();
}
}
</code></pre>
<p>it throws an error on the const line :</p>
<pre><code>> Can't define the 'const' constructor because the field 'controller' is initialized with a non-constant value.
</code></pre>
<p>so it requires me to delete the <code>const</code>, but since adding <code>const</code> is recommended for better performance, I want to let it there and use my controller.</p>
<p>I could shut down this error by declaring the controller inside the <code>build()</code> method, but I guess it's not a good idea.</p>
|
[
{
"answer_id": 74620325,
"author": "Gwhyyy",
"author_id": 18670641,
"author_profile": "https://Stackoverflow.com/users/18670641",
"pm_score": 1,
"selected": true,
"text": "build() Get.put() final controller = Get.put(TestController());\n const getter GetxController TestController get controller => Get.put(TestController());\n final const GetView<T> class TextWidget extends GetView<TestController> {\n const TextWidget({super.key});\n @override\n Widget build(BuildContext context) {\n return Text(\"${controller.index}\"); // use controller directly to access controller.\n }\n}\n GetView<T> controller"
},
{
"answer_id": 74627329,
"author": "Sparko Sol",
"author_id": 20407048,
"author_profile": "https://Stackoverflow.com/users/20407048",
"pm_score": 1,
"selected": false,
"text": "class HomeController extends GetxController {}\n class HomeBinding extends Bindings {\n @override\n void dependencies() {\n Get.put<HomeController>(HomeController());\n }\n}\n class HomePage extends GetView<HomeController> {\n const HomePage({Key? key}) : super(key: key);\n\n @override\n Widget build(BuildContext context) {\n return Scaffold(\n appBar: AppBar(title: const Text('Homepage')),\n );\n }\n}\n await Get.to(\n () => const HomePage(),\n binding: HomeBinding(),\n);\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74620324",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18670641/"
] |
74,620,364
|
<p>I am trying to understand chain assignment in Python.</p>
<p>If I run <code>x = x[1] = [1, 2]</code>, I get an infinite list <code>[1, [...]]</code>.</p>
<p>But if I run <code>x = x[1:] = [1, 2]</code>, I will get a normal list <code>[1, 1, 2]</code>.</p>
<p>How does it work in the background to make these two different results?</p>
|
[
{
"answer_id": 74620393,
"author": "John Gordon",
"author_id": 494134,
"author_profile": "https://Stackoverflow.com/users/494134",
"pm_score": 0,
"selected": false,
"text": "x = x[1] = [1, 2]\n x x[1] ... x = x[1:] = [1, 2]\n x"
},
{
"answer_id": 74620523,
"author": "Jiya",
"author_id": 12017533,
"author_profile": "https://Stackoverflow.com/users/12017533",
"pm_score": 0,
"selected": false,
"text": "x = x[1] = [1, 2] # Output: [1, [...]]\n x = x[1:] = [1, 2] # Output: [1, 1, 2]\n"
},
{
"answer_id": 74620550,
"author": "chepner",
"author_id": 1126841,
"author_profile": "https://Stackoverflow.com/users/1126841",
"pm_score": 3,
"selected": true,
"text": "x = y = z t = z # A new temporary variable \"t\" to hold the result of evaluating z\nx = t\ny = t\ndel t\n t x[1] x[1:] x t x[1] x[2] t[0] t[1] x t = [1,2]\nx = t\nx[1] = t\ndel t\n x[1] x list.__repr__ ... x x[1] x[1][1] [1,2] t = [1,2]\nx = t\nx[1:] = t\ndel t\n x[1] 1 x t x x[2] 2 x[1:] = t x = [x[0]]; x.extend(t)"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74620364",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20638160/"
] |
74,620,380
|
<p>The idea is that there are two models: Group and Player. My objective is that there are different Groups and each group has players. Each player can belong to one or more groups. Inside a group, each player has some points accumulated, but the same player can have different points accumulated in another group.</p>
<pre><code>class Player(models.Model):
username = models.CharField(max_length = 200)
won_games = models.IntegerField(default=0)
class Point(models.Model):
player = models.ForeignKey(Player, on_delete=models.PROTECT, related_name='points')
val = models.IntegerField()
group = models.ForeignKey(Group, on_delete=models.PROTECT, related_name='points')
class Group(models.Model):
id = models.CharField(max_length = 200)
players = models.ManyToManyField(Player,related_name="groups")
points = models.ManyToManyField(Point)
</code></pre>
<p>I am confused because I don't know how to make that a player has "x" points in group A (for example) and also has "y" points in group B.
I want to be able to show the data of a group, for each group, show its members and their points.</p>
|
[
{
"answer_id": 74620393,
"author": "John Gordon",
"author_id": 494134,
"author_profile": "https://Stackoverflow.com/users/494134",
"pm_score": 0,
"selected": false,
"text": "x = x[1] = [1, 2]\n x x[1] ... x = x[1:] = [1, 2]\n x"
},
{
"answer_id": 74620523,
"author": "Jiya",
"author_id": 12017533,
"author_profile": "https://Stackoverflow.com/users/12017533",
"pm_score": 0,
"selected": false,
"text": "x = x[1] = [1, 2] # Output: [1, [...]]\n x = x[1:] = [1, 2] # Output: [1, 1, 2]\n"
},
{
"answer_id": 74620550,
"author": "chepner",
"author_id": 1126841,
"author_profile": "https://Stackoverflow.com/users/1126841",
"pm_score": 3,
"selected": true,
"text": "x = y = z t = z # A new temporary variable \"t\" to hold the result of evaluating z\nx = t\ny = t\ndel t\n t x[1] x[1:] x t x[1] x[2] t[0] t[1] x t = [1,2]\nx = t\nx[1] = t\ndel t\n x[1] x list.__repr__ ... x x[1] x[1][1] [1,2] t = [1,2]\nx = t\nx[1:] = t\ndel t\n x[1] 1 x t x x[2] 2 x[1:] = t x = [x[0]]; x.extend(t)"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74620380",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20637100/"
] |
74,620,396
|
<p>I have recently learned how to read ppm3(P3) images in C++. I just read RGB pixels written in a plain format. I want to convert some certain jpg pictures to ppm3 and then experiment with different things, like identifying numbers there, the circled answers in exam papers, etc.</p>
<p>I have tried this website: <a href="https://convertio.co/pdf-ppm/" rel="nofollow noreferrer">https://convertio.co/pdf-ppm/</a>, but it transformed a photo in the P6 format. Could anyone help?</p>
|
[
{
"answer_id": 74620447,
"author": "Mark Setchell",
"author_id": 2836621,
"author_profile": "https://Stackoverflow.com/users/2836621",
"pm_score": 1,
"selected": false,
"text": "magick INPUT.JPG -compress none OUTPUT.PPM\n -compress none convert INPUT.JPG -compress none OUTPUT.PPM\n magick INPUT.PPM OUTPUT.JPG\n magick INPUT.PPM OUTPUT.PNG\n #!/bin/bash\n\nW=5; H=4\necho \"P3\\n${W} ${H}\\n255\" > image.ppm\nfor ((i=0;i<$((W*H*3));i++)) ; do \n echo $((RANDOM%255))\ndone >> image.ppm\n magick image.ppm -scale 200x result.png\n #!/bin/bash\n\nW=5; H=4\n{\n printf \"P3\\n${W} ${H}\\n255\\n\"\n for ((i=0;i<$((W*H*3));i++)) ; do \n echo $((RANDOM%255))\n done\n} | magick ppm:- -scale 200x result.png\n jpegtopnm -plain INPUT.JPG > OUTPUT.PPM\n"
},
{
"answer_id": 74628972,
"author": "K J",
"author_id": 10802527,
"author_profile": "https://Stackoverflow.com/users/10802527",
"pm_score": 0,
"selected": false,
"text": "255 ÿ ÿ 255 "
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74620396",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8576092/"
] |
74,620,401
|
<p>I am working on what i thought is a simple algorithm:</p>
<blockquote>
<p>Task: Look at the given array, take only the even numbers and multiply them by 2. The catch is to modify the array in its place and NOT create a new array.</p>
</blockquote>
<p>I can loop/map through an array and figure out what numbers are even, so
I got this far:</p>
<pre><code>const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
arr.forEach((x, y) => {
if (x % 2 !== 0) {
// I would like to splice those numbers,
// but can't figure out how to do it?
}
})
</code></pre>
<p>Again, the catch is that modifying the original array is not allowed, returning 4, 8, 12, 16, and 20.</p>
|
[
{
"answer_id": 74620496,
"author": "Carsten Massmann",
"author_id": 2610061,
"author_profile": "https://Stackoverflow.com/users/2610061",
"pm_score": 0,
"selected": false,
"text": "const arr=[1,2,3,4,5,6,7,8,9,10];\n\nfor (let i=arr.length-1;i>=0;i--)\n if(arr[i]%2>0) arr.splice(i,1)\narr.forEach((v,i,a)=> a[i]=v*2)\n\nconsole.log(arr); 0"
},
{
"answer_id": 74620542,
"author": "Angel Zlatanov",
"author_id": 14342112,
"author_profile": "https://Stackoverflow.com/users/14342112",
"pm_score": 2,
"selected": true,
"text": "const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];\n\nlet i = 0;\nwhile (i < arr.length) {\n if (arr[i] % 2 === 0) {\n arr[i] *= 2;\n } else {\n arr.splice(i, 1);\n i--;\n }\n i++;\n}\n\nconsole.log(arr.join(\", \"));\n"
},
{
"answer_id": 74620606,
"author": "Nina Scholz",
"author_id": 1447675,
"author_profile": "https://Stackoverflow.com/users/1447675",
"pm_score": 1,
"selected": false,
"text": "const\n array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];\n\nlet l = 0; i = 0;\n\nwhile (i < array.length) {\n console.log(...array);\n if (array[i] % 2 === 0) array[l++] = array[i] * 2;\n i++;\n}\n\narray.length = l;\n\nconsole.log(...array); .as-console-wrapper { max-height: 100% !important; top: 0; }"
},
{
"answer_id": 74620625,
"author": "Yosvel Quintero",
"author_id": 1932552,
"author_profile": "https://Stackoverflow.com/users/1932552",
"pm_score": 1,
"selected": false,
"text": "const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\n\nconst result = arr\n .filter(n => n % 2 === 0)\n .map(n => n * 2)\n\nconsole.log(result)"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74620401",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18992987/"
] |
74,620,449
|
<p>I have dialog fragment and i set my custom view to it. I want to make it with round corners and im using CardView for it, but the shape of dialog is still rectangle. Here is my view:</p>
<pre><code> <?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="16dp"
app:cardCornerRadius="40dp">
<androidx.constraintlayout.widget.ConstraintLayout
android:id="@+id/card_cl"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="36dp">
<androidx.appcompat.widget.AppCompatTextView
android:id="@+id/id_tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:textSize="36sp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:text="12" />
</androidx.constraintlayout.widget.ConstraintLayout>
</androidx.cardview.widget.CardView>
</code></pre>
<p>the result :
<a href="https://i.stack.imgur.com/eCCKi.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/eCCKi.png" alt="enter image description here" /></a></p>
|
[
{
"answer_id": 74620496,
"author": "Carsten Massmann",
"author_id": 2610061,
"author_profile": "https://Stackoverflow.com/users/2610061",
"pm_score": 0,
"selected": false,
"text": "const arr=[1,2,3,4,5,6,7,8,9,10];\n\nfor (let i=arr.length-1;i>=0;i--)\n if(arr[i]%2>0) arr.splice(i,1)\narr.forEach((v,i,a)=> a[i]=v*2)\n\nconsole.log(arr); 0"
},
{
"answer_id": 74620542,
"author": "Angel Zlatanov",
"author_id": 14342112,
"author_profile": "https://Stackoverflow.com/users/14342112",
"pm_score": 2,
"selected": true,
"text": "const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];\n\nlet i = 0;\nwhile (i < arr.length) {\n if (arr[i] % 2 === 0) {\n arr[i] *= 2;\n } else {\n arr.splice(i, 1);\n i--;\n }\n i++;\n}\n\nconsole.log(arr.join(\", \"));\n"
},
{
"answer_id": 74620606,
"author": "Nina Scholz",
"author_id": 1447675,
"author_profile": "https://Stackoverflow.com/users/1447675",
"pm_score": 1,
"selected": false,
"text": "const\n array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];\n\nlet l = 0; i = 0;\n\nwhile (i < array.length) {\n console.log(...array);\n if (array[i] % 2 === 0) array[l++] = array[i] * 2;\n i++;\n}\n\narray.length = l;\n\nconsole.log(...array); .as-console-wrapper { max-height: 100% !important; top: 0; }"
},
{
"answer_id": 74620625,
"author": "Yosvel Quintero",
"author_id": 1932552,
"author_profile": "https://Stackoverflow.com/users/1932552",
"pm_score": 1,
"selected": false,
"text": "const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\n\nconst result = arr\n .filter(n => n % 2 === 0)\n .map(n => n * 2)\n\nconsole.log(result)"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74620449",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19971105/"
] |
74,620,455
|
<p>I can't seem to find a ready answer to this, or even if the question has ever been asked before, but I want functionality similar to the SQL STRING_SPLIT functions floating around, where each item in a comma separated list is identified by its ordinal in the string.</p>
<p>Given the string "abc,xyz,def,tuv", I want to get a list of tuples like:</p>
<pre><code><1, "abc">
<2, "xyz">
<3, "def">
<4, "tuv">
</code></pre>
<p>Order is important, and I need to preserve the order, and be able to take the list and further join it with another list using linq, and be able to preserve the order. For example, if a second list is <"tuv", "abc">, I want the final output of the join to be:</p>
<pre><code><1, "abc">
<4, "tuv">
</code></pre>
<p>Basically, I want the comma separated string to determine the ORDER of the end result, where the comma separated string contains ALL possible strings, and it is joined with an unordered list of a subset of strings, and the output is a list of ordered tuples that consists only of the elements in the second list, but in the order determined by the comma separated string at the beginning.</p>
<p>I could likely figure out all of this on my own if I could just get a C# equivalent to all the various SQL STRING_SPLIT functions out there, which do the split but also include the ordinal element number in the output. But I've searched, and I find nothing for C# but splitting a string into individual elements, or splitting them into tuples where both elements of the tuple are in the string itself, not generated integers to preserve order.</p>
<p>The order is the important thing to me here. So if an element number isn't readily possible, a way to inner join two lists and guarantee preserving the order of the first list while returning only those elements in the second list would be welcome. The tricky part for me is this last part: the result of a join needs a specific (not easy to sort by) order. The ordinal number would give me something to sort by, but if I can inner join with some guarantee the output is in the same order as the first input, that'd work too.</p>
|
[
{
"answer_id": 74620586,
"author": "Vic F",
"author_id": 4054386,
"author_profile": "https://Stackoverflow.com/users/4054386",
"pm_score": 0,
"selected": false,
"text": "string[] vals = new[] { \"abc\", \"xyz\", \"dev\", \"tuv\"};\n\nstring[] results = new string[vals.Length];\n\nint index = 0;\n\nfor (int i = 0; i < vals.Length; i++)\n{\n results[i] = $\"<{++index},\\\"{vals[i]}\\\">\";\n}\n\nforeach (var item in results)\n{\n Console.WriteLine(item);\n}\n <1,\"abc\">\n<2,\"xyz\">\n<3,\"dev\">\n<4,\"tuv\">\n"
},
{
"answer_id": 74620593,
"author": "T.S.",
"author_id": 1704458,
"author_profile": "https://Stackoverflow.com/users/1704458",
"pm_score": 2,
"selected": false,
"text": "var input = \"abc,xyz,def,tuv\";\nstring[] items = input.Split(',');\nvar tuples = new List<(int, string)>();\nfor (int i = 0; i < items.Length)\n{\n tuples.Add(((i + 1), items[i]));\n}\n \"tuv\" \"abc\" int int int var input2 = \"xxx,xyz,yyy,tuv,\";\nstring[] items2 = input2.Split(',');\n\nIEnumerable<(int, string)> finalTupleOutput = \n tuples.Join(items2, t => t.Item2, i2 => i2, (t, i2) => (t.Item1, i2)).OrderBy(tpl => tpl.Item1);\n\n L2 L1"
},
{
"answer_id": 74620656,
"author": "Ethan Shannon",
"author_id": 18621413,
"author_profile": "https://Stackoverflow.com/users/18621413",
"pm_score": 3,
"selected": true,
"text": "using System.Linq;\nstring str = \"abc,xyz,def,tuv\";\nstring str2 = \"abc,tuv\";\n\n\nIEnumerable< PretendFileObject> secondList = str2.Split(',').Select(x=> new PretendFileObject() { FileName = x}); //\n\nvar tups = str.Split(',')\n .Select((x, i) => { return (i + 1, x); })\n .Join(secondList, //Join Second list ON \n item => item.Item2 //This is the filename in the tuples \n ,item2 => item2.FileName, // This is the filename property for a given object in the second list to join on\n (item,item2) => new {Index = item.Item1,FileName = item.Item2, Obj = item2})\n .OrderBy(JoinedObject=> JoinedObject.Index)\n .ToList();\n\nforeach (var tup in tups)\n{\n Console.WriteLine(tup.Obj.FileName);\n}\n\n\npublic class PretendFileObject\n{\n public string FileName { get; set; }\n public string Foo { get; set; }\n}\n using System.Linq;\nstring str = \"abc,xyz,def,tuv\";\nstring str2 = \"abc,tuv\";\nvar secondList = str2.Split(',');\n\nvar tups = str.Split(',')\n .Select((x, i) => { return (i + 1, x); })\n .IntersectBy(secondList, s=>s.Item2) //Filter down to only the strings found in both.\n .ToList();\n\nforeach(var tup in tups)\n{\n Console.WriteLine(tup);\n}\n"
},
{
"answer_id": 74620688,
"author": "Ram Singh",
"author_id": 627885,
"author_profile": "https://Stackoverflow.com/users/627885",
"pm_score": 1,
"selected": false,
"text": "string inputString = \"abc,xyz,def,tuv\";\nvar output = inputString.Split(',')\n.Select((item, index) => { return (index + 1, item); });\n output"
},
{
"answer_id": 74620745,
"author": "Ingenioushax",
"author_id": 6177689,
"author_profile": "https://Stackoverflow.com/users/6177689",
"pm_score": 0,
"selected": false,
"text": "List<string> temp = new List<string>() { \"abc\", \"def\", \"xyz\", \"tuv\" };\nList<string> temp2 = new List<string>() { \"dbc\", \"ace\", \"zyw\", \"tke\", \"abc\", \"xyz\" };\nvar intersect = temp.Intersect(temp2).Select((list, idx) => (idx+1, list));\n <1, \"abc\">\n<2, \"xyz\">\n Intersect Union"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74620455",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/594448/"
] |
74,620,471
|
<p>I have 2 dict objects with the same key but different elements.I would like to merge them into one dict.</p>
<p>First, I used append and it works but append is deprecated so that I prefer to use concat.</p>
<p>here is the code :</p>
<pre><code>data1 = {'a':1, 'b':2}
data2 = {'a':3, 'b':4}
list = [data1, data2]
df = pd.DataFrame()
for x in range(len(list)):
df = df.append(list[x], ignore_index=True)
df
</code></pre>
<p>The code below works with append. In my case I would like to have concat
Maybe you can help. Thanks</p>
|
[
{
"answer_id": 74620586,
"author": "Vic F",
"author_id": 4054386,
"author_profile": "https://Stackoverflow.com/users/4054386",
"pm_score": 0,
"selected": false,
"text": "string[] vals = new[] { \"abc\", \"xyz\", \"dev\", \"tuv\"};\n\nstring[] results = new string[vals.Length];\n\nint index = 0;\n\nfor (int i = 0; i < vals.Length; i++)\n{\n results[i] = $\"<{++index},\\\"{vals[i]}\\\">\";\n}\n\nforeach (var item in results)\n{\n Console.WriteLine(item);\n}\n <1,\"abc\">\n<2,\"xyz\">\n<3,\"dev\">\n<4,\"tuv\">\n"
},
{
"answer_id": 74620593,
"author": "T.S.",
"author_id": 1704458,
"author_profile": "https://Stackoverflow.com/users/1704458",
"pm_score": 2,
"selected": false,
"text": "var input = \"abc,xyz,def,tuv\";\nstring[] items = input.Split(',');\nvar tuples = new List<(int, string)>();\nfor (int i = 0; i < items.Length)\n{\n tuples.Add(((i + 1), items[i]));\n}\n \"tuv\" \"abc\" int int int var input2 = \"xxx,xyz,yyy,tuv,\";\nstring[] items2 = input2.Split(',');\n\nIEnumerable<(int, string)> finalTupleOutput = \n tuples.Join(items2, t => t.Item2, i2 => i2, (t, i2) => (t.Item1, i2)).OrderBy(tpl => tpl.Item1);\n\n L2 L1"
},
{
"answer_id": 74620656,
"author": "Ethan Shannon",
"author_id": 18621413,
"author_profile": "https://Stackoverflow.com/users/18621413",
"pm_score": 3,
"selected": true,
"text": "using System.Linq;\nstring str = \"abc,xyz,def,tuv\";\nstring str2 = \"abc,tuv\";\n\n\nIEnumerable< PretendFileObject> secondList = str2.Split(',').Select(x=> new PretendFileObject() { FileName = x}); //\n\nvar tups = str.Split(',')\n .Select((x, i) => { return (i + 1, x); })\n .Join(secondList, //Join Second list ON \n item => item.Item2 //This is the filename in the tuples \n ,item2 => item2.FileName, // This is the filename property for a given object in the second list to join on\n (item,item2) => new {Index = item.Item1,FileName = item.Item2, Obj = item2})\n .OrderBy(JoinedObject=> JoinedObject.Index)\n .ToList();\n\nforeach (var tup in tups)\n{\n Console.WriteLine(tup.Obj.FileName);\n}\n\n\npublic class PretendFileObject\n{\n public string FileName { get; set; }\n public string Foo { get; set; }\n}\n using System.Linq;\nstring str = \"abc,xyz,def,tuv\";\nstring str2 = \"abc,tuv\";\nvar secondList = str2.Split(',');\n\nvar tups = str.Split(',')\n .Select((x, i) => { return (i + 1, x); })\n .IntersectBy(secondList, s=>s.Item2) //Filter down to only the strings found in both.\n .ToList();\n\nforeach(var tup in tups)\n{\n Console.WriteLine(tup);\n}\n"
},
{
"answer_id": 74620688,
"author": "Ram Singh",
"author_id": 627885,
"author_profile": "https://Stackoverflow.com/users/627885",
"pm_score": 1,
"selected": false,
"text": "string inputString = \"abc,xyz,def,tuv\";\nvar output = inputString.Split(',')\n.Select((item, index) => { return (index + 1, item); });\n output"
},
{
"answer_id": 74620745,
"author": "Ingenioushax",
"author_id": 6177689,
"author_profile": "https://Stackoverflow.com/users/6177689",
"pm_score": 0,
"selected": false,
"text": "List<string> temp = new List<string>() { \"abc\", \"def\", \"xyz\", \"tuv\" };\nList<string> temp2 = new List<string>() { \"dbc\", \"ace\", \"zyw\", \"tke\", \"abc\", \"xyz\" };\nvar intersect = temp.Intersect(temp2).Select((list, idx) => (idx+1, list));\n <1, \"abc\">\n<2, \"xyz\">\n Intersect Union"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74620471",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11779489/"
] |
74,620,474
|
<p>I am having trouble with some basic IO operations using Clojure. I have a text file which I need to read, split with the "|" character, and enter into a list for later processing. Here are the contents of my text file:</p>
<pre><code>1|John Smith|123 Here Street|456-4567
2|Sue Jones|43 Rose Court Street|345-7867
3|Fan Yuhong|165 Happy Lane|345-4533
</code></pre>
<p>And here is my current code:</p>
<pre class="lang-clj prettyprint-override"><code>((defn -main []
(println "Enter an option: \n")
(let [choice (read-line)]
(cond (= choice "1")
(let [cust-contents (slurp "file.txt")
nums-as-strings (clojure.string/split cust-contents #"|")
numbers (map read-string nums-as-strings)]
(print numbers)
)
)
) ) )
(-main)
</code></pre>
<p>I would think this code to work, however here is the error I get when running my program:</p>
<pre><code>(; Execution error at user/eval7923$-main (REPL:11).
; EOF while reading
</code></pre>
<p>Could anyone please guide me on where I went wrong and on how to fix this?</p>
|
[
{
"answer_id": 74620709,
"author": "Alan Thompson",
"author_id": 1822379,
"author_profile": "https://Stackoverflow.com/users/1822379",
"pm_score": 0,
"selected": false,
"text": "((defn ... (ns tst.demo.core\n (:use demo.core tupelo.core tupelo.test)\n (:require\n [tupelo.csv :as csv]))\n\n(verify\n ; ***** NOTE ***** most CSV has a header line, which is added below for convenience!\n (let [data-str \"id|name|address|phone\n 1|John Smith|123 Here Street|456-4567\n 2|Sue Jones|43 Rose Court Street|345-7867\n 3|Fan Yuhong|165 Happy Lane|345-4533 \"\n entity-maps (csv/csv->entities data-str {:separator \\|})]\n (is= entity-maps\n [{:address \"123 Here Street\", :id \"1\", :name \"John Smith\", :phone \"456-4567\"}\n {:address \"43 Rose Court Street\", :id \"2\", :name \"Sue Jones\", :phone \"345-7867\"}\n {:address \"165 Happy Lane\", :id \"3\", :name \"Fan Yuhong\", :phone \"345-4533\"}])))\n (verify\n (let [data-str \"1|John Smith|123 Here Street|456-4567\n 2|Sue Jones|43 Rose Court Street|345-7867\n 3|Fan Yuhong|165 Happy Lane|345-4533 \"\n data-lines (str/split-lines data-str)\n token-table-str (vec (for [line data-lines]\n (let [token-strs (str/split line #\"\\|\")]\n (mapv str/trim token-strs))))]\n (is= token-table-str\n [[\"1\" \"John Smith\" \"123 Here Street\" \"456-4567\"]\n [\"2\" \"Sue Jones\" \"43 Rose Court Street\" \"345-7867\"]\n [\"3\" \"Fan Yuhong\" \"165 Happy Lane\" \"345-4533\"]])))\n"
},
{
"answer_id": 74620979,
"author": "Martin Půda",
"author_id": 13590263,
"author_profile": "https://Stackoverflow.com/users/13590263",
"pm_score": 3,
"selected": true,
"text": "read-string \" \" \" \" clojure.string/split #\"\\|\" #\"|\" read-string \"456-4567\" clojure.string/split-lines 2 Display Product Table, 3. Display Sales Table case cond (ns homework.core\n (:require [clojure.string :as s])\n (:gen-class))\n\n(defn -main []\n (println \"Enter an option: \\n\")\n (let [choice (read-line)]\n (case choice\n \"1\" (->> (s/split-lines (slurp \"file.txt\"))\n (mapv #(s/split % #\"\\|\"))\n println)\n \"Wrong number\")))\n\n(-main)\n"
},
{
"answer_id": 74637082,
"author": "Gwang-Jin Kim",
"author_id": 9690090,
"author_profile": "https://Stackoverflow.com/users/9690090",
"pm_score": 0,
"selected": false,
"text": "[clojure-csv/clojure-csv \"2.0.1\"] lein lein deps 1|John Smith|123 Here Street|456-4567 \n2|Sue Jones|43 Rose Court Street|345-7867 \n3|Fan Yuhong|165 Happy Lane|345-4533\n (ns csvread\n (:require [clojure-csv.core :as csv]))\n\n(defn parse-table [file]\n (csv/parse-csv (slurp file) :delimiter \\|))\n\n(defn parse-table-from-string [s]\n (csv/parse-csv s :delimiter \\|))\n (parse-table \"/home/me/test.csv\")\n;; => ([\"1\" \"John Smith\" \"123 Here Street\" \"456-4567\"] \n;; [\"2\" \"Sue Jones\" \"43 Rose Court Street\" \"345-7867\"] \n;; [\"3\" \"Fan Yuhong\" \"165 Happy Lane\" \"345-4533 \"])\n\n(def s \"1|John Smith|123 Here Street|456-4567 \n2|Sue Jones|43 Rose Court Street|345-7867 \n3|Fan Yuhong|165 Happy Lane|345-4533\")\n\n(parse-table-from-string s)\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74620474",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17360950/"
] |
74,620,478
|
<p>Working on a project for my bootcamp course, I was using my MacBook when writing the code for the index and it looked great. I have now switched over to my desktop and realized the footer is not at the bottom of my page. I have tried googling a solution but thus far nothing has worked to fix this. I also would have loved for my image links to have been a bit closer together but after playing around with the code, it doesn't seem to move. I also realized when making adjusting browser size it looks a bit off. I would greatly appreciate some assistance with this.</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>html {
background-image: url(https://wallpaperaccess.com/full/2510671.jpg);
background-size: cover;
background-repeat: no-repeat;
overflow: auto;
}
html body {
margin: 0;
height: 100%;
overflow: scroll;
}
.container {
max-width: 100%;
width: 100%;
}
h1 {
color: rgb(85, 13, 134);
font-family: 'Patrick Hand', cursive;
font-size: 80;
text-align: center;
font-weight: 900px;
border-style: rounded;
border-color: bisque;
border: solid;
background-color: rgba(230, 181, 213, 0.726);
border-radius: 10em;
border-width: 3;
padding: 2;
width: 900px;
height: 110px;
margin: auto;
margin-top: 30;
letter-spacing: 2;
}
#left {
display: flex;
justify-content: center;
padding: 160;
float: left;
margin-inline-start: auto;
}
#right {
display: flex;
justify-content: center;
padding: 160;
float: right;
margin-inline-start: auto;
}
img {
height: 200px;
width: 400px;
}
footer {
text-align: center;
color: rgb(85, 13, 134);
font-family: 'Patrick Hand', cursive, Arial, Helvetica, sans-serif;
font-size: 16;
font-weight: 60px;
letter-spacing: 2;
postion: fixed
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="css/style.css">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Patrick+Hand&display=swap" rel="stylesheet">
<title>Cheatsheet</title>
</head>
<header>
<h1>HTML and CSS Cheatsheet</h1>
</header>
<body>
<div>
<a href="HTML /index.html">
<img src="images/HTML logo.svg" id="left" width="800" height="200"></a>
</div>
<div>
<a href="CSS Sheet/index.html">
<img src="images/CSS Logo.svg" id="right" width="800" height="200"></a>
</div>
<footer>
<p>Created by: Stephanie M.</p>
<p>Connnect with me: stephanie678@gmail.com</p>
</footer>
</body>
</html></code></pre>
</div>
</div>
</p>
|
[
{
"answer_id": 74620709,
"author": "Alan Thompson",
"author_id": 1822379,
"author_profile": "https://Stackoverflow.com/users/1822379",
"pm_score": 0,
"selected": false,
"text": "((defn ... (ns tst.demo.core\n (:use demo.core tupelo.core tupelo.test)\n (:require\n [tupelo.csv :as csv]))\n\n(verify\n ; ***** NOTE ***** most CSV has a header line, which is added below for convenience!\n (let [data-str \"id|name|address|phone\n 1|John Smith|123 Here Street|456-4567\n 2|Sue Jones|43 Rose Court Street|345-7867\n 3|Fan Yuhong|165 Happy Lane|345-4533 \"\n entity-maps (csv/csv->entities data-str {:separator \\|})]\n (is= entity-maps\n [{:address \"123 Here Street\", :id \"1\", :name \"John Smith\", :phone \"456-4567\"}\n {:address \"43 Rose Court Street\", :id \"2\", :name \"Sue Jones\", :phone \"345-7867\"}\n {:address \"165 Happy Lane\", :id \"3\", :name \"Fan Yuhong\", :phone \"345-4533\"}])))\n (verify\n (let [data-str \"1|John Smith|123 Here Street|456-4567\n 2|Sue Jones|43 Rose Court Street|345-7867\n 3|Fan Yuhong|165 Happy Lane|345-4533 \"\n data-lines (str/split-lines data-str)\n token-table-str (vec (for [line data-lines]\n (let [token-strs (str/split line #\"\\|\")]\n (mapv str/trim token-strs))))]\n (is= token-table-str\n [[\"1\" \"John Smith\" \"123 Here Street\" \"456-4567\"]\n [\"2\" \"Sue Jones\" \"43 Rose Court Street\" \"345-7867\"]\n [\"3\" \"Fan Yuhong\" \"165 Happy Lane\" \"345-4533\"]])))\n"
},
{
"answer_id": 74620979,
"author": "Martin Půda",
"author_id": 13590263,
"author_profile": "https://Stackoverflow.com/users/13590263",
"pm_score": 3,
"selected": true,
"text": "read-string \" \" \" \" clojure.string/split #\"\\|\" #\"|\" read-string \"456-4567\" clojure.string/split-lines 2 Display Product Table, 3. Display Sales Table case cond (ns homework.core\n (:require [clojure.string :as s])\n (:gen-class))\n\n(defn -main []\n (println \"Enter an option: \\n\")\n (let [choice (read-line)]\n (case choice\n \"1\" (->> (s/split-lines (slurp \"file.txt\"))\n (mapv #(s/split % #\"\\|\"))\n println)\n \"Wrong number\")))\n\n(-main)\n"
},
{
"answer_id": 74637082,
"author": "Gwang-Jin Kim",
"author_id": 9690090,
"author_profile": "https://Stackoverflow.com/users/9690090",
"pm_score": 0,
"selected": false,
"text": "[clojure-csv/clojure-csv \"2.0.1\"] lein lein deps 1|John Smith|123 Here Street|456-4567 \n2|Sue Jones|43 Rose Court Street|345-7867 \n3|Fan Yuhong|165 Happy Lane|345-4533\n (ns csvread\n (:require [clojure-csv.core :as csv]))\n\n(defn parse-table [file]\n (csv/parse-csv (slurp file) :delimiter \\|))\n\n(defn parse-table-from-string [s]\n (csv/parse-csv s :delimiter \\|))\n (parse-table \"/home/me/test.csv\")\n;; => ([\"1\" \"John Smith\" \"123 Here Street\" \"456-4567\"] \n;; [\"2\" \"Sue Jones\" \"43 Rose Court Street\" \"345-7867\"] \n;; [\"3\" \"Fan Yuhong\" \"165 Happy Lane\" \"345-4533 \"])\n\n(def s \"1|John Smith|123 Here Street|456-4567 \n2|Sue Jones|43 Rose Court Street|345-7867 \n3|Fan Yuhong|165 Happy Lane|345-4533\")\n\n(parse-table-from-string s)\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74620478",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20550590/"
] |
74,620,494
|
<p>So I have a list of tuples which looks like:</p>
<pre><code>[(1, 60),
(1, 93),
(1, 104),
(1, 145),
(1, 159),
(4, 20),
(4, 30),
(4, 103),
(8, 8),
(9, 35),
(9, 172),
(9, 191),
(10, 33),
(10, 164),
(10, 185)]
</code></pre>
<p>However, the numbers on the left side of the tuple should all be unique. So I would like to have something like this:</p>
<pre><code>[(1, 60),
(4, 20),
(8, 8),
(9, 35),
(10, 33)]
</code></pre>
<p>I tried to make some unique functions in order to filter them out. But for example the count function does not work for integers.</p>
|
[
{
"answer_id": 74620531,
"author": "Ricardo",
"author_id": 16353662,
"author_profile": "https://Stackoverflow.com/users/16353662",
"pm_score": 2,
"selected": true,
"text": "test = [(1, 60),\n (1, 93),\n (1, 104),\n (1, 145),\n (1, 159),\n (4, 20),\n (4, 30),\n (4, 103),\n (8, 8),\n (9, 35),\n (9, 172),\n (9, 191),\n (10, 33),\n (10, 164),\n (10, 185)]\nseen = set()\nprint([x for x in test if x[0] not in seen and not seen.add(x[0])])\n>>>\n[(1, 60), (4, 20), (8, 8), (9, 35), (10, 33)]\n"
},
{
"answer_id": 74620544,
"author": "Pranav Hosangadi",
"author_id": 843953,
"author_profile": "https://Stackoverflow.com/users/843953",
"pm_score": 2,
"selected": false,
"text": "already_added already_added lst = [(1, 60),\n (1, 93),\n (1, 104),\n (1, 145),\n (1, 159),\n (4, 20),\n (4, 30),\n (4, 103),\n (8, 8),\n (9, 35),\n (9, 172),\n (9, 191),\n (10, 33),\n (10, 164),\n (10, 185)]\n\nresult = []\nalready_added = set()\n\nfor item in lst:\n if item[0] not in already_added:\n result.append(item)\n already_added.add(item[0]) \n result [(1, 60), (4, 20), (8, 8), (9, 35), (10, 33)]\n"
},
{
"answer_id": 74620579,
"author": "Marcelo Ruiz",
"author_id": 794402,
"author_profile": "https://Stackoverflow.com/users/794402",
"pm_score": 0,
"selected": false,
"text": "x=[(1, 60),\n (1, 93),\n (1, 104),\n (1, 145),\n (1, 159),\n (4, 20),\n (4, 30),\n (4, 103),\n (8, 8),\n (9, 35),\n (9, 172),\n (9, 191),\n (10, 33),\n (10, 164),\n (10, 185)]\nx.reverse()\nl={i:(i,j) for i,j in x}\nfilter_list = list(l.values())\nfilter_list.reverse()\n"
},
{
"answer_id": 74620683,
"author": "cards",
"author_id": 16462878,
"author_profile": "https://Stackoverflow.com/users/16462878",
"pm_score": 0,
"selected": false,
"text": "lst = # from above\n\n# if ordering is important\nlst = sorted(lst, key=lambda p: (p[0], -p[1]))\n\n# grant unicity in 1st entry (take latest entry for each repeated key)\nlst = {x: (x, y) for x, y in lst}\n\nres = list(lst.values())\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74620494",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20142969/"
] |
74,620,538
|
<p>I cannot send data of <code><textarea></code> to node js, Node js don't see the my sent data.</p>
<p>For Fetch data to Node Js</p>
<pre><code>
continueBtn.addEventListener("click", async () => {
console.log(myMsg.value)
console.log(typeof(myMsg.value))
const req = await fetch("/sendmsg", {method: "POST",body: myMsg.value}) ;
console.log("Fetched")
})
</code></pre>
<p>For get data in Node js</p>
<pre><code>const {userMessage} = Object.keys(req.body)
</code></pre>
|
[
{
"answer_id": 74620583,
"author": "Quentin",
"author_id": 19068,
"author_profile": "https://Stackoverflow.com/users/19068",
"pm_score": 2,
"selected": false,
"text": "body text/plain req.body text/plain body Content-Type"
},
{
"answer_id": 74620609,
"author": "c0d3ster",
"author_id": 9571755,
"author_profile": "https://Stackoverflow.com/users/9571755",
"pm_score": 0,
"selected": false,
"text": "const {userMessage} = Object.keys(req.body) userMessage console.log(JSON.stringify(req.body))"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74620538",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20540520/"
] |
74,620,602
|
<p>I'd like to calculate a lagged rolling average on a complicated time-series dataset. Consider the toy example as follows:</p>
<pre class="lang-py prettyprint-override"><code>import numpy as np
import pandas as pd
np.random.seed(101)
fruit = ['apples', 'apples', 'apples', 'oranges', 'apples', 'oranges', 'oranges',
'oranges', 'apples', 'oranges', 'apples', 'apples']
people = ['alice']*6+['bob']*6
date = ['2022-01-01', '2022-01-03', '2022-01-04', '2022-01-04', '2022-01-11', '2022-01-11',
'2022-01-04', '2022-01-05', '2022-01-05', '2022-01-20', '2022-01-20', '2022-01-25']
count = np.random.poisson(4,size=12)
weight_per = np.round(np.random.uniform(1,3,size=12),2)
df = pd.DataFrame({'date':date, 'people':people, 'fruit':fruit,
'count':count, 'weight':weight_per*count})
df['date'] = pd.to_datetime(df.date)
</code></pre>
<p>This results in the following DataFrame:</p>
<pre><code> date people fruit count weight
0 2022-01-01 alice apples 2 2.72
1 2022-01-03 alice apples 6 11.28
2 2022-01-04 alice apples 5 13.80
3 2022-01-04 alice oranges 3 8.70
4 2022-01-11 alice apples 2 3.92
5 2022-01-11 alice oranges 3 5.76
6 2022-01-04 bob oranges 8 18.16
7 2022-01-05 bob oranges 5 8.25
8 2022-01-05 bob apples 5 6.20
9 2022-01-20 bob oranges 4 4.40
10 2022-01-20 bob apples 2 4.56
11 2022-01-25 bob apples 2 5.24
</code></pre>
<p>Now I'd like to add a column representing the average weight per fruit for the previous 7 days: <code>wgt_per_frt_prev_7d</code>. It should be defined as the sum of all the fruit weights divided by the sum of all the fruit counts for the past 7 days, not including the current day. While there are many ways to brute force this answer, I'm looking for something with relatively good time complexity. If I were to calculate this column by hand, these would be the calculations and expected results:</p>
<pre class="lang-py prettyprint-override"><code>df['wgt_per_frt_prev_7d'] = np.nan
df.loc[1, 'wgt_per_frt_prev_7d'] = 2.72/2 # row 0
df.loc[2, 'wgt_per_frt_prev_7d'] = (2.72+11.28)/(2+6) # row 0 and 1
df.loc[3, 'wgt_per_frt_prev_7d'] = (2.72+11.28)/(2+6)
df.loc[4, 'wgt_per_frt_prev_7d'] = (8.70+13.80+6.20+8.25+18.16)/(3+5+5+5+8) # row 2,3,6,7,8
df.loc[5, 'wgt_per_frt_prev_7d'] = (8.70+13.80+6.20+8.25+18.16)/(3+5+5+5+8)
df.loc[6, 'wgt_per_frt_prev_7d'] = (2.72+11.28)/(2+6) # row 0,1
df.loc[7, 'wgt_per_frt_prev_7d'] = (8.70+13.80+2.72+11.28+18.16)/(3+5+6+2+8) # row 0,1,2,3,6
df.loc[8, 'wgt_per_frt_prev_7d'] = (8.70+13.80+2.72+11.28+18.16)/(3+5+6+2+8)
df.loc[11, 'wgt_per_frt_prev_7d'] = (4.40+4.56)/(2+4) # row 9,10
</code></pre>
<p>Final DF:</p>
<pre><code>
date people fruit count weight wgt_per_frt_prev_7d
0 2022-01-01 alice apples 2 2.72 NaN
1 2022-01-03 alice apples 6 11.28 1.360000
2 2022-01-04 alice apples 5 13.80 1.750000
3 2022-01-04 alice oranges 3 8.70 1.750000
4 2022-01-11 alice apples 2 3.92 2.119615
5 2022-01-11 alice oranges 3 5.76 2.119615
6 2022-01-04 bob oranges 8 18.16 1.750000
7 2022-01-05 bob oranges 5 8.25 2.277500
8 2022-01-05 bob apples 5 6.20 2.277500
9 2022-01-20 bob oranges 4 4.40 NaN
10 2022-01-20 bob apples 2 4.56 NaN
11 2022-01-25 bob apples 2 5.24 1.493333
</code></pre>
<p>EDIT</p>
<p>The final column I'd like to add is <code>wgt_per_apl_prev_7d</code>, which only considers the apple weights when calculating this field, but still applies to all rows, even rows with just oranges. The output of this calculation should be as follows:</p>
<pre><code> date people fruit count weight wgt_per_frt_prev_7d wgt_per_apl_prev_7d
0 2022-01-01 alice apples 2 2.72 NaN NaN
1 2022-01-03 alice apples 6 11.28 1.360000 1.360000
2 2022-01-04 alice apples 5 13.80 1.750000 1.750000
3 2022-01-04 alice oranges 3 8.70 1.750000 1.750000
4 2022-01-11 alice apples 2 3.92 2.119615 2.000000
5 2022-01-11 alice oranges 3 5.76 2.119615 2.000000
6 2022-01-04 bob oranges 8 18.16 1.750000 1.750000
7 2022-01-05 bob oranges 5 8.25 2.277500 2.138462
8 2022-01-05 bob apples 5 6.20 2.277500 2.138462
9 2022-01-20 bob oranges 4 4.40 NaN NaN
10 2022-01-20 bob apples 2 4.56 NaN NaN
11 2022-01-25 bob apples 2 5.24 1.493333 2.280000
</code></pre>
|
[
{
"answer_id": 74620583,
"author": "Quentin",
"author_id": 19068,
"author_profile": "https://Stackoverflow.com/users/19068",
"pm_score": 2,
"selected": false,
"text": "body text/plain req.body text/plain body Content-Type"
},
{
"answer_id": 74620609,
"author": "c0d3ster",
"author_id": 9571755,
"author_profile": "https://Stackoverflow.com/users/9571755",
"pm_score": 0,
"selected": false,
"text": "const {userMessage} = Object.keys(req.body) userMessage console.log(JSON.stringify(req.body))"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74620602",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4942417/"
] |
74,620,623
|
<p>So I struggle only with part of task included in the title but my WHOLE task is to write linux bash script which is supposed to:</p>
<ol>
<li>read user name
if user found, print their UID, default shell, print home directory and groups they belong to
if user not found - create one with given $name</li>
<li>for each user list directories they own together with these dir's access permissions</li>
<li>in each of the listed directories (and subdirs) create file summary.txt containing list of its . directory and summarized size of dirs & files in this dir</li>
</ol>
<p>So far I have this code:
`</p>
<pre><code>#! /bin/bash
echo "input username"
read name
awk -F':' -v name="$name" '$1==name {
print "uid: " $3 "\nhome directory: "$6 "\n default shell: "$7
}' /etc/passwd
echo "belongs to groups:"
groups $name
#awk -F':' '{print }' /etc/group | grep $name
useradd -m $name
#ls -lR ~/ $name | awk '{print $3 " "$9" "$1}' #it shows everything, files as well
echo -e "\n\n listing dirs which user owns:"
find / -type d -user $name -ls | awk '{print $11 "\t" $3}'
echo -e "\n\n creating files summary.txt:"
for dir in $(find / -type d -user $name -ls);
do ls > summary.txt; du -sh ./>> summary.txt; done;
#find . -type d -exec touch summary.txt {} \;
</code></pre>
<p>`
Last lines is just one of many many tries and I see the FOR IN loop is invalid: it creates summary.txt file find-ls-times in the directory I run the script from and overwrites the previous summary all the time.
I need it to create this file in each directory owned by $name, eg. after creating user "maria" the output (run as sudo) is:</p>
<blockquote>
<p>uid: 1001
home dir: /home/maria
default shell: /bin/sh
belongs to groups:
maria : maria
useradd: user 'maria' already exists</p>
<p>listing dirs which user owns:
find: ‘/run/user/1000/doc’: Permission denied
find: ‘/run/user/1000/gvfs’: Permission denied
/home/maria drwxr-x---
/home/maria/.config drwxr-xr-x
/home/maria/.config/hexchat drwxr-xr-x
/home/maria/.config/qt5ct drwxr-xr-x
/home/maria/.config/caja drwxr-xr-x</p>
<p>creating files summary.txt:
find: ‘/run/user/1000/doc’: Permission denied
find: ‘/run/user/1000/gvfs’: Permission denied</p>
</blockquote>
<p>P.S. I know I list only dirs of given $name instead of all users but that's a minor problem, I'd be glad for pointing out different errors tho. Thanks</p>
|
[
{
"answer_id": 74622285,
"author": "Eric Marceau",
"author_id": 9716110,
"author_profile": "https://Stackoverflow.com/users/9716110",
"pm_score": 1,
"selected": false,
"text": "find . -mindepth 1 -maxdepth 1 -user ${owner} \\( ! -name 'summary.txt' \\) -print0 | sed 's+^\\./++' | xargs -0 stat --format=\"|%F|%y|%a|%U|%G|%s|%n|\"\n #! /bin/bash\n\n#QUESTION: https://stackoverflow.com/questions/74620623/bash-script-list-all-directories-belonging-to-user-and-create-file-in-each-of-t\n\necho \"input username\"\nread owner \n\nawk -F':' -v name=\"$owner\" '$1==name { \n print \"uid: \" $3 \"\\nhome directory: \"$6 \"\\n default shell: \"$7\n }' /etc/passwd\n\necho \"belongs to groups:\"\ngroups $owner\n#awk -F':' '{print }' /etc/group | grep $owner\n\n#useradd -m $owner \n#ls -lR ~/ $owner | awk '{print $3 \" \"$9\" \"$1}' #it shows everything, files as well\n\n### Original command format\n#find / -xdev -type d -user $owner -ls 2>>/dev/null > $$.tmp\n# 6820719 4 drwxr-xr-x 5 ericthered ericthered 4096 Nov 17 15:30 /media/ericthered\n\n\n### Do find only once, not multiple times\n### Generate reverse sorted list, to facilitate visual progress towards beginning of list (if visually monitoring outputs).\n### Also, want to control format of report to correctly identify dirname, \n### otherwise AWK may later incorrectly report full filename if there is a $12, $13, etc.\n### Output format: inode permissions username groupname modified filesize filename\n### FORMAT #1\n#find / -xdev -type d -user $owner -printf \"%i|%M|%u|%g|%Tb %Td %TY|%s|%p\\n\" 2>>/dev/null > $$.tmp\n### FORMAT #2\nfind / -xdev -type d -user $owner -printf \"%i|%M|%u|%g|%t|%s|%p\\n\" 2>>/dev/null | sort -nr > $$.tmp\nhead -10 $$.tmp\n\necho -e \"\\n\\n listing dirs which user owns:\"\n### If having permissions in the report is significant, \n### usually best to present so that \"deviations\" from norm are more self-evident, namely all lined up at begining.\nawk -F \\| '{ print $2 \"\\t\" $7 }' $$.tmp\n\necho -e \"\\n\\n creating files summary.txt:\"\nwhile read dir\ndo\n echo ${dir}\n ### Must do cd into ${dir} to simplify directory-specific actions, and get correct results\n cd ${dir}\n\n ### When some data is not same as the remainder in a file,\n ### it is best to have that non-conforming data at the top for visibility.\n du -sh \"${dir}\" > summary.txt\n ls -l >> summary.txt\ndone < $$.tmp\n\n### Unless specify a specific time value for touch,\n### touch time will vary from file to file.\n### Use time of last summary file created for common reference (newest).\nREFERENCE_FILE=\"$( tail -1 $$.tmp | awk -F\\| '{ print $7 }' )/summary.txt\"\n\nprintf \"\\n Setting '${REFERENCE_FILE}' as reference file for uniform timestamp ...\\n\"\n\n### This find and exec is malformed. -type will never find file to 'touch'.\n#find / -type d -user ${owner} -exec touch summary.txt {} \\;\n\nfind / -user ${owner} -name 'summary.txt' -print | xargs touch --reference=\"${REFERENCE_FILE}\"\n \nrm -f $$.tmp\n"
},
{
"answer_id": 74623023,
"author": "Jetchisel",
"author_id": 4452265,
"author_profile": "https://Stackoverflow.com/users/4452265",
"pm_score": 0,
"selected": false,
"text": "bash #!/usr/bin/env bash\n\nIFS= read -rp 'Input_name: ' name\n\n[[ -z \"$name\" ]] && {\n printf 'Please give a name as input!\\n' >&2\n exit 1\n}\n\nif IFS=: read -ra geckos_field < <(getent passwd \"$name\"); then\n printf 'uid: %s\\nhome_directory: %s\\ndefault_login_shell: %s\\n' \"${geckos_field[2]}\" \"${geckos_field[5]}\" \"${geckos_field[6]}\"\nelse\n useradd -m \"$name\" || exit\n IFS=: read -ra geckos_field < <(getent passwd \"$name\") || exit\n printf 'uid: %s\\nhome_directory: %s\\ndefault_login_shell: %s\\n' \"${geckos_field[2]}\" \"${geckos_field[5]}\" \"${geckos_field[6]}\"\nfi\n\nread -ra group_name < <(groups \"${geckos_field[0]}\") || exit\n\nprintf '\\nUser %s belongs to group(s):\\n' \"${geckos_field[0]}\"\nprintf '%s\\n' \"${group_name[@]:2}\"\n\nprintf '\\nDirectories for user %s:\\n' \"${geckos_field[0]}\"\nfind \"${geckos_field[5]}\" -type d -printf \"%M %p\\n\"\n\nfind \"${geckos_field[5]}\" -type d -exec bash -O nullglob -O dotglob -c '\n for f; do\n cd -- \"$f\" || exit; du -sh -- * > summary.txt\n done' _ {} +\n\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74620623",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20435110/"
] |
74,620,653
|
<p>Example data:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>some_parent_id</th>
<th>some_parent_name</th>
<th>some_subset_name</th>
<th>some_subset_id</th>
<th>address</th>
</tr>
</thead>
<tbody>
<tr>
<td>123456</td>
<td>SPECIAL</td>
<td>special_shop</td>
<td>9876</td>
<td>1234 road st</td>
</tr>
<tr>
<td>null</td>
<td>null</td>
<td>special_shop</td>
<td>9876</td>
<td>1234 road st</td>
</tr>
<tr>
<td>654321</td>
<td>NOT_SPECIAL</td>
<td>not_special_shop</td>
<td>9877</td>
<td>1258 diff st</td>
</tr>
<tr>
<td>654321</td>
<td>NOT_SPECIAL</td>
<td>not_special_shop</td>
<td>9877</td>
<td>1258 diff st</td>
</tr>
</tbody>
</table>
</div>
<p>I would like to find a query that returns only the below results - so only if there are 2 total records for some_subset_id, and only if one record has a null some_parent_id and the other record has a non-null some_parent_id.</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>some_parent_id</th>
<th>some_parent_name</th>
<th>some_subset_name</th>
<th>some_subset_id</th>
<th>address</th>
</tr>
</thead>
<tbody>
<tr>
<td>123456</td>
<td>SPECIAL</td>
<td>special_shop</td>
<td>9876</td>
<td>1234 road st</td>
</tr>
<tr>
<td>null</td>
<td>null</td>
<td>special_shop</td>
<td>9876</td>
<td>1234 road st</td>
</tr>
</tbody>
</table>
</div>
<p>The table I'm working with has well over 2 million records, and there are intentional duplicates, but unfortunately no unique identifier for rows. I did not create the table.</p>
|
[
{
"answer_id": 74622285,
"author": "Eric Marceau",
"author_id": 9716110,
"author_profile": "https://Stackoverflow.com/users/9716110",
"pm_score": 1,
"selected": false,
"text": "find . -mindepth 1 -maxdepth 1 -user ${owner} \\( ! -name 'summary.txt' \\) -print0 | sed 's+^\\./++' | xargs -0 stat --format=\"|%F|%y|%a|%U|%G|%s|%n|\"\n #! /bin/bash\n\n#QUESTION: https://stackoverflow.com/questions/74620623/bash-script-list-all-directories-belonging-to-user-and-create-file-in-each-of-t\n\necho \"input username\"\nread owner \n\nawk -F':' -v name=\"$owner\" '$1==name { \n print \"uid: \" $3 \"\\nhome directory: \"$6 \"\\n default shell: \"$7\n }' /etc/passwd\n\necho \"belongs to groups:\"\ngroups $owner\n#awk -F':' '{print }' /etc/group | grep $owner\n\n#useradd -m $owner \n#ls -lR ~/ $owner | awk '{print $3 \" \"$9\" \"$1}' #it shows everything, files as well\n\n### Original command format\n#find / -xdev -type d -user $owner -ls 2>>/dev/null > $$.tmp\n# 6820719 4 drwxr-xr-x 5 ericthered ericthered 4096 Nov 17 15:30 /media/ericthered\n\n\n### Do find only once, not multiple times\n### Generate reverse sorted list, to facilitate visual progress towards beginning of list (if visually monitoring outputs).\n### Also, want to control format of report to correctly identify dirname, \n### otherwise AWK may later incorrectly report full filename if there is a $12, $13, etc.\n### Output format: inode permissions username groupname modified filesize filename\n### FORMAT #1\n#find / -xdev -type d -user $owner -printf \"%i|%M|%u|%g|%Tb %Td %TY|%s|%p\\n\" 2>>/dev/null > $$.tmp\n### FORMAT #2\nfind / -xdev -type d -user $owner -printf \"%i|%M|%u|%g|%t|%s|%p\\n\" 2>>/dev/null | sort -nr > $$.tmp\nhead -10 $$.tmp\n\necho -e \"\\n\\n listing dirs which user owns:\"\n### If having permissions in the report is significant, \n### usually best to present so that \"deviations\" from norm are more self-evident, namely all lined up at begining.\nawk -F \\| '{ print $2 \"\\t\" $7 }' $$.tmp\n\necho -e \"\\n\\n creating files summary.txt:\"\nwhile read dir\ndo\n echo ${dir}\n ### Must do cd into ${dir} to simplify directory-specific actions, and get correct results\n cd ${dir}\n\n ### When some data is not same as the remainder in a file,\n ### it is best to have that non-conforming data at the top for visibility.\n du -sh \"${dir}\" > summary.txt\n ls -l >> summary.txt\ndone < $$.tmp\n\n### Unless specify a specific time value for touch,\n### touch time will vary from file to file.\n### Use time of last summary file created for common reference (newest).\nREFERENCE_FILE=\"$( tail -1 $$.tmp | awk -F\\| '{ print $7 }' )/summary.txt\"\n\nprintf \"\\n Setting '${REFERENCE_FILE}' as reference file for uniform timestamp ...\\n\"\n\n### This find and exec is malformed. -type will never find file to 'touch'.\n#find / -type d -user ${owner} -exec touch summary.txt {} \\;\n\nfind / -user ${owner} -name 'summary.txt' -print | xargs touch --reference=\"${REFERENCE_FILE}\"\n \nrm -f $$.tmp\n"
},
{
"answer_id": 74623023,
"author": "Jetchisel",
"author_id": 4452265,
"author_profile": "https://Stackoverflow.com/users/4452265",
"pm_score": 0,
"selected": false,
"text": "bash #!/usr/bin/env bash\n\nIFS= read -rp 'Input_name: ' name\n\n[[ -z \"$name\" ]] && {\n printf 'Please give a name as input!\\n' >&2\n exit 1\n}\n\nif IFS=: read -ra geckos_field < <(getent passwd \"$name\"); then\n printf 'uid: %s\\nhome_directory: %s\\ndefault_login_shell: %s\\n' \"${geckos_field[2]}\" \"${geckos_field[5]}\" \"${geckos_field[6]}\"\nelse\n useradd -m \"$name\" || exit\n IFS=: read -ra geckos_field < <(getent passwd \"$name\") || exit\n printf 'uid: %s\\nhome_directory: %s\\ndefault_login_shell: %s\\n' \"${geckos_field[2]}\" \"${geckos_field[5]}\" \"${geckos_field[6]}\"\nfi\n\nread -ra group_name < <(groups \"${geckos_field[0]}\") || exit\n\nprintf '\\nUser %s belongs to group(s):\\n' \"${geckos_field[0]}\"\nprintf '%s\\n' \"${group_name[@]:2}\"\n\nprintf '\\nDirectories for user %s:\\n' \"${geckos_field[0]}\"\nfind \"${geckos_field[5]}\" -type d -printf \"%M %p\\n\"\n\nfind \"${geckos_field[5]}\" -type d -exec bash -O nullglob -O dotglob -c '\n for f; do\n cd -- \"$f\" || exit; du -sh -- * > summary.txt\n done' _ {} +\n\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74620653",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20576980/"
] |
74,620,655
|
<p>Suppose I have a <code>numpy</code> array (or <code>pandas</code> <code>Series</code> if it makes it any easier), which looks like this:</p>
<pre><code>foo = np.array([1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0])
</code></pre>
<p>I want to transform into an array</p>
<pre><code>bar = np.array([0, 1, 2, 3, 4,0, 1, 2, 0, 1, 2, 3])
</code></pre>
<p>where the entry is how many steps you need to walk to the left to find a <code>1</code> in <code>foo</code>.</p>
<p>Now, obviously one can write a loop to compute <code>bar</code> from <code>foo</code>, but this will be bog slow. Is there anything more clever one can do?</p>
<p><strong>UPDATE</strong> The <code>pd.Series</code> solution is around 7 times slower than the pure <code>numpy</code> solution. The stupid loop solution is very slow (no surprise), but when jit compiled with <code>numba</code> is as fast as the <code>numpy</code> solution.</p>
|
[
{
"answer_id": 74620808,
"author": "BENY",
"author_id": 7964527,
"author_profile": "https://Stackoverflow.com/users/7964527",
"pm_score": 3,
"selected": false,
"text": "cumcount pandas s = pd.Series(foo)\nbar = s.groupby(s.cumsum()).cumcount().to_numpy()\nOut[13]: array([0, 1, 2, 3, 4, 0, 1, 2, 0, 1, 2, 3], dtype=int64)\n"
},
{
"answer_id": 74620956,
"author": "sammywemmy",
"author_id": 7175713,
"author_profile": "https://Stackoverflow.com/users/7175713",
"pm_score": 2,
"selected": false,
"text": "# get positions where value is 1\npos = foo.nonzero()[0]\n# need this when computing the cumsum\nvalues = np.diff(pos) - 1\narr = np.ones(foo.size, dtype=int)\narr[0] = 0\narr[pos[1:]] = -values\narr.cumsum()\n\narray([0, 1, 2, 3, 4, 0, 1, 2, 0, 1, 2, 3])\n"
},
{
"answer_id": 74675921,
"author": "August Vilakia",
"author_id": 20314495,
"author_profile": "https://Stackoverflow.com/users/20314495",
"pm_score": 1,
"selected": false,
"text": "numpy.cumsum() import numpy as np\n\n# Define the input array\nfoo = np.array([1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0])\n\n# Compute the cumulative sum of foo, but shift the values\n# to the right by one position and insert a 0 at the beginning\ncs = np.insert(np.cumsum(foo), 0, 0)\n\n# Subtract the shifted cumulative sum from the original cumulative sum\nbar = np.cumsum(foo) - cs\n\n# Print the result\nprint(bar)\n array([0, 1, 2, 3, 4, 0, 1, 2, 0, 1, 2, 3]) numpy.cumsum() numpy.cumsum() [1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0] [1, 1, 1, 1, 1, 2, 2, 2, 3, 3, 3, 3] numpy.insert() [0, 1, 1, 1, 1, 1, 2, 2, 2, 3, 3, 3] [0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0] foo"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74620655",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2977256/"
] |
74,620,662
|
<p>So, I'm working on this project and I added the following trigger to check age eligibility.</p>
<pre><code>create or replace TRIGGER AGEVALIDATION
BEFORE INSERT OR UPDATE ON RECIPIENT
FOR EACH ROW
BEGIN
IF (EXTRACT (YEAR FROM SYSDATE) - EXTRACT (YEAR FROM :NEW.DATE_OF_BIRTH)) < 12 THEN
raise_application_error(-20001,'VACCINE ELIGIBILITY AGE IS 12 AND ABOVE');
end if;
END;
</code></pre>
<p>The following trigger works but needs to handle the following errors. I need both ORA-06512 and ORA-6512 handled. Can anyone help me with this?</p>
<pre><code>Error starting at line : 1 in command -
INSERT INTO RECIPIENT(RECIPIENT_ID,FIRST_NAME,LAST_NAME,DATE_OF_BIRTH,CONTACT_NUMBER,STREET_ADDRESS,CITY,ZIPCODE,GENDER)
VALUES(152,'Batman1','adams','23-OCT-2019',6172544372,'234 HUNTINGTON AVE','BOSTON','02115','MALE')
Error report -
ORA-20001: VACCINE ELIGIBILITY AGE IS 12 AND ABOVE
ORA-06512: at "APP_ADMIN.AGEVALIDATION", line 3
ORA-04088: error during execution of trigger 'APP_ADMIN.AGEVALIDATION'
</code></pre>
|
[
{
"answer_id": 74620832,
"author": "MT0",
"author_id": 1509264,
"author_profile": "https://Stackoverflow.com/users/1509264",
"pm_score": 1,
"selected": false,
"text": "2022-01-01 2010-12-31 MONTHS_BETWEEN create or replace TRIGGER AGEVALIDATION \n BEFORE INSERT OR UPDATE ON RECIPIENT \n FOR EACH ROW\nBEGIN\n IF MONTHS_BETWEEN(SYSDATE, :NEW.DATE_OF_BIRTH) < 12*12 THEN\n raise_application_error(-20001,'VACCINE ELIGIBILITY AGE IS 12 AND ABOVE');\n END IF;\nEND;\n/\n INSERT"
},
{
"answer_id": 74621300,
"author": "Bob Jarvis - Слава Україні",
"author_id": 213136,
"author_profile": "https://Stackoverflow.com/users/213136",
"pm_score": 0,
"selected": false,
"text": "DECLARE\n excpUser_1 EXCEPTION;\n EXCEPTION_INIT(excpUser_1, -20001);\nBEGIN\n UPDATE RECIPIENT SET DATE_OF_BIRTH = SYSDATE - 3650; -- ten years, more or less\nEXCEPTION\n WHEN excpUser_1 THEN\n DBMS_OUTPUT.PUT_LINE('Caught excpUser_1');\nEND;\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74620662",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10828315/"
] |
74,620,671
|
<p>I'm creating a dynamic sidebar in a Document with a Google Apps Scripts sidebar served by HTMLService.</p>
<p>In the client-side sidebar template script, I can find my container via a jQuery selector and dynamically append DOM buttons to it, but I cannot remove any button elements from the same container (which is best practice since each holds an event handler which, as I understand it, would not be deleted from memory).</p>
<p>The function within the sidebar.html responsible for these actions:</p>
<pre><code>function fillContainerWithWords(arrayOfWords, container, wordClass) {
while (container.first()) { // empty word container
container.remove(container.first());
}
arrayOfWords.forEach(word => { // fill word container
let wordButton = `<div><button class="${wordClass}" onclick=getNewWords("${word}")>${word}</button></div>`;
container.append(wordButton);
})
}
</code></pre>
<p>CAN append to the container correctly, but DOES NOT remove any children from the container (so it ends up stacking DOM elements onto the container)</p>
<p>I've tried deviations of the same intent, such as:</p>
<ul>
<li>container.firstChild, <em>(typical javascript way)</em></li>
<li>$(container).firstChild, <em>(the jQuery way)</em></li>
<li>container.removeChild(container.first())</li>
</ul>
<p>and nothing seems to work.<br />
The "firstChild" approach produces an "undefined" (clearly not a property of the container.)
The code above is the closest I've managed, but produces an error deep in the jQuery implementation (or perhaps with Caja?):</p>
<pre><code> jquery.min.js:4 Uncaught TypeError: t.replace is not a function
at st.matchesSelector (**jquery.min.js:4:10383**)
at Function.filter (**jquery.min.js:4:23300**)
at init.remove (**jquery.min.js:4:26762**)
at **fillContainerWithWords** (userCodeAppPanel:73:17)
at userCodeAppPanel:55:17
at Of (2515706220-mae_html_user_bin_i18n_mae_html_user.js:94:266)
at 2515706220-mae_html_user_bin_i18n_mae_html_user.js:25:132
at Ug.U (2515706220-mae_html_user_bin_i18n_mae_html_user.js:123:380)
at Bd (2515706220-mae_html_user_bin_i18n_mae_html_user.js:54:477)
at a (2515706220-mae_html_user_bin_i18n_mae_html_user.js:52:52)
</code></pre>
<p>Any info on restrictions or possible options is greatly appreciated...</p>
<p>Stripped down minimum example:</p>
<p>Code.gs</p>
<pre><code>/**
* @OnlyCurrentDoc
*/
function onOpen(e) {
DocumentApp.getUi().createAddonMenu()
.addItem('Start', 'showSidebar')
.addToUi();
}
function onInstall(e) {
onOpen(e);
}
function showSidebar() {
const ui = HtmlService.createHtmlOutputFromFile('basic').setTitle('stackoverflow').setSandboxMode(HtmlService.SandboxMode.EMULATED);;
DocumentApp.getUi().showSidebar(ui);
}
</code></pre>
<p>basic.html</p>
<pre><code><!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<style>
.col-contain {
overflow: hidden;
}
.col-one {
float: left;
width: 50%;
}
.blue {
color: blue;
}
.red {
color: red;
}
</style>
<body>
<button class="blue" id="change-button">Change List</button>
<div class="block col-contain">
<div class="col-one" id="list"></div>
</div>
</body>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
$(function() {
$('#change-button').click(() => fillContainerWithWords(['five', 'six', 'seven'], $("#list"), 'blue'));
});
function fillContainerWithWords(arrayOfWords, container, wordClass) {
// while (container.first()) { // empty word container
// container.remove(container.first());
// }
arrayOfWords.forEach(word => { // fill word container
let wordButton = `<div><button class="${wordClass}">${word}</button></div>`;
container.append(wordButton);
})
}
fillContainerWithWords(['one', 'two', 'three', 'four'], $("#list"), 'red');
</script>
</html>
</code></pre>
|
[
{
"answer_id": 74620832,
"author": "MT0",
"author_id": 1509264,
"author_profile": "https://Stackoverflow.com/users/1509264",
"pm_score": 1,
"selected": false,
"text": "2022-01-01 2010-12-31 MONTHS_BETWEEN create or replace TRIGGER AGEVALIDATION \n BEFORE INSERT OR UPDATE ON RECIPIENT \n FOR EACH ROW\nBEGIN\n IF MONTHS_BETWEEN(SYSDATE, :NEW.DATE_OF_BIRTH) < 12*12 THEN\n raise_application_error(-20001,'VACCINE ELIGIBILITY AGE IS 12 AND ABOVE');\n END IF;\nEND;\n/\n INSERT"
},
{
"answer_id": 74621300,
"author": "Bob Jarvis - Слава Україні",
"author_id": 213136,
"author_profile": "https://Stackoverflow.com/users/213136",
"pm_score": 0,
"selected": false,
"text": "DECLARE\n excpUser_1 EXCEPTION;\n EXCEPTION_INIT(excpUser_1, -20001);\nBEGIN\n UPDATE RECIPIENT SET DATE_OF_BIRTH = SYSDATE - 3650; -- ten years, more or less\nEXCEPTION\n WHEN excpUser_1 THEN\n DBMS_OUTPUT.PUT_LINE('Caught excpUser_1');\nEND;\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74620671",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3138756/"
] |
74,620,682
|
<pre class="lang-html prettyprint-override"><code>
<div class="inputs">
<input type="text" id="title" placeholder="tilte">
<div class="price">
<input type="number" id="price" placeholder="price">
<input type="number" id="taxes" placeholder="taxes">
<input type="number" id="ads" placeholder="ads">
<input type="number" id="discount" placeholder="discount">
</div>
</code></pre>
<p>i want to iterate over every element inside parent "inputs" of HTML into JS.
is there is a way to do this without error:</p>
<pre class="lang-js prettyprint-override"><code>
let elements = ["title","price","taxes","ads","discount","total","count","category","submit"]
for ( i = 0 ; i < elements.length ; i++ ){
let elements[i] = document.querySelectorAll(elements["i"])
}
</code></pre>
|
[
{
"answer_id": 74620832,
"author": "MT0",
"author_id": 1509264,
"author_profile": "https://Stackoverflow.com/users/1509264",
"pm_score": 1,
"selected": false,
"text": "2022-01-01 2010-12-31 MONTHS_BETWEEN create or replace TRIGGER AGEVALIDATION \n BEFORE INSERT OR UPDATE ON RECIPIENT \n FOR EACH ROW\nBEGIN\n IF MONTHS_BETWEEN(SYSDATE, :NEW.DATE_OF_BIRTH) < 12*12 THEN\n raise_application_error(-20001,'VACCINE ELIGIBILITY AGE IS 12 AND ABOVE');\n END IF;\nEND;\n/\n INSERT"
},
{
"answer_id": 74621300,
"author": "Bob Jarvis - Слава Україні",
"author_id": 213136,
"author_profile": "https://Stackoverflow.com/users/213136",
"pm_score": 0,
"selected": false,
"text": "DECLARE\n excpUser_1 EXCEPTION;\n EXCEPTION_INIT(excpUser_1, -20001);\nBEGIN\n UPDATE RECIPIENT SET DATE_OF_BIRTH = SYSDATE - 3650; -- ten years, more or less\nEXCEPTION\n WHEN excpUser_1 THEN\n DBMS_OUTPUT.PUT_LINE('Caught excpUser_1');\nEND;\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74620682",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20638607/"
] |
74,620,728
|
<p>I have a table that looks like the following:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Type</th>
<th>Number</th>
</tr>
</thead>
<tbody>
<tr>
<td>A</td>
<td>1</td>
</tr>
<tr>
<td>B</td>
<td>2</td>
</tr>
<tr>
<td>E</td>
<td>3</td>
</tr>
<tr>
<td>C</td>
<td>4</td>
</tr>
<tr>
<td>D</td>
<td>5</td>
</tr>
<tr>
<td>C</td>
<td>6</td>
</tr>
<tr>
<td>G</td>
<td>7</td>
</tr>
</tbody>
</table>
</div>
<p>I would like to make a table where I group Types (A-C) and add these same observations to the bottom of the table. So the new table would look like:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Type</th>
<th>Number</th>
</tr>
</thead>
<tbody>
<tr>
<td>A</td>
<td>1</td>
</tr>
<tr>
<td>B</td>
<td>2</td>
</tr>
<tr>
<td>E</td>
<td>3</td>
</tr>
<tr>
<td>C</td>
<td>4</td>
</tr>
<tr>
<td>D</td>
<td>5</td>
</tr>
<tr>
<td>C</td>
<td>6</td>
</tr>
<tr>
<td>G</td>
<td>7</td>
</tr>
<tr>
<td>A-C</td>
<td>1</td>
</tr>
<tr>
<td>A-C</td>
<td>2</td>
</tr>
<tr>
<td>E</td>
<td>3</td>
</tr>
<tr>
<td>A-C</td>
<td>4</td>
</tr>
<tr>
<td>D</td>
<td>5</td>
</tr>
<tr>
<td>A-C</td>
<td>6</td>
</tr>
<tr>
<td>G</td>
<td>7</td>
</tr>
</tbody>
</table>
</div>
<p>Is this possible? Any help would be much appreciated!</p>
|
[
{
"answer_id": 74620832,
"author": "MT0",
"author_id": 1509264,
"author_profile": "https://Stackoverflow.com/users/1509264",
"pm_score": 1,
"selected": false,
"text": "2022-01-01 2010-12-31 MONTHS_BETWEEN create or replace TRIGGER AGEVALIDATION \n BEFORE INSERT OR UPDATE ON RECIPIENT \n FOR EACH ROW\nBEGIN\n IF MONTHS_BETWEEN(SYSDATE, :NEW.DATE_OF_BIRTH) < 12*12 THEN\n raise_application_error(-20001,'VACCINE ELIGIBILITY AGE IS 12 AND ABOVE');\n END IF;\nEND;\n/\n INSERT"
},
{
"answer_id": 74621300,
"author": "Bob Jarvis - Слава Україні",
"author_id": 213136,
"author_profile": "https://Stackoverflow.com/users/213136",
"pm_score": 0,
"selected": false,
"text": "DECLARE\n excpUser_1 EXCEPTION;\n EXCEPTION_INIT(excpUser_1, -20001);\nBEGIN\n UPDATE RECIPIENT SET DATE_OF_BIRTH = SYSDATE - 3650; -- ten years, more or less\nEXCEPTION\n WHEN excpUser_1 THEN\n DBMS_OUTPUT.PUT_LINE('Caught excpUser_1');\nEND;\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74620728",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20636182/"
] |
74,620,762
|
<p>I want to remove icons from my website using CSS</p>
<p><a href="https://i.stack.imgur.com/O2eb4.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/O2eb4.png" alt="enter image description here" /></a></p>
<p>You can see it here <a href="https://www.stormyark.de/hksv" rel="nofollow noreferrer">https://www.stormyark.de/hksv</a></p>
<p>I uploaded the website files at <a href="https://github.com/stormyark/stormyark.de" rel="nofollow noreferrer">github</a></p>
<p>I already tried to set the "width=0" of the icons but nothing happened.</p>
|
[
{
"answer_id": 74620785,
"author": "Charles Yang",
"author_id": 13101880,
"author_profile": "https://Stackoverflow.com/users/13101880",
"pm_score": 1,
"selected": false,
"text": "display: none;"
},
{
"answer_id": 74620831,
"author": "Dark ShadoW",
"author_id": 20637210,
"author_profile": "https://Stackoverflow.com/users/20637210",
"pm_score": 0,
"selected": false,
"text": "display: none;\n opacity: 0;\n visibility:hidden;\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74620762",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17790109/"
] |
74,620,768
|
<p>I have tried to combine the two files into 1 common <code>manifestAB.txt</code> file. This is a snippet of my <code>assembly.xml</code> file.</p>
<pre><code><files>
<file>
<source>src/resources/manifestA</source>
<outputDirectory>./</outputDirectory>
<destName>manifestAB.txt</destName>
<filtered>true</filtered>
</file>
<file>
<source>src/resources/otherDir/manifestB</source>
<outputDirectory>./</outputDirectory>
<destName>manifestAB.txt</destName>
<filtered>true</filtered>
</file>
</files>
</code></pre>
<p>Right now, it is only copying the contents of <code>manifestA</code>.</p>
|
[
{
"answer_id": 74620785,
"author": "Charles Yang",
"author_id": 13101880,
"author_profile": "https://Stackoverflow.com/users/13101880",
"pm_score": 1,
"selected": false,
"text": "display: none;"
},
{
"answer_id": 74620831,
"author": "Dark ShadoW",
"author_id": 20637210,
"author_profile": "https://Stackoverflow.com/users/20637210",
"pm_score": 0,
"selected": false,
"text": "display: none;\n opacity: 0;\n visibility:hidden;\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74620768",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1265077/"
] |
74,620,774
|
<p>I want to allocate memory for a two-dimensional array (matrix) and write the sums of the diagonals in a separate one-dimensional array. So my code has an array of pointers to pointers,</p>
<pre><code>int N, ** matrix = NULL;
matrix = (int**) malloc(sizeof(int*) * N);
</code></pre>
<p>I fill it and then I create an array to store the sums of the diagonals,</p>
<pre><code>int diag = 2 * N - 1;
int *diagonals = NULL;
diagonals = (int*)malloc(sizeof(int) * diag);
</code></pre>
<p>but when I want to write a value into an array, something goes wrong, the values just don't get written into the array; I don't know why.</p>
<p><a href="https://i.stack.imgur.com/yhe4P.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/yhe4P.png" alt="enter image description here" /></a></p>
<p>Here is my code:</p>
<pre><code>#include <stdio.h>
#include <time.h>
#include <stdlib.h>
int main() {
srand(time(NULL));
int N, ** matrix = NULL;
printf("Input the number of rows\n");
scanf_s("%d", &N);
printf("\n");
// Memory allocation for the array of pointers to pointers
matrix = (int**) malloc(sizeof(int*) * N);
if (matrix != NULL)
{
for (int i = 0; i < N; i++)
*(matrix + i) = (int*)malloc(sizeof(int) * N);
for (int i = 0; i < N; i++)
{
for (int j = 0; j < N; j++)
{
matrix[i][j] = rand() % 14 - 4;
printf("%d\t", matrix[i][j]);
}
printf("\n");
}
printf("\n");
int diag = 2 * N - 1;
int *diagonals = NULL;
diagonals = (int*)malloc(sizeof(int) * diag);
for (int i = 0; i < N; i++)
{
for (int j = 0; j < N; j++)
{
diagonals[i+j] += matrix[i][j];;
}
}
for (int i = 0; i < diag; i++) {
printf("diagonals[%d] - %d\n",i, *(diagonals+i));
}
}
else
printf("Not enough memory.. oops..\n");
}
</code></pre>
|
[
{
"answer_id": 74620866,
"author": "tstanisl",
"author_id": 4989451,
"author_profile": "https://Stackoverflow.com/users/4989451",
"pm_score": 3,
"selected": true,
"text": "diagonals malloc() calloc() diagonals = calloc(diag, sizeof *diagonals);\n"
},
{
"answer_id": 74620868,
"author": "paddy",
"author_id": 1553090,
"author_profile": "https://Stackoverflow.com/users/1553090",
"pm_score": 2,
"selected": false,
"text": "diagonals diagonals = malloc(sizeof(int) * diag);\nfor (int i = 0; i < N; i++)\n{\n for (int j = 0; j < N; j++)\n {\n diagonals[i+j] += matrix[i][j];;\n }\n}\n memset diagonals = malloc(sizeof(int) * diag);\n memset(diagonals, 0, sizeof(int) * diag);\n diagonals = malloc(sizeof(int) * diag);\n for (int i = 0; i < diag; i++) diagonals[i] = 0;\n calloc diagonals = calloc(diag, sizeof(int));\n"
},
{
"answer_id": 74621156,
"author": "0___________",
"author_id": 6110094,
"author_profile": "https://Stackoverflow.com/users/6110094",
"pm_score": 0,
"selected": false,
"text": " int (*matrix)[N] = malloc(N * sizeof(*matrix)); \n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74620774",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20276903/"
] |
74,620,828
|
<p>I have the following dataframe <strong><code>df</code></strong>:</p>
<pre><code> topic num
0 a01 1
1 a01 1
2 a01 2
3 a02 1
4 a02 3
5 a02 2
6 a02 3
7 a03 2
8 a03 1
</code></pre>
<p>And I need to create a new dataframe <strong><code>newdf</code></strong>, where each row corresponds to the topic and the maximum number for each topic, like the following:</p>
<pre><code> topic num
0 a01 2
1 a02 3
2 a03 2
</code></pre>
<p>I've tried to use the max() function from pandas, but to no avail. What I don't seem to get is how I'm gonna iterate through each row and find the highest value correspondent to the topic. How do I separate a01 from a02, so that I can get the maximum value for each? I've also tried transposing, but the same doubt keeps appearing.</p>
|
[
{
"answer_id": 74620866,
"author": "tstanisl",
"author_id": 4989451,
"author_profile": "https://Stackoverflow.com/users/4989451",
"pm_score": 3,
"selected": true,
"text": "diagonals malloc() calloc() diagonals = calloc(diag, sizeof *diagonals);\n"
},
{
"answer_id": 74620868,
"author": "paddy",
"author_id": 1553090,
"author_profile": "https://Stackoverflow.com/users/1553090",
"pm_score": 2,
"selected": false,
"text": "diagonals diagonals = malloc(sizeof(int) * diag);\nfor (int i = 0; i < N; i++)\n{\n for (int j = 0; j < N; j++)\n {\n diagonals[i+j] += matrix[i][j];;\n }\n}\n memset diagonals = malloc(sizeof(int) * diag);\n memset(diagonals, 0, sizeof(int) * diag);\n diagonals = malloc(sizeof(int) * diag);\n for (int i = 0; i < diag; i++) diagonals[i] = 0;\n calloc diagonals = calloc(diag, sizeof(int));\n"
},
{
"answer_id": 74621156,
"author": "0___________",
"author_id": 6110094,
"author_profile": "https://Stackoverflow.com/users/6110094",
"pm_score": 0,
"selected": false,
"text": " int (*matrix)[N] = malloc(N * sizeof(*matrix)); \n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74620828",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20638561/"
] |
74,620,829
|
<p>i have problem with translated query, ToList(), AsEnumerable etc.</p>
<p>I need construct or create query which is shared.</p>
<p>Branches -> Customer -> some collection -> some collection
Customer -> some collection -> some collection.</p>
<p>Do you help me how is the best thingh how to do it and share the query.</p>
<p>i access to repository via graphql use projection etc.</p>
<pre class="lang-cs prettyprint-override"><code>public IQueryable<CustomerTableGraphQL> BranchTableReportTest(DateTime actualTime, long userId)
{
var r =
(
from b in _dbContext.Branches
let t = Customers(b.Id).ToList()
select new CustomerTableGraphQL
{
Id = b.Id,
Name = b.Name,
Children =
(
from c in t
select new CustomerTableGraphQL
{
Id = c.Id,
Name = c.Name
}
)
.AsEnumerable()
}
);
return r;
}
public IQueryable<Customer> Customers(long branchId) =>
_dbContext.Customers.Where(x => x.BranchId.Value == branchId).ToList().AsQueryable();
</code></pre>
<p>Some example how to doit and share iquearable between query</p>
|
[
{
"answer_id": 74620866,
"author": "tstanisl",
"author_id": 4989451,
"author_profile": "https://Stackoverflow.com/users/4989451",
"pm_score": 3,
"selected": true,
"text": "diagonals malloc() calloc() diagonals = calloc(diag, sizeof *diagonals);\n"
},
{
"answer_id": 74620868,
"author": "paddy",
"author_id": 1553090,
"author_profile": "https://Stackoverflow.com/users/1553090",
"pm_score": 2,
"selected": false,
"text": "diagonals diagonals = malloc(sizeof(int) * diag);\nfor (int i = 0; i < N; i++)\n{\n for (int j = 0; j < N; j++)\n {\n diagonals[i+j] += matrix[i][j];;\n }\n}\n memset diagonals = malloc(sizeof(int) * diag);\n memset(diagonals, 0, sizeof(int) * diag);\n diagonals = malloc(sizeof(int) * diag);\n for (int i = 0; i < diag; i++) diagonals[i] = 0;\n calloc diagonals = calloc(diag, sizeof(int));\n"
},
{
"answer_id": 74621156,
"author": "0___________",
"author_id": 6110094,
"author_profile": "https://Stackoverflow.com/users/6110094",
"pm_score": 0,
"selected": false,
"text": " int (*matrix)[N] = malloc(N * sizeof(*matrix)); \n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74620829",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11352680/"
] |
74,620,846
|
<p>I have two solutions in Visual Studio. Solution A is my website and Solution B is just a reference in Solution A. However a function from Solution B is throwing an error when I call it in Solution A. However since it is complied code I can't actually step through the function.</p>
<p>My question, since I have access to Solution B in Visual Studio, how do I connect the two solutions so I can step through and see what is happening?</p>
|
[
{
"answer_id": 74620866,
"author": "tstanisl",
"author_id": 4989451,
"author_profile": "https://Stackoverflow.com/users/4989451",
"pm_score": 3,
"selected": true,
"text": "diagonals malloc() calloc() diagonals = calloc(diag, sizeof *diagonals);\n"
},
{
"answer_id": 74620868,
"author": "paddy",
"author_id": 1553090,
"author_profile": "https://Stackoverflow.com/users/1553090",
"pm_score": 2,
"selected": false,
"text": "diagonals diagonals = malloc(sizeof(int) * diag);\nfor (int i = 0; i < N; i++)\n{\n for (int j = 0; j < N; j++)\n {\n diagonals[i+j] += matrix[i][j];;\n }\n}\n memset diagonals = malloc(sizeof(int) * diag);\n memset(diagonals, 0, sizeof(int) * diag);\n diagonals = malloc(sizeof(int) * diag);\n for (int i = 0; i < diag; i++) diagonals[i] = 0;\n calloc diagonals = calloc(diag, sizeof(int));\n"
},
{
"answer_id": 74621156,
"author": "0___________",
"author_id": 6110094,
"author_profile": "https://Stackoverflow.com/users/6110094",
"pm_score": 0,
"selected": false,
"text": " int (*matrix)[N] = malloc(N * sizeof(*matrix)); \n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74620846",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18224693/"
] |
74,620,852
|
<p>I am writing a function that works as follows it receives list of numbers e.g [0.5,-0.5,1]
then it returns a list with this in each index[(-0.5-0.5) + (1-0.5)]. In other words, it adds the difference between the current value and the other values. So the output should be [-0.5,2.5,-2]</p>
<pre><code>def Calculate(initial_values,b):
x = np.array([initial_values]).T
results=[0]
for i in range(len(initial_values)):
results.append( (initial_values[:i] - initial_values[i])+(initial_values[i+1:]-initial_values[i])
</code></pre>
<p>Error</p>
<pre><code>TypeError: unsupported operand type(s) for -: 'list' and 'float'
</code></pre>
|
[
{
"answer_id": 74621038,
"author": "joanis",
"author_id": 3216427,
"author_profile": "https://Stackoverflow.com/users/3216427",
"pm_score": 0,
"selected": false,
"text": "Calculate() initial_opinion Calculate(np.array([0.5, -0.5, 1]), 5)\n"
},
{
"answer_id": 74621085,
"author": "Sterling ",
"author_id": 4880945,
"author_profile": "https://Stackoverflow.com/users/4880945",
"pm_score": 2,
"selected": true,
"text": "def Calculate(arr):\n res = []\n for i, val in enumerate(arr):\n total = -val * (len(arr) - 1) + sum(arr[0:i]) + sum(arr[i+1:])\n res.append(total)\n return res\n"
},
{
"answer_id": 74621303,
"author": "Chrysophylaxs",
"author_id": 9499196,
"author_profile": "https://Stackoverflow.com/users/9499196",
"pm_score": 0,
"selected": false,
"text": "np.subtract.outer np.ndarray.sum import numpy as np\n\ndef Calculate(arr):\n return np.subtract.outer(arr, arr).sum(axis=0)\n\ninitial_values = [0.5, -0.5, 1]\nout = Calculate(initial_values)\n# out = array([-0.5, 2.5, -2. ])\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74620852",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20232879/"
] |
74,620,854
|
<p>I have an array called "data" which contains the following information.</p>
<pre><code>[['amazon',
'phone',
'serious',
'mind',
'blown',
'serious',
'enjoy',
'use',
'applic',
'full',
'blown',
'websit',
'allow',
'quick',
'track',
'packag',
'descript',
'say'],
['would',
'say',
'app',
'real',
'thing',
'show',
'ghost',
'said',
'quot',
'orang',
'quot',
'ware',
'orang',
'cloth',
'app',
'adiquit',
'would',
'recsmend',
'want',
'talk',
'ghost'],
['love',
'play',
'backgammonthi',
'game',
'offer',
'varieti',
'difficulti',
'make',
'perfect',
'beginn',
'season',
'player'],
</code></pre>
<p><em><strong>The case is that I would like to save in a list, the values that appear at least 1% in this array.</strong></em></p>
<p>The closest approximation I have found is the following but it does not return what I need. Any ideas?</p>
<pre><code>import numpy_indexed as npi
idx = [np.ones(len(a))*i for i, a in enumerate(tokens_list_train)]
(rows, cols), table = npi.count_table(np.concatenate(idx), np.concatenate(tokens_list_train))
table = table / table.sum(axis=1, keepdims=True)
print(table * 100)`
</code></pre>
|
[
{
"answer_id": 74621038,
"author": "joanis",
"author_id": 3216427,
"author_profile": "https://Stackoverflow.com/users/3216427",
"pm_score": 0,
"selected": false,
"text": "Calculate() initial_opinion Calculate(np.array([0.5, -0.5, 1]), 5)\n"
},
{
"answer_id": 74621085,
"author": "Sterling ",
"author_id": 4880945,
"author_profile": "https://Stackoverflow.com/users/4880945",
"pm_score": 2,
"selected": true,
"text": "def Calculate(arr):\n res = []\n for i, val in enumerate(arr):\n total = -val * (len(arr) - 1) + sum(arr[0:i]) + sum(arr[i+1:])\n res.append(total)\n return res\n"
},
{
"answer_id": 74621303,
"author": "Chrysophylaxs",
"author_id": 9499196,
"author_profile": "https://Stackoverflow.com/users/9499196",
"pm_score": 0,
"selected": false,
"text": "np.subtract.outer np.ndarray.sum import numpy as np\n\ndef Calculate(arr):\n return np.subtract.outer(arr, arr).sum(axis=0)\n\ninitial_values = [0.5, -0.5, 1]\nout = Calculate(initial_values)\n# out = array([-0.5, 2.5, -2. ])\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74620854",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20503504/"
] |
74,620,855
|
<p>So I am trying to make a custom component that inserts a icon.svg from a specific directory in my assets. The component loads in fine and custom attributes work too, however when they try to look for the image I get a 404 error.</p>
<p><img src="https://i.stack.imgur.com/J4SOG.png" alt="enter image description here" /><br>
<img src="https://i.stack.imgur.com/ekWRo.png" alt="enter image description here" />
<img src="https://i.stack.imgur.com/rZDTt.png" alt="enter image description here" /></p>
<pre class="lang-html prettyprint-override"><code> <template>
<img :src="'../src/assets/heroicons/'+this.styling+'/'+this.icon+'.svg'" alt=""> <!-- this one does not work -->
<img src="../src/assets/heroicons/solid/database.svg" alt=""> <!-- this one works -->
</template>
<script>
export default {
name: "IconComp",
props: [
'styling',
'icon'
],
created() {
console.log(this.styling+' '+this.icon)
}
}
</script>
<style scoped>
img {
filter: invert(100%);
}
</style>
</code></pre>
<p>As you can see in the images, the attributes end up at the right place but it can't find the files.</p>
|
[
{
"answer_id": 74621038,
"author": "joanis",
"author_id": 3216427,
"author_profile": "https://Stackoverflow.com/users/3216427",
"pm_score": 0,
"selected": false,
"text": "Calculate() initial_opinion Calculate(np.array([0.5, -0.5, 1]), 5)\n"
},
{
"answer_id": 74621085,
"author": "Sterling ",
"author_id": 4880945,
"author_profile": "https://Stackoverflow.com/users/4880945",
"pm_score": 2,
"selected": true,
"text": "def Calculate(arr):\n res = []\n for i, val in enumerate(arr):\n total = -val * (len(arr) - 1) + sum(arr[0:i]) + sum(arr[i+1:])\n res.append(total)\n return res\n"
},
{
"answer_id": 74621303,
"author": "Chrysophylaxs",
"author_id": 9499196,
"author_profile": "https://Stackoverflow.com/users/9499196",
"pm_score": 0,
"selected": false,
"text": "np.subtract.outer np.ndarray.sum import numpy as np\n\ndef Calculate(arr):\n return np.subtract.outer(arr, arr).sum(axis=0)\n\ninitial_values = [0.5, -0.5, 1]\nout = Calculate(initial_values)\n# out = array([-0.5, 2.5, -2. ])\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74620855",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20638676/"
] |
74,620,898
|
<p>How to Write a program that receive a number from the input at each step and continue to work until zero is entered. After the zero digit is entered, this program should print the sum of the entered numbers. I want to get n different numbers in n different lines and it stops when it reaches Zero</p>
<p><strong>For ex:(input:)</strong></p>
<blockquote>
<p>3</p>
<p>4</p>
<p>5</p>
<p>0</p>
</blockquote>
<p><strong>Output:</strong></p>
<blockquote>
<p>12</p>
</blockquote>
<p>Actually I have this code but it doesn’t work:
‘’’python’’’</p>
<pre><code>Sum= 0
Num = int(input())
While num!=0 :
Num = int(input())
Sum+= num
Print(sum)
</code></pre>
<p><strong>But it gives ‘9’ instead of ‘12’</strong></p>
|
[
{
"answer_id": 74621038,
"author": "joanis",
"author_id": 3216427,
"author_profile": "https://Stackoverflow.com/users/3216427",
"pm_score": 0,
"selected": false,
"text": "Calculate() initial_opinion Calculate(np.array([0.5, -0.5, 1]), 5)\n"
},
{
"answer_id": 74621085,
"author": "Sterling ",
"author_id": 4880945,
"author_profile": "https://Stackoverflow.com/users/4880945",
"pm_score": 2,
"selected": true,
"text": "def Calculate(arr):\n res = []\n for i, val in enumerate(arr):\n total = -val * (len(arr) - 1) + sum(arr[0:i]) + sum(arr[i+1:])\n res.append(total)\n return res\n"
},
{
"answer_id": 74621303,
"author": "Chrysophylaxs",
"author_id": 9499196,
"author_profile": "https://Stackoverflow.com/users/9499196",
"pm_score": 0,
"selected": false,
"text": "np.subtract.outer np.ndarray.sum import numpy as np\n\ndef Calculate(arr):\n return np.subtract.outer(arr, arr).sum(axis=0)\n\ninitial_values = [0.5, -0.5, 1]\nout = Calculate(initial_values)\n# out = array([-0.5, 2.5, -2. ])\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74620898",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17721501/"
] |
74,620,908
|
<p>I have a React project written in JS that I am converting to TS. Using JS, this works:</p>
<pre><code>import { ReactComponent as IconPerson } from '../../../icons/person.svg';
</code></pre>
<p>Using TS, I get this error:</p>
<blockquote>
<p>Cannot find module '../../../icons/person.svg' or its corresponding type declarations.</p>
</blockquote>
<p>I have added the following to a new <strong>index.d.ts</strong> file:</p>
<pre><code>declare module '*.svg';
</code></pre>
<p>I have also added the index.d.ts file to the <code>include</code> array in my <strong>tsconfig.json</strong>:</p>
<pre><code>{
include: ["src", "**/*.ts", "**/*.tsx", "index.d.ts"]
}
</code></pre>
<p>What am I missing?</p>
|
[
{
"answer_id": 74621038,
"author": "joanis",
"author_id": 3216427,
"author_profile": "https://Stackoverflow.com/users/3216427",
"pm_score": 0,
"selected": false,
"text": "Calculate() initial_opinion Calculate(np.array([0.5, -0.5, 1]), 5)\n"
},
{
"answer_id": 74621085,
"author": "Sterling ",
"author_id": 4880945,
"author_profile": "https://Stackoverflow.com/users/4880945",
"pm_score": 2,
"selected": true,
"text": "def Calculate(arr):\n res = []\n for i, val in enumerate(arr):\n total = -val * (len(arr) - 1) + sum(arr[0:i]) + sum(arr[i+1:])\n res.append(total)\n return res\n"
},
{
"answer_id": 74621303,
"author": "Chrysophylaxs",
"author_id": 9499196,
"author_profile": "https://Stackoverflow.com/users/9499196",
"pm_score": 0,
"selected": false,
"text": "np.subtract.outer np.ndarray.sum import numpy as np\n\ndef Calculate(arr):\n return np.subtract.outer(arr, arr).sum(axis=0)\n\ninitial_values = [0.5, -0.5, 1]\nout = Calculate(initial_values)\n# out = array([-0.5, 2.5, -2. ])\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74620908",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2262604/"
] |
74,620,909
|
<p>If I use Row() instead of Center(), it will not be displayed,just blank.</p>
<p>I expect a music player like layout.
Make 2 Row, the 1st Row contain "LeftMenu" and "Expanded Container" for content .</p>
|
[
{
"answer_id": 74621038,
"author": "joanis",
"author_id": 3216427,
"author_profile": "https://Stackoverflow.com/users/3216427",
"pm_score": 0,
"selected": false,
"text": "Calculate() initial_opinion Calculate(np.array([0.5, -0.5, 1]), 5)\n"
},
{
"answer_id": 74621085,
"author": "Sterling ",
"author_id": 4880945,
"author_profile": "https://Stackoverflow.com/users/4880945",
"pm_score": 2,
"selected": true,
"text": "def Calculate(arr):\n res = []\n for i, val in enumerate(arr):\n total = -val * (len(arr) - 1) + sum(arr[0:i]) + sum(arr[i+1:])\n res.append(total)\n return res\n"
},
{
"answer_id": 74621303,
"author": "Chrysophylaxs",
"author_id": 9499196,
"author_profile": "https://Stackoverflow.com/users/9499196",
"pm_score": 0,
"selected": false,
"text": "np.subtract.outer np.ndarray.sum import numpy as np\n\ndef Calculate(arr):\n return np.subtract.outer(arr, arr).sum(axis=0)\n\ninitial_values = [0.5, -0.5, 1]\nout = Calculate(initial_values)\n# out = array([-0.5, 2.5, -2. ])\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74620909",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19583956/"
] |
74,620,911
|
<p>The scenario is to mimic rolling 3 six-sided die in Prolog while trying to obey the recursive nature of prolog. This is easily done with the <a href="https://www.youtube.com/watch?v=sHo6-hk21L8" rel="nofollow noreferrer">Fibonacci series</a></p>
<pre><code>n_factorial(N, F) :-
N #> 0,
F #= N*F1,
N1 #= N-1,
n_factorial(N1, F1).
</code></pre>
<p>I'm having difficulty translating this to the dice paradigm, where we add a random number to the sum.</p>
<pre><code># N = number of dice, S = number of sides, R = result
roll_dice(N, S, R) :-
N1 #> 0,
R = random_between(1, S, R1),
N1 #= N-1,
roll_dice(N1, S, R1).
</code></pre>
<p>throws an error but neglects the sum anyway. I would normally use <code>+=</code> in other languages.</p>
|
[
{
"answer_id": 74621038,
"author": "joanis",
"author_id": 3216427,
"author_profile": "https://Stackoverflow.com/users/3216427",
"pm_score": 0,
"selected": false,
"text": "Calculate() initial_opinion Calculate(np.array([0.5, -0.5, 1]), 5)\n"
},
{
"answer_id": 74621085,
"author": "Sterling ",
"author_id": 4880945,
"author_profile": "https://Stackoverflow.com/users/4880945",
"pm_score": 2,
"selected": true,
"text": "def Calculate(arr):\n res = []\n for i, val in enumerate(arr):\n total = -val * (len(arr) - 1) + sum(arr[0:i]) + sum(arr[i+1:])\n res.append(total)\n return res\n"
},
{
"answer_id": 74621303,
"author": "Chrysophylaxs",
"author_id": 9499196,
"author_profile": "https://Stackoverflow.com/users/9499196",
"pm_score": 0,
"selected": false,
"text": "np.subtract.outer np.ndarray.sum import numpy as np\n\ndef Calculate(arr):\n return np.subtract.outer(arr, arr).sum(axis=0)\n\ninitial_values = [0.5, -0.5, 1]\nout = Calculate(initial_values)\n# out = array([-0.5, 2.5, -2. ])\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74620911",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2035811/"
] |
74,620,931
|
<p>I have a spreadsheet that my company uses to submit and track orders. There is a submit button on the order form and it uses the code below to execute. The problem is that it does not work on mobile. Instead of launching the code it just selects the image. I have read I may be able to do a work around with a checkbox but I'm having trouble figuring that out. Please advise. I just want to be able to submit and clear the form on mobile as well. I cannot do onedit() because the form submits to one line and if it submitted each entry at a time it would mess things up.</p>
<pre><code>function Submit() {
var ss =SpreadsheetApp.getActiveSpreadsheet();
var formS =ss.getSheetByName('Order Form'); //data entry sheet
var dataS = ss.getSheetByName('Events Summary'); //data sheet
var values = [[formS.getRange("B3").getValue(),
formS.getRange("B5").getValue(),
formS.getRange("B6").getValue(),
formS.getRange("B7").getValue(),
formS.getRange("B8").getValue(),
formS.getRange("B10").getValue(),
formS.getRange("B11").getValue(),
formS.getRange("B12").getValue(),
formS.getRange("B13").getValue(),
formS.getRange("B14").getValue(),
formS.getRange("B16").getValue(),
formS.getRange("D3").getValue(),
formS.getRange("D4").getValue(),
formS.getRange("D5").getValue(),
formS.getRange("D6").getValue(),
formS.getRange("E6").getValue(),
formS.getRange("D7").getValue(),
formS.getRange("E7").getValue(),
formS.getRange("D8").getValue(),
formS.getRange("E8").getValue(),
formS.getRange("D9").getValue(),
formS.getRange("E9").getValue(),
formS.getRange("D10").getValue(),
formS.getRange("E10").getValue(),
formS.getRange("D11").getValue(),
formS.getRange("E11").getValue(),
formS.getRange("D12").getValue(),
formS.getRange("E12").getValue(),
formS.getRange("D13").getValue(),
formS.getRange("B19").getValue(),
formS.getRange("B20").getValue(),
formS.getRange("B21").getValue(),
formS.getRange("B22").getValue(),
formS.getRange("B23").getValue(),
formS.getRange("B24").getValue(),
formS.getRange("B25").getValue(),
formS.getRange("B26").getValue(),
formS.getRange("B27").getValue(),
formS.getRange("B28").getValue(),
formS.getRange("B29").getValue(),
formS.getRange("B30").getValue(),
formS.getRange("D18").getValue(),
formS.getRange("D19").getValue(),
formS.getRange("D20").getValue(),
formS.getRange("D21").getValue(),
formS.getRange("D22").getValue(),
formS.getRange("D23").getValue(),
formS.getRange("D24").getValue(),
formS.getRange("D25").getValue(),
formS.getRange("D26").getValue(),
formS.getRange("D27").getValue(),
formS.getRange("D28").getValue(),
formS.getRange("D29").getValue(),
formS.getRange("D30").getValue(),
formS.getRange("D31").getValue(),
formS.getRange("F9").getValue(),
formS.getRange("F11").getValue(),
formS.getRange("F13").getValue(),
formS.getRange("F15").getValue(),
formS.getRange("F17").getValue(),
formS.getRange("F7").getValue(),
formS.getRange("F19").getValue(),
formS.getRange("F21").getValue(),
formS.getRange("F23").getValue(),
formS.getRange("F25").getValue(),
formS.getRange("F27").getValue(),
formS.getRange("F29").getValue(),
formS.getRange("F31").getValue(),
formS.getRange("B50").getValue(),
formS.getRange("C50").getValue(),
formS.getRange("E50").getValue(),
formS.getRange("F2").getValue(),
formS.getRange("F3").getValue(),
formS.getRange("F4").getValue()]];
dataS.getRange(dataS.getLastRow()+1,1,1,74).setValues(values);
ClearCell();
}
</code></pre>
|
[
{
"answer_id": 74621038,
"author": "joanis",
"author_id": 3216427,
"author_profile": "https://Stackoverflow.com/users/3216427",
"pm_score": 0,
"selected": false,
"text": "Calculate() initial_opinion Calculate(np.array([0.5, -0.5, 1]), 5)\n"
},
{
"answer_id": 74621085,
"author": "Sterling ",
"author_id": 4880945,
"author_profile": "https://Stackoverflow.com/users/4880945",
"pm_score": 2,
"selected": true,
"text": "def Calculate(arr):\n res = []\n for i, val in enumerate(arr):\n total = -val * (len(arr) - 1) + sum(arr[0:i]) + sum(arr[i+1:])\n res.append(total)\n return res\n"
},
{
"answer_id": 74621303,
"author": "Chrysophylaxs",
"author_id": 9499196,
"author_profile": "https://Stackoverflow.com/users/9499196",
"pm_score": 0,
"selected": false,
"text": "np.subtract.outer np.ndarray.sum import numpy as np\n\ndef Calculate(arr):\n return np.subtract.outer(arr, arr).sum(axis=0)\n\ninitial_values = [0.5, -0.5, 1]\nout = Calculate(initial_values)\n# out = array([-0.5, 2.5, -2. ])\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74620931",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19047952/"
] |
74,620,938
|
<p>I'm developing an Android app with Kotlin.</p>
<p>For example I have an access token which I get on my LoginActivity and I need this access token on each activity to call API. I know that I could use putExtra() and getExtra(), but it doesn't make sense to write this code for each new activity.</p>
<p>Is there a way to create a global variable or something like static class which will be accessible for all activities in app?</p>
<p>What is the right Android approach for that?</p>
|
[
{
"answer_id": 74621038,
"author": "joanis",
"author_id": 3216427,
"author_profile": "https://Stackoverflow.com/users/3216427",
"pm_score": 0,
"selected": false,
"text": "Calculate() initial_opinion Calculate(np.array([0.5, -0.5, 1]), 5)\n"
},
{
"answer_id": 74621085,
"author": "Sterling ",
"author_id": 4880945,
"author_profile": "https://Stackoverflow.com/users/4880945",
"pm_score": 2,
"selected": true,
"text": "def Calculate(arr):\n res = []\n for i, val in enumerate(arr):\n total = -val * (len(arr) - 1) + sum(arr[0:i]) + sum(arr[i+1:])\n res.append(total)\n return res\n"
},
{
"answer_id": 74621303,
"author": "Chrysophylaxs",
"author_id": 9499196,
"author_profile": "https://Stackoverflow.com/users/9499196",
"pm_score": 0,
"selected": false,
"text": "np.subtract.outer np.ndarray.sum import numpy as np\n\ndef Calculate(arr):\n return np.subtract.outer(arr, arr).sum(axis=0)\n\ninitial_values = [0.5, -0.5, 1]\nout = Calculate(initial_values)\n# out = array([-0.5, 2.5, -2. ])\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74620938",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3484533/"
] |
74,620,973
|
<p>I have a <code>.txt</code> file that I am attempting to read in pandas. When I open the <code>.txt</code> file, I see it has the content and data I expect. However, when I read the file in pandas, the data is missing and I only <code>NaNs</code>.</p>
<p>here's sample content from <code>.txt</code> file:</p>
<pre><code>980145115 189699454 SD Vacant Land Agricultural/Horticultural/Forest Vacant Land 3290522 216200 43.585481 -96.626588 10255 46099 I
707951172 189699522 AZ Government, Special Purpose Religious 91630 26730 102-55-008 4013 I
</code></pre>
<p><a href="https://i.stack.imgur.com/W1fgY.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/W1fgY.png" alt="data-img" /></a></p>
<p>I have tried different parameters of encoding and sep in <code>read_csv</code>.</p>
<pre><code>import pandas as pd
df = pd.read_csv('s3://filepath', encoding='latin-1', sep="\t")
</code></pre>
<p><a href="https://i.stack.imgur.com/Tlgfnm.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Tlgfnm.png" alt="nans" /></a></p>
<p>Is there anything else I can try to read the data?</p>
|
[
{
"answer_id": 74621038,
"author": "joanis",
"author_id": 3216427,
"author_profile": "https://Stackoverflow.com/users/3216427",
"pm_score": 0,
"selected": false,
"text": "Calculate() initial_opinion Calculate(np.array([0.5, -0.5, 1]), 5)\n"
},
{
"answer_id": 74621085,
"author": "Sterling ",
"author_id": 4880945,
"author_profile": "https://Stackoverflow.com/users/4880945",
"pm_score": 2,
"selected": true,
"text": "def Calculate(arr):\n res = []\n for i, val in enumerate(arr):\n total = -val * (len(arr) - 1) + sum(arr[0:i]) + sum(arr[i+1:])\n res.append(total)\n return res\n"
},
{
"answer_id": 74621303,
"author": "Chrysophylaxs",
"author_id": 9499196,
"author_profile": "https://Stackoverflow.com/users/9499196",
"pm_score": 0,
"selected": false,
"text": "np.subtract.outer np.ndarray.sum import numpy as np\n\ndef Calculate(arr):\n return np.subtract.outer(arr, arr).sum(axis=0)\n\ninitial_values = [0.5, -0.5, 1]\nout = Calculate(initial_values)\n# out = array([-0.5, 2.5, -2. ])\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74620973",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3380902/"
] |
74,621,055
|
<p>I'm trying to get all the possible combinations of a 3d array.
I found a lot of answers for one- or two-dimensional arrays with recursive functions but no solution works for a deeper nested array.</p>
<p>The array structure is always the same (three levels), but the length of each level can change.</p>
<p>example code:</p>
<pre><code>function getCombinations(arr){
...
}
var arr = [[[100, 200]], [[10, 20], [30, 40]]];
var arr2 = [[[100, 200]], [[10, 20], [50]], [[400, 500, 600]]];
res = getCombinations(arr);
res2 = getCombinations(arr2);
</code></pre>
<p>expected outputs:</p>
<pre><code>// arr: [[[100, 200]], [[10, 20], [30, 40]]]
[
[[100], [10, 30]],
[[100], [10, 40]],
[[100], [20, 30]],
[[100], [20, 40]],
[[200], [10, 30]],
[[200], [10, 40]],
[[200], [20, 30]],
[[200], [20, 40]],
];
// arr2: [[[100, 200]], [[10, 20], [50]], [[400, 500, 600]]]
[
[[100], [10, 50], [400]],
[[100], [10, 50], [500]],
[[100], [10, 50], [600]],
[[100], [20, 50], [400]],
[[100], [20, 50], [500]],
[[100], [20, 50], [600]],
[[200], [10, 50], [400]],
[[200], [10, 50], [500]],
[[200], [10, 50], [600]],
[[200], [20, 50], [400]],
[[200], [20, 50], [500]],
[[200], [20, 50], [600]],
];
</code></pre>
|
[
{
"answer_id": 74630804,
"author": "Scott Sauyet",
"author_id": 1243641,
"author_profile": "https://Stackoverflow.com/users/1243641",
"pm_score": 0,
"selected": false,
"text": "cartesian const cartesian = ([xs, ...xss]) =>\n xs == undefined ? [[]] : xs .flatMap (x => cartesian (xss) .map (ys => [x, ...ys]))\n\nconst getCombinations = (xss) => \n cartesian (xss .map (cartesian))\n\n\nconst arr = [[[100, 200]], [[10, 20], [30, 40]]];\nconst arr2 = [[[100, 200]], [[10, 20], [50]], [[400, 500, 600]]];\n\nconsole .log (JSON .stringify (getCombinations (arr), null, 4))\nconsole .log (JSON .stringify (getCombinations (arr2), null, 4)) .as-console-wrapper {max-height: 100% !important; top: 0}"
},
{
"answer_id": 74634554,
"author": "no_mans_code",
"author_id": 20638199,
"author_profile": "https://Stackoverflow.com/users/20638199",
"pm_score": 1,
"selected": false,
"text": "function cartesianProduct(arr) {\n return arr.reduce(function (a, b) {\n return a.map(function (x) {\n return b.map(function (y) {\n return x.concat([y]);\n });\n }).reduce(function (a, b) {\n return a.concat(b);\n }, []);\n }, [[]]);\n}\n let arr = [[[100, 200]], [[10, 20], [30, 40]]];\nlet res = cartesianProduct(arr.map(a => cartesianProduct(a)));\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74621055",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20638199/"
] |
74,621,056
|
<p>I need to know that what is the error in my code because everything is correct but form data could not be submitted and in php file the error popups that undefined index lname while submiting the form that means form is submitting through jquery but data is not going in backend. so please resolve this error or help me find out what the error is in code.</p>
<p>this is the html code:-</p>
<pre><code><span id="answer"></span>
<form id='contact_form' method="post">
<div class="modal-body">
<div id='name_error' class='error'>Please enter your name.</div>
<div>
<input type='text' name='lname' id='name' class="form-control" placeholder="Your Name" required>
</div>
<div id='email_error' class='error'>Please enter your valid E-mail ID.</div>
<div>
<input type='email' name='email' id='email' class="form-control" placeholder="Your Email" required>
</div>
<div id='phone_error' class='error'>Please enter your phone number.</div>
<div>
<input type='text' name='phone' id='phone' class="form-control" placeholder="Your Phone" required>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
<button type="submit" onclick="formSubmit(event);" class="btn btn-primary">I Agree</button>
</div>
</form>
</code></pre>
<p>This is the jquery code:-</p>
<pre><code>$('#subButton').click(function(e) {
console.log('in');
e.preventDefault();
var FormData = $('#contact-form').submit();
$.ajax({
type: "POST",
url: "admin/backend/leads.php",
data: FormData,
dataType: "json",
success: function(data) {
var html = '';
if (data.errors) {
html = '<div class="alert alert-danger">' + data.errors + '</div>';
}
if (data.success) {
html = '<div class="alert alert-success">' + data.success + '</div>';
$('#contact-form')[0].reset();
localStorage.setItem('#phone', true);
}
$('#answer').html(html);
},
error: function(data) {
html = '<div class="alert alert-danger">' + data.errors + '</div>';
$('#answer').html(html);
}
});
});
</code></pre>
|
[
{
"answer_id": 74621208,
"author": "Phil",
"author_id": 283366,
"author_profile": "https://Stackoverflow.com/users/283366",
"pm_score": 1,
"selected": false,
"text": "id=\"subButton\" formSubmit $('#contact-form').submit() jQuery onClick <button type=\"submit\" class=\"btn btn-primary\">I Agree</button>\n id=\"subButton\" <button> $(\"#contact_form\").on(\"submit\", (e) => {\n e.preventDefault();\n const postData = $(e.target).serialize();\n\n $.post(\"admin/backend/leads.php\", postData, null, \"json\")\n .done((data) => {\n // make HTML changes, etc\n })\n .fail((_, textStatus, errorThrown) => {\n // report error, etc\n });\n});\n document\n .getElementById(\"contact_form\")\n .addEventListener(\"submit\", async (e) => {\n e.preventDefault();\n const body = new URLSearchParams(new FormData(e.target));\n try {\n const res = await fetch(\"admin/backend/leads.php\", {\n method: \"POST\",\n body,\n });\n if (!res.ok) {\n throw res;\n }\n const data = await res.json();\n // make HTML changes, etc\n } catch (err) {\n // report error, etc\n }\n });\n"
},
{
"answer_id": 74638428,
"author": "Nagonus Lrak",
"author_id": 20476491,
"author_profile": "https://Stackoverflow.com/users/20476491",
"pm_score": 0,
"selected": false,
"text": "$('#contact-form').submit(function(e) {\n console.log('in');\n e.preventDefault();\n var body = $(this).serialize();\n $.ajax({\n type: \"POST\",\n url: \"admin/backend/leads.php\",\n data: JSON.stringify(body),\n dataType: \"json\",\n success: function(data) {\n var html = '';\n if (data.errors) {\n html = '<div class=\"alert alert-danger\">' + data.errors + '</div>';\n }\n if (data.success) {\n html = '<div class=\"alert alert-success\">' + data.success + '</div>';\n $('#contact-form')[0].reset();\n localStorage.setItem('#phone', true);\n }\n $('#answer').html(html);\n },\n error: function(data) {\n html = '<div class=\"alert alert-danger\">' + data.errors + '</div>';\n $('#answer').html(html);\n }\n });\n });\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74621056",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19117931/"
] |
74,621,070
|
<p>I have a problem in calculating the shortest path through BFS algorithm in Java.</p>
<p>When I tried to define a path from Node 0 to Node 7 , I got this result. <code>(0 -> 2 -> 3 -> 4 -> 5)</code></p>
<p>How can I fix the issue?</p>
<p>Here is my Node Class</p>
<pre><code>public class Node {
private final int value;
private final Set<Node> siblingNodes;
public Node(int value) {
this.value = value;
siblingNodes = new HashSet<Node>();
}
public Set<Node> getSiblingNodes() {
return siblingNodes;
}
public boolean equals(Node compareTo) {
return (compareTo.getValue() == value);
}
public int getValue() {
return value;
}
public void addSiblingNode(Node node) {
siblingNodes.add(node);
}
}
</code></pre>
<p>Here is the code snippets shown below.</p>
<pre><code> public static void main(String[] args) {
/**
*
* 1 -> 5
* 0 -> -> 4
* 2 -> 3 -> 6 -> 7
*
*/
Node node0 = new Node(0);
Node node1 = new Node(1);
Node node2 = new Node(2);
node0.addSiblingNode(node1);
node0.addSiblingNode(node2);
Node node3 = new Node(3);
node2.addSiblingNode(node3);
Node node4 = new Node(4);
node3.addSiblingNode(node4);
Node node5 = new Node(5);
Node node6 = new Node(6);
node4.addSiblingNode(node5);
node4.addSiblingNode(node6);
Node node7 = new Node(7);
node6.addSiblingNode(node7);
List<Node> shortestPath = getDirections(node0, node7);
for(Node node : shortestPath) {
System.out.println(node.getValue());
}
}
public static List<Node> getDirections(Node sourceNode, Node destinationNode) {
// Initialization.
Map<Node, Node> nextNodeMap = new HashMap<Node, Node>();
Node currentNode = sourceNode;
Node previousNode = sourceNode;
// Queue
Queue<Node> queue = new LinkedList<Node>();
queue.add(currentNode);
/*
* The set of visited nodes doesn't have to be a Map, and, since order
* is not important, an ordered collection is not needed. HashSet is
* fast for add and lookup, if configured properly.
*/
Set<Node> visitedNodes = new HashSet<Node>();
visitedNodes.add(currentNode);
//Search.
while (!queue.isEmpty()) {
currentNode = queue.remove();
if (currentNode.equals(destinationNode)) {
// Handle case where the node leading to the destinatino node
// itself pointed to multiple nodes. In this case,
// nextNodeMap is incorrect and we need to rely on the previously
// seen node.
// Also need to check for edge-case of start node == end node.
if (!previousNode.equals(currentNode)) {
nextNodeMap.put(previousNode, currentNode);
}
break;
} else {
for (Node nextNode : currentNode.getSiblingNodes()) {
if (!visitedNodes.contains(nextNode)) {
queue.add(nextNode);
visitedNodes.add(nextNode);
// Look up of next node instead of previous.
nextNodeMap.put(currentNode, nextNode);
previousNode = currentNode;
}
}
}
}
// If all nodes are explored and the destination node hasn't been found.
if (!currentNode.equals(destinationNode)) {
throw new RuntimeException("No feasible path.");
}
// Reconstruct path. No need to reverse.
List<Node> directions = new LinkedList<Node>();
for (Node node = sourceNode; node != null; node = nextNodeMap.get(node)) {
directions.add(node);
}
return directions;
}
}
</code></pre>
|
[
{
"answer_id": 74621509,
"author": "Alexander Ivanchenko",
"author_id": 17949945,
"author_profile": "https://Stackoverflow.com/users/17949945",
"pm_score": 3,
"selected": true,
"text": "Map 4 -> 6 4 -> 5 destination destination source HashSet public static List<Node> getDirections(Node source, Node destination) {\n Map<Node, Node> paths = new HashMap<>(); // Map of paths also allows to track the visited nodes\n Queue<Node> queue = new ArrayDeque<>(); // is more performant than LinkedList\n queue.add(source);\n paths.put(source, null); // the starting point of the path\n \n boolean isFound = false;\n \n while (!isFound && !queue.isEmpty()) {\n Node current = queue.remove();\n \n for (Node sibling : current.getSiblingNodes()) {\n if (paths.containsKey(sibling)) continue;\n // update the Map of paths\n paths.put(sibling, current);\n // the target node was found\n if (sibling.equals(destination)) {\n isFound = true; // we need to terminate the search, no need to explore all nodes if the path is found\n break;\n }\n queue.add(sibling); // adding the sibling to the queue\n }\n }\n return getPath(source, destination, paths);\n}\n public static List<Node> getPath(Node start, Node end, Map<Node, Node> paths) {\n List<Node> path = new ArrayList<>();\n Node current = end;\n path.add(current);\n while (current != start && current != null) { // if there's no path from start to end current eventually will become null\n path.add(paths.get(current));\n current = paths.get(current);\n }\n Collections.reverse(path);\n return current != null ? path : Collections.emptyList();\n}\n equals() Node java.lang.Object.equals() hashCode() equals() equals hashCode public class Node {\n private final int value;\n private final Set<Node> siblingNodes = new HashSet<>();\n \n // constructor, getters, addSiblingNode(), etc.\n \n @Override\n public boolean equals(Object o) {\n return o instanceof Node other && value == other.value;\n }\n \n @Override\n public int hashCode() {\n return Objects.hash(value);\n }\n}\n main() public static void main(String[] args) {\n // sample data from the question\n \n List<Node> shortestPath = getDirections(node0, node7);\n \n String path = shortestPath.stream()\n .map(Node::getValue)\n .map(String::valueOf)\n .collect(Collectors.joining(\" -> \"));\n\n System.out.println(path);\n}\n 0 -> 2 -> 3 -> 4 -> 6 -> 7\n"
},
{
"answer_id": 74622023,
"author": "モキャデ",
"author_id": 20607467,
"author_profile": "https://Stackoverflow.com/users/20607467",
"pm_score": 0,
"selected": false,
"text": "getDirections() Node Node Node Map Set @Override\n public int hashCode() {\n return value;\n }\n\n @Override\n public boolean equals(Object obj) {\n return obj instanceof Node n\n && n.value == value;\n }\n 0\n2\n3\n4\n6\n7\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74621070",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5719229/"
] |
74,621,107
|
<p>How can I fill the area between two curves (Kaplan-Meier) limited to a especific time, in the figure (by example, x=40) where the length of "x" and "y" differ.
x1= km<a href="https://i.stack.imgur.com/jI1nV.jpg" rel="nofollow noreferrer">1</a>$time y1=km<a href="https://i.stack.imgur.com/jI1nV.jpg" rel="nofollow noreferrer">1</a>$surv in curve 1; and x2=km<a href="https://i.stack.imgur.com/q9dMx.jpg" rel="nofollow noreferrer">2</a>$time y2=km<a href="https://i.stack.imgur.com/q9dMx.jpg" rel="nofollow noreferrer">2</a>$surv in curve 2</p>
<p>Thanks</p>
<pre><code>library(survival)
data(cancer)
aml
km<- survfit(Surv(time,status)~x, aml)
plot(km, col=1:2)
#x1= km[1]$time y1=km[1]$surv in curve 1; and
#x2= km[2]$time y2=km[2]$surv in curve 2
</code></pre>
<p><a href="https://i.stack.imgur.com/jI1nV.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/jI1nV.jpg" alt="enter image description here" /></a></p>
<p>I am looking for something like this:
<a href="https://i.stack.imgur.com/q9dMx.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/q9dMx.jpg" alt="enter image description here" /></a></p>
|
[
{
"answer_id": 74621509,
"author": "Alexander Ivanchenko",
"author_id": 17949945,
"author_profile": "https://Stackoverflow.com/users/17949945",
"pm_score": 3,
"selected": true,
"text": "Map 4 -> 6 4 -> 5 destination destination source HashSet public static List<Node> getDirections(Node source, Node destination) {\n Map<Node, Node> paths = new HashMap<>(); // Map of paths also allows to track the visited nodes\n Queue<Node> queue = new ArrayDeque<>(); // is more performant than LinkedList\n queue.add(source);\n paths.put(source, null); // the starting point of the path\n \n boolean isFound = false;\n \n while (!isFound && !queue.isEmpty()) {\n Node current = queue.remove();\n \n for (Node sibling : current.getSiblingNodes()) {\n if (paths.containsKey(sibling)) continue;\n // update the Map of paths\n paths.put(sibling, current);\n // the target node was found\n if (sibling.equals(destination)) {\n isFound = true; // we need to terminate the search, no need to explore all nodes if the path is found\n break;\n }\n queue.add(sibling); // adding the sibling to the queue\n }\n }\n return getPath(source, destination, paths);\n}\n public static List<Node> getPath(Node start, Node end, Map<Node, Node> paths) {\n List<Node> path = new ArrayList<>();\n Node current = end;\n path.add(current);\n while (current != start && current != null) { // if there's no path from start to end current eventually will become null\n path.add(paths.get(current));\n current = paths.get(current);\n }\n Collections.reverse(path);\n return current != null ? path : Collections.emptyList();\n}\n equals() Node java.lang.Object.equals() hashCode() equals() equals hashCode public class Node {\n private final int value;\n private final Set<Node> siblingNodes = new HashSet<>();\n \n // constructor, getters, addSiblingNode(), etc.\n \n @Override\n public boolean equals(Object o) {\n return o instanceof Node other && value == other.value;\n }\n \n @Override\n public int hashCode() {\n return Objects.hash(value);\n }\n}\n main() public static void main(String[] args) {\n // sample data from the question\n \n List<Node> shortestPath = getDirections(node0, node7);\n \n String path = shortestPath.stream()\n .map(Node::getValue)\n .map(String::valueOf)\n .collect(Collectors.joining(\" -> \"));\n\n System.out.println(path);\n}\n 0 -> 2 -> 3 -> 4 -> 6 -> 7\n"
},
{
"answer_id": 74622023,
"author": "モキャデ",
"author_id": 20607467,
"author_profile": "https://Stackoverflow.com/users/20607467",
"pm_score": 0,
"selected": false,
"text": "getDirections() Node Node Node Map Set @Override\n public int hashCode() {\n return value;\n }\n\n @Override\n public boolean equals(Object obj) {\n return obj instanceof Node n\n && n.value == value;\n }\n 0\n2\n3\n4\n6\n7\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74621107",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18017716/"
] |
74,621,129
|
<p>In the <a href="https://doc.rust-lang.org/book/ch10-00-generics.html" rel="nofollow noreferrer">Rust official doc</a>, there is a code sample as:</p>
<pre><code>fn main() {
let number_list = vec![34, 50, 25, 100, 65];
let result = largest(&number_list);
println!("The largest number is {}", result);
let number_list = vec![102, 34, 6000, 89, 54, 2, 43, 8];
let result = largest(&number_list);
println!("The largest number is {}", result);
}
</code></pre>
<p>I was wondering what <code>&number_list</code> looks like (is it the same as <code>&number_list[0]</code>), so I tried this example:</p>
<pre><code>fn reference() {
let number_list = vec![1,2,3,4,5];
let ref = &number_list;
println!("{}", ref);
}
</code></pre>
<p>However, I got the error:</p>
<pre><code>error: expected identifier, found `=`
|
| let ref = &number_list;
| ^ expected identifier
</code></pre>
<p>Any clues on this? Why is it not assign-able and gives an error message that doesn't quite make sense (at least for me)?</p>
|
[
{
"answer_id": 74621276,
"author": "Matias Bertoni",
"author_id": 19272564,
"author_profile": "https://Stackoverflow.com/users/19272564",
"pm_score": 0,
"selected": false,
"text": "ref"
},
{
"answer_id": 74621284,
"author": "9bO3av5fw5",
"author_id": 6712861,
"author_profile": "https://Stackoverflow.com/users/6712861",
"pm_score": 2,
"selected": false,
"text": "ref fn reference() {\n let number_list = vec![1,2,3,4,5];\n let my_variable = &number_list;\n println!(\"{}\", my_variable);\n}\n"
},
{
"answer_id": 74621390,
"author": "Silvio Mayolo",
"author_id": 2288659,
"author_profile": "https://Stackoverflow.com/users/2288659",
"pm_score": 2,
"selected": false,
"text": "ref ref"
},
{
"answer_id": 74628785,
"author": "Miiao",
"author_id": 20028181,
"author_profile": "https://Stackoverflow.com/users/20028181",
"pm_score": 0,
"selected": false,
"text": "ref fn reference() {\n let number_list = vec![1,2,3,4,5];\n let ref my_ref = &number_list;\n println!(\"{:?}\", my_ref);\n}\n &idxable &idxable[0] &idxable"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74621129",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7062272/"
] |
74,621,143
|
<p>I have a method in my Interface that retrieves all records from my Room Database as a LiveData List. My method is as follows:</p>
<pre><code> @Query("SELECT *FROM task_table ORDER BY taskId DESC")
fun getAll():LiveData<List<Task>>
</code></pre>
<p>I have the following code in my ViewModel class:</p>
<pre><code>val tasks:LiveData<List<Task>> = taskDao.getAll()
</code></pre>
<p>Also I've got an Observer setup in my Fragment as follows:</p>
<pre><code>//After some other code and code to create an instance of the ViewModel
viewModel.tasks.observe(viewLifecycleOwner, Observer {
it?.let {
adapter.data = it
}
})
</code></pre>
<p>I'm a bit confused with LiveData. When I add a new record to my Room Database, my LiveData<List> updates on it's own without me having to call the</p>
<p>getAll() method. When you have LiveData, does the Android OS updates this List when you add/delete/update a record in the Database? Thanks.</p>
|
[
{
"answer_id": 74621276,
"author": "Matias Bertoni",
"author_id": 19272564,
"author_profile": "https://Stackoverflow.com/users/19272564",
"pm_score": 0,
"selected": false,
"text": "ref"
},
{
"answer_id": 74621284,
"author": "9bO3av5fw5",
"author_id": 6712861,
"author_profile": "https://Stackoverflow.com/users/6712861",
"pm_score": 2,
"selected": false,
"text": "ref fn reference() {\n let number_list = vec![1,2,3,4,5];\n let my_variable = &number_list;\n println!(\"{}\", my_variable);\n}\n"
},
{
"answer_id": 74621390,
"author": "Silvio Mayolo",
"author_id": 2288659,
"author_profile": "https://Stackoverflow.com/users/2288659",
"pm_score": 2,
"selected": false,
"text": "ref ref"
},
{
"answer_id": 74628785,
"author": "Miiao",
"author_id": 20028181,
"author_profile": "https://Stackoverflow.com/users/20028181",
"pm_score": 0,
"selected": false,
"text": "ref fn reference() {\n let number_list = vec![1,2,3,4,5];\n let ref my_ref = &number_list;\n println!(\"{:?}\", my_ref);\n}\n &idxable &idxable[0] &idxable"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74621143",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6998445/"
] |
74,621,213
|
<p>I am writing a program in Angular which displays short texts. In these texts I want to blur a certain substring, EACH time it occurs.</p>
<p>E.g. Tomorrow I will have to go to London. Tomorrow is the day it will happen. My only hope is tomorrow.</p>
<p>Here I would want to blur the text 'tomorrow', three times.
Sometimes the substring occurs once, sometimes twice, ... or five times.</p>
<p>A tap or click on the words or on the paragraph UNBLURS them.</p>
<p>I did it with an indexOf function, put the substring into a span with a different class and an ngStyle attribute. But this does it only for the first occurrence of the substring.</p>
<pre><code> const position = quoteL.indexOf(titleL);
if (position > -1) { // if the substr appears in the quote -> chop up the string and blur it
this.p1= quote?.substring(0, position);
this.p2= quote?.substring(position, position + title.length);
this.p3= quote?.substring(position+title.length, quote.length);
} else {
this.p1 = this.lyrics;
this.p2="";
this.p3=""
}
</code></pre>
<p>`</p>
|
[
{
"answer_id": 74622008,
"author": "Leonid Shvab",
"author_id": 20639512,
"author_profile": "https://Stackoverflow.com/users/20639512",
"pm_score": 2,
"selected": false,
"text": ".highlighted {\n opacity: .3;\n}\n\n<p id=\"text\">Tomorrow I will have to go to London. Tomorrow is the day it will happen. My only hope is tomorrow.</p>\n<button onclick=\"highlightQueryStr('Tomorrow')\">highlightQuery</button>\n \n<script>\n function highlightQueryStr(query) {\n const textEl = document.querySelector(\"#text\");\n const reg = new RegExp(query,\"gi\");\n textEl.innerHTML = textEl.innerHTML.replace(reg, `<span \n class=\"highlighted\">${query}</span>`);\n }\n</script>\n"
},
{
"answer_id": 74627828,
"author": "Eliseo",
"author_id": 8558186,
"author_profile": "https://Stackoverflow.com/users/8558186",
"pm_score": 0,
"selected": false,
"text": "@Ouput @Output() click:EventEmitter<any>=new EventEmitter<any>() //define the EventEmitter\n\n ngAfterContentChecked() {\n if (this.el.nativeElement.innerHTML != this.oldValue) {\n ...\n this.renderer.listen(this.div,'click',(event)=>{\n this.click.emit(event)\n })\n }\n }\n strong click(event)\n {\n if (event.target.tagName==\"STRONG\")\n event.target.classList.add('no-blur');\n }\n .highlight strong {\n color: red;\n font-weight: normal;\n filter: blur(.3rem);\n}\n.highlight strong.no-blur {\n color: blue;\n font-weight: normal;\n filter: none;\n}\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74621213",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10936870/"
] |
74,621,217
|
<p>I have a df (reference image) that I create that shows an aggregation of all the combinations each publisher has to another and then does calculations based on said pair(s). <a href="https://i.stack.imgur.com/IVDiV.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/IVDiV.jpg" alt="enter image description here" /></a></p>
<p>I want to pull every distinct pair that only contains 2 publishers and all the other field values that are tied to that pair (example would be Amazon, CBS but twice since there is one for month 10 and one for month 11 and so on.</p>
<p>How do I extract this or apply some dplyr function to only pull those? Was thinking of using a regex function in with a pipe but not sure how to do it.</p>
<h1>Expected output</h1>
<pre><code>Publisher | month_grp
Amazon, CBS 10
Amazon, CBS 11
Amazon, CW 10
Amazon, CW 11
Amazon, ESPN 10
Amazon, ESPN 11
</code></pre>
|
[
{
"answer_id": 74621270,
"author": "G5W",
"author_id": 4752675,
"author_profile": "https://Stackoverflow.com/users/4752675",
"pm_score": 3,
"selected": true,
"text": "df[grep('^[^,]+,[^,]+$', df$publishers),]\n"
},
{
"answer_id": 74621278,
"author": "Andy Baxter",
"author_id": 10744082,
"author_profile": "https://Stackoverflow.com/users/10744082",
"pm_score": 1,
"selected": false,
"text": "dplyr::filter stringr::str_detect library(tidyverse)\n\ntribble(~ Publisher, ~month_grp,\n \"AWS, CBS\", 4,\n \"AWS, CBS, CW\", 2,\n \"AWS, ESPN\", 6,\n \"AWS, CBS, ESPN\", 2,\n \"AWS, Samsung TV plus\", 4,\n \"AWS, ESPN, CBS\", 4\n ) |> \n filter(str_detect(Publisher, \"^[\\\\w ]*, [\\\\w ]*$\"))\n\n#> # A tibble: 3 × 2\n#> Publisher month_grp\n#> <chr> <dbl>\n#> 1 AWS, CBS 4\n#> 2 AWS, ESPN 6\n#> 3 AWS, Samsung TV plus 4\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74621217",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11692944/"
] |
74,621,267
|
<pre><code>import pygame
import os
WIDTH, HEIGHT = 900, 500
WIN = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("First Game!")
WHITE = (255, 255, 255)
FPS = 60
SPACESHIP_WIDTH, SPACESHIP_HEIGHT = 55, 40
YELLOW_SPACESHIP_IMAGE = pygame.image.load(
os.path.join('Assets', 'spaceship_yellow.png'))
YELLOW_SPACESHIP = pygame.image.rotate(pygame.transform.scale(
YELLOW_SPACESHIP_IMAGE, (SPACESHIP_WIDTH, SPACESHIP_HEIGHT)), 90)
RED_SPACESHIP_IMAGE = pygame.image.load(
os.path.join('Assets', 'spaceship_red.png'))
RED_SPACESHIP = pygame.transform.scale(
RED_SPACESHIP_IMAGE, (SPACESHIP_WIDTH, SPACESHIP_HEIGHT))
def draw_window():
WIN.fill(WHITE)
WIN.blit(YELLOW_SPACESHIP, (300, 100))
pygame.display.update()
def main():
clock = pygame.time.Clock()
run = True
while run:
clock.tick(FPS)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
draw_window()
pygame.quit()
if __name__ == "__main__":
main()
</code></pre>
<p>I have been carefully following an introduction video to making games using pygame and have reached the point when running the code the error</p>
<pre><code>Traceback (most recent call last):
File "C:\Users\morle\PycharmProjects\pythonProject\first game test.py", line 15, in <module>
YELLOW_SPACESHIP = pygame.image.rotate(pygame.transform.scale(
AttributeError: module 'pygame.image' has no attribute 'rotate'
</code></pre>
<p>the line in question is</p>
<pre><code>YELLOW_SPACESHIP = pygame.image.rotate(pygame.transform.scale(
YELLOW_SPACESHIP_IMAGE, (SPACESHIP_WIDTH, SPACESHIP_HEIGHT)), 90)
</code></pre>
<p>I dont understand why this is happening any help would be much appreciated.</p>
<p>here is the link for the video 27:08
<a href="https://www.youtube.com/watch?v=jO6qQDNa2UY" rel="nofollow noreferrer">text</a></p>
|
[
{
"answer_id": 74621270,
"author": "G5W",
"author_id": 4752675,
"author_profile": "https://Stackoverflow.com/users/4752675",
"pm_score": 3,
"selected": true,
"text": "df[grep('^[^,]+,[^,]+$', df$publishers),]\n"
},
{
"answer_id": 74621278,
"author": "Andy Baxter",
"author_id": 10744082,
"author_profile": "https://Stackoverflow.com/users/10744082",
"pm_score": 1,
"selected": false,
"text": "dplyr::filter stringr::str_detect library(tidyverse)\n\ntribble(~ Publisher, ~month_grp,\n \"AWS, CBS\", 4,\n \"AWS, CBS, CW\", 2,\n \"AWS, ESPN\", 6,\n \"AWS, CBS, ESPN\", 2,\n \"AWS, Samsung TV plus\", 4,\n \"AWS, ESPN, CBS\", 4\n ) |> \n filter(str_detect(Publisher, \"^[\\\\w ]*, [\\\\w ]*$\"))\n\n#> # A tibble: 3 × 2\n#> Publisher month_grp\n#> <chr> <dbl>\n#> 1 AWS, CBS 4\n#> 2 AWS, ESPN 6\n#> 3 AWS, Samsung TV plus 4\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74621267",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20636522/"
] |
74,621,283
|
<p>I have been trying to find a solution to this problem for a little while now and all the answers don't seem to be quite what I'm looking for.</p>
<p>I'm sure the answer to this is probably simple and I'm overthinking it.</p>
<p>I've been trying to have a table next to a barplot which corresponds to the same observations in the table. However, the table doesn't seem to line up with the size of the plot because it has too much white space or is too small.</p>
<p>Is there a way that I can have the title of the plot and the title of the columns in the table lineup?</p>
<pre><code>data(mtcars)
library(ggplot2)
library(dplyr)
library(grid)
library(gridExtra)
library(cowplot)
data <- mtcars %>% select(mpg, disp, cyl, qsec) %>% tibble::rownames_to_column("Car Name") %>% slice(1:7)
data$`Car Name` <- factor(data$`Car Name`, levels = data$`Car Name`)
t <- tableGrob(data %>% slice(1:7) %>% select(-mpg),
theme = ttheme_minimal(),
rows = NULL)
plot(t)
p <- ggplot(data = data, aes(x = mpg, y = `Car Name`)) +
geom_bar(stat = "identity", fill = "white", color = "black", alpha = 0.3, size = .75) + theme_classic() +
theme(axis.text.y = element_blank(),
axis.title.y = element_blank(),
axis.title.x = element_blank(),
plot.title = element_text(face = "bold")) +
ggtitle("No. of mpg") +
scale_x_continuous(expand = expansion(mult = c(0, .1)), limits = c(0,30)) +
scale_y_discrete(limits=rev)
p
grid.arrange(t, p, nrow = 1)
</code></pre>
<p>This is what I have done to make the table and plot. I have a basic grid.arrange at the bottom to highlight my issue.</p>
<p>The image here highlights the differences in size between the table and the plot
<a href="https://i.stack.imgur.com/rUjk4.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/rUjk4.png" alt="enter image description here" /></a></p>
|
[
{
"answer_id": 74621375,
"author": "Andy Baxter",
"author_id": 10744082,
"author_profile": "https://Stackoverflow.com/users/10744082",
"pm_score": 2,
"selected": false,
"text": "patchwork library(tidyverse)\nlibrary(patchwork)\n\ndata <- mtcars %>% select(mpg, disp, cyl, qsec) %>% rownames_to_column(\"Car Name\") %>% slice(1:7)\n\ndata$order <- factor(as.integer(factor(data$`Car Name`)))\n\ndata_rs <- data |> \n select(order, disp, cyl, qsec, `Car Name`) |> \n pivot_longer(-order, names_to = \"var\", values_to = \"val\", values_transform = as.character)\n\np1 <- ggplot(data = data, aes(x = mpg, y = order)) + \n geom_bar(stat = \"identity\", fill = \"white\", color = \"black\", alpha = 0.3, linewidth = .75) +\n theme_classic() +\n theme(axis.text.y = element_blank(),\n axis.title.y = element_blank(),\n axis.title.x = element_blank(),\n strip.background = element_blank(),\n strip.text = element_text(face = \"bold\", size = 12, hjust = 0)) +\n scale_x_continuous(expand = expansion(mult = c(0, .1)), limits = c(0,30)) +\n scale_y_discrete(limits=rev) +\n facet_wrap(~\"No. of mpg\")\n\np2 <- ggplot(data_rs, (aes(x = 1, y = order, label = val))) +\n geom_text() +\n facet_wrap(~fct_inorder(var), nrow = 1) +\n scale_y_discrete(limits=rev) +\n theme(axis.title.y = element_blank(),\n axis.text.y = element_blank(),\n axis.ticks = element_blank(),\n axis.text.x = element_blank(),\n axis.title.x = element_blank(),\n panel.grid = element_blank(),\n strip.background = element_blank(),\n panel.background = element_blank(),\n strip.clip = \"off\",\n strip.text = element_text(face = \"bold\", size = 12)) +\n coord_cartesian(clip = \"off\")\n\np2 + p1 + plot_layout(widths = c(0.7, 0.3))\n theme"
},
{
"answer_id": 74621400,
"author": "Jon Spring",
"author_id": 6851825,
"author_profile": "https://Stackoverflow.com/users/6851825",
"pm_score": 2,
"selected": false,
"text": "library(dplyr); library(gt); library(gtExtras)\nmtcars %>%\n tibble::rownames_to_column(\"Car Name\") %>%\n select(1, disp, cyl, qsec, mpg) %>%\n slice(1:7) %>%\n gt() %>%\n gt_plt_bar(column = mpg, color = \"gray80\", scale_type = \"number\", \n text_color = \"gray30\")\n gt::ggplot_image library(tidyverse); library(gt)\nplot_mpg <- function(df) {\n ggplot(data = df, aes(mpg, \"a\")) +\n geom_col(orientation = \"y\", fill = NA, color = \"gray20\", size = 4) +\n geom_text(aes(label = mpg), hjust = 1.1, size = 60) +\n coord_fixed(ratio = 5, xlim = c(0, 30)) +\n theme_void()\n}\n\nmtcars %>%\n tibble::rownames_to_column(\"Car Name\") %>%\n nest(data = mpg) %>%\n mutate(plot = map(data, plot_mpg)) %>%\n select(1, disp, cyl, qsec, plot) %>%\n mutate(mpg = NA) %>% # placeholder column\n slice(1:7) -> a\n\ngt(a) %>%\n cols_width(mpg ~ px(80)) %>%\n tab_options(data_row.padding = px(2)) %>%\n text_transform(\n locations = cells_body(mpg),\n fn = function(x) { map(a$plot, ~ggplot_image(., height = px(20), aspect_ratio = 6)) }\n ) %>%\n cols_hide(plot)\n \n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74621283",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20638922/"
] |
74,621,288
|
<p><a href="https://i.stack.imgur.com/VJNrn.png" rel="nofollow noreferrer">Dataframe</a>Basically, Im trying to give the team in the snitchCatcher variable + 5 goals in their specific homeGoals/awayGoals variable.
`</p>
<pre><code>ifelse(Df$snitchCatcher == "home",
Df$homeGoals + 5,
Df$awayGoals + 5)
</code></pre>
<p>`</p>
<p>This is the code that i use, it does give correct calculation in the console, but yet it is defined at 1 list and not yet make any change inside of the dataframe variable. Is there any chance i can directly change/replace the value of the variable with above condition?</p>
<p>I am very new to R, i have think about subsetting data, create a data with only 1 team then combine later, etc,... however i do not know what to do, and I have already late on my assignment. I really need some help to at least solve the above issue so I can continue. Please help.</p>
<p>I will post a screencap of the dataframe</p>
|
[
{
"answer_id": 74621375,
"author": "Andy Baxter",
"author_id": 10744082,
"author_profile": "https://Stackoverflow.com/users/10744082",
"pm_score": 2,
"selected": false,
"text": "patchwork library(tidyverse)\nlibrary(patchwork)\n\ndata <- mtcars %>% select(mpg, disp, cyl, qsec) %>% rownames_to_column(\"Car Name\") %>% slice(1:7)\n\ndata$order <- factor(as.integer(factor(data$`Car Name`)))\n\ndata_rs <- data |> \n select(order, disp, cyl, qsec, `Car Name`) |> \n pivot_longer(-order, names_to = \"var\", values_to = \"val\", values_transform = as.character)\n\np1 <- ggplot(data = data, aes(x = mpg, y = order)) + \n geom_bar(stat = \"identity\", fill = \"white\", color = \"black\", alpha = 0.3, linewidth = .75) +\n theme_classic() +\n theme(axis.text.y = element_blank(),\n axis.title.y = element_blank(),\n axis.title.x = element_blank(),\n strip.background = element_blank(),\n strip.text = element_text(face = \"bold\", size = 12, hjust = 0)) +\n scale_x_continuous(expand = expansion(mult = c(0, .1)), limits = c(0,30)) +\n scale_y_discrete(limits=rev) +\n facet_wrap(~\"No. of mpg\")\n\np2 <- ggplot(data_rs, (aes(x = 1, y = order, label = val))) +\n geom_text() +\n facet_wrap(~fct_inorder(var), nrow = 1) +\n scale_y_discrete(limits=rev) +\n theme(axis.title.y = element_blank(),\n axis.text.y = element_blank(),\n axis.ticks = element_blank(),\n axis.text.x = element_blank(),\n axis.title.x = element_blank(),\n panel.grid = element_blank(),\n strip.background = element_blank(),\n panel.background = element_blank(),\n strip.clip = \"off\",\n strip.text = element_text(face = \"bold\", size = 12)) +\n coord_cartesian(clip = \"off\")\n\np2 + p1 + plot_layout(widths = c(0.7, 0.3))\n theme"
},
{
"answer_id": 74621400,
"author": "Jon Spring",
"author_id": 6851825,
"author_profile": "https://Stackoverflow.com/users/6851825",
"pm_score": 2,
"selected": false,
"text": "library(dplyr); library(gt); library(gtExtras)\nmtcars %>%\n tibble::rownames_to_column(\"Car Name\") %>%\n select(1, disp, cyl, qsec, mpg) %>%\n slice(1:7) %>%\n gt() %>%\n gt_plt_bar(column = mpg, color = \"gray80\", scale_type = \"number\", \n text_color = \"gray30\")\n gt::ggplot_image library(tidyverse); library(gt)\nplot_mpg <- function(df) {\n ggplot(data = df, aes(mpg, \"a\")) +\n geom_col(orientation = \"y\", fill = NA, color = \"gray20\", size = 4) +\n geom_text(aes(label = mpg), hjust = 1.1, size = 60) +\n coord_fixed(ratio = 5, xlim = c(0, 30)) +\n theme_void()\n}\n\nmtcars %>%\n tibble::rownames_to_column(\"Car Name\") %>%\n nest(data = mpg) %>%\n mutate(plot = map(data, plot_mpg)) %>%\n select(1, disp, cyl, qsec, plot) %>%\n mutate(mpg = NA) %>% # placeholder column\n slice(1:7) -> a\n\ngt(a) %>%\n cols_width(mpg ~ px(80)) %>%\n tab_options(data_row.padding = px(2)) %>%\n text_transform(\n locations = cells_body(mpg),\n fn = function(x) { map(a$plot, ~ggplot_image(., height = px(20), aspect_ratio = 6)) }\n ) %>%\n cols_hide(plot)\n \n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74621288",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20616820/"
] |
74,621,306
|
<p>I am hoping to find the winning percentage for the NBA only (cell F18). Here is the formula for winning percentage: sum(wins)/(sum(losses)+sum(wins)).</p>
<p>In the example I use below there are 4 games that have been played. 3 of these games are for the NBA, the other is for the NHL (which I do not need).</p>
<p>The Win/Loss for the NBA in this example is 2 Wins and 1 loss for a win percentage of 66%.</p>
<p>Here is a snapshot of my current Google Sheets:</p>
<p><a href="https://i.stack.imgur.com/VuClZ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/VuClZ.png" alt="Google Sheets" /></a></p>
<p>I am working with 3 formulas in this example:1) <strong>Total win %</strong>, 2) <strong>NBA profit</strong> 3) <strong>NBA win %</strong>.</p>
<p>Formula #1 and #2 are working correctly. I am having an issue applying formula #3 <strong>NBA win%</strong>, however. Any suggestions?</p>
<p>Here are the working formulas...</p>
<p><strong>Total win %</strong> located in cell E18:</p>
<pre><code>=sum(B18:B)/(sum(C18:C)+sum(B18:B))
</code></pre>
<p><strong>NBA profit</strong> located in cell G18:</p>
<pre><code>=SUMIFS(D18:D,A18:A,"NBA")
</code></pre>
<p>Here is my attempt at applying the <strong>NBA win%</strong> to only the NBA data:</p>
<pre><code>=SUMIFS(D18:D,A18:A,F16,sum(B18:B)/(sum(C18:C)+sum(B18:B)))
</code></pre>
<p>Here is the error that I received:</p>
<pre><code>#Error! (Formula parse error)
</code></pre>
<p>I have browsed Stack and Google and unable to find something that applies to this specific situation. Any help would be greatly appreciated. Thanks in advance for any value that you may offer.</p>
<p>Note: I am trying to apply the <strong>NBA win %</strong> to cell F18. Also, the <strong>NBA win %</strong> formula and <strong>Total win %</strong> are the same. The only difference is The <strong>NBA win %</strong> output should include NBA win % data only(not NHL).</p>
|
[
{
"answer_id": 74621375,
"author": "Andy Baxter",
"author_id": 10744082,
"author_profile": "https://Stackoverflow.com/users/10744082",
"pm_score": 2,
"selected": false,
"text": "patchwork library(tidyverse)\nlibrary(patchwork)\n\ndata <- mtcars %>% select(mpg, disp, cyl, qsec) %>% rownames_to_column(\"Car Name\") %>% slice(1:7)\n\ndata$order <- factor(as.integer(factor(data$`Car Name`)))\n\ndata_rs <- data |> \n select(order, disp, cyl, qsec, `Car Name`) |> \n pivot_longer(-order, names_to = \"var\", values_to = \"val\", values_transform = as.character)\n\np1 <- ggplot(data = data, aes(x = mpg, y = order)) + \n geom_bar(stat = \"identity\", fill = \"white\", color = \"black\", alpha = 0.3, linewidth = .75) +\n theme_classic() +\n theme(axis.text.y = element_blank(),\n axis.title.y = element_blank(),\n axis.title.x = element_blank(),\n strip.background = element_blank(),\n strip.text = element_text(face = \"bold\", size = 12, hjust = 0)) +\n scale_x_continuous(expand = expansion(mult = c(0, .1)), limits = c(0,30)) +\n scale_y_discrete(limits=rev) +\n facet_wrap(~\"No. of mpg\")\n\np2 <- ggplot(data_rs, (aes(x = 1, y = order, label = val))) +\n geom_text() +\n facet_wrap(~fct_inorder(var), nrow = 1) +\n scale_y_discrete(limits=rev) +\n theme(axis.title.y = element_blank(),\n axis.text.y = element_blank(),\n axis.ticks = element_blank(),\n axis.text.x = element_blank(),\n axis.title.x = element_blank(),\n panel.grid = element_blank(),\n strip.background = element_blank(),\n panel.background = element_blank(),\n strip.clip = \"off\",\n strip.text = element_text(face = \"bold\", size = 12)) +\n coord_cartesian(clip = \"off\")\n\np2 + p1 + plot_layout(widths = c(0.7, 0.3))\n theme"
},
{
"answer_id": 74621400,
"author": "Jon Spring",
"author_id": 6851825,
"author_profile": "https://Stackoverflow.com/users/6851825",
"pm_score": 2,
"selected": false,
"text": "library(dplyr); library(gt); library(gtExtras)\nmtcars %>%\n tibble::rownames_to_column(\"Car Name\") %>%\n select(1, disp, cyl, qsec, mpg) %>%\n slice(1:7) %>%\n gt() %>%\n gt_plt_bar(column = mpg, color = \"gray80\", scale_type = \"number\", \n text_color = \"gray30\")\n gt::ggplot_image library(tidyverse); library(gt)\nplot_mpg <- function(df) {\n ggplot(data = df, aes(mpg, \"a\")) +\n geom_col(orientation = \"y\", fill = NA, color = \"gray20\", size = 4) +\n geom_text(aes(label = mpg), hjust = 1.1, size = 60) +\n coord_fixed(ratio = 5, xlim = c(0, 30)) +\n theme_void()\n}\n\nmtcars %>%\n tibble::rownames_to_column(\"Car Name\") %>%\n nest(data = mpg) %>%\n mutate(plot = map(data, plot_mpg)) %>%\n select(1, disp, cyl, qsec, plot) %>%\n mutate(mpg = NA) %>% # placeholder column\n slice(1:7) -> a\n\ngt(a) %>%\n cols_width(mpg ~ px(80)) %>%\n tab_options(data_row.padding = px(2)) %>%\n text_transform(\n locations = cells_body(mpg),\n fn = function(x) { map(a$plot, ~ggplot_image(., height = px(20), aspect_ratio = 6)) }\n ) %>%\n cols_hide(plot)\n \n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74621306",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10244126/"
] |
74,621,340
|
<p>I am trying to implement redis using the packages : "CacheModule" and "cache-manager-redis-store". The latter brings me a type error when assigning it to the store property of the register method of CacheModule.</p>
<p>code where the error occurs:</p>
<p>`</p>
<pre><code>import { Module, CacheModule } from "@nestjs/common";
import { AuthModule } from "./auth/auth.module";
import { MongooseModule } from "@nestjs/mongoose";
import { EnvConfiguration } from "./config/env.config";
import { ConfigModule } from "@nestjs/config";
import { redisStore } from "cache-manager-redis-store";
@Module({
imports: [
ConfigModule.forRoot({
load: [EnvConfiguration],
}),
MongooseModule.forRoot(process.env.MONGODB),
AuthModule,
CacheModule.register({
store: redisStore, <--- HERE THE ERROR HAPPENS
host: "localhost",
port: 6379,
}),
],
controllers: [],
providers: [],
})
export class AppModule {}
</code></pre>
<p>`</p>
<p>ERROR:
`</p>
<pre><code>(property) store: (string | CacheStoreFactory | CacheStore) & ((config: RedisClientOptions<RedisModules, RedisFunctions, RedisScripts> & Config) => Promise<...>)
Cache manager. The default value is 'memory' (memory storage). See Different Stores for more information.
Type '(config: RedisClientOptions<RedisModules, RedisFunctions, RedisScripts> & Config) => Promise<RedisStore>' cannot be assigned to type '(string | CacheStoreFactory | CacheStore) & ((config: RedisClientOptions<RedisModules, RedisFunctions, RedisScripts > & Configuration) => Promise<...>)'.
Type '(config: RedisClientOptions<RedisModules, RedisFunctions, RedisScripts> & Config) => Promise<RedisStore>' cannot be assigned to type 'string & ((config: RedisClientOptions<RedisModules, RedisFunctions, RedisScripts> & Config) => Promise<...>)'.
Type '(config: RedisClientOptions<RedisModules, RedisFunctions, RedisScripts> & Config) => Promise<RedisStore>' cannot be assigned to type 'string'.ts(2322)
</code></pre>
<p>`</p>
<p>I want to be able to implement redis with nestjs, solving the described problem or with another way of implementing it that works correctly.</p>
|
[
{
"answer_id": 74621375,
"author": "Andy Baxter",
"author_id": 10744082,
"author_profile": "https://Stackoverflow.com/users/10744082",
"pm_score": 2,
"selected": false,
"text": "patchwork library(tidyverse)\nlibrary(patchwork)\n\ndata <- mtcars %>% select(mpg, disp, cyl, qsec) %>% rownames_to_column(\"Car Name\") %>% slice(1:7)\n\ndata$order <- factor(as.integer(factor(data$`Car Name`)))\n\ndata_rs <- data |> \n select(order, disp, cyl, qsec, `Car Name`) |> \n pivot_longer(-order, names_to = \"var\", values_to = \"val\", values_transform = as.character)\n\np1 <- ggplot(data = data, aes(x = mpg, y = order)) + \n geom_bar(stat = \"identity\", fill = \"white\", color = \"black\", alpha = 0.3, linewidth = .75) +\n theme_classic() +\n theme(axis.text.y = element_blank(),\n axis.title.y = element_blank(),\n axis.title.x = element_blank(),\n strip.background = element_blank(),\n strip.text = element_text(face = \"bold\", size = 12, hjust = 0)) +\n scale_x_continuous(expand = expansion(mult = c(0, .1)), limits = c(0,30)) +\n scale_y_discrete(limits=rev) +\n facet_wrap(~\"No. of mpg\")\n\np2 <- ggplot(data_rs, (aes(x = 1, y = order, label = val))) +\n geom_text() +\n facet_wrap(~fct_inorder(var), nrow = 1) +\n scale_y_discrete(limits=rev) +\n theme(axis.title.y = element_blank(),\n axis.text.y = element_blank(),\n axis.ticks = element_blank(),\n axis.text.x = element_blank(),\n axis.title.x = element_blank(),\n panel.grid = element_blank(),\n strip.background = element_blank(),\n panel.background = element_blank(),\n strip.clip = \"off\",\n strip.text = element_text(face = \"bold\", size = 12)) +\n coord_cartesian(clip = \"off\")\n\np2 + p1 + plot_layout(widths = c(0.7, 0.3))\n theme"
},
{
"answer_id": 74621400,
"author": "Jon Spring",
"author_id": 6851825,
"author_profile": "https://Stackoverflow.com/users/6851825",
"pm_score": 2,
"selected": false,
"text": "library(dplyr); library(gt); library(gtExtras)\nmtcars %>%\n tibble::rownames_to_column(\"Car Name\") %>%\n select(1, disp, cyl, qsec, mpg) %>%\n slice(1:7) %>%\n gt() %>%\n gt_plt_bar(column = mpg, color = \"gray80\", scale_type = \"number\", \n text_color = \"gray30\")\n gt::ggplot_image library(tidyverse); library(gt)\nplot_mpg <- function(df) {\n ggplot(data = df, aes(mpg, \"a\")) +\n geom_col(orientation = \"y\", fill = NA, color = \"gray20\", size = 4) +\n geom_text(aes(label = mpg), hjust = 1.1, size = 60) +\n coord_fixed(ratio = 5, xlim = c(0, 30)) +\n theme_void()\n}\n\nmtcars %>%\n tibble::rownames_to_column(\"Car Name\") %>%\n nest(data = mpg) %>%\n mutate(plot = map(data, plot_mpg)) %>%\n select(1, disp, cyl, qsec, plot) %>%\n mutate(mpg = NA) %>% # placeholder column\n slice(1:7) -> a\n\ngt(a) %>%\n cols_width(mpg ~ px(80)) %>%\n tab_options(data_row.padding = px(2)) %>%\n text_transform(\n locations = cells_body(mpg),\n fn = function(x) { map(a$plot, ~ggplot_image(., height = px(20), aspect_ratio = 6)) }\n ) %>%\n cols_hide(plot)\n \n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74621340",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10402159/"
] |
74,621,353
|
<p>I am not sure how to gather the values of each input from the while loop to find product of 4 numbers, I am gathering 4 number inputs. cannot use array list</p>
<pre><code> int numbers =0;
int a;
while (numbers <= 3) {
Scanner in = new Scanner(System.in);
System.out.println("Enter A number: ");
numbers++;
a = in.nextInt();
}
</code></pre>
|
[
{
"answer_id": 74621375,
"author": "Andy Baxter",
"author_id": 10744082,
"author_profile": "https://Stackoverflow.com/users/10744082",
"pm_score": 2,
"selected": false,
"text": "patchwork library(tidyverse)\nlibrary(patchwork)\n\ndata <- mtcars %>% select(mpg, disp, cyl, qsec) %>% rownames_to_column(\"Car Name\") %>% slice(1:7)\n\ndata$order <- factor(as.integer(factor(data$`Car Name`)))\n\ndata_rs <- data |> \n select(order, disp, cyl, qsec, `Car Name`) |> \n pivot_longer(-order, names_to = \"var\", values_to = \"val\", values_transform = as.character)\n\np1 <- ggplot(data = data, aes(x = mpg, y = order)) + \n geom_bar(stat = \"identity\", fill = \"white\", color = \"black\", alpha = 0.3, linewidth = .75) +\n theme_classic() +\n theme(axis.text.y = element_blank(),\n axis.title.y = element_blank(),\n axis.title.x = element_blank(),\n strip.background = element_blank(),\n strip.text = element_text(face = \"bold\", size = 12, hjust = 0)) +\n scale_x_continuous(expand = expansion(mult = c(0, .1)), limits = c(0,30)) +\n scale_y_discrete(limits=rev) +\n facet_wrap(~\"No. of mpg\")\n\np2 <- ggplot(data_rs, (aes(x = 1, y = order, label = val))) +\n geom_text() +\n facet_wrap(~fct_inorder(var), nrow = 1) +\n scale_y_discrete(limits=rev) +\n theme(axis.title.y = element_blank(),\n axis.text.y = element_blank(),\n axis.ticks = element_blank(),\n axis.text.x = element_blank(),\n axis.title.x = element_blank(),\n panel.grid = element_blank(),\n strip.background = element_blank(),\n panel.background = element_blank(),\n strip.clip = \"off\",\n strip.text = element_text(face = \"bold\", size = 12)) +\n coord_cartesian(clip = \"off\")\n\np2 + p1 + plot_layout(widths = c(0.7, 0.3))\n theme"
},
{
"answer_id": 74621400,
"author": "Jon Spring",
"author_id": 6851825,
"author_profile": "https://Stackoverflow.com/users/6851825",
"pm_score": 2,
"selected": false,
"text": "library(dplyr); library(gt); library(gtExtras)\nmtcars %>%\n tibble::rownames_to_column(\"Car Name\") %>%\n select(1, disp, cyl, qsec, mpg) %>%\n slice(1:7) %>%\n gt() %>%\n gt_plt_bar(column = mpg, color = \"gray80\", scale_type = \"number\", \n text_color = \"gray30\")\n gt::ggplot_image library(tidyverse); library(gt)\nplot_mpg <- function(df) {\n ggplot(data = df, aes(mpg, \"a\")) +\n geom_col(orientation = \"y\", fill = NA, color = \"gray20\", size = 4) +\n geom_text(aes(label = mpg), hjust = 1.1, size = 60) +\n coord_fixed(ratio = 5, xlim = c(0, 30)) +\n theme_void()\n}\n\nmtcars %>%\n tibble::rownames_to_column(\"Car Name\") %>%\n nest(data = mpg) %>%\n mutate(plot = map(data, plot_mpg)) %>%\n select(1, disp, cyl, qsec, plot) %>%\n mutate(mpg = NA) %>% # placeholder column\n slice(1:7) -> a\n\ngt(a) %>%\n cols_width(mpg ~ px(80)) %>%\n tab_options(data_row.padding = px(2)) %>%\n text_transform(\n locations = cells_body(mpg),\n fn = function(x) { map(a$plot, ~ggplot_image(., height = px(20), aspect_ratio = 6)) }\n ) %>%\n cols_hide(plot)\n \n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74621353",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20639122/"
] |
74,621,354
|
<p>I have a client that wants to have a checkbox that says "Mark as Compete" and once marked it makes the div with content fade. They basically want a step by step list like a recipe where users can check the box when they are done with a step and have it fade out.</p>
<p>I have been able to do so but not in a friendly way that someone who doesn't know code would be comfortable with editing. I am looking for some help simplifying it.</p>
<p>Current 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>function ShowHideDivOne(chk_one) {
var one = document.getElementById("one");
one.style.opacity = chk_one.checked ? "0.5" : "1";
}
function ShowHideDivTwo(chk_two) {
var two = document.getElementById("two");
two.style.opacity = chk_two.checked ? "0.5" : "1";
}
function ShowHideDivThree(chk_three) {
var three = document.getElementById("three");
three.style.opacity = chk_three.checked ? "0.5" : "1";
}</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>div {font-wieght:bold;font-size:30px; margin-top:30px;}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="one">One</div>
<input type="checkbox" id="chk_one" onclick="ShowHideDivOne(this)"/>Mark as done
<div id="two">Two</div>
<input type="checkbox" id="chk_two" onclick="ShowHideDivTwo(this)"/>Mark as done
<div id="three">Three</div>
<input type="checkbox" id="chk_three" onclick="ShowHideDivThree(this)"/>Mark as done</code></pre>
</div>
</div>
</p>
<p>Right now if they wanted to add a "Four," I would have to have the <code>ShowHideDivFour(chk_four)</code> function preprogrammed and then they would have to go in and change all of the <code>ids</code> and <code>onclicks</code> in the <code>div</code> and the <code>checkbox</code>.</p>
<p>I am ok with showing them how to edit the <code>id</code> in the <code>div</code>. What I would prefer is to have a JavaScript code that works for an unlimited number of items in their list and they would only have to change the <code>div</code> <code>id</code>. I understand if they would also have to change the <code>checkbox</code> code but it would be preferable if they didn't.</p>
<p>Any help would be much appreciated.</p>
|
[
{
"answer_id": 74621375,
"author": "Andy Baxter",
"author_id": 10744082,
"author_profile": "https://Stackoverflow.com/users/10744082",
"pm_score": 2,
"selected": false,
"text": "patchwork library(tidyverse)\nlibrary(patchwork)\n\ndata <- mtcars %>% select(mpg, disp, cyl, qsec) %>% rownames_to_column(\"Car Name\") %>% slice(1:7)\n\ndata$order <- factor(as.integer(factor(data$`Car Name`)))\n\ndata_rs <- data |> \n select(order, disp, cyl, qsec, `Car Name`) |> \n pivot_longer(-order, names_to = \"var\", values_to = \"val\", values_transform = as.character)\n\np1 <- ggplot(data = data, aes(x = mpg, y = order)) + \n geom_bar(stat = \"identity\", fill = \"white\", color = \"black\", alpha = 0.3, linewidth = .75) +\n theme_classic() +\n theme(axis.text.y = element_blank(),\n axis.title.y = element_blank(),\n axis.title.x = element_blank(),\n strip.background = element_blank(),\n strip.text = element_text(face = \"bold\", size = 12, hjust = 0)) +\n scale_x_continuous(expand = expansion(mult = c(0, .1)), limits = c(0,30)) +\n scale_y_discrete(limits=rev) +\n facet_wrap(~\"No. of mpg\")\n\np2 <- ggplot(data_rs, (aes(x = 1, y = order, label = val))) +\n geom_text() +\n facet_wrap(~fct_inorder(var), nrow = 1) +\n scale_y_discrete(limits=rev) +\n theme(axis.title.y = element_blank(),\n axis.text.y = element_blank(),\n axis.ticks = element_blank(),\n axis.text.x = element_blank(),\n axis.title.x = element_blank(),\n panel.grid = element_blank(),\n strip.background = element_blank(),\n panel.background = element_blank(),\n strip.clip = \"off\",\n strip.text = element_text(face = \"bold\", size = 12)) +\n coord_cartesian(clip = \"off\")\n\np2 + p1 + plot_layout(widths = c(0.7, 0.3))\n theme"
},
{
"answer_id": 74621400,
"author": "Jon Spring",
"author_id": 6851825,
"author_profile": "https://Stackoverflow.com/users/6851825",
"pm_score": 2,
"selected": false,
"text": "library(dplyr); library(gt); library(gtExtras)\nmtcars %>%\n tibble::rownames_to_column(\"Car Name\") %>%\n select(1, disp, cyl, qsec, mpg) %>%\n slice(1:7) %>%\n gt() %>%\n gt_plt_bar(column = mpg, color = \"gray80\", scale_type = \"number\", \n text_color = \"gray30\")\n gt::ggplot_image library(tidyverse); library(gt)\nplot_mpg <- function(df) {\n ggplot(data = df, aes(mpg, \"a\")) +\n geom_col(orientation = \"y\", fill = NA, color = \"gray20\", size = 4) +\n geom_text(aes(label = mpg), hjust = 1.1, size = 60) +\n coord_fixed(ratio = 5, xlim = c(0, 30)) +\n theme_void()\n}\n\nmtcars %>%\n tibble::rownames_to_column(\"Car Name\") %>%\n nest(data = mpg) %>%\n mutate(plot = map(data, plot_mpg)) %>%\n select(1, disp, cyl, qsec, plot) %>%\n mutate(mpg = NA) %>% # placeholder column\n slice(1:7) -> a\n\ngt(a) %>%\n cols_width(mpg ~ px(80)) %>%\n tab_options(data_row.padding = px(2)) %>%\n text_transform(\n locations = cells_body(mpg),\n fn = function(x) { map(a$plot, ~ggplot_image(., height = px(20), aspect_ratio = 6)) }\n ) %>%\n cols_hide(plot)\n \n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74621354",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15652286/"
] |
74,621,357
|
<p>I'd like to have button in excel that insert a row and then merge the first three columns as well.</p>
<p>below is my code. It makes the row but it doesn not merge the columns. I just started VBA today so I assume it might be a syntax error.</p>
<p>Can someone assist pls?
Cheers</p>
<p>my vba code:</p>
<pre><code>Sub AddRow()
Dim rowNum As Integer
On Error Resume Next
rowNum = Application.InputBox(Prompt:="Enter Row Number where you want to add a row:", _
Title:="VCRM")
Rows(rowNum & ":" & rowNum).Insert Shift:=xlDown
Range("A(rowNum):A(rowNum + 1)").Merge False
End Sub
</code></pre>
|
[
{
"answer_id": 74621870,
"author": "Tim Williams",
"author_id": 478884,
"author_profile": "https://Stackoverflow.com/users/478884",
"pm_score": 0,
"selected": false,
"text": "Sub AddRow()\n Dim ws As Worksheet, rowNum As Long 'use Long instead of Integer\n On Error Resume Next 'ignore error if user doesn't enter a number\n rowNum = Application.InputBox(Prompt:=\"Enter Row Number where you want to add a row:\", _\n Title:=\"VCRM\")\n On Error GoTo 0 'stop ignoring errors\n If rowNum = 0 Then\n MsgBox \"A numeric value is required!\", vbExclamation\n Exit Sub\n End If\n \n Set ws = ActiveSheet\n ws.Rows(rowNum).Insert Shift:=xlDown\n ws.Cells(rowNum, \"A\").Resize(1, 3).Merge\nEnd Sub\n"
},
{
"answer_id": 74621994,
"author": "Dhruvin Vadgama",
"author_id": 20499874,
"author_profile": "https://Stackoverflow.com/users/20499874",
"pm_score": 1,
"selected": false,
"text": "Sub add_rows()\n row_number = Application.InputBox(Prompt:=\"Enter Row Number where you want to add a row:\", _\n Title:=\"VCRM\", Type:=1)\n ThisWorkbook.Sheets(\"Sheet1\").Rows(row_number).Insert\n Rng = \"A\" & row_number & \":\" & \"C\" & row_number\n ThisWorkbook.Sheets(\"Sheet1\").Range(Rng).Merge\n ThisWorkbook.Sheets(\"Sheet1\").Range(Rng).HorizontalAlignment = xlCenter\nEnd Sub\n\n\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74621357",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20639118/"
] |
74,621,360
|
<p>I want to create a new column <code>diff</code> aqualing the differenciation of a series in a nother column.</p>
<p>The following is my dataframe:</p>
<pre><code>df=pd.DataFrame({
'series_1' : [10.1, 15.3, 16, 12, 14.5, 11.8, 2.3, 7.7,5,10],
'series_2' : [9.6,10.4, 11.2, 3.3, 6, 4, 1.94, 15.44, 6.17, 8.16]
})
</code></pre>
<p>It has the following display:</p>
<pre><code>series_1 series_2
0 10.1 9.60
1 15.3 10.40
2 16.0 11.20
3 12.0 3.30
4 14.5 6.00
5 11.8 4.00
6 2.3 1.94
7 7.7 15.44
8 5.0 6.17
9 10.0 8.16
</code></pre>
<p><strong>Goal</strong></p>
<p>Is to get the following output:</p>
<pre><code>series_1 series_2 diff_2
0 10.1 9.60 NaN
1 15.3 10.40 0.80
2 16.0 11.20 0.80
3 12.0 3.30 -7.90
4 14.5 6.00 2.70
5 11.8 4.00 -2.00
6 2.3 1.94 -2.06
7 7.7 15.44 13.50
8 5.0 6.17 -9.27
9 10.0 8.16 1.99
</code></pre>
<p><strong>My code</strong></p>
<p>To reach the desired output I used the following code and it worked:</p>
<pre><code>diff_2=[np.nan]
l=len(df)
for i in range(1, l):
diff_2.append(df['series_2'][i] - df['series_2'][i-1])
df['diff_2'] = diff_2
</code></pre>
<p><strong>Issue with my code</strong></p>
<p>I replicated here a simplified dataframe, the real one I am working on is extremly large and my code took almost 9 minute runtime!</p>
<p>I want an alternative allowing me to get the output in a fast way,</p>
<p>Any suggestion from your side will be highly appreciated, thanks.</p>
|
[
{
"answer_id": 74621373,
"author": "Naveed",
"author_id": 3494754,
"author_profile": "https://Stackoverflow.com/users/3494754",
"pm_score": 3,
"selected": true,
"text": "\n# create a new col by taking difference b/w consecutive rows of DF using diff\ndf['diff_2']=df['series_2'].diff()\ndf\n series_1 series_2 diff_2\n0 10.1 9.60 NaN\n1 15.3 10.40 0.80\n2 16.0 11.20 0.80\n3 12.0 3.30 -7.90\n4 14.5 6.00 2.70\n5 11.8 4.00 -2.00\n6 2.3 1.94 -2.06\n7 7.7 15.44 13.50\n8 5.0 6.17 -9.27\n9 10.0 8.16 1.99\n"
},
{
"answer_id": 74621495,
"author": "alphamu",
"author_id": 10215873,
"author_profile": "https://Stackoverflow.com/users/10215873",
"pm_score": 1,
"selected": false,
"text": "df[\"diff_2\"] = df[\"series_2\"].sub(df[\"series_2\"].shift(1))\n series_1 series_2 diff_2\n0 10.1 9.60 NaN\n1 15.3 10.40 0.80\n2 16.0 11.20 0.80\n3 12.0 3.30 -7.90\n4 14.5 6.00 2.70\n5 11.8 4.00 -2.00\n6 2.3 1.94 -2.06\n7 7.7 15.44 13.50\n8 5.0 6.17 -9.27\n9 10.0 8.16 1.99\n pandas"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74621360",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15852600/"
] |
74,621,387
|
<p>I'm looking to validate a chess <a href="https://en.wikipedia.org/wiki/Forsyth%E2%80%93Edwards_Notation" rel="nofollow noreferrer">FEN</a> string and I'm working on the Regex for it. I'm looking to implement only very simple validation. Here are the rules I'm looking to match with my regex:</p>
<ul>
<li>Exactly 7 "/" characters</li>
<li>Start and end of the string cannot be "/"</li>
<li>In between the slashes it must be either a number from 1-8 or the letters <code>PNBRQK</code> uppercase or lowercase</li>
</ul>
<p><strong>Example of a match</strong> <br />
rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR</p>
<p><strong>Examples of non-match</strong> <br />
rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR<code>/</code> <br />
<code>/</code>pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR<code>/</code> <br />
rnbqkbnr/pppppppp/8/8/8/<code>10</code>/PPPPPPPP/RNBQKBNR <br />
rnbqkbnr/<code>Z</code>/8/8/8/8/PPPPPPPP/RNBQKBNR</p>
<p>Currently, I have been able to implement exactly 7 "/" anywhere in the string with the following regex:</p>
<p><code>/^(?:[^\/]*\/){7}[^\/]*$/gm</code></p>
<p>I'm unsure how to implement the rest as RegEx is not my strong suit.</p>
|
[
{
"answer_id": 74621373,
"author": "Naveed",
"author_id": 3494754,
"author_profile": "https://Stackoverflow.com/users/3494754",
"pm_score": 3,
"selected": true,
"text": "\n# create a new col by taking difference b/w consecutive rows of DF using diff\ndf['diff_2']=df['series_2'].diff()\ndf\n series_1 series_2 diff_2\n0 10.1 9.60 NaN\n1 15.3 10.40 0.80\n2 16.0 11.20 0.80\n3 12.0 3.30 -7.90\n4 14.5 6.00 2.70\n5 11.8 4.00 -2.00\n6 2.3 1.94 -2.06\n7 7.7 15.44 13.50\n8 5.0 6.17 -9.27\n9 10.0 8.16 1.99\n"
},
{
"answer_id": 74621495,
"author": "alphamu",
"author_id": 10215873,
"author_profile": "https://Stackoverflow.com/users/10215873",
"pm_score": 1,
"selected": false,
"text": "df[\"diff_2\"] = df[\"series_2\"].sub(df[\"series_2\"].shift(1))\n series_1 series_2 diff_2\n0 10.1 9.60 NaN\n1 15.3 10.40 0.80\n2 16.0 11.20 0.80\n3 12.0 3.30 -7.90\n4 14.5 6.00 2.70\n5 11.8 4.00 -2.00\n6 2.3 1.94 -2.06\n7 7.7 15.44 13.50\n8 5.0 6.17 -9.27\n9 10.0 8.16 1.99\n pandas"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74621387",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14538687/"
] |
74,621,388
|
<p>I have a dataframe like so:</p>
<pre><code>ID <- c('A','A','A','A','A','A','A','A','A','A','A','A','A','A','A','A' )
BRR <- c(62,57,66,53,54,50,55,65,71,53,51,50,58,54,55,57)
val1 <- c(1,1,1,1,1,1,1,2,2,2,3,3,3,3,3,3)
val2 <- c(0,0,0,0,0,0,0,1,1,1,2,2,2,2,2,2)
df <- data.frame(ID, BRR, val1, val2)
</code></pre>
<p>Output:</p>
<pre><code> ID BRR val1 val2
1 A 62 1 0
2 A 57 1 0
3 A 66 1 0
4 A 53 1 0
5 A 54 1 0
6 A 50 1 0
7 A 55 1 0
8 A 65 2 1
9 A 71 2 1
10 A 53 2 1
11 A 51 3 2
12 A 50 3 2
13 A 58 3 2
14 A 54 3 2
15 A 55 3 2
16 A 57 3 2
</code></pre>
<p>I would like to get the max value of <code>BRR</code> by group (<code>ID</code>, <code>val1</code>, <code>val2</code>). In this case, <code>ID</code> has the same value. <code>Val2</code> will always be 1 less than <code>val1</code> so I am not sure that this column is even required.</p>
<p>So when <code>val2</code> is 0, <code>max_val_KP</code> will be 0. When <code>val2</code> is 1, I would like the max value from <code>val1</code> grouping, like so:</p>
<pre><code> ID BRR val1 val2 Max_val_KP
1 A 62 1 0 0
2 A 57 1 0 0
3 A 66 1 0 0
4 A 53 1 0 0
5 A 54 1 0 0
6 A 50 1 0 0
7 A 55 1 0 0
8 A 65 2 1 66
9 A 71 2 1 66
10 A 53 2 1 66
11 A 51 3 2 71
12 A 50 3 2 71
13 A 58 3 2 71
14 A 54 3 2 71
15 A 55 3 2 71
16 A 57 3 2 71
</code></pre>
<p>I tried:</p>
<pre><code>require(dplyr)
df <- df %>%
filter(va1 == val2) %>%
group_by(ID, val2) %>%
mutate(max_val_KP = max(BRR))
</code></pre>
<p>I also tried:</p>
<pre><code>require(dplyr)
df <- df %>%
group_by(ID, val1 == val2) %>%
mutate(max_val_KP = max(BRR))
</code></pre>
|
[
{
"answer_id": 74621502,
"author": "ncraig",
"author_id": 13110995,
"author_profile": "https://Stackoverflow.com/users/13110995",
"pm_score": 1,
"selected": false,
"text": "val2 val1 val1 == val2 mutate() dplyr library(dplyr)\n df |> group_by(val1, val2) |> \n mutate(Max_val_KP = max(BRR)) |> ungroup()\n"
},
{
"answer_id": 74621540,
"author": "Edjotace",
"author_id": 12909354,
"author_profile": "https://Stackoverflow.com/users/12909354",
"pm_score": 2,
"selected": false,
"text": "ID <- c('A','A','A','A','A','A','A','A','A','A','A','A','A','A','A','A' )\nBRR <- c(62,57,66,53,54,50,55,65,71,53,51,50,58,54,55,57)\nval1 <- c(1,1,1,1,1,1,1,2,2,2,3,3,3,3,3,3)\nval2 <- c(0,0,0,0,0,0,0,1,1,1,2,2,2,2,2,2)\n\ndf <- data.frame(ID, BRR, val1, val2)\n\n\nGroup <- df%>%group_by(val1)%>%summarise(Max_val_KP = max(BRR))\ncolnames(Group)[1] <- \"val2\"\n\nFinal <- left_join(df, Group)\nFinal$Max_val_KP[is.na(Final$Max_val_KP)] <- 0\n"
},
{
"answer_id": 74621561,
"author": "Ritchie Sacramento",
"author_id": 2835261,
"author_profile": "https://Stackoverflow.com/users/2835261",
"pm_score": 3,
"selected": true,
"text": "library(dplyr)\nlibrary(tidyr)\n\ndf %>%\n group_by(ID) %>%\n mutate(max_val_KP = replace_na(ave(BRR, val1, FUN = max)[match(val2, val1)], 0)) %>%\n ungroup()\n\n# A tibble: 16 × 5\n ID BRR val1 val2 max_val_KP\n <chr> <dbl> <dbl> <dbl> <dbl>\n 1 A 62 1 0 0\n 2 A 57 1 0 0\n 3 A 66 1 0 0\n 4 A 53 1 0 0\n 5 A 54 1 0 0\n 6 A 50 1 0 0\n 7 A 55 1 0 0\n 8 A 65 2 1 66\n 9 A 71 2 1 66\n10 A 53 2 1 66\n11 A 51 3 2 71\n12 A 50 3 2 71\n13 A 58 3 2 71\n14 A 54 3 2 71\n15 A 55 3 2 71\n16 A 57 3 2 71\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74621388",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13932170/"
] |
74,621,424
|
<p>I built a javascript gallery (no libraries) for presentation slides as images. prev/next buttons should cycle through the array regardless of its size.
Desired bevavior
Next button: 1,2,3,4,5,0,1,2...
Prev button: 5,4,3,2,1,0,5,4...</p>
<p>Issues</p>
<ol>
<li>change in count doesn't always change the image</li>
<li>"previous" button decrementing goes up first, and displays a -1</li>
<li>I have to call the "next" button function onload, otherwise two clicks are needed to start the images changing. I'd prefer to preload the gallery with image 0 via html or an inital function.</li>
</ol>
<p>Please take a look <a href="https://codepen.io/cnote/pen/gOKdpxr" rel="nofollow noreferrer">https://codepen.io/cnote/pen/gOKdpxr</a>
Thank you</p>
<p>I tried starting with images[0] loaded, but that requires 2 initial clicks for the buttons to work.
I've tried reworking the logic in the functions, but I'm bad at this.</p>
<pre><code>var currentImage = 0;
var images = [];
images[0] = "https://chrismichaelides.com/img/test0.jpg";
images[1] = "https://chrismichaelides.com/img/test1.jpg";
images[2] = "https://chrismichaelides.com/img/test2.jpg";
images[3] = "https://chrismichaelides.com/img/test3.jpg";
images[4] = "https://chrismichaelides.com/img/test4.jpg";
function nextImage() {
document.getElementById("deckImage").src = images[currentImage++];
document.getElementById("deckNumber").innerHTML = currentImage + " of " + images.length;
console.log("slide = " + currentImage);
//start over
if (currentImage >= images.length) {
currentImage = 0;
console.log("slide = " + currentImage);
}
}
function prevImage() {
document.getElementById("deckImage").src = images[currentImage--];
document.getElementById("deckNumber").innerHTML = currentImage + " of " + images.length;
console.log("slide = " + currentImage);
//cycle backwards to last from first
if (currentImage < 0) {
currentImage = images.length - 1;
console.log("slide = " + currentImage);
}
}
</code></pre>
|
[
{
"answer_id": 74621502,
"author": "ncraig",
"author_id": 13110995,
"author_profile": "https://Stackoverflow.com/users/13110995",
"pm_score": 1,
"selected": false,
"text": "val2 val1 val1 == val2 mutate() dplyr library(dplyr)\n df |> group_by(val1, val2) |> \n mutate(Max_val_KP = max(BRR)) |> ungroup()\n"
},
{
"answer_id": 74621540,
"author": "Edjotace",
"author_id": 12909354,
"author_profile": "https://Stackoverflow.com/users/12909354",
"pm_score": 2,
"selected": false,
"text": "ID <- c('A','A','A','A','A','A','A','A','A','A','A','A','A','A','A','A' )\nBRR <- c(62,57,66,53,54,50,55,65,71,53,51,50,58,54,55,57)\nval1 <- c(1,1,1,1,1,1,1,2,2,2,3,3,3,3,3,3)\nval2 <- c(0,0,0,0,0,0,0,1,1,1,2,2,2,2,2,2)\n\ndf <- data.frame(ID, BRR, val1, val2)\n\n\nGroup <- df%>%group_by(val1)%>%summarise(Max_val_KP = max(BRR))\ncolnames(Group)[1] <- \"val2\"\n\nFinal <- left_join(df, Group)\nFinal$Max_val_KP[is.na(Final$Max_val_KP)] <- 0\n"
},
{
"answer_id": 74621561,
"author": "Ritchie Sacramento",
"author_id": 2835261,
"author_profile": "https://Stackoverflow.com/users/2835261",
"pm_score": 3,
"selected": true,
"text": "library(dplyr)\nlibrary(tidyr)\n\ndf %>%\n group_by(ID) %>%\n mutate(max_val_KP = replace_na(ave(BRR, val1, FUN = max)[match(val2, val1)], 0)) %>%\n ungroup()\n\n# A tibble: 16 × 5\n ID BRR val1 val2 max_val_KP\n <chr> <dbl> <dbl> <dbl> <dbl>\n 1 A 62 1 0 0\n 2 A 57 1 0 0\n 3 A 66 1 0 0\n 4 A 53 1 0 0\n 5 A 54 1 0 0\n 6 A 50 1 0 0\n 7 A 55 1 0 0\n 8 A 65 2 1 66\n 9 A 71 2 1 66\n10 A 53 2 1 66\n11 A 51 3 2 71\n12 A 50 3 2 71\n13 A 58 3 2 71\n14 A 54 3 2 71\n15 A 55 3 2 71\n16 A 57 3 2 71\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74621424",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20638943/"
] |
74,621,464
|
<p>Imagine the model Event like this</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>name</th>
<th>email</th>
</tr>
</thead>
<tbody>
<tr>
<td>A</td>
<td>u1@example.org</td>
</tr>
<tr>
<td>B</td>
<td>u1@example.org</td>
</tr>
<tr>
<td>B</td>
<td>u1@example.org</td>
</tr>
<tr>
<td>C</td>
<td>u2@example.org</td>
</tr>
<tr>
<td>B</td>
<td>u3@example.org</td>
</tr>
<tr>
<td>B</td>
<td>u3@example.org</td>
</tr>
<tr>
<td>A</td>
<td>u4@example.org</td>
</tr>
<tr>
<td>B</td>
<td>u4@example.org</td>
</tr>
</tbody>
</table>
</div>
<p>I would like to find all emails that contain name <code>A</code> and <code>B</code>. In my example <code>["u1@example.org", "u4@example.org"]</code></p>
<p>Today I'm doing</p>
<pre class="lang-py prettyprint-override"><code>emails = [
e["email"]
for e in models.Event.objects.filter(name__in=["A", "B"])
.values("email")
.annotate(count=Count("id"))
.order_by()
.filter(count__gt=1)
]
</code></pre>
<p>It's not working because I'm also getting duplicates of emails containing only one name (like <code>u3@example.org</code>).</p>
|
[
{
"answer_id": 74621976,
"author": "Niko",
"author_id": 7100120,
"author_profile": "https://Stackoverflow.com/users/7100120",
"pm_score": 0,
"selected": false,
"text": "from django.db import connection\n\ndef get_random_events(request):\n cursor = connection.cursor()\n cursor.execute(\"SELECT DISTINCT email FROM event WHERE name = 'A' OR 'B'\")\n for row in cursor:\n print(row[0])\n\n return render(request, 'blank.html')\n RandomEvent.objects.values('email').distinct().filter(Q(name='B') | Q(name='A'))\n\n# Query Structure\nSELECT DISTINCT email FROM random_event WHERE (name = 'B' OR name = 'A')\n"
},
{
"answer_id": 74625104,
"author": "Guillaume Vincent",
"author_id": 866886,
"author_profile": "https://Stackoverflow.com/users/866886",
"pm_score": 1,
"selected": false,
"text": "\nevents = [\"A\", \"B\"]\nemails = [\n e[\"email\"]\n for e in models.Event.objects.filter(name__in=events)\n .values(\"email\")\n .annotate(count_name=Count(\"name\", distinct=True))\n .order_by()\n .filter(count_name=len(events))\n]\n email name"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74621464",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/866886/"
] |
74,621,465
|
<p>I have a process that create a quote divided in different test cases:</p>
<p><a href="https://i.stack.imgur.com/34l4W.png" rel="nofollow noreferrer">enter image description here</a></p>
<p>in the first IT I have the cy.visit which visit the login page of my page filling it with user and password
"the issue appears when I submit " I got a new URL generated and what I assumed is that it is not linking to the new url so the process stuck and cannot continue</p>
<p><a href="https://i.stack.imgur.com/o0cC8.png" rel="nofollow noreferrer">enter image description here</a></p>
<p>so after that I got the error that the page cannot proceed, it stuck and get back to the login page and dont proceed with the other page generated automatically:</p>
<p><a href="https://i.stack.imgur.com/RTDfa.png" rel="nofollow noreferrer">enter image description here</a></p>
<p>Well I am new in Cypress automation so I am not sure what is going on after I login on my page it get stuck in the process going back to the login page. So I am kind of sure it is not linking into the new URL that has the same domain so any person who has knowledge in Cypress can help me</p>
|
[
{
"answer_id": 74621676,
"author": "Graciella",
"author_id": 20639409,
"author_profile": "https://Stackoverflow.com/users/20639409",
"pm_score": 2,
"selected": false,
"text": "describe('before logged in', () => {\n it(\"Login into the system\", function () {\n cy.visit(Cypress.env(\"ur146b\"));\n //login\n login.getUser().type(this.data.user);\n login.getPass().type(this.data.pass);\n login.getLogin().click();\n cy.wait(1000);\n });\n})\n\ndescribe('when logged in', () => {\n // now make such the login is renewed for each test\n beforeEach(() => {\n cy.session('login', () => {\n cy.visit(Cypress.env(\"ur146b\"));\n //login\n login.getUser().type(this.data.user);\n login.getPass().type(this.data.pass);\n login.getLogin().click();\n })\n })\n\n it(\"Menu - full quote - get client\", function () {\n cy.visit('/homepage');\n menu.getPolicy().click();\n menu.getQuote().click();\n menu.getClient().click();\n cy.wait(1000);\n });\n\n it(\"fill client and address info\", function () { \n cy.visit('/homepage');\n ...\n });\n})\n cy.visit() cy.session() cy.visit()"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74621465",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20638973/"
] |
74,621,475
|
<p>Given a ring, together with a bijection to another set (n.b. set not type), it ought to be "trivial" to define the (unique) induced ring structure on the "other set" that makes the bijection an isomorphism. But my proof that tries to use this takes 101 lines (plus definitions and lemmas). Is there another approach using e.g. "lifting" that makes the whole thing fall out more easily?</p>
<p>Here's an example that could be filled in to do what I want:</p>
<pre><code>theory InducedRing
imports "HOL-Algebra.QuotRing"
begin
lemma
assumes "ring ℛ" "bij_betw φ (carrier ℛ) S"
obtains where "ring " and "carrier = S" and "φ ∈ ring_hom ℛ "
sorry
end
</code></pre>
<p>Feel free to rewrite this to an equivalent or stronger statement (e.g., reverse the direction of <code>\<phi></code> or even assume a pair of inverse bijections, make the hypotheses part of a locale definition, assert uniqueness of <code>\<S></code>, change the names according to your own taste....)</p>
<p>The goal is to make the proof feel short and natural. I'm hoping there's a theorem somewhere in <code>HOL-Algebra</code> or another library that will make this easy, but sledgehammer was not able to find it for me -- at least, not with this version of the statement.</p>
|
[
{
"answer_id": 74643437,
"author": "Charles Staats",
"author_id": 2318074,
"author_profile": "https://Stackoverflow.com/users/2318074",
"pm_score": 0,
"selected": false,
"text": "ring_iso_imp_img_ring theory InducedRing\n imports \"HOL-Algebra.QuotRing\"\nbegin\n\nlemma induced_ring:\n assumes ring_R: \"ring ℛ\" and phi_bij: \"bij_betw φ (carrier ℛ) S\"\n obtains where \"ring \" and \"carrier = S\" and \"φ ∈ ring_hom ℛ \"\nproof -\n interpret R_: ring ℛ by (rule ring_R)\n\n let ?R = \"carrier ℛ\"\n define ψ where \"ψ = the_inv_into ?R φ\"\n have [simp]: \"r∈?R ⟹ ψ (φ r) = r\" for r by (metis ψ_def phi_bij bij_betw_def the_inv_into_f_eq)\n define S_add where [simp]: \"S_add x' y' = φ (ψ x' ⊕⇘ℛ⇙ ψ y')\" for x' y'\n define S_zero where \"S_zero = φ ⇘ℛ⇙\"\n define S_mult where [simp]: \"S_mult x' y' = φ (ψ x' ⊗⇘ℛ⇙ ψ y')\" for x' y'\n define S_one where [simp]: \"S_one = φ ⇘ℛ⇙\"\n define where \" = ⦇carrier = S, mult = S_mult, one = S_one, zero = S_zero, add = S_add,\n … = m::'d⦈\"\n have φ_in_ring_hom: \"φ ∈ ring_hom ℛ \"\n proof (auto simp add: ring_hom_def _def)\n fix x assume x: \"x ∈ ?R\"\n show \"φ x ∈ S\" using bij_betwE phi_bij x by auto\n qed\n\n have carrier_S: \"carrier = S\" by (simp add: _def)\n\n have φ_in_ring_iso: \"φ ∈ ring_iso ℛ \"\n using φ_in_ring_hom ring_iso_def phi_bij carrier_S by blast\n have [simp]: \"⦇zero := φ ⇘ℛ⇙⦈ = \"\n apply (rule ring.equality, simp_all)\n using S_zero_def _def by auto\n interpret _: ring using R_.ring_iso_imp_img_ring[OF φ_in_ring_iso] by simp\n\n show ?thesis using that[OF _.is_ring carrier_S φ_in_ring_hom] .\nqed\nend\n theory InducedRing\n imports \"HOL-Algebra.Ring\"\nbegin\n\nlemma\n assumes ring_R: \"ring ℛ\" and phi_bij: \"bij_betw φ (carrier ℛ) S\"\n obtains where \"ring \" and \"carrier = S\" and \"φ ∈ ring_hom ℛ \"\nproof -\n interpret R_: ring ℛ by (rule ring_R)\n let ?R = \"carrier ℛ\"\n define ψ where \"ψ = the_inv_into ?R φ\"\n have [simp]: \"r∈?R ⟹ ψ (φ r) = r\" for r by (metis ψ_def phi_bij bij_betw_def the_inv_into_f_eq)\n have [simp]: \"s∈ S ⟹ φ (ψ s) = s\" for s by (metis ψ_def phi_bij f_the_inv_into_f_bij_betw)\n define S_add where [simp]: \"S_add x' y' = φ (ψ x' ⊕⇘ℛ⇙ ψ y')\" for x' y'\n then have S_add_closed: \"⟦x'∈S; y'∈S⟧ ⟹ S_add x' y' ∈ S\" for x' y'\n by (metis R_.add.m_closed ψ_def bij_betwE bij_betw_the_inv_into phi_bij)\n define S_zero where [simp]: \"S_zero = φ ⇘ℛ⇙\"\n then have S_zero_closed: \"S_zero ∈ S\" using bij_betwE phi_bij by blast\n define S_mult where [simp]: \"S_mult x' y' = φ (ψ x' ⊗⇘ℛ⇙ ψ y')\" for x' y'\n then have S_mult_closed: \"⟦x'∈S; y'∈S⟧ ⟹ S_mult x' y' ∈ S\" for x' y'\n by (metis R_.m_closed ψ_def bij_betwE bij_betw_the_inv_into phi_bij)\n define S_one where [simp]: \"S_one = φ ⇘ℛ⇙\"\n then have S_one_closed: \"S_one ∈ S\" using bij_betwE phi_bij by blast\n define where \" = ⦇carrier = S, mult = S_mult, one = S_one, zero = S_zero, add = S_add,\n … = m::'d⦈\"\n have φ_in_ring_hom: \"φ ∈ ring_hom ℛ \"\n proof (auto simp add: ring_hom_def _def)\n fix x assume x: \"x ∈ ?R\"\n show \"φ x ∈ S\" using bij_betwE phi_bij x by auto\n qed\n have carrier_S: \"carrier = S\" by (simp add: _def)\n interpret _: ring \n proof (unfold_locales, auto simp add: Units_def carrier_S)\n show \"⇘⇙ ∈ S\" using S_zero_closed _def by auto\n show \"⇘⇙ ∈ S\" using S_one_closed _def by auto\n\n fix x' assume x': \"x' ∈ S\"\n let ?x = \"ψ x'\"\n have x: \"?x ∈ ?R\" \"φ ?x = x'\"\n using x' apply (metis ψ_def bij_betw_apply bij_betw_the_inv_into phi_bij)\n using x' by auto\n show \"⇘⇙ ⊗⇘⇙ x' = x'\" \"x' ⊗⇘⇙ ⇘⇙ = x'\" \"x' ⊕⇘⇙ ⇘⇙ = x'\" \"⇘⇙ ⊕⇘⇙ x' = x'\"\n using φ_in_ring_hom by (simp_all add: _def x)\n show \"∃mx'∈S. mx' ⊕⇘⇙ x' = ⇘⇙ ∧ x' ⊕⇘⇙ mx' = ⇘⇙\"\n proof (rule, rule)\n let ?mx' = \"φ (⊖⇘ℛ⇙ ?x)\"\n show \"?mx' ∈ S\" using bij_betwE phi_bij x(1) by blast\n show \"?mx' ⊕⇘⇙ x' = ⇘⇙\" \"x' ⊕⇘⇙ ?mx' = ⇘⇙\"\n by (simp_all add: _def R_.l_neg R_.r_neg x(1))\n qed\n\n fix y' assume y': \"y' ∈ S\"\n let ?y = \"ψ y'\"\n have y: \"?y ∈ ?R\" \"φ ?y = y'\"\n using y' apply (metis ψ_def bij_betw_apply bij_betw_the_inv_into phi_bij)\n using y' by auto\n show \"x' ⊗⇘⇙ y' ∈ S\" using _def S_mult_closed by (simp add: x' y')\n show \"x' ⊕⇘⇙ y' ∈ S\" using _def S_add_closed by (simp add: x' y')\n show \"x' ⊕⇘⇙ y' = y' ⊕⇘⇙ x'\"\n using φ_in_ring_hom by (simp add: R_.add.m_comm _def x(1) y(1))\n\n fix z' assume z': \"z' ∈ S\"\n let ?z = \"ψ z'\"\n have z: \"?z ∈ ?R\" \"φ ?z = z'\"\n using z' apply (metis ψ_def bij_betw_apply bij_betw_the_inv_into phi_bij)\n using z' by auto\n show \"(x' ⊕⇘⇙ y') ⊕⇘⇙ z' = x' ⊕⇘⇙ (y' ⊕⇘⇙ z')\"\n using φ_in_ring_hom _def x(1) y(1) z(1) R_.add.m_assoc by simp\n show \"x' ⊗⇘⇙ y' ⊗⇘⇙ z' = x' ⊗⇘⇙ (y' ⊗⇘⇙ z')\"\n using φ_in_ring_hom _def x(1) y(1) z(1) R_.m_assoc by simp\n show \"(x' ⊕⇘⇙ y') ⊗⇘⇙ z' = x' ⊗⇘⇙ z' ⊕⇘⇙ y' ⊗⇘⇙ z'\"\n using ring_hom_add[OF φ_in_ring_hom] ring_hom_mult[OF φ_in_ring_hom] x y z\n R_.l_distr R_.add.m_closed R_.m_closed\n by (smt (verit, ccfv_threshold))\n show \"z' ⊗⇘⇙ (x' ⊕⇘⇙ y') = z' ⊗⇘⇙ x' ⊕⇘⇙ z' ⊗⇘⇙ y'\"\n using ring_hom_add[OF φ_in_ring_hom] ring_hom_mult[OF φ_in_ring_hom] x y z\n R_.r_distr R_.add.m_closed R_.m_closed\n by (smt (verit, ccfv_threshold))\n qed\n\n show ?thesis using that[of , OF _.ring_axioms carrier_S φ_in_ring_hom] .\nqed\nend\n"
},
{
"answer_id": 74654521,
"author": "Simon Roßkopf",
"author_id": 20665512,
"author_profile": "https://Stackoverflow.com/users/20665512",
"pm_score": 2,
"selected": true,
"text": "auto auto auto lemma\n assumes \"ring ℛ\" \"bij_betw φ (carrier ℛ) S\"\n obtains where \"ring \" and \"carrier = S\" and \"φ ∈ ring_hom ℛ \"\nproof-\n interpret ℛ: ring ℛ \n using assms(1) .\n\n (* Define the ring *)\n let ?Z = \"φ (zero ℛ)\"\n let ?O = \"φ (one ℛ)\"\n let ?mult = \"λx y . φ (inv_into (carrier ℛ) φ x ⊗⇘ℛ⇙ inv_into (carrier ℛ) φ y)\" \n let ?add = \"λx y . φ (inv_into (carrier ℛ) φ x ⊕⇘ℛ⇙ inv_into (carrier ℛ) φ y)\" \n let ? = \"⦇ carrier = S, mult = ?mult , one = ?O, zero = ?Z, add = ?add, \n … = (undefined :: 'd) ⦈ :: ('c, 'd) ring_scheme\"\n \n show thesis\n proof(rule that[of ?])\n (* The only part where auto needed some help *)\n have helper: \"∃y∈S. φ (inv_into (carrier ℛ) φ x ⊕⇘ℛ⇙ inv_into (carrier ℛ) φ y) = φ ⇘ℛ⇙\" \n if \"x ∈ S\" for x \n using assms that by (intro bexI[where x=\"φ (⊖⇘ℛ⇙ (inv_into (carrier ℛ) φ x))\"])\n (auto intro: bij_betw_apply \n simp add: ring.ring_simprules bij_betw_imp_inj_on bij_betw_imp_surj_on inv_into_into)\n \n show \"ring ?\"\n using assms by unfold_locales \n (auto intro: bij_betw_apply simp add: ring.ring_simprules bij_betw_inv_into_right \n bij_betw_imp_inj_on bij_betw_imp_surj_on inv_into_into Units_def helper)\n next\n show \"carrier ? = S\"\n by simp\n next\n from assms(2) show \"φ ∈ ring_hom ℛ ?\"\n by (intro ring_hom_memI) (auto intro: bij_betw_apply simp add: bij_betw_inv_into_left)\n qed\nqed\n obtains S carrier ℛ abbreviation \"bij_ring ℛ φ ≡ ⦇carrier = φ ` carrier ℛ, \n mult = λx y . φ (inv_into (carrier ℛ) φ x ⊗⇘ℛ⇙ inv_into (carrier ℛ) φ y), one = φ (one ℛ), \n zero = φ (zero ℛ), add = λx y . φ (inv_into (carrier ℛ) φ x ⊕⇘ℛ⇙ inv_into (carrier ℛ) φ y), \n … = (undefined :: 'd) ⦈ :: ('c, 'd) ring_scheme\"\n\nlemma\n assumes \"ring ℛ\" \"bij_betw φ (carrier ℛ) (φ ` (carrier ℛ))\"\n shows \"ring (bij_ring ℛ φ)\" and \"φ ∈ ring_hom ℛ (bij_ring ℛ φ)\"\nproof-\n interpret ℛ: ring ℛ \n using assms(1) . \n (* Sadly it still needs help *)\n from assms have helper: \"∃x∈carrier ℛ. φ (y ⊕⇘ℛ⇙ x) = φ ⇘ℛ⇙\" \n if \"y ∈ carrier ℛ\" for y \n using that by (metis ℛ.add.r_inv_ex)\n\n from assms show \"ring (bij_ring ℛ φ)\"\n by unfold_locales (auto simp add: bij_betw_inv_into_left\n ℛ.add.m_assoc bij_betw_imp_inj_on ring.ring_simprules Units_def helper)\n from assms(2) show \"φ ∈ ring_hom ℛ (bij_ring ℛ φ)\"\n by (intro ring_hom_memI) (auto intro: bij_betw_apply simp add: bij_betw_inv_into_left)\nqed\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74621475",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2318074/"
] |
74,621,497
|
<p>I am new to PowerBi.
I would like to get a table on PowerIb, from this <a href="https://hptrial.pythonanywhere.com/rest_api_data" rel="nofollow noreferrer">JSON API</a></p>
<p>Sample of data:</p>
<pre><code>{"data": [{"user_id": 54710, "hp_user_id": 5806514, "username": "Jay_J1", "user_profile_url": "https://h30434.www3.hp.com/t5/user/viewprofilepage/user-id/5806514", "user_blocked": 0, "hp_post_id": 8550808, "post_datetime": "2022-11-28 10:54:00", "post_url": "https://h30434.www3.hp.com/t5/Notebook-Hardware-and-Upgrade-Questions/HP-Envy-360-broken-left-hinge-and-screen-separating/m-p/8550808?search-action-id=587041408161&search-result-uid=8550808", "post_summary": "Like many others have experienced, the hinge on my HP Envy 360 broke last night. All I did was simply open it, but I heard a crack, and now the metal part is stuck at an angle to where I can no l...", "me_too": "", "post_tags": "\"[\"HP ENVY x360 Laptop - 15m-ee0023dx\",\"Microsoft Windows 11\"]\""}, {"user_id": 52629, "hp_user_id": 5800465, "username": "BrookeDorbit", "user_profile_url": "https://h30434.www3.hp.com/t5/user/viewprofilepage/user-id/5800465", "user_blocked": 0, "hp_post_id": 8550124, "post_datetime": "2022-11-27 15:39:00", "post_url": "https://h30434.www3.hp.com/t5/Notebook-Hardware-and-Upgrade-Questions/Hinge-Issue/m-p/8550124?search-action-id=586827468132&search-result-uid=8550124", "post_summary": "I\u2019ve seen many others mention the same issue with their HP envy laptop but I am just as upset. I purchased my laptop in the summer of 2020 and only 2 years later, the hinge is broken. I have never o...", "me_too": "\"[{\"username\":\"Jay_J1\",\"hp_user_id\":\"5806514\",\"post_datetime\":\"2022-11-28\"}]\"", "post_tags": "\"[\"HP ENVY Laptop - 13t-ba000 CTO\"]\""},
]}
</code></pre>
<p>I can change the JSON Response if needed.</p>
<p>So far, I followed these steps:</p>
<ul>
<li>Click on "New Source" and select "JSON" or "Web" (same issue):</li>
</ul>
<p><a href="https://i.stack.imgur.com/4MPqj.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/4MPqj.png" alt="enter image description here" /></a></p>
<ul>
<li>Then I get a select between Html and Text which is fair:</li>
</ul>
<p><a href="https://i.stack.imgur.com/xHBLW.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/xHBLW.png" alt="enter image description here" /></a></p>
<p>And if I select Text, I get the text of the JSON, which is fair...</p>
<p>My question is how would I get the table associated with this JSON response.
As well is it possible to skip the GUI and import the Json text in Python or JS, and deliver it to the GUI?</p>
<p>End result, would be a table with the items in the "data" key.</p>
<p>Thanks a lot, and best!</p>
|
[
{
"answer_id": 74622318,
"author": "Je Je",
"author_id": 1536343,
"author_profile": "https://Stackoverflow.com/users/1536343",
"pm_score": -1,
"selected": false,
"text": "= let\n Source = Json.Document(Web.Contents(\"https://hptrial.pythonanywhere.com/rest_api_data\")),\n data = Source[data],\n #\"Converted to Table\" = Table.FromList(data, Splitter.SplitByNothing(), null, null, ExtraValues.Error),\n #\"Expanded Column1\" = Table.ExpandRecordColumn(#\"Converted to Table\", \"Column1\", {\"user_id\", \"hp_user_id\", \"username\", \"user_profile_url\", \"user_blocked\", \"hp_post_id\", \"post_datetime\", \"post_url\", \"post_summary\", \"me_too\", \"post_tags\"}, {\"user_id\", \"hp_user_id\", \"username\", \"user_profile_url\", \"user_blocked\", \"hp_post_id\", \"post_datetime\", \"post_url\", \"post_summary\", \"me_too\", \"post_tags\"})\n\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74621497",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1536343/"
] |
74,621,515
|
<p>I'm a django developer and I'm new to htmx.
I was wondering if there was an easy way to implement the onselect event in htmx.</p>
<p>I have the following dropdown:</p>
<p><a href="https://i.stack.imgur.com/vMPJo.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/vMPJo.png" alt="Change user role on select" /></a></p>
<p>When the role is selected "onselect", I want to send an http request to the back-end using htmx(not jquery or javascript)</p>
<p>How can I do this?</p>
<p>Any help is much appreciated!
Thanks!</p>
<p>Tried searching "onselect" on <a href="https://htmx.org/docs" rel="nofollow noreferrer">htmx docs</a> but there's no built in implementation.
Tried searching "onselect htmx" stack overflow but I couldn't find a helpful post.</p>
|
[
{
"answer_id": 74622318,
"author": "Je Je",
"author_id": 1536343,
"author_profile": "https://Stackoverflow.com/users/1536343",
"pm_score": -1,
"selected": false,
"text": "= let\n Source = Json.Document(Web.Contents(\"https://hptrial.pythonanywhere.com/rest_api_data\")),\n data = Source[data],\n #\"Converted to Table\" = Table.FromList(data, Splitter.SplitByNothing(), null, null, ExtraValues.Error),\n #\"Expanded Column1\" = Table.ExpandRecordColumn(#\"Converted to Table\", \"Column1\", {\"user_id\", \"hp_user_id\", \"username\", \"user_profile_url\", \"user_blocked\", \"hp_post_id\", \"post_datetime\", \"post_url\", \"post_summary\", \"me_too\", \"post_tags\"}, {\"user_id\", \"hp_user_id\", \"username\", \"user_profile_url\", \"user_blocked\", \"hp_post_id\", \"post_datetime\", \"post_url\", \"post_summary\", \"me_too\", \"post_tags\"})\n\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74621515",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14580830/"
] |
74,621,520
|
<p>I have a list containing tuples and I would like to remove tuples that contain words in the first position of the tuple based on words from a second list.</p>
<pre><code>list_of_tuples = [
("apple",2),
("banana",54),
("flower", 5),
("apple",4),
("fruit", 3)
]
list_of_words = [
"apple",
"banana"
]
</code></pre>
<p>The final result should look like this:</p>
<pre><code> [("flower", 5), ("fruit", 3)]
</code></pre>
|
[
{
"answer_id": 74621584,
"author": "Nimrod Shanny",
"author_id": 20631164,
"author_profile": "https://Stackoverflow.com/users/20631164",
"pm_score": 2,
"selected": true,
"text": "list_of_tuples = [\n (\"apple\", 2),\n (\"banana\", 54),\n (\"flower\", 5),\n (\"apple\", 4),\n (\"fruit\", 3)\n]\n\nlist_of_words = [\n \"apple\",\n \"banana\"\n]\n\nfinal_list_of_tuples = [tup for tup in list_of_tuples if tup[0] not in list_of_words]\n\nprint(final_list_of_tuples)\n"
},
{
"answer_id": 74621659,
"author": "rhurwitz",
"author_id": 8635547,
"author_profile": "https://Stackoverflow.com/users/8635547",
"pm_score": 0,
"selected": false,
"text": "list_of_tuples = [\n (\"apple\",2),\n (\"banana\",54), \n (\"flower\", 5), \n (\"apple\",4), \n (\"fruit\", 3)\n]\n\nlist_of_words = [\"apple\", \"banana\"]\n\n# demonstrates tuple unpacking in Python\nword, quantity = list_of_tuples[0]\nprint(word, quantity)\n\n# demonstrates how to test against a collection\nprint(word in list_of_words)\n\n# demonstrates how to iterate over a list of tuples and unpack\nfor word, quantity in list_of_tuples:\n print(f\"word: {fruit}, quantity: {quantity}\")\n\n# demonstrates how to create a new list from an existing list\nnew_list_of_tuples = []\nfor word, quantity in list_of_tuples:\n if word != \"flower\":\n new_list_of_tuples.append((word, quantity))\nprint(new_list_of_tuples)\n apple 2\nTrue\nword: apple, quantity: 2\nword: apple, quantity: 54\nword: apple, quantity: 5\nword: apple, quantity: 4\nword: apple, quantity: 3\n[('apple', 2), ('banana', 54), ('apple', 4), ('fruit', 3)]\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74621520",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14916069/"
] |
74,621,552
|
<p>I can't understand the behaviour of <code>pandas.rolling.apply</code> with <code>np.prod</code> and NaNs. E.g.</p>
<pre><code>import pandas as pd
import numpy as np
df = pd.DataFrame({'B': [1, 1, 2, np.nan, 4], 'C': [1, 2, 3, 4, 5]}, index=pd.date_range('2013-01-01', '2013-01-05'))
</code></pre>
<p>Gives this dataframe:</p>
<pre><code> B C
2013-01-01 1.0 1
2013-01-02 1.0 2
2013-01-03 2.0 3
2013-01-04 NaN 4
2013-01-05 4.0 5
</code></pre>
<p>If I <code>apply</code> the numpy <code>np.prod</code> function to a 3 day rolling window with <code>raw=False</code> and <code>min_periods=1</code> it works as expected, ignoring the NaNs.</p>
<pre><code>df.rolling('3D', min_periods=1).apply(np.prod, raw=False)
B C
2013-01-01 1.0 1.0
2013-01-02 1.0 2.0
2013-01-03 2.0 6.0
2013-01-04 2.0 24.0
2013-01-05 8.0 60.0
</code></pre>
<p>However with <code>raw=True</code> I get NaNs in column B:</p>
<pre><code>df.rolling('3D', min_periods=1).apply(np.prod, raw=True)
B C
2013-01-01 1.0 1.0
2013-01-02 1.0 2.0
2013-01-03 2.0 6.0
2013-01-04 NaN 24.0
2013-01-05 NaN 60.0
</code></pre>
<p>I'd like to use <code>raw=True</code> for speed, but I don't understand this behavior? Can someone explain what's going on?</p>
|
[
{
"answer_id": 74623958,
"author": "padu",
"author_id": 16591526,
"author_profile": "https://Stackoverflow.com/users/16591526",
"pm_score": 1,
"selected": false,
"text": "import pandas as pd\nimport numpy as np\n\n\ndef foo(x):\n return np.prod(x, where=~np.isnan(x))\n\n\nif __name__ == '__main__':\n df = pd.DataFrame({'B': [1, 1, 2, np.nan, 4], 'C': [1, 2, 3, 4, 5]},\n index=pd.date_range('2013-01-01', '2013-01-05'))\n res = df.rolling('3D', min_periods=1).apply(foo, raw=True)\n \n print(res)\n\n B C\n2013-01-01 1.0 1.0\n2013-01-02 1.0 2.0\n2013-01-03 2.0 6.0\n2013-01-04 2.0 24.0\n2013-01-05 8.0 60.0\n\n"
},
{
"answer_id": 74627390,
"author": "Justin",
"author_id": 1588847,
"author_profile": "https://Stackoverflow.com/users/1588847",
"pm_score": 0,
"selected": false,
"text": "apply raw=False np.prod raw=True np.prod np.prod(np.array([1, 2, np.nan, 3])) nan np.prod(pd.Series([1, 2, np.nan, 3])) 6.0 where np.prod"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74621552",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1588847/"
] |
74,621,578
|
<h2>This is a jshint warning question.How can I solve this problem?</h2>
<pre><code>var comment_btn=document.querySelector('.comment_button');
var comment_ul=document.querySelector('.comment_ul');
var comment_text=document.querySelector('#comment');
comment_btn.onclick = function(){
var comment_li = document.createElement('li');
comment_li.className = 'comment_li';
if(comment_text.value != '') {
comment_li.innerHTML = comment_text.value + "<a class='comment_a' href='javascript:;'>Delete</a>";
comment_ul.insertBefore(comment_li,comment_ul.children[0]);
var del = document.querySelectorAll('.comment_a');
for (var i = 0; i < del.length; i++) {
del[i].onclick = function() {
comment_ul.removeChild(this.parentNode);
};
}
}
else {
alert('Please input!');
}
};
</code></pre>
<p><em>Warning:</em><br />
<em>Functions declared within loops referencing an outer scoped variable may lead to confusing semantics. (comment_ul) (W083)jshint(W083)</em></p>
<p>I really can't think of a solution,please help me.</p>
|
[
{
"answer_id": 74623958,
"author": "padu",
"author_id": 16591526,
"author_profile": "https://Stackoverflow.com/users/16591526",
"pm_score": 1,
"selected": false,
"text": "import pandas as pd\nimport numpy as np\n\n\ndef foo(x):\n return np.prod(x, where=~np.isnan(x))\n\n\nif __name__ == '__main__':\n df = pd.DataFrame({'B': [1, 1, 2, np.nan, 4], 'C': [1, 2, 3, 4, 5]},\n index=pd.date_range('2013-01-01', '2013-01-05'))\n res = df.rolling('3D', min_periods=1).apply(foo, raw=True)\n \n print(res)\n\n B C\n2013-01-01 1.0 1.0\n2013-01-02 1.0 2.0\n2013-01-03 2.0 6.0\n2013-01-04 2.0 24.0\n2013-01-05 8.0 60.0\n\n"
},
{
"answer_id": 74627390,
"author": "Justin",
"author_id": 1588847,
"author_profile": "https://Stackoverflow.com/users/1588847",
"pm_score": 0,
"selected": false,
"text": "apply raw=False np.prod raw=True np.prod np.prod(np.array([1, 2, np.nan, 3])) nan np.prod(pd.Series([1, 2, np.nan, 3])) 6.0 where np.prod"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74621578",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20639300/"
] |
74,621,586
|
<p>I have an xml file with multiple elements with the same key elements with the same name. I'm trying to concatonate the sub elements but can only get the first occurrence.</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<FOLDER JOBNAME="some Job" MAXWAIT="5">
<OTHER>
<ELEMENTS>
</ELEMENTS>
</OTHER>
</FOLDER>
<FOLDER JOBNAME="some Other Job" MAXWAIT="15">
<OTHER>
<ELEMENTS>
</ELEMENTS>
</OTHER>
</FOLDER>
</code></pre>
<p>Is there a way to use xmllint or some other tool to get output like:</p>
<pre><code>some Job 5
some Other Job 15
etc...
</code></pre>
<p>when I try with <code>xmllint --xpath</code>, I get the following:</p>
<pre><code>me@myComp tmp $ xmllint --xpath 'concat(//@JOBNAME," ",//@MAXWAIT)' jobs.xml
ADDRESS_VERIFICATION 5
me@myComp tmp $ xmllint --xpath 'concat(//JOBNAME[*]," ",//MAXWAIT[*])' jobs.xml
me@myComp tmp $
</code></pre>
<p>Is there a way to concatenate multiple parameters with <code>xmllint</code> or any other tool on the command line?</p>
<p>UPDATE - Yeah, it's a proper XML - Also, just notices the repeated lines and removed them.</p>
|
[
{
"answer_id": 74623958,
"author": "padu",
"author_id": 16591526,
"author_profile": "https://Stackoverflow.com/users/16591526",
"pm_score": 1,
"selected": false,
"text": "import pandas as pd\nimport numpy as np\n\n\ndef foo(x):\n return np.prod(x, where=~np.isnan(x))\n\n\nif __name__ == '__main__':\n df = pd.DataFrame({'B': [1, 1, 2, np.nan, 4], 'C': [1, 2, 3, 4, 5]},\n index=pd.date_range('2013-01-01', '2013-01-05'))\n res = df.rolling('3D', min_periods=1).apply(foo, raw=True)\n \n print(res)\n\n B C\n2013-01-01 1.0 1.0\n2013-01-02 1.0 2.0\n2013-01-03 2.0 6.0\n2013-01-04 2.0 24.0\n2013-01-05 8.0 60.0\n\n"
},
{
"answer_id": 74627390,
"author": "Justin",
"author_id": 1588847,
"author_profile": "https://Stackoverflow.com/users/1588847",
"pm_score": 0,
"selected": false,
"text": "apply raw=False np.prod raw=True np.prod np.prod(np.array([1, 2, np.nan, 3])) nan np.prod(pd.Series([1, 2, np.nan, 3])) 6.0 where np.prod"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74621586",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7583449/"
] |
74,621,598
|
<p>I am trying to redirect the user after entering the correct credentials, but my frontend is putting out this Error "Uncaught (in promise) TypeError: navigator is undefined". I couldn't really find any solution so I was hoping to get some help here.</p>
<p>This is is the part of my code which throws the error: It only happens in case of correct input (meaning the input data was found inside of the database), so when <code>redirect</code> is called.</p>
<pre><code>import { useParams, useNavigate, Route } from "react-router";
const Login = () => {
const redirect = useNavigate();
async function handleLogin() {
try {
const success = await Api.login(username, password);
redirect('/home'); // Console says this line is where the error comes form
} catch (error) {
console.log(error);
}
}
const [username, setUserName] = useState('');
const [password, setPassword] = useState('');
return (
<div className="cover">
<div className="headline">
<h1>Login</h1>
</div>
<form>
<InputField placeholder={"Benutzername"} onChange={setUserName} />
<InputField placeholder={"Passwort"} isPassword onChange={setPassword} />
</form>
<Button active
onClick={handleLogin}>
Login
</Button>
<p className="text">
Noch nicht registriert? <a href="#">Hier Account erstellen.</a>{" "}
</p>
<div className={popupStyle}>
<h3>Login Failed</h3>
<p>Username or password incorrect</p>
</div>
</div>
);
};
export default Login;
</code></pre>
<p>This is my routing code:</p>
<p><strong>Routing.js</strong></p>
<pre><code>import { Routes, Route, Router } from "react-router-dom";
import Login from "../components/Login";
import Home from "../components/Home";
import NoNavRouting from "./NoNavRouting";
import NavRouting from "./NavRouting";
export default function Routing() {
return (
<Router location={"/"}>
<Routes>
<Route element={<NoNavRouting />}>
<Route path="/" element={<Login />} />
</Route>
<Route element={<NavRouting />}>
<Route path="home">
<Route index element={<Home />} />
<Route path=":userId" element={<Home />} />
</Route>
</Route>
</Routes>
</Router>
);
}
</code></pre>
<p><strong>NoNavRouting</strong></p>
<pre><code>import React from "react";
import { Outlet } from "react-router";
export default function NoNavRouting() {
return <Outlet />;
}
</code></pre>
<p><strong>NavRouting</strong></p>
<pre><code>import React from "react";
import NavBar from "../components/Navbar";
import { Outlet } from "react-router";
export default function NavRouting() {
return (
<>
<NavBar />
<Outlet />
</>
);
}
</code></pre>
<p>The complete error message looks like this:</p>
<pre><code>TypeError: navigator is undefined
navigate hooks.tsx:211
handleLogin Login.jsx:39
React 23
js index.js:5
factory react refresh:6
Webpack 3
</code></pre>
<p>I tried to put my redirect constant at different places, but that did not work so far, as I am still new to React and try to find my way around it.</p>
|
[
{
"answer_id": 74621673,
"author": "dbonev",
"author_id": 4200334,
"author_profile": "https://Stackoverflow.com/users/4200334",
"pm_score": 0,
"selected": false,
"text": " const redirect = useNavigate();\n async function handleLogin() {\n try {\n const success = await Api.login(username, password);\n redirect('/home');\n } catch (error) {\n console.log(error);\n }\n }\n"
},
{
"answer_id": 74621868,
"author": "Drew Reese",
"author_id": 8690857,
"author_profile": "https://Stackoverflow.com/users/8690857",
"pm_score": 2,
"selected": true,
"text": "Router declare function Router(\n props: RouterProps\n): React.ReactElement | null;\n\ninterface RouterProps {\n basename?: string;\n children?: React.ReactNode;\n location: Partial<Location> | string; // <-- required\n navigationType?: NavigationType;\n navigator: Navigator; // <-- required\n static?: boolean;\n}\n import { Routes, Route, Router } from \"react-router-dom\"; // <-- Router\nimport Login from \"../components/Login\";\nimport Home from \"../components/Home\";\nimport NoNavRouting from \"./NoNavRouting\";\nimport NavRouting from \"./NavRouting\";\n\nexport default function Routing() {\n return (\n <Router location={\"/\"}> // <-- Missing `navigator` prop!!\n <Routes>\n <Route element={<NoNavRouting />}>\n <Route path=\"/\" element={<Login />} />\n </Route>\n <Route element={<NavRouting />}>\n <Route path=\"home\">\n <Route index element={<Home />} />\n <Route path=\":userId\" element={<Home />} />\n </Route>\n </Route>\n </Routes>\n </Router>\n );\n}\n BrowserRouter MemoryRouter import { Routes, Route, BrowserRouter } from \"react-router-dom\";\nimport Login from \"../components/Login\";\nimport Home from \"../components/Home\";\nimport NoNavRouting from \"./NoNavRouting\";\nimport NavRouting from \"./NavRouting\";\n\nexport default function Routing() {\n return (\n <BrowserRouter>\n <Routes>\n <Route element={<NoNavRouting />}>\n <Route path=\"/\" element={<Login />} />\n </Route>\n <Route element={<NavRouting />}>\n <Route path=\"home\">\n <Route index element={<Home />} />\n <Route path=\":userId\" element={<Home />} />\n </Route>\n </Route>\n </Routes>\n </BrowserRouter>\n );\n}\n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74621598",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19478799/"
] |
74,621,618
|
<p>I have a stored procedure <code>GetVideo</code> in a SQL Server 2019 database that does this:</p>
<pre><code>select
[video.id] = vid,
[video.title] = title
from
videos
for json path, root('x');
</code></pre>
<p>Which returns this JSON:</p>
<pre><code>{
"x":
[
{
"video":
{
"id": 11,
"title": "Forest Gump"
}
},
{
"video":
{
"id": 22,
"title": "Merry Christmas"
}
}
]
}
</code></pre>
<p>However using C# and EF Core 3.1 generates an error:</p>
<blockquote>
<p>Sequence has no elements</p>
</blockquote>
<pre><code>public class Sp
{
public List<video> XV {get; set;}
public class video
{
public int id {get; set;}
public string title {get; set;}
}
}
public async Task<ActionResult<IEnumerable<Sp>>> X() // Task<IActionResult> same error
{
// this line throws "Sequence has no elements", same for .ToArrayAsync()
var v = await _context.Sp.FromSqlRaw("dbo.GetVideo").ToListAsync();
return Ok(a);
}
</code></pre>
<p><strong>Update</strong></p>
<ol>
<li><p>My <code>DbContext</code> class does have this line omitted in original question: <code>public virtual DbSet<Sp> Sp { get; set; }.</code></p>
</li>
<li><p><code>.FromSqlRaw()</code> always works for calling a stored procedure. That is, it works without <code>for json path, root('x')</code> in stored procedure along with <code>builder.Entity<SP>().HasNoKey()</code>.</p>
</li>
</ol>
<p>Unfortunately I'm locked in with JSON being returned from SQL Server and EF Core version 3.1. At the moment I'm wondering if <code>DbSet<Sp></code> is right because it may expects table-like returns therefore <em>Sequence contains no elements?</em></p>
<p>I need to find a way to call a stored procedure which returns JSON instead of table-like data.</p>
|
[
{
"answer_id": 74621673,
"author": "dbonev",
"author_id": 4200334,
"author_profile": "https://Stackoverflow.com/users/4200334",
"pm_score": 0,
"selected": false,
"text": " const redirect = useNavigate();\n async function handleLogin() {\n try {\n const success = await Api.login(username, password);\n redirect('/home');\n } catch (error) {\n console.log(error);\n }\n }\n"
},
{
"answer_id": 74621868,
"author": "Drew Reese",
"author_id": 8690857,
"author_profile": "https://Stackoverflow.com/users/8690857",
"pm_score": 2,
"selected": true,
"text": "Router declare function Router(\n props: RouterProps\n): React.ReactElement | null;\n\ninterface RouterProps {\n basename?: string;\n children?: React.ReactNode;\n location: Partial<Location> | string; // <-- required\n navigationType?: NavigationType;\n navigator: Navigator; // <-- required\n static?: boolean;\n}\n import { Routes, Route, Router } from \"react-router-dom\"; // <-- Router\nimport Login from \"../components/Login\";\nimport Home from \"../components/Home\";\nimport NoNavRouting from \"./NoNavRouting\";\nimport NavRouting from \"./NavRouting\";\n\nexport default function Routing() {\n return (\n <Router location={\"/\"}> // <-- Missing `navigator` prop!!\n <Routes>\n <Route element={<NoNavRouting />}>\n <Route path=\"/\" element={<Login />} />\n </Route>\n <Route element={<NavRouting />}>\n <Route path=\"home\">\n <Route index element={<Home />} />\n <Route path=\":userId\" element={<Home />} />\n </Route>\n </Route>\n </Routes>\n </Router>\n );\n}\n BrowserRouter MemoryRouter import { Routes, Route, BrowserRouter } from \"react-router-dom\";\nimport Login from \"../components/Login\";\nimport Home from \"../components/Home\";\nimport NoNavRouting from \"./NoNavRouting\";\nimport NavRouting from \"./NavRouting\";\n\nexport default function Routing() {\n return (\n <BrowserRouter>\n <Routes>\n <Route element={<NoNavRouting />}>\n <Route path=\"/\" element={<Login />} />\n </Route>\n <Route element={<NavRouting />}>\n <Route path=\"home\">\n <Route index element={<Home />} />\n <Route path=\":userId\" element={<Home />} />\n </Route>\n </Route>\n </Routes>\n </BrowserRouter>\n );\n}\n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74621618",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5063031/"
] |
74,621,633
|
<p>I have a state array of object and i want to concat each URL of an object with all the URLs of the previous objects of it:</p>
<pre><code> navigation:[
{
"type": "LINK",
"uri": "arbress"
},
{
"type": "LINK",
"uri": "arbres-a-grand-developpement"
},
{
"type": "LINK",
"uri": "Acer-xfreemanii"
}
]
</code></pre>
<p>An i want the result to be like this :</p>
<pre><code>navigation:[
{
"type": "LINK",
"uri": "arbress"
},
{
"type": "LINK",
"uri": "arbress/arbres-a-grand-developpement"
},
{
"type": "LINK",
"uri": "arbress/arbres-a-grand-developpement/Acer-xfreemanii"
}
]
</code></pre>
<p>this is my code but it changed nothing, i always get the initial state:</p>
<pre><code>useEffect(() => {
const newState = navigation.map((obj1) => {
if(obj1.type === 'LINK'){
navigation.map((obj2) => {
if (obj2 === 'LINK'){
return {...obj1, uri: obj2.uri+"/"+uri}
}
})
}
return obj1;
})
setNavigation(newState)
}
}, [])
</code></pre>
|
[
{
"answer_id": 74621673,
"author": "dbonev",
"author_id": 4200334,
"author_profile": "https://Stackoverflow.com/users/4200334",
"pm_score": 0,
"selected": false,
"text": " const redirect = useNavigate();\n async function handleLogin() {\n try {\n const success = await Api.login(username, password);\n redirect('/home');\n } catch (error) {\n console.log(error);\n }\n }\n"
},
{
"answer_id": 74621868,
"author": "Drew Reese",
"author_id": 8690857,
"author_profile": "https://Stackoverflow.com/users/8690857",
"pm_score": 2,
"selected": true,
"text": "Router declare function Router(\n props: RouterProps\n): React.ReactElement | null;\n\ninterface RouterProps {\n basename?: string;\n children?: React.ReactNode;\n location: Partial<Location> | string; // <-- required\n navigationType?: NavigationType;\n navigator: Navigator; // <-- required\n static?: boolean;\n}\n import { Routes, Route, Router } from \"react-router-dom\"; // <-- Router\nimport Login from \"../components/Login\";\nimport Home from \"../components/Home\";\nimport NoNavRouting from \"./NoNavRouting\";\nimport NavRouting from \"./NavRouting\";\n\nexport default function Routing() {\n return (\n <Router location={\"/\"}> // <-- Missing `navigator` prop!!\n <Routes>\n <Route element={<NoNavRouting />}>\n <Route path=\"/\" element={<Login />} />\n </Route>\n <Route element={<NavRouting />}>\n <Route path=\"home\">\n <Route index element={<Home />} />\n <Route path=\":userId\" element={<Home />} />\n </Route>\n </Route>\n </Routes>\n </Router>\n );\n}\n BrowserRouter MemoryRouter import { Routes, Route, BrowserRouter } from \"react-router-dom\";\nimport Login from \"../components/Login\";\nimport Home from \"../components/Home\";\nimport NoNavRouting from \"./NoNavRouting\";\nimport NavRouting from \"./NavRouting\";\n\nexport default function Routing() {\n return (\n <BrowserRouter>\n <Routes>\n <Route element={<NoNavRouting />}>\n <Route path=\"/\" element={<Login />} />\n </Route>\n <Route element={<NavRouting />}>\n <Route path=\"home\">\n <Route index element={<Home />} />\n <Route path=\":userId\" element={<Home />} />\n </Route>\n </Route>\n </Routes>\n </BrowserRouter>\n );\n}\n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74621633",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19567750/"
] |
74,621,761
|
<p>I am working on a multi-language book, and I need to find and replace all hyphens with en-dashes that occur between numbers in the citations section. I need to avoid all hyphens that exist between roman letters.</p>
<p>If I use a GREP [0-9]-[0-9] it selects the numbers before and after the hyphen and I have to manually select the hyphen and replace it with an en-dash. This is labor intensive.</p>
<p>Is there a way for me to find the hyphen that exists between the numbers, but EXCLUDE the numbers themselves from being highlighted? This way I can run a the Find and Replace to change what will probably be 1000+ manual changes?</p>
<p>I tried using GREP [0-9]-[0-9] to find the hyphens, but then couldn't find a way to have the find and replace keep the existing numbers.</p>
|
[
{
"answer_id": 74631333,
"author": "cybernetic.nomad",
"author_id": 8260484,
"author_profile": "https://Stackoverflow.com/users/8260484",
"pm_score": 2,
"selected": true,
"text": "(?<=[0-9])-(?=[0-9])\n"
},
{
"answer_id": 74634579,
"author": "The fourth bird",
"author_id": 5424988,
"author_profile": "https://Stackoverflow.com/users/5424988",
"pm_score": 0,
"selected": false,
"text": "([0-9])-([0-9])\n $1–$2"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74621761",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20639478/"
] |
74,621,810
|
<p>I have a regex in JS</p>
<p>const messageArray = message.split(/(?<!\r)\n/gm)</p>
<p>Below is my 'message'.</p>
<pre><code>'Hello, please can you send &#163;100.00 to MNBVCXZLSTERIA1 on 04/08/21 \n\nhttps://www.co-operativebank.co.uk/help-and-support/faqs/accounts/savings/isas/ \r\nwhat-happens-if-i-put-too-much-money-in-my-cash-isa/PROD-2740 \n\nThank you'
</code></pre>
<p>As you can see above, I am receiving \r\n values inside links which is new line char and due to that it is not able to recognize link and showing in multiline.</p>
<p>But the above regex converts this to link in chrome correctly but not working in safari because of lookbehind/lookahead.</p>
<p>Spent some time trying to think about a good workaround, but did not find one. Any insight?</p>
<p>Thanks!</p>
|
[
{
"answer_id": 74631333,
"author": "cybernetic.nomad",
"author_id": 8260484,
"author_profile": "https://Stackoverflow.com/users/8260484",
"pm_score": 2,
"selected": true,
"text": "(?<=[0-9])-(?=[0-9])\n"
},
{
"answer_id": 74634579,
"author": "The fourth bird",
"author_id": 5424988,
"author_profile": "https://Stackoverflow.com/users/5424988",
"pm_score": 0,
"selected": false,
"text": "([0-9])-([0-9])\n $1–$2"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74621810",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9581091/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.