qid
int64 4
22.2M
| question
stringlengths 18
48.3k
| answers
list | date
stringlengths 10
10
| metadata
list |
|---|---|---|---|---|
74,463,918
|
<p>I'm fairly new to React. Here I've made a small form component for a project (with a bit of tailwind included). Above the form proper is a hidden alert box that will show on submission (green for success and red for fail). The handler that I have attached to the form shows the correct alert, however it takes two clicks. In the handler validateFormData() I'm resetting state (isError). I'm aware the useState hook is asynchronous, so my isError variable is not updating properly before I render my alert box (right?). I've tried passing callbacks to my setIsError functions (after looking online for solutions) but I could not resolve the issue. Am I even in the right ball park here? Or am I missing something?</p>
<pre><code>
function ContactInsert() {
const contactForm = useRef(null);
const alertBox = useRef(null);
const [isError, setIsError] = useState(false);
function showAlertBox() {
alertBox.current.classList.add("alert-show");
setTimeout(() => {
alertBox.current.classList.remove("alert-show");
}, 3000);
}
async function validateFormData() {
// unpack and validate data
const name = contactForm.current.querySelector("[name=name]").value.trim();
const email = contactForm.current.querySelector("[name=email]").value.trim();
const comment = contactForm.current.querySelector("[name=comment]").value.trim();
if (name.length > 0 && email.length > 0 && comment.length > 0) {
setIsError(false);
} else {
setIsError(true);
}
showAlertBox();
}
return (
<div className="flex flex-col">
<div className="flex justify-center my-2">
<h1>Drop me a message!</h1>
</div>
{isError ?
<div ref={alertBox} className="flex h-12 w-2/3 justify-center bg-[#ff462e] invisible">hello</div> :
<div ref={alertBox} className="flex h-12 w-2/3 justify-center bg-[#77ff6e] invisible">hello</div>
}
<form
className="flex flex-col items-center justify-center md:h-full"
method="POST"
name="contact"
id="contact"
type="submit"
ref={contactForm}
onSubmit={(e) => {
e.preventDefault();
validateFormData();
}}
>
<div className="flex flex-col justify-between w-2/3">
<label>name</label>
<input type="text" name="name"/>
</div>
<br/>
<div className="flex flex-col justify-between w-2/3">
<label>email</label>
<input type="text" name="email"/>
</div>
<br/>
<div className="flex flex-col justify-between w-2/3 h-40">
<label>comment</label>
<textarea className="h-full" name="comment"/>
</div>
<div className="flex w-2/3 justify-start my-4">
<button className="p-1" form="contact">Submit</button>
</div>
</form>
</div>
);
}
</code></pre>
|
[
{
"answer_id": 74464523,
"author": "Sushanth --",
"author_id": 941272,
"author_profile": "https://Stackoverflow.com/users/941272",
"pm_score": 2,
"selected": true,
"text": "setState"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74463918",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11214003/"
] |
74,463,937
|
<p>I am trying to get data for the month 5 before the current one. I have tried</p>
<pre><code>MONTH(GETDATE()) - MonthNum ='5'
</code></pre>
<p>Where <code>monthnum</code> has been parsed from the date in a previous CTE.</p>
<p>This works for the 6th month and beyond but doesn't for earlier months.</p>
<p>The end goal is, for example in November I can see data only for June, for all years not just the current one.</p>
<pre class="lang-sql prettyprint-override"><code>SELECT *
FROM TABLE
WHERE MONTH(GETDATE()) - AnniMonthNum ='5'
</code></pre>
|
[
{
"answer_id": 74464407,
"author": "Tim Jarosz",
"author_id": 2452207,
"author_profile": "https://Stackoverflow.com/users/2452207",
"pm_score": 2,
"selected": true,
"text": "DECLARE @month = MONTH(DATEADD(month,-5,GETDATE())); \n\nSELECT t.* \nFROM table as t \nWHERE MONTH(t.transaction_date) = @month;\n"
},
{
"answer_id": 74465281,
"author": "Golden Lion",
"author_id": 4001177,
"author_profile": "https://Stackoverflow.com/users/4001177",
"pm_score": 0,
"selected": false,
"text": " where DateDiff(month,AnniversaryDate,GetDate)=5\n"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74463937",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12507364/"
] |
74,463,958
|
<p>I am trying to setup peer to peer networking and am trying to understand how this works.</p>
<p>Normally in Client to Server connection, I will connect to the server IP and port. Behind the scenes, it will create a client socket bound to a local port at the local ip, and the packet is sent to the router. The router will then NAT the local port and the local socket, to the client public ip and a different public client socket with a destination for the server IP and port.</p>
<p>When the server responds, the router then DENATs the public client ip and public client port back to the local ip and local port, and the packet arrives at the computer.</p>
<p>In a Peer to Peer networking, I may have the peer's public IP, but it is shared by many machines and the router hasn't allowed a connection yet, so there isn't a open port I can send the data to.</p>
<p>There was then an option that both peers contact a server. That opens a port on the router. Then the peers send packets to each other's client port.</p>
<p>However, usually the router will only accept packets from the same IP the request was made to, so the two peers cannot reuse the server's connection.</p>
<p>How do the two peers talk to each other in this scenario ?</p>
|
[
{
"answer_id": 74464407,
"author": "Tim Jarosz",
"author_id": 2452207,
"author_profile": "https://Stackoverflow.com/users/2452207",
"pm_score": 2,
"selected": true,
"text": "DECLARE @month = MONTH(DATEADD(month,-5,GETDATE())); \n\nSELECT t.* \nFROM table as t \nWHERE MONTH(t.transaction_date) = @month;\n"
},
{
"answer_id": 74465281,
"author": "Golden Lion",
"author_id": 4001177,
"author_profile": "https://Stackoverflow.com/users/4001177",
"pm_score": 0,
"selected": false,
"text": " where DateDiff(month,AnniversaryDate,GetDate)=5\n"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74463958",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20132669/"
] |
74,463,967
|
<p>I'm trying to implement push notifications with Firebase Cloud Messaging on an iOS application.</p>
<p>My applications uses the SwiftUI life cycle.</p>
<p>I followed the official documentation from Firebase <a href="https://firebase.google.com/docs/cloud-messaging/ios/client" rel="nofollow noreferrer">documentation</a>
But, for the moment, I'm unable to make it works. I'try a lot of things, but none of them make the job. There is somebody who sees what can be the problem?</p>
<p>I tested on a real device, which ask me for the notification's permission. But no one arrives...</p>
<p>My AppDelegate class:</p>
<pre><code>import SwiftUI
import FirebaseCore
import GoogleMobileAds
import FirebaseMessaging
class AppDelegate: NSObject, UIApplicationDelegate {
func application(_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {
FirebaseApp.configure()
if #available(iOS 10.0, *) {
// For iOS 10 display notification (sent via APNS)
UNUserNotificationCenter.current().delegate = self
let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
UNUserNotificationCenter.current().requestAuthorization(
options: authOptions,
completionHandler: { _, _ in }
)
} else {
let settings: UIUserNotificationSettings =
UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
application.registerUserNotificationSettings(settings)
}
application.registerForRemoteNotifications()
Messaging.messaging().delegate = self
GADMobileAds.sharedInstance().start(completionHandler: nil)
return true
}
</code></pre>
<p>}</p>
<pre><code>extension AppDelegate: UNUserNotificationCenterDelegate{
func userNotificationCenter(_ center: UNUserNotificationCenter,
willPresent notification: UNNotification,
withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
let userInfo = notification.request.content.userInfo
Messaging.messaging().appDidReceiveMessage(userInfo)
// Change this to your preferred presentation option
completionHandler([[.alert, .sound]])
}
func userNotificationCenter(_ center: UNUserNotificationCenter,
didReceive response: UNNotificationResponse,
withCompletionHandler completionHandler: @escaping () -> Void) {
let userInfo = response.notification.request.content.userInfo
Messaging.messaging().appDidReceiveMessage(userInfo)
completionHandler()
}
func application(_ application: UIApplication,
didReceiveRemoteNotification userInfo: [AnyHashable : Any],
fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
Messaging.messaging().appDidReceiveMessage(userInfo)
completionHandler(.noData)
}
func application(application: UIApplication,
didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
Messaging.messaging().apnsToken = deviceToken
}
</code></pre>
<p>}</p>
<pre><code>extension AppDelegate: MessagingDelegate{
func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String?) {
print("Firebase registration token: \(String(describing: fcmToken))")
let dataDict: [String: String] = ["token": fcmToken ?? ""]
NotificationCenter.default.post(
name: Notification.Name("FCMToken"),
object: nil,
userInfo: dataDict
)
// TODO: If necessary send token to application server.
// Note: This callback is fired at each app startup and whenever a new token is generated.
}
</code></pre>
<p>}</p>
<pre><code>@main
struct BochoGameApp: App {
@UIApplicationDelegateAdaptor(AppDelegate.self) var delegate
var body: some Scene {
WindowGroup {
SplashScreen()
}
}
}
</code></pre>
<p>I created a key on my Apple account with the Apple Push Notifications service (APNs) service enabled. After I configured the Firebase console with it.
<a href="https://i.stack.imgur.com/N8J0o.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/N8J0o.png" alt="enter image description here" /></a>
(I erased the empty fields for the image)</p>
<p>I set the next capabilities
<a href="https://i.stack.imgur.com/UWz0R.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/UWz0R.png" alt="enter image description here" /></a></p>
<p>On the info.pils I set FirebaseAppDelegateProxyEnabled to false</p>
<p>Also, I have an App ID with the Push Notification checked
<a href="https://i.stack.imgur.com/iAe2z.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/iAe2z.png" alt="enter image description here" /></a></p>
<p>In my profile says I enable to use Push notifications.</p>
<p><a href="https://i.stack.imgur.com/EvCbL.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/EvCbL.png" alt="enter image description here" /></a></p>
<p>And I set the provisioning profile on Xcode</p>
<p>Any idea? Any help will be appreciated</p>
|
[
{
"answer_id": 74464407,
"author": "Tim Jarosz",
"author_id": 2452207,
"author_profile": "https://Stackoverflow.com/users/2452207",
"pm_score": 2,
"selected": true,
"text": "DECLARE @month = MONTH(DATEADD(month,-5,GETDATE())); \n\nSELECT t.* \nFROM table as t \nWHERE MONTH(t.transaction_date) = @month;\n"
},
{
"answer_id": 74465281,
"author": "Golden Lion",
"author_id": 4001177,
"author_profile": "https://Stackoverflow.com/users/4001177",
"pm_score": 0,
"selected": false,
"text": " where DateDiff(month,AnniversaryDate,GetDate)=5\n"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74463967",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12479599/"
] |
74,463,992
|
<p>I am trying to use variables created in one file and still use them in another file without having to run all of the code from the first file.</p>
<p>Would I be better off saving the variables to a text file and calling the text file in my second python file?</p>
<p>Ex.
File #1</p>
<pre><code>name = input('What is your name')
job = input('How do you earn your money')
user_input = name, job
</code></pre>
<p>File #2
I want to be able to call the input from the first file for name without having to import all of rest of the code in file #1</p>
|
[
{
"answer_id": 74464407,
"author": "Tim Jarosz",
"author_id": 2452207,
"author_profile": "https://Stackoverflow.com/users/2452207",
"pm_score": 2,
"selected": true,
"text": "DECLARE @month = MONTH(DATEADD(month,-5,GETDATE())); \n\nSELECT t.* \nFROM table as t \nWHERE MONTH(t.transaction_date) = @month;\n"
},
{
"answer_id": 74465281,
"author": "Golden Lion",
"author_id": 4001177,
"author_profile": "https://Stackoverflow.com/users/4001177",
"pm_score": 0,
"selected": false,
"text": " where DateDiff(month,AnniversaryDate,GetDate)=5\n"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74463992",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20353896/"
] |
74,464,008
|
<p>I have a user table like this,</p>
<pre><code> USERID Week_Number Year
0 fb 5.0 2021
1 twitter 1.0 2021
2 twitter 2.0 2021
3 twitter 3.0 2021
4 twitter 1.0 2022
5 twitter 2.0 2022
6 twitter 3.0 2022
7 twitter 15.0 2022
8 twitter NaN NaN
9 human 21.0 2022
</code></pre>
<p>I want to find the users who login >= 3 consecutive weeks in the same year. The week numbers will be unique for each year. For example, in the above table we can see that user twitter is logged in week_no: 1, 2, 3 in the same year 2022 thereby satisfying the condition that I am looking for.</p>
<p>The output I am looking for,</p>
<pre><code>USERID Year
twitter 2021
twitter 2022
</code></pre>
<p>You can create the sample table using,</p>
<pre><code>import pandas as pd
import numpy as np
data = pd.DataFrame({"USERID": ["fb", "twitter", "twitter", "twitter", "twitter", "twitter", "twitter", "twitter", "twitter", "human"],
"Week_Number": [5, 1, 2, 3, 1, 2, 3, 15, np.nan, 21],
"Year": ["2021", "2021","2021","2021", "2022", "2022", "2022", "2022", np.nan, "2022"]})
</code></pre>
<p>Can someone help me achieve this required output? I have tried few things but not able to arrive at proper output.</p>
<pre><code>for ix, group in data.groupby([data.USERID, data.Year]):
group = group.sort_values("Week_Number")
group["Diff"] = (group.Week_Number - group.Week_Number.shift(1)).fillna(1)
break
</code></pre>
<p>Thank you for any help in advance.</p>
|
[
{
"answer_id": 74464356,
"author": "sophocles",
"author_id": 9167382,
"author_profile": "https://Stackoverflow.com/users/9167382",
"pm_score": 0,
"selected": false,
"text": "data.sort_values(by=['USERID','Year','Week_Number'],ascending=True,inplace=True)\n\ndata.assign(\n grouped_increase = data.groupby([data.USERID, data.Year])[\"Week_Number\"]\n .diff()\n .gt(0)\n .astype(int)\n).groupby([data.USERID, data.Year])[\"grouped_increase\"].sum().reset_index().query(\n \"grouped_increase >= 3\"\n).drop(\n \"grouped_increase\", axis=1\n)\n"
},
{
"answer_id": 74465949,
"author": "Pierre D",
"author_id": 758174,
"author_profile": "https://Stackoverflow.com/users/758174",
"pm_score": 3,
"selected": true,
"text": "(user, year)"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74464008",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11816060/"
] |
74,464,013
|
<p>Let's say I got a list like this:</p>
<p><code>L = [600, 200, 100, 80, 20]</code></p>
<p>What is the most efficient way to calculate the cumulative sum starting from the next element for every element in the list.</p>
<p>The output of should thus be:</p>
<pre><code> x_1 = 400 (200 + 100 + 80 + 20)
x_2 = 200 (100 + 80 + 20)
x_3 = 20 (20)
x_4 = 0
</code></pre>
|
[
{
"answer_id": 74464180,
"author": "Daniel",
"author_id": 11952668,
"author_profile": "https://Stackoverflow.com/users/11952668",
"pm_score": 2,
"selected": true,
"text": " l = [600, 200, 100, 80, 20]\n res = [sum(l[i:]) for i in range(1, len(l))]\n print(res)\n"
},
{
"answer_id": 74465272,
"author": "Golden Lion",
"author_id": 4001177,
"author_profile": "https://Stackoverflow.com/users/4001177",
"pm_score": 0,
"selected": false,
"text": "L = [600, 200, 100, 80, 20]\ndf=pd.DataFrame(L,columns=['Value'])\ndf['Running_Total'] = df['Value'].cumsum()\ndf['Running_Total2'] = df['Value'].expanding().sum()\nprint(df)\n"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74464013",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12292254/"
] |
74,464,021
|
<p>I have a problem returning dynamic array pointer with function parameter. I get segfault</p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
void createArray(int *ptr, int n)
{
ptr = malloc(n * sizeof(int));
for(int i = 1; i <= n; ++i)
{
*(ptr + (i - 1)) = i*i;
}
}
int main() {
int *array = NULL;
int n = 5;
createArray(array, n);
for(int i = 0; i < n; ++i)
{
printf("%d", array[i]);
}
return 0;
}
</code></pre>
<p>I have to fill my array with i*i, when I is from 1 to n.
I don't get any errors or warnings. Just message about segmentation fault. <em>Process finished with exit code 139 (interrupted by signal 11: SIGSEGV)</em></p>
|
[
{
"answer_id": 74465460,
"author": "Peter Irich",
"author_id": 20275388,
"author_profile": "https://Stackoverflow.com/users/20275388",
"pm_score": 1,
"selected": false,
"text": "#include <stdio.h>\n#include <stdlib.h>\n\nvoid createArray(int *ptr, int n){\n int i;\n for(i = 1; i <= n; i++) {\n *(ptr + (i - 1)) = i*i;\n// fprintf(stdout,\"%d %d\\n\", i, *(ptr + (i -1)));fflush(stdout);\n }\n}\n\nint main() {\n int i, n, *array = NULL;\n void *pvc;\n n = 5;\n array = (int *)malloc(n * sizeof(int));\n createArray(array, n);\n for(i = 0; i < n; i++) {\n fprintf(stdout,\"%d %d\\n\", i, array[i]);fflush(stdout);\n }\n pvc = (void *)array;\n free(pvc);\n return 0;\n}\n"
},
{
"answer_id": 74465751,
"author": "Kurbamit",
"author_id": 12652243,
"author_profile": "https://Stackoverflow.com/users/12652243",
"pm_score": 1,
"selected": true,
"text": "void createArray(int **ptr, int n)\n{\n *ptr = malloc(n * sizeof(int));\n for(int i = 1; i <= n; ++i)\n {\n (*ptr)[i - 1] = i*i;\n }\n}\n\nint main() {\n int *array = NULL;\n int n = 5;\n createArray(&array, n);\n"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74464021",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12652243/"
] |
74,464,037
|
<p>I have an API that saves an the image to S3 bucket and returns the S3 URL but the saving part of the PIL image is slow. Here is a snippet of code:</p>
<pre><code>from PIL import Image
import io
import boto3
BUCKET = ''
s3 = boto3.resource('s3')
def convert_fn(args):
pil_image = Image.open(args['path']).convert('RGBA')
.
.
.
in_mem_file = io.BytesIO()
pil_image.save(in_mem_file, format='PNG') #<--- This takes too long
in_mem_file.seek(0)
s3.meta.client.upload_fileobj(
in_mem_file,
BUCKET,
'outputs/{}.png'.format(args['save_name']),
ExtraArgs={
'ACL': 'public-read',
'ContentType':'image/png'
}
)
return json.dumps({"Image saved in": "https://{}.s3.amazonaws.com/outputs/{}.png".format(BUCKET, args['save_name'])})
</code></pre>
<p>How can I speed up the upload?, Would it be easier to return the bytes?</p>
<p>The <code>Image.save</code> method is the most time consuming part of my script. I want to increase the performance of my app and I'm thinking that returning as a stream of bytes may be the fastest way to return the image.</p>
|
[
{
"answer_id": 74466930,
"author": "jsbueno",
"author_id": 108205,
"author_profile": "https://Stackoverflow.com/users/108205",
"pm_score": 2,
"selected": false,
"text": ".tga"
},
{
"answer_id": 74468352,
"author": "Diego Rodea",
"author_id": 19583119,
"author_profile": "https://Stackoverflow.com/users/19583119",
"pm_score": 0,
"selected": false,
"text": "PIL.Image.save"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74464037",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19583119/"
] |
74,464,058
|
<p>I am new at Selenium and came up with an issue - how to take and save screenshot into the specific folder. I am using Selenium+C#+NUnit bond.</p>
<p>Have read many information on this but most of them is on - how to capture screenshot and add it to html file. But this is not what I need.</p>
<p>I need the screenshot file to be save into a folder so when I'm running Pipeline in AzureDevOps the "Tests results" block contain this screenshot as well and display it.</p>
<p>I was using this part of the code. The test runs and fails, but no screenshot was make</p>
<pre><code>[OneTimeTearDown]
public void OneTimeTearDown()
{
if (TestContext.CurrentContext.Result.Outcome != ResultState.Failure)
{
var screenshot = ((ITakesScreenshot)driver).GetScreenshot();
var filePath = "pathToTheFolder\\Screenshots\\";
screenshot.SaveAsFile(filePath, Png);
}
}
</code></pre>
<p>Maybe someone can help on this and maybe share the knowledge and the code as well)</p>
<p>Thank you all!</p>
|
[
{
"answer_id": 74466930,
"author": "jsbueno",
"author_id": 108205,
"author_profile": "https://Stackoverflow.com/users/108205",
"pm_score": 2,
"selected": false,
"text": ".tga"
},
{
"answer_id": 74468352,
"author": "Diego Rodea",
"author_id": 19583119,
"author_profile": "https://Stackoverflow.com/users/19583119",
"pm_score": 0,
"selected": false,
"text": "PIL.Image.save"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74464058",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19956328/"
] |
74,464,113
|
<p>I want to prevent data being written using a constraint, but the constraints are complicated.</p>
<p>I have 3 columns: A B C</p>
<p>A record is duplicate if A & B match an existing record, and if A & C match an existing record, but it's valid for B & C to match an existing record, unless A=2.</p>
<p>E.g.
Assume existing records</p>
<pre><code>A=1,B=2,C=3
</code></pre>
<p>If I insert</p>
<pre><code>A=1,B=2,C=4
</code></pre>
<p>I should get an error</p>
<p>If I insert</p>
<pre><code>A=1,B=99,C=3
</code></pre>
<p>I should get an error</p>
<p>If I insert:</p>
<pre><code>A=99,B=2,C=3
</code></pre>
<p>That will succeed.</p>
<p>If I insert:</p>
<pre><code>A=2,B=2,C=3
</code></pre>
<p>I should get an error.</p>
<p>The checks have to be done at INSERT time. I can't SELECT then INSERT because the data may have changed between the SELECT and the INSERT.</p>
<p>Ideas:</p>
<ul>
<li>If I put the logic in a TRIGGER would that work? I'm not sure if triggers are 100% atomic.</li>
<li>Would a TRANSACTION work? I don't want to LOCK the table because other processes will be inserting data constantly.</li>
<li>Could I add one or more constraint(s)? Is there a way to check the constraints at INSERT time?</li>
</ul>
|
[
{
"answer_id": 74464349,
"author": "Joe Derham",
"author_id": 7180277,
"author_profile": "https://Stackoverflow.com/users/7180277",
"pm_score": -1,
"selected": false,
"text": "-- Assuming A and B do not permit NULLs\n; WITH cteAB AS (\n SELECT DISTINCT a,b FROM YourTable\n)\n, cteBC AS (\n SELECT DISTINCT b,c FROM YourTable\n)\nINSERT YourTable ( a, b )\nSELECT NewA, NewB\nFROM YourTable yt \nLEFT JOIN cteAB ab ON ab.a=NewA AND ab.b=NewB\nLEFT JOIN cteBC bc ON bc.a=NewA AND bc.b=NewB\nWHERE ( ab.a IS NULL AND bc.a IS NULL )\n OR NewA=2\n"
},
{
"answer_id": 74464387,
"author": "Larnu",
"author_id": 2029983,
"author_profile": "https://Stackoverflow.com/users/2029983",
"pm_score": 3,
"selected": true,
"text": "A"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74464113",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/759558/"
] |
74,464,155
|
<p><code>SELECT NEW Map (PRODUCT_CATEGORY, COUNT(PRODUCT_CATEGORY) AS COUNTER) from Product WHERE USER_ID = (SELECT USER_ID FROM USERS WHERE USERNAME='burak123' </code></p>
<p>Hi everyone,
As hibernates document says here: <a href="https://docs.jboss.org/hibernate/orm/3.3/reference/en/html/queryhql.html#queryhql-select" rel="nofollow noreferrer">https://docs.jboss.org/hibernate/orm/3.3/reference/en/html/queryhql.html#queryhql-select</a></p>
<p>I am trying to map the query result into a hash map like this</p>
<pre><code>@Query(value = "SELECT NEW Map( PRODUCT_CATEGORY , COUNT(PRODUCT_CATEGORY) AS COUNTER ) from Product WHERE USER_ID=(SELECT USER_ID FROM USERS WHERE USERNAME=(:username)) ",nativeQuery = true)
HashMap<Integer,Integer> getCategoryCountsWithUsername(@Param("username")String username);
</code></pre>
<p>But it throws an JdbcSyntaxErrorException. I am trying to solve this for like 1 hours already. Can someone help?</p>
|
[
{
"answer_id": 74491086,
"author": "Marc Bannout",
"author_id": 13695861,
"author_profile": "https://Stackoverflow.com/users/13695861",
"pm_score": 0,
"selected": false,
"text": "nativeQuery = true"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74464155",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19728398/"
] |
74,464,183
|
<p>I have an array of objects, and I need to generate other based on it.</p>
<p>But, if the new arrays don't have the property, I need to generate a default value based on first array.</p>
<pre><code> const dailyLabels = [
"01/11",
"02/11",
"03/11",
"04/11"
]
const dailyCurr = [
{
mov_date: "2022-11-03T14:16:10.694Z",
value: 2,
cod: 5,
product: "ODONTO",
day: "03/11",
year: "curr"
},
{
mov_date: "2022-11-04T14:16:10.694Z",
value: 2,
cod: 5,
product: "ODONTO",
day: "04/11",
year: "curr"
}
]
</code></pre>
<p>So, I need to generate a third array with the missing days between <code>dailyLabels</code> and <code>dailyCurr</code>, I expect something like this:</p>
<pre><code>const thirdArray = [
{
mov_date: "",
value: 0,
cod: null,
product: "",
day: "01/11",
year: "curr"
},
{
mov_date: "",
value: 0,
cod: null,
product: "",
day: "02/11",
year: "curr"
},
{
mov_date: "2022-11-03T14:16:10.694Z",
value: 2,
cod: 5,
product: "ODONTO",
day: "03/11",
year: "curr"
},
{
mov_date: "2022-11-04T14:16:10.694Z",
value: 2,
cod: 5,
product: "ODONTO",
day: "04/11",
year: "curr"
}
]
</code></pre>
|
[
{
"answer_id": 74464371,
"author": "lemek",
"author_id": 4860179,
"author_profile": "https://Stackoverflow.com/users/4860179",
"pm_score": 0,
"selected": false,
"text": "const dailyLabes = [ \"01/11\", \"02/11\", \"03/11\", \"04/11\" ]\n\nconst dailyCurr = [ { mov_date: \"2022-11-03T14:16:10.694Z\", value: 2, cod: 5, product: \"ODONTO\", day: \"03/11\", year: \"curr\" }, { mov_date: \"2022-11-04T14:16:10.694Z\", value: 2, cod: 5, product: \"ODONTO\", day: \"04/11\", year: \"curr\" } ]\n\n// Deep copy\nconst thirdArr = [...dailyCurr];\n\ndailyLabes.forEach(label => {\n if (!dailyCurr.find(dateObj => dateObj.day === label)) {\n thirdArr.push({ mov_date: \"\", value: 0, cod: 0, product: \"\", day: label, year: \"curr\" });\n }\n});\n"
},
{
"answer_id": 74464394,
"author": "symlink",
"author_id": 818326,
"author_profile": "https://Stackoverflow.com/users/818326",
"pm_score": 1,
"selected": false,
"text": "Array.map()"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74464183",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14790033/"
] |
74,464,200
|
<p>I am just learning nestjs for about a day and I came across this strange bug, probably has something to do with me not understanding what Im doing and rushing the project so please bear with me. My main issue is that while using JWT authentication, JSON coming from body is "username" and I can't change it. I want to log in using {"email":"test@gmail.com", "password": "password123"}, but instead it only accepts {"username":"test@gmail.com", "password": "password123"}. The word "username" is not defined or mentioned anywhere in my codebase</p>
<p>users.controller.ts</p>
<pre><code>import { Controller, Get, Post, Body, Param, UseGuards } from '@nestjs/common';
import { UsersService} from './users.service';
import { CreateUserDto} from './dto/create-user.dto';
import { AuthGuard} from '@nestjs/passport';
@Controller('/users')
export class UsersController {
// constructor(private readonly usersService: UsersService) {}
constructor(private readonly userService: UsersService) {}
@UseGuards(AuthGuard('jwt'))
@Get('username')
getUserByEmail(@Param() param) {
return this.userService.getUserByEmail(param.email);
}
@Post('register')
registerUser(@Body() createUserDto: CreateUserDto) {
return this.userService.registerUser(createUserDto);
}
}
</code></pre>
<p>users.service.ts</p>
<pre><code>import { Injectable, BadRequestException } from '@nestjs/common';
import { CreateUserDto } from './dto/create-user.dto';
import { UpdateUserDto } from './dto/update-user.dto';
import { Model } from 'mongoose';
import { InjectModel } from '@nestjs/mongoose';
import { HashService } from './hash.service';
import { User, UserDocument} from '../schemas/user.schema'
@Injectable()
export class UsersService {
constructor(@InjectModel(User.name) private userModel: Model < UserDocument > , private hashService: HashService) {}
async getUserByEmail(email: string) {
return this.userModel.findOne({
email
})
.exec();
}
async registerUser(createUserDto: CreateUserDto) {
// validate DTO
const createUser = new this.userModel(createUserDto);
// check if user exists
const user = await this.getUserByEmail(createUser.email);
if (user) {
throw new BadRequestException();
}
// Hash Password
createUser.password = await this.hashService.hashPassword(createUser.password);
return createUser.save();
}
}
</code></pre>
<p>auth.controller.ts</p>
<pre><code>import { AuthService} from './auth.service';
import { Controller, Request, UseGuards, Post} from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';
@Controller('auth')
export class AuthController {
constructor(private authService: AuthService) {}
@UseGuards(AuthGuard('local'))
@Post(`/login`)
async login(@Request() req) {
console.log(req.user, "here")
return this.authService.login(req.user);
}
}
</code></pre>
<p>Here is the source code <a href="https://github.com/networkdavit/pillicam_test" rel="nofollow noreferrer">https://github.com/networkdavit/pillicam_test</a>
Any help or suggestion is highly appreciated!</p>
<p>I tried changing all the parameter names, user schemas, adding a DTO, I googled how to add a custom parameter name or override it, tried to find if "default username param" actually exists. Nothing has worked for me so far</p>
|
[
{
"answer_id": 74464371,
"author": "lemek",
"author_id": 4860179,
"author_profile": "https://Stackoverflow.com/users/4860179",
"pm_score": 0,
"selected": false,
"text": "const dailyLabes = [ \"01/11\", \"02/11\", \"03/11\", \"04/11\" ]\n\nconst dailyCurr = [ { mov_date: \"2022-11-03T14:16:10.694Z\", value: 2, cod: 5, product: \"ODONTO\", day: \"03/11\", year: \"curr\" }, { mov_date: \"2022-11-04T14:16:10.694Z\", value: 2, cod: 5, product: \"ODONTO\", day: \"04/11\", year: \"curr\" } ]\n\n// Deep copy\nconst thirdArr = [...dailyCurr];\n\ndailyLabes.forEach(label => {\n if (!dailyCurr.find(dateObj => dateObj.day === label)) {\n thirdArr.push({ mov_date: \"\", value: 0, cod: 0, product: \"\", day: label, year: \"curr\" });\n }\n});\n"
},
{
"answer_id": 74464394,
"author": "symlink",
"author_id": 818326,
"author_profile": "https://Stackoverflow.com/users/818326",
"pm_score": 1,
"selected": false,
"text": "Array.map()"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74464200",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19159834/"
] |
74,464,204
|
<p>I use a microscope taking images of particles. I get data out in an xml-file that contain information( see extract of a file) and I wonder if the entry pixel can be used to get the picture that has been taken of the particle. I'm confused if it is pixel data, because some entries also have letters. If it is possible, how can it be done?</p>
<p><code><particledata FileVersion="1.0"> <data measurement="2022-09-26 13:31:34.4610 0228 Q" product="EQPT" filter="<<DIAMETER_EQPC >= 1E-5>> AND <<DIAMETER_EQPC <= 0.0002>>"/> <particle frame="181" EQPC="5.92777219475097e-05" FERET_MAX="6.16502327208423e-05" FERET_MIN="5.96099987626077e-05" FERET_MEAN="6.09342368979882e-05" SPHERICITY="0.947197455424963" ASPECT_RATIO="0.966906305650574" CONVEXITY="0.956224350205198"> <image width="30" height="30" pixel="0E0000000100090001000B00070002001000060003001200050004001400040005001600030006001800020007001A00020008001A00010009001C0001000A001C0000000B001D0000000C001D0000000D001E0000000E001E0000000F001E00000010001E00000011001E00000012001D00010013001C00010014001C00010015001C00020016001A00020017001A0003001800180004001900160005001A00140006001B00110008001C000E000A001D000900"/> </particle> <particle frame="439" EQPC="1.75112776854003e-05" FERET_MAX="2.70261182554826e-05" FERET_MIN="1.98699995875359e-05" FERET_MEAN="2.33606593187573e-05" SPHERICITY="0.539453245456778" ASPECT_RATIO="0.735214706000371" CONVEXITY="0.635416666666667"> <image width="12" height="10" pixel="0800000001000500010005000500020005000100010003000100020003000100030009000100040004000600040005000100050005000700050004000000060004000800060002000100070002000800070004000200080001000800080002000B0008000100080009000100"/> </particle> </code></p>
|
[
{
"answer_id": 74468987,
"author": "ardget",
"author_id": 12793185,
"author_profile": "https://Stackoverflow.com/users/12793185",
"pm_score": 1,
"selected": false,
"text": "0E 00 -> 0x000e = 14 x0\n00 00 -> 0x0000 = 0 y0\n01 00 -> 0x0001 = 1 x1 \n09 00 -> 0x0009 = 9 y1\n:\n"
},
{
"answer_id": 74533101,
"author": "Mark Setchell",
"author_id": 2836621,
"author_profile": "https://Stackoverflow.com/users/2836621",
"pm_score": 0,
"selected": false,
"text": "#!/usr/bin/env python3\n\nimport re\nfrom PIL import Image\nfrom struct import unpack\nfrom binascii import unhexlify\n\nxml = \"\"\"<particledata FileVersion=\"1.0\"> <data measurement=\"2022-09-26 13:31:34.4610 0228 Q\" product=\"EQPT\" filter=\"<<DIAMETER_EQPC >= 1E-5>> AND <<DIAMETER_EQPC <= 0.0002>>\"/> <particle frame=\"181\" EQPC=\"5.92777219475097e-05\" FERET_MAX=\"6.16502327208423e-05\" FERET_MIN=\"5.96099987626077e-05\" FERET_MEAN=\"6.09342368979882e-05\" SPHERICITY=\"0.947197455424963\" ASPECT_RATIO=\"0.966906305650574\" CONVEXITY=\"0.956224350205198\"> <image width=\"30\" height=\"30\" pixel=\"0E0000000100090001000B00070002001000060003001200050004001400040005001600030006001800020007001A00020008001A00010009001C0001000A001C0000000B001D0000000C001D0000000D001E0000000E001E0000000F001E00000010001E00000011001E00000012001D00010013001C00010014001C00010015001C00020016001A00020017001A0003001800180004001900160005001A00140006001B00110008001C000E000A001D000900\"/> </particle> <particle frame=\"439\" EQPC=\"1.75112776854003e-05\" FERET_MAX=\"2.70261182554826e-05\" FERET_MIN=\"1.98699995875359e-05\" FERET_MEAN=\"2.33606593187573e-05\" SPHERICITY=\"0.539453245456778\" ASPECT_RATIO=\"0.735214706000371\" CONVEXITY=\"0.635416666666667\"> <image width=\"12\" height=\"10\" pixel=\"0800000001000500010005000500020005000100010003000100020003000100030009000100040004000600040005000100050005000700050004000000060004000800060002000100070002000800070004000200080001000800080002000B0008000100080009000100\"/> </particle>\"\"\" \n\nseq = 0\n# Iterate over all <image width=/height=/pixel=> occurrences in xml string\nfor match in re.finditer('<image width=\"(\\d+)\" height=\"(\\d+)\" pixel=\"([0-9A-F]+)\"', xml):\n # Extract width, height and pixels\n width, height, pixel = match.groups()\n filename = f'extracted-{seq}.png'\n print(f'Image width: {width}, height: {height} -> {filename}')\n # Make a new, empty, black image the correct size\n im = Image.new('L', (int(width)+1,int(height)+1))\n\n # Unpack the hideous hex into groups of 4 hexdigits, each a short\n shorts = [pixel[i:i+4] for i in range(0,len(pixel), 4)]\n # print('DEBUG: ', shorts)\n # Convert little-endian short hex string things into integers\n px = [unpack('<H', unhexlify(short))[0] for short in shorts]\n # print('DEBUG: ',px)\n\n # Put the pixels in the image with white colour - slowly but there are only a few\n for i in range(0, len(px), 2):\n x, y = px[i], px[i+1]\n im.putpixel((x,y), 255)\n # print(f'DEBUG: x={x}, y={y}')\n\n # Save the image \n im.save(filename)\n seq += 1\n"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74464204",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20522107/"
] |
74,464,214
|
<p>I have 4 branches.
main, release, master, preview.</p>
<p>Preview is used for doing experiments. I want to clean the preview branch and sync it with release branch.</p>
<p>If I just merge release branch into preview, I still have the old experiment code. I am not sure how to go about it</p>
|
[
{
"answer_id": 74464281,
"author": "eftshift0",
"author_id": 2437508,
"author_profile": "https://Stackoverflow.com/users/2437508",
"pm_score": 3,
"selected": true,
"text": "git checkout preview\ngit merge --no-commit release\n# let's get the contents of files just like in release:\ngit restore --staged --worktree --source=release -- .\ngit merge --continue\n"
},
{
"answer_id": 74467530,
"author": "knittl",
"author_id": 112968,
"author_profile": "https://Stackoverflow.com/users/112968",
"pm_score": 1,
"selected": false,
"text": "git branch -D preview\ngit branch preview release\n"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74464214",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/303723/"
] |
74,464,216
|
<p>Suppose I have a list with nested lists such of strings such as:</p>
<pre><code>items = ['Hello', ['Ben', 'Chris', 'Linda'], '! The things you can buy today are', ['Apples', 'Oranges']]
</code></pre>
<p>I want a list of strings that combine and flatten the nested lists into all possibilities such that the result is:</p>
<pre><code>new_list = ['Hello Ben ! The things you can buy today are Apples',
'Hello Ben ! The things you can buy today are Oranges',
'Hello Chris ! The things you can buy today are Apples',
'Hello Chris ! The things you can buy today are Oranges',
'Hello Linda ! The things you can buy today are Apples',
'Hello Linda ! The things you can buy today are Oranges',]
</code></pre>
<p>I've been looking through itertools documentation and nothing quite works as expected. I don't want to hard code iterations because this items list can range in number of items as well as number of nested lists.</p>
<p>For example:</p>
<pre><code>list(itertools.chain(*items))
</code></pre>
<p>Will flatten the list but it splits up individual characters in the string items. Part of the challenge is that some items in the list are strings, and others are additional lists. Would appreciate any help. Thanks</p>
|
[
{
"answer_id": 74464537,
"author": "Jay",
"author_id": 8677071,
"author_profile": "https://Stackoverflow.com/users/8677071",
"pm_score": 3,
"selected": true,
"text": "itertools.product()"
},
{
"answer_id": 74464652,
"author": "amirhm",
"author_id": 4529589,
"author_profile": "https://Stackoverflow.com/users/4529589",
"pm_score": 0,
"selected": false,
"text": "def test(itm):\n n = len(itm)\n results = []\n def dfs(idx, res):\n if idx == n:\n results.append(res.copy())\n return\n if isinstance(itm[idx], list):\n for d in itm[idx]:\n res.append(d)\n dfs(idx+1, res)\n res.pop()\n else:\n res.append(itm[idx])\n dfs(idx+1, res)\n res.pop()\n\n dfs(0, [])\n return results\n"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74464216",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7237305/"
] |
74,464,230
|
<p>I have a table, and I have a list of indexes.</p>
<p>Lets say the table is</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Column A</th>
<th>Column B</th>
<th>Column C</th>
<th>Column D</th>
</tr>
</thead>
<tbody>
<tr>
<td>Cell 1</td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>Cell 2</td>
<td></td>
<td></td>
<td></td>
</tr>
</tbody>
</table>
</div>
<p>And the list is MyList={1,2}</p>
<p>Based on the list, which is the index of the Columns that needs to be removed, I would like to get a new table that consists of Column 0 and 3 which would be</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Column A</th>
<th>Column D</th>
</tr>
</thead>
<tbody>
<tr>
<td>Cell 1</td>
<td></td>
</tr>
<tr>
<td>Cell 2</td>
<td></td>
</tr>
</tbody>
</table>
</div>
<p>Of course in the actual scenario, the table sizes are dynamic, and the list is generated automatically. I need the M code for removing the columns based on the indexes in a list.</p>
<p>I am actually trying to remove the columns in the table where the values are the same. I have gotten so far to retrieving a list of indexes of the columns that need to be removed, and I would appreciate a help in pointing me in the right direction from here.</p>
|
[
{
"answer_id": 74464477,
"author": "horseyride",
"author_id": 9264230,
"author_profile": "https://Stackoverflow.com/users/9264230",
"pm_score": 3,
"selected": true,
"text": "let Source = Excel.CurrentWorkbook(){[Name=\"Table1\"]}[Content],\nMyList={1,2},\nx = Table.RemoveColumns(Source,List.Transform(MyList, each Table.ColumnNames(Source){_}))\nin x\n"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74464230",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8951502/"
] |
74,464,231
|
<p>I'm trying to merge one column values from <code>df2</code> to <code>df1</code>. <code>df1.merge(df2, how='outer')</code> seems to be what I needed but result is not what I wanted because of duplicate. Using 'on' introduces <code>_x</code> and <code>_y</code> which I don't want either.</p>
<p>In below Example: <code>sub=site1</code> in both <code>df1</code> and <code>df2</code> is same, then <code>'fred'</code> from <code>df2</code> replaces <code>'own'</code> of <code>df1</code>.</p>
<pre><code># Pandas Merge test:
import pandas as pd
df1 = pd.DataFrame({'sub': ['site1', 'site2', 'site3'], 'iss': ['enc1', 'enc2', 'enc3'], 'rem': [1, 3, 5], 'own': ['andy', 'brian', 'cody']})
df2 = pd.DataFrame({'sub': ['data1', 'data2', 'site1'], 'rem': [2, 4, 6], 'own': ['david', 'edger', 'fred']})
>>> df1
sub iss rem own
0 site1 enc1 1 andy
1 site2 enc2 3 brian
2 site3 enc3 5 cody
>>> df2
sub rem own
0 data1 2 david
1 data2 4 edger
2 site1 6 fred
>>> df1.merge(df2, how='outer')
sub iss rem own
0 site1 enc1 1 andy
1 site2 enc2 3 brian
2 site3 enc3 5 cody
3 data1 NaN 2 david
4 data2 NaN 4 edger
5 site1 NaN 6 fred
>>> df1.merge(df2, on='sub', how='outer')
sub iss rem_x own_x rem_y own_y
0 site1 enc1 1.0 andy 6.0 fred
1 site2 enc2 3.0 brian NaN NaN
2 site3 enc3 5.0 cody NaN NaN
3 data1 NaN NaN NaN 2.0 david
4 data2 NaN NaN NaN 4.0 edger
</code></pre>
<p>Expected Output:</p>
<pre><code> sub iss rem own
0 site1 enc1 1 fred
1 site2 enc2 3 brian
2 site3 enc3 5 cody
3 data1 NaN 2 david
4 data2 NaN 4 edger
</code></pre>
|
[
{
"answer_id": 74464477,
"author": "horseyride",
"author_id": 9264230,
"author_profile": "https://Stackoverflow.com/users/9264230",
"pm_score": 3,
"selected": true,
"text": "let Source = Excel.CurrentWorkbook(){[Name=\"Table1\"]}[Content],\nMyList={1,2},\nx = Table.RemoveColumns(Source,List.Transform(MyList, each Table.ColumnNames(Source){_}))\nin x\n"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74464231",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13923735/"
] |
74,464,255
|
<p>SO I'm trying to install Moodle using Ubuntu and I followed the instructions from <a href="https://www.linode.com/docs/guides/how-to-install-moodle-on-ubuntu-server-2004/" rel="nofollow noreferrer">https://www.linode.com/docs/guides/how-to-install-moodle-on-ubuntu-server-2004/</a> , but when I type localhost/moodle on my browser, it just displays the PHP code which I'll add. I should be displayed with the Moodle installation steps right? I can't imagine it would be a problem with Moodle itself but rather a PHP issue. Any help would be greatly appreciated!</p>
<pre><code><?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Moodle frontpage.
*
* @package core
* @copyright 1999 onwards Martin Dougiamas (http://dougiamas.com)
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
if (!file_exists('./config.php')) {
header('Location: install.php');
die;
}
require_once('config.php');
require_once($CFG->dirroot .'/course/lib.php');
require_once($CFG->libdir .'/filelib.php');
redirect_if_major_upgrade_required();
$urlparams = array();
if (!empty($CFG->defaulthomepage) && ($CFG->defaulthomepage == HOMEPAGE_MY) && optional_param('redirect', 1, PARAM_BOOL) === 0) {
$urlparams['redirect'] = 0;
}
$PAGE->set_url('/', $urlparams);
$PAGE->set_pagelayout('frontpage');
$PAGE->set_other_editing_capability('moodle/course:update');
$PAGE->set_other_editing_capability('moodle/course:manageactivities');
$PAGE->set_other_editing_capability('moodle/course:activityvisibility');
// Prevent caching of this page to stop confusion when changing page after making AJAX changes.
$PAGE->set_cacheable(false);
require_course_login($SITE);
$hasmaintenanceaccess = has_capability('moodle/site:maintenanceaccess', context_system::instance());
// If the site is currently under maintenance, then print a message.
if (!empty($CFG->maintenance_enabled) and !$hasmaintenanceaccess) {
print_maintenance_message();
}
$hassiteconfig = has_capability('moodle/site:config', context_system::instance());
if ($hassiteconfig && moodle_needs_upgrading()) {
redirect($CFG->wwwroot .'/'. $CFG->admin .'/index.php');
}
// If site registration needs updating, redirect.
\core\hub\registration::registration_reminder('/index.php');
if (get_home_page() != HOMEPAGE_SITE) {
// Redirect logged-in users to My Moodle overview if required.
$redirect = optional_param('redirect', 1, PARAM_BOOL);
if (optional_param('setdefaulthome', false, PARAM_BOOL)) {
set_user_preference('user_home_page_preference', HOMEPAGE_SITE);
} else if (!empty($CFG->defaulthomepage) && ($CFG->defaulthomepage == HOMEPAGE_MY) && $redirect === 1) {
redirect($CFG->wwwroot .'/my/');
} else if (!empty($CFG->defaulthomepage) && ($CFG->defaulthomepage == HOMEPAGE_USER)) {
$frontpagenode = $PAGE->settingsnav->find('frontpage', null);
if ($frontpagenode) {
$frontpagenode->add(
get_string('makethismyhome'),
new moodle_url('/', array('setdefaulthome' => true)),
navigation_node::TYPE_SETTING);
} else {
$frontpagenode = $PAGE->settingsnav->add(get_string('frontpagesettings'), null, navigation_node::TYPE_SETTING, null);
$frontpagenode->force_open();
$frontpagenode->add(get_string('makethismyhome'),
new moodle_url('/', array('setdefaulthome' => true)),
navigation_node::TYPE_SETTING);
}
}
}
// Trigger event.
course_view(context_course::instance(SITEID));
$PAGE->set_pagetype('site-index');
$PAGE->set_docs_path('');
$editing = $PAGE->user_is_editing();
$PAGE->set_title($SITE->fullname);
$PAGE->set_heading($SITE->fullname);
$courserenderer = $PAGE->get_renderer('core', 'course');
echo $OUTPUT->header();
$siteformatoptions = course_get_format($SITE)->get_format_options();
$modinfo = get_fast_modinfo($SITE);
$modnamesused = $modinfo->get_used_module_names();
// Print Section or custom info.
if (!empty($CFG->customfrontpageinclude)) {
// Pre-fill some variables that custom front page might use.
$modnames = get_module_types_names();
$modnamesplural = get_module_types_names(true);
$mods = $modinfo->get_cms();
include($CFG->customfrontpageinclude);
} else if ($siteformatoptions['numsections'] > 0) {
echo $courserenderer->frontpage_section1();
}
// Include course AJAX.
include_course_ajax($SITE, $modnamesused);
echo $courserenderer->frontpage();
if ($editing && has_capability('moodle/course:create', context_system::instance())) {
echo $courserenderer->add_new_course_button();
}
echo $OUTPUT->footer();
</code></pre>
<p>I looked at the modules in my httpd.conf file, but when adding "LoadModule php_module modules/libphp.so" apache throws an error when attempting to restart.</p>
|
[
{
"answer_id": 74464477,
"author": "horseyride",
"author_id": 9264230,
"author_profile": "https://Stackoverflow.com/users/9264230",
"pm_score": 3,
"selected": true,
"text": "let Source = Excel.CurrentWorkbook(){[Name=\"Table1\"]}[Content],\nMyList={1,2},\nx = Table.RemoveColumns(Source,List.Transform(MyList, each Table.ColumnNames(Source){_}))\nin x\n"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74464255",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
74,464,270
|
<p>I was tasked with removing unnecessary tags from computer-generated HTML that had a lot of useless tags (I only wanted to keep color/strong/em information). I came along something similar to this HTML:</p>
<pre class="lang-html prettyprint-override"><code><b>
<span style="FONT: 20pt &quot;Arial&quot;">
<strong>bold</strong> not bold <b>bold</b> not bold
</span>
</b>
</code></pre>
<p>For me (on chrome & firefox), it shows the <code>bold</code> text as bold and the <code>not bold</code> text as not bold, and I am confused as to why this is. In particular, this makes my task more complicated: I thought I could just remove the tags that do not have color/strong/em info, so change it to something like this:</p>
<pre class="lang-html prettyprint-override"><code><b>
<strong>bold</strong> not bold <strong>bold</strong> not bold
</b>
</code></pre>
<p>But now, all is bold instead of what it used to be.</p>
<p>I tried to find out what I could put in the <code>FONT</code> style to reproduce this behaviour:</p>
<p>Replacing <code>Arial</code> with <code>foo</code> kept the behaviour:</p>
<pre class="lang-html prettyprint-override"><code><b>
<span style="FONT: 20pt foo">
<strong>bold</strong> not bold <b>bold</b> not bold <!-- not bold is actually not bold! 20pt is applied -->
</span>
</b>
</code></pre>
<p>Switching the size and font changed the behaviour:</p>
<pre class="lang-html prettyprint-override"><code><b>
<span style="FONT: &quot;Arial&quot; 20pt">
<strong>bold</strong> not bold <b>bold</b> not bold <!-- everything is bold. 20pt is _not_ applied -->
</span>
</b>
</code></pre>
<p>Any of the two values on their own did nothing much:</p>
<pre class="lang-html prettyprint-override"><code><b>
<span style="FONT: &quot;Arial&quot;">
<strong>bold</strong> not bold <b>bold</b> not bold <!-- everything is bold -->
</span>
</b>
</code></pre>
<pre class="lang-html prettyprint-override"><code><b>
<span style="FONT: 20pt">
<strong>bold</strong> not bold <b>bold</b> not bold <!-- everything is bold -->
</span>
</b>
</code></pre>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><b>
<span style="FONT: 20pt &quot;Arial&quot;">
<strong>bold</strong> not bold <b>bold</b> not bold
</span>
</b>
<div>Replacing `Arial` with `foo` kept the behaviour:</div>
<b>
<span style="FONT: 20pt foo">
<strong>bold</strong> not bold <b>bold</b> not bold
<!-- not bold is actually not bold! 20pt is applied -->
</span>
</b>
<div>Switching the size and font changed the behaviour:</div>
<b>
<span style="FONT: &quot;Arial&quot; 20pt">
<strong>bold</strong> not bold <b>bold</b> not bold
<!-- everything is bold. 20pt is _not_ applied -->
</span>
</b>
<div>Any of the two values on their own did nothing much:</div>
<b>
<span style="FONT: &quot;Arial&quot;">
<strong>bold</strong> not bold <b>bold</b> not bold
<!-- everything is bold -->
</span>
</b>
<b>
<span style="FONT: 20pt">
<strong>bold</strong> not bold <b>bold</b> not bold
<!-- everything is bold -->
</span>
</b></code></pre>
</div>
</div>
</p>
<p>Can anyone explain this behaviour, or at least tell me what styles I should look for that cancel outer styles?</p>
|
[
{
"answer_id": 74464994,
"author": "Mark Schultheiss",
"author_id": 125981,
"author_profile": "https://Stackoverflow.com/users/125981",
"pm_score": 0,
"selected": false,
"text": "sans-serif"
},
{
"answer_id": 74465161,
"author": "student91",
"author_id": 5754961,
"author_profile": "https://Stackoverflow.com/users/5754961",
"pm_score": 1,
"selected": false,
"text": "font: 20pt arial"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74464270",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5754961/"
] |
74,464,287
|
<p>When opening my component, I want to get Assets from a Media Folder (which works fine) and then passing it through to another component. The Problem is that when first launching the app, the "listOfAssets" state is empty and when refreshing it, it stores all necessary Assets.</p>
<p>How can I achieve that the Assets are getting stored the first time and that I don't have to refresh it.</p>
<p>Could there be a problem with my async code?</p>
<pre><code>const [listOfAssets, setListOfAssets] = useState([]);
useEffect(() => {
async function getAssets() {
const assets = await MediaLibrary.getAssetsAsync({
album: folderToSort,
includeSmartAlbums: true,
});
assets.assets.map((asset) => {
listOfAssets.push({
id: asset.id,
uri: asset.uri,
height: asset.height,
width: asset.width,
});
});
}
getAssets();
}, []);
return (
<View>
<SlideComponent
imageUri={listOfAssets}
moveImageToGOAlbum={moveImageToGOAlbum}
/>
</View>
);
</code></pre>
|
[
{
"answer_id": 74464994,
"author": "Mark Schultheiss",
"author_id": 125981,
"author_profile": "https://Stackoverflow.com/users/125981",
"pm_score": 0,
"selected": false,
"text": "sans-serif"
},
{
"answer_id": 74465161,
"author": "student91",
"author_id": 5754961,
"author_profile": "https://Stackoverflow.com/users/5754961",
"pm_score": 1,
"selected": false,
"text": "font: 20pt arial"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74464287",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11325009/"
] |
74,464,290
|
<p>I have a text file called test.txt with the words "cat dog frog" in it. I need to split it so each word appears on a new line. Can someone help me please?</p>
<pre><code>def get_tokens_from_file(test):
with open("test.txt") as f:
</code></pre>
|
[
{
"answer_id": 74464994,
"author": "Mark Schultheiss",
"author_id": 125981,
"author_profile": "https://Stackoverflow.com/users/125981",
"pm_score": 0,
"selected": false,
"text": "sans-serif"
},
{
"answer_id": 74465161,
"author": "student91",
"author_id": 5754961,
"author_profile": "https://Stackoverflow.com/users/5754961",
"pm_score": 1,
"selected": false,
"text": "font: 20pt arial"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74464290",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20412028/"
] |
74,464,292
|
<p>I found this neat little code for sleeping in TypeScript and JavaScript on Stack Overflow:</p>
<pre><code>async function sleep(ms : number) {
return new Promise<void>(resolve => setTimeout(resolve, ms));
}
</code></pre>
<p>I use it like this:</p>
<pre><code>while(true) {
updateBackground();
await sleep(1000);
}
</code></pre>
<p>The potential problem is that the sleep function adds "then" to the callstack and it looks like the callstack grows bigger and bigger for each sleep call. I assume that I will run out of space on the stack sooner or later.</p>
<p><a href="https://i.stack.imgur.com/pcbCc.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/pcbCc.png" alt="stacktrace in chrome" /></a></p>
<p>Is there a good way to solve that. How do I sleep?</p>
|
[
{
"answer_id": 74464411,
"author": "Mr. Polywhirl",
"author_id": 1762224,
"author_profile": "https://Stackoverflow.com/users/1762224",
"pm_score": 3,
"selected": true,
"text": "while"
},
{
"answer_id": 74464487,
"author": "Elias Soares",
"author_id": 3429323,
"author_profile": "https://Stackoverflow.com/users/3429323",
"pm_score": 0,
"selected": false,
"text": "while (true)"
},
{
"answer_id": 74467100,
"author": "Johan Mattsson",
"author_id": 1738290,
"author_profile": "https://Stackoverflow.com/users/1738290",
"pm_score": 0,
"selected": false,
"text": " \"target\": \"es2015\"\n"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74464292",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1738290/"
] |
74,464,304
|
<pre><code> @override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Title Text'),
),
body: SafeArea(
child: Stack(children: [
Column(
children: const [
Text('short content'),
],
),
const Positioned(
top: 100,
width: 320,
child: SizedBox(
width: 320,
height: 50,
child: ColoredBox(color: Colors.red),
))
])),
);
</code></pre>
<p><a href="https://i.stack.imgur.com/vx4ch.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/vx4ch.png" alt="enter image description here" /></a></p>
<p>I need the red box taking almost the entire screen with, but it flows the text width. How should I make this work?</p>
|
[
{
"answer_id": 74464535,
"author": "eamirho3ein",
"author_id": 10306997,
"author_profile": "https://Stackoverflow.com/users/10306997",
"pm_score": 1,
"selected": false,
"text": "Stack"
},
{
"answer_id": 74464592,
"author": "offworldwelcome",
"author_id": 11760076,
"author_profile": "https://Stackoverflow.com/users/11760076",
"pm_score": 1,
"selected": true,
"text": "Align"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74464304",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1389917/"
] |
74,464,310
|
<p>I need to parse out the "permission" substring from group names, however I have two patterns this group names follow:</p>
<pre class="lang-none prettyprint-override"><code>gcp-edp-platform-dgov-nonprod-oneil-(permission)
gcp-edp-platform-dgov-prod-atp-(permission).groups
</code></pre>
<p>Either the group name ends with the permission substring, or it ends with the permission substring.groups.</p>
<p>I need to be able to extract just the permission substring without grabbing the <code>.groups</code>.</p>
<p>I know just <code>.*-(.*)</code> get me everything after the last hyphen but it still grabs the .groups for the names that do have it. Can someone help me create a regex for this instance?</p>
|
[
{
"answer_id": 74464695,
"author": "Bohemian",
"author_id": 256196,
"author_profile": "https://Stackoverflow.com/users/256196",
"pm_score": 0,
"selected": false,
"text": "(?<=-)[^-.]+(?!.*-)\n"
},
{
"answer_id": 74523675,
"author": "Wiktor Stribiżew",
"author_id": 3832970,
"author_profile": "https://Stackoverflow.com/users/3832970",
"pm_score": 2,
"selected": true,
"text": ".*-(.*?)(?:[.]groups)?$\n"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74464310",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17928364/"
] |
74,464,351
|
<p>I am new to integer optimization. I am trying to solve the following large (although not that large) binary linear optimization problem:</p>
<p>max_{x} x_1+x_2+...+x_n</p>
<p>subject to: A*x <= b ; x_i is binary for all i=1,...,n</p>
<p>As you can see,</p>
<p>. the control variable is a vector x of lengh, say, n=150; x_i is binary for all i=1,...,n</p>
<p>. I want to maximize the sum of the x_i's</p>
<p>. in the constraint, A is an nxn matrix and b is an nx1 vector. So I have n=150 linear inequality constraints.</p>
<p><strong>I want to obtain a certain number of solutions, NS. Say, NS=100.</strong> (I <em><strong>know</strong></em> there is more than one solution, and there are potentially millions of them.)</p>
<p>I am using Google's OR-Tools for Python. I was able to write the problem and to obtain one solution. I have tried many different ways to obtain <em><strong>more</strong></em> solutions after that, but I just couldn't. For example:</p>
<ol>
<li>I tried using the SCIP solver, and then I used the value of the objective function at the optimum, call it V, to <em>add another</em> constraint, x_1+x_2+...+x_n >= V, on top of the original "Ax<=b," and then used the CP-SAT solver to find NS <em>feasible</em> vectors (I followed the instructions in <a href="https://developers.google.com/optimization/cp/cp_tasks" rel="nofollow noreferrer">this guide</a>). There is no optimization in this second step, just a quest for feasibility. This didn't work: the solver produced N replicas of the same vector. Still, when asked for the number of solutions found, it misleadingly replies that solution_printer.solution_count() is equal to NS. Here's a snippet of the code that I used:</li>
</ol>
<pre><code># Define the constraints (A and b are lists)
for j in range(n):
constraint_expr = [int(A[j][l])*x[l] for l in range(n)]
model.Add(sum(constraint_expr) <= int(b[j][0]))
V = 112
constraint_obj_val = [-x[l] for l in range(n)]
model.Add(sum(constraint_obj_val) <= -V)
# Call the solver:
solver = cp_model.CpSolver()
solution_printer = VarArraySolutionPrinterWithLimit(x, NS)
solver.parameters.enumerate_all_solutions = True
status = solver.Solve(model, solution_printer)
</code></pre>
<ol start="2">
<li>I tried using the SCIP solver and then using solver.NextSolution(), but every time I was using this command, the algorithm would produce a vector that was less and less optimal every time: the first one corresponded to a value of, say, V=112 (the optimal one!); the second vector corresponded to a value of 111; the third one, to 108; fourth to sixth, to 103; etc.</li>
</ol>
<p>My question is, unfortunately, a bit vague, but here it goes: what's the best way to obtain more than one <em><strong>solution</strong></em> to my optimization problem?</p>
<p>Please let me know if I'm not being clear enough or if you need more/other chunks of the code, etc. This is my first time posting a question here :)</p>
<p>Thanks in advance.</p>
|
[
{
"answer_id": 74465150,
"author": "watchdogs132",
"author_id": 18823783,
"author_profile": "https://Stackoverflow.com/users/18823783",
"pm_score": 0,
"selected": false,
"text": "solver->SetSolverSpecificParametersAsString(\"PoolSearchMode=2\"); // or-tools [Gurobi]\n"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74464351",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20519407/"
] |
74,464,396
|
<p>Let's suppose a file with following content named file.txt is used as a source.</p>
<pre><code>12345
ABC-12
XCD-13
BCD-12345
Some text on this line
*+-%&
</code></pre>
<p>What I am looking for with sed would be to get only ABC-12 line and remove hyphen so the desired output would be <code>ABC12</code></p>
<p>So far I have been able to get numbers only with following command:</p>
<pre><code>sed "s/[^0-9]//g" file.txt
</code></pre>
<p>Output</p>
<pre><code>12345
12
13
12345
</code></pre>
<p>I got the closest with grep with command:
<code>grep -oP 'ABC-\b\d{2}\b' file.txt</code></p>
<p>Output</p>
<pre><code>ABC-12
</code></pre>
<p>How should this be constructed with sed and also hyphen removed from the output?</p>
<p>Note also that numbers after ABC can be considered as changing like a variable so the idea would be to search for "ABC and numbers following it after hyphen" instead of searching for "ABC-12" directly.</p>
|
[
{
"answer_id": 74464573,
"author": "anubhava",
"author_id": 548225,
"author_profile": "https://Stackoverflow.com/users/548225",
"pm_score": 2,
"selected": true,
"text": "ABC"
},
{
"answer_id": 74464842,
"author": "Wiktor Stribiżew",
"author_id": 3832970,
"author_profile": "https://Stackoverflow.com/users/3832970",
"pm_score": 0,
"selected": false,
"text": "sed -En '/^.*(ABC)-([0-9]+).*/{s//\\1\\2/p;q}'\n"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74464396",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12041338/"
] |
74,464,415
|
<p>Okay so my current code works, but I have a feeling it's incredibly inefficient. Essentially, I need to evaluate if a String contains the letters of a String that is shorter or the same length as the first one. (Imagine trying to use the letters that exist in Word A to spell a new word Word B. Word B can be shorter than Word A or the same length but has to only use the letters from Word A and cannot use the same letter twice.)</p>
<p>My current solution is to sort both strings into an array, then index each letter in the Word B array, check if it appears in the Word A array, then remove that character from the Word A array.</p>
<pre><code>let wordOne = "battle"
let wordTwo = "table"
var wordOneSorted = wordOne.sorted()
var wordTwoSorted = wordTwo.sorted()
for letter in wordTwoSorted {
if wordOneSorted.contains(letter) {
print("Valid Letter")
let idx = wordOneSorted.firstIndex(of:letter)
wordOneSorted.remove(at: idx!)
} else {
print("Invalid Letter")
}
}
</code></pre>
<p>Prints:
Valid Letter
Valid Letter
Valid Letter
Valid Letter
Valid Letter</p>
<p>This works but it feels clunky and I wanted to see if I'm making a simple task more complicated than I need it to be. I only need an evaluation of the entire comparison, if all the leters work than "True" and if at least one is invalid than "False".</p>
<p>Thank you!</p>
|
[
{
"answer_id": 74464858,
"author": "Larme",
"author_id": 1801544,
"author_profile": "https://Stackoverflow.com/users/1801544",
"pm_score": 0,
"selected": false,
"text": "[Character: (Int, Int)]"
},
{
"answer_id": 74465078,
"author": "HangarRash",
"author_id": 20287183,
"author_profile": "https://Stackoverflow.com/users/20287183",
"pm_score": 2,
"selected": false,
"text": "let wordOne = \"battle\"\nlet wordTwo = \"table\"\n\nvar letters = wordOne\nvar good = true\nfor letter in wordTwo {\n if letters.contains(letter) {\n let idx = letters.firstIndex(of:letter)\n letters.remove(at: idx!)\n } else {\n good = false\n break\n }\n}\nprint(good ? \"Good\" : \"Bad\")\n"
},
{
"answer_id": 74466243,
"author": "akjndklskver",
"author_id": 5318223,
"author_profile": "https://Stackoverflow.com/users/5318223",
"pm_score": 0,
"selected": false,
"text": "func isContained(in word1: String, word word2: String) -> Bool {\n \n var word1Sorted = word1.sorted()\n var word2Sorted = word2.sorted()\n \n var c1 = word1Sorted.count - 1\n var c2 = word2Sorted.count - 1\n \n while c2 >= 0 && c1 >= 0 {\n \n if word1Sorted[c1] == word2Sorted[c2] {\n // Found a match - advance to next character in both arrays\n print(\"Valid Letter \\(word2Sorted[c2])\")\n c1 -= 1\n c2 -= 1\n } else if word1Sorted[c1] > word2Sorted[c2] {\n // Ignoring a letter present in wordOne, but not wordTwo\n print(\"Skipping Letter \\(word1Sorted[c1])\")\n c1 -= 1\n } else { // wordOneSorted[c1] < wordTwoSorted[c2]\n // the letter was not found in wordOneSorted - no need to continue\n print(\"Invalid Letter \\(word2Sorted[c2])\")\n return false\n }\n }\n \n // If we finished the loop then the result is:\n // - We've got to the beginning of word2, meaning we found all letters of it in word1\n // - Or we've got to the beginning of word1, meaning not all letters of word 2 were found\n return c2 < 0\n}\n"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74464415",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17527370/"
] |
74,464,450
|
<p>I am already using Prisma as an ORM for a Postgres DB. I need to run a simple raw query on a SQL Server DB. I do not need to use any of the ORM features like the Prisma schema, migrations, etc. Is it possible to do with Prisma? I am trying to minimize dependencies.</p>
|
[
{
"answer_id": 74464858,
"author": "Larme",
"author_id": 1801544,
"author_profile": "https://Stackoverflow.com/users/1801544",
"pm_score": 0,
"selected": false,
"text": "[Character: (Int, Int)]"
},
{
"answer_id": 74465078,
"author": "HangarRash",
"author_id": 20287183,
"author_profile": "https://Stackoverflow.com/users/20287183",
"pm_score": 2,
"selected": false,
"text": "let wordOne = \"battle\"\nlet wordTwo = \"table\"\n\nvar letters = wordOne\nvar good = true\nfor letter in wordTwo {\n if letters.contains(letter) {\n let idx = letters.firstIndex(of:letter)\n letters.remove(at: idx!)\n } else {\n good = false\n break\n }\n}\nprint(good ? \"Good\" : \"Bad\")\n"
},
{
"answer_id": 74466243,
"author": "akjndklskver",
"author_id": 5318223,
"author_profile": "https://Stackoverflow.com/users/5318223",
"pm_score": 0,
"selected": false,
"text": "func isContained(in word1: String, word word2: String) -> Bool {\n \n var word1Sorted = word1.sorted()\n var word2Sorted = word2.sorted()\n \n var c1 = word1Sorted.count - 1\n var c2 = word2Sorted.count - 1\n \n while c2 >= 0 && c1 >= 0 {\n \n if word1Sorted[c1] == word2Sorted[c2] {\n // Found a match - advance to next character in both arrays\n print(\"Valid Letter \\(word2Sorted[c2])\")\n c1 -= 1\n c2 -= 1\n } else if word1Sorted[c1] > word2Sorted[c2] {\n // Ignoring a letter present in wordOne, but not wordTwo\n print(\"Skipping Letter \\(word1Sorted[c1])\")\n c1 -= 1\n } else { // wordOneSorted[c1] < wordTwoSorted[c2]\n // the letter was not found in wordOneSorted - no need to continue\n print(\"Invalid Letter \\(word2Sorted[c2])\")\n return false\n }\n }\n \n // If we finished the loop then the result is:\n // - We've got to the beginning of word2, meaning we found all letters of it in word1\n // - Or we've got to the beginning of word1, meaning not all letters of word 2 were found\n return c2 < 0\n}\n"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74464450",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12636797/"
] |
74,464,464
|
<p>I want to link to specific part of the page, which is divided in 2 columns, but whenever I click on the anchor link it scrolls the whole page and also the column with content.</p>
<p>Here's an example of my layout: <a href="https://codepen.io/Xoouu/pen/KKeXMxr?editors=1100" rel="nofollow noreferrer">CodePen</a></p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
overflow-x: hidden;
overflow-y: scroll;
}
.container {
height: 100vh;
width: 100vw;
display: grid;
grid-template-columns: 1fr;
grid-template-rows: 1fr;
}
.header {
border-bottom: 1px solid lightgrey;
}
.sidebar {
border-right: 1px solid lightgrey;
}
.footer {
border-top: 1px solid lightgrey;
}
.body {
display: grid;
grid-template-columns: 1fr 3fr;
overflow: hidden;
}
.content {
overflow-y: scroll;
padding: 20px;
}
p {
max-width: 600px;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
<div class="header">.header</div>
<div class="body">
<div class="sidebar"><a href="#test">asdas</a></div>
<div class="content">
<p>.content</p>
<p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Phasellus hendrerit. Pellentesque aliquet nibh nec urna. In nisi neque, aliquet vel, dapibus id, mattis vel, nisi. Sed pretium, ligula sollicitudin laoreet viverra, tortor libero sodales
leo, eget blandit nunc tortor eu nibh. Nullam mollis. Ut justo. Suspendisse potenti.
<p>
<p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Phasellus hendrerit. Pellentesque aliquet nibh nec urna. In nisi neque, aliquet vel, dapibus id, mattis vel, nisi. Sed pretium, ligula sollicitudin laoreet viverra, tortor libero sodales
leo, eget blandit nunc tortor eu nibh. Nullam mollis. Ut justo. Suspendisse potenti.
<p>
<p>Sed egestas, ante et vulputate volutpat, eros pede semper est, vitae luctus metus libero eu augue. Morbi purus libero, faucibus adipiscing, commodo quis, gravida id, est. Sed lectus. Praesent elementum hendrerit tortor. Sed semper lorem
at felis. Vestibulum volutpat, lacus a ultrices sagittis, mi neque euismod dui, eu pulvinar nunc sapien ornare nisl. Phasellus pede arcu, dapibus eu, fermentum et, dapibus sed, urna.</p>
<p>Morbi interdum mollis sapien. Sed ac risus. Phasellus lacinia, magna a ullamcorper laoreet, lectus arcu pulvinar risus, vitae facilisis libero dolor a purus. Sed vel lacus. Mauris nibh felis, adipiscing varius, adipiscing in, lacinia vel,
tellus. Suspendisse ac urna. Etiam pellentesque mauris ut lectus. Nunc tellus ante, mattis eget, gravida vitae, ultricies ac, leo. Integer leo pede, ornare a, lacinia eu, vulputate vel, nisl.</p>
<p>Suspendisse mauris. Fusce accumsan mollis eros. Pellentesque a diam sit amet mi ullamcorper vehicula. Integer adipiscing risus a sem. Nullam quis massa sit amet nibh viverra malesuada. Nunc sem lacus, accumsan quis, faucibus non, congue
vel, arcu. Ut scelerisque hendrerit tellus. Integer sagittis. Vivamus a mauris eget arcu gravida tristique. Nunc iaculis mi in ante. Vivamus imperdiet nibh feugiat est.</p>
<p>Ut convallis, sem sit amet interdum consectetuer, odio augue aliquam leo, nec dapibus tortor nibh sed augue. Integer eu magna sit amet metus fermentum posuere. Morbi sit amet nulla sed dolor elementum imperdiet. Quisque fermentum. Cum sociis
natoque penatibus et magnis xdis parturient montes, nascetur ridiculus mus. Pellentesque adipiscing eros ut libero. Ut condimentum mi vel tellus. Suspendisse laoreet. Fusce ut est sed dolor gravida convallis. Morbi vitae ante. Vivamus
ultrices luctus nunc. Suspendisse et dolor. Etiam dignissim. Proin malesuada adipiscing lacus. Donec metus. Curabitur gravida</p>
<p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Phasellus hendrerit. Pellentesque aliquet nibh nec urna. In nisi neque, aliquet vel, dapibus id, mattis vel, nisi. Sed pretium, ligula sollicitudin laoreet viverra, tortor libero
sodales leo, eget blandit nunc tortor eu nibh. Nullam mollis. Ut justo. Suspendisse potenti.
<p>
<p>Sed egestas, ante et vulputate volutpat, eros pede semper est, vitae luctus metus libero eu augue. Morbi purus libero, faucibus adipiscing, commodo quis, gravida id, est. Sed lectus. Praesent elementum hendrerit tortor. Sed semper lorem
at felis. Vestibulum volutpat, lacus a ultrices sagittis, mi neque euismod dui, eu pulvinar nunc sapien ornare nisl. Phasellus pede arcu, dapibus eu, fermentum et, dapibus sed, urna.</p>
<p>Morbi interdum mollis sapien. Sed ac risus. Phasellus lacinia, magna a ullamcorper laoreet, lectus arcu pulvinar risus, vitae facilisis libero dolor a purus. Sed vel lacus. Mauris nibh felis, adipiscing varius, adipiscing in, lacinia
vel, tellus. Suspendisse ac urna. Etiam pellentesque mauris ut lectus. Nunc tellus ante, mattis eget, gravida vitae, ultricies ac, leo. Integer leo pede, ornare a, lacinia eu, vulputate vel, nisl.</p>
<p>Suspendisse mauris. Fusce accumsan mollis eros. Pellentesque a diam sit amet mi ullamcorper vehicula. Integer adipiscing risus a sem. Nullam quis massa sit amet nibh viverra malesuada. Nunc sem lacus, accumsan quis, faucibus non, congue
vel, arcu. Ut scelerisque hendrerit tellus. Integer sagittis. Vivamus a mauris eget arcu gravida tristique. Nunc iaculis mi in ante. Vivamus imperdiet nibh feugiat est.</p>
<p>Ut convallis, sem sit amet interdum consectetuer, odio augue aliquam leo, nec dapibus tortor nibh sed augue. Integer eu magna sit amet metus fermentum posuere. Morbi sit amet nulla sed dolor elementum imperdiet. Quisque fermentum. Cum
sociis natoque penatibus et magnis xdis parturient montes, nascetur ridiculus mus. Pellentesque adipiscing eros ut libero. Ut condimentum mi vel tellus. Suspendisse laoreet. Fusce ut est sed dolor gravida convallis. Morbi vitae ante.
Vivamus ultrices luctus nunc. Suspendisse et dolor. Etiam dignissim. Proin malesuada adipiscing lacus. Donec metus. Curabitur gravida</p>
<p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Phasellus hendrerit. Pellentesque aliquet nibh nec urna. In nisi neque, aliquet vel, dapibus id, mattis vel, nisi. Sed pretium, ligula sollicitudin laoreet viverra, tortor libero
sodales leo, eget blandit nunc tortor eu nibh. Nullam mollis. Ut justo. Suspendisse potenti.
<p>
<p>Sed egestas, ante et vulputate volutpat, eros pede semper est, vitae luctus metus libero eu augue. Morbi purus libero, faucibus adipiscing, commodo quis, gravida id, est. Sed lectus. Praesent elementum hendrerit tortor. Sed semper
lorem at felis. Vestibulum volutpat, lacus a ultrices sagittis, mi neque euismod dui, eu pulvinar nunc sapien ornare nisl. Phasellus pede arcu, dapibus eu, fermentum et, dapibus sed, urna.</p>
<p>Morbi interdum mollis sapien. Sed ac risus. Phasellus lacinia, magna a ullamcorper laoreet, lectus arcu pulvinar risus, vitae facilisis libero dolor a purus. Sed vel lacus. Mauris nibh felis, adipiscing varius, adipiscing in, lacinia
vel, tellus. Suspendisse ac urna. Etiam pellentesque mauris ut lectus. Nunc tellus ante, mattis eget, gravida vitae, ultricies ac, leo. Integer leo pede, ornare a, lacinia eu, vulputate vel, nisl.</p>
<p>Suspendisse mauris. Fusce accumsan mollis eros. Pellentesque a diam sit amet mi ullamcorper vehicula. Integer adipiscing risus a sem. Nullam quis massa sit amet nibh viverra malesuada. Nunc sem lacus, accumsan quis, faucibus non,
congue vel, arcu. Ut scelerisque hendrerit tellus. Integer sagittis. Vivamus a mauris eget arcu gravida tristique. Nunc iaculis mi in ante. Vivamus imperdiet nibh feugiat est.</p>
<p>Ut convallis, sem sit amet interdum consectetuer, odio augue aliquam leo, nec dapibus tortor nibh sed augue. Integer eu magna sit amet metus fermentum posuere. Morbi sit amet nulla sed dolor elementum imperdiet. Quisque fermentum.
Cum sociis natoque penatibus et magnis xdis parturient montes, nascetur ridiculus mus. Pellentesque adipiscing eros ut libero. Ut condimentum mi vel tellus. Suspendisse laoreet. Fusce ut est sed dolor gravida convallis. Morbi vitae
ante. Vivamus ultrices luctus nunc. Suspendisse et dolor. Etiam dignissim. Proin malesuada adipiscing lacus. Donec metus. Curabitur gravida</p>
<p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Phasellus hendrerit. Pellentesque aliquet nibh nec urna. In nisi neque, aliquet vel, dapibus id, mattis vel, nisi. Sed pretium, ligula sollicitudin laoreet viverra, tortor
libero sodales leo, eget blandit nunc tortor eu nibh. Nullam mollis. Ut justo. Suspendisse potenti.
<p>
<p>Sed egestas, ante et vulputate volutpat, eros pede semper est, vitae luctus metus libero eu augue. Morbi purus libero, faucibus adipiscing, commodo quis, gravida id, est. Sed lectus. Praesent elementum hendrerit tortor. Sed semper
lorem at felis. Vestibulum volutpat, lacus a ultrices sagittis, mi neque euismod dui, eu pulvinar nunc sapien ornare nisl. Phasellus pede arcu, dapibus eu, fermentum et, dapibus sed, urna.</p>
<p>Morbi interdum mollis sapien. Sed ac risus. Phasellus lacinia, magna a ullamcorper laoreet, lectus arcu pulvinar risus, vitae facilisis libero dolor a purus. Sed vel lacus. Mauris nibh felis, adipiscing varius, adipiscing in,
lacinia vel, tellus. Suspendisse ac urna. Etiam pellentesque mauris ut lectus. Nunc tellus ante, mattis eget, gravida vitae, ultricies ac, leo. Integer leo pede, ornare a, lacinia eu, vulputate vel, nisl.</p>
<p>Suspendisse mauris. Fusce accumsan mollis eros. Pellentesque a diam sit amet mi ullamcorper vehicula. Integer adipiscing risus a sem. Nullam quis massa sit amet nibh viverra malesuada. Nunc sem lacus, accumsan quis, faucibus
non, congue vel, arcu. Ut scelerisque hendrerit tellus. Integer sagittis. Vivamus a mauris eget arcu gravida tristique. Nunc iaculis mi in ante. Vivamus imperdiet nibh feugiat est.</p>
<p>Ut convallis, sem sit amet interdum consectetuer, odio augue aliquam leo, nec dapibus tortor nibh sed augue. Integer eu magna sit amet metus fermentum posuere. Morbi sit amet nulla sed dolor elementum imperdiet. Quisque fermentum.
Cum sociis natoque penatibus et magnis xdis parturient montes, nascetur ridiculus mus. Pellentesque adipiscing eros ut libero. Ut condimentum mi vel tellus. Suspendisse laoreet. Fusce ut est sed dolor gravida convallis. Morbi
vitae ante. Vivamus ultrices luctus nunc. Suspendisse et dolor. Etiam dignissim. Proin malesuada adipiscing lacus. Donec metus. Curabitur gravida</p>
<p>Sed egestas, ante et vulputate volutpat, eros pede semper est, vitae luctus metus libero eu augue. Morbi purus libero, faucibus adipiscing, commodo quis, gravida id, est. Sed lectus. Praesent elementum hendrerit tortor. Sed semper
lorem at felis. Vestibulum volutpat, lacus a ultrices sagittis, mi neque euismod dui, eu pulvinar nunc sapien ornare nisl. Phasellus pede arcu, dapibus eu, fermentum et, dapibus sed, urna.</p>
<p>Morbi interdum mollis sapien. Sed ac risus. Phasellus lacinia, magna a ullamcorper laoreet, lectus arcu pulvinar risus, vitae facilisis libero dolor a purus. Sed vel lacus. Mauris nibh felis, adipiscing varius, adipiscing in,
lacinia vel, tellus. Suspendisse ac urna. Etiam pellentesque mauris ut lectus. Nunc tellus ante, mattis eget, gravida vitae, ultricies ac, leo. Integer leo pede, ornare a, lacinia eu, vulputate vel, nisl.</p>
<p>Suspendisse mauris. Fusce accumsan mollis eros. Pellentesque a diam sit amet mi ullamcorper vehicula. Integer adipiscing risus a sem. Nullam quis massa sit amet nibh viverra malesuada. Nunc sem lacus, accumsan quis, faucibus
non, congue vel, arcu. Ut scelerisque hendrerit tellus. Integer sagittis. Vivamus a mauris eget arcu gravida tristique. Nunc iaculis mi in ante. Vivamus imperdiet nibh feugiat est.</p>
<p>Ut convallis, sem sit amet interdum consectetuer, odio augue aliquam leo, nec dapibus tortor nibh sed augue. Integer eu magna sit amet metus fermentum posuere. Morbi sit amet nulla sed dolor elementum imperdiet. Quisque fermentum.
Cum sociis natoque penatibus et magnis xdis parturient montes, nascetur ridiculus mus. Pellentesque adipiscing eros ut libero. Ut condimentum mi vel tellus. Suspendisse laoreet. Fusce ut est sed dolor gravida convallis. Morbi
vitae ante. Vivamus ultrices luctus nunc. Suspendisse et dolor. Etiam dignissim. Proin malesuada adipiscing lacus. Donec metus. Curabitur gravida</p>
<h1 id="test">TESTE</h1>
</div>
</div>
<div class="footer">.footer</div>
</div></code></pre>
</div>
</div>
</p>
<p>What I want to do is to only scroll the column with content and not the whole page. I'm fine if it is only possible with JavaScript and just really want to know if that is possible.</p>
|
[
{
"answer_id": 74464681,
"author": "McRaZick",
"author_id": 10930787,
"author_profile": "https://Stackoverflow.com/users/10930787",
"pm_score": 2,
"selected": true,
"text": "body {\n overflow: hidden;\n margin: 0;\n height: 100%;\n}\n"
},
{
"answer_id": 74464736,
"author": "Igor Ponso",
"author_id": 14623002,
"author_profile": "https://Stackoverflow.com/users/14623002",
"pm_score": 0,
"selected": false,
"text": ".container"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74464464",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19335865/"
] |
74,464,469
|
<p>I just need to click the load more button once to reveal a bunch more information so that I can scrape more HTML than what is loaded.</p>
<p>The following "should" go to <code>github.com/topics</code> and find the one and only button element and click it one time.</p>
<pre><code>from selenium import webdriver
from selenium.webdriver.common.by import By
import time
driver = webdriver.Edge()
driver.get("https://github.com/topics")
time.sleep(5)
btn = driver.find_element(By.TAG_NAME, "button")
btn.click()
time.sleep(3)
driver.quit()
</code></pre>
<p>I'm told <code>Message: element not interactable</code> so I'm obviously doing something wrong but I'm not sure what.</p>
|
[
{
"answer_id": 74464681,
"author": "McRaZick",
"author_id": 10930787,
"author_profile": "https://Stackoverflow.com/users/10930787",
"pm_score": 2,
"selected": true,
"text": "body {\n overflow: hidden;\n margin: 0;\n height: 100%;\n}\n"
},
{
"answer_id": 74464736,
"author": "Igor Ponso",
"author_id": 14623002,
"author_profile": "https://Stackoverflow.com/users/14623002",
"pm_score": 0,
"selected": false,
"text": ".container"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74464469",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20522191/"
] |
74,464,471
|
<p>I got most of the code down but I am having issues getting the string to space back out after making the first letter of each word uppercase</p>
<p>here's what I have so far:</p>
<p>message = input('Write a short message.')</p>
<p>new_message = message.split()</p>
<p>glue = ""</p>
<p>for item in new_message:</p>
<p>glue += item[0].upper() + item[1:]</p>
<p>print(glue)</p>
|
[
{
"answer_id": 74464499,
"author": "Hamall",
"author_id": 9025143,
"author_profile": "https://Stackoverflow.com/users/9025143",
"pm_score": 1,
"selected": false,
"text": "message.capitalize()\n"
},
{
"answer_id": 74464684,
"author": "Iulian St",
"author_id": 19333216,
"author_profile": "https://Stackoverflow.com/users/19333216",
"pm_score": 0,
"selected": false,
"text": " message = input('Write a short message.')\n \n new_message = message.split()\n cap_message = [x.capitalize() for x in new_message]\n print(cap_message)\n"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74464471",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20473614/"
] |
74,464,475
|
<p>I have done KMeans clusters and now I need to analyse each individual cluster. For example look at cluster 1 and see what clients are on it and make conclusions.</p>
<pre><code>dfRFM['idcluster'] = num_cluster
dfRFM.head()
idcliente Recencia Frecuencia Monetario idcluster
1 3 251 44 -90.11 0
2 8 1011 44 87786.44 2
6 88 537 36 8589.57 0
7 98 505 2 -179.00 0
9 156 11 15 35259.50 0
</code></pre>
<p>How do I group so I only see results from lets say idcluster 0 and sort by lets say "Monetario". Thanks!</p>
|
[
{
"answer_id": 74464499,
"author": "Hamall",
"author_id": 9025143,
"author_profile": "https://Stackoverflow.com/users/9025143",
"pm_score": 1,
"selected": false,
"text": "message.capitalize()\n"
},
{
"answer_id": 74464684,
"author": "Iulian St",
"author_id": 19333216,
"author_profile": "https://Stackoverflow.com/users/19333216",
"pm_score": 0,
"selected": false,
"text": " message = input('Write a short message.')\n \n new_message = message.split()\n cap_message = [x.capitalize() for x in new_message]\n print(cap_message)\n"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74464475",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13377260/"
] |
74,464,481
|
<p>Assuming I have the following two objects</p>
<pre><code>foo = {
a: 10
b: 'hello'
c: 'world'
}
bar = {
a:5
b: null
c: null
d: "This is not in foo"
}
</code></pre>
<p>I would like to have an operation which would do the equivalent of below operation but without having to specify it for each member.</p>
<pre><code> bar.a ??= foo.a
bar.b ??= foo.b
bar.c ??= foo.c
console.log(bar) // {a:5, b:'hello', c:'world', d:'This is not in foo'
</code></pre>
<p>Essentially: For each member of <code>bar</code>, if it is <code>nullish</code> take the value in <code>foo</code>. Leave all members which exist in <code>foo</code> but not in <code>bar</code> in peace</p>
<p>How would I go about this? I have tried to search a solution using destructuring in some way but with no success...</p>
|
[
{
"answer_id": 74464499,
"author": "Hamall",
"author_id": 9025143,
"author_profile": "https://Stackoverflow.com/users/9025143",
"pm_score": 1,
"selected": false,
"text": "message.capitalize()\n"
},
{
"answer_id": 74464684,
"author": "Iulian St",
"author_id": 19333216,
"author_profile": "https://Stackoverflow.com/users/19333216",
"pm_score": 0,
"selected": false,
"text": " message = input('Write a short message.')\n \n new_message = message.split()\n cap_message = [x.capitalize() for x in new_message]\n print(cap_message)\n"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74464481",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4923949/"
] |
74,464,503
|
<p>I have quaternion values <em>q</em> available.</p>
<p>These are correct, because they align the object correctly in the ROS RVIZ tool.</p>
<p>I now want to get a heading value from these values.</p>
<p>My idea was to calculate the Yaw value first and then do a Radian to Degree conversion to get the heading.
However, this works only conditionally, as soon as the object moves in the direction of NE everything is correct and the correct heading value is output. The same applies for the direction SW. However, when the object moves in the NW direction, I get a heading value of 135 degrees, exactly the opposite direction. Exactly the same applies to the direction SE.</p>
<p>My conversions look as follows:</p>
<pre><code>double heading = atan2(2.0*(q.y*q.z + q.w*q.x), -1.0 +2.0 * (q.w*q.w + q.x*q.x)) * 180 / M_PI;
if(heading < 0){
heading +=360;
}
</code></pre>
<p>I got the formula from:
<a href="https://math.stackexchange.com/questions/3496329/map-quaternion-to-heading-pitch-roll-using-different-axis">https://math.stackexchange.com/questions/3496329/map-quaternion-to-heading-pitch-roll-using-different-axis</a></p>
<p>My Question is:
What I'm doing wrong.. Why are NW and SE swapped?</p>
|
[
{
"answer_id": 74464861,
"author": "jonasmike",
"author_id": 4385834,
"author_profile": "https://Stackoverflow.com/users/4385834",
"pm_score": 1,
"selected": false,
"text": "siny = +2.0 * (q.w * q.z + q.y * q.x);\ncosy = +1.0 - 2.0 * (q.x * q.x + q.z * q.z);\nheading = atan2(siny, cosy); // in radians\n"
},
{
"answer_id": 74465632,
"author": "BTables",
"author_id": 11936229,
"author_profile": "https://Stackoverflow.com/users/11936229",
"pm_score": 1,
"selected": false,
"text": "getRPY()"
},
{
"answer_id": 74472884,
"author": "Nicooost",
"author_id": 9093743,
"author_profile": "https://Stackoverflow.com/users/9093743",
"pm_score": 1,
"selected": true,
"text": "double heading = (atan2(2.0*(q.y*q.z + q.w*q.x), -1.0 +2.0 * (q.w*q.w + q.x*q.x)) * 180 / M_PI) - 90;\nif(heading < 0){\n heading +=360;\n}\nheading = -heading + 360\n"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74464503",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9093743/"
] |
74,464,541
|
<p>I made a minimal example to describe my problem using the concept of player using items in a game (which makes my problem easier to understand).</p>
<p>My problematic is the following. Let's say I have to store items and the player holding them in my database.</p>
<p><a href="https://i.stack.imgur.com/B8Drl.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/B8Drl.png" alt="enter image description here" /></a></p>
<p>I didn't show it on the image but a player could hold no item but it's really important for my problem.</p>
<p>I translated that into :</p>
<p><a href="https://i.stack.imgur.com/FK0FO.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/FK0FO.png" alt="enter image description here" /></a></p>
<p>Which gives the two following tables (with PK_ and #FK) :</p>
<p><a href="https://i.stack.imgur.com/l4Ra6.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/l4Ra6.png" alt="enter image description here" /></a></p>
<p>In my example I can then fill them as such :</p>
<p><a href="https://i.stack.imgur.com/NLtXB.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/NLtXB.png" alt="enter image description here" /></a></p>
<p>By doing :</p>
<p><a href="https://i.stack.imgur.com/TAbOu.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/TAbOu.png" alt="enter image description here" /></a></p>
<p>Now, I want any player to have a "favorite" item, so I want to add a foreign key #item_id in the table Player but I want to make sure this new value refers to an item being hold by the right player in the Item table. How can I add a (check?) constraint to my table declarations so that condition is always true to ensure data integrity between my two tables? I don't think I can solve this by creating a third table since it's still a 1n cardinality. Also I don't want to ALTER the table I want to CREATE, since my database is not yet to be deployed.</p>
|
[
{
"answer_id": 74464755,
"author": "Progman",
"author_id": 286934,
"author_profile": "https://Stackoverflow.com/users/286934",
"pm_score": 0,
"selected": false,
"text": "isFavorite"
},
{
"answer_id": 74465087,
"author": "Progman",
"author_id": 286934,
"author_profile": "https://Stackoverflow.com/users/286934",
"pm_score": 2,
"selected": true,
"text": "player"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74464541",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15651162/"
] |
74,464,565
|
<p>I have the following dataframe (constructed as below):</p>
<pre><code>import pandas as pd
df = pd.DataFrame(data=None,columns=pd.MultiIndex.from_product([['Apple','Banana','Orange'],['Data1','Data2','Data3']]),index=[1])
df.loc[:,:] = [1,2,3,4,5,6,7,8,9]
>>> Apple Banana Orange
Data1 Data2 Data3 Data1 Data2 Data3 Data1 Data2 Data3
1 1 2 3 4 5 6 7 8 9
</code></pre>
<p>I want to transform this dataframe into the following dataframe (constructed as below):</p>
<pre><code>df = pd.DataFrame(data=[[1,2,3],[4,5,6],[7,8,9]],columns=['Data1','Data2','Data3'],index=['Apple','Banana','Orange'])
>>> Data1 Data2 Data3
Apple 1 2 3
Banana 4 5 6
Orange 7 8 9
</code></pre>
<p>I am trying to find the most pythonic way to make this transformation! I have looked into transformations, swapping axes etc... but not sure if this is the right route to take. I want to avoid having to rebuild the dataframe, but rather to just transform it with one or as few lines of code as possible. Thanks!</p>
<p>Also! As a side note, I could not figure out how to input the data directly into the first dataframe at the time of construction (as you can see I had to add it afterwards). What structure should this data take in order to input it directly at the time of construction. I tried multiple variations of lists and lists of lists etc... Thanks!</p>
|
[
{
"answer_id": 74465485,
"author": "MDR",
"author_id": 9192284,
"author_profile": "https://Stackoverflow.com/users/9192284",
"pm_score": 2,
"selected": true,
"text": "import pandas as pd\n\ndf = pd.DataFrame(data=None,columns=pd.MultiIndex.from_product([['Apple','Banana','Orange'],['Data1','Data2','Data3']]),index=[1])\ndf.loc[:,:] = [1,2,3,4,5,6,7,8,9]\n\nprint(df, '\\n\\n')\n\ndf = df.T.unstack()\ndf.columns = df.columns.droplevel()\n\nprint(df, '\\n\\n')\n"
},
{
"answer_id": 74465882,
"author": "PieCot",
"author_id": 5359797,
"author_profile": "https://Stackoverflow.com/users/5359797",
"pm_score": 0,
"selected": false,
"text": "new_index = df.columns.levels[0]\nnew_columns = df.columns.levels[1]\n\nnew_df = pd.DataFrame(\n data=[[df.iloc[0][(n, c)] for c in new_columns] for n in new_index],\n index=pd.Index(new_index),\n columns=new_columns,\n)\n"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74464565",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9230013/"
] |
74,464,594
|
<p>this error is in udemy maximilian schwarzmuller's flutter course error.
this is the code: I have provided the string value still I getting nonnull string provided to text widget error in ('tx.title'),</p>
<pre><code>import 'package:flutter/material.dart';
import './transaction.dart';
void main() => runApp(MyWidget());
class MyWidget extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'flutter app',
home: MyHomePage(),
);
}
}
class MyHomePage extends StatelessWidget {
final List<Transaction> transactions = [
Transaction(
id: '01',
title: 'azeem',
amount: 90.98,
date: DateTime.now(),
),
Transaction(
id: '02',
title: 'azeem',
amount: 90.98,
date: DateTime.now(),
)
];
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Expense App'),
),
body: Column(
mainAxisAlignment: MainAxisAlignment.spaceAround,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Container(
width: double.infinity,
child: Card(
child: Text('Text_1'),
color: Colors.blue,
),
),
Column(
children: transactions.map((tx) {
return Card(
child: Text(tx.title),
);
}).toList(),
),
],
),
);
}
}
</code></pre>
<p>I have provided the string to this function but I am getting an error.</p>
<p><a href="https://i.stack.imgur.com/tAuIp.png" rel="nofollow noreferrer">enter image description here</a></p>
|
[
{
"answer_id": 74465485,
"author": "MDR",
"author_id": 9192284,
"author_profile": "https://Stackoverflow.com/users/9192284",
"pm_score": 2,
"selected": true,
"text": "import pandas as pd\n\ndf = pd.DataFrame(data=None,columns=pd.MultiIndex.from_product([['Apple','Banana','Orange'],['Data1','Data2','Data3']]),index=[1])\ndf.loc[:,:] = [1,2,3,4,5,6,7,8,9]\n\nprint(df, '\\n\\n')\n\ndf = df.T.unstack()\ndf.columns = df.columns.droplevel()\n\nprint(df, '\\n\\n')\n"
},
{
"answer_id": 74465882,
"author": "PieCot",
"author_id": 5359797,
"author_profile": "https://Stackoverflow.com/users/5359797",
"pm_score": 0,
"selected": false,
"text": "new_index = df.columns.levels[0]\nnew_columns = df.columns.levels[1]\n\nnew_df = pd.DataFrame(\n data=[[df.iloc[0][(n, c)] for c in new_columns] for n in new_index],\n index=pd.Index(new_index),\n columns=new_columns,\n)\n"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74464594",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17720978/"
] |
74,464,598
|
<p>A JDK 19 ShutdownOnFailure scope also allows for explicit cancelation of all tasks using the shutdown method.
How can I know if the scope has been shutdown?
The API includes an isShutdown method but it is private.</p>
<p>Here is some (incomplete) code just to illustrate a possible use, where a scope is canceled some time after starting by the owner calling shutdown.</p>
<p>I guess that after a join() I could issue another scope.fork() and check if if returns a future to a canceled task but that seems weird. Is that the way to go?</p>
<pre><code> ExecutorService executor = Executors.newCachedThreadPool();
try (StructuredTaskScope.ShutdownOnFailure scope = new StructuredTaskScope.ShutdownOnFailure()) {
Future<Integer> numOrders = scope.fork(Business::getNumItemsFromRequest);
Future<Double> price = scope.fork(Business::getPriceFromDB);
Business.sleepFor(500);
scope.shutdown(); // cancels all the scope tasks
//numOrders.cancel(true); // cancel just one task
scope.join(); // wait for all tasks
try {
scope.throwIfFailed();
// how would I know if scope was shutdown before all tasks completed?
System.out.println("Scope Completed Without Errors ( But possibly canceled ) ");
double amount = numOrders.get() * price.get();
</code></pre>
|
[
{
"answer_id": 74547554,
"author": "Michael Easter",
"author_id": 12704,
"author_profile": "https://Stackoverflow.com/users/12704",
"pm_score": 1,
"selected": false,
"text": "var result = \"error\";\n\ntry (var scope = new StructuredTaskScope.ShutdownOnFailure()) {\n var numOrders = scope.fork(() -> taskGetNumItemsFromRequest()); \n var price = scope.fork(() -> taskGetPriceFromDB());\n\n if (doShutdown) {\n scope.shutdown();\n }\n \n scope.join(); \n scope.throwIfFailed();\n\n result = numOrders.resultNow() + \" \" + price.resultNow();\n} catch (Exception ex) {\n if (ex != null) {\n System.err.println(\"caught ex: \" + ex.getClass());\n System.err.println(\"caught ex message: \" + ex.getMessage());\n }\n}\n"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74464598",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/889742/"
] |
74,464,611
|
<p>I am planning to move some elements from a list to the target container(say vector) for further processing. Is it safe to use <code>move_iterator</code> for moving to target And <code>erase</code> the <em>moved section</em> of the source container?</p>
<pre><code>#include<list>
#include<vector>
#include<iterator>
struct DataPoint {};
int main() {
std::list<Datapoint> d_data; // source
std::vector<Datapoint> v2; // target
v2.insert(v2.end(),
std::make_move_iterator(d_data.begin()),
std::make_move_iterator(d_data.begin() + size)
);
d_data.erase(d_data.begin(), d_data.begin() + size); // safe? necessary?
//...
//d_batch->addData(v2);
return 0;
}
</code></pre>
|
[
{
"answer_id": 74547554,
"author": "Michael Easter",
"author_id": 12704,
"author_profile": "https://Stackoverflow.com/users/12704",
"pm_score": 1,
"selected": false,
"text": "var result = \"error\";\n\ntry (var scope = new StructuredTaskScope.ShutdownOnFailure()) {\n var numOrders = scope.fork(() -> taskGetNumItemsFromRequest()); \n var price = scope.fork(() -> taskGetPriceFromDB());\n\n if (doShutdown) {\n scope.shutdown();\n }\n \n scope.join(); \n scope.throwIfFailed();\n\n result = numOrders.resultNow() + \" \" + price.resultNow();\n} catch (Exception ex) {\n if (ex != null) {\n System.err.println(\"caught ex: \" + ex.getClass());\n System.err.println(\"caught ex message: \" + ex.getMessage());\n }\n}\n"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74464611",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/805896/"
] |
74,464,617
|
<p>Can someone help me with my code and let me know what's wrong in it?</p>
<pre><code>def count_primes(nums):
count = 0
for num in range(2,nums+1):
if num%2!=0 or num%3!=0 or num%5!=0:
count+=1
return count
</code></pre>
|
[
{
"answer_id": 74547554,
"author": "Michael Easter",
"author_id": 12704,
"author_profile": "https://Stackoverflow.com/users/12704",
"pm_score": 1,
"selected": false,
"text": "var result = \"error\";\n\ntry (var scope = new StructuredTaskScope.ShutdownOnFailure()) {\n var numOrders = scope.fork(() -> taskGetNumItemsFromRequest()); \n var price = scope.fork(() -> taskGetPriceFromDB());\n\n if (doShutdown) {\n scope.shutdown();\n }\n \n scope.join(); \n scope.throwIfFailed();\n\n result = numOrders.resultNow() + \" \" + price.resultNow();\n} catch (Exception ex) {\n if (ex != null) {\n System.err.println(\"caught ex: \" + ex.getClass());\n System.err.println(\"caught ex message: \" + ex.getMessage());\n }\n}\n"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74464617",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16761890/"
] |
74,464,621
|
<p>In snowflake, I have a table <code>"dbtest"."schematest"."testtable"</code> created by role Accountadmin.</p>
<p>Now i want to alter a column in this table using another role <code>roletest</code>;</p>
<p>I have given all access till table leve to roletest</p>
<pre><code># using accountadmin roles i have granted all the access
use role accountadmin
use warehouse testwarehouse
# granted database level permission to the role
GRANT USAGE ON DATABASE DBTEST TO ROLE ROLETEST;
# granted schema level permission to the rol
GRANT USAGE ON SCHEMA DBTEST.SCHEMATEST TO ROLE ROLETEST;
GRANT SELECT ON ALL VIEWS IN SCHEMA DBTEST.SCHEMATEST TO ROLE ROLETEST;
GRANT SELECT ON FUTURE VIEWS IN SCHEMA DBTEST.SCHEMATEST TO ROLE ROLETEST;
GRANT SELECT ON ALL TABLES IN SCHEMA DBTEST.SCHEMATEST TO ROLE ROLETEST;
GRANT SELECT ON FUTURE TABLES IN SCHEMA DBTEST.SCHEMATEST TO ROLE ROLETEST;
GRANT USAGE, CREATE FUNCTION, CREATE PROCEDURE, CREATE TABLE, CREATE VIEW, CREATE EXTERNAL TABLE, CREATE MATERIALIZED VIEW, CREATE TEMPORARY TABLE ON SCHEMA DBTEST.SCHEMATEST TO ROLE ROLETEST;
# also at table leve i have granted the permissions
GRANT INSERT, DELETE, REBUILD, REFERENCES, SELECT, TRUNCATE, UPDATE ON TABLE "DBTEST"."SCHEMATEST"."testtable" TO ROLE "ROLETEST";
</code></pre>
<p>Now when i try</p>
<pre><code>use role roletest;
use warehouse roletest_wh;
alter table "DBTEST"."SCHEMATEST"."testtable" alter column c1 drop not null;
</code></pre>
<p>i get the error</p>
<pre><code>SQL access control error: Insufficient privileges to operate on table 'testtable'
</code></pre>
<p>I also tried</p>
<pre><code>GRANT OWNERSHIP ON "DBTEST"."SCHEMATEST"."testtable" TO ROLE roletest;
</code></pre>
<p>it gives error</p>
<pre><code>SQL execution error: Dependent grant of privilege 'SELECT' on securable "DBTEST"."SCHEMATEST"."testtable" to role 'SYSADMIN' exists. It must be revoked first. More than one dependent grant may exist: use 'SHOW GRANTS' command to view them. To revoke all dependent grants while transferring object ownership, use convenience command 'GRANT OWNERSHIP ON <target_objects> TO <target_role> REVOKE CURRENT GRANTS'.
</code></pre>
|
[
{
"answer_id": 74547554,
"author": "Michael Easter",
"author_id": 12704,
"author_profile": "https://Stackoverflow.com/users/12704",
"pm_score": 1,
"selected": false,
"text": "var result = \"error\";\n\ntry (var scope = new StructuredTaskScope.ShutdownOnFailure()) {\n var numOrders = scope.fork(() -> taskGetNumItemsFromRequest()); \n var price = scope.fork(() -> taskGetPriceFromDB());\n\n if (doShutdown) {\n scope.shutdown();\n }\n \n scope.join(); \n scope.throwIfFailed();\n\n result = numOrders.resultNow() + \" \" + price.resultNow();\n} catch (Exception ex) {\n if (ex != null) {\n System.err.println(\"caught ex: \" + ex.getClass());\n System.err.println(\"caught ex message: \" + ex.getMessage());\n }\n}\n"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74464621",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2897115/"
] |
74,464,639
|
<p>I have a function that for a given camelCase object returns the same object in snake_case</p>
<pre><code>// Let's imagine these are the types
interface CamelData {
exempleId: number
myData:string
}
interface SnakeData {
exemple_id: number
my_data: string
}
export const camelToSnake = (
camelData: Partial<CamelData>
): Partial<SnakeData> => {
return {
exemple_id: camelData.exempleId,
my_data: camelData.myData
}
</code></pre>
<p>The thing is I want my function returning type to be SnakeData whenever camelData is of type CamelData.</p>
<p>Basically something that works like that</p>
<pre><code>export const camelToSnake = (
camelData: Partial<CamelData>
): if (camelData is of type CamelData) {SnakeData} else {Partial<SnakeData>} => {
return {
exemple_id: camelData.exempleId,
my_data: camelData.myData
}
</code></pre>
<p>Can you help ?
Have a great day</p>
|
[
{
"answer_id": 74465000,
"author": "Dimava",
"author_id": 5734961,
"author_profile": "https://Stackoverflow.com/users/5734961",
"pm_score": 1,
"selected": false,
"text": "export function camelToSnake (camelData: CamelData): SnakeData;\nexport function camelToSnake (camelData: Partial<CamelData>): Partial<SnakeData>;\nexport function camelToSnake (camelData: Partial<CamelData>): Partial<SnakeData> {\n return {\n exemple_id: camelData.exempleId,\n my_data: camelData.myData\n }\n}\n"
},
{
"answer_id": 74465007,
"author": "Tadhg McDonald-Jensen",
"author_id": 5827215,
"author_profile": "https://Stackoverflow.com/users/5827215",
"pm_score": 1,
"selected": false,
"text": "CamelData"
},
{
"answer_id": 74476041,
"author": "RouckyKM",
"author_id": 19103670,
"author_profile": "https://Stackoverflow.com/users/19103670",
"pm_score": 1,
"selected": true,
"text": "interface CamelData {\n exempleId: number\n myData:string\n}\n\ninterface SnakeData {\n exemple_id: number\n my_data: string\n}\n\ntype SnakeDataFor<T extends Partial<CamelData>> = {\n example_id: T['exampleId'];\n my_data: T['myData'];\n}\n\nexport function camelToSnake(camelData: CamelData): SnakeData;\nexport function camelToSnake<T extends Partial<CamelData>>(\n camelData: T\n): SnakeDataFor<typeof camelData>;\nexport function camelToSnake<T extends Partial<CamelData>>(\n camelData: T\n): SnakeDataFor<typeof camelData> {\n return {\n exemple_id: camelData.exempleId,\n my_data: camelData.myData\n }\n}\n"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74464639",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19103670/"
] |
74,464,646
|
<p>I have some XML content in a single field; I want to split each xml field in multiple rows.</p>
<p>The XML is something like that:</p>
<pre><code><env>
<id>id1<\id>
<DailyProperties>
<date>01/01/2022<\date>
<value>1<\value>
<\DailyProperties>
<DailyProperties>
<date>05/05/2022<\date>
<value>2<\value>
<\DailyProperties>
<\env>
</code></pre>
<p>I want to put everything in a table as:</p>
<pre><code>ID DATE VALUE
id1 01/01/2022 1
id1 05/05/2022 2
</code></pre>
<p>For now I managed to parse the xml value, and I have found something online to get a string into multiple rows (<a href="https://stackoverflow.com/questions/17942508/sql-split-values-to-multiple-rows">like this</a>), but my string should have some kind of delimiter. I did this:</p>
<pre><code>SELECT
ID,
XMLDATA.X.query('/env/DailyProperties/date').value('.', 'varchar(100)') as r_date,
XMLDATA.X.query('/env/DailyProperties/value').value('.', 'varchar(100)') as r_value
from tableX
outer apply xmlData.nodes('.') as XMLDATA(X)
WHERE ID = 'id1'
</code></pre>
<p>but I get all values without a delimiter, as such:</p>
<p><code>01/10/202202/10/202203/10/202204/10/202205/10/202206/10/202207/10/202208/10/202209/10/202210/10/2022</code></p>
<p>Or, as in my example:</p>
<pre><code>ID R_DATE R_VALUE
id01 01/01/202205/05/2022 12
</code></pre>
<p>I have found out that XQuery has a <code>last()</code> function that return the last value parsed; in my xml example it will return only <code>05/05/2022</code>, so it should exists something for address the adding of a delimiter. The number of rows could vary, as it could vary the number of days of which I have a value.</p>
|
[
{
"answer_id": 74465399,
"author": "Yitzhak Khabinsky",
"author_id": 1932311,
"author_profile": "https://Stackoverflow.com/users/1932311",
"pm_score": 3,
"selected": true,
"text": "DECLARE @tbl TABLE (id INT IDENTITY PRIMARY KEY, xmldata XML);\nINSERT INTO @tbl (xmldata) VALUES\n(N'<env>\n <id>id1</id>\n <DailyProperties>\n <date>01/01/2022</date>\n <value>1</value>\n </DailyProperties>\n <DailyProperties>\n <date>05/05/2022</date>\n <value>2</value>\n </DailyProperties>\n</env>');\n\nSELECT p.value('(id/text())[1]','VARCHAR(20)') AS id\n , c.value('(date/text())[1]','VARCHAR(10)') AS [date]\n , c.value('(value/text())[1]','INT') AS [value]\nFROM @tbl\nCROSS APPLY xmldata.nodes('/env') AS t1(p)\n OUTER APPLY t1.p.nodes('DailyProperties') AS t2(c);\n"
},
{
"answer_id": 74465453,
"author": "Bernie156",
"author_id": 20522983,
"author_profile": "https://Stackoverflow.com/users/20522983",
"pm_score": 1,
"selected": false,
"text": "--==== XML Data:\nDECLARE @xml XML = \n'<env>\n <id>id1</id>\n <DailyProperties>\n <date>01/01/2022</date>\n <value>1</value>\n </DailyProperties>\n <DailyProperties>\n <date>05/05/2022</date>\n <value>2</value>\n </DailyProperties>\n</env>';\n\n--==== Solution:\nSELECT \n ID = ff2.xx.value('(text())[1]','varchar(20)'),\n [Date] = ff.xx.value('(date/text())[1]', 'date'),\n [Value] = ff.xx.value('(value/text())[1]', 'int')\nFROM (VALUES(@xml)) AS f(X)\nCROSS APPLY f.X.nodes('env/DailyProperties') AS ff(xx)\nCROSS APPLY f.X.nodes('env/id') AS ff2(xx);\n"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74464646",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4949261/"
] |
74,464,690
|
<p>This is an example of a bigger dataframe. Imagine I have a dataframe like this:</p>
<pre><code>import pandas as pd
df = pd.DataFrame({"ID":["4SSS50FX","2TT1897FA"],
"VALUE":[13, 56]})
df
Out[2]:
ID VALUE
0 4SSS50FX 13
1 2TT1897FA 56
</code></pre>
<p>I would like to insert "-" in the strings from df["ID"] everytime it changes from number to text and from text to number. So the output should be like:</p>
<pre><code> ID VALUE
0 4-SSS-50-FX 13
1 2-TT-1897-FA 56
</code></pre>
<p>I could create specific conditions for each case, but I would like to automate it for all the samples. Anyone could help me?</p>
|
[
{
"answer_id": 74465399,
"author": "Yitzhak Khabinsky",
"author_id": 1932311,
"author_profile": "https://Stackoverflow.com/users/1932311",
"pm_score": 3,
"selected": true,
"text": "DECLARE @tbl TABLE (id INT IDENTITY PRIMARY KEY, xmldata XML);\nINSERT INTO @tbl (xmldata) VALUES\n(N'<env>\n <id>id1</id>\n <DailyProperties>\n <date>01/01/2022</date>\n <value>1</value>\n </DailyProperties>\n <DailyProperties>\n <date>05/05/2022</date>\n <value>2</value>\n </DailyProperties>\n</env>');\n\nSELECT p.value('(id/text())[1]','VARCHAR(20)') AS id\n , c.value('(date/text())[1]','VARCHAR(10)') AS [date]\n , c.value('(value/text())[1]','INT') AS [value]\nFROM @tbl\nCROSS APPLY xmldata.nodes('/env') AS t1(p)\n OUTER APPLY t1.p.nodes('DailyProperties') AS t2(c);\n"
},
{
"answer_id": 74465453,
"author": "Bernie156",
"author_id": 20522983,
"author_profile": "https://Stackoverflow.com/users/20522983",
"pm_score": 1,
"selected": false,
"text": "--==== XML Data:\nDECLARE @xml XML = \n'<env>\n <id>id1</id>\n <DailyProperties>\n <date>01/01/2022</date>\n <value>1</value>\n </DailyProperties>\n <DailyProperties>\n <date>05/05/2022</date>\n <value>2</value>\n </DailyProperties>\n</env>';\n\n--==== Solution:\nSELECT \n ID = ff2.xx.value('(text())[1]','varchar(20)'),\n [Date] = ff.xx.value('(date/text())[1]', 'date'),\n [Value] = ff.xx.value('(value/text())[1]', 'int')\nFROM (VALUES(@xml)) AS f(X)\nCROSS APPLY f.X.nodes('env/DailyProperties') AS ff(xx)\nCROSS APPLY f.X.nodes('env/id') AS ff2(xx);\n"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74464690",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11001493/"
] |
74,464,715
|
<p>I've come across this problem before, say with Categories or Tags.
You have multiple tags that can be children of each other:</p>
<pre><code>{ id: 1, name: 'Sports', parent_id: null }
{ id: 2, name: 'Fruits', parent_id: null }
{ id: 3, name: 'Citrus', parent_id: 2 }
{ id: 4, name: 'Orange', parent_id: 3 }
{ id: 5, name: 'Hockey', parent_id: 1 }
</code></pre>
<p>Another representation of these nodes:</p>
<pre><code>Sports -> Hockey
Fruits -> Citrius -> Orange
</code></pre>
<p>What is the algorithm that efficiently finds the top-most parent for each node? So we can go from Orange -> Fruits in O(1) time.</p>
<p>(Requires some preprocessing).</p>
|
[
{
"answer_id": 74466298,
"author": "Asraf",
"author_id": 20361860,
"author_profile": "https://Stackoverflow.com/users/20361860",
"pm_score": 0,
"selected": false,
"text": "O(n)"
},
{
"answer_id": 74467976,
"author": "trincot",
"author_id": 5459839,
"author_profile": "https://Stackoverflow.com/users/5459839",
"pm_score": 1,
"selected": false,
"text": "const categories = [\n { id: 1, name: 'Sports', parent_id: null },\n { id: 2, name: 'Fruits', parent_id: null },\n { id: 3, name: 'Citrus', parent_id: 2 },\n { id: 4, name: 'Orange', parent_id: 3 },\n { id: 5, name: 'Hockey', parent_id: 1 },\n { id: 6, name: 'Apple', parent_id: 2 }\n];\n\n// Build a Map of nodes keyed by node id:\nconst map = new Map(categories.map(node => [node.id, node]));\n\n// Enrich each node with parent and top node-references\nfunction extendNode(node) {\n if (!node.top) {\n node.parent = map.get(node.parent_id);\n node.top = node.parent ? extendNode(node.parent) : node;\n }\n return node.top;\n}\ncategories.forEach(extendNode);\n\n// Example use:\nconst orange = map.get(4);\nconsole.log(orange.name, \"=>\", orange.top.name);"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74464715",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/213371/"
] |
74,464,732
|
<p>I have a table where one column has repeating values that I need to group. I then want to see if all of the cells within a different column, but within the same grouping match, or more specifically if they don't match.</p>
<p><a href="https://i.stack.imgur.com/5i25E.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/5i25E.png" alt="enter image description here" /></a></p>
<p>This is what I have so far.</p>
<pre><code>SELECT Dashboard_Widget_Id, Position ????? AS Is_Different
FROM toolbox.Dashboard_Widget_Sizes
GROUP BY Dashboard_Widget_Id
</code></pre>
|
[
{
"answer_id": 74466298,
"author": "Asraf",
"author_id": 20361860,
"author_profile": "https://Stackoverflow.com/users/20361860",
"pm_score": 0,
"selected": false,
"text": "O(n)"
},
{
"answer_id": 74467976,
"author": "trincot",
"author_id": 5459839,
"author_profile": "https://Stackoverflow.com/users/5459839",
"pm_score": 1,
"selected": false,
"text": "const categories = [\n { id: 1, name: 'Sports', parent_id: null },\n { id: 2, name: 'Fruits', parent_id: null },\n { id: 3, name: 'Citrus', parent_id: 2 },\n { id: 4, name: 'Orange', parent_id: 3 },\n { id: 5, name: 'Hockey', parent_id: 1 },\n { id: 6, name: 'Apple', parent_id: 2 }\n];\n\n// Build a Map of nodes keyed by node id:\nconst map = new Map(categories.map(node => [node.id, node]));\n\n// Enrich each node with parent and top node-references\nfunction extendNode(node) {\n if (!node.top) {\n node.parent = map.get(node.parent_id);\n node.top = node.parent ? extendNode(node.parent) : node;\n }\n return node.top;\n}\ncategories.forEach(extendNode);\n\n// Example use:\nconst orange = map.get(4);\nconsole.log(orange.name, \"=>\", orange.top.name);"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74464732",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5248324/"
] |
74,464,758
|
<p>`</p>
<pre><code>switch(selectedOption){
case 'B':
printf("Please enter the first number\n");
if (scanf("%f", &firstNumber) == 1){
printf("Is a valid number\n");
}
else{
printf("Is not a valid number\n");
}
}
</code></pre>
<p>`</p>
<p>I have a school assignment where I have to program a calculator. One of the requirements is to ask for the user to input another number if they for example input a character instead of a number. I'm not sure how to go about this and I looked everywhere and no solutions made sense. I would appreciate it a ton if someone could help me out with this problem.</p>
|
[
{
"answer_id": 74466298,
"author": "Asraf",
"author_id": 20361860,
"author_profile": "https://Stackoverflow.com/users/20361860",
"pm_score": 0,
"selected": false,
"text": "O(n)"
},
{
"answer_id": 74467976,
"author": "trincot",
"author_id": 5459839,
"author_profile": "https://Stackoverflow.com/users/5459839",
"pm_score": 1,
"selected": false,
"text": "const categories = [\n { id: 1, name: 'Sports', parent_id: null },\n { id: 2, name: 'Fruits', parent_id: null },\n { id: 3, name: 'Citrus', parent_id: 2 },\n { id: 4, name: 'Orange', parent_id: 3 },\n { id: 5, name: 'Hockey', parent_id: 1 },\n { id: 6, name: 'Apple', parent_id: 2 }\n];\n\n// Build a Map of nodes keyed by node id:\nconst map = new Map(categories.map(node => [node.id, node]));\n\n// Enrich each node with parent and top node-references\nfunction extendNode(node) {\n if (!node.top) {\n node.parent = map.get(node.parent_id);\n node.top = node.parent ? extendNode(node.parent) : node;\n }\n return node.top;\n}\ncategories.forEach(extendNode);\n\n// Example use:\nconst orange = map.get(4);\nconsole.log(orange.name, \"=>\", orange.top.name);"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74464758",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13244489/"
] |
74,464,772
|
<p>I'm trying to style the border bottom color of my mat-paginator when a option is selected, which has a default purple color. Anyone got a solution?</p>
<p><a href="https://i.stack.imgur.com/aPNAu.png" rel="nofollow noreferrer">Mat-paginator purple border</a></p>
<p>I tried looking for class that style the border on devtools, but didn't succeed.</p>
|
[
{
"answer_id": 74465037,
"author": "Mr. Stash",
"author_id": 13625800,
"author_profile": "https://Stackoverflow.com/users/13625800",
"pm_score": 1,
"selected": false,
"text": "::ng-deep .mat-form-field.mat-focused .mat-form-field-ripple{\n background-color: red;\n}\n"
},
{
"answer_id": 74465062,
"author": "Alejandro Suárez",
"author_id": 17751007,
"author_profile": "https://Stackoverflow.com/users/17751007",
"pm_score": 0,
"selected": false,
"text": ".mat-form-field.mat-focused .mat-form-field-ripple {\n background-color: red;\n}\n"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74464772",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19729470/"
] |
74,464,780
|
<p>I want to get data out of youtube's "heat-map" feature, which is present in videos with certain features. <a href="https://www.youtube.com/watch?v=09wcDevb1q4" rel="nofollow noreferrer">This</a> is an example. I want to retrieve this data somehow yet Youtube API's don't provide it and, <a href="https://stackoverflow.com/questions/72610552/most-replayed-data-of-youtube-video-via-api">this api</a> doesn't always work. I'm aware they probably use the same approach, but I want to be able to have a reliable source of information. As of this approach (web-scrapping), I have tried using selenium, with the XPath of the element (you can find in the html of the video if you search for the class <code>ytp-heat-map-path</code>, like this):</p>
<pre><code>driver = webdriver.Firefox()
driver.get("https://www.youtube.com/watch?v=09wcDevb1q4")
while len(driver.find_elements(By.XPATH,"/html/body/ytd-app/div[1]/ytd-page-manager/ytd-watch-flexy/div[3]/div/ytd-player/div/div/div[31]/div[1]/div[1]/div[2]/svg/defs/clipPath/path")) == 0:
pass
a = driver.find_element(By.XPATH,"/html/body/ytd-app/div[1]/ytd-page-manager/ytd-watch-flexy/div[3]/div/ytd-player/div/div/div[31]/div[1]/div[1]/div[2]/svg/defs/clipPath/path")
</code></pre>
<p>I have also tried with beautifulSoup, finding the class:</p>
<pre><code>mydivs = soup.find_all("path", {"class": "ytp-heat-map-path"})
</code></pre>
<p>None of them can find the data. I'm happy to find a solution to this with web scrapping or any other method. Thanks.</p>
|
[
{
"answer_id": 74465259,
"author": "Fazlul",
"author_id": 12848411,
"author_profile": "https://Stackoverflow.com/users/12848411",
"pm_score": 2,
"selected": true,
"text": "d"
},
{
"answer_id": 74465469,
"author": "Benjamin Loison",
"author_id": 7123660,
"author_profile": "https://Stackoverflow.com/users/7123660",
"pm_score": 1,
"selected": false,
"text": "ytInitialData"
},
{
"answer_id": 74554663,
"author": "Kevin M.",
"author_id": 9329155,
"author_profile": "https://Stackoverflow.com/users/9329155",
"pm_score": 0,
"selected": false,
"text": "ytInitialData"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74464780",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9329155/"
] |
74,464,781
|
<p>So I'm having problem converting my date to this format:</p>
<pre><code>DD/MM/YYYY HH:MM:ss
</code></pre>
<p>my front end is retrieving the date from the date stored in the database but somehow when I convert it it's changing the hours. The date is:</p>
<pre><code>2022-11-16T15:00:00.000Z
</code></pre>
<p>And I have tried:</p>
<pre><code>const date = moment(date).format("DD/MM/YYYY HH:MM:ss")
</code></pre>
<p>it returned:</p>
<pre><code>16/11/2022 12:11:00
</code></pre>
<p>How can I achieve just:</p>
<pre><code>16/11/2022 15:00:00
</code></pre>
|
[
{
"answer_id": 74465259,
"author": "Fazlul",
"author_id": 12848411,
"author_profile": "https://Stackoverflow.com/users/12848411",
"pm_score": 2,
"selected": true,
"text": "d"
},
{
"answer_id": 74465469,
"author": "Benjamin Loison",
"author_id": 7123660,
"author_profile": "https://Stackoverflow.com/users/7123660",
"pm_score": 1,
"selected": false,
"text": "ytInitialData"
},
{
"answer_id": 74554663,
"author": "Kevin M.",
"author_id": 9329155,
"author_profile": "https://Stackoverflow.com/users/9329155",
"pm_score": 0,
"selected": false,
"text": "ytInitialData"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74464781",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18545081/"
] |
74,464,813
|
<p>Quickly, my need: create a Spark dataframe from a more or less complex query in T-SQL (SQL Server) and/or from the output of a SQL Server stored procedure.</p>
<p>As far I understand, Spark does not allow to execute queries in the dialect of the underlying data source. Yes, there is <a href="https://stackoverflow.com/questions/60354376/how-to-execute-a-stored-procedure-in-azure-databricks-pyspark">a way</a> to obtain low level object and perform stored procedures but in this manner I don't have the Spark DF in output.</p>
<p>So, I thought to perform a query in the classical pyodbc way, obtain the results and then build the Spark dataframe with the function <a href="https://spark.apache.org/docs/3.2.2/api/python/reference/api/pyspark.sql.SparkSession.createDataFrame.html" rel="nofollow noreferrer"><em>SparkSession.createDataFrame(data, schema=None, samplingRatio=None, verifySchema=True)</em></a> providing the data and the schema. I can obtain the data, but I can't build the schema (a list of pairs <em>(column name, data type)</em>) from the output cursor. Follows a working example to (generate and) extract sample data from a local instance of SQL Server:</p>
<pre><code>import pyodbc
connection_string = "Driver={SQL Server};Server=LOCALHOST;Database=master;Trusted_Connection=yes;"
db_connection = pyodbc.connect(connection_string)
sql_query = """
SET NOCOUNT ON
DECLARE @TBL_TEST AS TABLE (
column_1 INT NOT NULL PRIMARY KEY CLUSTERED IDENTITY(1, 1),
column_2 VARCHAR(10) NOT NULL,
column_3 VARCHAR(20) NULL,
column_4 INT NOT NULL
)
INSERT INTO @TBL_TEST (column_2, column_3, column_4)
VALUES
('test1_col2', 'test1_col3', 100),
('test2_col2', 'test2_col3', 200),
('test3_col2', NULL, 300)
SET NOCOUNT OFF
SELECT t.* FROM @TBL_TEST AS t
"""
cursor = db_connection.cursor()
rows = cursor.execute(sql_query).fetchall()
cursor.close()
db_connection.close()
print(rows)
</code></pre>
<p>How can I extract the schema from the returned cursor and obtain a <em>schema</em> object to give to the createDataFrame() function?</p>
<p>Remember that my goal is that on the topic, so other ways are also welcome!</p>
<p>Thank you in advance!</p>
|
[
{
"answer_id": 74466271,
"author": "CRAFTY DBA",
"author_id": 2577687,
"author_profile": "https://Stackoverflow.com/users/2577687",
"pm_score": 1,
"selected": false,
"text": "#\n# Set connection properties\n#\n\nserver_name = \"jdbc:sqlserver://svr4tips2030.database.windows.net\"\ndatabase_name = \"dbs4advwrks\"\nurl = server_name + \";\" + \"databaseName=\" + database_name + \";\"\ntable_name = \"dbo.vDMPrep\"\nuser_name = \"enter your user here\"\npassword = \"enter your password here\"\n"
},
{
"answer_id": 74466808,
"author": "CRAFTY DBA",
"author_id": 2577687,
"author_profile": "https://Stackoverflow.com/users/2577687",
"pm_score": 0,
"selected": false,
"text": "-- \n-- Sample Call\n-- \nCREATE PROCEDURE dbo.StackOverFlowTest\nAS\nBEGIN\n DROP TABLE IF EXISTS stage.DimSalesTerritory;\n SELECT * INTO stage.DimSalesTerritory FROM dbo.DimSalesTerritory\nEND\n"
},
{
"answer_id": 74513108,
"author": "CRAFTY DBA",
"author_id": 2577687,
"author_profile": "https://Stackoverflow.com/users/2577687",
"pm_score": 0,
"selected": false,
"text": "#\n# Create function to call tsql + return df\n#\n\n# use module\nimport pymssql \n\n# define function\ndef call_tsql(info):\n \n # make connection\n conn = pymssql.connect(server=info[0], user=info[1], password=info[2], database=info[3]) \n \n # open cursor\n cursor = conn.cursor() \n cursor.execute(info[4])\n \n # grab column data (name, type, ...)\n desc = cursor.description\n \n # grab data as list of tuples\n dat1 = cursor.fetchall()\n \n # close cursor\n conn.commit()\n conn.close()\n \n # extract column names\n col1 = list(map(lambda x: x[0], desc))\n \n # let spark infer data types\n df1 = spark.createDataFrame(data=dat1, schema=col1)\n \n # return dataframe\n return df1\n \n"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74464813",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4596414/"
] |
74,464,816
|
<p>I'm new in Blazor and I'm a little bit confused about warnings and nullable. If I declare a varible like this: <code>List<Course> result = new List<Course>();</code>
I get a warning in here: <code>result = await ClientHttp.GetFromJsonAsync<List<Course>>("api/GetCourses");</code></p>
<p>But if I set the variable as nullable: <code>List<Course>? result = new List<Course>();</code>
The first warning dissapears but I get a new one: <code>result.Remove(aux);</code></p>
<p>So, I can build with the warnings and I could hide them but I would like to know what is really happening and how control it.</p>
|
[
{
"answer_id": 74466519,
"author": "Henk",
"author_id": 60761,
"author_profile": "https://Stackoverflow.com/users/60761",
"pm_score": 2,
"selected": false,
"text": "result"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74464816",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5667921/"
] |
74,464,826
|
<p>When I make a request from <strong>Postman</strong>, I get an error, but when I make a Post request from a <strong>React page</strong>, I get an error.
I <strong>am not</strong> using <strong>Spring Security</strong>.</p>
<pre><code>Access to XMLHttpRequest at 'http://localhost:8080/api/createData' from origin 'http://localhost:3001' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
</code></pre>
<p><strong>React axios code:</strong></p>
<pre><code>return axios.post("http://localhost:8080/api/createData", {
name: 'Michael'
});
</code></pre>
<p><strong>pom.xml</strong></p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.7.5</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>test1</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>test1</name>
<description>Test1 project for Spring Boot</description>
<properties>
<java.version>17</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web-services</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
</project>
</code></pre>
<p><strong>Cotroller class for Request:</strong></p>
<pre><code>import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/api")
public class Tutorial {
@PostMapping("/createData")
public void createData(@RequestBody Data data) {
System.out.println(data.getName());
}
}
</code></pre>
<p>I did some research but couldn't figure it out. I get an error when requesting from postman.
Why does the problem occur and how can I fix it?</p>
|
[
{
"answer_id": 74466519,
"author": "Henk",
"author_id": 60761,
"author_profile": "https://Stackoverflow.com/users/60761",
"pm_score": 2,
"selected": false,
"text": "result"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74464826",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14686302/"
] |
74,464,839
|
<p>I have a class called Sound from the framework SwiftySound and a subclass called SoundWrapper which makes it hashable. Now I am adding a string property "imageName" to the subclass so that I can add an image to every sound. Therefore, I am required to write an initializer for the superclass using super.init.</p>
<p>However, when I try to do that the error shows: 'url' is inaccessible due to 'private' protection level.</p>
<p>Is there any way to resolve this?</p>
<p>To be clear, this is my first time creating subclasses in Swift so I could be making some obvious mistakes here and might need a different approach altogether.</p>
<p>This is my subclass:</p>
<pre><code>class SoundWrapper:Sound, Hashable{
let id = UUID()
let imageName : String
init(imageName: String) {
self.imageName = imageName
super.init(url: url)
// Error: 'url' is inaccessible due to 'private' protection level
}
public func hash(into hasher: inout Hasher) {
hasher.combine(0)
}
static func == (lhs: SoundWrapper, rhs: SoundWrapper) -> Bool {
return lhs.id == rhs.id
}
}
</code></pre>
<p>How I plan to initialize the subclass:</p>
<pre><code>
let backgroundAudio1 = SoundWrapper(imageName: "image1", url: getFileUrl(name: "backgroundAudio1"))
</code></pre>
<p>How I get the url:</p>
<pre><code>func getFileUrl (name: String) -> URL {
let filePath = Bundle.main.path(forResource: name, ofType: "wav")!
return URL(fileURLWithPath: filePath)
}
</code></pre>
<p>This is the SwiftySound framework where I get the Sound class from:</p>
<pre><code>
import Foundation
import AVFoundation
#if os(iOS) || os(tvOS)
/// SoundCategory is a convenient wrapper for AVAudioSessions category constants.
public enum SoundCategory {
/// Equivalent of AVAudioSession.Category.ambient.
case ambient
/// Equivalent of AVAudioSession.Category.soloAmbient.
case soloAmbient
/// Equivalent of AVAudioSession.Category.playback.
case playback
/// Equivalent of AVAudioSession.Category.record.
case record
/// Equivalent of AVAudioSession.Category.playAndRecord.
case playAndRecord
fileprivate var avFoundationCategory: AVAudioSession.Category {
get {
switch self {
case .ambient:
return .ambient
case .soloAmbient:
return .soloAmbient
case .playback:
return .playback
case .record:
return .record
case .playAndRecord:
return .playAndRecord
}
}
}
}
#endif
/// Sound is a class that allows you to easily play sounds in Swift. It uses AVFoundation framework under the hood.
open class Sound {
// MARK: - Global settings
/// Number of AVAudioPlayer instances created for every sound. SwiftySound creates 5 players for every sound to make sure that it will be able to play the same sound more than once. If your app doesn't need this functionality, you can reduce the number of players to 1 and reduce memory usage. You can increase the number if your app plays the sound more than 5 times at the same time.
public static var playersPerSound: Int = 10 {
didSet {
stopAll()
sounds.removeAll()
}
}
#if os(iOS) || os(tvOS)
/// Sound session. The default value is the shared `AVAudioSession` session.
public static var session: Session = AVAudioSession.sharedInstance()
/// Sound category for current session. Using this variable is a convenient way to set AVAudioSessions category. The default value is .ambient.
public static var category: SoundCategory = {
let defaultCategory = SoundCategory.ambient
try? session.setCategory(defaultCategory.avFoundationCategory)
return defaultCategory
}() {
didSet {
try? session.setCategory(category.avFoundationCategory)
}
}
#endif
private static var sounds = [URL: Sound]()
private static let defaultsKey = "com.moonlightapps.SwiftySound.enabled"
/// Globally enable or disable sound. This setting value is stored in UserDefaults and will be loaded on app launch.
public static var enabled: Bool = {
return !UserDefaults.standard.bool(forKey: defaultsKey)
}() { didSet {
let value = !enabled
UserDefaults.standard.set(value, forKey: defaultsKey)
if value {
stopAll()
}
}
}
private let players: [Player]
private var counter = 0
/// The class that is used to create `Player` instances. Defaults to `AVAudioPlayer`.
public static var playerClass: Player.Type = AVAudioPlayer.self
/// The bundle used to load sounds from filenames. The default value of this property is Bunde.main. It can be changed to load sounds from another bundle.
public static var soundsBundle: Bundle = .main
// MARK: - Initialization
/// Create a sound object.
///
/// - Parameter url: Sound file URL.
public init?(url: URL) {
#if os(iOS) || os(tvOS)
_ = Sound.category
#endif
let playersPerSound = max(Sound.playersPerSound, 1)
var myPlayers: [Player] = []
myPlayers.reserveCapacity(playersPerSound)
for _ in 0..<playersPerSound {
do {
let player = try Sound.playerClass.init(contentsOf: url)
myPlayers.append(player)
} catch {
print("SwiftySound initialization error: \(error)")
}
}
if myPlayers.count == 0 {
return nil
}
players = myPlayers
NotificationCenter.default.addObserver(self, selector: #selector(Sound.stopNoteRcv), name: Sound.stopNotificationName, object: nil)
}
deinit {
NotificationCenter.default.removeObserver(self, name: Sound.stopNotificationName, object: nil)
}
@objc private func stopNoteRcv() {
stop()
}
private static let stopNotificationName = Notification.Name("com.moonlightapps.SwiftySound.stopNotification")
// MARK: - Main play method
/// Play the sound.
///
/// - Parameter numberOfLoops: Number of loops. Specify a negative number for an infinite loop. Default value of 0 means that the sound will be played once.
/// - Returns: If the sound was played successfully the return value will be true. It will be false if sounds are disabled or if system could not play the sound.
@discardableResult public func play(numberOfLoops: Int = 0, completion: PlayerCompletion? = nil) -> Bool {
if !Sound.enabled {
return false
}
paused = false
counter = (counter + 1) % players.count
let player = players[counter]
return player.play(numberOfLoops: numberOfLoops, completion: completion)
}
// MARK: - Stop playing
/// Stop playing the sound.
public func stop() {
for player in players {
player.stop()
}
paused = false
}
/// Pause current playback.
public func pause() {
players[counter].pause()
paused = true
}
/// Resume playing.
@discardableResult public func resume() -> Bool {
if paused {
players[counter].resume()
paused = false
return true
}
return false
}
/// Indicates if the sound is currently playing.
public var playing: Bool {
return players[counter].isPlaying
}
/// Indicates if the sound is paused.
public private(set) var paused: Bool = false
// MARK: - Prepare sound
/// Prepare the sound for playback
///
/// - Returns: True if the sound has been prepared, false in case of error
@discardableResult public func prepare() -> Bool {
let nextIndex = (counter + 1) % players.count
return players[nextIndex].prepareToPlay()
}
// MARK: - Convenience static methods
/// Play sound from a sound file.
///
/// - Parameters:
/// - file: Sound file name.
/// - fileExtension: Sound file extension.
/// - numberOfLoops: Number of loops. Specify a negative number for an infinite loop. Default value of 0 means that the sound will be played once.
/// - Returns: If the sound was played successfully the return value will be true. It will be false if sounds are disabled or if system could not play the sound.
@discardableResult public static func play(file: String, fileExtension: String? = nil, numberOfLoops: Int = 0) -> Bool {
if let url = url(for: file, fileExtension: fileExtension) {
return play(url: url, numberOfLoops: numberOfLoops)
}
return false
}
/// Play a sound from URL.
///
/// - Parameters:
/// - url: Sound file URL.
/// - numberOfLoops: Number of loops. Specify a negative number for an infinite loop. Default value of 0 means that the sound will be played once.
/// - Returns: If the sound was played successfully the return value will be true. It will be false if sounds are disabled or if system could not play the sound.
@discardableResult public static func play(url: URL, numberOfLoops: Int = 0) -> Bool {
if !Sound.enabled {
return false
}
var sound = sounds[url]
if sound == nil {
sound = Sound(url: url)
sounds[url] = sound
}
return sound?.play(numberOfLoops: numberOfLoops) ?? false
}
/// Stop playing sound for given URL.
///
/// - Parameter url: Sound file URL.
public static func stop(for url: URL) {
let sound = sounds[url]
sound?.stop()
}
/// Duration of the sound.
public var duration: TimeInterval {
get {
return players[counter].duration
}
}
/// Sound volume.
/// A value in the range 0.0 to 1.0, with 0.0 representing the minimum volume and 1.0 representing the maximum volume.
public var volume: Float {
get {
return players[counter].volume
}
set {
for player in players {
player.volume = newValue
}
}
}
/// Stop playing sound for given sound file.
///
/// - Parameters:
/// - file: Sound file name.
/// - fileExtension: Sound file extension.
public static func stop(file: String, fileExtension: String? = nil) {
if let url = url(for: file, fileExtension: fileExtension) {
let sound = sounds[url]
sound?.stop()
}
}
/// Stop playing all sounds.
public static func stopAll() {
NotificationCenter.default.post(name: stopNotificationName, object: nil)
}
// MARK: - Private helper method
private static func url(for file: String, fileExtension: String? = nil) -> URL? {
return soundsBundle.url(forResource: file, withExtension: fileExtension)
}
}
/// Player protocol. It duplicates `AVAudioPlayer` methods.
public protocol Player: AnyObject {
/// Play the sound.
///
/// - Parameters:
/// - numberOfLoops: Number of loops.
/// - completion: Complation handler.
/// - Returns: true if the sound was played successfully. False otherwise.
func play(numberOfLoops: Int, completion: PlayerCompletion?) -> Bool
/// Stop playing the sound.
func stop()
/// Pause current playback.
func pause()
/// Resume playing.
func resume()
/// Prepare the sound.
func prepareToPlay() -> Bool
/// Create a Player for sound url.
///
/// - Parameter url: sound url.
init(contentsOf url: URL) throws
/// Duration of the sound.
var duration: TimeInterval { get }
/// Sound volume.
var volume: Float { get set }
/// Indicates if the player is currently playing.
var isPlaying: Bool { get }
}
fileprivate var associatedCallbackKey = "com.moonlightapps.SwiftySound.associatedCallbackKey"
public typealias PlayerCompletion = ((Bool) -> ())
extension AVAudioPlayer: Player, AVAudioPlayerDelegate {
public func play(numberOfLoops: Int, completion: PlayerCompletion?) -> Bool {
if let cmpl = completion {
objc_setAssociatedObject(self, &associatedCallbackKey, cmpl, .OBJC_ASSOCIATION_COPY_NONATOMIC)
self.delegate = self
}
self.numberOfLoops = numberOfLoops
return play()
}
public func resume() {
play()
}
public func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) {
let cmpl = objc_getAssociatedObject(self, &associatedCallbackKey) as? PlayerCompletion
cmpl?(flag)
objc_removeAssociatedObjects(self)
self.delegate = nil
}
public func audioPlayerDecodeErrorDidOccur(_ player: AVAudioPlayer, error: Error?) {
print("SwiftySound playback error: \(String(describing: error))")
}
}
#if os(iOS) || os(tvOS)
/// Session protocol. It duplicates `setCategory` method of `AVAudioSession` class.
public protocol Session: AnyObject {
/// Set category for session.
///
/// - Parameter category: category.
func setCategory(_ category: AVAudioSession.Category) throws
}
extension AVAudioSession: Session {}
#endif
</code></pre>
|
[
{
"answer_id": 74465015,
"author": "Caleb Bolton",
"author_id": 7098384,
"author_profile": "https://Stackoverflow.com/users/7098384",
"pm_score": 0,
"selected": false,
"text": "url"
},
{
"answer_id": 74465227,
"author": "HangarRash",
"author_id": 20287183,
"author_profile": "https://Stackoverflow.com/users/20287183",
"pm_score": 2,
"selected": true,
"text": "Sound"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74464839",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7876521/"
] |
74,464,847
|
<p>I am trying to make a music quiz where the bot plays a song and asks the question "What is the name of this song?", the user then is given a 30 second time period where it can enter the songs name or else it will say no one got the answer right in time. Now when I try executing this command and give the right answer the bot just ignores it and waits for the 30 seconds to run out and says that no one got it right in time.</p>
<pre class="lang-js prettyprint-override"><code>const filter = m => m.content.toLowerCase() === item.title.toLowerCase(); // the filter
interaction.reply({ content: "What is the name of this song?"})
const collector = interaction.channel.createMessageCollector({ filter, time: 30000 }); // creates a collector with the filter and 30 second time period
collector.on('collect', m => { // this is the event that gets triggered if it gets collected
console.log(`Collected ${m.content}`);
interaction.followUp(`${m.author} got the correct answer!`)
queue.skip()
});
collector.on('end', collected => { // this is the even that gets triggered when the time runs out
console.log(`Collected ${collected.size} items`);
interaction.followUp(`${collected.size} people got the right answer!`)
queue.skip()
});
</code></pre>
<p>The item object is just a JSON file that contains the data of the current song: the artist(s), the URL and the title. So let's say for this example that this is the given information:</p>
<pre><code>{
"title": "Uptown Funk",
"url": "https://www.youtube.com/watch?v=OPf0YbXqDm0",
"singers": ["Mark Ronson", "Bruno Mars"]
},
</code></pre>
<p>Then even if the users says uptown funk, it doesn't get picked up.</p>
|
[
{
"answer_id": 74466137,
"author": "Crytek1012",
"author_id": 16825118,
"author_profile": "https://Stackoverflow.com/users/16825118",
"pm_score": 0,
"selected": false,
"text": "item.title"
},
{
"answer_id": 74468166,
"author": "vixitu",
"author_id": 19617459,
"author_profile": "https://Stackoverflow.com/users/19617459",
"pm_score": 1,
"selected": false,
"text": "const collector = new MessageCollector(interaction.channel, filter, {time: 60000,});\n"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74464847",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19617459/"
] |
74,464,877
|
<p>I'm making a Flutter application and I'm trying to get the user's data in the app.</p>
<p>So basically, the user registers with his info (name, email, password), and this data is displayed in a <code>ProfilePage</code> when he's logged in.</p>
<p>According to Firestore documentation, I'm supposed to use a <code>StreamBuilder</code> to get his data.</p>
<p>At this point, everything works fine.</p>
<p>The problem is that when the user logs out and another user logs in, the <code>ProfilePage</code> displays the precedent user's data (the user logged out).</p>
<p>Only if I restart the app, then I'm getting the right data.</p>
<p>Here's my <code>ProfilePage</code> :</p>
<pre><code>class UserInformation extends StatefulWidget {
@override
_UserInformationState createState() => _UserInformationState();
}
class _UserInformationState extends State<UserInformation> {
final _uid = FirebaseAuth.instance.currentUser!.uid;
final Stream<QuerySnapshot> _usersStream =
FirebaseFirestore.instance.collection('Users')
.doc(_uid)
.collection('UserData')
.snapshots();
@override
Widget build(BuildContext context) {
return StreamBuilder<QuerySnapshot>(
key: Key(_uid),
stream: _usersStream,
builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
if (snapshot.hasError) {
return const Text('Something went wrong');
}
if (snapshot.connectionState == ConnectionState.waiting) {
return const Text("Loading");
}
return ListView(
children: snapshot.data!.docs
.map((DocumentSnapshot document) {
Map<String, dynamic> data =
document.data()! as Map<String, dynamic>;
return ListTile(
title: Text(data['full_name']),
subtitle: Text(data['company']),
);
})
.toList()
.cast(),
);
},
);
}
}
</code></pre>
<p>I see that this is a question asked several times on SO but I couldn't find a good solution. I tried to add a unique key in the <code>StreamBuilder</code> but it doesn't solve the problem.</p>
<p>I also saw the use of <code>didUpdateWidget</code> but I don't understand how to use it.</p>
|
[
{
"answer_id": 74466137,
"author": "Crytek1012",
"author_id": 16825118,
"author_profile": "https://Stackoverflow.com/users/16825118",
"pm_score": 0,
"selected": false,
"text": "item.title"
},
{
"answer_id": 74468166,
"author": "vixitu",
"author_id": 19617459,
"author_profile": "https://Stackoverflow.com/users/19617459",
"pm_score": 1,
"selected": false,
"text": "const collector = new MessageCollector(interaction.channel, filter, {time: 60000,});\n"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74464877",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19573944/"
] |
74,464,890
|
<p>Stateless lambdas can be converted to function pointers, e.g. this is valid,</p>
<pre class="lang-cpp prettyprint-override"><code>using Fun = bool(*)(int, int);
constexpr auto less = [](int a, int b){ return a < b; };
Fun f{less};
</code></pre>
<p>but objects like <code>std::less<int>{}</code> can't.</p>
<p>I do understand why <code>std::less<>{}</code> can't, because it's <code>operator()</code> is not instantiated until the object is applied to some arguments, so how could it be converted to a <code>Fun</code>, if the decision of what its template argument(s) are is not been taken yet?</p>
<p>But <code>std::less<int>{}</code> seems just the same as the lambda I've written above, no?</p>
|
[
{
"answer_id": 74465933,
"author": "Marshall Clow",
"author_id": 992490,
"author_profile": "https://Stackoverflow.com/users/992490",
"pm_score": 0,
"selected": false,
"text": "std::less<int>"
},
{
"answer_id": 74466164,
"author": "Nicol Bolas",
"author_id": 734069,
"author_profile": "https://Stackoverflow.com/users/734069",
"pm_score": 3,
"selected": true,
"text": "std::less<int>{}"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74464890",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5825294/"
] |
74,464,896
|
<p>I am doing sort of a code migration from Python to Teradata:</p>
<p>The python code is this:</p>
<p><code>max = min(datetime.today(), date + timedelta(days=90))</code></p>
<p>where date variable holds a date.</p>
<p>However, in Teradata, I know this min function won't work the same way. And, I have to get the 'date' using a select statement.</p>
<p><code>SEL min(SELECT CURRENT_TIMESTAMP, SEL MAX(DTM) + INTERVAL '90' DAY FROM BILLS) as max</code></p>
<p>Those select statements individually run correct. Only thing is I want the minimum of those two dates. Also, the '<code>SELECT CURRENT_TIMESTAMP</code>' is generating output like <code>2022-11-16 12:18:37.120000+00:00</code>. I only want <code>2022-11-16 12:18:37</code>. How can this be done in a single query?</p>
<p>Thank you.</p>
|
[
{
"answer_id": 74465138,
"author": "access_granted",
"author_id": 5812981,
"author_profile": "https://Stackoverflow.com/users/5812981",
"pm_score": 1,
"selected": false,
"text": "SELECT LEAST(13, 6); \nSELECT LEAST( to_char(date1,'YYYYMMDD'), to_char(date2,'YYYYMMDD') ) ...\n"
},
{
"answer_id": 74466239,
"author": "Fred",
"author_id": 11552426,
"author_profile": "https://Stackoverflow.com/users/11552426",
"pm_score": 0,
"selected": false,
"text": "SELECT LEAST(CAST(CURRENT_TIMESTAMP(0) AS TIMESTAMP(0)),\n MAX(DTM) + INTERVAL '90' DAY)\nFROM BILLS;\n"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74464896",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5633396/"
] |
74,464,918
|
<p>I am currently making an <code>if</code> statement, but in that if statement I need to add string character, so based on what you say it either takes away 4 or not.</p>
<pre><code>public static void yesornodisability()
{
String disabled;
Scanner scanner = new Scanner(System.in);
System.out.println("Are you registered disabled(Yes / No)? ");
disabled = scanner.nextLine();
return;
}
</code></pre>
<p>This is the method I am using for my string, When I run the top code (yesornodisability) it works. However when I run the second code it gives me an error saying void cannot be converted to java.lang.String.</p>
<p>This is my if statement</p>
<pre><code>public static int swimmingprice()
{
int userAge = age();
int totalCost = total();
String disabled = yesornodisability();
if (userAge<=18)
{
totalCost= totalCost/2;
}
else if(userAge>=65)
{
totalCost = totalCost-3;
}
else if(disabled.equals("Yes"))
{
totalCost = totalCost-4;
}
else
{
totalCost = 10;
}
System.out.println("The swimming price for you is "+totalCost+" pounds.");
return swimmingprice();
}
</code></pre>
|
[
{
"answer_id": 74465138,
"author": "access_granted",
"author_id": 5812981,
"author_profile": "https://Stackoverflow.com/users/5812981",
"pm_score": 1,
"selected": false,
"text": "SELECT LEAST(13, 6); \nSELECT LEAST( to_char(date1,'YYYYMMDD'), to_char(date2,'YYYYMMDD') ) ...\n"
},
{
"answer_id": 74466239,
"author": "Fred",
"author_id": 11552426,
"author_profile": "https://Stackoverflow.com/users/11552426",
"pm_score": 0,
"selected": false,
"text": "SELECT LEAST(CAST(CURRENT_TIMESTAMP(0) AS TIMESTAMP(0)),\n MAX(DTM) + INTERVAL '90' DAY)\nFROM BILLS;\n"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74464918",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20372133/"
] |
74,464,928
|
<p>I want to sort an array of posts by createdAt dates, now the posts are sorting by first the oldest one then the new one, but I want to be sorted the opposite way! already tried <code>.sort((a, b) => b.createdAt - a.createdAt)</code> but didn't work, I'm not sure if it's the way to implement it. The post data is stored in mongodb as shown in the picture below</p>
<p><strong>Posts Model:</strong>
<a href="https://i.stack.imgur.com/sLUY0.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/sLUY0.png" alt="enter image description here" /></a></p>
<p><strong><code>Post.jsx</code> Code:</strong></p>
<pre><code>export default function Posts({ posts = [] }) {
const [filteredResults, setFilteredResults] = useState([]);
const [searchInput, setSearchInput] = useState('');
const [isLoading, setIsLoading] = useState(false);
const filter = (e) => {
const keyword = e.target.value;
if (keyword !== '') {
const filteredData = posts.filter((post) => {
return Object.values(post)
.join('')
.toLowerCase()
.includes(searchInput.toLowerCase())
})
setFilteredResults(filteredData)
} else {
setFilteredResults(posts)
}
setSearchInput(keyword);
}
console.log(filteredResults)
return (
<div className="posts">
<div className="postsContainer">
<div className="postsSearchContainer">
<div className="postsSearch">
<div class="postsSearchIconContainer">
<SearchIcon class="w-5 h-5" />
</div>
<input type="text"
className="postsSearchInput"
placeholder="بحث"
name="postsSearchText"
id="postsSearchText"
onChange={filter}
/>
</div>
{/* ENDS OF POSTSSEARCHCONTAINER */}
</div>
{/* ENDS OF POSTSSEARCH */}
<div className="postsBoxContainer">
<div className="postsBox">
{isLoading ? (
<Box sx={{ display: 'flex' }}>
<CircularProgress />
</Box>
) : (
filteredResults.length > 0 ? (
filteredResults.map((p) => (
<Post post={p} />
))
) : (posts.map((p) => (
<Post post={p} />
))
)
}
</div>
</div>
{/* ENDS OF POSTSBOX */}
</div>
{/* ENDS OF POSTCONTAINER */}
</div>
//ENDS OF POSTS
);
};
</code></pre>
<p><strong><code>The Code I tried:</code></strong></p>
<pre><code>(
filteredResults.length > 0 ? (
filteredResults.map((p) => (
<Post post={p} />
)).sort((a, b) => b.createdAt - a.createdAt)
) : (posts.map((p) => (
<Post post={p} />
)).sort((a, b) => b.createdAt - a.createdAt))
)
</code></pre>
|
[
{
"answer_id": 74465138,
"author": "access_granted",
"author_id": 5812981,
"author_profile": "https://Stackoverflow.com/users/5812981",
"pm_score": 1,
"selected": false,
"text": "SELECT LEAST(13, 6); \nSELECT LEAST( to_char(date1,'YYYYMMDD'), to_char(date2,'YYYYMMDD') ) ...\n"
},
{
"answer_id": 74466239,
"author": "Fred",
"author_id": 11552426,
"author_profile": "https://Stackoverflow.com/users/11552426",
"pm_score": 0,
"selected": false,
"text": "SELECT LEAST(CAST(CURRENT_TIMESTAMP(0) AS TIMESTAMP(0)),\n MAX(DTM) + INTERVAL '90' DAY)\nFROM BILLS;\n"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74464928",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17342280/"
] |
74,464,932
|
<p><strong>Input js Array</strong></p>
<pre><code>var foo =
[ { name: 'John', age: '30', car: 'yellow' }
, { name: 'shayam', age: '13', car: 'blue' }
, { name: 'ram', age: '23', car: 'red' }
];
</code></pre>
<pre><code>function poo(keyName, value)
{
// Change all the value of JSON array according to key and value
}
</code></pre>
<pre><code>poo("car", "orange"); // 1
poo("age","20"); // 2
</code></pre>
<p>expected output 1</p>
<pre><code> [ { name: "John", age: 30, car: "orange" }
, { name: "shayam", age: 13, car: "orange" }
, { name: "ram", age: "23", car: "orange" }
]
</code></pre>
<p>expected output 2</p>
<pre><code> [ { name: "John", age: "20", car: "orange" }
, { name: "shayam", age: "20", car: "orange" }
, { name: "ram", age: "20", car: "orange" }
]
</code></pre>
|
[
{
"answer_id": 74465138,
"author": "access_granted",
"author_id": 5812981,
"author_profile": "https://Stackoverflow.com/users/5812981",
"pm_score": 1,
"selected": false,
"text": "SELECT LEAST(13, 6); \nSELECT LEAST( to_char(date1,'YYYYMMDD'), to_char(date2,'YYYYMMDD') ) ...\n"
},
{
"answer_id": 74466239,
"author": "Fred",
"author_id": 11552426,
"author_profile": "https://Stackoverflow.com/users/11552426",
"pm_score": 0,
"selected": false,
"text": "SELECT LEAST(CAST(CURRENT_TIMESTAMP(0) AS TIMESTAMP(0)),\n MAX(DTM) + INTERVAL '90' DAY)\nFROM BILLS;\n"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74464932",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9971923/"
] |
74,464,935
|
<p>My Laravel links keep breaking each time I restart my local server</p>
<p>So, I am using Laravel 9 and my links keep breaking each time I reload the page or when I restart the server
For example</p>
<p>127.0.0.1:8000/cars/1/edit</p>
<p>will become <code>127.0.0.1:8000/cars/cars/1/edit</code> next time I click it.</p>
<p>I have searched for a solution and stumbled upon this <a href="https://stackoverflow.com/q/58711450/15770919">On every click link changes in blade view</a></p>
<p>But the problem is that the guy that asked the question is using named routes from web.php route</p>
<p>I, on the other hand, am using resource routes ( I do not know what to call them = <code>Route::resource('/cars', CarsController::class);)</code><a href="https://i.stack.imgur.com/1eHEj.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/1eHEj.png" alt="Resouce route" /></a></p>
<p>For that reason, I'm finding it difficult to implement the route() solution proposed as his had a named route name</p>
<p>The href I want to make changes to looks like this. I am using resources routes in web.php</p>
<pre><code><a href="cars/{{ $car['id'] }}/edit">Edit &rarr;</a>
</code></pre>
<p><a href="https://i.stack.imgur.com/uY4mK.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/uY4mK.png" alt="Href I want to edit" /></a></p>
|
[
{
"answer_id": 74464993,
"author": "Pouria Jahedi",
"author_id": 8509638,
"author_profile": "https://Stackoverflow.com/users/8509638",
"pm_score": 1,
"selected": false,
"text": "\n<a href='{{ url(\"cars/\".$car['id'].\"/edit\") }}'> edit </a>\n\n"
},
{
"answer_id": 74465047,
"author": "xenooooo",
"author_id": 20283630,
"author_profile": "https://Stackoverflow.com/users/20283630",
"pm_score": 2,
"selected": false,
"text": "route()"
},
{
"answer_id": 74465088,
"author": "Dream Bold",
"author_id": 12743692,
"author_profile": "https://Stackoverflow.com/users/12743692",
"pm_score": 0,
"selected": false,
"text": "<a href=\"<?php echo route('cars', ['id' => $car['id'])?>\">Edit</a>\n"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74464935",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15770919/"
] |
74,464,939
|
<p>What is the DBClients recommended way to work with a large number of rows?</p>
<p>I am currently using the <a href="https://helidon.io/docs/latest/apidocs/io.helidon.dbclient/io/helidon/dbclient/DbStatement.html#execute()" rel="nofollow noreferrer">execute()</a> API on <a href="https://helidon.io/docs/latest/apidocs/io.helidon.dbclient/io/helidon/dbclient/DbStatement.html" rel="nofollow noreferrer">DbStatement</a> that returns Multi. Will this download the whole universe into JVM memory or does it internally stream in batches? If it is paging/batching the resultset, is there some API that should be used to hint the fetch size?</p>
<p>--</p>
<p>jOOQ exposes <a href="https://www.jooq.org/javadoc/latest/org.jooq/org/jooq/conf/Settings.html#setFetchSize(java.lang.Integer)" rel="nofollow noreferrer">Settings.setFetchSize</a> to globally hint the fetch size for all jOOQ queries, which I believe is directly bound to JDBC Statement’s <a href="https://docs.oracle.com/en/java/javase/17/docs/api/java.sql/java/sql/Statement.html#setFetchSize(int)" rel="nofollow noreferrer">setFetchSize</a> API.</p>
<p>Does DBClient have any similar setup?</p>
|
[
{
"answer_id": 74470741,
"author": "Ashwin Prabhu",
"author_id": 177784,
"author_profile": "https://Stackoverflow.com/users/177784",
"pm_score": 3,
"selected": true,
"text": "dbClient.execute(\n dbExecute -> dbExecute.createQuery(sql).execute()\n).map(dbRow -> <doSomething>)\n"
},
{
"answer_id": 74481713,
"author": "Barchetta",
"author_id": 8067392,
"author_profile": "https://Stackoverflow.com/users/8067392",
"pm_score": 1,
"selected": false,
"text": "doSomething"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74464939",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/177784/"
] |
74,464,989
|
<p>I have to add every number with one behind it in the list using loops or functions</p>
<p>example text;</p>
<pre><code>list[1,2,3] => (1+3)+(2+1)+(3+2)
</code></pre>
<p>output = 12</p>
<p>example code;</p>
<pre><code>myList = [1,2,3]
x = myList [0] + myList [2]
x = x + (myList [1]+myList [0])
x = x + (myList [2]+myList [1])
print(x) # 12
</code></pre>
<p>I dont want to calculate them using <code>sum() or just like 1+2+3 </code></p>
|
[
{
"answer_id": 74465054,
"author": "Jay",
"author_id": 8677071,
"author_profile": "https://Stackoverflow.com/users/8677071",
"pm_score": 1,
"selected": false,
"text": "list[-1]"
},
{
"answer_id": 74465080,
"author": "Barmar",
"author_id": 1491895,
"author_profile": "https://Stackoverflow.com/users/1491895",
"pm_score": 2,
"selected": true,
"text": "total = 0\nfor i in range(len(myList)):\n total += myList[i] + myList[i-1]\nprint(total)\n"
},
{
"answer_id": 74465091,
"author": "Abdul Gaffar",
"author_id": 3975244,
"author_profile": "https://Stackoverflow.com/users/3975244",
"pm_score": 0,
"selected": false,
"text": ">>> [x+mylist[i-1] for i, x in enumerate(mylist)]\n[4, 3, 5]\n"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74464989",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18745426/"
] |
74,465,004
|
<p>I'm working with data from my Spotify account and I've created a dataframe that contains all the minutes in the day and the total playtime during that minute for the last 5 years. The dataframe is this (by the way, I wonder if there is any way to work with time without having to select a specific date):</p>
<pre><code> time playtime
0 1970-01-01 00:00:00 47.138733
1 1970-01-01 00:01:00 52.419767
2 1970-01-01 00:02:00 47.943567
3 1970-01-01 00:03:00 43.322283
4 1970-01-01 00:04:00 58.029217
... ... ...
1435 1970-01-01 23:55:00 46.276150
1436 1970-01-01 23:56:00 53.202717
1437 1970-01-01 23:57:00 49.844367
1438 1970-01-01 23:58:00 62.703600
1439 1970-01-01 23:59:00 55.437700
</code></pre>
<p>I've plotted the dataframe in order to obtain a visualization of how much music I listen during the day. This is the graph:</p>
<p><a href="https://i.stack.imgur.com/QNIkU.png" rel="nofollow noreferrer">enter image description here</a></p>
<p>There are 1440 points, so outliers will appear. But, as you can probably see, there is a smooth curve that emerges from the graph. I want to get the actual smooth graph, but every method that I see uses interpolation and I don't think interpolating 1440 points is efficient. Is there any way to get a moving average or something similar so that I can plot a smooth curve?</p>
<p>I've tried interpolating, but there are too many points and it takes ages to run.</p>
|
[
{
"answer_id": 74465054,
"author": "Jay",
"author_id": 8677071,
"author_profile": "https://Stackoverflow.com/users/8677071",
"pm_score": 1,
"selected": false,
"text": "list[-1]"
},
{
"answer_id": 74465080,
"author": "Barmar",
"author_id": 1491895,
"author_profile": "https://Stackoverflow.com/users/1491895",
"pm_score": 2,
"selected": true,
"text": "total = 0\nfor i in range(len(myList)):\n total += myList[i] + myList[i-1]\nprint(total)\n"
},
{
"answer_id": 74465091,
"author": "Abdul Gaffar",
"author_id": 3975244,
"author_profile": "https://Stackoverflow.com/users/3975244",
"pm_score": 0,
"selected": false,
"text": ">>> [x+mylist[i-1] for i, x in enumerate(mylist)]\n[4, 3, 5]\n"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74465004",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13268177/"
] |
74,465,018
|
<p>I need to convert the value in the column 'value' to a list format.
The dataframe df:</p>
<pre><code> emp_no value
0 390 10.0
1 395 20.0
2 397 30.0
3 522 40.0
4 525 40.0
</code></pre>
<p>Output should be:</p>
<pre><code> emp_no value
0 390 [5,10.0]
1 395 [5,20.0]
2 397 [5,30.0]
3 522 [5,40.0]
4 525 [5,40.0]
</code></pre>
|
[
{
"answer_id": 74465054,
"author": "Jay",
"author_id": 8677071,
"author_profile": "https://Stackoverflow.com/users/8677071",
"pm_score": 1,
"selected": false,
"text": "list[-1]"
},
{
"answer_id": 74465080,
"author": "Barmar",
"author_id": 1491895,
"author_profile": "https://Stackoverflow.com/users/1491895",
"pm_score": 2,
"selected": true,
"text": "total = 0\nfor i in range(len(myList)):\n total += myList[i] + myList[i-1]\nprint(total)\n"
},
{
"answer_id": 74465091,
"author": "Abdul Gaffar",
"author_id": 3975244,
"author_profile": "https://Stackoverflow.com/users/3975244",
"pm_score": 0,
"selected": false,
"text": ">>> [x+mylist[i-1] for i, x in enumerate(mylist)]\n[4, 3, 5]\n"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74465018",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20418639/"
] |
74,465,042
|
<p>I know how to name variables in classes but how does it relate to functions? I've noticed that some devs use final keywords for variables that never change in functions, but the others use var even in functions.</p>
<p>Which of the following examples is recommended in terms of clean code and speed?</p>
<pre class="lang-dart prettyprint-override"><code>doSomething() {
final int i = 1;
print(i.toString());
}
doSomething() {
final i = 1;
print(i.toString());
}
doSomething() {
int i = 1;
print(i.toString());
}
doSomething() {
var i = 1;
print(i.toString());
}
</code></pre>
|
[
{
"answer_id": 74465114,
"author": "LacticWhale",
"author_id": 11962301,
"author_profile": "https://Stackoverflow.com/users/11962301",
"pm_score": 0,
"selected": false,
"text": "dart pub add lints"
},
{
"answer_id": 74465152,
"author": "MendelG",
"author_id": 12349734,
"author_profile": "https://Stackoverflow.com/users/12349734",
"pm_score": 1,
"selected": false,
"text": "var"
},
{
"answer_id": 74465208,
"author": "TarHalda",
"author_id": 15170120,
"author_profile": "https://Stackoverflow.com/users/15170120",
"pm_score": 2,
"selected": true,
"text": "final"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74465042",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16846281/"
] |
74,465,057
|
<p>I'm scraping <a href="https://www.helpmycash.com/hipotecas/hipotecas-interes-fijo/" rel="nofollow noreferrer">this site</a>, specifically the content of the tables inside the <code>div</code> tags with <code>class</code> containing <code>'ranking-data'</code>. So for the first <code>td</code> that would be:
<code>//div[contains(@class, 'ranking-data')]//tr[th//text()[contains(., 'TIN')]]/td[1]/text()"</code></p>
<p>This is working fine for all columns in all tables (with needed modifications) except for a cell in column 2 that contains an <code>i</code> tag: on Google Spreadsheets it adds an extra blank cell below the cell with the text itself. I've first tried to scrap it with:
<code>//div[contains(@class, 'ranking-data')]//tr[th//text()[contains(., 'TIN')]]/td[2]/text()</code></p>
<p>Then I've tried something like <code>*[not(i[contains(@class,'info-circle')])]/text()</code> after the <code>td[2]</code>, and some other variants, but it doesn't work.</p>
<p>How can I avoid this <code>i</code> tag?</p>
|
[
{
"answer_id": 74465114,
"author": "LacticWhale",
"author_id": 11962301,
"author_profile": "https://Stackoverflow.com/users/11962301",
"pm_score": 0,
"selected": false,
"text": "dart pub add lints"
},
{
"answer_id": 74465152,
"author": "MendelG",
"author_id": 12349734,
"author_profile": "https://Stackoverflow.com/users/12349734",
"pm_score": 1,
"selected": false,
"text": "var"
},
{
"answer_id": 74465208,
"author": "TarHalda",
"author_id": 15170120,
"author_profile": "https://Stackoverflow.com/users/15170120",
"pm_score": 2,
"selected": true,
"text": "final"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74465057",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2683259/"
] |
74,465,060
|
<p>I have 2 tables. <strong>Table 1</strong> is the main table but the name's are messy. I would like to use <strong>Table 2</strong> to map in the Name_Simplified. I have tried xlookup with wildcards but I don't know how to apply it in reverse for this.</p>
<p>Any help greatly appreciated!</p>
<p><strong>TABLE 1</strong></p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Original Name</th>
</tr>
</thead>
<tbody>
<tr>
<td>Amazon LA</td>
</tr>
<tr>
<td>Amazon LTD New York</td>
</tr>
<tr>
<td>Dallas Amazon</td>
</tr>
<tr>
<td>AMZ.com</td>
</tr>
<tr>
<td>AMZ online</td>
</tr>
<tr>
<td>Home Depot</td>
</tr>
<tr>
<td>The Home Depot</td>
</tr>
</tbody>
</table>
</div>
<p><strong>TABLE 2</strong></p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Contains_Name</th>
<th>Name_Simplified</th>
</tr>
</thead>
<tbody>
<tr>
<td>Amazon</td>
<td>Amazon</td>
</tr>
<tr>
<td>AMZ</td>
<td>Amazon</td>
</tr>
<tr>
<td>Home Depot</td>
<td>Home Depot</td>
</tr>
</tbody>
</table>
</div>
<p>The Result I am looking for:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Original Name</th>
<th>Name_Simplified</th>
</tr>
</thead>
<tbody>
<tr>
<td>Amazon LA</td>
<td>Amazon</td>
</tr>
<tr>
<td>Amazon LTD New York</td>
<td>Amazon</td>
</tr>
<tr>
<td>Dallas Amazon</td>
<td>Amazon</td>
</tr>
<tr>
<td>AMZ.com</td>
<td>Amazon</td>
</tr>
<tr>
<td>AMZ online</td>
<td>Amazon</td>
</tr>
<tr>
<td>Home Depot</td>
<td>Home Depot</td>
</tr>
<tr>
<td>The Home Depot</td>
<td>Home Depot</td>
</tr>
</tbody>
</table>
</div>
|
[
{
"answer_id": 74465114,
"author": "LacticWhale",
"author_id": 11962301,
"author_profile": "https://Stackoverflow.com/users/11962301",
"pm_score": 0,
"selected": false,
"text": "dart pub add lints"
},
{
"answer_id": 74465152,
"author": "MendelG",
"author_id": 12349734,
"author_profile": "https://Stackoverflow.com/users/12349734",
"pm_score": 1,
"selected": false,
"text": "var"
},
{
"answer_id": 74465208,
"author": "TarHalda",
"author_id": 15170120,
"author_profile": "https://Stackoverflow.com/users/15170120",
"pm_score": 2,
"selected": true,
"text": "final"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74465060",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12954974/"
] |
74,465,101
|
<p>If I type any Nodejs command in Vscode Terminal there comes the error</p>
<blockquote>
<p>The term "nodemon" was not recognized as the name of a cmdlet, function, script file, or executable program. Check the spelling of the name, or if the path is correct (if included),
and repeat the process.</p>
</blockquote>
<p>It also doesn't works in external Terminal but it works in Terminal which isn't opened by VSCode.</p>
<p>Thanks for your help!</p>
|
[
{
"answer_id": 74465114,
"author": "LacticWhale",
"author_id": 11962301,
"author_profile": "https://Stackoverflow.com/users/11962301",
"pm_score": 0,
"selected": false,
"text": "dart pub add lints"
},
{
"answer_id": 74465152,
"author": "MendelG",
"author_id": 12349734,
"author_profile": "https://Stackoverflow.com/users/12349734",
"pm_score": 1,
"selected": false,
"text": "var"
},
{
"answer_id": 74465208,
"author": "TarHalda",
"author_id": 15170120,
"author_profile": "https://Stackoverflow.com/users/15170120",
"pm_score": 2,
"selected": true,
"text": "final"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74465101",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20469384/"
] |
74,465,139
|
<p>Hey I'm trying to change the font of everything in this code block and I'm not sure how this is what is given</p>
<pre><code><div>
<iframe
id="waitlist_iframe"
title="waitlist"
frameborder="0"
marginheight="0"
marginwidth="0"
width="600px"
height="400px"
src="{code}"
style="border-radius: 8px;"
>
</iframe>
</div>
<script>
const url = new URL(window.location.href);
const ref_id = url.searchParams.get('ref_id');
if (ref_id) {
document.getElementById("waitlist_iframe").src += `?ref_id=${ref_id}`;
}
</script>
</code></pre>
<pre><code>.container--waitlistapi // outermost div containing the component
.container--waitlistapi > h1 // main heading
.button--waitlistapi // main submit button
.input--waitlistapi // input fields
.statusToggleLabel // "Signed up before?" label
.statusToggleLabel > a // "Check your status" link
</code></pre>
<p>Nothing is changing when I attempt</p>
|
[
{
"answer_id": 74465114,
"author": "LacticWhale",
"author_id": 11962301,
"author_profile": "https://Stackoverflow.com/users/11962301",
"pm_score": 0,
"selected": false,
"text": "dart pub add lints"
},
{
"answer_id": 74465152,
"author": "MendelG",
"author_id": 12349734,
"author_profile": "https://Stackoverflow.com/users/12349734",
"pm_score": 1,
"selected": false,
"text": "var"
},
{
"answer_id": 74465208,
"author": "TarHalda",
"author_id": 15170120,
"author_profile": "https://Stackoverflow.com/users/15170120",
"pm_score": 2,
"selected": true,
"text": "final"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74465139",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14389743/"
] |
74,465,147
|
<p>I wanto to create a crossword puzzles's solver with Lua. I'm not used to this language tho and my english is poor, sorry for that.</p>
<p>I have to iterate multiples times the same table of tables checking if the given word is present or not and, if present, replace every char of that word in the table with a "*" simbol.</p>
<p>For example:</p>
<pre><code>schema= {
{"A","B","C","D","H","F","G","W","T","Y"},
{"U","H","E","L","L","O","I","I","O","L"},
{"G","F","D","R","Y","T","R","G","R","R"}}
function(schema,"HELLO")
schema= {
{"A","B","C","D","H","F","G","W","T","Y"},
{"U","*","*","*","*","*","I","I","O","L"},
{"G","F","D","R","Y","T","R","G","R","R"}}
</code></pre>
<p>For now i'm focusing on find the word scanning the table from left to right. Here's my code:</p>
<pre><code>i = 1
t = {}
for k,w in pairs(schema) do
t[k] = w
end
cercaPrima = function(tabella,stringa)
for v = 1, 10 do
if string.sub(stringa,1,1) == t[i][v] then
print(t[i][v]) v = v+1
return cercaDS(t,stringa,i,v)
else
v = v+1
end
end
if i < #t then
i = i+1
cercaPrima(tabella,stringa)
else
return print("?")
end
end
cercaDS = function(tabella,stringa,d,s)
local o = 2
local l = 2
while o <= #stringa do
if string.sub(stringa,o,l) == tabella[d][s] then
print(tabella[d][s])
tabella[d][s] = "*"
s=s+1
o=o+1
l=l+1
else
l=l-1
s=s-l
o=#stringa+1
tabella[d][s] = "*"
return cercaPrima(tabella,stringa)
end
end
end
cercaPrima(schema,"HELLO")
</code></pre>
<p>It's probably overcomplicated, but my question is: How can I make it ignore the first "H" (not turning it into a "*") while keep iterating the table looking for another "H" who fits the criteria?</p>
<p>My goal is to create a function who takes a table and a list of words in input, iterates the table looking for every single word, if it finds them all it replaces every char of every word found in the table with a "*" and print the remaining characters as a string.</p>
<p>Another problem that i'll probabily have is: what if a char of a word is a char of another word too? It will read "*" instead of the real char if it has already found the first word.</p>
<p>Should I create a new table for every word I'm looking for? But then how can i merge those table togheter to extrapolate the remaining characters?</p>
<p>Thank you for your help!</p>
|
[
{
"answer_id": 74465114,
"author": "LacticWhale",
"author_id": 11962301,
"author_profile": "https://Stackoverflow.com/users/11962301",
"pm_score": 0,
"selected": false,
"text": "dart pub add lints"
},
{
"answer_id": 74465152,
"author": "MendelG",
"author_id": 12349734,
"author_profile": "https://Stackoverflow.com/users/12349734",
"pm_score": 1,
"selected": false,
"text": "var"
},
{
"answer_id": 74465208,
"author": "TarHalda",
"author_id": 15170120,
"author_profile": "https://Stackoverflow.com/users/15170120",
"pm_score": 2,
"selected": true,
"text": "final"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74465147",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20522339/"
] |
74,465,173
|
<p>I googled and I found out the solution for Python and SQL but not for R coding.</p>
<p>I attach an example of a dataframe called df1 in order to be easy to understand.</p>
<pre><code>Genus Species Genusspecie
Escherichia coli Escherichia coli
Campylobacter NA NA
Shigella sonnei Shigella sonnei
</code></pre>
<p>If exists NA in df1 is only in the variable column of Specie.</p>
<p>Then I desire that if NA exists in Specie the complete species name (new variable created called Genusspecie) appears NA. If Genus and Specie are both informed, I desire to obtain the completne specie name.</p>
<p>I tried the command paste but then I will need to transform the string cells of dataframe containing NA to a string cell only containing NA without genus information.</p>
<pre><code>
df1$Genusspecie <- paste(taxa2$Genus, taxa2$Species)
</code></pre>
<p>Thanks on advance for your help,</p>
|
[
{
"answer_id": 74465114,
"author": "LacticWhale",
"author_id": 11962301,
"author_profile": "https://Stackoverflow.com/users/11962301",
"pm_score": 0,
"selected": false,
"text": "dart pub add lints"
},
{
"answer_id": 74465152,
"author": "MendelG",
"author_id": 12349734,
"author_profile": "https://Stackoverflow.com/users/12349734",
"pm_score": 1,
"selected": false,
"text": "var"
},
{
"answer_id": 74465208,
"author": "TarHalda",
"author_id": 15170120,
"author_profile": "https://Stackoverflow.com/users/15170120",
"pm_score": 2,
"selected": true,
"text": "final"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74465173",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20522749/"
] |
74,465,180
|
<p>I'd like to know if <a href="https://www.php.net/manual/en/function.fstat" rel="nofollow noreferrer">fstat()</a> is cached.</p>
<p>Documentation says nothing about it.</p>
<p>(PHP 8.1.12)</p>
<p><strong>EDIT:</strong></p>
<p>I made a LOT of tests, I have now an accurate answer for that.</p>
<p><strong>Introduction:</strong></p>
<p>I created two scripts and ran them both simultaneously (locking the file pointer with an exclusive lock (<a href="https://www.php.net/manual/en/function.flock" rel="nofollow noreferrer">flock($fp, LOCK_EX)</a>)* to prevent them from overwriting each other) and on their own; I printed <a href="https://www.php.net/manual/en/function.print-r" rel="nofollow noreferrer">print_r</a>(<a href="https://www.php.net/manual/en/function.fstat" rel="nofollow noreferrer">fstat($fp)</a>) at various stages of a loop that led to writing 5 MB of data. I also used <a href="https://www.php.net/manual/en/function.var-dump" rel="nofollow noreferrer">var_dump</a>(<a href="https://www.php.net/manual/en/function.realpath-cache-get.php" rel="nofollow noreferrer">realpath_cache_get()</a>)</p>
<blockquote>
<p>Returns an array of realpath cache entries. The keys are original path entries, and the values are arrays of data items, containing the resolved path, expiration date, and other options kept in the cache.</p>
</blockquote>
<p>to detect the realpath cache and ran tests trying to clear and not clear the cache via <a href="https://www.php.net/manual/en/function.clearstatcache.php" rel="nofollow noreferrer">clearstatcache()</a>.</p>
<p><strong>What happened:</strong></p>
<p>I found that the only item that gets cached is 'atime'</p>
<blockquote>
<p>time of last access (Unix timestamp)</p>
</blockquote>
<p>, but most upsetting of all: it is not put in the realpath cache, consequently nothing will change if you clear it via <a href="https://www.php.net/manual/en/function.clearstatcache.php" rel="nofollow noreferrer">clearstatcache()</a>, you can only restart the machine or wait for the cache timeout to clear the data (depending on the machine).</p>
<p>Fortunately this doesn't affect me since I only need 'size' element of fstat. Sadly I cannot give you the source code cause I changed it a lot of time to try all possibilities.</p>
<p>Thank you to everyone who spent time to help me.</p>
<p>*NOTE: Use flock in both files, if you use it only in one the other file will be able to write in the not locked file that has been ran before</p>
<p><strong>CONCLUSION</strong></p>
<p>The only cached element of <a href="https://www.php.net/manual/en/function.flock" rel="nofollow noreferrer">fstat</a> is atime, but it is not cached in the <a href="https://www.php.net/manual/en/function.realpath-cache-get.php" rel="nofollow noreferrer">realpath</a>, so <a href="https://www.php.net/manual/en/function.clearstatcache.php" rel="nofollow noreferrer">clearstatcache()</a> is useless</p>
|
[
{
"answer_id": 74465875,
"author": "Chris Haas",
"author_id": 231316,
"author_profile": "https://Stackoverflow.com/users/231316",
"pm_score": 1,
"selected": false,
"text": "$filename = __DIR__.'/test.txt';\n\n@unlink($filename);\ntouch($filename);\necho 'STAT - Size before write: '.stat($filename)['size'], PHP_EOL;\nfile_put_contents($filename, 'test');\necho 'STAT - Size after write: '.stat($filename)['size'], PHP_EOL;\nclearstatcache();\necho 'STAT - Size after cache clear: '.stat($filename)['size'], PHP_EOL;\n\n@unlink($filename);\ntouch($filename);\n$fp = fopen($filename, 'wb');\necho 'FSTAT - Size before write: '.fstat($fp)['size'], PHP_EOL;\nfwrite($fp, 'test');\necho 'FSTAT - Size after write: '.fstat($fp)['size'], PHP_EOL;\nclearstatcache();\necho 'FSTAT - Size after cache clear: '.fstat($fp)['size'], PHP_EOL;\n"
},
{
"answer_id": 74471803,
"author": "jspit",
"author_id": 7271221,
"author_profile": "https://Stackoverflow.com/users/7271221",
"pm_score": 0,
"selected": false,
"text": "/*\n * Open test.txt with a text editor\n * Run this script\n * Add some characters in the editor and save while the script is running\n */\n$file = __DIR__.'/../test/test.txt';\n$fp = fopen($file,'r');\n$size[] = fstat($fp)['size'];\nsleep(10);\n$size[] = fstat($fp)['size'];\nvar_dump($size);\n//array(2) { [0]=> int(3) [1]=> int(13) }\n"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74465180",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18302645/"
] |
74,465,232
|
<p>I have this huge check in Form values of Angular Application and I need to refactor.</p>
<pre><code>((this.dropdownSearchForm.get('name').value === undefined || this.dropdownSearchForm.get('name').value === null || this.dropdownSearchForm.get('name').value.length === 0) &&
(this.dropdownSearchForm.get('status').value === undefined || this.dropdownSearchForm.get('status').value === null || this.dropdownSearchForm.get('status').value.length === 0) &&
(this.dropdownSearchForm.get('address').value === undefined || this.dropdownSearchForm.get('address').value === null || this.dropdownSearchForm.get('address').value.length === 0) &&
(this.dropdownSearchForm.get('edu').value === undefined || this.dropdownSearchForm.get('edu').value === null || this.dropdownSearchForm.get('edu').value.length === 0) &&
(this.dropdownSearchForm.get('salary').value === undefined || this.dropdownSearchForm.get('salary').value === null || this.dropdownSearchForm.get('salary').value.length === 0));
</code></pre>
<p>How can I simplify this with Typescript utils to achieve the same result with minimum code?</p>
<p>Note: Angular forms touch or pristine doesn't work. So checking this logic to validate form values.</p>
<p>I tried checking type of and it didn't work for some reason.</p>
|
[
{
"answer_id": 74465875,
"author": "Chris Haas",
"author_id": 231316,
"author_profile": "https://Stackoverflow.com/users/231316",
"pm_score": 1,
"selected": false,
"text": "$filename = __DIR__.'/test.txt';\n\n@unlink($filename);\ntouch($filename);\necho 'STAT - Size before write: '.stat($filename)['size'], PHP_EOL;\nfile_put_contents($filename, 'test');\necho 'STAT - Size after write: '.stat($filename)['size'], PHP_EOL;\nclearstatcache();\necho 'STAT - Size after cache clear: '.stat($filename)['size'], PHP_EOL;\n\n@unlink($filename);\ntouch($filename);\n$fp = fopen($filename, 'wb');\necho 'FSTAT - Size before write: '.fstat($fp)['size'], PHP_EOL;\nfwrite($fp, 'test');\necho 'FSTAT - Size after write: '.fstat($fp)['size'], PHP_EOL;\nclearstatcache();\necho 'FSTAT - Size after cache clear: '.fstat($fp)['size'], PHP_EOL;\n"
},
{
"answer_id": 74471803,
"author": "jspit",
"author_id": 7271221,
"author_profile": "https://Stackoverflow.com/users/7271221",
"pm_score": 0,
"selected": false,
"text": "/*\n * Open test.txt with a text editor\n * Run this script\n * Add some characters in the editor and save while the script is running\n */\n$file = __DIR__.'/../test/test.txt';\n$fp = fopen($file,'r');\n$size[] = fstat($fp)['size'];\nsleep(10);\n$size[] = fstat($fp)['size'];\nvar_dump($size);\n//array(2) { [0]=> int(3) [1]=> int(13) }\n"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74465232",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19584581/"
] |
74,465,242
|
<p>I have a json fragment like below. I want to return the value of the name key together with the value of the version key if the version key has a value. The expected output is "name": "value" , "version" : "value"</p>
<p>It is better to have a solution with grep or jq.</p>
<pre><code>node ~/wappalyzer/src/drivers/npm/cli.js https://youtube.com | jq .
</code></pre>
<p>Result:</p>
<pre class="lang-json prettyprint-override"><code>{
"urls": {
"https://youtube.com/": {
"status": 301
},
"https://www.youtube.com/": {
"status": 200
}
},
"technologies": [
{
"slug": "youtube",
"name": "YouTube",
"description": "YouTube is a video sharing service where users can create their own profile, upload videos, watch, like and comment on other videos.",
"confidence": 100,
"version": null,
"icon": "YouTube.png",
"website": "http://www.youtube.com",
"cpe": null,
"categories": [
{
"id": 14,
"slug": "video-players",
"name": "Video players"
}
],
"rootPath": true
},
{
"slug": "polymer",
"name": "Polymer",
"description": null,
"confidence": 100,
"version": "3.5.0",
"icon": "Polymer.png",
"website": "http://polymer-project.org",
"cpe": null,
"categories": [
{
"id": 12,
"slug": "javascript-frameworks",
"name": "JavaScript frameworks"
}
],
"rootPath": true
},
{
"slug": "google-ads",
"name": "Google Ads",
"description": "Google Ads is an online advertising platform developed by Google.",
"confidence": 100,
"version": null,
"icon": "Google Ads.svg",
"website": "https://ads.google.com",
"cpe": null,
"categories": [
{
"id": 36,
"slug": "advertising",
"name": "Advertising"
}
]
},
{
"slug": "hammer-js",
"name": "Hammer.js",
"description": null,
"confidence": 100,
"version": "2.0.2",
"icon": "Hammer.js.png",
"website": "https://hammerjs.github.io",
"cpe": null,
"categories": [
{
"id": 59,
"slug": "javascript-libraries",
"name": "JavaScript libraries"
}
],
"rootPath": true
},
{
"slug": "google-font-api",
"name": "Google Font API",
"description": "Google Font API is a web service that supports open-source font files that can be used on your web designs.",
"confidence": 100,
"version": null,
"icon": "Google Font API.png",
"website": "http://google.com/fonts",
"cpe": null,
"categories": [
{
"id": 17,
"slug": "font-scripts",
"name": "Font scripts"
}
],
"rootPath": true
},
{
"slug": "recaptcha",
"name": "reCAPTCHA",
"description": "reCAPTCHA is a free service from Google that helps protect websites from spam and abuse.",
"confidence": 100,
"version": null,
"icon": "reCAPTCHA.svg",
"website": "https://www.google.com/recaptcha/",
"cpe": null,
"categories": [
{
"id": 16,
"slug": "security",
"name": "Security"
}
]
},
{
"slug": "google-ads-conversion-tracking",
"name": "Google Ads Conversion Tracking",
"description": "Google Ads Conversion Tracking is a free tool that shows you what happens after a customer interacts with your ads.",
"confidence": 100,
"version": null,
"icon": "Google.svg",
"website": "https://support.google.com/google-ads/answer/1722022",
"cpe": null,
"categories": [
{
"id": 10,
"slug": "analytics",
"name": "Analytics"
}
]
},
{
"slug": "hsts",
"name": "HSTS",
"description": "HTTP Strict Transport Security (HSTS) informs browsers that the site should only be accessed using HTTPS.",
"confidence": 100,
"version": null,
"icon": "default.svg",
"website": "https://www.rfc-editor.org/rfc/rfc6797#section-6.1",
"cpe": null,
"categories": [
{
"id": 16,
"slug": "security",
"name": "Security"
}
],
"rootPath": true
},
{
"slug": "webpack",
"name": "webpack",
"description": "Webpack is an open-source JavaScript module bundler.",
"confidence": 50,
"version": null,
"icon": "webpack.svg",
"website": "https://webpack.js.org/",
"cpe": null,
"categories": [
{
"id": 19,
"slug": "miscellaneous",
"name": "Miscellaneous"
}
]
},
{
"slug": "pwa",
"name": "PWA",
"description": "Progressive Web Apps (PWAs) are web apps built and enhanced with modern APIs to deliver enhanced capabilities, reliability, and installability while reaching anyone, anywhere, on any device, all with a single codebase.",
"confidence": 100,
"version": null,
"icon": "PWA.svg",
"website": "https://web.dev/progressive-web-apps/",
"cpe": null,
"categories": [
{
"id": 19,
"slug": "miscellaneous",
"name": "Miscellaneous"
}
],
"rootPath": true
},
{
"slug": "open-graph",
"name": "Open Graph",
"description": "Open Graph is a protocol that is used to integrate any web page into the social graph.",
"confidence": 100,
"version": null,
"icon": "Open Graph.png",
"website": "https://ogp.me",
"cpe": null,
"categories": [
{
"id": 19,
"slug": "miscellaneous",
"name": "Miscellaneous"
}
],
"rootPath": true
},
{
"slug": "module-federation",
"name": "Module Federation",
"description": "Module Federation is a webpack technology for dynamically loading parts of other independently deployed builds.",
"confidence": 50,
"version": null,
"icon": "Module Federation.png",
"website": "https://webpack.js.org/concepts/module-federation/",
"cpe": null,
"categories": [
{
"id": 19,
"slug": "miscellaneous",
"name": "Miscellaneous"
}
]
},
{
"slug": "http-3",
"name": "HTTP/3",
"description": "HTTP/3 is the third major version of the Hypertext Transfer Protocol used to exchange information on the World Wide Web.",
"confidence": 100,
"version": null,
"icon": "HTTP3.svg",
"website": "https://httpwg.org/",
"cpe": null,
"categories": [
{
"id": 19,
"slug": "miscellaneous",
"name": "Miscellaneous"
}
],
"rootPath": true
}
]
}
</code></pre>
<p><strong>I expect this:</strong></p>
<p>Polymer 3.5.0</p>
<p>Hammer.js 2.0.2</p>
|
[
{
"answer_id": 74465340,
"author": "pmf",
"author_id": 2158479,
"author_profile": "https://Stackoverflow.com/users/2158479",
"pm_score": 1,
"selected": false,
"text": "//"
},
{
"answer_id": 74465747,
"author": "glenn jackman",
"author_id": 7552,
"author_profile": "https://Stackoverflow.com/users/7552",
"pm_score": 1,
"selected": true,
"text": "jq -r '.[] | select(.version) | \"\\(.name) \\(.version)\"' file.json\n"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74465242",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20522711/"
] |
74,465,247
|
<p>I want to <code>split()</code> a string on both newlines <em><strong>and</strong></em> space characters:</p>
<pre><code>#!/usr/bin/perl
use warnings;
use strict;
my $str = "aa bb cc\ndd ee ff";
my @arr = split(/\s\n/, $str); # Split on ' ' and '\n'
print join("\n", @arr); # Print array, one element per line
</code></pre>
<p>Output is this:</p>
<pre><code>aa bb cc
dd ee ff
</code></pre>
<p>But, what I want is this:</p>
<pre><code>aa
bb
cc
dd
ee
ff
</code></pre>
<p>So my code is splitting on the newline (good) but not the spaces. <a href="https://perldoc.perl.org/perlrecharclass" rel="nofollow noreferrer">According to perldoc</a>, whitespace should be matched with <code>\s</code> in a character class, and I would have assumed that <code> </code> is whitespace. Am I missing something?</p>
|
[
{
"answer_id": 74465343,
"author": "toolic",
"author_id": 197758,
"author_profile": "https://Stackoverflow.com/users/197758",
"pm_score": 4,
"selected": true,
"text": "aa bb cc\\ndd ee ff"
},
{
"answer_id": 74465527,
"author": "ikegami",
"author_id": 589924,
"author_profile": "https://Stackoverflow.com/users/589924",
"pm_score": 3,
"selected": false,
"text": "split /[\\s\\n]/, $str\n"
},
{
"answer_id": 74468247,
"author": "TLP",
"author_id": 725418,
"author_profile": "https://Stackoverflow.com/users/725418",
"pm_score": 0,
"selected": false,
"text": "Data::Dumper"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74465247",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4040743/"
] |
74,465,250
|
<p>I would like to see the name of files modified in my git history, but not including one commit.</p>
<p>When I use the command: <code>git log --oneline</code>, git returns these commits:</p>
<p><a href="https://i.stack.imgur.com/ZPJkg.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ZPJkg.png" alt="git log" /></a></p>
<p>The problem is the commit <code>0810c44</code>. This commit because it is a sync commit and it contains a lot of files that were update, but they aren't needed for my current task (It contains a lot of files to synchronize with my local repo).</p>
<p><a href="https://i.stack.imgur.com/qrOY5.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/qrOY5.png" alt="git commit wiht a lot of files" /></a></p>
<p>I would like to see all name of file changed from the current HEAD to a previous commit (example, <code>824be3b</code>), but in a way that the commit <code>0810c44</code> is omitted, how can I do this?</p>
<h2>Git returns as text:</h2>
<p><code>git log --oneline</code></p>
<pre><code>9dfe1b9 (HEAD -> tmp_merge_branch) merge
0810c44 retrieved
ff16e9a (1362-bolecode) commerce user permission
3de9164 update flow filter
ec04c9e xml
8851063 add untracked permissions, profiles, etc...
252b039 object
b5db337 add new flows
d9cb7de add B2BCommerceUser Permission Set
f9dc6d2 add diferences from Merge
c0d5f11 remove files
824be3b check before deploy
3212074 restante
69ef93e retrieved
</code></pre>
<pre><code>PS C:\> git log --name-only
commit 9dfe1b9a919c2153f1af56cd21f13d750588b4f6 (HEAD -> tmp_merge_branch)
Author: Me
Date: Mon Nov 14 16:12:44 2022 -0300
merge
mergeFolder/classes/BoletoItauController.cls
mergeFolder/classes/RegisterBolecodeTest.cls
mergeFolder/flows/Boleto_Bolecode_Integration.flow
mergeFolder/flows/Boleto_Bolecode_Integration_On_Create.flow
mergeFolder/permissionsets/B2BCommerceUser.permissionset
commit 0810c44fc622d476d54d713b23c993891d7219df
Author: Me
Date: Mon Nov 14 14:14:42 2022 -0300
retrieved
mergeFolder/classes/BolecodeService.cls
mergeFolder/classes/BolecodeService.cls-meta.xml
mergeFolder/classes/BolecodeServiceTest.cls
mergeFolder/classes/BolecodeServiceTest.cls-meta.xml
mergeFolder/classes/BolecodeStructure.cls
mergeFolder/classes/BolecodeStructure.cls-meta.xml
mergeFolder/classes/BoletoApiService.cls
mergeFolder/classes/BoletoApiService.cls-meta.xml
mergeFolder/classes/BoletoApiServiceMock.cls
mergeFolder/classes/BoletoApiServiceMock.cls-meta.xml
mergeFolder/classes/BoletoApiServiceTest.cls
mergeFolder/classes/BoletoApiServiceTest.cls-meta.xml
mergeFolder/classes/BoletoBo.cls
mergeFolder/classes/BoletoBo.cls-meta.xml
mergeFolder/classes/BoletoDAO.cls
mergeFolder/classes/BoletoDAO.cls-meta.xml
mergeFolder/classes/BoletoItauController.cls
mergeFolder/classes/BoletoItauController.cls-meta.xml
mergeFolder/classes/BoletoService.cls
mergeFolder/classes/BoletoService.cls-meta.xml
<log with 74 files in total>
commit 9dfe1b9a919c2153f1af56cd21f13d750588b4f6 (HEAD -> tmp_merge_branch)
Author: Me
Date: Mon Nov 14 16:12:44 2022 -0300
merge
mergeFolder/classes/BoletoItauController.cls
mergeFolder/classes/RegisterBolecodeTest.cls
mergeFolder/flows/Boleto_Bolecode_Integration.flow
mergeFolder/flows/Boleto_Bolecode_Integration_On_Create.flow
mergeFolder/permissionsets/B2BCommerceUser.permissionset
</code></pre>
|
[
{
"answer_id": 74465343,
"author": "toolic",
"author_id": 197758,
"author_profile": "https://Stackoverflow.com/users/197758",
"pm_score": 4,
"selected": true,
"text": "aa bb cc\\ndd ee ff"
},
{
"answer_id": 74465527,
"author": "ikegami",
"author_id": 589924,
"author_profile": "https://Stackoverflow.com/users/589924",
"pm_score": 3,
"selected": false,
"text": "split /[\\s\\n]/, $str\n"
},
{
"answer_id": 74468247,
"author": "TLP",
"author_id": 725418,
"author_profile": "https://Stackoverflow.com/users/725418",
"pm_score": 0,
"selected": false,
"text": "Data::Dumper"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74465250",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8173813/"
] |
74,465,296
|
<p>I've no idea what I'm doing wrong in the following line of code and it's driving me nuts!
As you'll probably know from the code, I only want the <em><strong>if block</strong></em> to run if it's before 5.15pm.</p>
<pre><code>if time(datetime.now().hour,datetime.now().minute) < time(17, 15):
</code></pre>
<p>I've imported <code>date</code> and <code>datetime</code> so that's not the issue (it's <code>TypeError</code> error - see below error message I'm getting)</p>
<pre><code>Exception has occurred: TypeError (note: full exception trace is shown but execution is paused at: _run_module_as_main) 'module' object is not callable
</code></pre>
<p>Can someone advise on what I'm doing wrong</p>
|
[
{
"answer_id": 74465342,
"author": "Andrej Kesely",
"author_id": 10035985,
"author_profile": "https://Stackoverflow.com/users/10035985",
"pm_score": 2,
"selected": false,
"text": "from datetime import time"
},
{
"answer_id": 74465804,
"author": "SergFSM",
"author_id": 18344512,
"author_profile": "https://Stackoverflow.com/users/18344512",
"pm_score": 1,
"selected": false,
"text": "from datetime import datetime, time\n\ndatetime.now().time() < time(20,10) # False\n"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74465296",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6512922/"
] |
74,465,300
|
<p>As I mentioned in the title I have a problem properly embedding my animation in my <strong>Django</strong> project.</p>
<p>At some point, I decided to update the logo used by my web page built-in <strong>Django</strong>.
Having small experience with <strong>JavaScript</strong> I was looking for approaches that fit my needs.
I built an animation engine having some inspiration <a href="https://stackoverflow.com/a/9487083/15372196">from this <strong>StackOverflow</strong> answer.</a> <em>(Thanks to user <strong>gilly3</strong>)</em>.</p>
<p>My approach is, though, different in this topic because I realised that if I would have a lot of pictures then sticking/concatenating them together in one file might be difficult. I've decided to use another approach and use a bunch of files instead of one. For that sake, I built a function with a generator which I could call in another function to display all pictures in order. This <em>animation engine</em> looks like this:</p>
<pre><code>function* indexGenerator() {
let index = 1;
while (index < 28) {
yield index++;
}
if (index = 28)
yield* indexGenerator();
};
var number = indexGenerator();
setInterval(function animationslider()
{
var file = "<img src=\"../../../static/my_project/logos/media/slides_banner_f/slide_" + number.next().value + ".jpg\" />";
document.getElementById("animation-slider").innerHTML = file;
$("#animation-slider").fadeIn(1000);
}, 100);
</code></pre>
<p><code>$("#animation-slider").fadeIn(1000);</code> doesn't do the trick with values from 10-1000.
I record what this looks like:
<a href="https://youtu.be/RVBtLbBArh0" rel="nofollow noreferrer">https://youtu.be/RVBtLbBArh0</a></p>
<p>I suspect that the solution to the first relocation problem can be solved using <strong>CSS</strong>, but I don't know how to do it, yet.</p>
<p>The blinking/flickering of the animation is probably caused by loading all these images one by one. In the example video above, there are 28 of them. I wonder if this content would be loaded asynchronously (e.g. using <strong>Ajax</strong>) would it solve the problem? Is it possible to load all and after all is loaded, then display the animation (some sort of preloading)? I will be grateful for all suggestions and hints.</p>
<p>I'm aware that in the topic mentioned by me before there is a solution. But I'm curious about other approaches.</p>
|
[
{
"answer_id": 74465342,
"author": "Andrej Kesely",
"author_id": 10035985,
"author_profile": "https://Stackoverflow.com/users/10035985",
"pm_score": 2,
"selected": false,
"text": "from datetime import time"
},
{
"answer_id": 74465804,
"author": "SergFSM",
"author_id": 18344512,
"author_profile": "https://Stackoverflow.com/users/18344512",
"pm_score": 1,
"selected": false,
"text": "from datetime import datetime, time\n\ndatetime.now().time() < time(20,10) # False\n"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74465300",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15372196/"
] |
74,465,307
|
<p>For a project in C i need to work on a table that contains x differents 2 dimensionnals tables. However, i don't know how to create one, and how to call only one value [i,j] of one table into my general table [x,y] --> x and y are the coordinates of a table.
<a href="https://i.stack.imgur.com/7jEOB.png" rel="nofollow noreferrer">this is an example of a small version of my table</a>
Could you please help me to understand how to call my values to then use them in my for or if conditions, or is it imposssible to work on such tables in C?
Thank You</p>
<p>I tried to create a small version of two 3×3 tables into one 1×2 table. But even that did not work.
I already know how to work on an x×x table.</p>
<p>I tried to also represent what i will have to work on with a little drawing on paint <a href="https://i.stack.imgur.com/JehUQ.png" rel="nofollow noreferrer">drawing</a>. I hope this will help. My goal is the same, learn how to call just one element of every "intern array" that i will have (one the drawing for example calling X, X1, X2, ..., Xn)</p>
|
[
{
"answer_id": 74465342,
"author": "Andrej Kesely",
"author_id": 10035985,
"author_profile": "https://Stackoverflow.com/users/10035985",
"pm_score": 2,
"selected": false,
"text": "from datetime import time"
},
{
"answer_id": 74465804,
"author": "SergFSM",
"author_id": 18344512,
"author_profile": "https://Stackoverflow.com/users/18344512",
"pm_score": 1,
"selected": false,
"text": "from datetime import datetime, time\n\ndatetime.now().time() < time(20,10) # False\n"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74465307",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20522799/"
] |
74,465,310
|
<p>When I execute the following query, the name of any product appears, but not the product with the lowest price:</p>
<pre><code>SELECT MIN(Price), ProductName
FROM Products;
</code></pre>
<p>How could I see <em><strong>the name of the product with the lowest price?</strong></em></p>
<p>Thanks in advance!</p>
|
[
{
"answer_id": 74465364,
"author": "HamidYari",
"author_id": 3807023,
"author_profile": "https://Stackoverflow.com/users/3807023",
"pm_score": -1,
"selected": false,
"text": "SELECT 'productName' \nFROM Products \nORDER BY Price LIMIT 1\n"
},
{
"answer_id": 74465372,
"author": "Bill Karwin",
"author_id": 20860,
"author_profile": "https://Stackoverflow.com/users/20860",
"pm_score": 0,
"selected": false,
"text": "SELECT MIN(Price), MAX(Price), ProductName\nFROM Products;\n"
},
{
"answer_id": 74465566,
"author": "WesDev",
"author_id": 6841713,
"author_profile": "https://Stackoverflow.com/users/6841713",
"pm_score": -1,
"selected": true,
"text": "SELECT Price, ProductName FROM Products ORDER BY Price ASC LIMIT 1\n"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74465310",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2280381/"
] |
74,465,311
|
<p><strong>I</strong> have a laravel blade view/page that I'd like to update without refreshing the page.</p>
<p>The blade.php code is working fine and retrieving data from a MySQL database - but the ajax/javascript isn't.</p>
<p>Apparently my AJAX calls are not even returning JSON but an object.</p>
<p>I come from a background of C# and never touched ajax/javascript/php in my life and I'd appreciate it if anyone could help me.</p>
<p>The controller.php works and returns the data I need which LOOKS like json but apparently isn't json.</p>
<p>What I would like to do is refresh the page a user is on (without reloading it), grab the data from a MySQL database and update the pre-existing tables with this new data - if there is any new data.</p>
<p>view.blade.php:</p>
<pre><code><table class="table custom--table" id="mainTable">
<thead>
<tr>
<th>@lang('ID')</th>
<th>@lang('Name')</th>
<th>@lang('Date')</th>
<th>@lang('Details')</th>
</tr>
</thead>
<tbody>
@forelse($items as $data)
<tr>
<td data-label="@lang('ID')">
{{ $loop->index + 1 }}
</td>
<td data-label="@lang('Name')">{{ $data->name }}</td>
<td data-label="@lang('Date')">{{ $data->created_at }}</td>
<td id="detailz" data-label="@lang('Details')">{{ $data->details }}</td>
</tr>
@empty
<tr>
<td colspan="100%" class="text-center justify-content-center">@lang('No data.')</td>
</tr>
@endforelse
</tbody>
</table>
</code></pre>
<p>AJAX: (Not working)</p>
<pre><code>function updatePost() {
setInterval(function() {
$.ajax({
type: "GET",
url: "{{route('user.posts.update')}}", // Route works.
success: function( response ){
$('#mainTable')[0].reset();
$("tbody").html("");
$.each(response, function( index, value ) {
var row = $("<tr><td>"
+ value.name + "</td><td>"
+ value.details + "</td><td>"
+ value.created_at + "</td><td>");
$("tbody").append(row);
});
},
error: function( response ){
console.log("Error!");
console.log(response);
}
});
}, 5000); // every 5s
</code></pre>
<p>controller.php:</p>
<pre><code> public function postUpdate(){
$pageTitle = 'Post Update';
$data = DataHistory::where('user_id', Auth::user()->id)->latest()->paginate(getPaginate());
return response()->json($data);
}
</code></pre>
<p>I've tried many different methods in ajax but apparently I can't seem to access the inner elements of the data.</p>
<p>Here's a sample of the data:</p>
<pre><code>{
"current_page":1,
"data":[
{
"id":34,
"user_id":1,
"name":"RANDOM NAME DATA",
"details":"RANDOM DETAILS",
"created_at":"2022-11-16T15:02:56.000000Z"
},{
"id":32,
"user_id":1,
"name":"RANDOM NAME DATA 2",
"details":"RANDOM DETAILS 2",
"created_at":"2022-11-16T10:19:29.000000Z"
},
"first_page_url":"https:\/\/xyz.com/posts/update/?page=1",
"from":1,
"last_page":1,
"last_page_url":"https:\/\/xyz.com/posts/update/?page=1",
"links":[
{
"url":null,
"label":"&laquo; Previous",
"active":false
},{
"url":"https:\/\/xyz.com/posts/update/?page=1",
"label":"1",
"active":true
},{
"url":null,
"label":"Next &raquo;",
"active":false
}
],
"next_page_url":null,
"path":"https:\/\/xyz.com/posts/update/",
"per_page":20,
"prev_page_url":null,
"to":7,
"total":7
}
</code></pre>
<p>How will I be able to achieve this? Am I going in the right direction?</p>
|
[
{
"answer_id": 74465364,
"author": "HamidYari",
"author_id": 3807023,
"author_profile": "https://Stackoverflow.com/users/3807023",
"pm_score": -1,
"selected": false,
"text": "SELECT 'productName' \nFROM Products \nORDER BY Price LIMIT 1\n"
},
{
"answer_id": 74465372,
"author": "Bill Karwin",
"author_id": 20860,
"author_profile": "https://Stackoverflow.com/users/20860",
"pm_score": 0,
"selected": false,
"text": "SELECT MIN(Price), MAX(Price), ProductName\nFROM Products;\n"
},
{
"answer_id": 74465566,
"author": "WesDev",
"author_id": 6841713,
"author_profile": "https://Stackoverflow.com/users/6841713",
"pm_score": -1,
"selected": true,
"text": "SELECT Price, ProductName FROM Products ORDER BY Price ASC LIMIT 1\n"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74465311",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20522722/"
] |
74,465,337
|
<p>After creating a web app config in firebase using the c# library, I wanted to get the configuration file, but I am getting error :- Google.GoogleApiException: Parameter validation failed for "parent" : The value did not match the regular expression ^projects/[^/]+$ ..... as shown below , how do I fix this issue?</p>
<pre><code> public static WebAppConfig GetWebAppConfig()
{
var listWeb = _firebaseManagementService.Projects.WebApps.List("projects/" + CloudManager.ProjectId + "/webApps").Execute();
return _firebaseManagementService.Projects.WebApps.GetConfig("projects/-/webApps/" + listWeb.Apps[0].AppId + "/config").Execute();
}
</code></pre>
<p>Edited -> The error that displays in my terminal is as shown below</p>
<p>Unhandled exception. The service firebase has thrown an exception.
No HttpStatusCode was specified.
No error details were specified.
Google.GoogleApiException: Parameter validation failed for "parent" : The value did not match the regular expression ^projects/[^/]+$
at Google.Apis.Requests.ClientServiceRequest<code>1.AddParameters(RequestBuilder requestBuilder, ParameterCollection inputParameters) at Google.Apis.Requests.ClientServiceRequest</code>1.CreateBuilder()
at Google.Apis.Requests.ClientServiceRequest<code>1.CreateRequest(Nullable</code>1 overrideGZipEnabled)
at Google.Apis.Requests.ClientServiceRequest<code>1.ExecuteUnparsedAsync(CancellationToken cancellationToken) at Google.Apis.Requests.ClientServiceRequest</code>1.Execute()</p>
|
[
{
"answer_id": 74465731,
"author": "Philip P.",
"author_id": 2486874,
"author_profile": "https://Stackoverflow.com/users/2486874",
"pm_score": 1,
"selected": false,
"text": "return _firebaseManagementService.Projects.WebApps.GetConfig(\"projects/-/webApps/\" + listWeb.Apps[0].AppId + \"/config\").Execute();"
},
{
"answer_id": 74492517,
"author": "Samaritan",
"author_id": 20410799,
"author_profile": "https://Stackoverflow.com/users/20410799",
"pm_score": 1,
"selected": true,
"text": "var listWeb = _firebaseManagementService.Projects.WebApps.List(\"projects/\" + CloudManager.ProjectId + \"/webApps\").Execute();\n"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74465337",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20410799/"
] |
74,465,341
|
<p>I want to filter a dataframe column (col_A) and append the output to existing lists. The filters to apply to col_A are included in a vector col_A_filters.</p>
<p>My question is how to create a function for this with R.</p>
<p>Example:</p>
<pre><code>Df <- data.frame(
col_A = c("abc","def"),
col_B = c(123,456)
)
# existing lists:
abc <- list()
def <- list()
col_A_filters <- c("abc", "def")
</code></pre>
<p>The output should be that to each of the lists abc and def the filtered rows of Df are added.</p>
|
[
{
"answer_id": 74465549,
"author": "Rui Barradas",
"author_id": 8245406,
"author_profile": "https://Stackoverflow.com/users/8245406",
"pm_score": 2,
"selected": false,
"text": "mget"
},
{
"answer_id": 74465858,
"author": "Julian",
"author_id": 14137004,
"author_profile": "https://Stackoverflow.com/users/14137004",
"pm_score": 2,
"selected": false,
"text": "{purrr}"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74465341",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12617528/"
] |
74,465,409
|
<p>Ok I am building a small app to learn some Speech Recognition in Kotlin. The issue I am experiencing is that my EditText is not posting what is being said. It returns a null value. So when I access the <code>text.text = result?.get(0).tostring()</code> it says it has to an Editable!.</p>
<p>I then changed it to <code>text.append(Editable.Factory.getInstance().newEditable(result?.get(0).toString()))</code> I have also tried <code>setText</code>, <code>append</code> and <code>text.text</code></p>
<p>I am not understanding where my code is posting <code>null</code> in the editText field of the app. I have the correct permissions in my manifest, here is my code:</p>
<p><code>MainActivity</code></p>
<pre><code>import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.speech.RecognizerIntent
import android.speech.SpeechRecognizer
import android.widget.Button
import android.widget.EditText
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import java.util.*
class MainActivity : AppCompatActivity() {
private val RQ_SPEECH_REC = 102
private lateinit var mic : Button
private lateinit var text : EditText
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
mic = findViewById(R.id.btnMic)
text = findViewById(R.id.etMain)
mic.setOnClickListener {
askSpeechInput()
}
}
@Suppress("DEPRECATION")
@Deprecated("Deprecated in Java")
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == RQ_SPEECH_REC && resultCode == Activity.RESULT_OK){
val result = data?.getStringArrayExtra(RecognizerIntent.EXTRA_RESULTS)
if(text.length() >= 0){
text.append(text.editableText.toString() + result?.get(0).toString())
}else{
text.setText(result?.get(0).toString())
}
// text.append(Editable.Factory.getInstance().newEditable(result?.get(0).toString()))
}
}
@Suppress("DEPRECATION")
private fun askSpeechInput() {
if (!SpeechRecognizer.isRecognitionAvailable(this)){
Toast.makeText(this, "Speech is Not Available", Toast.LENGTH_SHORT).show()
}else{
val i = Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH)
i.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM)
i.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault())
i.putExtra(RecognizerIntent.EXTRA_PROMPT, "Begin Speaking")
startActivityForResult(i, RQ_SPEECH_REC)
}
}
}
</code></pre>
<p>I am learning the concepts of speech in kotlin. However this app, will be used as a typing source and also voice recognition source to type in the document. I have built numerous Speech in C#, however I wanting to learn Speech in Kotlin to expand my apps and knowledge.I have looked at this for over 3 hours trying different methods. I even used a <code>TextView</code> and the same results appear. Any help is greatly appreciated.</p>
<p>also here is the result:</p>
<p><a href="https://i.stack.imgur.com/Pq5nJ.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Pq5nJ.jpg" alt="mainview" /></a></p>
<p><a href="https://i.stack.imgur.com/sYSj3.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/sYSj3.jpg" alt="speech" /></a></p>
<p><a href="https://i.stack.imgur.com/GXmTT.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/GXmTT.jpg" alt="null in edittext" /></a></p>
|
[
{
"answer_id": 74465549,
"author": "Rui Barradas",
"author_id": 8245406,
"author_profile": "https://Stackoverflow.com/users/8245406",
"pm_score": 2,
"selected": false,
"text": "mget"
},
{
"answer_id": 74465858,
"author": "Julian",
"author_id": 14137004,
"author_profile": "https://Stackoverflow.com/users/14137004",
"pm_score": 2,
"selected": false,
"text": "{purrr}"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74465409",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14809236/"
] |
74,465,418
|
<p>I need to create a Trigger in oracle. Trigger has to check if the number of employees in department is between 1 and 10. I'm wondering about this for 2 days and still I can not find a solution.</p>
<p>I wrote something like this, but I got an error: "ORA-04091: table is mutating"</p>
<pre><code>CREATE OR REPLACE TRIGGER deptEmp
BEFORE INSERT OR UPDATE OR DELETE ON emp
FOR EACH ROW
DECLARE
emp_counts NUMBER;
BEGIN
SELECT COUNT(*) INTO emp_counts FROM emp WHERE emp.deptno = :NEW.deptno;
IF emp_counts > 10 OR emp_counts = 0 THEN
raise_application_error(-20000, 'Not correct number of employees in dept'):
END IF;
END;
/
</code></pre>
|
[
{
"answer_id": 74465793,
"author": "Barbaros Özhan",
"author_id": 5841306,
"author_profile": "https://Stackoverflow.com/users/5841306",
"pm_score": 0,
"selected": false,
"text": "CREATE OR REPLACE TRIGGER deptEmp\nBEFORE INSERT OR UPDATE OR DELETE ON emp\nDECLARE\n emp_counts_min INT;\n emp_counts_max INT;\nBEGIN\n SELECT MIN(COUNT(*)), MAX(COUNT(*))\n INTO emp_counts_min, emp_counts_max\n FROM emp \n GROUP BY deptno; -- overlaps each dept which is provided next to WHERE within the current case \n \n IF (emp_counts_min NOT BETWEEN 1 AND 10) OR (emp_counts_max NOT BETWEEN 1 AND 10) THEN\n raise_application_error(-20001, 'Not correct number of employees in dept'):\n END IF;\nEND;\n/\n"
},
{
"answer_id": 74465915,
"author": "nbk",
"author_id": 5193536,
"author_profile": "https://Stackoverflow.com/users/5193536",
"pm_score": 1,
"selected": false,
"text": "COALESCE (:NEw.deptno,:OLD.deptno)"
},
{
"answer_id": 74466716,
"author": "MT0",
"author_id": 1509264,
"author_profile": "https://Stackoverflow.com/users/1509264",
"pm_score": 1,
"selected": false,
"text": "CREATE OR REPLACE TRIGGER deptEmp\n AFTER INSERT OR UPDATE OR DELETE ON emp\nDECLARE\n v_invalid PLS_INTEGER;\nBEGIN\n SELECT 1\n INTO v_invalid\n FROM (\n SELECT 1\n FROM departments d\n LEFT OUTER JOIN emp e\n ON (e.deptno = d.deptno)\n GROUP BY d.deptno\n HAVING COUNT(e.deptno) < 1\n OR COUNT(e.deptno) > 10\n )\n WHERE ROWNUM = 1;\n\n RAISE_APPLICATION_ERROR(\n -20000,\n 'Must be between 1 and 10 employees in a department'\n );\nEXCEPTION\n WHEN NO_DATA_FOUND THEN\n NULL;\nEND;\n/\n"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74465418",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12096346/"
] |
74,465,420
|
<p>(obs: <em>the <em><strong>ids</strong> are not pk they are unique keys, the pks are a government "id" called <strong>cpf</strong></em></em>);</p>
<p>I want to create a function that reads the <strong>id</strong> in <em>table1 [person]</em> of a person and then insert this <em>[person].<strong>id</strong></em> in <em>table 2 [went_to].<strong>id</strong></em> (it is null at the moment)* if the <em><strong>cpf</strong></em> in *[went_to] matches the <em><strong>cpf</strong></em> in <em>[person]</em></p>
<p>But the following error happens <strong>(it never stops going because i don't know how to stoop the loop)</strong>:</p>
<p>Here is the code:</p>
<pre><code>CREATE OR REPLACE FUNCTION migrate_id() RETURNS INTEGER AS $$
BEGIN
LOOP
UPDATE schema.went_to
SET id = person.id
FROM schema.person
WHERE went.cpf = person.cpf;
END LOOP;
END
$$
LANGUAGE plpgsql
</code></pre>
<p>But as it will be part of a trigger I don't think I need to create a Loop as long as I define the Trigger as to EACH ROW.</p>
<p>Then I tried without the loop:</p>
<pre><code>CREATE OR REPLACE FUNCTION migrate_id() RETURNS INTEGER AS $$
BEGIN
UPDATE schema.went_to
SET id = person.id
FROM schema.person
WHERE went.cpf = person.cpf;
END
$$
LANGUAGE plpgsql
</code></pre>
<p>But it doesn't work because there is no return in the end of the function. So I tried to make a return in many ways but I failed in all my tries. I end up running out of ideas and I can't find the "answer" to my problem online, could someone help me?</p>
<p>I manage to get an "result" if I type</p>
<pre><code>CREATE OR REPLACE FUNCTION pa_migrarID_vp(OUT ID INTEGER) RETURNS INTEGER AS $$
</code></pre>
<p>But it gives null (because all the ids are already null)</p>
<p>Here is how I intend to use the trigger:</p>
<pre><code>CREATE TRIGGER ADD_ID
AFTER INSERT ON went_to
FOR EACH ROW
EXECUTE PROCEDURE migrate_id();
</code></pre>
|
[
{
"answer_id": 74465621,
"author": "yellow_melro",
"author_id": 20333201,
"author_profile": "https://Stackoverflow.com/users/20333201",
"pm_score": 0,
"selected": false,
"text": "CREATE OR REPLACE FUNCTION schema.migrated_id() RETURNS TRIGGER AS $$\nBEGIN\n\n UPDATE schema.went_to\n SET id = person.id \n FROM schema.person \n WHERE went.cpf = person.cpf;\n\nEND\n$$\n LANGUAGE plpgsql \n"
},
{
"answer_id": 74469506,
"author": "Erwin Brandstetter",
"author_id": 939860,
"author_profile": "https://Stackoverflow.com/users/939860",
"pm_score": 1,
"selected": false,
"text": "BEFORE INSERT"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74465420",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20333201/"
] |
74,465,426
|
<p>I am creating countdown for the "coming soon page", but it doesn't works, it always says 00:00:00:00
Can you help me please.</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><script>
var countDownDate = new Date("Jan 5, 2024 15:37:25").getTime(); var x = setInterval (function(){ var now = new Date().getTime; var distance = countDowndate - now;
var days = Math.floor(distance / (1000 * 60 * 60 * 24)); var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)); var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60)); var seconds = Math.floor((distance % (1000 * 60)) / 1000);
document.getElementById("days").innerHTML = days; document.getElementById("hours").innerHTML = hours; document.getElementById("minutes").innerHTML = minutes; document.getElementById("seconds").innerHTML = seconds;
if (distance < 0) { clearInterval (x); document.getElementById("days").innerHTML = "00"; document.getElementById("hours").innerHTML = "00"; document.getElementById("minutes").innerHTML = "00"; document.getElementById("seconds").innerHTML = "00";
}
1000); </script></code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="launch-time">
<div>
<p id="days">00</p>
<span>days</span>
</div>
<div>
<p id="hours">00</p>
<span>Hours</span>
</div>
<div>
<p id="minutes">00</p>
<span>Minutes</span>
</div>
<div>
<p id="seconds">00</p>
<span>Seconds</span>
</div> </div></code></pre>
</div>
</div>
</p>
<p>I tried to create countdown for the website coming soon page. It should tell how much time it is left, but it always says 00:00:00:00</p>
|
[
{
"answer_id": 74465621,
"author": "yellow_melro",
"author_id": 20333201,
"author_profile": "https://Stackoverflow.com/users/20333201",
"pm_score": 0,
"selected": false,
"text": "CREATE OR REPLACE FUNCTION schema.migrated_id() RETURNS TRIGGER AS $$\nBEGIN\n\n UPDATE schema.went_to\n SET id = person.id \n FROM schema.person \n WHERE went.cpf = person.cpf;\n\nEND\n$$\n LANGUAGE plpgsql \n"
},
{
"answer_id": 74469506,
"author": "Erwin Brandstetter",
"author_id": 939860,
"author_profile": "https://Stackoverflow.com/users/939860",
"pm_score": 1,
"selected": false,
"text": "BEFORE INSERT"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74465426",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6652796/"
] |
74,465,430
|
<p>I am trying to code the summation of the following series:</p>
<p><a href="https://i.stack.imgur.com/fpJD3.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/fpJD3.png" alt="enter image description here" /></a></p>
<p>I can't figure out how to alternate the sign from "-" to "+" to "-" and so on....</p>
<p>Here is my code:</p>
<pre><code>#include<stdio.h>
int main()
{
int i=1,n;
float sum,num,den;
den=2;
sum=0;
printf("Enter number of terms for summation: ");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
num=i*(i+1);
den=den*(i+2);
sum+=num/den;
}
printf("%f",sum);
}
</code></pre>
|
[
{
"answer_id": 74465495,
"author": "abelenky",
"author_id": 34824,
"author_profile": "https://Stackoverflow.com/users/34824",
"pm_score": 3,
"selected": true,
"text": "int coeff = +1;\n"
},
{
"answer_id": 74465500,
"author": "0___________",
"author_id": 6110094,
"author_profile": "https://Stackoverflow.com/users/6110094",
"pm_score": 1,
"selected": false,
"text": "int main()\n{\n int i=1,n, sign = 1;\n float sum,num,den;\n den=2;\n sum=0;\n\n printf(\"Enter number of terms for summation: \");\n scanf(\"%d\",&n);\n\n for(i=1;i<=n;i++)\n {\n num=i*(i+1);\n den=den*(i+2);\n sum+=sign * num/den;\n sign *= -1;\n }\n printf(\"%f\",sum);\n}\n"
},
{
"answer_id": 74465554,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "x = i % 2"
},
{
"answer_id": 74465639,
"author": "Eric Postpischil",
"author_id": 298225,
"author_profile": "https://Stackoverflow.com/users/298225",
"pm_score": 2,
"selected": false,
"text": "sum+=pow(-1,i)*num/den"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74465430",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20292136/"
] |
74,465,451
|
<p>so I am currently learning Dart (Flutter) and I have come to something I can't really understand. So I'm hoping that someone will be able to point out the obvious thing here :)</p>
<p>If I write my code like this:</p>
<pre><code>class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: QuizPage(
title: 'Quiz APP',
questions: [
{'question': 'Color?', 'answers': ["Red", "Blue", "Green", "Black"]},
{'question': 'Animal?', 'answers': ["Cat", "Dog", "Snake", "Rabbit"]},
]),
);
}
}
class QuizPage extends StatefulWidget {
QuizPage({super.key, required this.title, required this.questions});
final String title;
final List<Map<String, Object>> questions;
@override
State<StatefulWidget> createState() {
return _QuizPageSate();
}
}
</code></pre>
<p>It works, but I have later to cast the answers Object with <code>as List<String></code>. However, if I directly define the <code>questions</code> type as:</p>
<pre><code>final List<Map<String, List<String>>> questions;
</code></pre>
<p>it will not work and throw an error:</p>
<pre><code>The element type 'String' can't be assigned to the map value type 'List<String>'.
</code></pre>
<p>It seems like it doesn't know how to interpret the type I pass in. Do all non "primitive" types inside a <code>Map</code> have to be defined as <code>Object</code> or am I missing something fundamental here?</p>
|
[
{
"answer_id": 74465503,
"author": "eamirho3ein",
"author_id": 10306997,
"author_profile": "https://Stackoverflow.com/users/10306997",
"pm_score": 0,
"selected": false,
"text": "questions"
},
{
"answer_id": 74465643,
"author": "Bruno Kinast",
"author_id": 15651035,
"author_profile": "https://Stackoverflow.com/users/15651035",
"pm_score": 1,
"selected": false,
"text": "[\n {\n 'question': 'Color?',\n 'answers': [\n \"Red\", \"Blue\", \"Green\", \"Black\"\n ]\n },\n {\n 'question': 'Animal?',\n 'answers': [\n \"Cat\", \"Dog\", \"Snake\", \"Rabbit\"\n ]\n },\n]\n"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74465451",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4478466/"
] |
74,465,455
|
<p>I have the following <code>Spring</code> component that I am trying to unit test:</p>
<pre><code>@Component
public class OrderService {
private final DatabaseConnection dbConnection;
private final String collectionName;
@Autowired
public OrderService(
DatabaseConnection dbConnection,
DatabaseConfig databaseConfig) {
this.dbConnection = dbConnection;
this.collectionName = databaseConfig.getCollectionName();
}
//methods etc...
}
</code></pre>
<p>The <code>DatabaseConfig</code> class is as follows:</p>
<pre><code>@ConfigurationProperties(prefix = "database")
@ConstructorBinding
public class DatabaseConfig {
//methods etc...
}
</code></pre>
<p>I am trying to inject mocks in my <code>OrderService</code> class as follows:</p>
<pre><code>@RunWith(MockitoJUnitRunner.class)
class OrderServiceTest {
@InjectMocks
OrderService orderService;
@Mock
DatabaseConnection dbConnection; // working as expected
@Mock
DatabaseConfig databaseConfig; // giving null pointer
@Mock
DatabaseCollectionConfig databaseCollectionConfig;
@BeforeEach
public void setup() {
MockitoAnnotations.openMocks(this);
when(databaseConfig.getCollections()).thenReturn(databaseCollectionConfig);
when(databaseCollectionConfig.getCollectionName()).thenReturn("myCollection");
}
</code></pre>
<p>When I run my test class I get:</p>
<pre><code>org.mockito.exceptions.misusing.InjectMocksException:
Cannot instantiate @InjectMocks field named 'OrderService' of type 'class com.my.package.OrderService'.
You haven't provided the instance at field declaration so I tried to construct the instance.
However the constructor or the initialization block threw an exception : null
</code></pre>
<p>The issue is that in the <code>OrderService</code> constructor when I debug this line is coming as null:</p>
<pre><code> this.collectionName = databaseConfig.getCollectionName();
</code></pre>
<p>How can I correctly mock <code>databaseConfig.getCollectionName()</code> to solve the null issue?</p>
|
[
{
"answer_id": 74465668,
"author": "chrylis -cautiouslyoptimistic-",
"author_id": 1189885,
"author_profile": "https://Stackoverflow.com/users/1189885",
"pm_score": 0,
"selected": false,
"text": "@ConfigurationProperties"
},
{
"answer_id": 74465721,
"author": "PR16",
"author_id": 6337866,
"author_profile": "https://Stackoverflow.com/users/6337866",
"pm_score": 1,
"selected": false,
"text": "InjectMocks"
},
{
"answer_id": 74465937,
"author": "Rohit Agarwal",
"author_id": 7871511,
"author_profile": "https://Stackoverflow.com/users/7871511",
"pm_score": 3,
"selected": true,
"text": "\n\n@RunWith(MockitoJUnitRunner.class)\nclass OrderServiceTest {\n\n OrderService orderService;\n\n @Mock\n DatabaseConnection dbConnection; // working as expected\n @Mock\n DatabaseConfig databaseConfig; // giving null pointer\n @Mock\n DatabaseCollectionConfig databaseCollectionConfig;\n\n @BeforeEach\n public void setup(){\n when(databaseConfig.getCollections()).thenReturn(databaseCollectionConfig);\n\nwhen(databaseCollectionConfig.getCollectionName()).thenReturn(\"myCollection\");\n\n orderService = new OrderService(dbConnection, databaseConfig);\n\n \n \n\n }\n }\n\n"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74465455",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12268910/"
] |
74,465,477
|
<p>I am new to this data science world and trying to understand some basic pandas examples.
I have a pandas data frame that I would like to create a new column and add some conditional values as below:
It will include <code>yes</code> at every 2 seconds. Otherwise include <code>no</code>. Here is an example:
This is my original data frame.</p>
<pre><code> id name time
0 1 name1 260.123
1 2 name2 261.323
2 3 name3 261.342
3 4 name4 261.567
4 5 name5 262.123
...
</code></pre>
<p>The new data frame will be like this:</p>
<pre><code> id name time time_delta
0 1 name1 260.123 yes
1 2 name2 261.323 no
2 3 name3 261.342 no
3 4 name4 261.567 no
4 5 name5 262.123 yes
5 6 name6 262.345 yes
6 7 name7 264.876 yes
7 8 name8 265.234 no
8 9 name9 266.234 yes
9 10 name10 267.234 no
...
</code></pre>
<p>The code that I was using is:
<code>df['time_delta'] = df['time'].apply(apply_test)</code>
And the actual code of the function:</p>
<pre><code>def apply_test(num):
prev = num
if round(num) != prev + 2:
prev = prev
return "no"
else:
prev = num
return "yes"
</code></pre>
<p>Please note that the time column has decimals and no patterns.</p>
<p>The result came as all <code>no</code> since the prev is assigned to the next number at each iteration. This was the way I thought it would be. Not sure if there are any other better ways. I would appreciate any help.</p>
<p>UPDATE:</p>
<ul>
<li>Please note that the time column has decimals and the decimal values have no value in this case. For instance, time=234.xxx will be considered as 234 seconds. Therefore, the next 2 second point is 236.</li>
<li>The data frame has multiple second value if we round it down. In this case, all of them have to be marked as <code>yes</code>. Please refer to the updates result data frame as an example.</li>
</ul>
|
[
{
"answer_id": 74465668,
"author": "chrylis -cautiouslyoptimistic-",
"author_id": 1189885,
"author_profile": "https://Stackoverflow.com/users/1189885",
"pm_score": 0,
"selected": false,
"text": "@ConfigurationProperties"
},
{
"answer_id": 74465721,
"author": "PR16",
"author_id": 6337866,
"author_profile": "https://Stackoverflow.com/users/6337866",
"pm_score": 1,
"selected": false,
"text": "InjectMocks"
},
{
"answer_id": 74465937,
"author": "Rohit Agarwal",
"author_id": 7871511,
"author_profile": "https://Stackoverflow.com/users/7871511",
"pm_score": 3,
"selected": true,
"text": "\n\n@RunWith(MockitoJUnitRunner.class)\nclass OrderServiceTest {\n\n OrderService orderService;\n\n @Mock\n DatabaseConnection dbConnection; // working as expected\n @Mock\n DatabaseConfig databaseConfig; // giving null pointer\n @Mock\n DatabaseCollectionConfig databaseCollectionConfig;\n\n @BeforeEach\n public void setup(){\n when(databaseConfig.getCollections()).thenReturn(databaseCollectionConfig);\n\nwhen(databaseCollectionConfig.getCollectionName()).thenReturn(\"myCollection\");\n\n orderService = new OrderService(dbConnection, databaseConfig);\n\n \n \n\n }\n }\n\n"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74465477",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3450163/"
] |
74,465,480
|
<p>Using <code>SlideToggle</code> of Skeleton, I am creating a toggle switch like this.</p>
<pre class="lang-html prettyprint-override"><code><script lang="ts">
import { SlideToggle } from '@brainandbones/skeleton';
let is_checked: boolean = false;
</script>
<div class="page-container">
<SlideToggle bind:checked={is_monitoring}>{is_checked ? 'Activated' : 'Disabled'}</SlideToggle>
</div>
</code></pre>
<p>How can I get on-change event instead of polling <code>is_checked</code> status manually?</p>
|
[
{
"answer_id": 74465647,
"author": "siraj",
"author_id": 9357440,
"author_profile": "https://Stackoverflow.com/users/9357440",
"pm_score": 2,
"selected": true,
"text": "<script lang=\"ts\">\n import { SlideToggle } from '@brainandbones/skeleton';\n\n let handleOnChange = (e) => {\n // your subroutine goes here\n }\n</script>\n\n<SlideToggle on:change={handleOnChange}>Label</SlideToggle>\n"
},
{
"answer_id": 74465918,
"author": "DumTux",
"author_id": 12570573,
"author_profile": "https://Stackoverflow.com/users/12570573",
"pm_score": 0,
"selected": false,
"text": "on:change"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74465480",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12570573/"
] |
74,465,521
|
<p>I have three arrays of numbers:</p>
<pre><code>const arr1 = [1, 2, 3, 4, 5, 6];
const arr2 = [10, 20];
const arr3 = [100, 200, 300, 400, 500, 600, 700, 800, 900, 1000];
</code></pre>
<p>i want to join them in a way where every time 'n' numbers are added (n starts with 1..2..3..and so on)
at first - one of each array, then 2 of each array, 3 of each untill the array is empty</p>
<p>so the final result should look like this:</p>
<pre><code>finalArray = [1, 10, 100, 2, 3, 20, 200, 300, 4, 5, 6, 400, 500, 600, 700, 800, 900, 1000,];
</code></pre>
<p>i tried and tested a couple of nested loops methods but couldn't define the stop conditions, i just added all the numbers multiple times without success.</p>
<p>i tried using Concat(), but couldn't figure the right order</p>
<pre><code>
let finalArray = [];
for (let i = 0; i < arrF3.length; i++) {
finalArray.push(arrF3[i]);
for (let j = 0; j < arrF2.length; j++) {
finalArray.push(arrF2[j]);
for (let k = 0; k < arrF1.length; k++) {
}
}
}
console.table(finalArray);
</code></pre>
<p>Thanks in advance!</p>
|
[
{
"answer_id": 74465571,
"author": "Samathingamajig",
"author_id": 12101554,
"author_profile": "https://Stackoverflow.com/users/12101554",
"pm_score": 2,
"selected": false,
"text": "const arr1 = [1, 2, 3, 4, 5, 6];\nconst arr2 = [10, 20];\nconst arr3 = [100, 200, 300, 400, 500, 600, 700, 800, 900, 1000];\n\nconst finalArray = [];\n\nlet totalI = 0;\n\nfor (let i = 0; i < Math.max(arr1.length, arr2.length, arr3.length); i++) {\n finalArray.push(\n ...arr1.slice(totalI, totalI + i + 1),\n ...arr2.slice(totalI, totalI + i + 1),\n ...arr3.slice(totalI, totalI + i + 1)\n );\n totalI += i + 1;\n}\n\nconsole.log(finalArray);"
},
{
"answer_id": 74465896,
"author": "gog",
"author_id": 3494774,
"author_profile": "https://Stackoverflow.com/users/3494774",
"pm_score": 2,
"selected": false,
"text": "const arrays = [\n [1, 2, 3, 4, 5, 6],\n [10, 20],\n [100, 200, 300, 400, 500, 600, 700, 800, 900, 1000]\n]\n\n\nlet res = [], pos = 0, len = 1;\n\nwhile (1) {\n let slices = arrays.map(a => a.slice(pos, pos + len))\n if (slices.every(s => s.length === 0))\n break\n res = res.concat(...slices)\n pos += len\n len += 1\n}\n\nconsole.log(...res)"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74465521",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17750799/"
] |
74,465,543
|
<p>I'm trying to add some text in the bootstrap modal footer, however the output looks like 2 divs side by side which I don't want. Below is the code :</p>
<pre><code><div class="modal fade" id="itiModal" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Day Wise data</h4>
<button type="button" class="close" data-dismiss="modal">&times;</button>
</div>
<div class="modal-body"> </div>
<div class="modal-footer">
<button type="button" class="btn btn-dark" data-dismiss="modal">Close</button>
Entire or partial data collected from Wikipedia.
</div>
</div>
</div>
</div>
</code></pre>
<p>And the output looks like this:<br />
<a href="https://i.stack.imgur.com/i8amZ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/i8amZ.png" alt="unexpected" /></a><br />
I want the text to appear below the buttons. I've tried putting the text in P/span tags.</p>
|
[
{
"answer_id": 74465571,
"author": "Samathingamajig",
"author_id": 12101554,
"author_profile": "https://Stackoverflow.com/users/12101554",
"pm_score": 2,
"selected": false,
"text": "const arr1 = [1, 2, 3, 4, 5, 6];\nconst arr2 = [10, 20];\nconst arr3 = [100, 200, 300, 400, 500, 600, 700, 800, 900, 1000];\n\nconst finalArray = [];\n\nlet totalI = 0;\n\nfor (let i = 0; i < Math.max(arr1.length, arr2.length, arr3.length); i++) {\n finalArray.push(\n ...arr1.slice(totalI, totalI + i + 1),\n ...arr2.slice(totalI, totalI + i + 1),\n ...arr3.slice(totalI, totalI + i + 1)\n );\n totalI += i + 1;\n}\n\nconsole.log(finalArray);"
},
{
"answer_id": 74465896,
"author": "gog",
"author_id": 3494774,
"author_profile": "https://Stackoverflow.com/users/3494774",
"pm_score": 2,
"selected": false,
"text": "const arrays = [\n [1, 2, 3, 4, 5, 6],\n [10, 20],\n [100, 200, 300, 400, 500, 600, 700, 800, 900, 1000]\n]\n\n\nlet res = [], pos = 0, len = 1;\n\nwhile (1) {\n let slices = arrays.map(a => a.slice(pos, pos + len))\n if (slices.every(s => s.length === 0))\n break\n res = res.concat(...slices)\n pos += len\n len += 1\n}\n\nconsole.log(...res)"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74465543",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/688720/"
] |
74,465,595
|
<p><strong>Short Explanation</strong>
I just want to get the data from the textboxes and send them to the server. In jquery I would just list out all my textboxes and get the value and form the json and send it to the server</p>
<p>Please see example code
<a href="https://codesandbox.io/s/xenodochial-euclid-3bl7tc" rel="nofollow noreferrer">https://codesandbox.io/s/xenodochial-euclid-3bl7tc</a></p>
<pre><code>const EMPTY_VALUE = "";
const App = () => {
const [valueFirstName, setValueFirstName] = React.useState(EMPTY_VALUE);
const [valueMiddleName, setValueMiddleName] = React.useState(EMPTY_VALUE);
const [valueLastName, setValueLastName] = React.useState(EMPTY_VALUE);
return (
<div>
First Name:
<Work365TextBox value={valueFirstName} setValue={setValueFirstName} />
<div>{valueFirstName}</div>
Middle Name:
<Work365TextBox value={valueMiddleName} setValue={setValueMiddleName} />
<div>{valueMiddleName}</div>
Last Name:
<Work365TextBox value={valueLastName} setValue={setValueLastName} />
<div>{valueLastName}</div>
</div>
);
};
</code></pre>
<p><strong>Problem</strong></p>
<p>The current code has a label for first name, middle name, and last name and components to contain the textboxes and then the state of the component is stored in the parent.Then the parent takes the state and displays it below the textbox. So the solution works great. But the code is messy</p>
<p><strong>Question</strong>
If I have a form that asks for 20 values what is a cleaner way to handle this ? I have tried to do this with by defining a object as json and calling a method when the value in each textbox changes but then I need to have a method for each textbox I have on the screen and it doesn't seem very clean. How would you solve this problem in a clean way ? Preferably I want to be able to have 50 textbox components but just call one method to update state.</p>
|
[
{
"answer_id": 74465571,
"author": "Samathingamajig",
"author_id": 12101554,
"author_profile": "https://Stackoverflow.com/users/12101554",
"pm_score": 2,
"selected": false,
"text": "const arr1 = [1, 2, 3, 4, 5, 6];\nconst arr2 = [10, 20];\nconst arr3 = [100, 200, 300, 400, 500, 600, 700, 800, 900, 1000];\n\nconst finalArray = [];\n\nlet totalI = 0;\n\nfor (let i = 0; i < Math.max(arr1.length, arr2.length, arr3.length); i++) {\n finalArray.push(\n ...arr1.slice(totalI, totalI + i + 1),\n ...arr2.slice(totalI, totalI + i + 1),\n ...arr3.slice(totalI, totalI + i + 1)\n );\n totalI += i + 1;\n}\n\nconsole.log(finalArray);"
},
{
"answer_id": 74465896,
"author": "gog",
"author_id": 3494774,
"author_profile": "https://Stackoverflow.com/users/3494774",
"pm_score": 2,
"selected": false,
"text": "const arrays = [\n [1, 2, 3, 4, 5, 6],\n [10, 20],\n [100, 200, 300, 400, 500, 600, 700, 800, 900, 1000]\n]\n\n\nlet res = [], pos = 0, len = 1;\n\nwhile (1) {\n let slices = arrays.map(a => a.slice(pos, pos + len))\n if (slices.every(s => s.length === 0))\n break\n res = res.concat(...slices)\n pos += len\n len += 1\n}\n\nconsole.log(...res)"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74465595",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/237109/"
] |
74,465,641
|
<p>everyone!
Here's the problem , I have this dataset and I need to add a column with the frequency of each pet, I don't want a new dataframe with the statistics. See, dog and cat appears 6 time each, I need a column with value of 6 beside each dog and cat. Then I'll be able to make relational studies, which is why creating a new dataframe with summary is not an option</p>
<pre><code> id answer
<chr> <chr>
1 1 cat
2 1 dog
3 2 bird
4 3 cat
5 3 dog
6 3 fish
7 4 dog
8 5 turtle
9 6 cat
10 7 cat
11 7 fish
12 7 dog
13 7 cat
14 8 dog
15 8 cat
16 9 bird
17 9 dog
</code></pre>
<p>by the end, it should look like this:</p>
<p><a href="https://i.stack.imgur.com/FSwlM.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/FSwlM.png" alt="Output that I'm looking for" /></a></p>
|
[
{
"answer_id": 74465679,
"author": "TarJae",
"author_id": 13321647,
"author_profile": "https://Stackoverflow.com/users/13321647",
"pm_score": 4,
"selected": true,
"text": "add_count"
},
{
"answer_id": 74465682,
"author": "Jamie",
"author_id": 11564586,
"author_profile": "https://Stackoverflow.com/users/11564586",
"pm_score": 2,
"selected": false,
"text": "data.table"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74465641",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19613162/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.